Draw Flights and Military 3D models through draw-port model sets

The two aircraft layers' fleet and tracked models are now draw-port
models sets made each layer lifetime, re-posed and restyled in place,
instead of Cesium models in a collection of their own. Model records are
plain data; picks name the set and the contact, readiness comes from the
set's ready event, the IR boost restyles in place (unlit, white tint,
full blend), and the drawn scale comes from the camera pose and pixel
floor. Fleet writes go out together at the end of each tick, before the
icons they replace, and a failed write hands the contacts back to their
icons. A model that has not loaded is rewritten every few seconds so the
renderer can retry it, which replaces the tracked model's load-failure
budget. Models load off the tile-contended job queue, as before.

aircraftModelLayer.js, modelRecord.js and the flights and military
lifecycle and testing files, plus flights rendering.js, come off the
Cesium allow-list.
This commit is contained in:
Sameh Khamis committed 2026-11-07 17:10:38 -08:00
1 parent eed3b83858
commit abe9f97768
28 files changed
+1310 -1255

No files matched your search

File diff suppressed because it is too large. Load diff
+275
View File
@@ -0,0 +1,275 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAircraftModels } from './aircraftModelLayer.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
const POLICY = {
MODEL_ALT_CEIL_M: 800_000,
MODEL_MAX: 40,
MODEL_MAX_ALL: 350,
COCKPIT_MODEL_MAX: 60,
MODEL_PROX_ADD_M: 150_000,
MODEL_PROX_KEEP_M: 185_000,
MODEL_ALL_ADD_M: 400_000,
MODEL_ALL_KEEP_M: 450_000,
MODEL_MIN_PX: 24,
TRACKED_MODEL_MIN_PX: 48,
TRACKED_MODEL_MAX_PX: 600,
MODEL_HEADING_OFFSET_DEG: 0,
FLEET_DR_INTERVAL_MS: 80,
};
const SPEC = {
url: 'plane.glb',
scale: 1,
bellyM: 3,
nativeRadiusM: 20,
blendAmount: 0.9,
};
/**
* A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a
* models layer over a fake draw port whose fleet set can be told to fail a
* write. The eye sits above them at 30 km.
*/
function fleetFixture(positions) {
const base = fakeDrawPort();
const removes = [];
let failNextUpsert = false;
const draw = {
...base,
models(spec) {
const set = base.models(spec);
return {
...set,
get show() {
return set.show;
},
set show(value) {
set.show = value;
},
id: set.id,
upsert(items) {
if (failNextUpsert && spec.id.includes('-models:')) {
failNextUpsert = false;
throw new Error('simulated write failure');
}
return set.upsert(items);
},
remove(ids) {
removes.push([...ids]);
return set.remove(ids);
},
};
},
};
const eye = fromDegrees(-97.71, 30.21, 30_000);
const viewer = {};
bindRenderer(viewer, {
draw,
camera: {
pose: () => ({
position: eye,
direction: { x: 0, y: 0, z: -1 },
up: { x: 0, y: 1, z: 0 },
right: { x: 1, y: 0, z: 0 },
fovy: Math.PI / 3,
aspectRatio: 1,
height: 30_000,
}),
},
});
const shown = new Map([...positions.keys()].map((id) => [id, true]));
const icons = {
show: true,
setId: 'flights-icons:1',
ids: () => [...positions.keys()],
has: (id) => positions.has(id),
position: (id) => positions.get(id),
course: () => 90,
alpha: () => 1,
focus: () => 1,
setShown: (id, value) => shown.set(id, value),
flush() {},
};
const state = {
_viewer: viewer,
_icons: icons,
_models: new Map(),
_modelSets: null,
_trackedIcao: null,
_trackedModel: null,
_models3dEnabled: true,
_models3dMode: 'proximity',
_cockpitContactMode: false,
_irBoost: false,
_lastFleetTickMs: 0,
_lastModelCapWarnMs: 0,
records: {
data: new Map(
[...positions.keys()].map((id) => [id, { klass: 'airliner' }]),
),
},
};
let now = 1_000_000;
const parts = {
icons: {
_displayMs: () => now,
_syncImageSwitch() {},
_replanExpired() {},
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
},
motion: { _displayTimeAt: () => null },
tracking: {
_refreshCockpitNearContacts() {},
_trackedModelRegimeActive: () => false,
},
};
const models = createAircraftModels({
state,
services: {
aircraftPresentation: { isTr3b: () => false },
camera: { trackedModelScaleForPixelCap: ({ baseScale }) => baseScale },
focus: { focusNowMs: () => now, getFocusTarget: () => null },
},
parts,
resolveAsset: (url) => url,
logLabel: 'Test',
setPrefix: 'flights',
policy: POLICY,
modelSpec: () => SPEC,
modelColor: () => ({ red: 1, green: 1, blue: 1, alpha: 1 }),
});
models._createModelSets(viewer);
const fleetId = models._modelSetIds()[0];
return {
models,
state,
draw: base,
fleet: () => base.set(fleetId),
fleetId,
removes,
shown,
failNextUpsert: () => (failNextUpsert = true),
/** One fleet tick, past the tick interval. */
tick() {
now += 1000;
models._fleetTick();
},
};
}
const near = (k) => fromDegrees(-97.71 + k * 0.01, 30.21, 10_000);
const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000);
test('the fleet tick hands contacts to ready models and back without a gap', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
]);
const f = fleetFixture(positions);
f.tick();
assert.deepEqual([...f.fleet().items.keys()].sort(), ['a1', 'a2']);
assert.equal(
f.shown.get('a1'),
true,
'icons carry contacts until models load',
);
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.shown.get('a1'), false, 'a ready, placed model takes over');
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(
f.shown.get('a2'),
true,
'a model still loading leaves its icon',
);
});
test('contacts leaving the model band are released in one write', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
['a3', near(3)],
]);
const f = fleetFixture(positions);
f.tick();
for (const id of ['a1', 'a2', 'a3']) f.draw.ready(f.fleetId, id);
f.tick();
positions.set('a2', far(2));
positions.set('a3', far(3));
f.removes.length = 0;
f.tick();
assert.deepEqual(
f.removes,
[['a2', 'a3']],
'one remove for every evicted model',
);
assert.deepEqual([...f.fleet().items.keys()], ['a1']);
assert.equal(
f.shown.get('a2'),
true,
'a released model hands back to its icon',
);
assert.equal(f.shown.get('a3'), true);
});
test('a failed fleet write leaves the icons in charge and is sent again', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
f.tick();
f.draw.ready(f.fleetId, 'a1');
const realWarn = console.warn;
console.warn = () => {};
try {
f.failNextUpsert();
f.tick();
} finally {
console.warn = realWarn;
}
assert.equal(f.shown.get('a1'), true, 'the contact keeps its icon');
assert.equal(
f.fleet().items.get('a1').show,
false,
'the set still has the hidden model',
);
assert.equal(f.models._modelOwnsVisual('a1'), false);
f.tick();
assert.equal(
f.fleet().items.get('a1').show,
true,
'the next tick sends it again',
);
assert.equal(f.shown.get('a1'), false);
});
test('a model that has not loaded is written again for the renderer to retry', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
const realNow = Date.now;
let clock = 50_000_000;
Date.now = () => clock;
try {
f.tick();
const writes = f.fleet().writes;
f.tick();
assert.equal(
f.fleet().writes,
writes,
'an unchanged loading model is not rewritten every tick',
);
clock += 5_000;
f.tick();
assert.equal(
f.fleet().writes,
writes + 1,
'but it is rewritten every few seconds',
);
} finally {
Date.now = realNow;
}
});
+11 -16
View File
@@ -5,10 +5,8 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
/**
* Every aircraft model drawn in the scene skips Cesium's dynamic environment
* map (a sky render and GPU readback per model). The preload calls only warm
* the glTF cache and are never added to the scene, so they are left out:
* drawn models are the calls that set a minimum pixel size.
* Every aircraft model drawn in the scene skips the renderer's dynamic
* environment map (a sky render and GPU readback per model).
*/
const SOURCES = [
{
@@ -28,18 +26,15 @@ test('the shared option turns the dynamic environment map off', () => {
for (const { name, source } of SOURCES) {
test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => {
const calls = [
...source.matchAll(/(?:fromGltfAsync|loadModel)\(\{([\s\S]*?)\}\)/g),
]
.map((match) => match[1])
.filter((options) => /\bminimumPixelSize:/.test(options));
assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`);
for (const [index, options] of calls.entries())
assert.match(
options,
/\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/,
`${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`,
);
// Its models are draw-port items; every item it builds (fleet, tracked
// and the tracked preload) carries the shared option.
assert.doesNotMatch(source, /fromGltfAsync|loadModel\(/);
const items = [...source.matchAll(/\burl: (?:record\.url|preloadUrl),/g)];
assert.ok(items.length >= 2, `expected model items in ${name}`);
const flags = [
...source.matchAll(/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/g),
];
assert.equal(flags.length, items.length, `${name} model items must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`);
});
}
+10 -2
View File
@@ -13,6 +13,11 @@ import assert from 'node:assert/strict';
* regression would silently revert. These assertions pin the decisions.
*/
const DRAW_MODELS_SOURCE = readFileSync(
new URL('../render/cesium/drawModels.js', import.meta.url),
'utf8',
);
const LAYERS = [
{ name: 'flights', path: new URL('./flights.js', import.meta.url) },
{ name: 'militaryFlights', path: new URL('./militaryFlights.js', import.meta.url) },
@@ -29,8 +34,11 @@ for (const layer of LAYERS) {
const source = readLayerSource(layer.path);
test(`${layer.name}: every GLB creation bypasses the tile-contended frame-spread queue`, () => {
const calls = [...source.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)];
assert.ok(calls.length >= 3, `expected fleet, tracked, and preload model calls; found ${calls.length}`);
// The fleet and tracked models are draw-port models sets; the Cesium
// draw port creates every model off the frame-spread queue.
assert.match(source, /\.models\(\{\s*id:/, 'the layer draws its models as draw-port models sets');
const calls = [...DRAW_MODELS_SOURCE.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)];
assert.ok(calls.length >= 1, 'the draw port creates models');
for (const [index, call] of calls.entries()) {
assert.match(call[1], /\basynchronous:\s*false\b/,
`Model.fromGltfAsync call ${index + 1} must keep bounded GLB readiness independent of tile jobs`);
+2
View File
@@ -40,6 +40,8 @@ export const _driveFleetModelHandoffForTest =
flightsLayer.testing._driveFleetModelHandoffForTest;
export const _ensureFleetModelForTest =
flightsLayer.testing._ensureFleetModelForTest;
export const _trackedModelForTest = flightsLayer.testing._trackedModelForTest;
export const _modelSetIdsForTest = flightsLayer.testing._modelSetIdsForTest;
export const _iconForTest = flightsLayer.testing._iconForTest;
export const _setIconForTest = flightsLayer.testing._setIconForTest;
export const _floorGroundedIconsForTest =
+4
View File
@@ -32,6 +32,10 @@ export const _driveFleetModelHandoffForTest =
militaryFlightsLayer.testing._driveFleetModelHandoffForTest;
export const _ensureFleetModelForTest =
militaryFlightsLayer.testing._ensureFleetModelForTest;
export const _trackedModelForTest =
militaryFlightsLayer.testing._trackedModelForTest;
export const _modelSetIdsForTest =
militaryFlightsLayer.testing._modelSetIdsForTest;
export const _iconForTest = militaryFlightsLayer.testing._iconForTest;
export const _setIconForTest = militaryFlightsLayer.testing._setIconForTest;
export const mapAnalystRecord = militaryFlightsLayer.mapAnalystRecord;
+97 -37
View File
@@ -1,47 +1,71 @@
/**
* @module modelRecord
* @description A layer's own record of one 3D model it draws, held in the
* layer's maps under the contact's id, so the layer reads what it pushed back
* from itself instead of from the renderer's object.
* @description A layer's own record of one 3D model it draws through a draw
* port `models` set, held in the layer's maps under the contact's id, so the
* layer reads what it pushed (and what the set told it) back from itself.
*
* Write `show` and the placement with {@link showModel} and {@link placeModel};
* read them from the record. What the renderer measures (`ready`,
* `computedScale`) is still read from `record.model`. Colour stays out: the
* cyber-sonar theme writes it too and reads the live value.
* Write `show` and the placement with {@link showModel} and
* {@link placeModel}; the set's `ready` event sets `ready`. The placement is
* kept as the column-major frame the model is posed in, the same frame a
* renderer builds from the item's position and heading, so anchors on the
* model can be read from it.
*/
import * as Cesium from 'cesium';
import { eastNorthUp } from '../geo/frames.js';
/**
* @typedef {object} ModelRecord
* @property {Cesium.Model} model
* @property {string|null} id The item's id in its set, where the record
* does not live under it in a map (the tracked model).
* @property {string|null} url The model asset the layer sends.
* @property {boolean} ready Whether the set reported the model loaded and
* posed (`ready`).
* @property {boolean} show Whether the layer last showed the model.
* @property {Cesium.Matrix4} matrix Where the layer last placed it.
* @property {string|null} specKey The model spec it was loaded for; a class
* change reloads.
* @property {boolean|null} irBoost The IR boost it was loaded with; a flip
* reloads.
* @property {boolean} placed Whether the layer has placed it yet.
* @property {Float64Array} matrix Where the layer last placed it: the
* east-north-up frame at its position turned by its heading, column-major.
* @property {{x:number,y:number,z:number}} position Where it is placed.
* @property {number} heading Radians, as the item's `orientation.heading`.
* @property {string|null} specKey The model spec it was admitted for; a
* class change readmits.
* @property {number} bellyM Metres from the model origin to its belly, to sit
* it on the ground.
* @property {number} scale The `scale` the layer last sent.
* @property {number} minPixelSize The `minPixelSize` the layer last sent.
* @property {number[]|null} tint The `tint` the layer last sent.
* @property {string|null} sent The item last sent, as a key, or null.
*/
/**
* A record for a model the layer just made, from the options it made it with
* (Cesium's defaults when none: shown, at the identity).
* @param {Cesium.Model} model
* @param {{specKey?: string, irBoost?: boolean, bellyM?: number}} [fields]
* A record for a model the layer just admitted.
* @param {{id?: string|null, url?: string|null, specKey?: string,
* bellyM?: number, scale?: number, minPixelSize?: number}} [fields]
* @returns {ModelRecord}
*/
export function createModelRecord(
model,
{ specKey = null, irBoost = null, bellyM = 0 } = {},
) {
export function createModelRecord({
id = null,
url = null,
specKey = null,
bellyM = 0,
scale = 1,
minPixelSize = 0,
} = {}) {
const matrix = new Float64Array(16);
matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1;
return {
model,
show: model.show ?? true,
matrix: Cesium.Matrix4.clone(model.modelMatrix ?? Cesium.Matrix4.IDENTITY),
id,
url,
ready: false,
show: false,
placed: false,
matrix,
position: { x: 0, y: 0, z: 0 },
heading: 0,
specKey,
irBoost,
bellyM,
scale,
minPixelSize,
tint: null,
sent: null,
};
}
@@ -52,21 +76,57 @@ export function createModelRecord(
*/
export function showModel(record, show) {
record.show = show;
record.model.show = show;
}
/**
* Place a model and record where. The matrix is copied into both, so a shared
* scratch can be passed and reused straight after.
* Place a model at `position` turned by `heading` (radians clockwise from
* north about the local up, as `orientation.heading`), and record its frame.
* @param {ModelRecord} record
* @param {Cesium.Matrix4} matrix
* @param {{x:number,y:number,z:number}} position ECEF; copied.
* @param {number} heading
*/
export function placeModel(record, matrix) {
Cesium.Matrix4.clone(matrix, record.matrix);
const model = record.model;
// Cesium clones the model's own matrix each frame, so write into it in place.
if (model.modelMatrix) Cesium.Matrix4.clone(matrix, model.modelMatrix);
else model.modelMatrix = Cesium.Matrix4.clone(matrix);
export function placeModel(record, position, heading) {
record.position.x = position.x;
record.position.y = position.y;
record.position.z = position.z;
record.heading = heading;
record.placed = true;
headingFrame(record.position, heading, record.matrix);
}
/**
* The east-north-up frame at `origin` turned by `heading` about its up axis,
* as a column-major 4x4: a heading of 0 keeps local x east, and a positive
* heading turns it clockwise seen from above.
* @param {{x:number,y:number,z:number}} origin
* @param {number} heading Radians.
* @param {Float64Array|number[]} out
* @returns {Float64Array|number[]} `out`.
*/
export function headingFrame(origin, heading, out) {
const enu = eastNorthUp(origin);
const c = Math.cos(heading);
const s = Math.sin(heading);
const e = enu.x;
const n = enu.y;
const u = enu.z;
out[0] = e.x * c - n.x * s;
out[1] = e.y * c - n.y * s;
out[2] = e.z * c - n.z * s;
out[3] = 0;
out[4] = e.x * s + n.x * c;
out[5] = e.y * s + n.y * c;
out[6] = e.z * s + n.z * c;
out[7] = 0;
out[8] = u.x;
out[9] = u.y;
out[10] = u.z;
out[11] = 0;
out[12] = origin.x;
out[13] = origin.y;
out[14] = origin.z;
out[15] = 1;
return out;
}
/**
@@ -75,5 +135,5 @@ export function placeModel(record, matrix) {
* @returns {boolean}
*/
export function modelIsRendering(record) {
return !!record && record.model.ready === true && record.show === true;
return !!record && record.ready === true && record.show === true;
}
+55
View File
@@ -0,0 +1,55 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createModelRecord,
headingFrame,
modelIsRendering,
placeModel,
showModel,
} from './modelRecord.js';
test('a placed model has the frame the Cesium renderer poses it in', () => {
for (const [lon, lat, height] of [
[-97.7, 30.2, 300],
[10, -60, 1000],
[179, 89.9, 0],
])
for (const heading of [0, 0.5, 2, 4, -1]) {
const at = Cesium.Cartesian3.fromDegrees(lon, lat, height);
const expected = Cesium.Transforms.headingPitchRollToFixedFrame(
at,
new Cesium.HeadingPitchRoll(heading, 0, 0),
Cesium.Ellipsoid.WGS84,
undefined,
new Cesium.Matrix4(),
);
const frame = headingFrame(
{ x: at.x, y: at.y, z: at.z },
heading,
new Float64Array(16),
);
for (let i = 0; i < 16; i++)
assert.ok(
Math.abs(frame[i] - expected[i]) < (i >= 12 ? 1e-6 : 1e-12),
`${lon},${lat} @ ${heading}: element ${i}`,
);
}
});
test('a record renders only once ready and shown', () => {
const record = createModelRecord({ specKey: 'a@1', bellyM: 2 });
assert.equal(record.ready, false);
assert.equal(modelIsRendering(record), false);
showModel(record, true);
assert.equal(modelIsRendering(record), false);
record.ready = true;
assert.equal(modelIsRendering(record), true);
const at = { x: 1, y: 2, z: 6_400_000 };
placeModel(record, at, 0.3);
at.x = 99;
assert.equal(record.position.x, 1, 'the position is copied');
assert.equal(record.matrix[12], 1);
assert.equal(record.heading, 0.3);
assert.equal(modelIsRendering(null), false);
});
+110 -205
View File
@@ -34,6 +34,8 @@ import flightsLayer, {
_trackedBillboardColorForTest as flightsTrackedBillboardColor,
_driveFleetModelHandoffForTest as flightsDriveFleetModel,
_ensureFleetModelForTest as flightsEnsureFleetModel,
_trackedModelForTest as flightsTrackedModel,
_modelSetIdsForTest as flightsModelSetIds,
_iconForTest as flightsIcon,
_setIconForTest as flightsSetIcon,
} from './flights.js';
@@ -44,11 +46,15 @@ import militaryFlightsLayer, {
_trackedBillboardColorForTest as militaryTrackedBillboardColor,
_driveFleetModelHandoffForTest as militaryDriveFleetModel,
_ensureFleetModelForTest as militaryEnsureFleetModel,
_trackedModelForTest as militaryTrackedModel,
_modelSetIdsForTest as militaryModelSetIds,
_iconForTest as militaryIcon,
_setIconForTest as militarySetIcon,
} from './militaryFlights.js';
import { clearTr3bRegistry, setTr3b } from './tr3bRegistry.js';
import { reportMeshFloorCell, _clearMeshFloorCellsForTest } from './groundFloor.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
// Sample altitudes are expressed RELATIVE to the band rather than as absolute
// offsets. The thresholds have already been retuned once (1_000_000 → 150_000
@@ -156,10 +162,13 @@ if (typeof globalThis.window === 'undefined') {
globalThis.window = { dispatchEvent() { return true; }, addEventListener() {}, removeEventListener() {} };
}
/** A viewer stub whose camera altitude the test can move between evaluations. */
/** A viewer stub whose camera altitude the test can move between evaluations.
* Its renderer has a fake draw port (`viewer.draw`) the layer's model sets
* are made on, and a query port whose height samples are `sampleHeight`'s. */
function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undefined } = {}) {
const tileset = { show: true, tilesLoaded };
return {
const draw = fakeDrawPort();
const viewer = {
camera: {
positionCartographic: { height },
positionWC: Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 5000),
@@ -172,9 +181,25 @@ function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undef
sampleHeight,
},
tileset,
draw,
trackedEntity: undefined,
entities: { remove() {} },
};
return bindFakeCesiumCamera(viewer, {
draw,
query: { sampleHeightNow: () => sampleHeight() },
canvas: viewer.scene.canvas,
});
}
/** The layer's fleet or tracked models set in the viewer's fake draw port. */
function modelSet(fixture, viewer, which) {
return viewer.draw.set(fixture.modelSetIds()[which]);
}
/** Where a model record places its model (its placement's translation). */
function placedAt(record) {
return new Cesium.Cartesian3(record.matrix[12], record.matrix[13], record.matrix[14]);
}
/** A billboard with a real position, so the tracked-model driver has somewhere
@@ -208,13 +233,6 @@ function iconView(icao24, readIcon, setIcon) {
};
}
/** Records what the driver hands to the scene, so a test can assert that a
* failing loader never put a model up. */
function recordingModelCollection() {
const added = [];
return { added, add(m) { added.push(m); }, remove() {}, isDestroyed() { return false; } };
}
const LAYERS = [
{
name: 'flights',
@@ -223,9 +241,11 @@ const LAYERS = [
driveTrackedModel: flightsDriveTrackedModel,
driveFleetModel: flightsDriveFleetModel,
ensureFleetModel: flightsEnsureFleetModel,
trackedModel: flightsTrackedModel,
modelSetIds: flightsModelSetIds,
trackedBillboardColor: flightsTrackedBillboardColor,
bellyM: 6.719,
seed({ viewer, tracked = true, icao24 = ICAO, modelCollection = null, onGround = false, models = [] }) {
seed({ viewer, tracked = true, icao24 = ICAO, onGround = false, models = [] }) {
const billboard = contactBillboard();
_setTrackedFlightRefreshStateForTest({
icao24,
@@ -235,7 +255,7 @@ const LAYERS = [
viewer,
tracked,
models,
modelCollection,
draw: viewer.draw,
meta: { callsign: 'TEST123 ', altitude: 10_668, klass: 'airliner', onGround },
});
return iconView(icao24, flightsIcon, flightsSetIcon);
@@ -248,9 +268,11 @@ const LAYERS = [
driveTrackedModel: militaryDriveTrackedModel,
driveFleetModel: militaryDriveFleetModel,
ensureFleetModel: militaryEnsureFleetModel,
trackedModel: militaryTrackedModel,
modelSetIds: militaryModelSetIds,
trackedBillboardColor: militaryTrackedBillboardColor,
bellyM: 5.631 * 0.8,
seed({ viewer, tracked = true, icao24 = ICAO, modelCollection = null, onGround = false, models = [] }) {
seed({ viewer, tracked = true, icao24 = ICAO, onGround = false, models = [] }) {
const billboard = contactBillboard();
_setTrackedMilitaryRefreshStateForTest({
icao24,
@@ -260,7 +282,7 @@ const LAYERS = [
viewer,
tracked,
models,
modelCollection,
draw: viewer.draw,
meta: { callsign: 'TEST123 ', altitudeFt: 35_000, klass: 'fastjet', onGround },
});
return iconView(icao24, militaryIcon, militarySetIcon);
@@ -269,44 +291,26 @@ const LAYERS = [
];
for (const fixture of LAYERS) {
test(`${fixture.name}: production fleet loader admits a HIDDEN primitive and fails back to 2D`, async () => {
test(`${fixture.name}: production fleet admission keeps the model HIDDEN until it is ready and placed`, () => {
clearTr3bRegistry();
fixture.layer.stopTracking();
fixture.layer.setParams({ models3d: true });
const realFrom = Cesium.Model.fromGltfAsync;
const viewer = viewerAtHeight(30_000, { tilesLoaded: false });
const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668);
const loadedCollection = recordingModelCollection();
const loadingModel = {
modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
ready: false,
show: true,
scale: 1,
destroy() {},
};
try {
const loadingIcao = fixture.name === 'flights' ? 'a0f201' : 'b0f201';
Cesium.Model.fromGltfAsync = () => Promise.resolve(loadingModel);
const billboard = fixture.seed({
viewer,
tracked: false,
icao24: loadingIcao,
onGround: true,
modelCollection: loadedCollection,
});
const admitted = await fixture.ensureFleetModel(loadingIcao);
assert.equal(admitted, loadingModel, 'the production fleet loader admits the resolved primitive');
assert.equal(loadedCollection.added.length, 1, 'the production loader adds it once');
assert.equal(loadingModel.ready, false);
// Cesium 1.138's Model.update has no `show` guard — PrimitiveCollection
// updates every member unconditionally and `_ready` flips in afterRender —
// so hiding an admitted primitive costs its load nothing, and it is the
// only thing that keeps Cesium's default show=true from claiming the
// visual at the identity matrix before the first tick places it.
assert.equal(loadingModel.show, false, 'admission hides the primitive until it is placed');
assert.equal(loadingModel.scale, 1, 'and never touches its scale to do it');
const admitted = fixture.ensureFleetModel(loadingIcao);
assert.ok(admitted, 'the production fleet admission records a model');
assert.equal(admitted.ready, false, 'nothing has loaded yet');
assert.equal(admitted.show, false, 'admission records the model hidden until it is placed');
assert.equal(billboard.show, true, 'the 2D billboard owns the cold loading state');
const nearby = fixture.layer.getNearby(billboard.position, 1_000, 50)
@@ -316,35 +320,64 @@ for (const fixture of LAYERS) {
'fleet proximity stays at the billboard rather than the unplaced model');
fixture.driveFleetModel({ icao24: loadingIcao, position, course: 92 });
assert.equal(loadingModel.show, false);
assert.equal(loadingModel.scale, 1);
const fleet = modelSet(fixture, viewer, 'fleet');
const item = fleet.items.get(loadingIcao);
assert.ok(item, 'the model set loads the contact from its first write');
assert.equal(item.show, false, 'and draws nothing while there is no safe placement');
assert.equal(admitted.show, false);
assert.equal(billboard.show, true, 'cold terrain preserves the same visible 2D owner');
const failedIcao = fixture.name === 'flights' ? 'a0f202' : 'b0f202';
const failedCollection = recordingModelCollection();
Cesium.Model.fromGltfAsync = () => Promise.reject(new Error('simulated fleet GLB failure'));
const failedBillboard = fixture.seed({
viewer,
tracked: false,
icao24: failedIcao,
onGround: true,
modelCollection: failedCollection,
});
const failedModel = await fixture.ensureFleetModel(failedIcao);
assert.equal(failedModel, null, 'a rejected fleet GLB is never admitted');
assert.equal(failedCollection.added.length, 0);
assert.equal(failedBillboard.show, true,
'fleet load rejection leaves the 2D owner visible');
assert.ok(fixture.layer.getNearby(failedBillboard.position, 1_000, 50)
.some((object) => object.icao24 === failedIcao),
'fleet load rejection leaves the contact in the billboard proximity cohort');
// A load that never finishes (a missing or broken GLB) never fires
// `ready`, so the billboard stays the visual for as long as it lasts.
viewer.draw.ready(fleet.spec.id, 'someone-else');
assert.equal(admitted.ready, false, 'another item loading does not ready this one');
fixture.driveFleetModel({ icao24: loadingIcao, position, course: 92 });
assert.equal(billboard.show, true, 'an unready model leaves the 2D owner visible');
assert.ok(fixture.layer.getNearby(billboard.position, 1_000, 50)
.some((object) => object.icao24 === loadingIcao),
'an unready model leaves the contact in the billboard proximity cohort');
viewer.draw.ready(fleet.spec.id, loadingIcao);
assert.equal(admitted.ready, true, "the set's ready marks the contact's model loaded");
} finally {
Cesium.Model.fromGltfAsync = realFrom;
fixture.layer.setParams({ models3d: false });
fixture.layer.stopTracking();
}
});
test(`${fixture.name}: the IR boost restyles a drawn model in place, flat white and unlit`, () => {
clearTr3bRegistry();
fixture.layer.stopTracking();
fixture.layer.setParams({ models3d: true, irBoost: false });
const viewer = viewerAtHeight(30_000);
const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668);
const icao24 = fixture.name === 'flights' ? 'a0f301' : 'b0f301';
try {
fixture.seed({ viewer, tracked: false, icao24 });
const record = fixture.ensureFleetModel(icao24);
const fleet = modelSet(fixture, viewer, 'fleet');
viewer.draw.ready(fleet.spec.id, icao24);
fixture.driveFleetModel({ icao24, position, course: 92 });
const normal = fleet.items.get(icao24);
assert.equal(normal.shading, 'pbr');
assert.equal(normal.show, true);
assert.ok(normal.colorBlend.amount < 1, 'the asset keeps a hint of its own colour');
fixture.layer.setParams({ irBoost: true });
fixture.driveFleetModel({ icao24, position, course: 92 });
const boosted = fleet.items.get(icao24);
assert.notEqual(boosted, normal, 'the boost writes the item again');
assert.equal(boosted.shading, 'unlit');
assert.deepEqual(boosted.tint, [1, 1, 1, 1]);
assert.deepEqual(boosted.colorBlend, { mode: 'mix', amount: 1 });
assert.equal(fixture.ensureFleetModel(icao24), record, 'the same model restyles; nothing reloads');
assert.equal(boosted.url, normal.url);
} finally {
fixture.layer.setParams({ models3d: false, irBoost: false });
fixture.layer.stopTracking();
}
});
test(`${fixture.name}: grounded fleet handoff waits through terrain load and keeps one visual owner`, () => {
clearTr3bRegistry();
fixture.layer.stopTracking();
@@ -397,7 +430,7 @@ for (const fixture of LAYERS) {
assert.equal(model.show, true);
assert.equal(billboard.show, false);
assert.ok(model.show || billboard.show, 'successful handoff keeps a visible owner');
const placed = Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3());
const placed = placedAt(model);
const placedHeight = Cesium.Cartographic.fromCartesian(placed).height;
assert.ok(Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001,
`placement uses the exact ${fixture.bellyM} m asset-measured belly offset`);
@@ -422,7 +455,7 @@ for (const fixture of LAYERS) {
assert.equal(model.show, true, 'no 3D→2D pop while the resample is backing off');
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());
const held = placedAt(model);
assert.ok(Math.abs(Cesium.Cartographic.fromCartesian(held).height
- (sampledHeight + fixture.bellyM)) < 0.001,
'the hold places the model on the last MEASURED floor, not on the feed altitude');
@@ -491,7 +524,7 @@ for (const fixture of LAYERS) {
};
/** Height (m) the model's matrix currently places it at. */
const placedHeightM = () => Cesium.Cartographic.fromCartesian(
Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3()),
placedAt(model),
).height;
const LAT = 30.21;
@@ -594,12 +627,11 @@ for (const fixture of LAYERS) {
}
});
test(`${fixture.name}: grounded tracked model waits for a valid terrain snap with no visual gap`, async () => {
test(`${fixture.name}: grounded tracked model waits for a valid terrain snap with no visual gap`, () => {
clearTr3bRegistry();
fixture.layer.stopTracking();
fixture.layer.setParams({ models3d: false });
const realFrom = Cesium.Model.fromGltfAsync;
const realNow = Date.now;
let now = 3_000_000;
Date.now = () => now;
@@ -609,30 +641,25 @@ for (const fixture of LAYERS) {
tilesLoaded: false,
sampleHeight: () => { sampleCalls++; return sampledHeight; },
});
const collection = recordingModelCollection();
const model = {
modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
ready: false,
show: true,
scale: 1,
destroy() {},
};
Cesium.Model.fromGltfAsync = () => Promise.resolve(model);
const icao24 = fixture.name === 'flights' ? 'a0f001' : 'b0f001';
try {
const billboard = fixture.seed({
viewer,
modelCollection: collection,
onGround: true,
icao24: fixture.name === 'flights' ? 'a0f001' : 'b0f001',
icao24,
});
fixture.driveTrackedModel();
await Promise.resolve(); await Promise.resolve();
assert.equal(collection.added.length, 1, 'the loaded primitive enters the scene once');
assert.equal(model.ready, false, 'the production loader is still awaiting GPU readiness');
assert.equal(model.show, false, 'the loading primitive is admitted hidden, not zero-scaled');
assert.equal(model.scale, 1, 'its scale is left to the pixel-cap driver');
const model = fixture.trackedModel();
const tracked = modelSet(fixture, viewer, 'tracked');
assert.ok(model, 'the driver records the tracked model');
assert.deepEqual([...tracked.items.keys()], [icao24],
'the tracked set loads the one model for the contact');
assert.equal(model.ready, false, 'the model is still loading');
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,
'the tracked billboard remains opaque while the model lacks safe placement');
assert.equal(sampleCalls, 0, 'cold tiles do not force a synchronous sample');
@@ -672,12 +699,14 @@ for (const fixture of LAYERS) {
assert.equal(fixture.trackedBillboardColor().alpha, 1,
'the billboard retains ownership until GPU readiness too');
model.ready = true;
assert.equal(model.scale, baseScale, 'its scale is left to the pixel-cap driver');
viewer.draw.ready(tracked.spec.id, icao24);
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,
'the billboard becomes transparent only when the model actually owns the visual');
const placed = Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3());
const placed = placedAt(model);
const placedHeight = Cesium.Cartographic.fromCartesian(placed).height;
assert.ok(Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001,
`tracked placement uses the exact ${fixture.bellyM} m asset-measured belly offset`);
@@ -710,7 +739,6 @@ for (const fixture of LAYERS) {
assert.equal(fixture.trackedBillboardColor().alpha, 1,
'there is no invisible-owner gap while the replacement snap is unavailable');
} finally {
Cesium.Model.fromGltfAsync = realFrom;
Date.now = realNow;
fixture.layer.stopTracking();
}
@@ -833,132 +861,9 @@ for (const fixture of LAYERS) {
});
}
// ---------------------------------------------------------------------------
// 3. Bounded on-demand loading
//
// The tracked regime is default-on and its driver runs every scene.preUpdate.
// A missing or corrupt GLB — or a dead network — used to leave the driver in a
// load→reject loop at frame rate for as long as the contact stayed selected,
// because the catch cleared only the in-flight flag. These pin the bound.
// ---------------------------------------------------------------------------
/** Drive N frames of the production tracked-model driver, letting each
* rejected load settle, with a fake clock the backoff can be walked past. */
async function driveFrames(fixture, count, clock) {
for (let i = 0; i < count; i++) {
fixture.driveTrackedModel();
await Promise.resolve(); await Promise.resolve(); // let the rejection settle
clock.advance(2000); // past the retry backoff, so only the LATCH can stop it
}
}
for (const fixture of LAYERS) {
test(`${fixture.name}: a rejecting GLB loader is bounded, not a per-frame retry loop`, async () => {
clearTr3bRegistry();
fixture.layer.setParams({ models3d: false });
const realFrom = Cesium.Model.fromGltfAsync;
const realNow = Date.now;
let now = 1_000_000;
const clock = { advance(ms) { now += ms; } };
Date.now = () => now;
let attempts = 0;
const requested = [];
Cesium.Model.fromGltfAsync = ({ url }) => {
attempts++; requested.push(url);
return Promise.reject(new Error('simulated missing GLB'));
};
// The give-up path warns once by design; keep the run's output clean.
const realWarn = console.warn;
const warnings = [];
console.warn = (...args) => { warnings.push(args.join(' ')); };
try {
const collection = recordingModelCollection();
const viewer = viewerAtHeight(30_000); // well inside the regime
const billboard = fixture.seed({ viewer, modelCollection: collection });
assert.equal(fixture.regimeActive(), true, 'the regime is open, so the driver will try to load');
await driveFrames(fixture, 12, clock);
const settled = attempts;
assert.ok(settled > 0, 'it must actually try');
assert.ok(settled <= 3,
`a failing asset must give up within 3 attempts per selection, got ${settled}`);
// Many more frames must produce NO further attempts — this is the loop bound.
await driveFrames(fixture, 25, clock);
assert.equal(attempts, settled,
'once latched, further frames must not re-ask for the same failed asset');
// Nothing was ever handed to the scene, so the billboard stayed the visual.
assert.equal(collection.added.length, 0, 'a failed load never puts a model up');
assert.equal(fixture.trackedBillboardColor().alpha, 1,
'a rejected tracked model leaves the tracked billboard opaque');
assert.equal(billboard.show, true,
'a rejected model never creates a frame with both visual representations hidden');
// Exactly one operator-facing warning, and it names the asset.
assert.equal(warnings.length, 1, 'the give-up is announced once, not per frame');
assert.ok(warnings[0].includes(requested[0]), `the warning names the asset: ${warnings[0]}`);
// A NEW selection gets a fresh budget — the latch is per contact.
fixture.layer.stopTracking();
fixture.seed({ viewer, icao24: 'def456', modelCollection: collection });
await driveFrames(fixture, 3, clock);
assert.ok(attempts > settled, 'selecting another contact restores the retry budget');
} finally {
Cesium.Model.fromGltfAsync = realFrom;
Date.now = realNow;
console.warn = realWarn;
fixture.layer.stopTracking();
}
});
test(`${fixture.name}: the failure latch clears on a same-icao re-track too`, async () => {
clearTr3bRegistry();
fixture.layer.setParams({ models3d: false });
const realFrom = Cesium.Model.fromGltfAsync;
const realNow = Date.now;
const realWarn = console.warn;
let now = 2_000_000;
const clock = { advance(ms) { now += ms; } };
Date.now = () => now;
let attempts = 0;
Cesium.Model.fromGltfAsync = () => { attempts++; return Promise.reject(new Error('simulated missing GLB')); };
console.warn = () => {};
try {
const collection = recordingModelCollection();
const viewer = viewerAtHeight(30_000);
fixture.seed({ viewer, modelCollection: collection });
await driveFrames(fixture, 12, clock);
const latched = attempts;
await driveFrames(fixture, 10, clock);
assert.equal(attempts, latched, 'latched for this selection');
// Deselect and re-select the SAME contact through the production path.
fixture.layer.stopTracking();
fixture.seed({ viewer, modelCollection: collection });
await driveFrames(fixture, 3, clock);
assert.ok(attempts > latched,
're-tracking the same contact is a new selection and gets its retries back');
} finally {
Cesium.Model.fromGltfAsync = realFrom;
Date.now = realNow;
console.warn = realWarn;
fixture.layer.stopTracking();
}
});
}
test('both layers gate the tracked-model load and record its failures', async () => {
test('both layers reset the per-selection tracked-model state', async () => {
for (const name of ['flights.js', 'militaryFlights.js']) {
const source = readLayerSource(new URL(`./${name}`, import.meta.url));
assert.match(source, /!(?:(?:flightState|state)\.)?_trackedModel\s*&&\s*!(?:(?:flightState|state)\.)?_trackedModelLoading\s*&&\s*(?:parts\.\w+\.)?_trackedModelLoadAllowed\(\s*,?\s*\)/,
`${name}: the driver asks permission before starting another tracked-model load`);
assert.match(source, /(?:parts\.\w+\.)?_noteTrackedModelLoadFailure\(\s*trackedSpec\.url,\s*err,?\s*\)/,
`${name}: a rejected load is recorded against this selection, not silently retried`);
// The reset must be reachable from the real teardown, not only a test seam.
assert.match(source, /(?:parts\.\w+\.)?_releaseTrackedModel\(\s*,?\s*\);\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/,
`${name}: deselect clears the per-selection latches in the production path`);