Draw military flights from the shared GPU icon set

The flights icon planning and presentation move into
`createAircraftIcons` (src/data/aircraftIconLayer.js), and the motion
regime both layers dead-reckon from into src/data/aircraftMotionRegime.js.
Flights keeps only its grounded-floor pass on top.

Military now draws every contact as a row of that icon set, like
flights: the billboards, the cull positions and the rotation-pass
signature go. Tracking hides the row and untracking re-plans it from
the tracked course. Queries read the drawn row position and judge the
horizon as the shader does. Snapshots that arrive before init or after
destroy are ignored, and per-contact lookups find no contact then
instead of throwing.

With about 120 live military contacts, preRender p95 drops from
0.7-0.8 ms to 0.2 ms on the same views. Render time and frame gaps are
unchanged or slightly lower.
This commit is contained in:
Sameh Khamis committed 2026-11-03 20:30:43 -08:00
1 parent fa3a3a3bca
commit b027bde6ad
33 files changed
+1256 -1376

No files matched your search

+177 -348
View File
@@ -9,15 +9,8 @@ import {
} from '../../data/modelVisualAnchor.js';
import * as Cesium from 'cesium';
import { selectModelEligible } from '../../data/modelEligibility.js';
import { cyberSonarBaseAlpha } from '../../cyberSonar.js';
import { cockpitContactDotImage } from '../../data/cockpitContactDot.js';
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
import {
cameraPoseSignature,
horizonOccluder,
screenProjectedRotation,
} from '../../data/iconOrientation.js';
import { limitCourseStep, courseSlewCapDps } from '../../data/motionModel.js';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { aircraftTreatmentAlpha } from '../../data/aircraftRecession.js';
import { isEmergency } from '../../data/aircraftEmergency.js';
import {
PLANE_MODEL_SCALE,
@@ -31,7 +24,6 @@ import {
MODEL_HEADING_OFFSET_DEG,
BILLBOARD_SCALE,
GROUND_SCALE,
COCKPIT_CONTACT_SIZE_PX,
MIL_ICON_COLOR,
TRACKED_ICON_COLOR,
EMERGENCY_ICON_COLOR,
@@ -49,13 +41,9 @@ import {
TRACKED_MODEL_MIN_PX,
TRACKED_MODEL_MAX_PX,
FLEET_DR_INTERVAL_MS,
COURSE_SLEW_DT_MAX_SEC,
ROTATION_REFRESH_MS,
COURSE_MAX_DPS,
} from './policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
import { aircraftVisuals } from '../aircraft/visualState.js';
import { billboardState, setBillboard } from '../../data/billboardMirror.js';
import { modelState, setModel } from '../../data/modelMirror.js';
export function createRendering({
@@ -67,23 +55,8 @@ export function createRendering({
}) {
const { tr3bIconKind, isTr3b } = services.aircraftPresentation;
const { trackedModelScaleForPixelCap } = services.camera;
const {
focusNowMs,
getFocusTarget,
nearFarScalarValueAtDistance,
advanceProjectedSpriteFocus,
} = services.focus;
const { applyAircraftBillboardTreatment, applyAircraftModelTreatment } =
services.recession;
/** Depth-test policy for aircraft billboards (mirror of flights.js — see the
* full rationale there). Round 5 (owner directive 2026-07-06): EVERY contact
* renders depth-test-free at every distance — a uniform always-visible rule;
* the fleet tick's horizon occluder still removes far-side contacts. */
function _groundDepthDistance() {
return Number.POSITIVE_INFINITY;
}
const { focusNowMs, getFocusTarget } = services.focus;
const { applyAircraftModelTreatment } = services.recession;
function _modelSpec(klass) {
let spec = flightState._specCache.get(klass);
@@ -140,7 +113,9 @@ export function createRendering({
return new Cesium.NearFarScalar(1000, 1.15, 8000000, 0.65);
}
function _militaryBillboardScale(icao24) {
/** Fleet icon scale: per-class scale, ×GROUND_SCALE while grounded. */
function _fleetBillboardScale(icao24) {
const meta = flightState.records.data.get(icao24);
return (
BILLBOARD_SCALE *
@@ -149,42 +124,7 @@ export function createRendering({
);
}
/** Apply the current normal/cockpit visual contract to one owned fleet billboard. */
function _applyFleetBillboardPresentation(icao24, bb) {
if (!bb) return;
const limbScale = flightState._billboardLimbScale.get(bb) ?? 1;
const isCockpitContact =
flightState._cockpitContactMode && icao24 !== flightState._trackedIcao;
const isCockpitNear =
isCockpitContact && flightState._cockpitNearContacts.has(icao24);
if (isCockpitContact && !isCockpitNear) {
const freshnessAlpha = cyberSonarBaseAlpha(bb);
bb.image = cockpitContactDotImage();
setBillboard(bb, 'width', COCKPIT_CONTACT_SIZE_PX);
setBillboard(bb, 'height', COCKPIT_CONTACT_SIZE_PX);
setBillboard(bb, 'scale', limbScale);
setBillboard(bb, 'scaleByDistance', _cockpitBillboardScaleByDistance());
bb.color = _fleetBillboardColor(icao24).withAlpha(freshnessAlpha);
setBillboard(bb, 'rotation', 0);
return;
}
const meta = flightState.records.data.get(icao24);
bb.image = aircraftIcon(
_iconKind(icao24, meta?.klass),
aircraftVisuals.read(bb)?.iconLarge ? TRACKED_ICON_PX : undefined,
);
setBillboard(bb, 'width', icao24 === flightState._trackedIcao ? 24 : 20);
setBillboard(bb, 'height', icao24 === flightState._trackedIcao ? 24 : 20);
setBillboard(bb, 'scale', _militaryBillboardScale(icao24) * limbScale);
setBillboard(bb, 'scaleByDistance', _normalBillboardScaleByDistance());
bb.color = _fleetBillboardColor(icao24, meta).withAlpha(
cyberSonarBaseAlpha(bb),
);
}
/** Sprite kind for one contact's billboard. Identity for every aircraft except
/** Sprite kind for one contact's icon. Identity for every aircraft except
* the ones the operator converted into a TR-3B (Easter egg), which draw the
* black-triangle glyph — its thermal-reactive variant while an IR style owns
* the scene. Routing EVERY `aircraftIcon()` call through this is what makes a
@@ -210,6 +150,10 @@ export function createRendering({
return isEmergency(info?.emergency) ? EMERGENCY_ICON_COLOR : MIL_ICON_COLOR;
}
/** Cockpit far-contact pips wear the fleet tint. */
const _cockpitContactColor = _fleetBillboardColor;
/** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude
* ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the
* budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in
@@ -280,12 +224,12 @@ export function createRendering({
/** Everything scene.sampleHeight must NOT hit when snapping a grounded model (mirror of
* flights.js): the vertical pick ray at a plane's own lat/lon otherwise lands on its
* (or a parked neighbor's) billboard/model instead of the tile skin. Exclusion matches
* picked-object IDs — every billboard AND model here carries its icao as `id` — plus
* (or a parked neighbor's) icon/model instead of the tile skin. Exclusion matches
* picked-object IDs — every icon AND model here carries its icao as `id` — plus
* the tracked entity object itself. Built lazily, only when a sample actually fires. */
function _groundSampleExclusions() {
const out = [...flightState._billboards.keys()];
const out = parts.icons._iconIds();
if (flightState._trackedEntity) out.push(flightState._trackedEntity);
return out;
}
@@ -295,7 +239,7 @@ export function createRendering({
* (groundSnap.js; taxiing >50 m retires it to a bounded last-known) plus the belly
* offset so they sit on their
* gear; airborne planes pass through. Until the FIRST sample lands, callers keep the
* depth-test-free billboard visible and the model hidden while this returns null; a
* icon visible and the model hidden while this returns null; a
* contact that has already resolved once holds that measurement through a later
* outage inside groundSnap's drift bound, so taxiing does not pop it back to 2D. */
@@ -324,15 +268,23 @@ export function createRendering({
);
}
/** Atomically hand one fleet contact from its billboard to a safely placed,
/** Atomically hand one fleet contact from its icon to a safely placed,
* ready 3D model. Missing/loading models and unresolved terrain always leave
* the billboard owning the visual, so no render frame can hide both.
* the icon owning the visual, so no render frame can hide both.
* `beforeShow` runs only on the committing path — the per-tick model treatment
* belongs to a model that is about to draw, not to one still waiting. */
function _driveFleetModelHandoff(icao24, model, bb, pos, course, beforeShow) {
function _driveFleetModelHandoff(
icao24,
model,
row,
pos,
course,
beforeShow,
) {
const icons = flightState._icons;
if (!model) {
setBillboard(bb, 'show', true);
icons.setShown(row, true);
return false;
}
const displayPos = _modelDisplayPosition(
@@ -342,7 +294,7 @@ export function createRendering({
);
if (!displayPos) {
setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at
setBillboard(bb, 'show', true);
icons.setShown(row, true);
return false;
}
// The matrix is written BEFORE the readiness test on purpose: a model can flip
@@ -361,12 +313,12 @@ export function createRendering({
);
if (!model.ready) {
setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash
setBillboard(bb, 'show', true);
icons.setShown(row, true);
return false;
}
beforeShow?.();
if (!modelState(model).show) setModel(model, 'show', true);
if (billboardState(bb).show) setBillboard(bb, 'show', false); // hand off ONLY once the model renders
icons.setShown(row, false); // hand off ONLY once the model renders
return true;
}
@@ -402,7 +354,7 @@ export function createRendering({
/** Class-change model sync — mirror of flights.js: drop a live model or
* in-flight load whose spec no longer matches the class, re-showing the
* fleet billboard FIRST (gap-proof) and covering the tracked standalone. */
* fleet icon (on release, gap-proof) and covering the tracked standalone. */
function _syncModelToClass(icao24) {
const key = _specKeyFor(flightState.records.data.get(icao24)?.klass);
@@ -411,9 +363,6 @@ export function createRendering({
(current && aircraftVisuals.read(current)?.specKey !== key) ||
(!current && flightState._modelPending.has(icao24))
) {
const bb = flightState._billboards.get(icao24);
if (bb && icao24 !== flightState._trackedIcao)
setBillboard(bb, 'show', true);
_releaseModel(icao24);
}
if (
@@ -447,16 +396,13 @@ export function createRendering({
aircraftVisuals.read(model)?.irBoost === flightState._irBoost
)
continue; // already right state
const bb = flightState._billboards.get(icao);
if (bb && icao !== flightState._trackedIcao)
setBillboard(bb, 'show', true);
_releaseModel(icao);
}
if (flightState._irReloadQueue.length === 0)
flightState._irReloadQueue = null;
}
/** Lazily create the glTF model for an aircraft (fire-and-forget; billboard shows until ready). */
/** Lazily create the glTF model for an aircraft (fire-and-forget; its icon shows until ready). */
async function _ensureModel(icao24) {
// Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet
@@ -501,7 +447,7 @@ export function createRendering({
id: icao24, // so scene.pick returns the icao for click-to-track
});
} catch {
// asset/decode fail — stay billboard. Only touch this lifecycle's state if still current
// asset/decode fail — stay an icon. Only touch this lifecycle's state if still current
// (a destroy/re-init may have swapped the globals while this load was in flight).
if (epoch === flightState._modelEpoch) {
flightState._modelPending.delete(icao24);
@@ -554,7 +500,7 @@ export function createRendering({
visual.specKey = specKey; // class-change sync compares against this
visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this
// Admitted, not yet the visual. Cesium's default is show=true, which would let
// an unplaced primitive claim ownership from the billboard for the frames
// an unplaced primitive claim ownership from the icon for the frames
// between admission and the next fleet tick (and draw at the identity matrix,
// i.e. the Earth's centre). The handoff turns it on once it has a matrix.
setModel(model, 'show', false);
@@ -589,6 +535,7 @@ export function createRendering({
}
}
flightState._models.delete(icao24);
_showReleasedIcon(icao24);
}
// Do NOT clear _modelPending here — the in-flight load's OWN post-await removes it. Keeping
// it (a) prevents a duplicate load from starting and (b) keeps the bumped gen entry alive so
@@ -607,7 +554,7 @@ export function createRendering({
flightState._modelGen.delete(icao24);
}
/** Remove all live models (toggle-off / zoom-out); billboards take back over next tick. */
/** Remove all live models (toggle-off / zoom-out); icons take back over at once. */
function _releaseModels() {
flightState._irReloadQueue = null; // a full release supersedes any pending boost-flip drain
@@ -629,9 +576,20 @@ export function createRendering({
}
}
}
for (const icao24 of flightState._models.keys()) _showReleasedIcon(icao24);
flightState._models.clear();
}
/** A released fleet model hands the visual straight back to its icon (the
* tracked contact's entity keeps its own). */
function _showReleasedIcon(icao24) {
const icons = flightState._icons;
const row = icons?.row(icao24) ?? -1;
if (row >= 0 && icao24 !== flightState._trackedIcao)
icons.setShown(row, true);
}
/** Destroy the standalone tracked-aircraft model and invalidate any in-flight load. */
function _releaseTrackedModel() {
@@ -672,8 +630,7 @@ export function createRendering({
// readout consumers then reuse that exact cached position.
const pos =
parts.motion._trackedDisplayPosition(flightState._trackedIcao) ||
billboardState(flightState._billboards.get(flightState._trackedIcao))
?.position;
parts.icons._iconPosition(flightState._trackedIcao);
if (!pos) {
if (flightState._trackedModel)
setModel(flightState._trackedModel, 'show', false);
@@ -750,9 +707,7 @@ export function createRendering({
// default here produces a one-frame jump to the Earth's center.
const currentPos =
parts.motion._trackedDisplayCached() ||
billboardState(
flightState._billboards.get(flightState._trackedIcao),
)?.position;
parts.icons._iconPosition(flightState._trackedIcao);
if (currentPos) {
const displayPos = _modelDisplayPosition(
flightState._trackedIcao,
@@ -832,57 +787,38 @@ export function createRendering({
}
/**
* Per-preRender fleet pass at ~12Hz: dead-reckons every untracked billboard,
* horizon-culls billboards beyond the limb (no far-side depth with the globe
* hidden), and refreshes screen-projected icon rotations whenever the camera
* pose changed (plus a 1s drift catch-up while idle). Driven by
* scene.preRender — NOT camera.changed, whose granularity is globally
* degraded by other layers mutating camera.percentageChanged.
* ~12 Hz fleet pass. Motion, rotation, the horizon cull, limb recession and
* the two-tier glyph swap all run on the GPU from each row's segment, so this
* only re-plans rows whose regime ended, advances focus de-emphasis while a
* target exists, and drives the 3D-model handoff inside the model regime.
* Driven by scene.preRender.
* @returns {void}
*/
function _fleetTick() {
if (
!flightState._viewer ||
!flightState._billboardCollection ||
!flightState._billboardCollection.show
)
return;
const icons = flightState._icons;
if (!flightState._viewer || !icons || !icons.show) return;
const scene = flightState._viewer.scene;
const camera = flightState._viewer.camera;
const nowMs = focusNowMs(Date.now());
// (The tracked trail head is now the per-frame _trailHeadEntity segment — no 1 Hz
// primitive rebuild here. The body rebuilds only when a real fix arrives.)
if (nowMs - flightState._lastFleetTickMs < FLEET_DR_INTERVAL_MS) return;
const tickDtSec = flightState._lastFleetTickMs
? Math.min(
COURSE_SLEW_DT_MAX_SEC,
(nowMs - flightState._lastFleetTickMs) / 1000,
)
: 0.08;
flightState._lastFleetTickMs = nowMs;
// Every contact in this pass shares the same delayed display instant.
const renderTime = parts.icons._displayTime(
flightState._scratchFleetRenderTime,
);
const tau = icons.seconds(renderTime);
_drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload
if (flightState._cockpitContactMode)
parts.tracking._refreshCockpitNearContacts();
const poseSig = cameraPoseSignature(camera);
// Only nearby Cockpit silhouettes need projected course; far dots remain
// rotation-free through the per-contact gate below.
const doRotations =
poseSig !== flightState._lastCamPoseSig ||
nowMs - flightState._lastRotPassMs >= ROTATION_REFRESH_MS;
if (doRotations) {
flightState._lastCamPoseSig = poseSig;
flightState._lastRotPassMs = nowMs;
}
const occluder = horizonOccluder(camera);
parts.icons._replanExpired(tau);
const focusTarget = getFocusTarget();
parts.icons._focusIcons(tau, scene, camera, nowMs, focusTarget);
// 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling.
// Drop all models the moment we leave it (toggled off / zoomed out) so billboards resume.
// Drop all models the moment we leave it (toggled off / zoomed out) so icons resume.
const useModels = _modelRegimeActive();
// Drop live models AND invalidate in-flight loads on leaving the regime (else a load that
// resolves after zoom-out could briefly add a model outside the 3D-model regime).
@@ -891,240 +827,133 @@ export function createRendering({
(flightState._models.size || flightState._modelPending.size)
)
_releaseModels();
if (!useModels) return;
// 3D-model eligibility: by DISTANCE (mode's add/keep band) with ON-SCREEN PRIORITY under the cap —
// mirror of flights.js. FOUR visible-first passes: (1) KEEP on-screen modeled; (2) ADD on-screen
// new in add radius; (3) KEEP off-screen modeled; (4) ADD off-screen new with leftover slots. KEEP
// is split by frustum so an off-screen retained model can't starve an on-screen plane (review finding).
let modelEligible = null;
if (useModels) {
const cap = _modelCap();
const camPos = camera.positionWC;
const addM = _modelAddDistM();
const addDistSq = addM * addM;
const keepM = _modelKeepDistM();
const keepDistSq = keepM * keepM;
const cull = camera.frustum.computeCullingVolume(
camPos,
camera.directionWC,
camera.upWC,
// 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the
// cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen
// already-modeled (hysteresis for visible planes); (2) ADD on-screen new inside the add radius,
// nearest first; (3) KEEP off-screen already-modeled; (4) ADD off-screen new with leftover slots
// (so a plane just off the cone still models — the "planes right next to me aren't 3D" complaint).
// Crucially KEEP is SPLIT by frustum: an off-screen retained model (pass 3) can never starve an
// on-screen plane that wants one (passes 1–2) — a single KEEP-everything pass could fill the cap
// with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum
// filtering dropped near off-screen planes entirely. This does both right.
const cap = _modelCap();
const camPos = camera.positionWC;
const addM = _modelAddDistM();
const addDistSq = addM * addM;
const keepM = _modelKeepDistM();
const keepDistSq = keepM * keepM;
const cull = camera.frustum.computeCullingVolume(
camPos,
camera.directionWC,
camera.upWC,
);
// Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness.
const cand = [];
for (let row = 0; row < icons.count; row++) {
const icao = icons.idAt(row);
if (icao === flightState._trackedIcao) continue;
// A converted TR-3B renders as an icon and can never take a model, so
// it must not occupy a CAP SLOT either — excluded here at selection time,
// not just at the handoff below, or accumulated conversions would starve
// ordinary contacts of 3D models. (The handoff guard stays as defence.)
if (isTr3b(icao)) continue;
// Ground planes compete for model slots like everyone else (owner decision
// 2026-07-03: "3D mode is respected regardless of whether a plane is on the
// ground or in the air — no distinction"). The cap + nearest-first ordering
// below already bound airport clusters; grounded placement is handled by the
// one-shot ground snap in _modelDisplayPosition.
const position = icons.position(
row,
tau,
flightState._scratchModelBS.center,
);
const cand = [];
for (const [icao, bb] of flightState._billboards) {
if (icao === flightState._trackedIcao) continue;
// A converted TR-3B renders as a billboard and can never take a model, so
// it must not occupy a CAP SLOT either (mirror of flights.js) — excluded
// at selection time, not just at the handoff below.
if (isTr3b(icao)) continue;
// Ground planes compete for model slots like everyone else (owner decision
// 2026-07-03, mirror of flights.js — no air/ground distinction; grounded
// placement is handled by the one-shot ground snap in _modelDisplayPosition).
const { position } = billboardState(bb);
const d2 = Cesium.Cartesian3.distanceSquared(camPos, position);
if (d2 > keepDistSq) continue; // beyond keep radius → never eligible
Cesium.Cartesian3.clone(position, flightState._scratchModelBS.center);
cand.push([
icao,
d2,
cull.computeVisibility(flightState._scratchModelBS) !==
Cesium.Intersect.OUTSIDE,
]);
}
cand.sort((a, b) => a[1] - b[1]);
if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) {
console.warn(
`[Data:Military] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen prioritized.`,
);
flightState._lastModelCapWarnMs = nowMs;
}
modelEligible = selectModelEligible(cand, {
cap,
addDistSq,
isModeled: (icao) => flightState._models.has(icao),
});
const toRelease = [];
for (const icao of flightState._models.keys()) {
if (icao !== flightState._trackedIcao && !modelEligible.has(icao))
toRelease.push(icao);
}
for (const icao of toRelease) _releaseModel(icao);
const d2 = Cesium.Cartesian3.distanceSquared(camPos, position);
if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible
cand.push([
icao,
d2,
cull.computeVisibility(flightState._scratchModelBS) !==
Cesium.Intersect.OUTSIDE,
]);
}
for (const [icao24, bb] of flightState._billboards) {
if (icao24 === flightState._trackedIcao) continue; // tracked entity owns its own motion
const icon = billboardState(bb);
const dr = parts.motion._deadReckon(icao24, flightState._scratchFleetPos);
// Gate the write — assigning Billboard.position dirties the whole
// collection's vertex buffer, so skip sub-meter moves.
if (dr && Cesium.Cartesian3.distanceSquared(dr, icon.position) > 1.0) {
setBillboard(bb, 'position', dr);
}
// Round 6: occlusion-test a LIFTED point for contacts at/below the
// ellipsoid (mirror of flights.js — sub-ellipsoid points near the limb
// read "beyond the horizon" and would hide low contacts awaiting floors).
const beyondHorizon = !occluder.isPointVisible(
flightState.records.data.get(icao24)?.cullPosition || icon.position,
cand.sort((a, b) => a[1] - b[1]); // nearest first
if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) {
console.warn(
`[Data:Military] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen planes are prioritized.`,
);
// A billboard flipping INTO view (horizon reveal while the camera idles)
// gets its rotation refreshed THIS tick even without a pose change —
// otherwise it reappears wearing its stale (often creation-north) nose for
// up to ROTATION_REFRESH_MS. (Model-handed-off planes also read show=false
// here; harmless — the model branch below `continue`s past the rotation.)
const revealed = !beyondHorizon && !icon.show;
if (icon.show === beyondHorizon) setBillboard(bb, 'show', !beyondHorizon);
if (beyondHorizon) {
// Also hide any 3D model — otherwise a model that crossed the limb would keep
// rendering through the hidden globe at its last matrix.
flightState._lastModelCapWarnMs = nowMs;
}
const modelEligible = selectModelEligible(cand, {
cap,
addDistSq,
isModeled: (icao) => flightState._models.has(icao),
});
const toRelease = [];
for (const icao of flightState._models.keys()) {
if (icao !== flightState._trackedIcao && !modelEligible.has(icao))
toRelease.push(icao);
}
for (const icao of toRelease) _releaseModel(icao);
// 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown
// until the model is actually READY to render, so a plane is never both iconless AND
// modelless (the "planes vanish when 3D turns on" bug). Position the model every tick
// regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on
// purpose: the Easter egg IS the triangle, and there is no GLB for it.
const occluder = horizonOccluder(camera);
for (const icao24 of modelEligible) {
if (isTr3b(icao24)) continue;
const row = icons.row(icao24);
if (row < 0) continue;
const position = icons.position(row, tau, flightState._scratchFleetPos);
if (!parts.icons._aboveHorizon(row, position, occluder)) {
// A model that crossed the limb would keep rendering through the
// hidden globe at its last matrix; the icon's own cull is on the GPU.
const m = flightState._models.get(icao24);
if (m && modelState(m)?.show) setModel(m, 'show', false);
continue;
}
const info = flightState.records.data.get(icao24);
// One sprite-owned write site composes freshness × focus × limb haze and
// base class/ground scale × limb taper. The locked NearFarScalar remains
// untouched and multiplicative; there is no cull or zero-alpha path.
const cameraDistanceM = Cesium.Cartesian3.distance(
camera.positionWC,
icon.position,
_ensureModel(icao24);
const model = flightState._models.get(icao24);
const cameraDistanceM = Cesium.Cartesian3.distance(camPos, position);
_driveFleetModelHandoff(
icao24,
model,
row,
position,
icons.course(row, tau),
() => {
applyAircraftModelTreatment({
model,
// IR boost must survive the per-tick treatment write — otherwise
// any alpha change would repaint the ordinary tint over the hot
// white. Boosted models also skip the recession fade: hot targets
// stay full-strength at any range (icons keep their normal
// fade — full-opacity glyph walls read as overwhelming).
baseColor: flightState._irBoost
? Cesium.Color.WHITE
: _modelColor(icao24),
alpha: flightState._irBoost
? 1
: aircraftTreatmentAlpha({
baseAlpha: icons.alpha(row),
focusFactor: icons.focus(row),
cameraDistanceM,
cameraHeightM: camera.positionCartographic?.height,
}),
});
},
);
const distanceScale = nearFarScalarValueAtDistance(
icon.scaleByDistance,
cameraDistanceM,
);
const focus = advanceProjectedSpriteFocus(
bb,
icon.position,
scene,
camera,
nowMs,
focusTarget,
undefined,
(icon.width || 20) * (icon.scale || 1) * distanceScale * 0.5,
(icon.height || 20) * (icon.scale || 1) * distanceScale * 0.5,
);
const isCockpitNear =
flightState._cockpitContactMode &&
flightState._cockpitNearContacts.has(icao24);
const baseColor = _fleetBillboardColor(icao24, info);
const treatment = applyAircraftBillboardTreatment({
billboard: bb,
baseScale:
flightState._cockpitContactMode && !isCockpitNear
? 1
: _militaryBillboardScale(icao24),
baseAlpha: flightState.records.missingPolls.get(icao24) ? 0.45 : 1,
baseColor,
focusFactor: focus.factor,
cameraDistanceM,
cameraHeightM: camera.positionCartographic?.height,
});
flightState._billboardLimbScale.set(bb, treatment.factors.scale);
// Two-tier glyph raster — mirror of flights.js: swap 64/192 px rasters on
// the billboard's ACTUAL on-screen size (post-treatment bb.scale, so
// focus/limb recession counts) with hysteresis (atlas has no mips).
if (!flightState._cockpitContactMode || isCockpitNear) {
const glyphDevPx =
(icon.width || 20) *
(icon.scale || 1) *
distanceScale *
(globalThis.devicePixelRatio || 1);
const visual = aircraftVisuals.write(bb);
const wantLarge = visual.iconLarge ? glyphDevPx > 56 : glyphDevPx > 76;
if (wantLarge !== !!visual.iconLarge) {
visual.iconLarge = wantLarge;
bb.image = aircraftIcon(
_iconKind(icao24, flightState.records.data.get(icao24)?.klass),
wantLarge ? TRACKED_ICON_PX : undefined,
);
}
}
// Smoothed display course: the path direction _deadReckon just reported
// for THIS aircraft (nothing else calls _deadReckon in between), rate-
// limited so segment-boundary course steps glide instead of snapping.
// The slew cap eases toward COURSE_MIN_DPS at low speed, and a hovering
// aircraft (hold flag) keeps its previous nose direction outright.
const rawCourse =
flightState._drCourseDeg != null
? flightState._drCourseDeg
: (info && info.track) || 0;
const prevCourse = flightState._displayCourse.get(icao24);
const course =
flightState._drCourseHold && prevCourse != null
? prevCourse
: limitCourseStep(
prevCourse,
rawCourse,
courseSlewCapDps(
flightState._drSpeedMps != null
? flightState._drSpeedMps
: ((info && info.speedMps) ?? NaN),
COURSE_MAX_DPS,
),
tickDtSec,
);
flightState._displayCourse.set(icao24, course);
// 3D model takes over from the billboard for in-view planes (modelEligible). GAP-PROOF: the
// billboard stays shown until the model is actually READY to render, so a plane is never both
// iconless AND modelless (the "planes vanish when 3D turns on" bug). Position the model every
// tick regardless so it's framed the instant it becomes ready.
// Converted TR-3Bs stay 2D on purpose (mirror of flights.js): the Easter
// egg IS the triangle and there is no GLB for it, so the model handoff is
// suppressed. The billboard keeps rendering, so the contact still satisfies
// the getNearby/getDetectableObjects visibility guards.
if (useModels && dr && modelEligible.has(icao24) && !isTr3b(icao24)) {
_ensureModel(icao24);
const model = flightState._models.get(icao24);
const ownsVisual = _driveFleetModelHandoff(
icao24,
model,
bb,
dr,
course,
() => {
applyAircraftModelTreatment({
model,
// IR boost must survive the per-tick treatment write; boosted
// models also skip the recession fade (mirror of flights.js —
// billboards keep their normal fade, hot MODELS stay full-strength).
baseColor: flightState._irBoost
? Cesium.Color.WHITE
: _modelColor(icao24),
alpha: flightState._irBoost ? 1 : treatment.alpha,
});
},
);
if (ownsVisual) continue; // skip billboard rotation
}
if (
(!flightState._cockpitContactMode || isCockpitNear) &&
(doRotations || revealed)
) {
const rot = screenProjectedRotation(
scene,
icon.position,
course,
icon.rotation,
);
if (rot !== null && Math.abs(rot - icon.rotation) > 0.002) {
setBillboard(bb, 'rotation', rot);
}
}
}
}
return {
_groundDepthDistance,
_modelSpec,
_normalBillboardScaleByDistance,
_cockpitBillboardScaleByDistance,
_militaryBillboardScale,
_applyFleetBillboardPresentation,
_fleetBillboardScale,
_cockpitContactColor,
_iconKind,
_modelColor,
_fleetBillboardColor,