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

+1
View File
@@ -218,6 +218,7 @@ export function createLifecycle({
}
parts.rendering._releaseModels();
parts.icons._disposeIcons();
parts.tracking._disposeTrackedIcon();
parts.rendering._disposeModelSets();
flightState._iconFocusActive = 0;
flightState._detectionObjects.clear();
+113 -82
View File
@@ -1,4 +1,23 @@
import * as Cesium from 'cesium';
import { findCamera, rendererOf } from '../../render/rendererOf.js';
import { renderedFrames } from '../../data/renderedFrames.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { eastNorthUp, framePoint } from '../../geo/frames.js';
import {
addSeconds,
julianLessThan,
julianNow,
secondsDifference,
} from '../../geo/julian.js';
import {
add,
clamp,
copyInto,
distance,
lerpInto,
scale,
sub,
vec,
} from '../../geo/vector.js';
import {
lerpAngleDeg,
COURSE_HOLD_SPEED_MPS,
@@ -37,6 +56,9 @@ import {
/** Where a military record carries its reported speed and track. */
const RECORD_FIELDS = { speed: 'speedMps', track: 'track' };
/** Whether two ECEF points are the same point, component for component. */
const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
export function createMotion({
flightState,
services,
@@ -48,11 +70,33 @@ export function createMotion({
const {
nearFarScalarValueAtDistance,
clearFocusTarget,
publishFocusTargetFromCachedPosition,
publishFocusTargetAt,
} = services.focus;
/** `_motionRegime`'s reused result. */
const regime = createMotionRegime();
/** The camera's pose, or null without a camera to ask. */
function _pose() {
const viewer = flightState._viewer;
try {
return (viewer && findCamera(viewer)?.pose()) ?? null;
} catch {
return null;
}
}
/** The renderer canvas's CSS height (the viewer's own canvas when no
* renderer is bound), or 0 without either. */
function _viewportHeightPx() {
const viewer = flightState._viewer;
const canvas = rendererOf(viewer)?.canvas ?? viewer?.canvas;
return Number(canvas?.clientHeight) || 0;
}
// Fixes leave the cache with their history; a corrected position
// invalidates the local frame even when the fix's point is changed in place.
const fixFrames = new WeakMap();
/**
* Dead-reckon an aircraft's current position using ENU (East-North-Up) frame math.
*
@@ -63,8 +107,8 @@ export function createMotion({
* source contact plus a bounded grace window.
*
* @param {string} icao24 - ICAO hex identifier of the aircraft
* @param {Cesium.Cartesian3} [result] - Optional out-parameter to write into.
* @returns {Cesium.Cartesian3|null} Estimated current ECEF position, or null if no history
* @param {{x: number, y: number, z: number}} [result] - Optional out-parameter to write into.
* @returns {{x: number, y: number, z: number}|null} Estimated current ECEF position, or null if no history
*/
function _deadReckon(icao24, result) {
@@ -77,11 +121,11 @@ export function createMotion({
return null;
}
const out = result || new Cesium.Cartesian3();
const out = result || vec();
// Render one poll interval behind real time so we interpolate between
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
const renderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
const renderTime = addSeconds(
julianNow(),
-RENDER_DELAY_SEC,
flightState._scratchRenderTime,
);
@@ -89,10 +133,7 @@ export function createMotion({
const regime = _motionRegime(history, info, renderTime);
if (regime.kind === 'between') {
const { a, b, span } = regime;
const t =
span > 0
? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span
: 1.0;
const t = span > 0 ? secondsDifference(renderTime, a.time) / span : 1.0;
const trackCourse = lerpAngleDeg(regime.trackFrom, regime.trackTo, t);
flightState._drCourseDeg =
regime.chordCourse != null
@@ -100,10 +141,10 @@ export function createMotion({
: trackCourse;
flightState._drSpeedMps = regime.speed;
flightState._drCourseHold = regime.speed < COURSE_HOLD_SPEED_MPS;
return Cesium.Cartesian3.lerp(a.position, b.position, t, out);
return lerpInto(a.position, b.position, t, out);
}
const dt = Cesium.Math.clamp(
Cesium.JulianDate.secondsDifference(renderTime, regime.fix.time),
const dt = clamp(
secondsDifference(renderTime, regime.fix.time),
regime.minDt,
regime.maxDt,
);
@@ -144,24 +185,26 @@ export function createMotion({
flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS;
if (speed === 0 || dt === 0) {
flightState._drCourseDeg = heading;
return Cesium.Cartesian3.clone(fix.position, out);
return copyInto(fix.position, out);
}
// Constant-rate-turn arc (straight line when turnRateDps ≈ 0) — a plane in a
// standard-rate turn is ~90° of arc wrong per 30 s if extrapolated straight.
arcOffsetEnu(speed, heading, turnRateDps, dt, flightState._scratchArc);
flightState._drCourseDeg = flightState._scratchArc.endCourseDeg;
Cesium.Cartesian3.fromElements(
flightState._scratchArc.east,
flightState._scratchArc.north,
0,
flightState._scratchOffset,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
fix.position,
Cesium.Ellipsoid.WGS84,
flightState._scratchEnu,
);
return Cesium.Matrix4.multiplyByPoint(enu, flightState._scratchOffset, out);
const offset = flightState._scratchOffset;
offset.x = flightState._scratchArc.east;
offset.y = flightState._scratchArc.north;
offset.z = 0;
let frame = fixFrames.get(fix);
if (!frame) {
frame = { position: vec(), enu: null };
fixFrames.set(fix, frame);
}
if (!frame.enu || !samePoint(frame.position, fix.position)) {
frame.enu = eastNorthUp(fix.position);
copyInto(fix.position, frame.position);
}
return copyInto(framePoint(frame.enu, offset), out);
}
/**
@@ -175,21 +218,21 @@ export function createMotion({
if (!flightState._trackedIcao) return false;
const history = flightState._positionHistory.get(flightState._trackedIcao);
if (!history || history.length === 0) return true;
const renderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
const renderTime = addSeconds(
julianNow(),
-RENDER_DELAY_SEC,
flightState._scratchWarmupTime,
);
return Cesium.JulianDate.lessThan(renderTime, history[0].time);
return julianLessThan(renderTime, history[0].time);
}
/** Resolve the selected aircraft's actual rendered square extent this frame. */
function _trackedFocusSizePx(icao24, position) {
const camera = flightState._viewer?.camera;
const scene = flightState._viewer?.scene;
if (!camera?.positionWC || !position || !scene) return 28;
const rangeM = Cesium.Cartesian3.distance(camera.positionWC, position);
const pose = _pose();
if (!pose || !position) return 28;
const rangeM = distance(pose.position, position);
const viewportHeightPx = _viewportHeightPx();
if (parts.rendering._modelOwnsVisual(icao24)) {
const spec = parts.rendering._modelSpec(
flightState.records.data.get(icao24)?.klass,
@@ -198,12 +241,11 @@ export function createMotion({
baseScale: spec.scale,
nativeRadiusM: spec.nativeRadiusM,
rangeM,
viewportHeightPx: scene.canvas.clientHeight,
fovyRad: camera.frustum.fovy,
viewportHeightPx,
fovyRad: pose.fovy,
maximumPixelSize: TRACKED_MODEL_MAX_PX,
});
const focalLengthPx =
scene.canvas.clientHeight / (2 * Math.tan(camera.frustum.fovy / 2));
const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2));
const projectedDiameterPx =
(2 * spec.nativeRadiusM * scale * focalLengthPx) / rangeM;
return Math.max(
@@ -226,16 +268,16 @@ export function createMotion({
}
/**
* Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by Cesium
* frame number so the position / rotation / trail-head callbacks share ONE computation
* Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by drawn
* frame (see renderedFrames.js) so the position / rotation / trail-head callbacks share ONE computation
* (and one reconciliation-state update) per frame. Returns a stable module holder, or
* null when the aircraft has no fix.
* @param {string} icao24
* @returns {Cesium.Cartesian3|null}
* @returns {{x: number, y: number, z: number}|null}
*/
function _trackedDisplayPosition(icao24) {
const frame = flightState._viewer?.scene?.frameState?.frameNumber ?? -1;
const frame = renderedFrames(flightState._viewer);
if (
frame === flightState._cachedDRFrame &&
icao24 === flightState._drReconcileIcao
@@ -266,32 +308,29 @@ export function createMotion({
const speed = (info && info.speedMps) || 0;
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
const plausible = speed * dtSec * 4 + 25;
if (Cesium.Cartesian3.distance(raw, flightState._drPrevRaw) > plausible) {
if (distance(raw, flightState._drPrevRaw) > plausible) {
// Discontinuity — re-anchor so the DISPLAYED position stays continuous, then decay.
Cesium.Cartesian3.subtract(
flightState._drPrevDisplay,
raw,
copyInto(
sub(flightState._drPrevDisplay, raw),
flightState._drCorrection,
);
flightState._drCorrectionStartMs = nowMs;
}
} else {
Cesium.Cartesian3.fromElements(0, 0, 0, flightState._drCorrection);
copyInto(vec(), flightState._drCorrection);
flightState._drCorrectionStartMs = nowMs - DR_CORRECTION_MS; // fully decayed
}
const elapsed = nowMs - flightState._drCorrectionStartMs;
const factor =
elapsed >= DR_CORRECTION_MS ? 0 : 1 - elapsed / DR_CORRECTION_MS;
const display = Cesium.Cartesian3.multiplyByScalar(
flightState._drCorrection,
factor,
const display = copyInto(
add(raw, scale(flightState._drCorrection, factor)),
flightState._trackedPosHolder,
);
Cesium.Cartesian3.add(raw, display, display);
Cesium.Cartesian3.clone(raw, flightState._drPrevRaw);
Cesium.Cartesian3.clone(display, flightState._drPrevDisplay);
copyInto(raw, flightState._drPrevRaw);
copyInto(display, flightState._drPrevDisplay);
flightState._drPrevMs = nowMs;
flightState._drReconcileValid = true;
flightState._cachedDRPosition = display;
@@ -299,14 +338,13 @@ export function createMotion({
icao24,
flightState._cachedDRPosition,
);
// Publish the exact frame cache shared by entity + follow camera. A second
// Publish the exact frame cache shared by billboard + follow camera. A second
// DR sample here would advance reconciliation in a different frame phase
// and visibly jitter the focus rectangle against the tracked aircraft.
publishFocusTargetFromCachedPosition({
publishFocusTargetAt({
ownerLayer: 'militaryFlights',
id: icao24,
scene: flightState._viewer?.scene,
camera: flightState._viewer?.camera,
viewer: flightState._viewer,
displayPosition: flightState._cachedDRPosition,
widthPx: focusSizePx,
heightPx: focusSizePx,
@@ -315,8 +353,8 @@ export function createMotion({
}
/** The tracked plane's display position WITHOUT recomputing — the value the follow-camera already
* settled on this frame. Mirror of flights.js: getDetectableObjects + the readout run in postRender at
* a later frameNumber, so recomputing _trackedDisplayPosition there jitters the label against the
* settled on this frame. Mirror of flights.js: getDetectableObjects + the readout run in postRender,
* later in the frame, so recomputing _trackedDisplayPosition there jitters the label against the
* now-stable plane. Null when no valid fix (callers fall back to the icon position). */
function _trackedDisplayCached() {
@@ -368,10 +406,12 @@ export function createMotion({
!parts.rendering._modelOwnsVisual(flightState._trackedIcao)
)
return null;
return Cesium.Matrix4.getTranslation(
flightState._trackedModel.matrix,
flightState._scratchTrailClip,
);
const m = flightState._trackedModel.matrix;
const out = flightState._scratchTrailClip;
out.x = m[12];
out.y = m[13];
out.z = m[14];
return out;
}
function _trackedModelEnvelopeM() {
@@ -471,7 +511,7 @@ export function createMotion({
flightState._cachedDRHold = false;
flightState._trackedCourseMs = 0;
}
/** The display instant `epochMs` as a JulianDate, for `_motionRegime`. */
/** The display instant `epochMs` as a Julian date, for `_motionRegime`. */
const _displayTimeAt = (epochMs, result) => julianAt(epochMs, result);
/**
@@ -497,15 +537,10 @@ export function createMotion({
)
continue;
info.renderAltitudeM = lifted;
const liftedPos = Cesium.Cartesian3.fromDegrees(
info.rawLon,
info.rawLat,
lifted,
);
const liftedPos = fromDegrees(info.rawLon, info.rawLat, lifted);
const hist = flightState._positionHistory.get(icao24);
const newest = hist?.[hist.length - 1];
if (newest)
newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position);
if (newest) newest.position = copyInto(liftedPos, newest.position);
if (flightState._icons.has(icao24)) {
parts.icons._applyIconPresentation(icao24);
parts.icons._planIcon(icao24);
@@ -515,19 +550,15 @@ export function createMotion({
/**
* Sample the rendered mesh under the collected floor cells (see
* meshFloorSampler.js), leaving this layer's own icons and models out of
* the probe so it cannot land on an aircraft instead of the pavement.
* meshFloorSampler.js), leaving this layer's own icon and model sets out
* of the probe so it cannot land on an aircraft instead of the pavement.
*/
function _sampleMeshFloor(points, viewerLat, viewerLon) {
services.meshFloor.sampleMeshFloorCells(
flightState._viewer?.scene,
points,
{
excludeObjects: parts.icons._iconIds(),
viewerLat,
viewerLon,
},
);
services.meshFloor.sampleMeshFloorCells(flightState._viewer, points, {
sets: parts.rendering._groundSampleExclusions().sets,
viewerLat,
viewerLon,
});
}
return {
+1 -1
View File
@@ -90,7 +90,7 @@ test('military state owns separate contact maps, motion scratch and ground sampl
'_displayCourse',
'_positionHistory',
'_groundSnap',
'_scratchCarto',
'_scratchNearbyPos',
'_models',
'lifetime',
]) {
+21 -15
View File
@@ -1,5 +1,11 @@
import * as Cesium from 'cesium';
import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
import { cssColor } from '../../render/color.js';
/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */
const rgba = (css, alpha) =>
Object.freeze(
alpha === undefined ? cssColor(css) : [...cssColor(css).slice(0, 3), alpha],
);
/**
* @module militaryFlights
@@ -21,18 +27,17 @@ import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
export const BILLBOARD_SCALE = 0.7;
/** @constant {Cesium.Color} Default amber tint for untracked military icons */
/** @constant {number[]} Default amber tint for untracked military icons */
export const MIL_ICON_COLOR = Cesium.Color.fromCssColorString('#FFB800');
export const MIL_ICON_COLOR = rgba('#FFB800');
/** @constant {Cesium.Color} Lighter amber tint applied to the actively tracked aircraft */
/** @constant {number[]} Lighter amber tint applied to the actively tracked aircraft */
export const TRACKED_ICON_COLOR = Cesium.Color.fromCssColorString('#FFD166');
export const TRACKED_ICON_COLOR = rgba('#FFD166');
/** @constant {Cesium.Color} Red tint for aircraft broadcasting an emergency (mirror of flights) */
/** @constant {number[]} Red tint for aircraft broadcasting an emergency (mirror of flights) */
export const EMERGENCY_ICON_COLOR =
Cesium.Color.fromCssColorString(EMERGENCY_TINT_CSS);
export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS);
// --- Ground traffic (owner reversal 2026-07-03; mirror of flights.js) ---------------
// adsb.lol/readsb flags ground traffic with alt_baro === "ground" (no separate
@@ -143,16 +148,17 @@ export const MODEL_BELLY_OFFSET_NATIVE = 5.631;
/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */
export const AMBER_TRANSPARENT = MIL_ICON_COLOR.withAlpha(0);
export const AMBER_TRANSPARENT = rgba('#FFB800', 0);
export const COCKPIT_CONTACT_SIZE_PX = 6;
export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = new Cesium.NearFarScalar(
1000,
3.0,
8000000,
0.5,
);
/** The tracked billboard's size by eye distance (the renderer's `NearFar`). */
export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = Object.freeze({
near: 1000,
nearValue: 3.0,
far: 8000000,
farValue: 0.5,
});
// ---------------------------------------------------------------------------
// Track-history trail state (PRD WS-F F2/F4): a fading polyline behind the
+24 -32
View File
@@ -1,8 +1,9 @@
import { cameraOf } from '../../render/cesium/camera.js';
import { cameraOf } from '../../render/rendererOf.js';
import { followedOf } from '../../data/followed.js';
import { displayedKinematics } from '../../data/motionModel.js';
import { t } from '../../i18n/index.js';
import * as Cesium from 'cesium';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { clone, distance as distanceBetween, vec } from '../../geo/vector.js';
import { isExplicitLayerStateOrigin } from '../../data/layerState.js';
import { aircraftIncludedInNearby } from '../../data/aircraftNearbyPolicy.js';
import { modelVisualAnchor } from '../../data/modelVisualAnchor.js';
@@ -89,7 +90,7 @@ export function createQueries({
* Build a public descriptor for one aircraft using its best current position
* (dead-reckoned when history exists, icon position otherwise).
* @param {string} icao24 - ICAO hex identifier of the aircraft.
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
* Descriptor with a cloned position, or null if the aircraft is unknown.
*/
@@ -97,7 +98,7 @@ export function createQueries({
const info = flightState.records.data.get(icao24);
const basePos =
parts.motion._deadReckon(icao24) ||
parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
parts.icons._iconPosition(icao24, vec());
if (!basePos) return null;
const displayed = displayedKinematics({
derivedSpeedMps: flightState._drSpeedMps,
@@ -105,11 +106,7 @@ export function createQueries({
reportedSpeedMps: info?.speedMps,
reportedTrackDeg: info?.track,
});
const carto = Cesium.Cartographic.fromCartesian(
basePos,
Cesium.Ellipsoid.WGS84,
flightState._scratchCarto,
);
const carto = toLonLatH(basePos);
if (!carto) return null;
return {
icao24,
@@ -118,9 +115,9 @@ export function createQueries({
// getTrackedSubject and the voice narration can read it straight off the
// descriptor instead of reaching back into `_flightData`.
registration: _toCleanText(info?.registration) || null,
position: Cesium.Cartesian3.clone(basePos),
latitude: Cesium.Math.toDegrees(carto.latitude),
longitude: Cesium.Math.toDegrees(carto.longitude),
position: clone(basePos),
latitude: carto.lat,
longitude: carto.lon,
// Keep the cockpit readout on the reported aviation altitude. Render
// terrain height is a separate visual datum and may be below zero.
altitudeM: Number.isFinite(info?.altitudeM)
@@ -342,7 +339,7 @@ export function createQueries({
/**
* Find military aircraft near a given ECEF position, sorted by distance.
* Used by proximity-based features (e.g. detection overlay, spatial queries).
* @param {Cesium.Cartesian3} center - Reference position in ECEF coordinates
* @param {{x: number, y: number, z: number}} center - Reference position in ECEF coordinates
* @param {number} range - Maximum distance in meters (Infinity if not specified)
* @param {number} [maxCount=50] - Maximum number of results to return
* @param {object} [options] Query membership options.
@@ -383,9 +380,9 @@ export function createQueries({
)
continue;
const distance = Cesium.Cartesian3.distance(center, drawn);
const distance = distanceBetween(center, drawn);
if (distance > maxRange) continue;
const pos = trackedPos || Cesium.Cartesian3.clone(drawn);
const pos = trackedPos || clone(drawn);
const info = flightState.records.data.get(icao24);
nearby.push({
@@ -423,7 +420,7 @@ export function createQueries({
* @param {Object} [options={}] - Options
* @param {number} [options.maxCount] - Maximum objects to return (defaults to all)
* @param {number} [options.seed] - Seed offset for stride sampling (for frame variation)
* @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>}
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>}
*/
getDetectableObjects(options = {}) {
const icons = flightState._icons;
@@ -464,8 +461,8 @@ export function createQueries({
sourceId: icao24,
type: 'AIR',
tier: 'military',
_weldPos: new Cesium.Cartesian3(),
_iconPos: new Cesium.Cartesian3(),
_weldPos: vec(),
_iconPos: vec(),
};
flightState._detectionObjects.set(icao24, object);
}
@@ -488,7 +485,7 @@ export function createQueries({
spec,
(view ??= parts.rendering._drawnScaleView()),
),
object._weldPos || (object._weldPos = new Cesium.Cartesian3()),
object._weldPos || (object._weldPos = vec()),
)
: icons.position(icao24, t, object._iconPos);
// An icon past the horizon is not drawn, so it is not detectable.
@@ -530,7 +527,7 @@ export function createQueries({
* Match priority: exact icao24 hex, exact callsign, callsign prefix,
* then callsign substring (all case-insensitive, trimmed).
* @param {string} query - ICAO hex or full/partial callsign.
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
* Best match with a cloned, dead-reckoned position, or null if none.
*/
findByQuery(query) {
@@ -574,7 +571,7 @@ export function createQueries({
* Cheap snapshot for voice-tool framing — drawn icon positions, no
* extra dead reckoning.
* @param {number} [maxCount=500] - Maximum number of entries to return.
* @returns {Array<{id: string, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number}>}
* @returns {Array<{id: string, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number}>}
*/
/**
* Whether this layer still carries a contact, in O(1).
@@ -606,12 +603,8 @@ export function createQueries({
const result = [];
for (const icao24 of icons.ids()) {
const pos = icons.position(icao24, t, new Cesium.Cartesian3());
const carto = Cesium.Cartographic.fromCartesian(
pos,
Cesium.Ellipsoid.WGS84,
flightState._scratchCarto,
);
const pos = icons.position(icao24, t, vec());
const carto = toLonLatH(pos);
if (!carto) continue;
const info = flightState.records.data.get(icao24);
result.push({
@@ -623,8 +616,8 @@ export function createQueries({
_toCleanText(info?.registration) ||
icao24,
position: pos,
latitude: Cesium.Math.toDegrees(carto.latitude),
longitude: Cesium.Math.toDegrees(carto.longitude),
latitude: carto.lat,
longitude: carto.lon,
altitudeM: carto.height,
});
if (result.length >= limit) break;
@@ -735,7 +728,6 @@ export function createQueries({
if (!flightState._icons?.has(id)) id = id.toLowerCase();
if (
id !== flightState._trackedIcao ||
!flightState._viewer.entities?.contains?.(flightState._trackedEntity) ||
followedOf(flightState._viewer) !== flightState._followTarget
)
return false;
@@ -777,7 +769,7 @@ export function createQueries({
/**
* Return the current aircraft as a Context subject without changing
* tracking or camera ownership.
* @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null}
* @returns {{layerId: string, id: string, label: string, position: {x: number, y: number, z: number}}|null}
* Detached subject descriptor, or null when no aircraft is tracked.
*/
getTrackedSubject() {
@@ -790,7 +782,7 @@ export function createQueries({
// Same label chain as getNearby/getDetectableObjects: a callsign-less
// contact reads as its registration, never as the raw ICAO hex.
label: described.callsign || described.registration || described.icao24,
position: Cesium.Cartesian3.clone(described.position),
position: clone(described.position),
};
},
@@ -32,7 +32,11 @@ function harness({ viewer = null, floor = null } = {}) {
records: { data: new Map() },
};
const parts = {
rendering: { _modelOwnsVisual: () => false, _syncModelToClass() {} },
rendering: {
_modelOwnsVisual: () => false,
_syncModelToClass() {},
_groundSampleExclusions: () => ({ sets: ['fleet-models', 'icons'] }),
},
icons: {
_iconIds: () => ['icon-primitive'],
_addIcon: (id) => iconIds.add(id),
@@ -115,10 +119,10 @@ test('the mesh floor probe takes the camera subpoint from the camera port', () =
h.apply(CONTACT, 1_700_000_000_000);
assert.equal(h.meshCalls.length, 1);
const [call] = h.meshCalls;
assert.equal(call.scene, viewer.scene);
assert.equal(call.scene, viewer);
assert.equal(call.options.viewerLat, 30.5);
assert.equal(call.options.viewerLon, -97.25);
assert.deepEqual(call.options.excludeObjects, ['icon-primitive']);
assert.deepEqual(call.options.sets, ['fleet-models', 'icons']);
});
test('without a viewer the mesh floor probe has no camera subpoint', () => {
+26 -38
View File
@@ -1,6 +1,5 @@
import { MilitaryFlightRecords } from './records.js';
import { createMilitaryFeed } from './ingestion.js';
import * as Cesium from 'cesium';
export function createFlightState({ source, services }) {
const { createGroundSnap } = services.groundSnap;
@@ -50,10 +49,6 @@ export function createFlightState({ source, services }) {
flightState._lastModelCapWarnMs = 0;
// throttle the "more planes in view than the cap" console notice
flightState._scratchModelBS = new Cesium.BoundingSphere(
new Cesium.Cartesian3(),
1.0,
);
// ---------------------------------------------------------------------------
// Module-level state
@@ -72,7 +67,7 @@ export function createFlightState({ source, services }) {
flightState._detectionObjects = new Map();
/** @type {Map<string, Array<{time: Cesium.JulianDate, position: Cesium.Cartesian3}>>} ICAO hex -> recent position samples for dead reckoning */
/** @type {Map<string, Array<{time: object, position: {x: number, y: number, z: number}}>>} ICAO hex -> recent position samples for dead reckoning */
flightState._positionHistory = new Map();
@@ -85,7 +80,7 @@ export function createFlightState({ source, services }) {
flightState._trackingIntentGeneration = 0;
/** @type {Cesium.Entity|null} Entity created for the tracked aircraft (camera follows this) */
/** @type {object|null} The tracked aircraft's record holder (its entity record is what the app shows; the camera follows a target reading it) */
flightState._trackedEntity = null;
@@ -102,7 +97,7 @@ export function createFlightState({ source, services }) {
flightState._clickSubscription = null;
/** @type {Cesium.Viewer|null} Cached viewer reference */
/** @type {object|null} Cached viewer reference */
flightState._viewer = null;
@@ -132,7 +127,7 @@ export function createFlightState({ source, services }) {
flightState._trailHeadOff = null;
/** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */
/** @type {{x: number, y: number, z: number}[]} Chronological tracked-aircraft fixes (oldest first) */
flightState._trailPositions = [];
@@ -148,50 +143,46 @@ export function createFlightState({ source, services }) {
flightState._lastTrackedRotation = 0;
/** @type {Cesium.Event.RemoveCallback|null} preRender listener disposer */
/** @type {() => void|null} preRender listener disposer */
flightState._preRenderRemove = null;
flightState._trackedModelPreUpdateRemove = null;
/** @type {Cesium.Event.RemoveCallback|null} camera.moveEnd listener disposer (arrival rotation pass) */
/** @type {() => void|null} camera.moveEnd listener disposer (arrival rotation pass) */
flightState._moveEndRemove = null;
/** @type {Cesium.Event.RemoveCallback|null} trackedEntityChanged listener disposer (cross-layer untrack) */
/** @type {() => void|null} trackedEntityChanged listener disposer (cross-layer untrack) */
flightState._trackedEntityChangedRemove = null;
// -- Scratch variables (reused each frame to avoid GC pressure) --
flightState._scratchOffset = new Cesium.Cartesian3();
flightState._scratchCarto = new Cesium.Cartographic();
flightState._scratchEnu = new Cesium.Matrix4();
flightState._scratchOffset = { x: 0, y: 0, z: 0 };
flightState._scratchArc = { east: 0, north: 0, endCourseDeg: 0 };
flightState._scratchRenderTime = new Cesium.JulianDate();
flightState._scratchRenderTime = { dayNumber: 0, secondsOfDay: 0 };
flightState._scratchFleetRenderTime = new Cesium.JulianDate();
flightState._scratchFleetRenderTime = { dayNumber: 0, secondsOfDay: 0 };
flightState._scratchFleetPos = new Cesium.Cartesian3();
flightState._scratchFleetPos = { x: 0, y: 0, z: 0 };
flightState._scratchCockpitPos = new Cesium.Cartesian3();
flightState._scratchCockpitPos = { x: 0, y: 0, z: 0 };
flightState._scratchNearbyPos = new Cesium.Cartesian3();
flightState._scratchNearbyPos = { x: 0, y: 0, z: 0 };
flightState._scratchSonarScreen = new Cesium.Cartesian2();
flightState._scratchSonarScreen = { x: 0, y: 0 };
flightState._scratchDrRaw = new Cesium.Cartesian3();
flightState._scratchDrRaw = { x: 0, y: 0, z: 0 };
flightState._scratchWarmupTime = new Cesium.JulianDate();
flightState._scratchWarmupTime = { dayNumber: 0, secondsOfDay: 0 };
flightState._trackedPosHolder = new Cesium.Cartesian3();
flightState._trackedPosHolder = { x: 0, y: 0, z: 0 };
// -- Per-frame dead-reckoning cache for the tracked entity --
/** @type {Cesium.Cartesian3|null} Cached DR position for the current render frame */
/** @type {{x: number, y: number, z: number}|null} Cached DR position for the current render frame */
flightState._cachedDRPosition = null;
@@ -240,13 +231,13 @@ export function createFlightState({ source, services }) {
flightState._displayCourse = new Map();
flightState._drCorrection = new Cesium.Cartesian3(0, 0, 0);
flightState._drCorrection = { x: 0, y: 0, z: 0 };
flightState._drCorrectionStartMs = 0;
flightState._drPrevRaw = new Cesium.Cartesian3();
flightState._drPrevRaw = { x: 0, y: 0, z: 0 };
flightState._drPrevDisplay = new Cesium.Cartesian3();
flightState._drPrevDisplay = { x: 0, y: 0, z: 0 };
flightState._drPrevMs = 0;
@@ -256,20 +247,20 @@ export function createFlightState({ source, services }) {
flightState._drReconcileIcao = null;
/** @type {Cesium.Cartesian3} Scratch for the tracked model's rendered translation. */
/** @type {{x: number, y: number, z: number}} Scratch for the tracked model's rendered translation. */
flightState._trackedVisualPos = new Cesium.Cartesian3();
flightState._trackedVisualPos = { x: 0, y: 0, z: 0 };
flightState._trackedTrailPos = new Cesium.Cartesian3();
flightState._trackedTrailPos = { x: 0, y: 0, z: 0 };
/** Scratch for the tracked model's world-space origin (the envelope centre). */
flightState._scratchTrailClip = new Cesium.Cartesian3();
flightState._scratchTrailClip = { x: 0, y: 0, z: 0 };
/** Scratch for the shortened trail-head start. Owned by the head-segment
* callback alone, so nothing else can overwrite it mid-frame. */
flightState._scratchTrailHead = new Cesium.Cartesian3();
flightState._scratchTrailHead = { x: 0, y: 0, z: 0 };
/** Hysteresis latch for the tracked contact's zoom regime, plus the selection it
* belongs to. Scoped per selection so a NEW target re-evaluates against the ENTER
@@ -285,8 +276,5 @@ export function createFlightState({ source, services }) {
flightState._irBoost = false;
/** @type {Cesium.Cartographic} Scratch for _trailFloorPosition (per-frame safe). */
flightState._scratchTrailCarto = new Cesium.Cartographic();
return flightState;
}
+139 -151
View File
@@ -1,19 +1,30 @@
import { cameraOf } from '../../render/cesium/camera.js';
import { findFrame } from '../../render/rendererOf.js';
import { cameraOf, findCamera, findFrame } from '../../render/rendererOf.js';
import {
entityFollowTarget,
onFollowChanged,
stopFollowing,
} from '../../data/followed.js';
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
import { trackedModelZoomActive } from '../../data/trackedModelRegime.js';
import {
screenProjectedRotation,
courseScreenRotation,
stabilizeScreenRotation,
} from '../../data/iconOrientation.js';
} from '../../data/screenRotation.js';
import {
createTrackedAircraftIcon,
isOtherTrackedIconSet,
trackedContactHolder,
} from '../../data/trackedAircraftIcon.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addSeconds,
julianLessThanOrEquals,
julianNow,
julianToEpochMs,
} from '../../geo/julian.js';
import { clone, distanceSquared, vec } from '../../geo/vector.js';
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import {
@@ -41,7 +52,7 @@ function aircraftPickId(picked) {
const id = picked?.id;
if (typeof id === 'string') return id;
if (id && typeof id.set === 'string' && typeof id.id === 'string')
return id.id;
return isOtherTrackedIconSet(id.set, 'military') ? undefined : id.id;
return picked?.primitive?.id;
}
@@ -67,6 +78,21 @@ export function createTracking({
const { clearFocusTarget } = services.focus;
const { FOLLOW_MIN_RANGE_M } = services.camera;
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
viewer: () => flightState._viewer,
setPrefix: 'military',
});
/** The camera's pose, or null without a camera to ask. */
function _pose() {
const viewer = flightState._viewer;
try {
return (viewer && findCamera(viewer)?.pose()) ?? null;
} catch {
return null;
}
}
function _emitAwarenessEvent(type, detail) {
if (
@@ -79,7 +105,7 @@ export function createTracking({
}
function _publishTrackedSelection(icao24, origin = 'programmatic') {
const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
const position = parts.icons._iconPosition(icao24, vec());
const info = flightState.records.data.get(icao24);
if (!position || !info) return false;
if (flightState._trackedEntity)
@@ -157,10 +183,8 @@ export function createTracking({
/** Refresh the AIR-only Cockpit near band independently from model admission. */
function _refreshCockpitNearContacts() {
if (
!flightState._cockpitContactMode ||
!flightState._viewer?.camera?.positionWC
) {
const eye = flightState._cockpitContactMode ? _pose()?.position : null;
if (!eye) {
if (flightState._cockpitNearContacts.size)
flightState._cockpitNearContacts = new Set();
return;
@@ -176,13 +200,7 @@ export function createTracking({
t,
flightState._scratchCockpitPos,
);
distancesSquared.push([
icao24,
Cesium.Cartesian3.distanceSquared(
flightState._viewer.camera.positionWC,
position,
),
]);
distancesSquared.push([icao24, distanceSquared(eye, position)]);
}
const next = nextCockpitNearContacts(
previous,
@@ -284,12 +302,9 @@ export function createTracking({
refreshTrackedSubjectContext(_contextSubjectMetadata(icao24));
}
/** Re-image the tracked entity's billboard from the current class/conversion. */
function _syncTrackedBillboardImage() {
if (!flightState._trackedIcao || !flightState._trackedEntity?.billboard)
return;
flightState._trackedEntity.billboard.image = aircraftIcon(
/** The tracked billboard's image, from the current class/conversion. */
function _trackedBillboardImage() {
return aircraftIcon(
parts.rendering._iconKind(
flightState._trackedIcao,
flightState.records.data.get(flightState._trackedIcao)?.klass,
@@ -298,6 +313,13 @@ export function createTracking({
);
}
/** Re-image the tracked billboard from the current class/conversion. */
function _syncTrackedBillboardImage() {
if (!flightState._trackedIcao || !flightState._trackedEntity) return;
trackedIcon.setImage(_trackedBillboardImage());
}
/**
* Re-render one contact after its TR-3B conversion (or the active IR style)
* changed. Mirror of flights.js: converting drops any 3D model so the triangle
@@ -325,7 +347,8 @@ export function createTracking({
_syncTrackedBillboardImage();
_updateTrackedLabelModel(id);
}
flightState._viewer?.scene?.requestRender?.();
if (flightState._viewer)
findFrame(flightState._viewer)?.requestRender('military: TR-3B restyle');
return flightState._icons?.has(id) || id === flightState._trackedIcao;
}
@@ -384,7 +407,7 @@ export function createTracking({
return false;
}
flightState._trackedZoomLatched = trackedModelZoomActive(
flightState._viewer?.camera?.positionCartographic?.height,
_pose()?.height,
flightState._trackedZoomLatched,
);
return flightState._trackedZoomLatched;
@@ -396,13 +419,10 @@ export function createTracking({
if (!flightState._trackedIcao || !flightState._viewer) return;
const pos =
parts.motion._trackedDisplayCached() ||
parts.icons._iconPosition(
flightState._trackedIcao,
new Cesium.Cartesian3(),
);
parts.icons._iconPosition(flightState._trackedIcao, vec());
if (!pos) return;
const projected = screenProjectedRotation(
flightState._viewer.scene,
const projected = courseScreenRotation(
_pose(),
pos,
parts.motion._trackedDisplayCourse(),
flightState._lastTrackedRotation,
@@ -423,31 +443,27 @@ export function createTracking({
* invariant), so every position entering the TRAIL subsystem (seed, append,
* per-frame head) goes through this instead — the visible taxi history sits
* on the surface without touching the billboard/model machinery.
* @param {Cesium.Cartesian3} position - Owned position (mutated/replaced freely).
* @returns {Cesium.Cartesian3} The same or a lifted position.
* @param {{x: number, y: number, z: number}} position - Owned ECEF position (mutated/replaced freely).
* @returns {{x: number, y: number, z: number}} The same or a lifted position.
*/
function _trailFloorPosition(position) {
const carto = Cesium.Cartographic.fromCartesian(
position,
Cesium.Ellipsoid.WGS84,
flightState._scratchTrailCarto,
);
const carto = toLonLatH(position);
if (!carto) return position;
const latDeg = Cesium.Math.toDegrees(carto.latitude);
const lonDeg = Cesium.Math.toDegrees(carto.longitude);
const latDeg = carto.lat;
const lonDeg = carto.lon;
const floored = floorAltitudeM(
carto.height,
cachedGroundFloor(latDeg, lonDeg),
);
if (floored == null || floored === carto.height) return position;
return Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, floored);
return fromDegrees(lonDeg, latDeg, floored);
}
/**
* Append one fix to the tracked aircraft's trail accumulation and refresh
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
* @param {Cesium.Cartesian3} position - New fix position, appended at the head.
* @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head.
*/
function _appendTrailFix(position) {
@@ -478,7 +494,7 @@ export function createTracking({
/**
* The live head: the last DISPLAYED body point to the delayed head, or no
* positions while there is none.
* @returns {Cesium.Cartesian3[]}
* @returns {Array<{x: number, y: number, z: number}>}
*/
function _trailHeadPositions() {
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
@@ -503,7 +519,7 @@ export function createTracking({
// Floor the head too (round 2): a grounded tracked contact's DR
// display height is the pre-datum default — without this the last
// segment dives underground while taxiing.
const end = _trailFloorPosition(Cesium.Cartesian3.clone(head));
const end = _trailFloorPosition(clone(head));
// On a contact that has not moved this segment runs from inside the
// model out to its own anchor — a line through the fuselage. The END
// never gives, so a moving trail still terminates on the tail; the
@@ -541,18 +557,18 @@ export function createTracking({
// Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
// would draw the trail in front of the plane. They join via _appendTrailFix as they age.
const seedRenderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
const seedRenderTime = addSeconds(
julianNow(),
-RENDER_DELAY_SEC,
flightState._scratchWarmupTime,
);
for (const fix of history) {
if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) {
if (julianLessThanOrEquals(fix.time, seedRenderTime)) {
// Floor grounded-history seeds (round 2): a grounded contact's stored
// fixes carry the pre-datum default height — the trail copy sits on
// the surface instead (pure lift; airborne fixes pass through).
flightState._trailPositions.push(
_trailFloorPosition(Cesium.Cartesian3.clone(fix.position)),
_trailFloorPosition(clone(fix.position)),
);
}
}
@@ -574,7 +590,7 @@ export function createTracking({
_refreshTrailDisplay();
const oldestFixEpochSec = history.length
? Cesium.JulianDate.toDate(history[0].time).getTime() / 1000
? julianToEpochMs(history[0].time) / 1000
: Infinity;
_backfillTrail(icao24, flightState._trailBackfillToken, oldestFixEpochSec);
}
@@ -664,7 +680,7 @@ export function createTracking({
// sentinel (an arbitrary placeholder, never a reported altitude).
if (altM == null) altM = lastAltM != null ? lastAltM : 50;
lastAltM = altM;
older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM));
older.push(fromDegrees(lon, lat, altM));
}
// Stride-thin the backfill so it plus the live fine segment fit the cap.
@@ -749,17 +765,15 @@ export function createTracking({
// release never flips it.
const trackedCourseDeg = flightState._displayCourse.get(clearedIcao);
// Stop tracking and remove the entity. skipViewerUntrack: another layer just grabbed the
// follow-camera, so tear down our state but DON'T clear the camera's follow (they own it now).
// Releasing trackedEntity does NOT move the camera: Cesium resets the lookAt transform in
// place, so the view stays where the follow left it and the user can immediately orbit/zoom.
// Stop tracking and hide the tracked billboard. skipViewerUntrack: another layer just grabbed
// the follow-camera, so tear down our state but DON'T clear the camera's follow (they own it
// now). Releasing the follow does NOT move the camera: the view stays where the follow left it
// and the user can immediately orbit/zoom.
if (flightState._viewer && !skipViewerUntrack) {
stopFollowing(flightState._viewer);
}
if (flightState._trackedEntity) {
flightState._viewer.entities.remove(flightState._trackedEntity);
flightState._trackedEntity = null;
}
trackedIcon.hide();
flightState._trackedEntity = null;
parts.rendering._releaseTrackedModel();
_resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped
flightState._trackedIcao = null;
@@ -820,19 +834,14 @@ export function createTracking({
// The tracked limiter continues from the nose the icon was drawn with, and
// the entity starts with the rotation the icon had on screen.
const t = parts.icons._displayMs();
const iconPosition = icons.position(icao24, t, new Cesium.Cartesian3());
const iconPosition = icons.position(icao24, t, vec());
const iconCourse = icons.course(icao24, t);
flightState._displayCourse.set(icao24, iconCourse);
flightState._trackedIcao = icao24;
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling
flightState._cachedDRFrame = -1;
flightState._lastTrackedRotation =
screenProjectedRotation(
flightState._viewer.scene,
iconPosition,
iconCourse,
0,
) ?? 0;
courseScreenRotation(_pose(), iconPosition, iconCourse, 0) ?? 0;
// Drop any fleet 3D model for this aircraft — the tracked entity now owns its visual (its
// own billboard + model graphic), and the fleet tick skips the tracked icao, so a leftover
// fleet model would be orphaned + double-rendered.
@@ -847,28 +856,20 @@ export function createTracking({
// aircraft has no fix.
const getTrackedPosition = () =>
parts.motion._trackedDisplayPosition(icao24) ||
parts.icons._iconPosition(icao24, new Cesium.Cartesian3()) ||
parts.icons._iconPosition(icao24, vec()) ||
iconPosition;
// Dead-reckoning position property evaluated every render frame.
// isConstant = false so CesiumJS re-evaluates each frame.
const positionProperty = new Cesium.CallbackProperty(() => {
return getTrackedPosition();
}, false);
// World-space orientation for the 3D model: nose along the course heading (ENU, pitch/roll 0).
// Create tracked entity: a 2D billboard when zoomed out, a 3D model when zoomed in past the
// TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on the
// DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
// The tracked billboard: a 2D icon when zoomed out, handing over to the 3D model when zoomed
// in past the TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on
// the DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
// resolves into an aircraft.
//
// The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by
// show=false: it drops its alpha only once the tracked model is drawing, so
// there's neither a billboard+model double-image nor a gap. The camera follows its own target
// through the camera port, so nothing here frames the camera.
// The tracked entity is a PURE BILLBOARD — no label or model graphic. The tracked plane's 3D
// model is the standalone primitive driven by _updateTrackedModel(); it stays off the entity (see _trackedModel).
// What the tracked billboard is drawn at, kept in its entity record so the
// show=false: it drops its alpha only once the tracked model is drawing, so there's neither a
// billboard+model double-image nor a gap. The camera follows its own target through the camera
// port, so nothing here frames the camera. The tracked plane's 3D model is a draw-set item
// driven by _updateTrackedModel() (see _trackedModel).
// What the tracked billboard is drawn at, kept in its record so the
// camera guard and screen annotations size it from the app.
const sprite = {
width: 28,
@@ -880,58 +881,49 @@ export function createTracking({
] || 1),
scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
};
flightState._trackedEntity = flightState._viewer.entities.add({
position: positionProperty,
billboard: {
image: aircraftIcon(
parts.rendering._iconKind(
flightState._trackedIcao,
flightState.records.data.get(flightState._trackedIcao)?.klass,
),
TRACKED_ICON_PX,
),
width: sprite.width,
height: sprite.height,
scale: sprite.scale,
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
// transparent once the STANDALONE tracked model is actually up (ready + shown).
color: new Cesium.CallbackProperty(
() =>
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? AMBER_TRANSPARENT
: TRACKED_ICON_COLOR,
false,
),
sizeInMeters: false,
scaleByDistance: sprite.scaleByDistance,
alignedAxis: Cesium.Cartesian3.ZERO,
// The tracked target must never vanish into tile geometry — tracking a
// taxiing plane at street level would otherwise bury the amber icon inside
// the runway skin, so it draws depth-test-free like the fleet icon set;
// its shared-host tracked card is top-composited separately.
disableDepthTestDistance: Number.POSITIVE_INFINITY,
// Screen-projected rotation, evaluated per frame: exact in tracked-orbit
// mode where camera.heading lives in the entity's reference frame.
rotation: new Cesium.CallbackProperty(() => {
const tracked = flightState.records.data.get(
flightState._trackedIcao,
);
const pos = getTrackedPosition();
if (!tracked || !pos || !flightState._viewer)
return flightState._lastTrackedRotation;
const projected = screenProjectedRotation(
flightState._viewer.scene,
pos,
parts.motion._trackedDisplayCourse(),
flightState._lastTrackedRotation,
);
const rot = stabilizeScreenRotation(
flightState._lastTrackedRotation,
projected,
);
if (rot !== null) flightState._lastTrackedRotation = rot;
// The tracked contact as its readers see it (the tracked card, Cockpit, share links): a
// plain holder of its entity record, drawn while it is the one tracked.
const holder = trackedContactHolder(
`military:${icao24}`,
trackedIcon,
parts.motion._trackedDisplayCached,
);
flightState._trackedEntity = holder;
entityRecord(holder).drawn = () => flightState._trackedEntity === holder;
trackedIcon.show({
id: icao24,
image: _trackedBillboardImage(),
sprite,
position: getTrackedPosition,
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
// transparent once the tracked model is actually up (ready + shown).
color: () =>
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? AMBER_TRANSPARENT
: TRACKED_ICON_COLOR,
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
// street level would otherwise bury the amber icon inside the runway
// skin, so it draws over depth like the fleet icon set; its
// shared-host tracked card is top-composited separately.
rotation: () => {
const tracked = flightState.records.data.get(flightState._trackedIcao);
const pos = getTrackedPosition();
if (!tracked || !pos || !flightState._viewer)
return flightState._lastTrackedRotation;
}, false),
const projected = courseScreenRotation(
_pose(),
pos,
parts.motion._trackedDisplayCourse(),
flightState._lastTrackedRotation,
);
const rot = stabilizeScreenRotation(
flightState._lastTrackedRotation,
projected,
);
if (rot !== null) flightState._lastTrackedRotation = rot;
return flightState._lastTrackedRotation;
},
});
entityRecord(flightState._trackedEntity).selectionOrigin = origin;
@@ -940,20 +932,16 @@ export function createTracking({
entityRecord(flightState._trackedEntity).labelModel =
trackedLabelModelFromText(_buildTrackedLabel(info, icao24), '#ffd166');
// A billboard has a ~zero bounding sphere, so Cesium's default follow distance is
// far too tight (the user had to scroll out to read the plane). Give the entity a
// A billboard has a ~zero bounding sphere, so the renderer's default follow distance is
// far too tight (the user had to scroll out to read the plane). Give the target a
// calibrated viewFrom — behind + above, distance scaled to altitude — for a readable
// initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.)
const altM = info?.altitudeFt ? info.altitudeFt * 0.3048 : 1500;
const followRange = Math.min(Math.max(altM * 1.1 + 2500, 3000), 30000);
const viewFrom = new Cesium.Cartesian3(
0,
-followRange * 0.8,
followRange * 0.55,
);
const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55);
// Cancel any in-progress camera flight first — otherwise Cesium won't apply the tracked
// entity's viewFrom on the first frame, so voice-initiated tracking (which often fires
// Cancel any in-progress camera flight first — otherwise the camera won't apply the follow
// target's viewFrom on the first frame, so voice-initiated tracking (which often fires
// mid-fly_to_location) would follow the plane WITHOUT centering it like a click does.
// Cross-module HUD consumers (tracked-target readout) read the camera's settled position, not a
// postRender recompute, so the label doesn't jitter against the now-stable plane (mirror of flights).
@@ -1011,7 +999,7 @@ export function createTracking({
* Clicking a military billboard starts tracking that aircraft; clicking empty
* space or a non-military object deselects. Also attaches the Escape key
* listener via {@link _onKeyDown}. Idempotent -- no-ops if already installed.
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
* @param {object} viewer - The viewer
*/
function _installClickHandler(viewer) {
@@ -1051,14 +1039,11 @@ export function createTracking({
const picked = event.hit;
if (picked) {
// Clicking the tracked entity itself -- ignore (don't deselect)
if (picked.id === flightState._trackedEntity) return;
// Clicking the plane we're ALREADY tracking (its standalone 3D model or
// any pick carrying its icao) — same no-op as the 2D tracked-entity click
// above. H1: the model used to have no pick id, so this fell through to
// Clicking the plane we're ALREADY tracking (its tracked billboard, its
// 3D model, or any pick carrying its icao) — ignore, don't deselect.
// H1: the model used to have no pick id, so this fell through to
// "empty space" and deselected the very plane being tracked.
// Its models are draw-set items keyed by icao, like its icons.
// Its billboard and models are draw-set items keyed by icao, like its icons.
const pickedIcao = aircraftPickId(picked);
if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao)
return;
@@ -1114,6 +1099,9 @@ export function createTracking({
_backfillTrail,
_clearTrail,
_destroyTrail,
/** Let the tracked billboard's set go (layer teardown). */
_disposeTrackedIcon: () => trackedIcon.dispose(),
/** The tracked billboard's set id, or null before one is made. */
_clearTracking,
_applyPendingTrackingRestore,
_cancelPendingTrackingRestore,