Aircraft drawn as far behind real time as their feed is late, along one curve their trail follows

Civil and military aircraft were drawn a fixed 30 s (15 s) behind real time
while anonymous feed reports arrive about 90 s old every 30 s, so every
contact dead reckoned about a minute past its newest report and snapped
when the next one landed (several km on a turn), and the tracked trail,
recorded from those drawn positions and patched as reports arrived, kinked.

- The display delay (data/displayDelay.js) is the 90th percentile of the
  newest 256 report lags plus 5 s, between the layer's floor (30 s, 15 s)
  and five minutes, slewed at most 0.2 s/s up and 0.05 s/s down. Icons,
  the renderer's live motion clock, labels, HUD, detection, the tracked
  camera and the trail read the one delay; following the world clock
  draws with none and deliveries leave it alone.
- Between two reports an aircraft flies a biarc (data/fixCurve.js) that
  passes through both and leaves each along its track, sent as contract
  arc segments; the trail is the reports joined along the same curve, so
  the icon sits on it. Nothing drawn between reports is kept.
- A report a coasting contact missed is eased onto from where it would
  have been that frame (at least 3 s, at most 30% over its speed, within
  20 s); over 5 km it jumps. Past its newest report a contact coasts
  straight on: a turn rate averaged over earlier reports outlived the turn.
- Forward synthetic fixes no longer block real reports older than them,
  and a history keeps 24 fixes.
- A feed simulation (testSupport/aircraftFeedSim.mjs) checks both layers
  against a 90 s late feed, a fallback switch, repeated reports, outages
  and the world clock.
This commit is contained in:
Sameh Khamis committed 2026-11-14 00:31:29 -08:00
1 parent c57eb74506
commit 5f98f8bdf3
40 files changed
+2606 -1238

No files matched your search

+13
View File
@@ -2,6 +2,19 @@
## [Unreleased]
- Aircraft no longer jump ahead or back, and their trails no longer kink,
when the feed is late. The civil and military layers draw as far behind
real time as their feed is late (the 90th percentile of recent report
lags plus 5 s, at least 30 s civil and 15 s military, at most five
minutes), so an aircraft is placed between two real reports rather than
dead reckoned past them; the delay changes slowly, and the icons, the
renderer's live clock, labels, the HUD, detection, the tracked camera and
the trail all read the same one. Between two reports an aircraft flies
one smooth curve that leaves each report along its track, sent to the
renderer as `arc` segments; its trail is its reports joined along that
same curve, so the icon always sits on it. A late report a coasting
aircraft missed is eased onto, at most 30% faster than it flies; past
its newest report an aircraft coasts straight on (samehkhamis).
- The Display panel has a Sky group on a renderer with a sky to set: the
atmosphere, day and night (sun lighting by scene time), the sun, the
moon, the stars and the Milky Way's brightness. The choice is kept for the
+1 -1
View File
@@ -532,7 +532,7 @@ _Walk the boneyard: rows of retired airframes, fully resolved in 3D._
How the globe handles live data:
- **World-stable icons.** Aircraft and ships point along their _true real-world heading_ at every camera angle — tracked or not, looking straight down or across the horizon — via per-frame screen-space course projection. No spinning, no viewport-locking.
- **Smooth motion from choppy data.** Live feeds arrive every 15–30s; the globe renders one interval behind real time and interpolates between known fixes. Dead reckoning fills the gaps.
- **Smooth motion from choppy data.** Live feeds arrive every 15–30s, often minutes late; the globe renders as far behind real time as the feed is late (at least one interval) and draws each aircraft along a smooth curve between its known fixes. Dead reckoning fills the gaps.
- **Honest satellites.** SGP4 propagation with orbit rings that stay locked to their satellites via GMST realignment — no drift, no per-second flicker.
- **Sits on the real ground.** Entity heights are aligned to work with Google 3D tiles, so aircraft park on aprons and cameras stand on street corners instead of floating.
- **Caching and request budgets.** An OpenSky credit governor, a TomTom daily tile budget, and disk-cached TLEs reduce repeated requests. These controls do not replace provider quotas or billing controls.
+17 -19
View File
@@ -1771,31 +1771,29 @@ A tracked civil or military aircraft's trail (`src/data/trailContinuity.js`) lif
the pen, drawing nothing, between two points more than 48 minutes or over 1,500 kt
apart (a parked aircraft within 0.1 nm keeps one line for up to three hours) and at a
waypoint with no altitude; a ground waypoint is drawn on the ground. The head joins the
aircraft only within 150 km. Each trail keeps up to 2,000 points, a full day of history
at one fix per minute plus the live session; past that the oldest recorded points go
first, and the oldest reports only once none are left. The renderer
aircraft only within 150 km. Each trail keeps up to 2,000 reports, a full day of history
at one fix per minute plus the live session; past that the oldest go first. The renderer
(`src/data/trailRenderer.js`) freezes every chunk of 128 points except the newest into
static geometry, so a long trail costs about as much per frame as a short one;
`scripts/qa-trail-freeze.mjs` checks that a freeze never shows a blank frame.
While an aircraft is tracked, its trail between reports is the path its icon was
drawn along: the displayed position is recorded about once a second or every 150 m
(`recordTrailPoint`). Recorded points are thinned by shape: one stays only where
dropping it would move the line more than 30 m across the track or in height from any
position it stood for, or leave a straight piece longer than 10 km, so straight flight
adds a vertex every 10 km at most and a turn keeps its curve. A recorded point that
would turn the line back sharper than 120° over a short step is dropped. Reports stay
in the trail as anchors, in time order. Recorded points never join two reports that are
not one flight under the 48-minute and 1,500 kt rules; the points between them go and
nothing is recorded across such a pair. A report for a time the display has already
passed replaces what was drawn after it, and nothing is recorded until the icon has
eased onto it, so the line reads arc, report, corrected path. History from before tracking started, and the backfill, run report to report.
A trail holds the aircraft's reports and nothing else, in time order: what the icon was
drawn at between them is never kept, so a late report cannot leave a kink. Between two
reports that are one flight and both carry a track, the icon is drawn along, and the
trail drawn through, one curve (`src/data/fixCurve.js`): a biarc, two constant-rate
turns sent to the renderer as contract `arc` segments, passing through both reports and
leaving each along its reported track, so the icon sits on its trail with no offset.
Pairs with no track, slower than 40 m/s, or with a track more than 75° off the line
between them are joined straight. The trail samples the curve at least every degree of
turn. History from before tracking started, and the backfill, run report to report the
same way.
The trail never runs past the icon or through its 3D model, and the head runs from the
newest kept point outside the model to the icon (to the model's tail when the model is
the visual). A contact with no new report coasts along its reported track for 5 minutes
past its last real report, at no more than 1,500 kt and never below known ground, then stops;
the visual). A contact with no new report coasts straight on along its reported track for 5 minutes
past its last real report (no turn: a turn rate measured over earlier reports outlives
the turn), at no more than 1,500 kt and never below known ground, then stops;
one that
went quiet on the ground, or within 150 m of a known ground floor, holds at its last
report, records nothing and draws no head (with the ground unknown, a low barometric
report and draws no head (with the ground unknown, a low barometric
altitude alone does not hold it). The hold-or-coast choice is made once per report (`staleHoldsForFix`
in `src/data/motionModel.js`), and the forward fix built when a repeated position carries
new speed or course follows the same rules and is never a trail report. A live report
@@ -6662,7 +6660,7 @@ silently demoting every later lookup for the session.
### Motion & Symbology Correctness (June 10, 2026)
- **Flights (commercial + military)** render one poll interval behind real time (30s/15s) and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The display latency is an intentional product decision — do not "fix" it away. The whole fleet dead-reckons at ~12Hz (1m² write gating); aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.”
- **Flights (commercial + military)** render behind real time and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The delay (`src/data/displayDelay.js`) follows how late the feed is: the 90th percentile of the newest 256 lags (a report's receipt time less the same contact's previous report time) plus 5 s, never under the layer's floor (30 s civil, 15 s military) nor over five minutes, so the anonymous OpenSky feed, whose reports arrive about 90 s old every 30 s, draws about two minutes behind. Before 16 lags, first reports' ages plus a poll interval stand in. The delay moves toward that aim by at most 0.2 s per second up and 0.05 s per second down (an aim within 2 s leaves it be), and takes it at once only while nothing is drawn; deliveries following the world clock, or replacing the world at another time, leave it alone and draw with no delay. Every consumer (icons, the renderer's live motion clock, labels, HUD, detection, the tracked camera and trail) reads the one delay. When a newer report puts a moving contact elsewhere than it is drawn (it was coasting past its newest report), it eases onto the new path over at least 3 s, at most 30% faster than its speed and within 20 s, from where it would have been that frame; more than 5 km off, it jumps. The display latency is an intentional product decision — do not "fix" it away. The whole fleet dead-reckons at ~12Hz (1m² write gating); aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.”
- **World-space headings at every angle** (`src/data/screenRotation.js`; the scene-reading helpers in `src/render/cesium/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder.
- **Military/OpenSky reconciliation** (`src/data/militaryRegistry.js`): known-military ICAOs render amber in the flights layer (60s self-poll of the cached mil endpoint when the military layer is off) and are suppressed there while the military layer renders them.
- **Satellites**: core catalog from CelesTrak's stations, visual, GPS, GLONASS, Galileo, GEO, resource, weather, planet, SAR and science groups, tracking lands ~726km out via `viewFrom` (tracked entity owns a point graphic so the tracking camera engages), rings realign via primitive modelMatrix (no per-second rebuild flicker), optional `setParams({catalog:'dense'})` Starlink mode.
+81 -10
View File
@@ -2,13 +2,18 @@ import {
COAST_FLOOR_LIFT_M,
COURSE_HOLD_SPEED_MPS,
courseSlewCapDps,
RECOVER_MIN_M,
RECOVER_SNAP_M,
recoveryMs,
} from './motionModel.js';
import { straightSegment } from './fixCurve.js';
import {
norm180,
distance,
clone,
copyInto,
toDegrees,
vec,
} from '../geo/vector.js';
import { fromRadians, toCartographicRadians } from '../geo/ellipsoid.js';
import { horizonFrom, liftedForHorizon } from '../geo/horizon.js';
@@ -349,6 +354,14 @@ export function floorCoastArc(arc, t, cachedGroundFloor) {
let instances = 0;
/** A plan that ran out longer ago than this (ms) is not eased away from. */
const RECOVER_STALE_PLAN_MS = 1_000;
/** A display delay that never changes (ms). */
function fixedDelay(ms) {
return { currentMs: ms, step: () => ms };
}
/**
* An aircraft layer's contacts as one icon draw set: each item's motion
* segment mirrors the layer's dead reckoning for the delayed display time,
@@ -369,7 +382,10 @@ let instances = 0;
* @param {object} options.services The layer's services (`focus`).
* @param {object} options.parts The layer's parts (`motion`, `rendering`).
* @param {string} options.layerId Pick and focus owner id.
* @param {number} options.renderDelaySec How far behind real time contacts draw.
* @param {{currentMs: number, step: (nowMs: number) => number}} [options.displayDelay]
* How far behind real time contacts draw (`data/displayDelay`), stepped
* once a frame; the renderer's motion clock follows it.
* @param {number} [options.renderDelaySec] A fixed delay instead.
* @param {() => boolean} [options.followsClock] True while the layer follows
* the world clock: contacts draw at the world's time (`state.now()`, the
* scene's time) with no delay.
@@ -389,7 +405,8 @@ export function createAircraftIcons({
services,
parts,
layerId,
renderDelaySec,
renderDelaySec = 0,
displayDelay = fixedDelay(renderDelaySec * 1000),
followsClock = () => false,
staleAlpha = 0.45,
courseMaxDps,
@@ -400,29 +417,40 @@ export function createAircraftIcons({
onForget = () => {},
}) {
const { focusPassIsNeeded } = services.focus;
const delayMs = renderDelaySec * 1000;
// The near-image switch the rows were last written with (CSS px).
let switchPx = nearImageSwitchPx(1);
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
const _displayMs = () =>
followsClock() ? state.now() : Date.now() - delayMs;
/** The live draw set, and whether its motion clock is the scene's. */
followsClock() ? state.now() : Date.now() - displayDelay.currentMs;
/** The live draw set, whether its motion clock is the scene's, and the
* delay its live clock was last given. */
let liveSet = null;
let sceneClock = false;
let sentDelayMs = NaN;
/** The motion clock for whether the layer follows the world clock. */
const motionClock = (scene) =>
scene ? { kind: 'scene' } : { kind: 'live', delayMs };
scene
? { kind: 'scene' }
: { kind: 'live', delayMs: displayDelay.currentMs };
/**
* Put the set's motion on the scene's clock (the world's time) while the
* layer follows the world clock, on the delayed live clock otherwise.
* Once a frame: move the display delay on, and put the set's motion on
* the scene's clock (the world's time) while the layer follows the world
* clock, on the delayed live clock otherwise, with the delay as it is now.
*/
function _syncMotionClock() {
const scene = followsClock();
if (!liveSet || scene === sceneClock) return;
if (!scene) displayDelay.step(Date.now());
if (!liveSet) return;
if (
scene === sceneClock &&
(scene || sentDelayMs === displayDelay.currentMs)
)
return;
sceneClock = scene;
sentDelayMs = scene ? NaN : displayDelay.currentMs;
liveSet.setOptions({ motionClock: motionClock(scene) });
}
@@ -443,6 +471,7 @@ export function createAircraftIcons({
set.setColumns?.({ ids: [] });
liveSet = set;
sceneClock = followsClock();
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
switchPx = _imageSwitchPx(viewer);
state._icons = createContactIcons(set, {
capabilities: rendererOf(viewer)?.capabilities ?? null,
@@ -537,7 +566,15 @@ export function createAircraftIcons({
let pos;
let course;
let expiresAt = Infinity;
if (regime.kind === 'between') {
if (regime.kind === 'between' && regime.piece) {
// Along the curve between the two reports, a piece at a time.
const segment = regime.piece.segment;
speed = segment.speedMps;
motion = { ...segment, fix: clone(segment.fix) };
pos = clone(segment.fix);
course = motionCourse(motion, undefined, t);
expiresAt = regime.piece.t1;
} else if (regime.kind === 'between') {
const { a, b, span, trackFrom, trackTo, chordCourse } = regime;
speed = regime.speed;
const blend = chordCourse == null ? 0 : regime.blend;
@@ -597,6 +634,40 @@ export function createAircraftIcons({
}
}
}
// A new report that puts a moving contact somewhere else than it is
// drawn now (it was coasting past its newest report): it eases from
// where it is onto the new path instead of jumping, unless that is
// farther than a jump would be anyway.
// Only a row on screen whose plan is still running (a hidden row, or one
// whose motion ran out long ago, is simply drawn where it is now).
if (
fromCourseDeg == null &&
icons.shown(icao24) &&
icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS
) {
const prev = icons.item(icao24);
const drawn = motionPosition(prev.motion, prev.pos, t);
const next = motionPosition(motion, pos, t);
const errorM = distance(drawn, next);
if (
errorM > RECOVER_MIN_M &&
errorM < RECOVER_SNAP_M &&
speed >= COURSE_HOLD_SPEED_MPS &&
!same(prev.motion, motion)
) {
const end = t + recoveryMs(errorM, speed);
// Where the new path has it by then, past this plan if need be.
const target = parts.motion._deadReckon(
icao24,
vec(),
parts.motion._displayTimeAt(end),
);
motion = straightSegment(drawn, t, end, target ?? next);
pos = clone(drawn);
course = motionCourse(motion, undefined, t);
expiresAt = end;
}
}
// Below hover speed the nose holds what is on screen (or, for a new row,
// where this motion starts); above it, it glides on at the slew cap.
const hold = speed < COURSE_HOLD_SPEED_MPS;
+43
View File
@@ -9,6 +9,7 @@ import {
import { COAST_FLOOR_LIFT_M } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { createDisplayDelay } from './displayDelay.js';
const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0);
@@ -46,6 +47,48 @@ test('following the world clock, contacts draw at the world’s time on the scen
icons._disposeIcons();
});
test('as the display delay moves, the renderer’s live clock and the layer’s display time move with it; the world clock ignores it', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = { _viewer: viewer, now: () => Date.now() };
const delay = createDisplayDelay({ floorMs: 30_000, pollMs: 30_000 });
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
displayDelay: delay,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
// Reports 90 s old every 30 s: the delay heads for about two minutes.
for (let i = 0; i < 20; i++)
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
delay.settle(WORLD_MS);
t.mock.timers.setTime(WORLD_MS + 10_000);
icons._syncMotionClock();
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
assert.equal(icons._displayMs(), Date.now() - 32_000);
// Following the world clock: no delay, and it is not moved on meanwhile.
following = true;
t.mock.timers.setTime(WORLD_MS + 20_000);
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
assert.equal(icons._displayMs(), Date.now());
assert.equal(delay.currentMs, 32_000);
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
icons._disposeIcons();
});
test('a coasting icon is kept above rising ground, as the CPU coast is', () => {
const T0 = WORLD_MS;
let now = T0;
+75 -13
View File
@@ -7,6 +7,7 @@ import {
secondsDifference,
} from '../geo/julian.js';
import { clone, distance } from '../geo/vector.js';
import { curvePieceAt, fixCurveCached } from './fixCurve.js';
import {
COAST_MAX_SPEED_MPS,
courseBetweenCartesians,
@@ -76,12 +77,54 @@ export function historyFix(epochMs, position, velocity, track) {
};
}
/**
* Whether a history fix is a forward synthetic fix (a motion aid built from
* a repeated report's new speed or course, `synthesizeForwardKinematicsFix`)
* rather than a report.
*/
export const isSyntheticFix = (fix) => Number.isFinite(fix?.reportEpochMs);
/**
* Put a new report at the end of a contact's history: forward synthetic
* fixes after the previous report go (the report supersedes them), and past
* `limit` the oldest fixes go.
* @param {Array<object>} history Oldest first; mutated.
* @param {object} fix The report's history fix.
* @param {number} limit
*/
export function pushReport(history, fix, limit) {
while (history.length && isSyntheticFix(history[history.length - 1]))
history.pop();
history.push(fix);
while (history.length > limit) history.shift();
}
/** The newest report in a history (not a synthetic fix), or undefined. */
export function newestReport(history) {
for (let i = history.length - 1; i >= 0; i--)
if (!isSyntheticFix(history[i])) return history[i];
return undefined;
}
/** The curve a contact is drawn along between two history fixes, or null. */
export function historyCurve(a, b) {
return fixCurveCached(
a.position,
fixEpochMs(a),
a.track,
b.position,
fixEpochMs(b),
b.track,
);
}
/** A reusable result for `aircraftMotionRegime`. */
export function createMotionRegime() {
return {
kind: 'fix',
a: null,
b: null,
piece: null,
span: 0,
speed: 0,
trackFrom: 0,
@@ -100,8 +143,11 @@ export function createMotionRegime() {
* Which motion an aircraft's history gives at `renderTime` — the one choice
* the CPU dead reckoning and the icon planner (GPU segment) both draw from.
*
* - `between`: interpolate the bracketing pair `a`→`b`, no extrapolation
* error and no snap-back. The course of the DISPLAYED motion blends the
* - `between`: between the bracketing pair `a`→`b`, no extrapolation
* error and no snap-back. Along their curve (`data/fixCurve`) when the
* pair describes one: `piece` is the curve's piece at `renderTime`, a
* contract `arc` segment with its times. Otherwise straight from `a` to
* `b` (`piece` null), and the course of the DISPLAYED motion blends the
* time-interpolated reported track toward the chord by `blend`: the chord
* is only trustworthy when the segment covers real ground (at hover its
* direction is GPS jitter; on a slow tight turn it STEPS the whole
@@ -136,43 +182,59 @@ export function aircraftMotionRegime(
result,
{ cachedGroundFloor } = {},
) {
for (let i = history.length - 1; i >= 1; i--) {
const a = history[i - 1];
const b = history[i];
// A synthetic fix a later report superseded is not on the path: the
// contact is drawn report to report, as its trail is.
let report = history.length - 1;
while (report >= 0 && isSyntheticFix(history[report])) report--;
let b = null;
for (let i = history.length - 1; i >= 0; i--) {
const a = history[i];
if (i < report && isSyntheticFix(a)) continue;
const pairB = b;
b = a;
if (!pairB) continue;
if (
!julianLessThanOrEquals(a.time, renderTime) ||
!julianLessThanOrEquals(renderTime, b.time)
!julianLessThanOrEquals(renderTime, pairB.time)
)
continue;
const span = secondsDifference(b.time, a.time);
const chordLenM = distance(a.position, b.position);
const span = secondsDifference(pairB.time, a.time);
const chordLenM = distance(a.position, pairB.position);
const speed =
span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0;
const fallbackTrack = (info && info[fields.track]) || 0;
const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack;
const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed);
const curve = span > 0 ? historyCurve(a, pairB) : null;
result.kind = 'between';
result.a = a;
result.b = b;
result.b = pairB;
result.piece = curve
? curvePieceAt(curve, julianToEpochMs(renderTime))
: null;
result.span = span;
result.speed = speed;
result.trackFrom = trackFrom;
result.trackTo = Number.isFinite(b.track) ? b.track : trackFrom;
result.trackTo = Number.isFinite(pairB.track) ? pairB.track : trackFrom;
result.chordCourse =
blend > 0 ? courseBetweenCartesians(a.position, b.position) : null;
blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null;
result.blend = blend;
return result;
}
const newest = history[history.length - 1];
const warming = julianLessThan(renderTime, history[0].time);
result.kind = 'fix';
result.piece = null;
result.fix = warming ? history[0] : newest;
result.speed = fixSpeedMps(result.fix, info, fields);
result.heading = fixTrackDeg(result.fix, info, fields);
result.turnRateDps = (info && info.turnRateDps) || 0;
// Past the newest report it flies straight on along its course: a turn
// rate averaged over earlier reports outlives the turn it measured, and
// coasting on it put contacts kilometres off a straight path.
result.turnRateDps = 0;
result.minDt = -60;
// A warm-up ends when real time reaches the oldest fix; a single fix keeps
// coasting forward on the same arc.
// coasting forward on the same line.
result.maxDt =
warming && history.length > 1
? 0
+164
View File
@@ -0,0 +1,164 @@
/**
* @module data/displayDelay
* @description How far behind real time a live aircraft feed is drawn.
*
* Contacts are drawn at `now − delay` so that, at the time drawn, every
* contact has a report on both sides and is placed between two real reports
* instead of dead reckoned past its newest one. The delay has to cover how
* late the feed really is: a feed whose reports arrive 90 s old every 30 s
* needs about two minutes, a fresh one about half a minute.
*
* Each time a contact's report moves on, the feed's lag is how long the
* display had to wait for it: its receipt time less the contact's previous
* report time (lateness, the gap between reports and the wait for the next
* poll together). The delay aimed at is the 90th percentile of the newest 256
* lags plus 5 s, within the layer's floor and a five-minute cap. Before a
* feed has given 16 lags, its first reports stand in: their age plus one poll
* interval.
*
* The delay drawn with moves toward that aim at a bounded rate, rising by at
* most 0.2 s and falling by at most 0.05 s per second, so every contact
* slows or speeds up a little rather than the whole fleet jumping; an aim
* within 2 s of where it is leaves it there. Until a layer has drawn a
* contact, it takes its aim at once.
*/
/** @constant {number} Percentile of the recent lags the delay covers. */
export const DISPLAY_DELAY_RANK = 0.9;
/** @constant {number} How many recent lags the percentile is taken over. */
export const DISPLAY_DELAY_LAGS = 256;
/** @constant {number} Lags before they, rather than first reports, set the aim. */
export const DISPLAY_DELAY_MIN_LAGS = 16;
/** @constant {number} Added to the percentile for jitter (ms). */
export const DISPLAY_DELAY_MARGIN_MS = 5_000;
/** @constant {number} The longest delay (ms). */
export const DISPLAY_DELAY_CAP_MS = 300_000;
/** @constant {number} Delay gained per unit of real time, at most. */
export const DISPLAY_DELAY_RISE = 0.2;
/** @constant {number} Delay shed per unit of real time, at most. */
export const DISPLAY_DELAY_FALL = 0.05;
/** @constant {number} An aim this close (ms) to the delay leaves it be. */
export const DISPLAY_DELAY_DEADBAND_MS = 2_000;
function createWindow(capacity) {
return { values: new Float64Array(capacity), count: 0, cursor: 0 };
}
function add(window, value) {
if (!Number.isFinite(value) || value < 0) return;
window.values[window.cursor] = value;
window.cursor = (window.cursor + 1) % window.values.length;
window.count = Math.min(window.count + 1, window.values.length);
}
function percentile(window, rank) {
const sorted = window.values.slice(0, window.count).sort();
return sorted[Math.max(0, Math.ceil(sorted.length * rank) - 1)];
}
/**
* One live feed's display delay.
* @param {object} options
* @param {number} options.floorMs The shortest delay (ms), and where it starts.
* @param {number} options.pollMs How often the feed is asked (ms).
* @param {number} [options.capMs] The longest delay (ms).
*/
export function createDisplayDelay({
floorMs,
pollMs,
capMs = DISPLAY_DELAY_CAP_MS,
}) {
const lags = createWindow(DISPLAY_DELAY_LAGS);
const firstAges = createWindow(DISPLAY_DELAY_LAGS);
let aimMs = floorMs;
let fromMs = floorMs;
let fromAtMs = NaN;
let currentMs = floorMs;
const clamp = (ms) => Math.max(floorMs, Math.min(capMs, ms));
/** The delay at `nowMs` on its way from `fromMs` toward the aim. */
function delayAt(nowMs) {
if (!Number.isFinite(fromAtMs)) return fromMs;
const elapsed = Math.max(0, nowMs - fromAtMs);
const change = Math.max(
-DISPLAY_DELAY_FALL * elapsed,
Math.min(DISPLAY_DELAY_RISE * elapsed, aimMs - fromMs),
);
return fromMs + change;
}
return {
/** The delay contacts are drawn with now (whole ms), as last stepped. */
get currentMs() {
return currentMs;
},
/** The delay it is moving toward (ms). */
get aimMs() {
return aimMs;
},
/** Lags seen so far, up to the window. */
get lagCount() {
return lags.count;
},
/**
* A contact's report received at `receiptMs`: its time, and the
* contact's previous report time (none for a contact seen first).
*/
noteReport(receiptMs, reportMs, previousReportMs) {
if (Number.isFinite(previousReportMs)) {
if (reportMs > previousReportMs)
add(lags, receiptMs - previousReportMs);
} else if (Number.isFinite(reportMs))
add(firstAges, receiptMs - reportMs);
},
/**
* Aim again after a delivery. `jump`: nothing is drawn yet, so the delay
* takes the aim at once.
* @param {number} nowMs
* @param {{jump?: boolean}} [options]
* @returns {number} The delay now (whole ms).
*/
settle(nowMs, { jump = false } = {}) {
let next = aimMs;
if (lags.count >= DISPLAY_DELAY_MIN_LAGS)
next = clamp(
percentile(lags, DISPLAY_DELAY_RANK) + DISPLAY_DELAY_MARGIN_MS,
);
else if (firstAges.count)
next = clamp(
percentile(firstAges, DISPLAY_DELAY_RANK) +
pollMs +
DISPLAY_DELAY_MARGIN_MS,
);
const now = delayAt(nowMs);
fromMs = jump ? next : now;
fromAtMs = nowMs;
// An aim this close leaves the delay where it is.
aimMs =
Math.abs(next - now) < DISPLAY_DELAY_DEADBAND_MS && !jump ? now : next;
currentMs = Math.round(fromMs);
return currentMs;
},
/**
* Move the delay on to `nowMs`: what the contacts are drawn with until
* the next step.
* @returns {number} Whole ms.
*/
step(nowMs) {
currentMs = Math.round(delayAt(nowMs));
return currentMs;
},
/** Forget the feed: back to the floor, nothing learned. */
reset() {
lags.count = lags.cursor = 0;
firstAges.count = firstAges.cursor = 0;
aimMs = fromMs = currentMs = floorMs;
fromAtMs = NaN;
},
};
}
+170
View File
@@ -0,0 +1,170 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createDisplayDelay,
DISPLAY_DELAY_CAP_MS,
DISPLAY_DELAY_DEADBAND_MS,
DISPLAY_DELAY_FALL,
DISPLAY_DELAY_LAGS,
DISPLAY_DELAY_MARGIN_MS,
DISPLAY_DELAY_MIN_LAGS,
DISPLAY_DELAY_RISE,
} from './displayDelay.js';
// A live feed is drawn far enough behind real time that every contact has a
// report on both sides of the time drawn.
const SEC = 1000;
const FLOOR = 30 * SEC;
const POLL = 30 * SEC;
/**
* A feed polled every 30 s whose reports arrive `ageMs` old, one new report
* per contact per poll: each lag is the age plus the poll interval.
*/
function feed(delay, { contacts = 20, polls = 4, ageMs, startMs = 0 }) {
let now = startMs;
for (let p = 0; p < polls; p++) {
now += POLL;
for (let c = 0; c < contacts; c++) {
const reportMs = now - ageMs - c * 10;
delay.noteReport(now, reportMs, reportMs - POLL);
}
}
return now;
}
test('the aim is the 90th percentile of recent lags plus the margin', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
assert.ok(delay.lagCount >= DISPLAY_DELAY_MIN_LAGS);
delay.settle(now, { jump: true });
// Lags 120 s (plus the spread of 0–190 ms): 125 s and a little.
assert.ok(
Math.abs(delay.currentMs - (120 * SEC + DISPLAY_DELAY_MARGIN_MS)) < 300,
`${delay.currentMs}`,
);
});
test('a fresh feed stays at the floor', () => {
// Polled every 10 s, reports 2 s old: lags of 12 s, aim 17 s, under the floor.
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: 10 * SEC });
for (let i = 1; i <= 40; i++)
delay.noteReport(
i * 10 * SEC,
i * 10 * SEC - 2 * SEC,
(i - 1) * 10 * SEC - 2 * SEC,
);
assert.equal(delay.settle(400 * SEC, { jump: true }), FLOOR);
});
test('the delay never passes the cap', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 20 * 60 * SEC });
assert.equal(delay.settle(now, { jump: true }), DISPLAY_DELAY_CAP_MS);
});
test('before enough lags, first reports stand in: their age plus a poll', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
for (let c = 0; c < 10; c++)
delay.noteReport(1_000 * SEC, 1_000 * SEC - 90 * SEC);
assert.equal(delay.lagCount, 0);
assert.equal(
delay.settle(1_000 * SEC, { jump: true }),
90 * SEC + POLL + DISPLAY_DELAY_MARGIN_MS,
);
});
test('a report that did not move on gives no lag', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
delay.noteReport(100 * SEC, 50 * SEC, 50 * SEC);
delay.noteReport(100 * SEC, 40 * SEC, 50 * SEC);
assert.equal(delay.lagCount, 0);
});
test('only the newest lags count', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, {
ageMs: 200 * SEC,
contacts: DISPLAY_DELAY_LAGS,
polls: 1,
});
now = feed(delay, {
ageMs: 10 * SEC,
contacts: DISPLAY_DELAY_LAGS,
polls: 1,
startMs: now,
});
assert.ok(delay.settle(now, { jump: true }) < 50 * SEC);
});
test('the delay rises toward its aim at most 0.2 s per second, then holds there', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
assert.equal(delay.settle(now), FLOOR, 'not jumped once drawing');
const aim = delay.aimMs;
let prev = delay.currentMs;
for (let s = 1; s <= 600; s++) {
const d = delay.step(now + s * SEC);
assert.ok(d - prev <= DISPLAY_DELAY_RISE * SEC + 1, `rose ${d - prev} ms`);
assert.ok(d >= prev);
prev = d;
}
assert.equal(prev, aim);
// Rising by 0.2 s a second, the time drawn still moves forward at 0.8×.
assert.ok(DISPLAY_DELAY_RISE < 1);
});
test('the delay falls at most 0.05 s per second', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
const high = delay.currentMs;
now = feed(delay, {
ageMs: 0,
polls: 13,
startMs: now,
});
delay.settle(now);
assert.ok(Math.abs(delay.aimMs - 35 * SEC) < 300, `${delay.aimMs}`);
const later = delay.step(now + 100 * SEC);
assert.equal(high - later, DISPLAY_DELAY_FALL * 100 * SEC);
});
test('an aim within the deadband leaves the delay where it is', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
const was = delay.currentMs;
now = feed(delay, {
ageMs: 90 * SEC + DISPLAY_DELAY_DEADBAND_MS / 2,
polls: 13,
startMs: now,
});
delay.settle(now);
assert.equal(delay.aimMs, was);
assert.equal(delay.step(now + 60 * SEC), was);
});
test('a delivery mid-slew carries on from where the delay is', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now);
const mid = delay.step(now + 100 * SEC);
now = feed(delay, {
ageMs: 90 * SEC,
polls: 1,
startMs: now + 100 * SEC - POLL,
});
assert.equal(delay.settle(now), mid);
});
test('reset forgets the feed', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
delay.reset();
assert.equal(delay.currentMs, FLOOR);
assert.equal(delay.lagCount, 0);
assert.equal(delay.settle(now, { jump: true }), FLOOR);
});
+310
View File
@@ -0,0 +1,310 @@
/**
* @module data/fixCurve
* @description The path an aircraft is drawn along between two of its
* reports, and the trail drawn behind it: a smooth curve that passes through
* both reports and leaves each one along its reported track.
*
* The curve is a biarc: two constant-rate turns, each a renderer `arc`
* motion segment (`render/contract/draw.d.ts`), joined where they share a
* course. So the renderer draws exactly this curve, the app reads it back with
* `render/motion/iconMotion`, and the trail samples the same segments: the
* icon always sits on its own trail. Speed is constant between the two
* reports, height changes evenly with time.
*
* The straight line between the reports is drawn instead (no curve) when
* either report has no track, the pair is slower than 40 m/s (taxiing,
* hovering, holding still), or a track points more than 75° off the line
* between them: the reports do not describe one smooth turn.
*
* Each segment runs on for two seconds past its end along the same turn, so
* when the next segment comes a little late the renderer keeps the icon moving
* instead of holding it.
*/
import { eastNorthUp } from '../geo/frames.js';
import { motionCourse, motionPosition } from '../render/motion/iconMotion.js';
import { norm180, norm360 } from '../geo/vector.js';
/** @constant {number} Pairs slower than this (m/s) are joined straight. */
export const CURVE_MIN_SPEED_MPS = 40;
/** @constant {number} A track further than this (°) off the chord is joined straight. */
export const CURVE_MAX_TRACK_OFF_DEG = 75;
/** @constant {number} How long (s) a segment runs on past its end. */
export const CURVE_RUN_ON_S = 2;
/** @constant {number} Turn (°) between points a trail samples along a curve. */
export const CURVE_POINT_STEP_DEG = 1;
const DEG = Math.PI / 180;
/** Turn rates under this (rad/s) fly straight, as `iconMotion` draws them. */
const STRAIGHT_BELOW_RAD_PER_S = 1e-4;
function sinc(x) {
return Math.abs(x) < 1e-4 ? 1 - (x * x) / 6 : Math.sin(x) / x;
}
const dot3 = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const sub3 = (a, b) => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
/** A course (degrees) at `from`'s frame, read in `to`'s frame. */
function courseIn(courseDeg, fromFrame, toFrame) {
const s = Math.sin(courseDeg * DEG);
const c = Math.cos(courseDeg * DEG);
const t = {
x: s * fromFrame.x.x + c * fromFrame.y.x,
y: s * fromFrame.x.y + c * fromFrame.y.y,
z: s * fromFrame.x.z + c * fromFrame.y.z,
};
return Math.atan2(dot3(t, toFrame.x), dot3(t, toFrame.y)) / DEG;
}
/**
* A constant-rate turn from `from` at `t0` setting off on `courseDeg`, that
* reaches `to` at `t1` (epoch ms): an `arc` segment, straight when the turn
* is too slow to draw as one.
* @returns {{segment: object, endCourseDeg: number}}
*/
function arcThrough(from, frame, t0, t1, courseDeg, to) {
const d = sub3(to, from);
const e = dot3(d, frame.x);
const n = dot3(d, frame.y);
const u = dot3(d, frame.z);
const seconds = (t1 - t0) / 1000;
const chord = Math.hypot(e, n);
const bearing = Math.atan2(e, n) / DEG;
let turn = 2 * norm180(bearing - courseDeg);
let track = courseDeg;
if (Math.abs((turn * DEG) / seconds) < STRAIGHT_BELOW_RAD_PER_S) {
turn = 0;
track = bearing;
}
const length = chord / sinc((turn * DEG) / 2);
return {
segment: {
kind: 'arc',
fix: { x: from.x, y: from.y, z: from.z },
t0,
minDtS: 0,
maxDtS: seconds + CURVE_RUN_ON_S,
speedMps: length / seconds,
trackDeg: norm360(track),
turnRateDps: turn / seconds,
climbMps: u / seconds,
},
endCourseDeg: track + turn,
};
}
/**
* A straight `arc` segment from `from` at `t0` that reaches `to` at `t1`
* (epoch ms) and runs on past it for CURVE_RUN_ON_S.
*/
export function straightSegment(from, t0, t1, to) {
const frame = eastNorthUp(from);
const d = sub3(to, from);
const bearing = Math.atan2(dot3(d, frame.x), dot3(d, frame.y)) / DEG;
return arcThrough(from, frame, t0, t1, bearing, to).segment;
}
/**
* The curve between two reports, or null to join them straight.
* @param {{x: number, y: number, z: number}} fromPos The earlier report (ECEF).
* @param {number} fromMs Its time, epoch ms.
* @param {number} fromTrackDeg Its reported track.
* @param {{x: number, y: number, z: number}} toPos The later report.
* @param {number} toMs
* @param {number} toTrackDeg
* @returns {{pieces: Array<{segment: object, t0: number, t1: number}>}|null}
* One or two pieces in time order, together running from `fromMs` to
* `toMs`; each `segment` is a contract `arc` motion segment.
*/
export function fixCurve(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
) {
if (!Number.isFinite(fromTrackDeg) || !Number.isFinite(toTrackDeg))
return null;
if (!(toMs > fromMs) || !fromPos || !toPos) return null;
const seconds = (toMs - fromMs) / 1000;
const frame = eastNorthUp(fromPos);
const d = sub3(toPos, fromPos);
const e = dot3(d, frame.x);
const n = dot3(d, frame.y);
const u = dot3(d, frame.z);
const chord = Math.hypot(e, n);
if (!(chord / seconds >= CURVE_MIN_SPEED_MPS)) return null;
const toFrame = eastNorthUp(toPos);
const startDeg = fromTrackDeg;
// The later report's track, read in the earlier report's frame.
const endDeg = courseIn(toTrackDeg, toFrame, frame);
const bearing = Math.atan2(e, n) / DEG;
if (
Math.abs(norm180(startDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG ||
Math.abs(norm180(endDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG
)
return null;
// The biarc's join with equal tangent lengths: p0 = 0, p1 = (e, n),
// unit tangents t0 and t1.
const t0x = Math.sin(startDeg * DEG);
const t0y = Math.cos(startDeg * DEG);
const t1x = Math.sin(endDeg * DEG);
const t1y = Math.cos(endDeg * DEG);
const vv = e * e + n * n;
const vt = e * (t0x + t1x) + n * (t0y + t1y);
const tt = t0x * t1x + t0y * t1y;
const denom = 2 * (1 - tt);
const reach =
denom < 1e-9
? vv / (4 * (e * t1x + n * t1y))
: (-vt + Math.sqrt(vt * vt + denom * vv)) / denom;
if (!(reach > 0) || !Number.isFinite(reach)) return null;
const jx = (reach * t0x + e - reach * t1x) / 2;
const jy = (reach * t0y + n - reach * t1y) / 2;
// Each arc's length from its chord and turn, to share the time by.
const arcLength = (cx, cy, courseDeg) => {
const c = Math.hypot(cx, cy);
const turn = 2 * norm180(Math.atan2(cx, cy) / DEG - courseDeg);
return { length: c / sinc((turn * DEG) / 2), turn };
};
const first = arcLength(jx, jy, startDeg);
const second = arcLength(e - jx, n - jy, startDeg + first.turn);
const total = first.length + second.length;
if (!(total > 0)) return null;
// One arc where a piece would be under a metre.
if (first.length < 1 || second.length < 1) {
const only = arcThrough(fromPos, frame, fromMs, toMs, startDeg, toPos);
return { pieces: [{ segment: only.segment, t0: fromMs, t1: toMs }] };
}
const joinMs = fromMs + (toMs - fromMs) * (first.length / total);
const share = first.length / total;
const join = {
x: fromPos.x + frame.x.x * jx + frame.y.x * jy + frame.z.x * u * share,
y: fromPos.y + frame.x.y * jx + frame.y.y * jy + frame.z.y * u * share,
z: fromPos.z + frame.x.z * jx + frame.y.z * jy + frame.z.z * u * share,
};
const a = arcThrough(fromPos, frame, fromMs, joinMs, startDeg, join);
// The second arc starts exactly where the first is drawn to end.
const joined = motionPosition(a.segment, null, joinMs);
const joinFrame = eastNorthUp(joined);
const b = arcThrough(
joined,
joinFrame,
joinMs,
toMs,
courseIn(a.endCourseDeg, frame, joinFrame),
toPos,
);
return {
pieces: [
{ segment: a.segment, t0: fromMs, t1: joinMs },
{ segment: b.segment, t0: joinMs, t1: toMs },
],
};
}
const cache = new WeakMap();
/**
* `fixCurve` for two report objects that keep their position object, kept
* per earlier report's position until either report changes.
*/
export function fixCurveCached(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
) {
if (!fromPos || typeof fromPos !== 'object') return null;
const hit = cache.get(fromPos);
if (
hit &&
hit.toPos === toPos &&
hit.fromMs === fromMs &&
hit.toMs === toMs &&
hit.fromTrackDeg === fromTrackDeg &&
hit.toTrackDeg === toTrackDeg &&
hit.fx === fromPos.x &&
hit.fy === fromPos.y &&
hit.fz === fromPos.z &&
hit.tx === toPos.x &&
hit.ty === toPos.y &&
hit.tz === toPos.z
)
return hit.curve;
const curve = fixCurve(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
);
cache.set(fromPos, {
toPos,
fromMs,
toMs,
fromTrackDeg,
toTrackDeg,
fx: fromPos.x,
fy: fromPos.y,
fz: fromPos.z,
tx: toPos?.x,
ty: toPos?.y,
tz: toPos?.z,
curve,
});
return curve;
}
/** The piece of `curve` drawn at `tMs` (the last one past its end). */
export function curvePieceAt(curve, tMs) {
const pieces = curve.pieces;
for (let i = 0; i < pieces.length - 1; i++)
if (tMs < pieces[i].t1) return pieces[i];
return pieces[pieces.length - 1];
}
/** Where the curve puts the aircraft at `tMs`, and its course. */
export function curvePositionAt(curve, tMs) {
const piece = curvePieceAt(curve, tMs);
const t = Math.min(tMs, piece.t1);
return {
position: motionPosition(piece.segment, null, t),
courseDeg: motionCourse(piece.segment, undefined, t),
};
}
/**
* Points along the curve from `fromMs` to `toMs` (exclusive of both ends),
* one at least every CURVE_POINT_STEP_DEG of turn, so the line drawn
* through them stays within a couple of metres of the curve.
* @returns {Array<{x: number, y: number, z: number}>}
*/
export function curvePoints(curve, fromMs, toMs) {
const out = [];
for (const piece of curve.pieces) {
const start = Math.max(fromMs, piece.t0);
const end = Math.min(toMs, piece.t1);
if (!(end > start)) continue;
const seconds = (end - start) / 1000;
const turned = Math.abs(piece.segment.turnRateDps * seconds);
const steps = Math.max(1, Math.ceil(turned / CURVE_POINT_STEP_DEG));
// The piece's start, unless it is the curve's own start.
if (start > fromMs) out.push(motionPosition(piece.segment, null, start));
for (let k = 1; k < steps; k++)
out.push(
motionPosition(
piece.segment,
null,
start + ((end - start) * k) / steps,
),
);
}
return out;
}
+141
View File
@@ -0,0 +1,141 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
CURVE_RUN_ON_S,
curvePieceAt,
curvePoints,
curvePositionAt,
fixCurve,
straightSegment,
} from './fixCurve.js';
import { motionPosition } from '../render/motion/iconMotion.js';
// Between two reports an aircraft is drawn along a curve through both that
// leaves each along its reported track, made of contract `arc` segments.
const SEC = 1000;
const T0 = Date.UTC(2026, 10, 9, 12);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Cartesian3.fromDegrees(-122.4, 37.6, 0),
);
const at = (e, n, u = 3_000) =>
Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(e, n, u),
new Cesium.Cartesian3(),
);
const near = (a, b, m, label) => {
const d = Cesium.Cartesian3.distance(a, b);
assert.ok(d < m, `${label}: ${d.toFixed(2)} m`);
};
const angleDiff = (a, b) => Math.abs(((a - b + 540) % 360) - 180);
// A 100 m/s left turn on a 2 km circle centred at (0, R), heading east at
// the origin.
const R = 2_000;
const W = 100 / R;
const circle = (t) => at(R * Math.sin(W * t), R - R * Math.cos(W * t));
const trackAt = (t) => (90 - (W * t * 180) / Math.PI + 360) % 360;
test('the curve passes through both reports and leaves each along its track', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
assert.ok(curve);
near(curvePositionAt(curve, T0).position, circle(0), 0.01, 'start');
near(curvePositionAt(curve, T0 + 15 * SEC).position, circle(15), 0.01, 'end');
assert.ok(angleDiff(curvePositionAt(curve, T0).courseDeg, trackAt(0)) < 0.1);
assert.ok(
angleDiff(curvePositionAt(curve, T0 + 15 * SEC).courseDeg, trackAt(15)) <
0.1,
);
// A true turn: the curve is the turn, within a couple of metres.
for (let s = 0; s <= 15; s += 0.5)
near(curvePositionAt(curve, T0 + s * SEC).position, circle(s), 3, `${s} s`);
});
test('its pieces are contiguous arc segments in time order', () => {
// Tracks that need an S: the first turn and the second do not agree.
const curve = fixCurve(at(0, 0), T0, 45, at(3_000, 0), T0 + 30 * SEC, 45);
assert.ok(curve);
assert.equal(curve.pieces.length, 2);
assert.equal(curve.pieces[0].t0, T0);
assert.equal(curve.pieces.at(-1).t1, T0 + 30 * SEC);
for (const piece of curve.pieces) assert.equal(piece.segment.kind, 'arc');
const [a, b] = curve.pieces;
assert.equal(a.t1, b.t0);
near(
motionPosition(a.segment, null, a.t1),
motionPosition(b.segment, null, b.t0),
0.01,
'join',
);
assert.equal(curvePieceAt(curve, a.t1 - 1), a);
assert.equal(curvePieceAt(curve, a.t1), b);
assert.equal(curvePieceAt(curve, T0 + 60 * SEC), b);
});
test('each segment runs on past its end rather than holding', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
const last = curve.pieces.at(-1);
const end = motionPosition(last.segment, null, last.t1);
const later = motionPosition(
last.segment,
null,
last.t1 + CURVE_RUN_ON_S * SEC,
);
near(later, circle(15 + CURVE_RUN_ON_S), 3, 'run on');
assert.ok(Cesium.Cartesian3.distance(end, later) > 150);
});
test('no curve without tracks, below 40 m/s, or with a track far off the line', () => {
const a = at(0, 0);
const b = at(1_500, 0);
assert.equal(fixCurve(a, T0, undefined, b, T0 + 15 * SEC, 90), null);
assert.equal(fixCurve(a, T0, 90, b, T0 + 60 * SEC, 90), null, 'slow');
assert.equal(fixCurve(a, T0, 180, b, T0 + 15 * SEC, 90), null, 'off line');
assert.equal(fixCurve(a, T0, 90, b, T0, 90), null, 'no time between');
});
test('trail points follow the curve, exclusive of both ends, a degree of turn apart', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
const points = curvePoints(curve, T0, T0 + 15 * SEC);
// 15 s at 2.86°/s: about 43° of turn.
assert.ok(points.length >= 42 && points.length <= 46, `${points.length}`);
for (const p of points)
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 3,
'off the turn',
);
assert.ok(Cesium.Cartesian3.distance(points[0], circle(0)) > 1);
assert.ok(Cesium.Cartesian3.distance(points.at(-1), circle(15)) > 1);
});
test('a straight segment reaches its end at its time and runs on along the same line', () => {
const a = at(0, 0);
const b = at(1_000, 0);
const segment = straightSegment(a, T0, T0 + 10 * SEC, b);
near(motionPosition(segment, null, T0), a, 0.01, 'start');
near(motionPosition(segment, null, T0 + 5 * SEC), at(500, 0), 1, 'middle');
near(motionPosition(segment, null, T0 + 10 * SEC), b, 0.01, 'end');
});
+33
View File
@@ -220,6 +220,39 @@ export function trailHeadStart(start, anchor, center, radiusM, result) {
return result;
}
/**
* The live head line from the last trail report through `points` (on the
* way to the aircraft) to `head`, as drawn: points inside the model's
* envelope are left out, and the link into the model slides as
* `trailHeadStart` decides (nothing on a contact that has not moved).
* @param {{x:number,y:number,z:number}} start The last body report.
* @param {Array<{x:number,y:number,z:number}>} points Between it and the head.
* @param {{x:number,y:number,z:number}} head The aircraft's trail anchor.
* @param {{x:number,y:number,z:number}|null} center Model origin, or null.
* @param {number|null} radiusM Rendered bounding radius.
* @param {{x:number,y:number,z:number}} result Scratch for the slid start.
* @returns {Array<{x:number,y:number,z:number}>} Empty when nothing is drawn.
*/
export function trailHeadLine(start, points, head, center, radiusM, result) {
const outside = (p) =>
!center ||
!(radiusM > 0) ||
Math.hypot(p.x - center.x, p.y - center.y, p.z - center.z) >= radiusM;
const line = [start];
for (const p of points) if (outside(p)) line.push(p);
// On a contact that has not moved the last link 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 START is what
// slides, from nothing on a parked contact out to the whole link once it
// has cleared its own envelope.
const from = trailHeadStart(line.pop(), head, center, radiusM, result);
if (!from)
return line.length ? [...line, { x: head.x, y: head.y, z: head.z }] : [];
line.push(from === result ? { x: from.x, y: from.y, z: from.z } : from);
line.push({ x: head.x, y: head.y, z: head.z });
return line;
}
/**
* Transform a model-local visual centre into world coordinates without
* allocating. `modelMatrix` continues to own the model origin (including
+28
View File
@@ -621,3 +621,31 @@ export function synthesizeForwardKinematicsFix(newest, next = {}) {
track: Number.isFinite(next.track) ? next.track : previousTrack,
};
}
/** @constant {number} The shortest ease (ms) from where a contact was drawn onto where a new report puts it. */
export const RECOVER_MIN_MS = 3_000;
/** @constant {number} An ease never moves a contact faster than its speed by more than this share... */
export const RECOVER_MAX_EXTRA_SPEED = 0.3;
/** @constant {number} ...unless that would take longer than this (ms). */
export const RECOVER_MAX_MS = 20_000;
/** @constant {number} Farther than this (m) from where a new report puts it, a contact jumps there. */
export const RECOVER_SNAP_M = 5_000;
/** @constant {number} Closer than this (m), it is simply drawn there. */
export const RECOVER_MIN_M = 5;
/**
* How long (ms) a contact drawn `errorM` off where a new report puts it eases
* onto that place: at least RECOVER_MIN_MS, and long enough that the ease
* adds at most RECOVER_MAX_EXTRA_SPEED of its speed, so it never looks like
* a jump, up to RECOVER_MAX_MS.
* @param {number} errorM
* @param {number} speedMps
* @returns {number}
*/
export function recoveryMs(errorM, speedMps) {
const extraMps = RECOVER_MAX_EXTRA_SPEED * Math.max(speedMps || 0, 10);
return Math.min(
RECOVER_MAX_MS,
Math.max(RECOVER_MIN_MS, (errorM / extraMps) * 1000),
);
}
+79 -355
View File
@@ -1,12 +1,15 @@
/**
* @module trailContinuity
* @description Where a tracked aircraft's trail lifts the pen.
* @description A tracked aircraft's trail, and where it lifts the pen.
*
* A trail is a chronological list of fixes `{position, timeMs, nullAltitude,
* breakBefore, drawn}`: reports, and (`drawn`) points where the tracked icon
* was drawn between them. Between two consecutive fixes that are not one path, a new
* segment starts and nothing is drawn between them: no dashes, no arcs.
* Nothing is dropped except the oldest fixes past the layer's point limit.
* A trail is a chronological list of reports `{position, timeMs, track,
* nullAltitude, breakBefore}`. Between two consecutive reports that are one
* path, the line follows the curve the aircraft is drawn along between them
* (`data/fixCurve`), so the icon always sits on its own trail and no guess
* about where it went between reports is ever kept: a late report can never
* leave a kink. Between two that are not one path, a new segment starts and
* nothing is drawn between them: no dashes, no arcs. Nothing is dropped
* except the oldest reports past the layer's point limit.
*
* Two points are not one path when time does not advance, when the gap is
* longer than 48 minutes (a coverage hole or a separate flight), when the
@@ -20,16 +23,8 @@
* Civil and military flight tracking share these rules.
*/
import { julianToEpochMs } from '../geo/julian.js';
import {
cross,
distance,
dot,
magnitude,
normalize,
scale,
sub,
toRadians,
} from '../geo/vector.js';
import { cross, distance, dot, magnitude, normalize } from '../geo/vector.js';
import { curvePoints, fixCurveCached } from './fixCurve.js';
/** @constant {number} A gap longer than this is a coverage hole or a separate flight. */
export const TRAIL_CONTINUITY_MAX_GAP_MS = 48 * 60_000;
@@ -115,10 +110,6 @@ export function trailDistanceM(a, b) {
*/
export function trailFixBreaks(prev, next) {
if (!prev || prev.nullAltitude || next.nullAltitude) return true;
// A recorded point is where the icon was drawn; the speed between it and a
// report it was eased onto is not a flight speed, so only the gap counts.
if (prev.drawn || next.drawn)
return Math.abs(next.timeMs - prev.timeMs) > TRAIL_CONTINUITY_MAX_GAP_MS;
return trailPairBreaks(
next.timeMs - prev.timeMs,
trailDistanceM(prev.position, next.position),
@@ -129,19 +120,20 @@ export function trailFixBreaks(prev, next) {
* Build backfill fixes from chronological waypoints. Every waypoint with a
* position is kept. A waypoint without one (no altitude and no known ground)
* is skipped, and the line still breaks there.
* @param {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean}[]} waypoints
* @param {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, track?: number}[]} waypoints
* @returns {{fixes: object[], breakAfter: boolean}} The fixes, and whether the
* line breaks after the last one because trailing waypoints were skipped.
*/
export function trailBackfillFixes(waypoints) {
const fixes = [];
let skipped = false;
for (const { position, timeMs, nullAltitude } of waypoints) {
for (const { position, timeMs, nullAltitude, track } of waypoints) {
if (!position) {
skipped = true;
continue;
}
const fix = { position, timeMs, nullAltitude: !!nullAltitude };
if (Number.isFinite(track)) fix.track = track;
fix.breakBefore = skipped || trailFixBreaks(fixes[fixes.length - 1], fix);
skipped = false;
fixes.push(fix);
@@ -176,7 +168,7 @@ export function trailGroundTransitionBreaks(
* not join it either. A live report that does not say uses the aircraft's
* state now; with no live fix to start after it, the backfill is checked
* against now and left out, so the head never draws that line. Past `maxPoints` the oldest
* recorded points go first, then the oldest reports.
* reports go.
* @param {{fixes: object[], breakAfter: boolean}} backfill
* @param {object[]} live - Live fixes; the first one's break is recomputed.
* @param {number} maxPoints - Point limit across all segments.
@@ -239,50 +231,68 @@ export function trailBodyCount(fixes, displayMs) {
}
/**
* Leave out the newest recorded points that lie inside the aircraft's 3D
* model, so the body never runs through the fuselage; the head then runs
* from the newest point outside the model to the plane. Reports are kept.
* @param {object[]} fixes
* @param {number} count - From `trailBodyCount`.
* @param {{x: number, y: number, z: number}|null} modelCenter - The model's centre, or null
* when no model is the visual.
* @param {number|null} envelopeM - The model's radius (m).
* @returns {number}
*/
export function trailBodyCountOutsideModel(
fixes,
count,
modelCenter,
envelopeM,
) {
if (!modelCenter || !(envelopeM > 0)) return count;
while (
count > 0 &&
fixes[count - 1].drawn &&
distance(fixes[count - 1].position, modelCenter) < envelopeM
)
count -= 1;
return count;
}
/**
* The drawn trail body, split at breaks: the first `count` fixes.
* The drawn trail body, split at breaks: the first `count` reports, each
* pair that is one path joined along its curve (`data/fixCurve`).
* @param {object[]} fixes
* @param {number} count - From `trailBodyCount`.
* @returns {{x: number, y: number, z: number}[][]}
*/
export function trailBodySegments(fixes, count) {
const segments = [];
let prev = null;
for (let i = 0; i < count; i++) {
const fix = fixes[i];
// A live report with no altitude keeps no position; it only breaks the line.
if (!fix.position) continue;
if (fix.breakBefore || !segments.length) segments.push([]);
if (!fix.position) {
prev = null;
continue;
}
if (fix.breakBefore || !segments.length || !prev) segments.push([]);
else {
const curve = trailPairCurve(prev, fix);
if (curve)
segments[segments.length - 1].push(
...curvePoints(curve, prev.timeMs, fix.timeMs),
);
}
segments[segments.length - 1].push(fix.position);
prev = fix;
}
return segments;
}
/** The curve between two consecutive trail reports, or null for a straight line. */
export function trailPairCurve(prev, next) {
return fixCurveCached(
prev.position,
prev.timeMs,
prev.track,
next.position,
next.timeMs,
next.track,
);
}
/**
* The points of the live head between the last body report and the time the
* aircraft is drawn: along the curve to the next report, which the aircraft
* is on its way to, when that pair is one path; none otherwise (the head is
* then a straight line to the aircraft).
* @param {object[]} fixes
* @param {number} count - Body reports, from `trailBodyCount`.
* @param {number} displayMs - Time the aircraft is drawn at.
* @returns {{x: number, y: number, z: number}[]}
*/
export function trailHeadCurvePoints(fixes, count, displayMs) {
const last = fixes[count - 1];
const next = fixes[count];
if (!last?.position || !next?.position || next.breakBefore) return [];
const curve = trailPairCurve(last, next);
if (!curve) return [];
// Exclusive of the display time: the point there is the aircraft's own.
return curvePoints(curve, last.timeMs, displayMs);
}
/**
* Draw body segments. A trail without breaks support draws only the newest
* segment, never a line across a break.
@@ -331,176 +341,13 @@ export function historyFixEpochMs(fix) {
return fix?.time ? julianToEpochMs(fix.time) : NaN;
}
/** @constant {number} The tracked icon's drawn position is recorded at least this often (ms of display time)... */
export const TRAIL_RECORD_STEP_MS = 1_000;
/** @constant {number} ...or whenever it has moved this far (m), whichever comes first. */
export const TRAIL_RECORD_STEP_M = 150;
/** @constant {number} A recorded point is kept only where dropping it would move the line by more than this (m) across the track or in height. */
export const TRAIL_THIN_TOLERANCE_M = 30;
/** @constant {number} A recorded point is kept where dropping it would leave a straight piece longer than this (m), so a long leg still has vertices. */
export const TRAIL_THIN_MAX_SPAN_M = 10_000;
/** @constant {number} A kept point stands in for at most this many dropped positions; past it the point is kept. */
const TRAIL_THIN_MAX_ABSORBED = 512;
/** @constant {number} A recorded point is dropped where the line turns back sharper than this (degrees)... */
export const TRAIL_SPUR_TURN_DEG = 120;
/** @constant {number} ...over a step shorter than this (m). */
export const TRAIL_SPUR_MAX_STEP_M = 500;
/** @constant {number} A recorded point closer than this (m) to the previous one is not kept: the aircraft is holding. */
const TRAIL_RECORD_MIN_STEP_M = 1;
/** Cosine of the turn at `b` on the way a → b → c, or NaN for a zero step. */
function turnCos(a, b, c) {
const u = sub(b, a);
const v = sub(c, b);
const lu = magnitude(u);
const lv = magnitude(v);
if (!(lu > 0 && lv > 0)) return NaN;
return dot(u, v) / (lu * lv);
}
const SPUR_COS = Math.cos(toRadians(TRAIL_SPUR_TURN_DEG));
/** Whether entry `i` and its neighbours are one drawn piece of line. */
function joinedAt(fixes, i) {
const a = fixes[i - 1];
const b = fixes[i];
const c = fixes[i + 1];
return (
a?.position &&
b?.position &&
c?.position &&
!b.breakBefore &&
!c.breakBefore
);
}
/** Whether the line turns back on itself at entry `i` over a short step. */
function spurAt(fixes, i) {
if (!joinedAt(fixes, i)) return false;
const a = fixes[i - 1].position;
const b = fixes[i].position;
const c = fixes[i + 1].position;
if (Math.min(distance(a, b), distance(b, c)) > TRAIL_SPUR_MAX_STEP_M)
return false;
return turnCos(a, b, c) < SPUR_COS;
}
/** Remove entry `i` and re-judge the break before the entry that takes its place. */
function removeAt(fixes, i) {
fixes.splice(i, 1);
if (i < fixes.length)
fixes[i].breakBefore = trailFixBreaks(fixes[i - 1], fixes[i]);
}
/**
* Keep the point limit: drop the oldest recorded point first, and the oldest
* report only when no recorded point is left.
* @param {object[]} fixes - The trail, mutated.
* @param {number} maxPoints
* @returns {object[]} `fixes`.
*/
/** Keep the point limit: the oldest reports go first. */
function keepTrailLimit(fixes, maxPoints) {
let excess = fixes.length - maxPoints;
if (excess <= 0) return fixes;
for (let i = 0; i < fixes.length && excess > 0;) {
if (fixes[i].drawn) {
removeAt(fixes, i);
excess -= 1;
} else i += 1;
}
const excess = fixes.length - maxPoints;
if (excess > 0) fixes.splice(0, excess);
return fixes;
}
/** Whether `p` lies within the thinning tolerance of segment a → b, across the track and in height. */
function nearSegment(p, a, b) {
const ab = sub(b, a);
const ap = sub(p, a);
const len2 = dot(ab, ab);
const t = len2 > 0 ? Math.max(0, Math.min(1, dot(ap, ab) / len2)) : 0;
const off = sub(ap, scale(ab, t));
const vertical = dot(off, normalize(p));
const across = Math.sqrt(Math.max(0, dot(off, off) - vertical * vertical));
return (
Math.abs(vertical) <= TRAIL_THIN_TOLERANCE_M &&
across <= TRAIL_THIN_TOLERANCE_M
);
}
/**
* Drop recorded point `i` when the line without it stays within the
* tolerance of every position it stood for, and the straight piece left is
* no longer than TRAIL_THIN_MAX_SPAN_M. The positions it stood for go on to
* the next entry. Reports are never dropped.
* @returns {boolean} Whether it was dropped.
*/
function thinAt(fixes, i) {
const entry = fixes[i];
if (!entry?.drawn || entry.sealed || !joinedAt(fixes, i)) return false;
const a = fixes[i - 1].position;
const next = fixes[i + 1];
if (next.sealed) return false;
const b = next.position;
if (distance(a, b) > TRAIL_THIN_MAX_SPAN_M) return false;
const stood = entry.absorbed ?? [];
const nextStood = next.absorbed ?? [];
if (stood.length + nextStood.length + 1 > TRAIL_THIN_MAX_ABSORBED)
return false;
if (!nearSegment(entry.position, a, b)) return false;
for (const p of stood) if (!nearSegment(p.position, a, b)) return false;
for (const p of nextStood) if (!nearSegment(p.position, a, b)) return false;
next.absorbed = stood.concat(
[{ position: entry.position, timeMs: entry.timeMs }],
nextStood,
);
removeAt(fixes, i);
return true;
}
/**
* Thin the recorded points either side of entry `i`, reaching past a
* neighbouring report: the point recorded just before a report is only
* judged once the line goes on beyond it.
*/
function thinAround(fixes, i) {
if (!thinAt(fixes, i + 1) && fixes[i + 1] && !fixes[i + 1].drawn)
thinAt(fixes, i + 2);
if (thinAt(fixes, i - 1)) i -= 1;
else if (fixes[i - 1] && !fixes[i - 1].drawn) thinAt(fixes, i - 2);
}
/**
* Drop recorded points that make a spur next to entry `i`. Reports are never
* dropped; at a report the recorded neighbour is dropped instead.
* @returns {number} The index entry `i` ends up at.
*/
function removeSpursAround(fixes, i) {
for (let guard = 0; guard < 64; guard++) {
let changed = false;
for (const j of [i - 1, i, i + 1]) {
if (!spurAt(fixes, j)) continue;
let drop = -1;
if (fixes[j].drawn) drop = j;
else if (fixes[j + 1]?.drawn) drop = j + 1;
else if (fixes[j - 1]?.drawn) drop = j - 1;
if (drop < 0) continue;
removeAt(fixes, drop);
if (drop < i) i -= 1;
changed = true;
break;
}
if (!changed) break;
}
return i;
}
/** Index a fix at `timeMs` goes in at: after every entry at or before it. */
function insertionIndex(fixes, timeMs) {
let i = fixes.length;
@@ -509,65 +356,16 @@ function insertionIndex(fixes, timeMs) {
}
/**
* Insert an entry at `i`, judge both breaks, remove spurs, thin the recorded
* points either side and keep the limit.
*/
function insertAt(fixes, i, entry, maxPoints) {
fixes.splice(i, 0, entry);
entry.breakBefore = trailFixBreaks(fixes[i - 1], entry);
const after = fixes[i + 1];
if (after) {
after.breakBefore = trailFixBreaks(entry, after);
// Positions the next entry stood for that come before this one are now
// on this entry's side.
if (after.absorbed?.length) {
const mine = after.absorbed.filter((p) => p.timeMs < entry.timeMs);
if (mine.length) {
entry.absorbed = mine;
after.absorbed = after.absorbed.filter((p) => p.timeMs >= entry.timeMs);
}
}
}
i = removeSpursAround(fixes, i);
thinAround(fixes, i);
keepTrailLimit(fixes, maxPoints);
}
/** Index of the newest report before entry `i`, or -1. */
function reportBefore(fixes, i) {
let j = i - 1;
while (j >= 0 && fixes[j].drawn) j -= 1;
return j;
}
/** Index of the oldest report at or after `i`, or `fixes.length`. */
function reportFrom(fixes, i) {
let j = i;
while (j < fixes.length && fixes[j].drawn) j += 1;
return j;
}
/**
* Put a report into the trail in time order. Reports are the record: they
* are kept as anchors among the recorded points.
*
* - A report the display has already passed replaces the guess drawn after
* it: the recorded points timed after it go, and nothing is recorded until
* the icon has eased onto the correction (`displayMs` + `settleMs`), so the
* line reads arc, report, corrected path.
* - Recorded points never join two reports that break under
* `trailPairBreaks` (too long or too fast apart to be one flight): the
* points between them go and the line breaks.
* - A live report with no altitude keeps no position and only breaks the
* line.
* Put a report into the trail in time order and judge the breaks on both
* sides of it. A live report with no altitude keeps no position and only
* breaks the line.
* @param {object[]} fixes - The trail, mutated.
* @param {{x: number, y: number, z: number}} position - Owned position.
* @param {number} timeMs - The report's epoch ms.
* @param {number} maxPoints - Point limit across all segments.
* @param {{nullAltitude?: boolean, displayMs?: number, settleMs?: number, onGround?: boolean}} [options]
* `displayMs`: the time the aircraft is drawn at as the report arrives;
* `settleMs`: how long the icon takes to ease onto a correction;
* `onGround`: whether the report was on the ground, when known.
* @param {{nullAltitude?: boolean, onGround?: boolean, track?: number}} [options]
* `onGround`: whether the report was on the ground, when known;
* `track`: its reported track, which the curve leaves it along.
* @returns {object[]} `fixes`.
*/
export function insertTrailFix(
@@ -575,97 +373,23 @@ export function insertTrailFix(
position,
timeMs,
maxPoints,
{
nullAltitude = false,
displayMs = NaN,
settleMs = 0,
onGround = undefined,
} = {},
{ nullAltitude = false, onGround = undefined, track = undefined } = {},
) {
const entry = {
position: nullAltitude ? null : position,
timeMs,
nullAltitude,
drawn: false,
breakBefore: false,
};
if (Number.isFinite(track)) entry.track = track;
// Whether the report was on the ground, when known: a history backfill
// joins it only across a landing or take-off it saw.
if (typeof onGround === 'boolean') entry.onGround = onGround;
let i = insertionIndex(fixes, timeMs);
// The guess drawn after a report the display already passed.
fixes.splice(i, reportFrom(fixes, i) - i);
if (displayMs > timeMs) entry.settleUntilMs = displayMs + settleMs;
// Recorded points across a pair of reports that are not one flight.
const before = reportBefore(fixes, i);
if (before >= 0 && trailFixBreaks(fixes[before], entry)) {
fixes.splice(before + 1, i - before - 1);
i = before + 1;
}
insertAt(fixes, i, entry, maxPoints);
const i = insertionIndex(fixes, timeMs);
fixes.splice(i, 0, entry);
entry.breakBefore = trailFixBreaks(fixes[i - 1], entry);
const after = fixes[i + 1];
if (after) after.breakBefore = trailFixBreaks(entry, after);
keepTrailLimit(fixes, maxPoints);
return fixes;
}
/**
* Record where the tracked aircraft was drawn at a display time. Between
* reports this recorded path is the trail, so the line follows every turn
* the icon made instead of a straight chord between two reports. Points are
* thinned by shape: one stays only where dropping it would move the line by
* more than TRAIL_THIN_TOLERANCE_M across the track or in height, or leave a
* straight piece longer than TRAIL_THIN_MAX_SPAN_M. Nothing is recorded
* while the aircraft holds.
* @param {object[]} fixes - The trail, mutated.
* @param {{x: number, y: number, z: number}} position - Owned drawn position.
* @param {number} timeMs - Display time it was drawn for.
* @param {number} maxPoints - Point limit across all segments.
* @returns {boolean} Whether the trail changed.
*/
export function recordTrailPoint(fixes, position, timeMs, maxPoints) {
const i = insertionIndex(fixes, timeMs);
const prev = fixes[i - 1];
if (
prev?.position &&
distance(prev.position, position) < TRAIL_RECORD_MIN_STEP_M
)
return false;
const entry = {
position,
timeMs,
nullAltitude: false,
drawn: true,
breakBefore: false,
};
insertAt(fixes, i, entry, maxPoints);
// Entries before the second report behind this point can never be thinned
// again, so they let go of the positions they stood for.
const passed = reportBefore(fixes, fixes.lastIndexOf(entry));
if (passed >= 0) sealThrough(fixes, reportBefore(fixes, passed));
return true;
}
/** Release the absorbed positions of entry `i` and everything before it. */
function sealThrough(fixes, i) {
for (let j = i; j >= 0 && !fixes[j].sealed; j--) {
fixes[j].sealed = true;
delete fixes[j].absorbed;
}
}
/**
* Whether the icon's drawn position must not be recorded at a display time:
* a report on either side of it has no altitude (the icon is drawn at an
* invented height), the reports on either side are not one flight
* (`trailPairBreaks`), or the icon is still easing onto a report that
* arrived after the display had passed it.
* @param {object[]} fixes
* @param {number} displayMs
* @returns {boolean}
*/
export function trailRecordingBlocked(fixes, displayMs) {
const i = insertionIndex(fixes, displayMs);
const before = fixes[reportBefore(fixes, i)];
const after = fixes[reportFrom(fixes, i)];
if (before?.nullAltitude || after?.nullAltitude) return true;
if (before?.settleUntilMs > displayMs) return true;
return !!(before && after && trailFixBreaks(before, after));
}
+106 -135
View File
@@ -3,163 +3,134 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
insertTrailFix,
recordTrailPoint,
trailBodySegments,
trailPairBreaks,
trailDistanceM,
trailRecordingBlocked,
trailHeadCurvePoints,
} from './trailContinuity.js';
// Reports decide where the line may run: recorded points never join two
// reports too far apart to be one flight, a report the display has already
// passed replaces the guess drawn after it, and old entries let go of the
// positions they stood for.
// A trail is the aircraft's reports and nothing else, each pair that is one
// path joined along the curve the icon is drawn along between them: no
// stretch it was drawn at between reports is kept, so a late report can
// never leave a kink.
const SEC = 1000;
const LIMIT = 2_000;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Cartesian3.fromDegrees(-100, 40, 0),
);
const at = (e, n, u = 10) =>
const at = (e, n, u = 3_000) =>
Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(e, n, u),
new Cesium.Cartesian3(),
);
/** No two neighbours in one drawn segment are too far apart to be one flight. */
function assertNoBrokenJoin(fixes) {
const reports = fixes.filter((fix) => !fix.drawn && fix.position);
for (const segment of trailBodySegments(fixes, fixes.length)) {
const inSegment = reports.filter((r) =>
segment.some((p) => Cesium.Cartesian3.distance(p, r.position) < 0.01),
);
for (let i = 1; i < inSegment.length; i++)
assert.equal(
trailPairBreaks(
inSegment[i].timeMs - inSegment[i - 1].timeMs,
trailDistanceM(inSegment[i - 1].position, inSegment[i].position),
),
false,
`one segment joins reports at ${inSegment[i - 1].timeMs / SEC} s and ${
inSegment[i].timeMs / SEC
} s`,
);
/** The sharpest turn (degrees) at any vertex of `line`, steps under 1 m skipped. */
function sharpestTurnDeg(line) {
const u = new Cesium.Cartesian3();
const v = new Cesium.Cartesian3();
let worst = 0;
for (let i = 1; i < line.length - 1; i++) {
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
const lu = Cesium.Cartesian3.magnitude(u);
const lv = Cesium.Cartesian3.magnitude(v);
if (!(lu > 1 && lv > 1)) continue;
const cos = Math.min(1, Cesium.Cartesian3.dot(u, v) / (lu * lv));
worst = Math.max(worst, (Math.acos(cos) * 180) / Math.PI);
}
return worst;
}
test('two reports 60 s and 51 km apart are not joined, even by recorded points', () => {
const A = Cesium.Cartesian3.fromDegrees(-100, 40, 9_000);
const B = Cesium.Cartesian3.fromDegrees(-99.4, 40, 9_000);
const fixes = [];
insertTrailFix(fixes, A, 0, LIMIT);
insertTrailFix(fixes, B, 60 * SEC, LIMIT); // ahead of the display
for (let t = 1; t < 60; t++) {
// Nothing is recorded across the pair.
assert.equal(trailRecordingBlocked(fixes, t * SEC), true);
}
assert.equal(trailBodySegments(fixes, fixes.length).length, 2);
// Points recorded before the far report was known are dropped.
const late = [];
insertTrailFix(late, A, 0, LIMIT);
for (let t = 1; t < 60; t++)
recordTrailPoint(
late,
Cesium.Cartesian3.lerp(A, B, t / 60, new Cesium.Cartesian3()),
t * SEC,
LIMIT,
);
insertTrailFix(late, B, 60 * SEC, LIMIT);
assert.equal(late.filter((fix) => fix.drawn).length, 0);
assert.equal(trailBodySegments(late, late.length).length, 2);
assertNoBrokenJoin(late);
});
// A 100 m/s aircraft in a left turn on a 2 km circle centred at (0, R),
// heading east at the origin, reporting every 15 s with its track.
const R = 2_000;
const W = 100 / R;
const circle = (t) => at(R * Math.sin(W * t), R - R * Math.cos(W * t));
const trackAt = (t) => (90 - (W * t * 180) / Math.PI + 360) % 360;
test('a coast, a hold and then a far report: nothing is drawn across', () => {
const A = at(0, 0, 9_000);
test('reports in a turn are joined along a smooth curve through each report', () => {
const fixes = [];
insertTrailFix(fixes, A, 0, LIMIT);
// The icon coasts east for 90 s at 230 m/s, then holds.
for (let t = 1; t <= 200; t++)
recordTrailPoint(
fixes,
at(230 * Math.min(t, 90), 0, 9_000),
t * SEC,
LIMIT,
);
assert.ok(fixes.filter((fix) => fix.drawn).length > 0);
// The next report is 150 km away two minutes later: over 1,500 kt.
const B = at(0, 150_000, 9_000);
insertTrailFix(fixes, B, 120 * SEC, LIMIT);
assertNoBrokenJoin(fixes);
const segments = trailBodySegments(fixes, fixes.length);
const segmentOf = (p) =>
segments.findIndex((s) =>
s.some((q) => Cesium.Cartesian3.distance(p, q) < 0.01),
);
assert.notEqual(segmentOf(A), segmentOf(B));
// No recorded point between the two reports remains.
assert.equal(
fixes.filter((fix) => fix.drawn && fix.timeMs < 120 * SEC).length,
0,
for (let t = 0; t <= 60; t += 15)
insertTrailFix(fixes, circle(t), t * SEC, LIMIT, { track: trackAt(t) });
assert.deepEqual(
fixes.map((f) => f.timeMs),
[0, 15, 30, 45, 60].map((s) => s * SEC),
);
const [line] = trailBodySegments(fixes, fixes.length);
for (const f of fixes)
assert.ok(
line.some((p) => Cesium.Cartesian3.distance(p, f.position) < 0.01),
'every report is on the line',
);
assert.ok(sharpestTurnDeg(line) < 3, `${sharpestTurnDeg(line)}°`);
// On the circle, not across its chords.
for (const p of line)
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 20,
'a point off the turn',
);
});
for (const off of [200, 400, 600, 1_000]) {
test(`a report the display already passed, ${off} m off a 2 km turn, leaves no spike`, () => {
const R = 2_000;
const w = 100 / R;
const pos = (t, r = R) =>
at(r * Math.sin(w * t), R - r * Math.cos(w * t), 3_000);
const fixes = [];
insertTrailFix(fixes, pos(0), 0, LIMIT);
for (let t = 1; t <= 60; t++)
recordTrailPoint(fixes, pos(t), t * SEC, LIMIT);
const report = pos(50, R - off);
// It arrives with the display at 60 s; the ease takes 900 ms.
insertTrailFix(fixes, report, 50 * SEC, LIMIT, {
displayMs: 60 * SEC,
settleMs: 900,
});
// The guess drawn after the report is gone...
assert.deepEqual(
fixes.filter((fix) => fix.drawn && fix.timeMs > 50 * SEC),
[],
);
// ...nothing is recorded while the icon eases onto the correction...
assert.equal(trailRecordingBlocked(fixes, 60.5 * SEC), true);
assert.equal(trailRecordingBlocked(fixes, 61 * SEC), false);
// ...and the line reads arc, report, corrected path.
for (let t = 61; t <= 70; t++)
recordTrailPoint(fixes, pos(t, R - off), t * SEC, LIMIT);
const line = trailBodySegments(fixes, fixes.length).flat();
const r = line.findIndex(
(p) => Cesium.Cartesian3.distance(p, report) < 0.01,
);
assert.ok(r > 0);
for (const p of line.slice(0, r))
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R, 3_000)) - R) < 31,
'a point before the report is off the arc',
);
for (const p of line.slice(r + 1))
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R, 3_000)) - (R - off)) <
31,
'a point after the report is off the corrected path',
);
});
}
test('entries behind the report before the display let go of the positions they stood for', () => {
test('reports with no track are joined straight, report to report', () => {
const fixes = [];
for (let s = 0; s <= 2 * 3_600; s++) {
const p = at(230 * s, 0, 10_000);
if (s % 15 === 0) insertTrailFix(fixes, p, s * SEC, LIMIT);
else recordTrailPoint(fixes, p, s * SEC, LIMIT);
}
let held = 0;
for (const fix of fixes) held += fix.absorbed?.length ?? 0;
// Only the newest stretch, up to two reports back, keeps what it stood for.
assert.ok(held <= 30, `${held} positions still held`);
for (let t = 0; t <= 60; t += 15)
insertTrailFix(fixes, circle(t), t * SEC, LIMIT);
const [line] = trailBodySegments(fixes, fixes.length);
assert.equal(line.length, fixes.length);
});
test('two reports 60 s and 51 km apart are not joined', () => {
const fixes = [];
insertTrailFix(
fixes,
Cesium.Cartesian3.fromDegrees(-100, 40, 9_000),
0,
LIMIT,
{ track: 90 },
);
insertTrailFix(
fixes,
Cesium.Cartesian3.fromDegrees(-99.4, 40, 9_000),
60 * SEC,
LIMIT,
{ track: 90 },
);
assert.equal(trailBodySegments(fixes, fixes.length).length, 2);
// Nor is the head drawn along a curve across them.
assert.deepEqual(trailHeadCurvePoints(fixes, 1, 30 * SEC), []);
});
test('a report with no altitude keeps no position and breaks the line', () => {
const fixes = [];
insertTrailFix(fixes, circle(0), 0, LIMIT, { track: trackAt(0) });
insertTrailFix(fixes, circle(15), 15 * SEC, LIMIT, { nullAltitude: true });
insertTrailFix(fixes, circle(30), 30 * SEC, LIMIT, { track: trackAt(30) });
assert.equal(fixes[1].position, null);
assert.equal(trailBodySegments(fixes, fixes.length).length, 2);
});
test('a report arriving late goes in time order and the curve stays smooth', () => {
const fixes = [];
for (const t of [0, 30, 15, 45])
insertTrailFix(fixes, circle(t), t * SEC, LIMIT, { track: trackAt(t) });
assert.deepEqual(
fixes.map((f) => f.timeMs / SEC),
[0, 15, 30, 45],
);
const [line] = trailBodySegments(fixes, fixes.length);
assert.ok(sharpestTurnDeg(line) < 3);
});
test('the head runs along the curve to the next report and stops before the display time', () => {
const fixes = [];
insertTrailFix(fixes, circle(0), 0, LIMIT, { track: trackAt(0) });
insertTrailFix(fixes, circle(15), 15 * SEC, LIMIT, { track: trackAt(15) });
const head = trailHeadCurvePoints(fixes, 1, 10 * SEC);
assert.ok(head.length > 5);
const drawnAt = circle(10);
const [body] = trailBodySegments(fixes, 1);
// Body, head points, then the aircraft: one smooth line.
assert.ok(sharpestTurnDeg([...body, ...head, drawnAt]) < 3);
for (const p of head)
assert.ok(Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 20);
});
-180
View File
@@ -1,180 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
insertTrailFix,
joinTrailBackfill,
recordTrailPoint,
TRAIL_THIN_MAX_SPAN_M,
TRAIL_THIN_TOLERANCE_M,
} from './trailContinuity.js';
// Recorded points are thinned by shape: a point stays only where the line
// would move without it. Reports always stay.
const SEC = 1000;
const LIMIT = 2_000;
const LAT0 = 40;
const LON0 = -100;
const M_PER_DEG_LAT = 111_320;
const mPerDegLon = (lat) => M_PER_DEG_LAT * Math.cos((lat * Math.PI) / 180);
/** Straight and level east at `speed` m/s, `tSec` after the start. */
const eastbound = (speed, tSec, heightM = 10_000) =>
Cesium.Cartesian3.fromDegrees(
LON0 + (speed * tSec) / mPerDegLon(LAT0),
LAT0,
heightM,
);
/** A standard-rate (3°/s) left turn from north, radius v / ω, `tSec` in. */
function turning(speed, tSec, heightM = 10_000) {
const omega = (3 * Math.PI) / 180;
const radius = speed / omega;
// Centre west of the start; heading north, turning left (towards west).
const angle = omega * tSec;
const east = -radius + radius * Math.cos(angle);
const north = radius * Math.sin(angle);
return Cesium.Cartesian3.fromDegrees(
LON0 + east / mPerDegLon(LAT0),
LAT0 + north / M_PER_DEG_LAT,
heightM,
);
}
/** Distance from p to the nearest point of a polyline. */
function distanceToPath(p, path) {
let best = Infinity;
const ab = new Cesium.Cartesian3();
const ap = new Cesium.Cartesian3();
const closest = new Cesium.Cartesian3();
for (let i = 1; i < path.length; i++) {
Cesium.Cartesian3.subtract(path[i], path[i - 1], ab);
Cesium.Cartesian3.subtract(p, path[i - 1], ap);
const len2 = Cesium.Cartesian3.magnitudeSquared(ab);
const t =
len2 > 0
? Math.max(0, Math.min(1, Cesium.Cartesian3.dot(ap, ab) / len2))
: 0;
Cesium.Cartesian3.add(
path[i - 1],
Cesium.Cartesian3.multiplyByScalar(ab, t, closest),
closest,
);
best = Math.min(best, Cesium.Cartesian3.distance(p, closest));
}
return best;
}
const drawnCount = (fixes) => fixes.filter((fix) => fix.drawn).length;
test('one hour straight and level with a report every 15 s adds under 60 recorded points', () => {
const speed = 230;
const fixes = [];
for (const t of [0, 15, 30])
insertTrailFix(fixes, eastbound(speed, t), t * SEC, LIMIT);
// Live order: a report arrives 30 s before the display reaches it, and the
// drawn icon is recorded once a second.
for (let t = 1; t <= 3_600; t++) {
const reportAt = t + 30;
if (reportAt % 15 === 0 && reportAt <= 3_600)
insertTrailFix(fixes, eastbound(speed, reportAt), reportAt * SEC, LIMIT);
recordTrailPoint(fixes, eastbound(speed, t), t * SEC, LIMIT);
}
assert.ok(
drawnCount(fixes) < 60,
`${drawnCount(fixes)} recorded points kept`,
);
assert.equal(fixes.filter((fix) => !fix.drawn).length, 241);
});
test('with no report at all, a straight leg keeps one point per 10 km and no more', () => {
const speed = 230;
const fixes = [];
insertTrailFix(fixes, eastbound(speed, 0), 0, LIMIT);
for (let t = 1; t <= 3_600; t++)
recordTrailPoint(fixes, eastbound(speed, t), t * SEC, LIMIT);
const legKm = (speed * 3_600) / 1_000;
assert.equal(TRAIL_THIN_MAX_SPAN_M, 10_000);
assert.ok(
drawnCount(fixes) <= Math.ceil(legKm / 10) + 1,
`${drawnCount(fixes)} points over ${legKm} km`,
);
for (let i = 1; i < fixes.length; i++)
assert.ok(
Cesium.Cartesian3.distance(fixes[i - 1].position, fixes[i].position) <=
TRAIL_THIN_MAX_SPAN_M + speed,
);
});
test('a standard-rate 180° turn keeps its curve: every recorded position stays within 30 m of the kept line', () => {
const speed = 230;
const fixes = [];
const recorded = [];
insertTrailFix(fixes, turning(speed, 0), 0, LIMIT);
for (let t = 1; t <= 60; t++) {
const position = turning(speed, t);
recorded.push(position);
recordTrailPoint(fixes, position, t * SEC, LIMIT);
}
const line = fixes.map((fix) => fix.position);
assert.equal(TRAIL_THIN_TOLERANCE_M, 30);
for (const position of recorded) {
const off = distanceToPath(position, line);
assert.ok(off <= TRAIL_THIN_TOLERANCE_M + 1, `${off.toFixed(1)} m off`);
}
assert.ok(drawnCount(fixes) < recorded.length, 'nothing was thinned');
assert.ok(drawnCount(fixes) >= 6, 'the curve was flattened');
});
test('a climb off the straight line keeps its vertices', () => {
const fixes = [];
insertTrailFix(fixes, eastbound(200, 0, 1_000), 0, LIMIT);
// 30 s level, then a 60 s climb of 20 m/s, then level again.
const height = (t) => 1_000 + 20 * Math.min(60, Math.max(0, t - 30));
const recorded = [];
for (let t = 1; t <= 150; t++) {
const position = eastbound(200, t, height(t));
recorded.push(position);
recordTrailPoint(fixes, position, t * SEC, LIMIT);
}
const line = fixes.map((fix) => fix.position);
for (const position of recorded)
assert.ok(distanceToPath(position, line) <= TRAIL_THIN_TOLERANCE_M + 1);
});
test('at the limit, old recorded points go before any report from the backfill', () => {
const max = 300;
const backfill = [];
for (let i = 0; i < 100; i++)
backfill.push({
position: eastbound(200, i * 60 - 20_000),
timeMs: (i * 60 - 20_000) * SEC,
nullAltitude: false,
});
let fixes = [];
insertTrailFix(fixes, turning(150, 0), 0, max);
// A long series of turns keeps many recorded points.
for (let t = 1; t <= 2_000; t++)
recordTrailPoint(fixes, turning(150, t), t * SEC, max);
assert.ok(drawnCount(fixes) > 150);
fixes = joinTrailBackfill(
{
fixes: backfill.map((b) => ({ ...b, breakBefore: false })),
breakAfter: false,
},
fixes,
max,
);
assert.ok(fixes.length <= max);
const reports = fixes.filter((fix) => !fix.drawn);
assert.equal(reports.length, 101, 'a report was dropped');
// More recording at the limit drops recorded points, never reports.
for (let t = 2_001; t <= 2_400; t++)
recordTrailPoint(fixes, turning(150, t), t * SEC, max);
assert.ok(fixes.length <= max);
assert.equal(fixes.filter((fix) => !fix.drawn).length, 101);
// The recorded points that remain are the newest.
const drawnTimes = fixes.filter((fix) => fix.drawn).map((fix) => fix.timeMs);
assert.ok(Math.min(...drawnTimes) > 1_000 * SEC);
});
+6
View File
@@ -0,0 +1,6 @@
import { feedLatencyTests } from '../../testSupport/aircraftFeedLatency.mjs';
import { RENDER_DELAY_SEC } from './policy.js';
// A slow live feed, as measured: reports about 90 s old every poll, now and
// then a fresh fallback feed, a report that does not move on, or an outage.
feedLatencyTests('flights', RENDER_DELAY_SEC);
+1 -2
View File
@@ -7,7 +7,6 @@ import {
COURSE_MAX_DPS,
FLOOR_FAR_EVERY_TICKS,
FLOOR_NEAR_M,
RENDER_DELAY_SEC,
STALE_ALPHA,
followsClock,
} from './policy.js';
@@ -27,7 +26,7 @@ export function createIcons({ flightState, services, parts }) {
services,
parts,
layerId: 'flights',
renderDelaySec: RENDER_DELAY_SEC,
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
staleAlpha: STALE_ALPHA,
courseMaxDps: COURSE_MAX_DPS,
+4
View File
@@ -155,6 +155,10 @@ test('a hidden contact shown again is where dead reckoning puts it now', (t) =>
const coastMps = 250;
const { flightState, icons, set } = setup({
motion: {
// Shown at the first fix when first planned 2 s on: it eases onto the
// path toward where it is on it then.
_deadReckon: () => null,
_displayTimeAt: (ms) => Cesium.JulianDate.fromDate(new Date(ms)),
// Between the two fixes until the newer one, then a coast past it.
_motionRegime: (_history, _info, renderTime) => {
const ms = Cesium.JulianDate.toDate(renderTime).getTime();
+62 -16
View File
@@ -1,5 +1,9 @@
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { renderedFrames } from '../../data/renderedFrames.js';
import {
motionCourse,
motionPosition,
} from '../../render/motion/iconMotion.js';
import {
fromDegrees,
fromRadians,
@@ -11,6 +15,7 @@ import {
addSeconds,
julianLessThan,
julianFromEpochMs,
julianToEpochMs,
secondsDifference,
} from '../../geo/julian.js';
import {
@@ -31,6 +36,8 @@ import {
staleHoldsForFix,
arcOffsetEnu,
courseSlewCapDps,
RECOVER_SNAP_M,
recoveryMs,
limitCourseStep,
corridorPathLatLon,
} from '../../data/motionModel.js';
@@ -222,8 +229,8 @@ export function createMotion({
}
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).
// Render behind real time, as late as the feed is (displayDelayMs), so we
// interpolate between two KNOWN fixes whenever possible.
const renderTime =
sampledRenderTime ??
addSeconds(
@@ -233,6 +240,16 @@ export function createMotion({
);
const regime = _motionRegime(history, info, renderTime);
if (regime.kind === 'between' && regime.piece) {
// Along the curve between the two reports, as the icon and the trail.
const ms = julianToEpochMs(renderTime);
const segment = regime.piece.segment;
flightState._drCourseDeg = motionCourse(segment, undefined, ms);
flightState._drSpeedMps = segment.speedMps;
flightState._drCourseHold = segment.speedMps < COURSE_HOLD_SPEED_MPS;
flightState._drExtrapolating = false;
return copyInto(motionPosition(segment, null, ms), out);
}
if (regime.kind === 'between') {
const { a, b, span } = regime;
const t = span > 0 ? secondsDifference(renderTime, a.time) / span : 1.0;
@@ -343,7 +360,7 @@ export function createMotion({
}
/**
* True while the tracked aircraft's delayed display time (now − RENDER_DELAY_SEC)
* True while the tracked aircraft's delayed display time (now − displayDelayMs)
* predates its oldest real fix — i.e. _deadReckon is extrapolating backward, with no
* real history yet sitting BEHIND the displayed icon. The trail must draw nothing in
* this window (every accumulated point is ahead of the icon).
@@ -431,30 +448,51 @@ export function createMotion({
// which plays faster than the wall clock when following it at a rate.
const worldMs = followsClock(flightState) ? flightState.now() : nowMs;
const info = flightState.records.data.get(icao24);
const dtSec = Math.max(
0.001,
(worldMs - flightState._drPrevWorldMs) / 1000,
);
let snapped = false;
if (sameTrack) {
const dtSec = Math.max(
0.001,
(worldMs - flightState._drPrevWorldMs) / 1000,
);
const speed = (info && info.velocity) || 0;
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
const plausible = speed * dtSec * 4 + 25;
// Plausible single-frame motion (m): its speed × frame Δt, half again
// for slack, plus 5 m. More is a jump (a new report put it elsewhere).
const plausible = speed * dtSec * 1.5 + 5;
if (distance(raw, flightState._drPrevRaw) > plausible) {
// Discontinuity — re-anchor so the DISPLAYED position stays continuous, then decay.
copyInto(
sub(flightState._drPrevDisplay, raw),
flightState._drCorrection,
);
// Discontinuity — re-anchor so the DISPLAYED position stays continuous,
// then ease onto the new path no faster than a little over its speed;
// farther off than RECOVER_SNAP_M it is a break, and it jumps.
// From where the icon would be this frame had it carried on as it
// was moving, not from where it was last frame: it never stands
// still for a frame.
const anchor =
flightState._drPrevStepSec > 0
? add(
flightState._drPrevDisplay,
scale(
flightState._drPrevStep,
dtSec / flightState._drPrevStepSec,
),
)
: flightState._drPrevDisplay;
const errorM = distance(anchor, raw);
snapped = errorM >= RECOVER_SNAP_M;
copyInto(snapped ? vec() : sub(anchor, raw), flightState._drCorrection);
flightState._drCorrectionStartMs = nowMs;
flightState._drCorrectionMs = Math.max(
DR_CORRECTION_MS,
recoveryMs(errorM, speed),
);
}
} else {
copyInto(vec(), flightState._drCorrection);
flightState._drCorrectionStartMs = nowMs - DR_CORRECTION_MS; // fully decayed
flightState._drCorrectionMs = DR_CORRECTION_MS;
}
const elapsed = nowMs - flightState._drCorrectionStartMs;
const factor =
elapsed >= DR_CORRECTION_MS ? 0 : 1 - elapsed / DR_CORRECTION_MS;
const easeMs = flightState._drCorrectionMs ?? DR_CORRECTION_MS;
const factor = elapsed >= easeMs ? 0 : 1 - elapsed / easeMs;
let display = copyInto(
add(raw, scale(flightState._drCorrection, factor)),
flightState._trackedPosHolder,
@@ -477,6 +515,14 @@ export function createMotion({
nowMs,
);
// How the icon moved this frame, to carry it on through a re-anchor.
if (sameTrack && !snapped) {
copyInto(
sub(display, flightState._drPrevDisplay),
flightState._drPrevStep,
);
flightState._drPrevStepSec = dtSec;
} else flightState._drPrevStepSec = 0;
copyInto(raw, flightState._drPrevRaw);
copyInto(display, flightState._drPrevDisplay);
flightState._drPrevMs = nowMs;
+21 -11
View File
@@ -110,7 +110,7 @@ export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = Object.freeze({
// ---------------------------------------------------------------------------
// Track-history trail state (PRD WS-F F1/F4): a fading polyline behind the
// tracked aircraft. The accumulation array is intentionally SEPARATE from
// _positionHistory (capped at POSITION_HISTORY_LIMIT=5 for dead reckoning)
// _positionHistory (capped at POSITION_HISTORY_LIMIT for drawing)
// so the visible trail can grow to TRAIL_MAX_POINTS fixes.
// ---------------------------------------------------------------------------
@@ -123,26 +123,36 @@ export const TRAIL_COLOR = '#00d4ff';
export const TRAIL_MAX_POINTS = 2000;
// ---------------------------------------------------------------------------
// Render-behind smoothing (PRD WS-C C2 — approved product decision):
// the fleet renders at now - RENDER_DELAY_SEC so positions interpolate
// BETWEEN two known fixes instead of extrapolating ahead and snapping back
// when the next poll lands. All consumers (labels, HUD, detection,
// frame_overhead) share this delayed clock; removing the delay reintroduces
// the back/forward oscillation and is a regression.
// Render-behind smoothing (PRD WS-C C2 — approved product decision): the fleet
// renders at now − the display delay so positions run BETWEEN two known
// fixes instead of extrapolating ahead and snapping back when the next poll
// lands. The delay follows how late the feed really is (data/displayDelay.js:
// the 90th percentile of how long the display waits for each next report,
// plus 5 s, changed slowly), never under RENDER_DELAY_SEC. All consumers
// (labels, HUD, detection, frame_overhead, the tracked camera, trails and the
// renderer's motion clock) share this one delayed clock; removing the delay
// reintroduces the back/forward oscillation and is a regression.
// ---------------------------------------------------------------------------
/** @constant {number} Display latency in seconds (= one poll interval). */
/** @constant {number} The shortest display delay in seconds (one poll interval). */
export const RENDER_DELAY_SEC = 30;
/** @constant {number} How often the feed is polled (ms). */
export const POLL_INTERVAL_MS = 30_000;
/** Whether the layer shows the world clock's time instead of the live feed:
* its source declares a timeline and the clock is away from live. */
export const followsClock = (state) => state.timeline?.active() === true;
/** How far behind the time contacts are drawn: RENDER_DELAY_SEC live, none
* following the clock, whose snapshots are loaded ahead of the time. */
/** How far behind the time contacts are drawn (ms): the feed's display
* delay live, none following the clock, whose snapshots are loaded ahead
* of the time. */
export const displayDelayMs = (state) =>
followsClock(state) ? 0 : RENDER_DELAY_SEC * 1000;
followsClock(state)
? 0
: (state._displayDelay?.currentMs ?? RENDER_DELAY_SEC * 1000);
/** @constant {number} Polls an aircraft may miss before removal (transient OpenSky dropouts). */
+2 -1
View File
@@ -17,6 +17,7 @@ import {
LANDED_SPEED_MAX_MPS,
FOCUS_EVIDENCE_DEV,
FLEET_DR_INTERVAL_MS,
POLL_INTERVAL_MS,
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
@@ -311,7 +312,7 @@ export function createQueries({
parts.testing._clearDisplayFloorStateForTest,
/** @type {number} Polling interval (ms) between update() calls */
updateInterval: 30000,
updateInterval: POLL_INTERVAL_MS,
/**
* Live layer params.
+3 -2
View File
@@ -2,8 +2,9 @@ export const GROUND_FLOOR_CLAMP_RADIUS_KM = 150;
export const GROUND_FLOOR_WARM_MAX_ALT_M = 4500;
/** Maximum feed fixes retained for dead reckoning. */
export const POSITION_HISTORY_LIMIT = 5;
/** Maximum feed fixes retained for drawing: enough to reach back over the
* longest display delay at one report per poll. */
export const POSITION_HISTORY_LIMIT = 24;
export const LANDED_MISSING_POLL_LIMIT = 1;
+53 -22
View File
@@ -7,6 +7,30 @@ import {
} from '../../data/motionModel.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
/**
* Note how late each report in a live snapshot is, and aim the display delay
* again, before any contact is planned with it: a layer drawing nothing yet
* takes the new delay at once.
*/
function noteDelivery(flightState, snapshot) {
const delay = flightState._displayDelay;
if (!delay) return;
const receiptMs = Date.now();
for (const observation of snapshot.records) {
const reportMs = observation.positionTimeMs;
if (!(Number.isFinite(reportMs) && reportMs > 0)) continue;
const history = flightState._positionHistory.get(observation.id);
const previous = history && newestReport(history);
delay.noteReport(
receiptMs,
reportMs,
previous ? Math.trunc(previous.epochMs) : undefined,
);
}
delay.settle(receiptMs, { jump: !flightState._icons.count });
}
/** Apply reconciled aircraft records to the layer's drawing and follow state. */
export function createFlightSnapshotRenderer({
@@ -42,6 +66,9 @@ export function createFlightSnapshotRenderer({
const viewerLonDeg = hasSubpoint ? pose.lon : null;
const floorWarmPoints = [];
records.beginSnapshot(snapshot.observedAtMs);
// Live, the display delay follows how late this delivery's reports are.
if (!replace && !followsClock(flightState))
noteDelivery(flightState, snapshot);
// Classification and display policy consume source-independent observations.
refreshMilitaryRegistryIfStale();
@@ -95,34 +122,37 @@ export function createFlightSnapshotRenderer({
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
// Whole milliseconds, as the fix times are kept.
const report = newestReport(history);
// Whole milliseconds, as the fix times are kept. A report newer than
// the last report goes in, past any synthetic fix after it.
if (
!newest ||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(newest))
!report ||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(report))
) {
// Per-fix kinematics: the fix's own velocity/track ride along so the
// extrapolation paths use the values that BELONG to the fix they
// extend, not whatever the latest poll reported.
history.push({
...motion._historyFix(
fixEpochMs,
position,
meta.velocity,
meta.true_track,
),
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
// Whether this report was on the ground: a trail backfill joins it
// only across a landing or take-off it saw.
onGround: meta.onGround === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
pushReport(
history,
{
...motion._historyFix(
fixEpochMs,
position,
meta.velocity,
meta.true_track,
),
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
// Whether this report was on the ground: a trail backfill joins it
// only across a landing or take-off it saw.
onGround: meta.onGround === true,
},
POSITION_HISTORY_LIMIT,
);
// Turn rate from the fix-track history — computed once per new fix
// (≤5 samples), consumed by the extrapolation paths at tick rate.
meta.turnRateDps = turnRateFromFixHistory(history);
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
// Trail accumulation is separate from the 5-fix DR history (PRD F1)
// so the visible trail keeps growing while tracked. Ground traffic
// appends nothing — a touchdown freezes the existing trail.
@@ -132,6 +162,7 @@ export function createFlightSnapshotRenderer({
if (isTracked)
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.true_track,
});
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
@@ -164,7 +195,7 @@ export function createFlightSnapshotRenderer({
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
}
}
}
+11 -3
View File
@@ -369,11 +369,19 @@ test('while the display is between reports, the trail stops at the report behind
const icon = Cesium.Cartesian3.fromDegrees(-100 + 0.075, 40, 10_000);
const h = trailHarness({ fixes, nowMs, head: icon });
h.tracking._startTrail('00a001');
// Reports at 0, 10 and 20 s are behind the icon (display time 25 s).
assert.equal(h.drawn().length, 3);
// Reports at 0, 10 and 20 s are behind the icon (display time 25 s): the
// body runs through them along their curve and ends at the third.
const body = h.drawn();
for (const report of fixes.slice(0, 3))
assert.ok(
body.some((p) => Cesium.Cartesian3.distance(p, report.position) < 0.01),
);
assert.ok(Cesium.Cartesian3.distance(body.at(-1), fixes[2].position) < 0.01);
// The head runs on from it to the icon.
const head = h.head();
assert.equal(head.length, 2);
assert.ok(head.length >= 2);
assert.ok(Cesium.Cartesian3.distance(head[0], fixes[2].position) < 0.01);
assert.ok(Cesium.Cartesian3.distance(head.at(-1), icon) < 0.01);
});
test('the hold-or-coast decision is made once per report: a floor that resolves mid-coast does not snap the icon back', () => {
+22 -13
View File
@@ -1,7 +1,12 @@
import { FlightRecords } from './records.js';
import { createFlightFeed } from './ingestion.js';
import { worldTimeFor } from '../../time/worldClock.js';
import { ENRICH_AMBIENT_BUDGET_CEIL } from './policy.js';
import { createDisplayDelay } from '../../data/displayDelay.js';
import {
ENRICH_AMBIENT_BUDGET_CEIL,
POLL_INTERVAL_MS,
RENDER_DELAY_SEC,
} from './policy.js';
export function createFlightState({ source, services }) {
const { createGroundSnap } = services.groundSnap;
@@ -14,6 +19,12 @@ export function createFlightState({ source, services }) {
});
/** The time contacts are drawn behind by the render delay, in epoch ms. */
flightState.now = worldTimeFor('flights');
/** How far behind real time live contacts are drawn: follows how late the
* feed's reports arrive (see displayDelayMs in policy.js). */
flightState._displayDelay = createDisplayDelay({
floorMs: RENDER_DELAY_SEC * 1000,
pollMs: POLL_INTERVAL_MS,
});
/** Follows the world clock while the source declares a timeline (set by the
* layer); see followsClock and displayDelayMs in policy.js. */
flightState.timeline = null;
@@ -154,10 +165,9 @@ export function createFlightState({ source, services }) {
flightState._trailHeadOff = null;
/** @type {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, drawn?: boolean}[]}
* Chronological tracked-aircraft trail (oldest first): reports, and
* (`drawn`) where the icon was drawn between them; `breakBefore` starts a
* new segment. */
/** @type {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, track?: number}[]}
* Chronological tracked-aircraft trail (oldest first): reports, joined along
* the curve the icon is drawn along; `breakBefore` starts a new segment. */
flightState._trailFixes = [];
@@ -165,14 +175,6 @@ export function createFlightState({ source, services }) {
flightState._trailBodyCount = 0;
/** @type {{x: number, y: number, z: number}|null} Where the tracked icon was last recorded into the trail. */
flightState._trailRecordPosition = null;
/** @type {number} Display time (epoch ms) of that recording. */
flightState._trailRecordMs = -Infinity;
/** @type {string|undefined} The stale cue last written into the tracked label (see `_staleCueTick`). */
flightState._trackedStaleCueText = undefined;
@@ -328,10 +330,17 @@ export function createFlightState({ source, services }) {
flightState._drCorrectionStartMs = 0;
/** How long (ms) the correction under way takes to ease out. */
flightState._drCorrectionMs = 0;
flightState._drPrevRaw = { x: 0, y: 0, z: 0 };
flightState._drPrevDisplay = { x: 0, y: 0, z: 0 };
/** How the tracked icon moved over the last frame, and that frame's length (s; 0 for none). */
flightState._drPrevStep = { x: 0, y: 0, z: 0 };
flightState._drPrevStepSec = 0;
flightState._drPrevMs = 0;
/** World time of that frame: the wall clock live, the cursor following the clock. */
+42 -88
View File
@@ -19,8 +19,8 @@ import {
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { julianToEpochMs } from '../../geo/julian.js';
import { renderedFrames } from '../../data/renderedFrames.js';
import { clone, distance, distanceSquared, vec } from '../../geo/vector.js';
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
import { clone, distanceSquared, vec } from '../../geo/vector.js';
import { trailHeadLine } from '../../data/modelVisualAnchor.js';
import { routePlausible } from '../../data/routePlausible.js';
import {
isTrackingSelectionGesture,
@@ -29,7 +29,6 @@ import {
import { inputFor } from '../../input/dispatcher.js';
import {
TRAIL_MAX_POINTS,
DR_CORRECTION_MS,
TRAIL_COLOR,
CYAN_TRANSPARENT,
TRACKED_CYAN,
@@ -42,15 +41,11 @@ import {
historyFixEpochMs,
insertTrailFix,
joinTrailBackfill,
recordTrailPoint,
trailBackfillFixes,
trailBodyCount,
trailBodyCountOutsideModel,
trailBodySegments,
trailHeadCurvePoints,
trailHeadStartFix,
trailRecordingBlocked,
TRAIL_RECORD_STEP_M,
TRAIL_RECORD_STEP_MS,
} from '../../data/trailContinuity.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
import { entityRecord } from '../../data/entityRecords.js';
@@ -337,13 +332,16 @@ export function createTracking({
* @param {{x: number, y: number, z: number}} position - The report's ECEF position.
* @param {number} [epochMs] - The report's time; defaults to the tracked
* aircraft's newest position-history fix, which every caller has just pushed.
* @param {{nullAltitude?: boolean}} [options] - `nullAltitude`: the report
* had no altitude, so its position is not kept and the line breaks there.
* A report for a time the display has already passed replaces what was
* drawn after it (see `insertTrailFix`).
* @param {{nullAltitude?: boolean, track?: number}} [options] - `nullAltitude`:
* the report had no altitude, so its position is not kept and the line
* breaks there; `track`: its reported track, which the line leaves it along.
*/
function _appendTrailFix(position, epochMs, { nullAltitude = false } = {}) {
function _appendTrailFix(
position,
epochMs,
{ nullAltitude = false, track = undefined } = {},
) {
const history = flightState._positionHistory.get(flightState._trackedIcao);
const timeMs = Number.isFinite(epochMs)
? epochMs
@@ -353,70 +351,36 @@ export function createTracking({
position,
timeMs,
TRAIL_MAX_POINTS,
{
nullAltitude,
displayMs: flightState.now() - displayDelayMs(flightState),
settleMs: DR_CORRECTION_MS,
},
{ nullAltitude, track },
);
_refreshTrailDisplay();
}
/**
* Per-frame trail work, run before each frame draws whether or not the
* head is visible: record where the tracked icon is drawn (at most once a
* second or every 150 m) and move the body on as the display time passes
* reports. The head only reads the result.
* head is visible: move the body on as the display time passes reports.
* The head only reads the result.
*/
function _trailTick() {
if (!flightState._trackedIcao || !flightState._trail) return;
const displayMs = flightState.now() - displayDelayMs(flightState);
let changed = false;
if (
flightState._trailFixes.length &&
!parts.motion._isTrackWarmingUp() &&
!trailRecordingBlocked(flightState._trailFixes, displayMs)
) {
const drawn = parts.motion._trackedDisplayPosition(
flightState._trackedIcao,
);
const last = flightState._trailRecordPosition;
if (
drawn &&
(!last ||
displayMs - flightState._trailRecordMs >= TRAIL_RECORD_STEP_MS ||
distance(last, drawn) >= TRAIL_RECORD_STEP_M)
) {
flightState._trailRecordMs = displayMs;
flightState._trailRecordPosition = clone(drawn);
changed = recordTrailPoint(
flightState._trailFixes,
clone(drawn),
displayMs,
TRAIL_MAX_POINTS,
);
}
}
if (changed || _trailBodyCountNow() !== flightState._trailBodyCount)
if (_trailBodyCountNow() !== flightState._trailBodyCount)
_refreshTrailDisplay();
}
/**
* Renders the trail with its head clamped to the render-behind display
* position. Raw newest fixes run up to RENDER_DELAY_SEC ahead of the
* displayed aircraft (PRD C2 delayed clock) — drawing them verbatim makes
* the trail extend in FRONT of the icon. The head is refreshed ~1Hz from
* the fleet tick so it stays glued to the moving aircraft.
* position. The newest reports run ahead of the displayed aircraft (the
* delayed clock) — drawing them verbatim makes the trail extend in FRONT of
* the icon.
*/
function _refreshTrailDisplay() {
// The trail BODY is the accumulated fixes at or before the delayed display time
// (now − RENDER_DELAY_SEC); newer fixes are AHEAD of the icon, so drawing them
// would push the trail in front of the plane. The cheap per-frame trail head
// line bridges the last body point to the delayed dead-reckoned head, so the
// body rebuilds only on a real fix or when the display time passes one, never
// at motion cadence.
// The trail BODY is the reports at or before the delayed display time,
// joined along the curve the aircraft is drawn along; newer reports are
// AHEAD of the icon. The per-frame head runs on along the same curve from
// the last body report to the icon, so the body rebuilds only on a real
// report or when the display time passes one, never at motion cadence.
// A break lifts the pen: each segment is its own line, nothing between them.
if (!flightState._trail) return;
flightState._trailBodyCount = _trailBodyCountNow();
@@ -426,18 +390,12 @@ export function createTracking({
);
}
/** Fixes at or before the time the aircraft is drawn (now − RENDER_DELAY_SEC),
* less the newest recorded points inside its 3D model. */
/** Reports at or before the time the aircraft is drawn (now − the display delay). */
function _trailBodyCountNow() {
return trailBodyCountOutsideModel(
return trailBodyCount(
flightState._trailFixes,
trailBodyCount(
flightState._trailFixes,
flightState.now() - displayDelayMs(flightState),
),
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
flightState.now() - displayDelayMs(flightState),
);
}
@@ -461,10 +419,9 @@ export function createTracking({
parts.motion._trackedTrailCached() ||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
if (!head) return [];
// The last body point (a report, or where the icon was drawn a moment
// ago) → the icon. No head across a break: a body point more than 150 km
// away, or too long ago or too far to be one path, stays detached; none
// while the aircraft holds at its last point.
// The last body report → the icon. No head across a break: a body point
// more than 150 km away, or too long ago or too far to be one path, stays
// detached; none while the aircraft holds at its last point.
const last = trailHeadStartFix(
flightState._trailFixes,
head,
@@ -472,22 +429,19 @@ export function createTracking({
flightState._trailBodyCount,
);
if (!last) return [];
// 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
// START is what slides, from nothing on a parked contact out to the
// whole segment once it has cleared its own envelope.
// See trailHeadStart. Read `head` in place and clone only on the draw
// path — a suppressed parked contact runs this every frame.
const from = trailHeadStart(
return trailHeadLine(
last.position,
// Along the curve the icon is drawn along, to where it is now.
trailHeadCurvePoints(
flightState._trailFixes,
flightState._trailBodyCount,
flightState.now() - displayDelayMs(flightState),
),
head,
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
flightState._scratchTrailHead,
);
if (!from) return [];
return [from, clone(head)];
}
/** Each drawn frame, before it draws: the trail moved on, then the live
@@ -507,11 +461,9 @@ export function createTracking({
function _startTrail(icao24) {
flightState._trailBackfillToken += 1;
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
const history = flightState._positionHistory.get(icao24) || [];
// Seed every report. The body only draws those at or before the delayed
// display time (now − RENDER_DELAY_SEC); newer ones join it as the display
// display time (now − displayDelayMs); newer ones join it as the display
// passes them. A synthetic forward fix (it carries `reportEpochMs`) is a
// motion aid, never a report. A report drawn at an invented height keeps
// no position and breaks the line.
@@ -522,7 +474,11 @@ export function createTracking({
clone(fix.position),
historyFixEpochMs(fix),
TRAIL_MAX_POINTS,
{ nullAltitude: fix.inventedHeight === true, onGround: fix.onGround },
{
nullAltitude: fix.inventedHeight === true,
onGround: fix.onGround,
track: fix.track,
},
);
}
if (!flightState._trail && flightState._viewer) {
@@ -671,8 +627,6 @@ export function createTracking({
function _clearTrail() {
flightState._trailBackfillToken += 1;
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
if (flightState._trail) flightState._trail.clear();
flightState._trailHeadOff?.();
flightState._trailHeadOff = null;
+117 -111
View File
@@ -8,8 +8,9 @@ import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
// Between reports, a tracked trail is the path the icon was actually drawn
// along: the real display position, recorded as the frames go by. These tests
// A tracked trail is the aircraft's reports joined along the curve the icon
// is drawn along between them, so the icon always sits on its trail and a
// late report can never leave a kink. These tests
// drive the real motion and display path frame by frame.
const SEC = 1000;
@@ -169,6 +170,42 @@ function harness({
};
}
/**
* The report a plane at `from` (speed and track as reported) gives at `toMs`
* after a constant turn at `rateDps` (negative left), with `trackDeg` its track.
*/
function turnedFix(from, toMs, rateDps, trackDeg) {
const seconds = (toMs - from.epochMs) / SEC;
const turned = (rateDps * seconds * Math.PI) / 180;
const r = from.velocity / Math.abs((rateDps * Math.PI) / 180);
const h = (from.track * Math.PI) / 180;
const fwd = [Math.sin(h), Math.cos(h)];
const side = Math.sign(rateDps);
// To the right of the heading for a right turn, the left for a left one.
const right = [Math.cos(h), -Math.sin(h)];
const along = r * Math.sin(Math.abs(turned));
const across = side * r * (1 - Math.cos(turned));
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(from.position);
const p = Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(
fwd[0] * along + right[0] * across,
fwd[1] * along + right[1] * across,
0,
),
new Cesium.Cartesian3(),
);
const c = Cesium.Cartographic.fromCartesian(p);
return fix(
toMs,
Cesium.Math.toDegrees(c.latitude),
Cesium.Math.toDegrees(c.longitude),
Cesium.Cartographic.fromCartesian(from.position).height,
from.velocity,
trackDeg,
);
}
/** Distance from p to the nearest point of a polyline. */
function distanceToPath(p, path) {
let best = Infinity;
@@ -215,6 +252,23 @@ function assertNoSpur(line, label) {
}
}
/** No vertex of `line` turns it more than `maxDeg` (steps under 1 m skipped). */
function assertSmooth(line, maxDeg, label) {
const u = new Cesium.Cartesian3();
const v = new Cesium.Cartesian3();
for (let i = 1; i < line.length - 1; i++) {
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
const lu = Cesium.Cartesian3.magnitude(u);
const lv = Cesium.Cartesian3.magnitude(v);
if (!(lu > 1 && lv > 1)) continue;
const deg =
(Math.acos(Math.min(1, Cesium.Cartesian3.dot(u, v) / (lu * lv))) * 180) /
Math.PI;
assert.ok(deg <= maxDeg, `${label}: ${deg.toFixed(1)}° at vertex ${i}`);
}
}
const indexOfPoint = (line, p) =>
line.findIndex((q) => Cesium.Cartesian3.distance(p, q) < 0.01);
@@ -242,64 +296,40 @@ function departure() {
return { fixes, info };
}
test('a report newer than the display time arrives mid-turn: the trail between the two reports stays on the drawn arc', () => {
test('a report from a turn lands while the icon coasts: the trail runs report to report along their curve, with no kink, and the icon is on it', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
// 40 s of turn with no new report: the icon flies the arc.
// 40 s with no new report: past it, the icon flies straight on.
h.run(start + 40 * SEC);
const arc = h.drawn.slice();
// The next report is where the plane really was 60 s after the last one,
// still ahead of the display time (normal 30 s delay, slow feed). The icon
// now interpolates the straight line between the two reports and is eased
// onto it.
const at60 = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(T0 + 150 * SEC)),
);
const c = Cesium.Cartographic.fromCartesian(at60);
const report = fix(
T0 + 150 * SEC,
Cesium.Math.toDegrees(c.latitude),
Cesium.Math.toDegrees(c.longitude),
c.height,
112,
220,
);
// still ahead of the display time: through a 2°/s left turn, heading 220°.
const report = turnedFix(fixes[3], T0 + 150 * SEC, -2, 220);
fixes.push(report);
info.true_track = 220;
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
{ track: 220 },
);
// The display passes the new report.
h.run(start + 75 * SEC);
const line = h.bodyPoints();
const from = indexOfPoint(line, fixes[3].position);
const to = indexOfPoint(line, report.position);
assert.ok(from >= 0 && to > from, 'both reports are on the trail');
const between = line.slice(from, to + 1);
// Every vertex between the reports is where the icon was drawn...
const drawnPath = [fixes[3].position, ...h.drawn, report.position];
for (const vertex of between) {
const off = distanceToPath(vertex, drawnPath);
assert.ok(
off < 50,
`trail vertex ${off.toFixed(0)} m off the drawn path`,
);
}
// ...and the arc the icon flew is still there: no straight chord. (The
// arc strays far from the chord, so a chord would fail this.)
const a = indexOfPoint(line, fixes[3].position);
const b = indexOfPoint(line, report.position);
assert.ok(a >= 0 && b > a, 'both reports are on the trail');
const between = line.slice(a, b + 1);
// A curve, not the chord, and smooth: no vertex turns more than 3°.
const chord = [fixes[3].position, report.position];
assert.ok(Math.max(...arc.map((p) => distanceToPath(p, chord))) > 300);
// The last 10 s of the arc are exempt: the correction pulled the icon back
// over them, and keeping them would fold the line back on itself.
for (const point of arc.slice(0, -100)) {
const off = distanceToPath(point, between);
assert.ok(off < 50, `drawn arc point ${off.toFixed(0)} m from the trail`);
assert.ok(Math.max(...between.map((p) => distanceToPath(p, chord))) > 300);
assertSmooth(between, 3, 'trail');
// Eased onto the curve, the icon is drawn on its trail.
const trail = [...line, ...h.head()];
for (const p of h.drawn.slice(-100)) {
const off = distanceToPath(p, trail);
assert.ok(off < 3, `drawn ${off.toFixed(1)} m off the trail`);
}
assertNoSpur(line, 'trail');
assertNoSpur(h.head(), 'head');
@@ -361,31 +391,30 @@ test('a fresh report after a hold resumes with no backward spur', () => {
}
});
test('with the head hidden the body keeps advancing, and untracking clears the recording', () => {
test('with the head hidden the body moves on as the display passes reports, and untracking clears the trail', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
// Drawn 30 s after the first report: the body holds the first two.
const start = T0 + 30 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
h.run(start + 5 * SEC);
const before = h.bodyPoints().at(-1);
// Cockpit view: the head is hidden and its callback never runs.
h.run(start + 30 * SEC, { readHead: false });
// The body's end keeps following the icon; straight stretches are thinned.
const end = h.bodyPoints().at(-1);
h.run(start + 1 * SEC);
assert.ok(
Cesium.Cartesian3.distance(end, before) > 1_000,
Cesium.Cartesian3.distance(h.bodyPoints().at(-1), fixes[1].position) <
0.01,
);
// Cockpit view: the head is hidden, the body still moves on.
h.run(start + 61 * SEC, { readHead: false });
assert.ok(
Cesium.Cartesian3.distance(h.bodyPoints().at(-1), fixes[3].position) <
0.01,
'the body stopped advancing',
);
assert.ok(Cesium.Cartesian3.distance(end, h.drawn.at(-1)) < 300);
h.tracking._clearTrail();
assert.equal(h.flightState._trailFixes.length, 0);
// A new track of the same plane starts from reports only.
// A new track of the same plane starts from its reports.
h.tracking._startTrail(ICAO);
assert.equal(
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
0,
);
assert.equal(h.flightState._trailFixes.length, fixes.length);
} finally {
h.restore();
}
@@ -452,7 +481,6 @@ test('a report the display already passed replaces the guess drawn after it, wit
try {
h.tracking._startTrail(ICAO);
h.run(start + 40 * SEC);
const displayMs = T0 + 130 * SEC;
// A report for 10 s before the display time, 400 m inside the drawn arc.
const guess = h.motion._deadReckon(
ICAO,
@@ -475,16 +503,11 @@ test('a report the display already passed replaces the guess drawn after it, wit
report.epochMs,
);
h.run(start + 55 * SEC);
const recorded = h.flightState._trailFixes.filter((entry) => entry.drawn);
// Nothing recorded between the report and the end of the ease.
// Reports only: nothing drawn between them is kept.
assert.deepEqual(
recorded
.filter(
(entry) =>
entry.timeMs > report.epochMs && entry.timeMs < displayMs + 900,
)
.map((entry) => entry.timeMs - T0),
[],
h.flightState._trailFixes.map((entry) => entry.timeMs),
fixes.map((f) => f.epochMs),
'the trail holds the reports and nothing else',
);
const line = h.bodyPoints();
assert.ok(indexOfPoint(line, report.position) >= 0);
@@ -494,7 +517,7 @@ test('a report the display already passed replaces the guess drawn after it, wit
}
});
test('a history report at an invented height is seeded with no position, and nothing is recorded next to it', () => {
test('a history report at an invented height is seeded with no position, and the trail holds only reports', () => {
const { fixes, info } = departure();
fixes[3].inventedHeight = true;
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
@@ -507,9 +530,10 @@ test('a history report at an invented height is seeded with no position, and not
assert.equal(seeded.position, null);
assert.equal(seeded.nullAltitude, true);
h.run(start + 10 * SEC);
assert.equal(
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
0,
assert.deepEqual(
h.flightState._trailFixes.map((entry) => entry.timeMs),
fixes.map((f) => f.epochMs),
'the trail holds the reports and nothing else',
);
} finally {
h.restore();
@@ -570,15 +594,14 @@ test('a plane that stops reporting keeps moving dimmed as STALE from its first m
);
// The coast ends 300 s past the report; the plane stops there.
h.run(pastReport(310));
const recorded = h.flightState._trailFixes.filter((e) => e.drawn).length;
h.run(pastReport(330));
assert.ok(
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-50)) < 0.01,
);
assert.equal(
h.flightState._trailFixes.filter((e) => e.drawn).length,
recorded,
'the trail kept recording a stopped plane',
assert.deepEqual(
h.flightState._trailFixes.map((entry) => entry.timeMs),
fixes.map((f) => f.epochMs),
'the trail holds the reports and nothing else',
);
// 330 s of display past the report is 330 s + the display delay of wall time.
const minutes = Math.floor((330 + RENDER_DELAY_SEC) / 60);
@@ -618,7 +641,7 @@ test('a plane held at its last report shows SIGNAL LOST in seconds under a minut
}
});
test('a report arriving 200 s into a coast: the plane eases onto it and the trail drops what was drawn after it', () => {
test('a report arriving 200 s into a coast: the plane eases onto it with no jump, and the trail runs report to report', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
@@ -645,27 +668,29 @@ test('a report arriving 200 s into a coast: the plane eases onto it and the trai
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
{ track: 90 },
);
// Reports only: nothing the coast drew is kept.
assert.deepEqual(
h.flightState._trailFixes.filter(
(e) => e.drawn && e.timeMs > report.epochMs,
),
[],
h.flightState._trailFixes.map((e) => e.timeMs),
fixes.map((f) => f.epochMs),
);
const from = h.drawn.length;
h.run(pastReport(203));
h.run(pastReport(240));
const after = h.drawn.slice(from - 1);
// Frames are 100 ms apart: 14 m at 140 m/s. The ease adds at most 30 %.
for (let i = 1; i < after.length; i++)
assert.ok(
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 400,
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 14 * 1.5,
'the plane jumped instead of easing',
);
// Eased onto the path from the report: 13 s on from it at 140 m/s.
// Eased onto the path from the report: 50 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
assert.ok(
Math.abs(off - 140 * 13) < 150,
Math.abs(off - 140 * 50) < 150,
`${off.toFixed(0)} m from the report`,
);
assert.ok(indexOfPoint(h.bodyPoints(), report.position) >= 0);
} finally {
h.restore();
}
@@ -778,7 +803,7 @@ test('a stalled feed dims the tracked plane as STALE', () => {
}
});
test('a report arriving after the plane has stopped: it eases in with no spur, and the trail keeps everything up to the stop', () => {
test('a report arriving after the plane has stopped far back: it jumps onto the new path, and the trail runs report to report with no spur', () => {
const { fixes, info } = outOfCoverage();
info.lastContactEpochMs = fixes.at(-1).epochMs;
const h = harness({ fixes, info, nowMs: pastReport(-5) });
@@ -787,14 +812,8 @@ test('a report arriving after the plane has stopped: it eases in with no spur, a
h.run(pastReport(360));
const stop = Cesium.Cartesian3.clone(h.drawn.at(-1));
assert.ok(Cesium.Cartesian3.distance(stop, h.drawn.at(-100)) < 0.01);
const kept = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => Cesium.Cartesian3.clone(e.position));
// The thinned straight coast, recorded up to where the plane stopped.
assert.ok(kept.length >= 2);
assert.ok(Cesium.Cartesian3.distance(kept.at(-1), stop) < 300);
// Heard again, for 20 s before the display time: the plane flew on, a
// little north of its old heading.
// little north of its old heading, 8 km past where it stopped.
const at = T0 + 30 * SEC + 340 * SEC;
const lonDeg =
-108.05 + (140 * 340) / (111_320 * Math.cos((43 * Math.PI) / 180));
@@ -803,26 +822,13 @@ test('a report arriving after the plane has stopped: it eases in with no spur, a
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
// Nothing was recorded after the stop, so nothing is dropped.
const after = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => e.position);
assert.equal(after.length, kept.length);
kept.forEach((p, i) =>
assert.ok(Cesium.Cartesian3.distance(p, after[i]) < 0.01),
{ track: 90 },
);
const from = h.drawn.length;
h.run(pastReport(365));
const eased = h.drawn.slice(from - 1);
const jump = Cesium.Cartesian3.distance(eased[0], eased.at(-1));
for (let i = 1; i < eased.length; i++)
assert.ok(
Cesium.Cartesian3.distance(eased[i], eased[i - 1]) < jump / 2,
'the plane jumped instead of easing',
);
// On the path from the report: 25 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(eased.at(-1), report.position);
const after = h.drawn.slice(from);
// On the path from the report at once: 25 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
assert.ok(Math.abs(off - 140 * 25) < 150, `${off.toFixed(0)} m`);
assertNoSpur(h.bodyPoints(), 'trail');
assertNoSpur(h.head(), 'head');
+6
View File
@@ -0,0 +1,6 @@
import { feedLatencyTests } from '../../testSupport/aircraftFeedLatency.mjs';
import { RENDER_DELAY_SEC } from './policy.js';
// A slow live feed, as measured: reports about 90 s old every poll, now and
// then a fresh fallback feed, a report that does not move on, or an outage.
feedLatencyTests('military', RENDER_DELAY_SEC);
+1 -2
View File
@@ -2,7 +2,6 @@ import { createAircraftIcons } from '../../data/aircraftIconLayer.js';
import {
COCKPIT_CONTACT_SIZE_PX,
COURSE_MAX_DPS,
RENDER_DELAY_SEC,
STALE_ALPHA,
followsClock,
} from './policy.js';
@@ -14,7 +13,7 @@ export function createIcons({ flightState, services, parts }) {
services,
parts,
layerId: 'military',
renderDelaySec: RENDER_DELAY_SEC,
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
staleAlpha: STALE_ALPHA,
courseMaxDps: COURSE_MAX_DPS,
+71 -24
View File
@@ -1,11 +1,16 @@
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { renderedFrames } from '../../data/renderedFrames.js';
import {
motionCourse,
motionPosition,
} from '../../render/motion/iconMotion.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { eastNorthUp, framePoint } from '../../geo/frames.js';
import {
addSeconds,
julianLessThan,
julianFromEpochMs,
julianToEpochMs,
secondsDifference,
} from '../../geo/julian.js';
import {
@@ -25,6 +30,8 @@ import {
staleHoldsForFix,
arcOffsetEnu,
courseSlewCapDps,
RECOVER_SNAP_M,
recoveryMs,
limitCourseStep,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
@@ -102,8 +109,8 @@ export function createMotion({
/**
* Dead-reckon an aircraft's current position using ENU (East-North-Up) frame math.
*
* Renders one poll interval behind real time so positions interpolate between
* two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale). When the
* Renders behind real time, as late as the feed is (displayDelayMs), so
* positions interpolate between two KNOWN fixes whenever possible. When the
* newest fix is older than the delayed render time (stale position), projects
* forward using the aircraft's ground speed and track through the freshest
* source contact plus a bounded grace window.
@@ -113,7 +120,7 @@ export function createMotion({
* @returns {{x: number, y: number, z: number}|null} Estimated current ECEF position, or null if no history
*/
function _deadReckon(icao24, result) {
function _deadReckon(icao24, result, sampledRenderTime) {
const history = flightState._positionHistory.get(icao24);
const info = flightState.records.data.get(icao24);
if (!history || history.length === 0) {
@@ -124,15 +131,26 @@ export function createMotion({
}
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 = addSeconds(
julianFromEpochMs(flightState.now()),
-displayDelayMs(flightState) / 1000,
flightState._scratchRenderTime,
);
// Render behind real time, as late as the feed is (displayDelayMs), so we
// interpolate between two KNOWN fixes whenever possible.
const renderTime =
sampledRenderTime ??
addSeconds(
julianFromEpochMs(flightState.now()),
-displayDelayMs(flightState) / 1000,
flightState._scratchRenderTime,
);
const regime = _motionRegime(history, info, renderTime);
if (regime.kind === 'between' && regime.piece) {
// Along the curve between the two reports, as the icon and the trail.
const ms = julianToEpochMs(renderTime);
const segment = regime.piece.segment;
flightState._drCourseDeg = motionCourse(segment, undefined, ms);
flightState._drSpeedMps = segment.speedMps;
flightState._drCourseHold = segment.speedMps < COURSE_HOLD_SPEED_MPS;
return copyInto(motionPosition(segment, null, ms), out);
}
if (regime.kind === 'between') {
const { a, b, span } = regime;
const t = span > 0 ? secondsDifference(renderTime, a.time) / span : 1.0;
@@ -244,7 +262,7 @@ export function createMotion({
}
/**
* True while the tracked aircraft's delayed display time (now − RENDER_DELAY_SEC)
* True while the tracked aircraft's delayed display time (now − displayDelayMs)
* predates its oldest real fix — _deadReckon is extrapolating backward with no real
* history yet behind the displayed icon, so the trail must draw nothing.
* @returns {boolean}
@@ -332,35 +350,64 @@ export function createMotion({
// which plays faster than the wall clock when following it at a rate.
const worldMs = followsClock(flightState) ? flightState.now() : nowMs;
const info = flightState.records.data.get(icao24);
const dtSec = Math.max(
0.001,
(worldMs - flightState._drPrevWorldMs) / 1000,
);
let snapped = false;
if (sameTrack) {
const dtSec = Math.max(
0.001,
(worldMs - flightState._drPrevWorldMs) / 1000,
);
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;
// Plausible single-frame motion (m): its speed × frame Δt, half again
// for slack, plus 5 m. More is a jump (a new report put it elsewhere).
const plausible = speed * dtSec * 1.5 + 5;
if (distance(raw, flightState._drPrevRaw) > plausible) {
// Discontinuity — re-anchor so the DISPLAYED position stays continuous, then decay.
copyInto(
sub(flightState._drPrevDisplay, raw),
flightState._drCorrection,
);
// Discontinuity — re-anchor so the DISPLAYED position stays continuous,
// then ease onto the new path no faster than a little over its speed;
// farther off than RECOVER_SNAP_M it is a break, and it jumps.
// From where the icon would be this frame had it carried on as it
// was moving, not from where it was last frame: it never stands
// still for a frame.
const anchor =
flightState._drPrevStepSec > 0
? add(
flightState._drPrevDisplay,
scale(
flightState._drPrevStep,
dtSec / flightState._drPrevStepSec,
),
)
: flightState._drPrevDisplay;
const errorM = distance(anchor, raw);
snapped = errorM >= RECOVER_SNAP_M;
copyInto(snapped ? vec() : sub(anchor, raw), flightState._drCorrection);
flightState._drCorrectionStartMs = nowMs;
flightState._drCorrectionMs = Math.max(
DR_CORRECTION_MS,
recoveryMs(errorM, speed),
);
}
} else {
copyInto(vec(), flightState._drCorrection);
flightState._drCorrectionStartMs = nowMs - DR_CORRECTION_MS; // fully decayed
flightState._drCorrectionMs = DR_CORRECTION_MS;
}
const elapsed = nowMs - flightState._drCorrectionStartMs;
const factor =
elapsed >= DR_CORRECTION_MS ? 0 : 1 - elapsed / DR_CORRECTION_MS;
const easeMs = flightState._drCorrectionMs ?? DR_CORRECTION_MS;
const factor = elapsed >= easeMs ? 0 : 1 - elapsed / easeMs;
const display = copyInto(
add(raw, scale(flightState._drCorrection, factor)),
flightState._trackedPosHolder,
);
// How the icon moved this frame, to carry it on through a re-anchor.
if (sameTrack && !snapped) {
copyInto(
sub(display, flightState._drPrevDisplay),
flightState._drPrevStep,
);
flightState._drPrevStepSec = dtSec;
} else flightState._drPrevStepSec = 0;
copyInto(raw, flightState._drPrevRaw);
copyInto(display, flightState._drPrevDisplay);
flightState._drPrevMs = nowMs;
+21 -13
View File
@@ -14,9 +14,9 @@ const rgba = (css, alpha) =>
* Renders aircraft as amber chevrons in one GPU icon set (iconSet.js), whose
* shader dead-reckons and orients every row. Supports click-to-track: selecting an aircraft
* spawns an Entity the camera follows, whose position is driven by a
* dead-reckoning CallbackProperty. The whole fleet renders at
* now - RENDER_DELAY_SEC so positions interpolate BETWEEN two known fixes
* instead of extrapolating ahead and snapping back when the next poll lands.
* dead-reckoning CallbackProperty. The whole fleet renders at now − the
* display delay so positions run BETWEEN two known fixes instead of
* extrapolating ahead and snapping back when the next poll lands.
*/
/** @constant {number} Milliseconds to wait before retrying after a transient error */
@@ -123,7 +123,7 @@ export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = Object.freeze({
// ---------------------------------------------------------------------------
// Track-history trail state (PRD WS-F F2/F4): a fading polyline behind the
// tracked aircraft. The accumulation array is intentionally SEPARATE from
// _positionHistory (capped at POSITION_HISTORY_LIMIT=5 for dead reckoning)
// _positionHistory (capped at POSITION_HISTORY_LIMIT for drawing)
// so the visible trail can grow to TRAIL_MAX_POINTS fixes.
// ---------------------------------------------------------------------------
@@ -136,25 +136,33 @@ export const TRAIL_COLOR = '#FFB800';
export const TRAIL_MAX_POINTS = 2000;
// ---------------------------------------------------------------------------
// Render-behind smoothing (mirrors flights.js): the fleet renders at
// now - RENDER_DELAY_SEC so positions interpolate BETWEEN two known fixes
// instead of extrapolating ahead and snapping back when the next poll lands.
// Removing the delay reintroduces the back/forward oscillation and is a
// regression.
// Render-behind smoothing (mirrors flights): the fleet renders at now − the
// display delay so positions run BETWEEN two known fixes instead of
// extrapolating ahead and snapping back when the next poll lands. The delay
// follows how late the feed really is (data/displayDelay.js), never under
// RENDER_DELAY_SEC, and every consumer shares it. Removing the delay
// reintroduces the back/forward oscillation and is a regression.
// ---------------------------------------------------------------------------
/** @constant {number} Display latency in seconds (= one poll interval). */
/** @constant {number} The shortest display delay in seconds (one poll interval). */
export const RENDER_DELAY_SEC = 15;
/** @constant {number} How often the feed is polled (ms). */
export const POLL_INTERVAL_MS = 15_000;
/** Whether the layer shows the world clock's time instead of the live feed:
* its source declares a timeline and the clock is away from live. */
export const followsClock = (state) => state.timeline?.active() === true;
/** How far behind the time contacts are drawn: RENDER_DELAY_SEC live, none
* following the clock, whose snapshots are loaded ahead of the time. */
/** How far behind the time contacts are drawn (ms): the feed's display
* delay live, none following the clock, whose snapshots are loaded ahead
* of the time. */
export const displayDelayMs = (state) =>
followsClock(state) ? 0 : RENDER_DELAY_SEC * 1000;
followsClock(state)
? 0
: (state._displayDelay?.currentMs ?? RENDER_DELAY_SEC * 1000);
/** @constant {number} Polls an aircraft may miss before removal (transient adsb.lol dropouts). */
+2 -1
View File
@@ -15,6 +15,7 @@ import {
import {
LANDED_ALT_MAX_FT,
LANDED_SPEED_MAX_MPS,
POLL_INTERVAL_MS,
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
@@ -234,7 +235,7 @@ export function createQueries({
source: flightState.feed._lastSource,
/** @type {number} Polling interval in ms between API fetches */
updateInterval: 15000,
updateInterval: POLL_INTERVAL_MS,
/** @deprecated Compatibility alias for {@link enable}. */
show(viewer) {
+3 -1
View File
@@ -1,6 +1,8 @@
export const GROUND_FLOOR_WARM_MAX_ALT_M = 4500;
export const POSITION_HISTORY_LIMIT = 5;
/** Maximum feed fixes retained for drawing: enough to reach back over the
* longest display delay at one report per poll. */
export const POSITION_HISTORY_LIMIT = 24;
export const LANDED_MISSING_POLL_LIMIT = 1;
+53 -22
View File
@@ -7,6 +7,30 @@ import {
} from '../../data/motionModel.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
/**
* Note how late each report in a live snapshot is, and aim the display delay
* again, before any contact is planned with it: a layer drawing nothing yet
* takes the new delay at once.
*/
function noteDelivery(flightState, snapshot) {
const delay = flightState._displayDelay;
if (!delay) return;
const receiptMs = Date.now();
for (const observation of snapshot.records) {
const reportMs = observation.positionTimeMs;
if (!(Number.isFinite(reportMs) && reportMs > 0)) continue;
const history = flightState._positionHistory.get(observation.id);
const previous = history && newestReport(history);
delay.noteReport(
receiptMs,
reportMs,
previous ? Math.trunc(previous.epochMs) : undefined,
);
}
delay.settle(receiptMs, { jump: !flightState._icons.count });
}
/** Apply military record changes to the layer's drawing and existing follow operations. */
export function createMilitarySnapshotRenderer({
@@ -32,6 +56,9 @@ export function createMilitarySnapshotRenderer({
const currentIcaos = new Set();
const receiptNowMs = snapshot.observedAtMs;
records.beginSnapshot(snapshot.observedAtMs);
// Live, the display delay follows how late this delivery's reports are.
if (!replace && !followsClock(flightState))
noteDelivery(flightState, snapshot);
// Field-test fix (RS46): coarse floor cells to warm for the below-ground
// clamp — collected during the loop (low airborne contacts only),
// batch-resolved once after it. Never a fetch inside the loop.
@@ -69,34 +96,37 @@ export function createMilitarySnapshotRenderer({
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
// Whole milliseconds, as the fix times are kept.
const report = newestReport(history);
// Whole milliseconds, as the fix times are kept. A report newer than
// the last report goes in, past any synthetic fix after it.
if (
!newest ||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(newest))
!report ||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(report))
) {
// Per-fix kinematics: the fix's own velocity/track ride along so the
// extrapolation paths use the values that BELONG to the fix they
// extend, not whatever the latest poll reported.
history.push({
...motion._historyFix(
fixEpochMs,
position,
meta.speedMps,
meta.track,
),
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
// Whether this report was on the ground: a trail backfill joins it
// only across a landing or take-off it saw.
onGround: meta.onGround === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
pushReport(
history,
{
...motion._historyFix(
fixEpochMs,
position,
meta.speedMps,
meta.track,
),
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
// Whether this report was on the ground: a trail backfill joins it
// only across a landing or take-off it saw.
onGround: meta.onGround === true,
},
POSITION_HISTORY_LIMIT,
);
// Turn rate from the fix-track history — computed once per new fix
// (≤5 samples), consumed by the extrapolation paths at tick rate.
meta.turnRateDps = turnRateFromFixHistory(history);
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
// Trail accumulation is separate from the 5-fix DR history (PRD F2)
// so the visible trail keeps growing while tracked. Round 2
// (owner): ground traffic appends too — taxi history stays live
@@ -105,6 +135,7 @@ export function createMilitarySnapshotRenderer({
if (isTracked)
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.track,
});
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
@@ -134,7 +165,7 @@ export function createMilitarySnapshotRenderer({
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
}
}
}
+7 -1
View File
@@ -191,6 +191,12 @@ test('a holding military contact draws no head and its trail ends at the last re
layer: {},
});
tracking._startTrail('00a003');
assert.equal(calls.at(-1).length, 3);
// The body runs through every report and ends at the last one.
const body = calls.at(-1);
for (const report of fixes)
assert.ok(
body.some((p) => Cesium.Cartesian3.distance(p, report.position) < 0.01),
);
assert.ok(Cesium.Cartesian3.distance(body.at(-1), last) < 0.01);
assert.deepEqual(tracking._trailHeadPositions(), []);
});
+18 -12
View File
@@ -1,6 +1,8 @@
import { MilitaryFlightRecords } from './records.js';
import { createMilitaryFeed } from './ingestion.js';
import { worldTimeFor } from '../../time/worldClock.js';
import { createDisplayDelay } from '../../data/displayDelay.js';
import { POLL_INTERVAL_MS, RENDER_DELAY_SEC } from './policy.js';
export function createFlightState({ source, services }) {
const { createGroundSnap } = services.groundSnap;
@@ -13,6 +15,12 @@ export function createFlightState({ source, services }) {
});
/** The time contacts are drawn behind by the render delay, in epoch ms. */
flightState.now = worldTimeFor('military');
/** How far behind real time live contacts are drawn: follows how late the
* feed's reports arrive (see displayDelayMs in policy.js). */
flightState._displayDelay = createDisplayDelay({
floorMs: RENDER_DELAY_SEC * 1000,
pollMs: POLL_INTERVAL_MS,
});
/** Follows the world clock while the source declares a timeline (set by the
* layer); see followsClock and displayDelayMs in policy.js. */
flightState.timeline = null;
@@ -132,10 +140,9 @@ export function createFlightState({ source, services }) {
flightState._trailHeadOff = null;
/** @type {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, drawn?: boolean}[]}
* Chronological tracked-aircraft trail (oldest first): reports, and
* (`drawn`) where the icon was drawn between them; `breakBefore` starts a
* new segment. */
/** @type {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, track?: number}[]}
* Chronological tracked-aircraft trail (oldest first): reports, joined along
* the curve the icon is drawn along; `breakBefore` starts a new segment. */
flightState._trailFixes = [];
@@ -143,14 +150,6 @@ export function createFlightState({ source, services }) {
flightState._trailBodyCount = 0;
/** @type {{x: number, y: number, z: number}|null} Where the tracked icon was last recorded into the trail. */
flightState._trailRecordPosition = null;
/** @type {number} Display time (epoch ms) of that recording. */
flightState._trailRecordMs = -Infinity;
/** @type {string|undefined} The stale cue last written into the tracked label (see `_staleCueTick`). */
flightState._trackedStaleCueText = undefined;
@@ -263,10 +262,17 @@ export function createFlightState({ source, services }) {
flightState._drCorrectionStartMs = 0;
/** How long (ms) the correction under way takes to ease out. */
flightState._drCorrectionMs = 0;
flightState._drPrevRaw = { x: 0, y: 0, z: 0 };
flightState._drPrevDisplay = { x: 0, y: 0, z: 0 };
/** How the tracked icon moved over the last frame, and that frame's length (s; 0 for none). */
flightState._drPrevStep = { x: 0, y: 0, z: 0 };
flightState._drPrevStepSec = 0;
flightState._drPrevMs = 0;
/** World time of that frame: the wall clock live, the cursor following the clock. */
+41 -84
View File
@@ -19,8 +19,8 @@ import {
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { julianToEpochMs } from '../../geo/julian.js';
import { renderedFrames } from '../../data/renderedFrames.js';
import { clone, distance, distanceSquared, vec } from '../../geo/vector.js';
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
import { clone, distanceSquared, vec } from '../../geo/vector.js';
import { trailHeadLine } from '../../data/modelVisualAnchor.js';
import {
isTrackingSelectionGesture,
isTrackingClickGesture,
@@ -28,7 +28,6 @@ import {
import { inputFor } from '../../input/dispatcher.js';
import {
TRAIL_MAX_POINTS,
DR_CORRECTION_MS,
displayDelayMs,
followsClock,
STALE_ALPHA,
@@ -41,15 +40,11 @@ import {
historyFixEpochMs,
insertTrailFix,
joinTrailBackfill,
recordTrailPoint,
trailBackfillFixes,
trailBodyCount,
trailBodyCountOutsideModel,
trailBodySegments,
trailHeadCurvePoints,
trailHeadStartFix,
trailRecordingBlocked,
TRAIL_RECORD_STEP_M,
TRAIL_RECORD_STEP_MS,
} from '../../data/trailContinuity.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
import { entityRecord } from '../../data/entityRecords.js';
@@ -566,7 +561,11 @@ export function createTracking({
* drawn after it (see `insertTrailFix`).
*/
function _appendTrailFix(position, epochMs, { nullAltitude = false } = {}) {
function _appendTrailFix(
position,
epochMs,
{ nullAltitude = false, track = undefined } = {},
) {
const history = flightState._positionHistory.get(flightState._trackedIcao);
const timeMs = Number.isFinite(epochMs)
? epochMs
@@ -576,63 +575,31 @@ export function createTracking({
_trailFloorPosition(position),
timeMs,
TRAIL_MAX_POINTS,
{
nullAltitude,
displayMs: flightState.now() - displayDelayMs(flightState),
settleMs: DR_CORRECTION_MS,
},
{ nullAltitude, track },
);
_refreshTrailDisplay();
}
/**
* Per-frame trail work, run before each frame draws whether or not the
* head is visible: record where the tracked icon is drawn (at most once a
* second or every 150 m, floored like the head) and move the body on as
* the display time passes reports. The head only reads the result.
* head is visible: move the body on as the display time passes reports.
* The head only reads the result.
*/
function _trailTick() {
if (!flightState._trackedIcao || !flightState._trail) return;
const displayMs = flightState.now() - displayDelayMs(flightState);
let changed = false;
if (
flightState._trailFixes.length &&
!parts.motion._isTrackWarmingUp() &&
!trailRecordingBlocked(flightState._trailFixes, displayMs)
) {
const drawn = parts.motion._trackedDisplayPosition(
flightState._trackedIcao,
);
const last = flightState._trailRecordPosition;
if (
drawn &&
(!last ||
displayMs - flightState._trailRecordMs >= TRAIL_RECORD_STEP_MS ||
distance(last, drawn) >= TRAIL_RECORD_STEP_M)
) {
flightState._trailRecordMs = displayMs;
flightState._trailRecordPosition = clone(drawn);
changed = recordTrailPoint(
flightState._trailFixes,
_trailFloorPosition(clone(drawn)),
displayMs,
TRAIL_MAX_POINTS,
);
}
}
if (changed || _trailBodyCountNow() !== flightState._trailBodyCount)
if (_trailBodyCountNow() !== flightState._trailBodyCount)
_refreshTrailDisplay();
}
/**
* Renders the trail BODY — the accumulated fixes at or before the delayed display
* time (now − RENDER_DELAY_SEC). Newer fixes are AHEAD of the icon, so drawing them
* would push the trail in FRONT of the plane. The cheap per-frame trail head line
* bridges the last body point to the delayed dead-reckoned head, so the body
* rebuilds only on a real fix or when the display time passes one, never at motion
* cadence. A break lifts the pen: each segment is its own line, nothing between
* them.
* Renders the trail BODY — the reports at or before the delayed display time,
* joined along the curve the aircraft is drawn along. Newer reports are AHEAD of
* the icon, so drawing them would push the trail in FRONT of the plane. The
* per-frame head runs on along the same curve from the last body report to the
* icon, so the body rebuilds only on a real report or when the display time
* passes one, never at motion cadence. A break lifts the pen: each segment is
* its own line, nothing between them.
*/
function _refreshTrailDisplay() {
@@ -644,18 +611,12 @@ export function createTracking({
);
}
/** Fixes at or before the time the aircraft is drawn (now − RENDER_DELAY_SEC),
* less the newest recorded points inside its 3D model. */
/** Reports at or before the time the aircraft is drawn (now − the display delay). */
function _trailBodyCountNow() {
return trailBodyCountOutsideModel(
return trailBodyCount(
flightState._trailFixes,
trailBodyCount(
flightState._trailFixes,
flightState.now() - displayDelayMs(flightState),
),
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
flightState.now() - displayDelayMs(flightState),
);
}
@@ -679,10 +640,9 @@ export function createTracking({
parts.motion._trackedTrailCached() ||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
if (!head) return [];
// The last body point (a report, or where the icon was drawn a moment
// ago) → the icon. No head across a break: a body point more than 150 km
// away, or too long ago or too far to be one path, stays detached; none
// while the aircraft holds at its last point.
// The last body report → the icon. No head across a break: a body point
// more than 150 km away, or too long ago or too far to be one path, stays
// detached; none while the aircraft holds at its last point.
const last = trailHeadStartFix(
flightState._trailFixes,
head,
@@ -690,27 +650,24 @@ export function createTracking({
flightState._trailBodyCount,
);
if (!last) return [];
const start = last.position;
// 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.
// segment dives underground while taxiing. The model envelope is
// measured against the FLOORED endpoint, which is the one actually drawn.
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
// START is what slides, from nothing on a parked contact out to the
// whole segment once it has cleared its own envelope. Measured against
// the FLOORED endpoint, which is the one actually drawn.
// See trailHeadStart.
const from = trailHeadStart(
start,
return trailHeadLine(
last.position,
// Along the curve the icon is drawn along, to where it is now.
trailHeadCurvePoints(
flightState._trailFixes,
flightState._trailBodyCount,
flightState.now() - displayDelayMs(flightState),
),
end,
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
flightState._scratchTrailHead,
);
if (!from) return [];
return [from, end];
}
/** Each drawn frame, before it draws: the trail moved on, then the live
@@ -730,11 +687,9 @@ export function createTracking({
function _startTrail(icao24) {
flightState._trailBackfillToken += 1;
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
const history = flightState._positionHistory.get(icao24) || [];
// Seed every report. The body only draws those at or before the delayed
// display time (now − RENDER_DELAY_SEC); newer ones join it as the display
// display time (now − displayDelayMs); newer ones join it as the display
// passes them. A synthetic forward fix (it carries `reportEpochMs`) is a
// motion aid, never a report. A report drawn at an invented height keeps
// no position and breaks the line.
@@ -748,7 +703,11 @@ export function createTracking({
_trailFloorPosition(clone(fix.position)),
historyFixEpochMs(fix),
TRAIL_MAX_POINTS,
{ nullAltitude: fix.inventedHeight === true, onGround: fix.onGround },
{
nullAltitude: fix.inventedHeight === true,
onGround: fix.onGround,
track: fix.track,
},
);
}
if (!flightState._trail && flightState._viewer) {
@@ -899,8 +858,6 @@ export function createTracking({
function _clearTrail() {
flightState._trailBackfillToken += 1;
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
if (flightState._trail) flightState._trail.clear();
flightState._trailHeadOff?.();
flightState._trailHeadOff = null;
+103 -96
View File
@@ -8,8 +8,9 @@ import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
// A tracked military contact's trail between reports is the path its icon
// was drawn along, recorded from the real display path frame by frame.
// A tracked military contact's trail is its reports joined along the curve
// the icon is drawn along between them, so the icon always sits on its trail
// and a late report can never leave a kink.
const SEC = 1000;
const ICAO = '00a004';
@@ -154,6 +155,42 @@ function harness({ fixes, info, nowMs, ground = () => null }) {
};
}
/**
* The report a plane at `from` (speed and track as reported) gives at `toMs`
* after a constant turn at `rateDps` (negative left), with `trackDeg` its track.
*/
function turnedFix(from, toMs, rateDps, trackDeg) {
const seconds = (toMs - from.epochMs) / SEC;
const turned = (rateDps * seconds * Math.PI) / 180;
const r = from.velocity / Math.abs((rateDps * Math.PI) / 180);
const h = (from.track * Math.PI) / 180;
const fwd = [Math.sin(h), Math.cos(h)];
const side = Math.sign(rateDps);
// To the right of the heading for a right turn, the left for a left one.
const right = [Math.cos(h), -Math.sin(h)];
const along = r * Math.sin(Math.abs(turned));
const across = side * r * (1 - Math.cos(turned));
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(from.position);
const p = Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(
fwd[0] * along + right[0] * across,
fwd[1] * along + right[1] * across,
0,
),
new Cesium.Cartesian3(),
);
const c = Cesium.Cartographic.fromCartesian(p);
return fix(
toMs,
Cesium.Math.toDegrees(c.latitude),
Cesium.Math.toDegrees(c.longitude),
Cesium.Cartographic.fromCartesian(from.position).height,
from.velocity,
trackDeg,
);
}
/** Distance from p to the nearest point of a polyline. */
function distanceToPath(p, path) {
let best = Infinity;
@@ -200,6 +237,23 @@ function assertNoSpur(line, label) {
}
}
/** No vertex of `line` turns it more than `maxDeg` (steps under 1 m skipped). */
function assertSmooth(line, maxDeg, label) {
const u = new Cesium.Cartesian3();
const v = new Cesium.Cartesian3();
for (let i = 1; i < line.length - 1; i++) {
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
const lu = Cesium.Cartesian3.magnitude(u);
const lv = Cesium.Cartesian3.magnitude(v);
if (!(lu > 1 && lv > 1)) continue;
const deg =
(Math.acos(Math.min(1, Cesium.Cartesian3.dot(u, v) / (lu * lv))) * 180) /
Math.PI;
assert.ok(deg <= maxDeg, `${label}: ${deg.toFixed(1)}° at vertex ${i}`);
}
}
const indexOfPoint = (line, p) =>
line.findIndex((q) => Cesium.Cartesian3.distance(p, q) < 0.01);
@@ -227,64 +281,40 @@ function departure() {
return { fixes, info };
}
test('military: a report newer than the display time arrives mid-turn, and the trail between the reports stays on the drawn arc', () => {
test('military: a report from a turn lands while the icon coasts: the trail runs report to report along their curve, with no kink, and the icon is on it', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
// 40 s of turn with no new report: the icon flies the arc.
// 40 s with no new report: past it, the icon flies straight on.
h.run(start + 40 * SEC);
const arc = h.drawn.slice();
// The next report is where the plane really was 60 s after the last one,
// still ahead of the display time (normal 30 s delay, slow feed). The icon
// now interpolates the straight line between the two reports and is eased
// onto it.
const at60 = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(T0 + 150 * SEC)),
);
const c = Cesium.Cartographic.fromCartesian(at60);
const report = fix(
T0 + 150 * SEC,
Cesium.Math.toDegrees(c.latitude),
Cesium.Math.toDegrees(c.longitude),
c.height,
112,
220,
);
// still ahead of the display time: through a 2°/s left turn, heading 220°.
const report = turnedFix(fixes[3], T0 + 150 * SEC, -2, 220);
fixes.push(report);
info.track = 220;
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
{ track: 220 },
);
// The display passes the new report.
h.run(start + 75 * SEC);
const line = h.bodyPoints();
const from = indexOfPoint(line, fixes[3].position);
const to = indexOfPoint(line, report.position);
assert.ok(from >= 0 && to > from, 'both reports are on the trail');
const between = line.slice(from, to + 1);
// Every vertex between the reports is where the icon was drawn...
const drawnPath = [fixes[3].position, ...h.drawn, report.position];
for (const vertex of between) {
const off = distanceToPath(vertex, drawnPath);
assert.ok(
off < 50,
`trail vertex ${off.toFixed(0)} m off the drawn path`,
);
}
// ...and the arc the icon flew is still there: no straight chord. (The
// arc strays far from the chord, so a chord would fail this.)
const a = indexOfPoint(line, fixes[3].position);
const b = indexOfPoint(line, report.position);
assert.ok(a >= 0 && b > a, 'both reports are on the trail');
const between = line.slice(a, b + 1);
// A curve, not the chord, and smooth: no vertex turns more than 3°.
const chord = [fixes[3].position, report.position];
assert.ok(Math.max(...arc.map((p) => distanceToPath(p, chord))) > 300);
// The last 10 s of the arc are exempt: the correction pulled the icon back
// over them, and keeping them would fold the line back on itself.
for (const point of arc.slice(0, -100)) {
const off = distanceToPath(point, between);
assert.ok(off < 50, `drawn arc point ${off.toFixed(0)} m from the trail`);
assert.ok(Math.max(...between.map((p) => distanceToPath(p, chord))) > 300);
assertSmooth(between, 3, 'trail');
// Eased onto the curve, the icon is drawn on its trail.
const trail = [...line, ...h.head()];
for (const p of h.drawn.slice(-100)) {
const off = distanceToPath(p, trail);
assert.ok(off < 3, `drawn ${off.toFixed(1)} m off the trail`);
}
assertNoSpur(line, 'trail');
assertNoSpur(h.head(), 'head');
@@ -300,7 +330,6 @@ test('military: a report the display already passed replaces the guess drawn aft
try {
h.tracking._startTrail(ICAO);
h.run(start + 40 * SEC);
const displayMs = T0 + 130 * SEC;
// A report for 10 s before the display time, 400 m inside the drawn arc.
const guess = h.motion._deadReckon(
ICAO,
@@ -323,16 +352,11 @@ test('military: a report the display already passed replaces the guess drawn aft
report.epochMs,
);
h.run(start + 55 * SEC);
const recorded = h.flightState._trailFixes.filter((entry) => entry.drawn);
// Nothing recorded between the report and the end of the ease.
// Reports only: nothing drawn between them is kept.
assert.deepEqual(
recorded
.filter(
(entry) =>
entry.timeMs > report.epochMs && entry.timeMs < displayMs + 900,
)
.map((entry) => entry.timeMs - T0),
[],
h.flightState._trailFixes.map((entry) => entry.timeMs),
fixes.map((f) => f.epochMs),
'the trail holds the reports and nothing else',
);
const line = h.bodyPoints();
assert.ok(indexOfPoint(line, report.position) >= 0);
@@ -342,7 +366,7 @@ test('military: a report the display already passed replaces the guess drawn aft
}
});
test('military: a history report at an invented height is seeded with no position, and nothing is recorded next to it', () => {
test('military: a history report at an invented height is seeded with no position, and the trail holds only reports', () => {
const { fixes, info } = departure();
fixes[3].inventedHeight = true;
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
@@ -355,9 +379,10 @@ test('military: a history report at an invented height is seeded with no positio
assert.equal(seeded.position, null);
assert.equal(seeded.nullAltitude, true);
h.run(start + 10 * SEC);
assert.equal(
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
0,
assert.deepEqual(
h.flightState._trailFixes.map((entry) => entry.timeMs),
fixes.map((f) => f.epochMs),
'the trail holds the reports and nothing else',
);
} finally {
h.restore();
@@ -421,15 +446,14 @@ test('military: a plane that stops reporting keeps moving dimmed as STALE from i
);
// The coast ends 300 s past the report; the plane stops there.
h.run(pastReport(310));
const recorded = h.flightState._trailFixes.filter((e) => e.drawn).length;
h.run(pastReport(330));
assert.ok(
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-50)) < 0.01,
);
assert.equal(
h.flightState._trailFixes.filter((e) => e.drawn).length,
recorded,
'the trail kept recording a stopped plane',
assert.deepEqual(
h.flightState._trailFixes.map((entry) => entry.timeMs),
fixes.map((f) => f.epochMs),
'the trail holds the reports and nothing else',
);
// 330 s of display past the report is 330 s + the display delay of wall time.
const minutes = Math.floor((330 + RENDER_DELAY_SEC) / 60);
@@ -469,7 +493,7 @@ test('military: a plane held at its last report shows SIGNAL LOST in seconds und
}
});
test('military: a report arriving 200 s into a coast: the plane eases onto it and the trail drops what was drawn after it', () => {
test('military: a report arriving 200 s into a coast: the plane eases onto it with no jump, and the trail runs report to report', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
@@ -496,27 +520,29 @@ test('military: a report arriving 200 s into a coast: the plane eases onto it an
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
{ track: 90 },
);
// Reports only: nothing the coast drew is kept.
assert.deepEqual(
h.flightState._trailFixes.filter(
(e) => e.drawn && e.timeMs > report.epochMs,
),
[],
h.flightState._trailFixes.map((e) => e.timeMs),
fixes.map((f) => f.epochMs),
);
const from = h.drawn.length;
h.run(pastReport(203));
h.run(pastReport(240));
const after = h.drawn.slice(from - 1);
// Frames are 100 ms apart: 14 m at 140 m/s. The ease adds at most 30 %.
for (let i = 1; i < after.length; i++)
assert.ok(
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 400,
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 14 * 1.5,
'the plane jumped instead of easing',
);
// Eased onto the path from the report: 13 s on from it at 140 m/s.
// Eased onto the path from the report: 50 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
assert.ok(
Math.abs(off - 140 * 13) < 150,
Math.abs(off - 140 * 50) < 150,
`${off.toFixed(0)} m from the report`,
);
assert.ok(indexOfPoint(h.bodyPoints(), report.position) >= 0);
} finally {
h.restore();
}
@@ -629,7 +655,7 @@ test('military: a stalled feed dims the tracked plane as STALE', () => {
}
});
test('military: a report arriving after the plane has stopped: it eases in with no spur, and the trail keeps everything up to the stop', () => {
test('military: a report arriving after the plane has stopped far back: it jumps onto the new path, and the trail runs report to report with no spur', () => {
const { fixes, info } = outOfCoverage();
info.lastContactEpochMs = fixes.at(-1).epochMs;
const h = harness({ fixes, info, nowMs: pastReport(-5) });
@@ -638,14 +664,8 @@ test('military: a report arriving after the plane has stopped: it eases in with
h.run(pastReport(360));
const stop = Cesium.Cartesian3.clone(h.drawn.at(-1));
assert.ok(Cesium.Cartesian3.distance(stop, h.drawn.at(-100)) < 0.01);
const kept = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => Cesium.Cartesian3.clone(e.position));
// The thinned straight coast, recorded up to where the plane stopped.
assert.ok(kept.length >= 2);
assert.ok(Cesium.Cartesian3.distance(kept.at(-1), stop) < 300);
// Heard again, for 20 s before the display time: the plane flew on, a
// little north of its old heading.
// little north of its old heading, 8 km past where it stopped.
const at = T0 + 30 * SEC + 340 * SEC;
const lonDeg =
-108.05 + (140 * 340) / (111_320 * Math.cos((43 * Math.PI) / 180));
@@ -654,26 +674,13 @@ test('military: a report arriving after the plane has stopped: it eases in with
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
// Nothing was recorded after the stop, so nothing is dropped.
const after = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => e.position);
assert.equal(after.length, kept.length);
kept.forEach((p, i) =>
assert.ok(Cesium.Cartesian3.distance(p, after[i]) < 0.01),
{ track: 90 },
);
const from = h.drawn.length;
h.run(pastReport(365));
const eased = h.drawn.slice(from - 1);
const jump = Cesium.Cartesian3.distance(eased[0], eased.at(-1));
for (let i = 1; i < eased.length; i++)
assert.ok(
Cesium.Cartesian3.distance(eased[i], eased[i - 1]) < jump / 2,
'the plane jumped instead of easing',
);
// On the path from the report: 25 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(eased.at(-1), report.position);
const after = h.drawn.slice(from);
// On the path from the report at once: 25 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
assert.ok(Math.abs(off - 140 * 25) < 150, `${off.toFixed(0)} m`);
assertNoSpur(h.bodyPoints(), 'trail');
assertNoSpur(h.head(), 'head');
+178
View File
@@ -0,0 +1,178 @@
/**
* The feed-latency checks both aircraft layers run (`flights` and `military`
* `feedLatency.test.mjs`): a slow feed played through the layer frame by
* frame, and where its contacts and the tracked trail were drawn judged
* against where they really were.
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import {
distanceToPath,
frameSteps,
placementError,
runAircraftFeedSim,
slowFeedPolls,
truePath,
} from './aircraftFeedSim.mjs';
const SEC = 1000;
const T0 = Date.UTC(2026, 10, 13, 18, 0);
const CONTACTS = 24;
const SPEED_MPS = 130;
/** The sharpest turn (degrees) at any vertex of `line`, steps under 1 m skipped. */
function sharpestTurnDeg(line) {
let worst = 0;
for (let i = 1; i < line.length - 1; i++) {
const a = line[i - 1];
const b = line[i];
const c = line[i + 1];
const u = { x: b.x - a.x, y: b.y - a.y, z: b.z - a.z };
const v = { x: c.x - b.x, y: c.y - b.y, z: c.z - b.z };
const lu = Math.hypot(u.x, u.y, u.z);
const lv = Math.hypot(v.x, v.y, v.z);
if (lu < 1 || lv < 1) continue;
const cos = Math.min(1, (u.x * v.x + u.y * v.y + u.z * v.z) / (lu * lv));
worst = Math.max(worst, (Math.acos(cos) * 180) / Math.PI);
}
return worst;
}
function run(layer, pollOptions = {}, { drop = [] } = {}) {
const polls = slowFeedPolls({
startMs: T0,
count: 30,
contacts: CONTACTS,
...pollOptions,
}).filter((_, k) => !drop.includes(k));
return runAircraftFeedSim({
layer,
startMs: T0,
polls,
untilMs: polls.at(-1).receiptMs + 10 * SEC,
// From the seventh poll: the delay has settled and the trail has begun.
measureFromMs: polls[6].receiptMs,
contacts: CONTACTS,
});
}
/** Every drawn step of the fleet contact and the tracked one is smooth. */
function assertSmoothMotion(sim) {
for (const key of ['fleet', 'tracked']) {
const steps = frameSteps(sim, sim.frames, key, SPEED_MPS);
assert.equal(steps.jumps, 0, `${key}: ${JSON.stringify(steps)}`);
assert.equal(steps.stalls, 0, `${key}: ${JSON.stringify(steps)}`);
}
}
/** The tracked trail is the true path, smooth, and the icon is drawn on it. */
function assertTrail(sim, maxOffPathM) {
const line = [...sim.body().flat(), ...sim.head()];
assert.ok(line.length > 30, `${line.length} trail points`);
const lastMs = sim.frames.at(-1).displayMs;
const path = truePath(sim, 0, lastMs - 30 * 60 * SEC, lastMs);
for (const p of sim.body().flat()) {
const off = distanceToPath(p, path);
assert.ok(off < maxOffPathM, `trail ${off.toFixed(0)} m off the true path`);
}
const turn = sharpestTurnDeg(line);
assert.ok(turn < 3, `trail turns ${turn.toFixed(1)}° at one vertex`);
for (const f of sim.frames.slice(-150)) {
const off = distanceToPath(f.tracked, line);
assert.ok(off < 3, `tracked icon ${off.toFixed(1)} m off its trail`);
}
}
/** Register the feed-latency tests for one aircraft layer. */
export function feedLatencyTests(layer, floorSec) {
test(`${layer}: a feed 90 s late every 30 s is drawn about two minutes behind, every contact between real reports, with no jump or stall`, () => {
const sim = run(layer);
assertSmoothMotion(sim);
for (const f of sim.frames) {
const delaySec = (f.nowMs - f.displayMs) / SEC;
assert.ok(delaySec > 120 && delaySec < 140, `${delaySec} s`);
}
// Placed between reports: within tens of metres of where it really was,
// not kilometres of dead reckoning.
assert.ok(placementError(sim, sim.frames, 'fleet', 1) < 100);
assert.ok(placementError(sim, sim.frames, 'tracked', 0) < 100);
assertTrail(sim, 60);
});
test(`${layer}: a fresh fallback feed for four polls and reports that do not move on: no jump, no stall, no kink`, () => {
const sim = run(layer, {
fallback: [12, 13, 14, 15],
repeats: [
[0, 20],
[1, 20],
[0, 21],
],
});
assertSmoothMotion(sim);
// The switch to the fresh feed leaves two minutes between two reports,
// the second turn starting 20 s before the later one. Two reports and
// their tracks cannot say when the turn began: the curve joining them
// spreads it over the gap, up to about 550 m off the true path.
assertTrail(sim, 600);
});
test(`${layer}: a two-minute outage on a straight leg: contacts coast on at their speed and carry on along their reports`, () => {
// Polls 9 to 12 never come: the newest reports are from the straight leg
// after the first turn, and the display passes them a minute in.
const sim = run(layer, {}, { drop: [9, 10, 11, 12] });
assertSmoothMotion(sim);
// Coasting holds its height while the plane descends 1.5 m/s: under two
// minutes of it.
assert.ok(placementError(sim, sim.frames, 'fleet', 1) < 200);
assertTrail(sim, 60);
});
test(`${layer}: an outage through a turn no report showed: off by more than 5 km it jumps once onto its reports, as a break; nothing else jumps`, () => {
// Polls 14 to 17 never come; the second turn starts after the newest
// report, so the coast flies straight on while the plane turns.
const sim = run(layer, {}, { drop: [14, 15, 16, 17] });
for (const key of ['fleet', 'tracked']) {
const steps = frameSteps(sim, sim.frames, key, SPEED_MPS);
assert.ok(steps.jumps <= 1, `${key}: ${JSON.stringify(steps)}`);
assert.ok(
steps.worstRatio < 1.5 || steps.worstJumpM > 5_000,
`${key}: a jump under 5 km: ${JSON.stringify(steps)}`,
);
assert.equal(steps.stalls, 0, `${key}: ${JSON.stringify(steps)}`);
}
assertTrail(sim, 1_500);
});
test(`${layer}: a fresh feed is drawn a poll and a few seconds behind, never under the ${floorSec} s floor`, () => {
const count = 30;
const intervalSec = floorSec >= 30 ? 30 : 15;
const sim = run(layer, {
count,
fallback: Array.from({ length: count }, (_, k) => k),
intervalSec,
});
// The wait for the next report: a poll interval, plus reports up to 3 s
// old, plus the 5 s margin.
for (const f of sim.frames) {
const delayMs = f.nowMs - f.displayMs;
assert.ok(delayMs >= floorSec * SEC);
assert.ok(delayMs <= (intervalSec + 3 + 5 + 1) * SEC, `${delayMs}`);
}
assertSmoothMotion(sim);
});
test(`${layer}: following the world clock, contacts draw at the world's time and deliveries leave the delay alone`, () => {
const polls = slowFeedPolls({ startMs: T0, count: 4, contacts: 2 });
const sim = runAircraftFeedSim({
layer,
startMs: T0,
polls,
untilMs: polls.at(-1).receiptMs + SEC,
contacts: 2,
followsClock: true,
});
assert.equal(sim.flightState._displayDelay.currentMs, floorSec * SEC);
assert.equal(sim.flightState._displayDelay.lagCount, 0);
for (const f of sim.frames) assert.equal(f.displayMs, f.nowMs);
});
}
+497
View File
@@ -0,0 +1,497 @@
/**
* A slow aircraft feed played through an aircraft layer's real ingestion,
* motion, icon planning and tracked trail, frame by frame on a fake clock.
*
* The feed is shaped like the anonymous live feed as measured: each poll
* (every 30 s) carries reports about 90 s old (p10 90.5 s, p50 91.5 s, p90
* 94.5 s), now and then a contact whose report did not move on, and a spell
* where a fallback feed with fresh reports stands in. Every contact flies one
* known path, so where it is drawn, and its trail, can be judged against
* where it really was.
*/
import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { createStubRenderer } from '../render/stub/index.js';
import { createContactIcons } from '../data/aircraftIconLayer.js';
import { createFlightState as flightsState } from '../layers/flights/state.js';
import { createIcons as flightsIcons } from '../layers/flights/icons.js';
import { createMotion as flightsMotion } from '../layers/flights/motion.js';
import { createTracking as flightsTracking } from '../layers/flights/tracking.js';
import { createFlightSnapshotRenderer } from '../layers/flights/snapshotRenderer.js';
import { createFlightState as militaryState } from '../layers/military/state.js';
import { createIcons as militaryIcons } from '../layers/military/icons.js';
import { createMotion as militaryMotion } from '../layers/military/motion.js';
import { createTracking as militaryTracking } from '../layers/military/tracking.js';
import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js';
const flights = {
createFlightState: flightsState,
createIcons: flightsIcons,
createMotion: flightsMotion,
createTracking: flightsTracking,
createSnapshotRenderer: createFlightSnapshotRenderer,
};
const military = {
createFlightState: militaryState,
createIcons: militaryIcons,
createMotion: militaryMotion,
createTracking: militaryTracking,
createSnapshotRenderer: createMilitarySnapshotRenderer,
};
const SEC = 1000;
const DEG = Math.PI / 180;
const EARTH_M = 6_371_008.8;
/** A small deterministic generator, 0..1. */
export function random(seed = 1) {
let s = seed >>> 0 || 1;
return () => {
s ^= s << 13;
s >>>= 0;
s ^= s >>> 17;
s ^= s << 5;
s >>>= 0;
return s / 0x1_0000_0000;
};
}
/**
* An arriving jet, seconds from its start: straight, a right turn of 160°,
* straight, a left turn of 90°, then straight on, at 130 m/s descending.
* Each contact flies it from its own start point.
* @returns {(tSec: number) => {lat: number, lon: number, heightM: number, trackDeg: number, speedMps: number}}
*/
export function arrivalPath({
lat0 = 37.9,
lon0 = -122.9,
speedMps = 130,
} = {}) {
const turns = [
[150, 107, 1.5],
[457, 90, -1],
];
const turnRate = (t) => {
for (const [start, length, rate] of turns)
if (t >= start && t < start + length) return rate;
return 0;
};
// Integrated at 0.1 s; positions in metres east and north of the start.
const STEP = 0.1;
const samples = [{ e: 0, n: 0, track: 120 }];
for (let i = 1; i <= 2000 / STEP; i++) {
const prev = samples[i - 1];
const t = (i - 0.5) * STEP;
const track = prev.track + turnRate(t) * STEP;
const mid = (prev.track + track) / 2;
samples.push({
e: prev.e + speedMps * STEP * Math.sin(mid * DEG),
n: prev.n + speedMps * STEP * Math.cos(mid * DEG),
track,
});
}
return (tSec) => {
const x = Math.max(0, Math.min(samples.length - 1.001, tSec / STEP));
const i = Math.floor(x);
const f = x - i;
const a = samples[i];
const b = samples[i + 1];
const e = a.e + (b.e - a.e) * f;
const n = a.n + (b.n - a.n) * f;
return {
lat: lat0 + n / EARTH_M / DEG,
lon: lon0 + e / (EARTH_M * Math.cos(lat0 * DEG)) / DEG,
heightM: Math.max(400, 3000 - 1.5 * tSec),
trackDeg: (((a.track + (b.track - a.track) * f) % 360) + 360) % 360,
speedMps,
};
};
}
/** A report age as measured on the anonymous feed: 90..95 s, now and then more. */
function slowAgeMs(rand) {
const u = rand();
return Math.round((90 + 4.5 * u * u) * SEC);
}
/**
* The polls: receipt times and, per contact, the report time each carries.
* `fallback` lists poll indexes the fresh fallback feed answers (reports 1-3 s
* old); `repeats` lists `[contactIndex, pollIndex]` pairs whose report did not
* move on (the poll repeats the contact's previous report).
*/
export function slowFeedPolls({
startMs,
count,
contacts,
firstPollSec = 120,
intervalSec = 30,
fallback = [],
repeats = [],
seed = 7,
}) {
const rand = random(seed);
const fallbackPolls = new Set(fallback);
const repeated = new Set(repeats.map(([c, p]) => `${c}:${p}`));
const polls = [];
const last = new Array(contacts).fill(null);
for (let k = 0; k < count; k++) {
const receiptMs =
startMs +
(firstPollSec + k * intervalSec) * SEC +
Math.round(rand() * 800);
const fresh = fallbackPolls.has(k);
const reports = [];
for (let c = 0; c < contacts; c++) {
const ageMs = fresh
? Math.round((1 + 2 * rand()) * SEC)
: slowAgeMs(rand);
let timeMs = Math.floor((receiptMs - ageMs) / SEC) * SEC;
if (repeated.has(`${c}:${k}`) && last[c] != null) timeMs = last[c];
last[c] = timeMs;
reports.push(timeMs);
}
polls.push({ receiptMs, fresh, reports });
}
return polls;
}
/** Any property is a no-op function unless given. */
function stub(overrides = {}) {
return new Proxy(overrides, {
get: (target, key) => (key in target ? target[key] : () => undefined),
});
}
function services(trails) {
return {
picking: stub(),
sprites: stub(),
labels: stub(),
meshFloor: stub(),
context: stub(),
render: stub(),
recession: stub(),
readout: stub(),
camera: stub(),
aircraftPresentation: stub({
isTr3b: () => false,
tr3bTypeLabel: (id, label) => label,
tr3bConvertedIds: new Set(),
}),
focus: stub({
focusPassIsNeeded: () => false,
nearFarScalarValueAtDistance: () => 1,
}),
militaryRegistry: stub({
isMilitaryIcao: () => false,
isMilitaryLayerActive: () => false,
}),
groundSnap: { createGroundSnap: () => stub() },
trails,
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: stub({
cachedGroundFloor: () => null,
GROUND_FLOOR_LIFT_M: 0.5,
stickyFloorCell: (lat, lon) => ({ lat, lon }),
coarseFloorCoord: (lat, lon) => ({ lat, lon }),
neighborFloorM: () => null,
floorAltitudeM: (alt) => alt,
corridorFloorCells: () => [],
allocateCorridorCells: () => [],
}),
};
}
/**
* Play `polls` through a layer and draw `frames` at `frameMs`.
* @param {object} options
* @param {'flights'|'military'} options.layer
* @param {number} options.startMs When every contact starts its path.
* @param {Array} options.polls From `slowFeedPolls`.
* @param {number} options.untilMs When the run stops.
* @param {number} [options.frameMs] Frame interval.
* @param {number} [options.measureFromMs] Frames before this are not kept.
* @param {boolean} [options.followsClock] The layer follows the world clock
* (the timeline) instead of drawing live.
* @returns {{frames: Array<{nowMs: number, displayMs: number, fleet: object|null, tracked: object|null}>,
* body: () => object[][], head: () => object[], truth: Function, layer: object}}
*/
export function runAircraftFeedSim({
layer = 'flights',
startMs,
polls,
untilMs,
frameMs = 1000 / 30,
measureFromMs = -Infinity,
contacts,
followsClock = false,
onFrame = null,
}) {
const mod = layer === 'flights' ? flights : military;
const truth = arrivalPath();
// Each contact flies the same path from its own start: contact c starts
// c km further south, so they never meet.
const where = (c, tMs) => {
const p = truth((tMs - startMs) / SEC);
return { ...p, lat: p.lat - c * 0.01 };
};
let clock = polls[0].receiptMs - 1;
const realDateNow = Date.now;
Date.now = () => clock;
let bodySegments = [];
let headPositions = [];
const trails = {
createTrail: () => ({
setSegments(segments) {
bodySegments = segments.map((segment) => segment.slice());
},
setPositions(positions) {
bodySegments = [positions.slice()];
},
setHead(positions) {
headPositions = positions.slice();
},
setVisible() {},
clear() {
bodySegments = [];
},
destroy() {},
}),
};
const svc = services(trails);
const flightState = mod.createFlightState({
services: svc,
source: { label: 'Fixture aircraft' },
});
flightState.now = () => clock;
if (followsClock) flightState.timeline = { active: () => true };
const renderer = createStubRenderer();
const viewer = {};
bindRenderer(viewer, renderer);
flightState._viewer = viewer;
flightState._icons = createContactIcons();
const parts = {
rendering: stub({
_modelOwnsVisual: () => false,
_modelSpec: () => ({}),
_iconKind: () => 'jet',
_fleetBillboardScale: () => 1,
_fleetBillboardColor: () => [1, 1, 1, 1],
_modelRegimeActive: () => false,
_groundSampleExclusions: () => ({ sets: [] }),
}),
queries: stub({
_contactLabel: (id, info) => info?.callsign || id,
_likelyLanded: () => false,
}),
};
parts.icons = mod.createIcons({ flightState, services: svc, parts });
parts.motion = mod.createMotion({
flightState,
services: svc,
parts,
layer: {},
});
parts.tracking = mod.createTracking({
flightState,
services: svc,
parts,
layer: {},
});
const tracking = new Proxy(parts.tracking, {
get: (target, key) =>
key === '_militaryLayerSuppresses'
? () => false
: key in target
? target[key]
: () => undefined,
});
const apply = mod.createSnapshotRenderer({
flightState,
records: flightState.records,
militaryRegistry: svc.militaryRegistry,
groundFloor: svc.groundFloor,
rendering: parts.rendering,
tracking,
motion: parts.motion,
icons: parts.icons,
enrichment: stub(),
queries: parts.queries,
});
const id = (c) => `a0${String(c).padStart(4, '0')}`;
const TRACKED = id(0);
const FLEET = id(1);
flightState._trackedIcao = TRACKED;
function observation(c, timeMs) {
const p = where(c, timeMs);
return {
id: id(c),
reference: id(c),
callsign: `TST${c}`,
latitude: p.lat,
longitude: p.lon,
baroAltitudeM: p.heightM,
ellipsoidAltitudeM: p.heightM,
onGround: false,
speedMps: p.speedMps,
courseDeg: p.trackDeg,
verticalRateMps: -1.5,
positionTimeMs: timeMs,
contactTimeMs: timeMs,
category: 3,
};
}
const frames = [];
let nextPoll = 0;
let lastTickMs = -Infinity;
let started = false;
renderer.frame.on('preRender', () => {
if (clock < measureFromMs) return;
const displayMs = parts.icons._displayMs();
const fleet = flightState._icons.has(FLEET)
? flightState._icons.position(FLEET, displayMs)
: null;
const tracked = parts.motion._trackedDisplayPosition(TRACKED);
frames.push({
nowMs: clock,
displayMs,
fleet: fleet && Cesium.Cartesian3.clone(fleet),
tracked: tracked && Cesium.Cartesian3.clone(tracked),
});
onFrame?.({
clock,
displayMs,
bodySegments,
headPositions,
flightState,
parts,
});
});
try {
while (clock < untilMs) {
clock = Math.min(untilMs, clock + frameMs);
while (nextPoll < polls.length && polls[nextPoll].receiptMs <= clock) {
const poll = polls[nextPoll++];
apply({
observedAtMs: poll.receiptMs,
source: poll.fresh ? 'fallback' : 'slow',
complete: true,
records: poll.reports.map((timeMs, c) => observation(c, timeMs)),
});
if (!started && flightState._positionHistory.has(TRACKED)) {
started = true;
parts.tracking._startTrail(TRACKED);
}
}
// The fleet pass: the motion clock every frame, plans at 12 Hz.
parts.icons._syncMotionClock?.();
if (clock - lastTickMs >= 80) {
lastTickMs = clock;
parts.icons._replanExpired(parts.icons._displayMs());
}
renderer.frame.requestRender('sim');
renderer.testing.tick();
}
} finally {
Date.now = realDateNow;
}
return {
frames,
body: () => bodySegments,
head: () => headPositions,
where,
flightState,
parts,
contacts,
};
}
/** The true path of contact `c` between two times, as ECEF points 0.5 s apart. */
export function truePath(sim, c, fromMs, toMs) {
const points = [];
for (let t = fromMs; t <= toMs; t += 500) {
const p = sim.where(c, t);
points.push(Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.heightM));
}
return points;
}
/** Distance from p to the nearest point of a polyline. */
export function distanceToPath(p, path) {
let best = Infinity;
const ab = new Cesium.Cartesian3();
const ap = new Cesium.Cartesian3();
const closest = new Cesium.Cartesian3();
if (path.length === 1) return Cesium.Cartesian3.distance(p, path[0]);
for (let i = 1; i < path.length; i++) {
Cesium.Cartesian3.subtract(path[i], path[i - 1], ab);
Cesium.Cartesian3.subtract(p, path[i - 1], ap);
const len2 = Cesium.Cartesian3.magnitudeSquared(ab);
const t =
len2 > 0
? Math.max(0, Math.min(1, Cesium.Cartesian3.dot(ap, ab) / len2))
: 0;
Cesium.Cartesian3.add(
path[i - 1],
Cesium.Cartesian3.multiplyByScalar(ab, t, closest),
closest,
);
best = Math.min(best, Cesium.Cartesian3.distance(p, closest));
}
return best;
}
/**
* Frame-to-frame movement of one drawn contact against how far it should
* move: its true speed over the display time that passed. A jump moves more
* than 1.5 times that; a stall less than a quarter of it.
* @returns {{worstRatio: number, worstJumpM: number, jumps: number, stalls: number, longestStall: number, worstAtMs: number}}
*/
export function frameSteps(sim, frames, key, speedMps) {
let worstRatio = 0;
let worstJumpM = 0;
let worstAtMs = NaN;
let jumps = 0;
let stalls = 0;
let run = 0;
let longestStall = 0;
for (let i = 1; i < frames.length; i++) {
const a = frames[i - 1][key];
const b = frames[i][key];
if (!a || !b) continue;
const expected =
(speedMps * (frames[i].displayMs - frames[i - 1].displayMs)) / SEC;
if (!(expected > 0.5)) continue;
const moved = Cesium.Cartesian3.distance(a, b);
const ratio = moved / expected;
if (ratio > worstRatio) {
worstRatio = ratio;
worstJumpM = moved;
worstAtMs = frames[i].nowMs;
}
if (ratio > 1.5) jumps += 1;
if (ratio < 0.25) {
stalls += 1;
run += 1;
longestStall = Math.max(longestStall, run);
} else run = 0;
}
return { worstRatio, worstJumpM, jumps, stalls, longestStall, worstAtMs };
}
/** How far the contact is drawn from where it really was at the display time. */
export function placementError(sim, frames, key, c) {
let worst = 0;
for (const frame of frames) {
const p = frame[key];
if (!p) continue;
const t = sim.where(c, frame.displayMs);
const real = Cesium.Cartesian3.fromDegrees(t.lon, t.lat, t.heightM);
worst = Math.max(worst, Cesium.Cartesian3.distance(p, real));
}
return worst;
}