Merge main (8d9c9071, #1750) into the renderer branch

Main brings satellites and vessels moving every frame, smooth rewind for
contacts, global clouds drawn to the level a feed names, and search for
degrees-minutes-seconds, UTM, MGRS and plus codes. They keep this branch's
renderer work: satellites write their reckoned positions into the points set
once a frame; vessels move every frame and ask for frames from the camera pose
and canvas, and a vessel not there yet is hidden through its icon; flights and
military keep the branch's rendering, with main's timeline fixes, trail top-up
and grounded lift; the cloud tiles keep their infrared transfer. The timeline
history module uses the geo helpers instead of Cesium, and main's new tests
use the draw port's items.
This commit is contained in:
Sameh Khamis committed 2026-11-15 11:00:24 -08:00
commit 4b47d5e058
49 files changed
+3367 -348

No files matched your search

+12 -3
View File
@@ -1,5 +1,6 @@
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { renderedFrames } from '../../data/renderedFrames.js';
import { liftGroundedHistory } from '../../data/timelineHistory.js';
import {
motionCourse,
motionPosition,
@@ -185,11 +186,15 @@ export function createMotion({
info.renderAltitudeM >= floor - 1
)
continue;
const drawnM = info.renderAltitudeM;
info.renderAltitudeM = lifted;
const position = fromDegrees(info.rawLon, info.rawLat, lifted);
const history = flightState._positionHistory.get(icao24);
const newest = history?.[history.length - 1];
if (newest) newest.position = copyInto(position, newest.position);
liftGroundedHistory(
flightState._positionHistory.get(icao24),
position,
drawnM,
lifted,
);
// Above the ellipsoid now (or floors say otherwise next poll).
parts.icons._applyIconPresentation(icao24);
parts.icons._planIcon(icao24);
@@ -213,6 +218,7 @@ export function createMotion({
function _deadReckon(icao24, result, sampledRenderTime) {
const info = flightState.records.data.get(icao24);
flightState._drUnseen = false;
if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) {
const position = parts.icons._iconPosition(icao24, vec());
flightState._drCourseDeg = info?.true_track || 0;
@@ -256,6 +262,9 @@ export function createMotion({
);
const regime = _motionRegime(history, info, renderTime);
// Following the clock, a time well before its first fix is before it
// was there: it is not drawn.
flightState._drUnseen = regime.unseen;
if (regime.kind === 'between' && regime.piece) {
// Along the curve between the two reports, as the icon and the trail.
const ms = julianToEpochMs(renderTime);
+116 -80
View File
@@ -9,6 +9,10 @@ import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
import { observeLiveAircraft } from './placed.js';
import {
historyAfterTrail,
mergeAircraftTimelineFixes,
} from '../../data/timelineHistory.js';
/**
* Note how late each report in a live snapshot is, and aim the display delay
@@ -114,6 +118,18 @@ export function createFlightSnapshotRenderer({
}
const isTracked = icao24 === flightState._trackedIcao;
// Following the clock, a record may carry its own track around the
// time: the contact is placed on it, so the clock can move within it,
// back as well as on, without another snapshot.
const timelineHistory = followsClock(flightState)
? mergeAircraftTimelineFixes(
flightState._positionHistory.get(icao24),
observation,
meta,
meta.velocity,
snapshot.observedAtMs ?? fixEpochMs,
)
: null;
// A host-supplied placement, if any, is told every fix as taken.
observeLiveAircraft(
flightState,
@@ -124,91 +140,111 @@ export function createFlightSnapshotRenderer({
meta.velocity,
meta.true_track,
);
// Append to position history stamped with the FEED's fix epoch
// (time_position), not client receipt time — OpenSky positions arrive
// 5-15s stale and receipt-time stamping is what caused the
// back/forward oscillation. Only append when the fix actually
// advances, so stale repeats don't create zero-dt segments.
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
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 (
!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.
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.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.
// Round 2 (owner): ground traffic appends too — taxi history stays
// live after touchdown (grounded flights positions are already
// surface-clamped via the surfaceM chain, so the ground leg drapes).
if (timelineHistory) {
if (isTracked)
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.true_track,
});
for (const entry of historyAfterTrail(
timelineHistory,
flightState._trailFixes,
snapshot.observedAtMs ?? fixEpochMs,
))
tracking._appendTrailFix(
motion._copyPosition(entry.position),
entry.epochMs,
{ nullAltitude: entry.inventedHeight, track: entry.track },
);
flightState._positionHistory.set(icao24, timelineHistory);
meta.turnRateDps = 0;
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
// Append to position history stamped with the FEED's fix epoch
// (time_position), not client receipt time — OpenSky positions arrive
// 5-15s stale and receipt-time stamping is what caused the
// back/forward oscillation. Only append when the fix actually
// advances, so stale repeats don't create zero-dt segments.
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
// Apply fresh kinematics only from a forward synthetic fix. Mutating
// the historical fix reprojects the entire stale interval and snaps
// the rendered aircraft when course or speed changes late. The stale
// rules apply: none for a contact that holds at its report, a coast
// capped from the real report, never below the ground. It is a motion
// aid, not a report, so it never joins the trail.
const kinematicsChanged =
newest.velocity !== meta.velocity || newest.track !== meta.true_track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.velocity,
track: meta.true_track,
turnRateDps: meta.turnRateDps,
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
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 (
!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.
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.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.
// Round 2 (owner): ground traffic appends too — taxi history stays
// live after touchdown (grounded flights positions are already
// surface-clamped via the surfaceM chain, so the ground leg drapes).
if (isTracked)
tracking._appendTrailFix(
motion._copyPosition(position),
fixEpochMs,
{
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.true_track,
},
);
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
}
// Apply fresh kinematics only from a forward synthetic fix. Mutating
// the historical fix reprojects the entire stale interval and snaps
// the rendered aircraft when course or speed changes late. The stale
// rules apply: none for a contact that holds at its report, a coast
// capped from the real report, never below the ground. It is a motion
// aid, not a report, so it never joins the trail.
const kinematicsChanged =
newest.velocity !== meta.velocity ||
newest.track !== meta.true_track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.velocity,
track: meta.true_track,
turnRateDps: meta.turnRateDps,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
}
}
}
}
+5
View File
@@ -277,6 +277,11 @@ export function createFlightState({ source, services }) {
flightState._drExtrapolating = false;
/** Set by `_deadReckon`: following the clock, the time drawn is well
* before the contact's first fix, so the fleet pass does not draw it. */
flightState._drUnseen = false;
/** Frame-cached course for the tracked aircraft (sibling of _cachedDRPosition). */
flightState._cachedDRCourse = null;
+12 -4
View File
@@ -1,5 +1,6 @@
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { renderedFrames } from '../../data/renderedFrames.js';
import { liftGroundedHistory } from '../../data/timelineHistory.js';
import {
motionCourse,
motionPosition,
@@ -124,6 +125,7 @@ export function createMotion({
*/
function _deadReckon(icao24, result, sampledRenderTime) {
flightState._drUnseen = false;
const history = flightState._positionHistory.get(icao24);
const info = flightState.records.data.get(icao24);
if (!history || history.length === 0) {
@@ -158,6 +160,9 @@ export function createMotion({
);
const regime = _motionRegime(history, info, renderTime);
// Following the clock, a time well before its first fix is before it
// was there: it is not drawn.
flightState._drUnseen = regime.unseen;
if (regime.kind === 'between' && regime.piece) {
// Along the curve between the two reports, as the icon and the trail.
const ms = julianToEpochMs(renderTime);
@@ -654,11 +659,14 @@ export function createMotion({
info.renderAltitudeM >= floor - 1
)
continue;
const drawnM = info.renderAltitudeM;
info.renderAltitudeM = lifted;
const liftedPos = fromDegrees(info.rawLon, info.rawLat, lifted);
const hist = flightState._positionHistory.get(icao24);
const newest = hist?.[hist.length - 1];
if (newest) newest.position = copyInto(liftedPos, newest.position);
liftGroundedHistory(
flightState._positionHistory.get(icao24),
fromDegrees(info.rawLon, info.rawLat, lifted),
drawnM,
lifted,
);
if (flightState._icons.has(icao24)) {
parts.icons._applyIconPresentation(icao24);
parts.icons._planIcon(icao24);
+111 -76
View File
@@ -5,6 +5,10 @@ import {
staleHoldsForFix,
synthesizeForwardKinematicsFix,
} from '../../data/motionModel.js';
import {
historyAfterTrail,
mergeAircraftTimelineFixes,
} from '../../data/timelineHistory.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
@@ -88,6 +92,18 @@ export function createMilitarySnapshotRenderer({
if (groundFlipped) flightState._groundSnap.forget(icao24);
const isTracked = icao24 === flightState._trackedIcao;
// Following the clock, a record may carry its own track around the
// time: the contact is placed on it, so the clock can move within it,
// back as well as on, without another snapshot.
const timelineHistory = followsClock(flightState)
? mergeAircraftTimelineFixes(
flightState._positionHistory.get(icao24),
aircraft,
meta,
meta.speedMps,
snapshot.observedAtMs ?? fixEpochMs,
)
: null;
// A host-supplied placement, if any, is told every fix as taken.
observeLiveAircraft(
flightState,
@@ -98,87 +114,106 @@ export function createMilitarySnapshotRenderer({
meta.speedMps,
meta.track,
);
// Append to position history stamped with the FEED's fix epoch.
// adsb.lol's seen_pos is the AGE in seconds of the last position
// report, so the fix epoch is receipt time minus that age. Only
// append when the fix actually advances, so stale repeats don't
// create zero-dt segments.
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
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 (
!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.
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.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
// after touchdown; _appendTrailFix floors grounded positions at
// the surface so the ground leg drapes instead of diving.
if (timelineHistory) {
if (isTracked)
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.track,
});
for (const entry of historyAfterTrail(
timelineHistory,
flightState._trailFixes,
snapshot.observedAtMs ?? fixEpochMs,
))
tracking._appendTrailFix(
motion._copyPosition(entry.position),
entry.epochMs,
{ nullAltitude: entry.inventedHeight, track: entry.track },
);
flightState._positionHistory.set(icao24, timelineHistory);
meta.turnRateDps = 0;
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
// Append to position history stamped with the FEED's fix epoch.
// adsb.lol's seen_pos is the AGE in seconds of the last position
// report, so the fix epoch is receipt time minus that age. Only
// append when the fix actually advances, so stale repeats don't
// create zero-dt segments.
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
// A forward synthetic fix follows the stale rules (none while the
// contact holds at its report, a coast capped from the real report,
// never below the ground) and is a motion aid, never a trail report.
const kinematicsChanged =
newest.velocity !== meta.speedMps || newest.track !== meta.track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.speedMps,
track: meta.track,
turnRateDps: meta.turnRateDps,
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
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 (
!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.
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.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
// after touchdown; _appendTrailFix floors grounded positions at
// the surface so the ground leg drapes instead of diving.
if (isTracked)
tracking._appendTrailFix(
motion._copyPosition(position),
fixEpochMs,
{
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.track,
},
);
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
}
// A forward synthetic fix follows the stale rules (none while the
// contact holds at its report, a coast capped from the real report,
// never below the ground) and is a motion aid, never a trail report.
const kinematicsChanged =
newest.velocity !== meta.speedMps || newest.track !== meta.track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.speedMps,
track: meta.track,
turnRateDps: meta.turnRateDps,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
}
}
}
}
+5
View File
@@ -232,6 +232,11 @@ export function createFlightState({ source, services }) {
flightState._drCourseHold = false;
/** Set by `_deadReckon`: following the clock, the time drawn is well
* before the contact's first fix, so the fleet pass does not draw it. */
flightState._drUnseen = false;
/** Frame-cached course for the tracked aircraft (sibling of _cachedDRPosition). */
flightState._cachedDRCourse = null;
+40 -30
View File
@@ -1,16 +1,16 @@
import { twoline2satrec } from 'satellite.js';
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { gstime, twoline2satrec } from 'satellite.js';
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
import { reckonEarthFixed, sampleOrbit } from './motion.js';
import {
DENSE_REFRESH_FRAMES,
DENSE_GROUP_PATH,
DENSE_SAMPLES_PER_FRAME_MAX,
POINT_STYLES,
DENSE_CREATE_CHUNK,
ORBIT_SAMPLE_HORIZON_MS,
} from './policy.js';
export function createCatalog({ state: layerState, services, parts, source }) {
// _movePoint copies the position, so one scratch point serves every move.
const scratch = { x: 0, y: 0, z: 0 };
function _abortActiveUpdates() {
for (const controller of layerState._activeUpdateControllers)
controller.abort();
@@ -20,35 +20,42 @@ export function createCatalog({ state: layerState, services, parts, source }) {
}
/**
* Re-propagate a small per-frame slice of the dense extras (round-robin).
* Budget: the full dense set completes one pass every ~DENSE_REFRESH_FRAMES
* frames (~5s at 60fps ≈ 1/5 of the core cadence), so per-frame cost stays
* ~35 propagations (~0.1 ms) even with 10K+ Starlink sats — spreading the
* work per frame avoids the once-per-second spike a tick-sized chunk
* (~2K props ≈ 4ms) would cause.
* Sample a small per-frame slice of the dense extras (round-robin); every
* point is then reckoned from its sample each frame (rendering.js
* _reckonPoints). At normal speed the full dense set is sampled once every
* ~DENSE_REFRESH_FRAMES frames (~5s at 60fps), so per-frame cost stays ~35
* propagations (~0.1 ms) even with 10K+ Starlink sats — spreading the work
* per frame avoids the once-per-second spike a tick-sized chunk (~2K props
* ≈ 4ms) would cause. While time plays fast, or after a seek, the slice
* grows so each sample stays within ORBIT_SAMPLE_HORIZON_MS of the world
* time, up to DENSE_SAMPLES_PER_FRAME_MAX a frame.
* @param {number} worldStepMs How far the world time moved since the last
* frame (NaN on the first).
*/
function _propagateDenseChunk() {
if (layerState._denseIds.length === 0) return;
const perFrame = Math.max(
1,
Math.ceil(layerState._denseIds.length / DENSE_REFRESH_FRAMES),
function _propagateDenseChunk(worldStepMs) {
const count = layerState._denseIds.length;
if (count === 0) return;
const share = Math.max(
1 / DENSE_REFRESH_FRAMES,
Number.isFinite(worldStepMs)
? Math.abs(worldStepMs) / ORBIT_SAMPLE_HORIZON_MS
: 1,
);
const now = new Date(layerState.now());
const perFrame = Math.min(
count,
DENSE_SAMPLES_PER_FRAME_MAX,
Math.max(1, Math.ceil(count * share)),
);
const nowMs = layerState.now();
for (let i = 0; i < perFrame; i++) {
if (layerState._denseCursor >= layerState._denseIds.length)
layerState._denseCursor = 0;
if (layerState._denseCursor >= count) layerState._denseCursor = 0;
const noradId = layerState._denseIds[layerState._denseCursor++];
if (noradId === layerState._trackedNorad) continue; // per-frame tracked path owns it
const sat = layerState._catalog.get(noradId);
if (!sat || !layerState._points.has(noradId)) continue;
const pos = parts.orbits.propagatePosition(sat.satrec, now);
if (pos) {
parts.rendering._movePoint(
noradId,
fromDegreesInto(pos.longitude, pos.latitude, pos.altitude, scratch),
);
}
if (!sat) continue;
const sample = sampleOrbit(sat.satrec, nowMs, sat.orbitSample);
if (sample) sat.orbitSample = sample;
}
}
@@ -97,7 +104,8 @@ export function createCatalog({ state: layerState, services, parts, source }) {
const entries = parts.orbits.parseTLE(text);
const style = POINT_STYLES.dense;
const now = new Date(layerState.now());
const nowMs = layerState.now();
const gmst = gstime(new Date(nowMs));
let added = 0;
for (let start = 0; start < entries.length; start += DENSE_CREATE_CHUNK) {
@@ -116,8 +124,9 @@ export function createCatalog({ state: layerState, services, parts, source }) {
if (!satrec || satrec.error !== 0) continue;
const noradId = noradIdFromSatnum(satrec.satnum);
if (layerState._catalog.has(noradId)) continue; // core catalog keeps priority
const pos = parts.orbits.propagatePosition(satrec, now);
if (!pos) continue;
// Its first sample places it now and moves it from then on.
const orbitSample = sampleOrbit(satrec, nowMs);
if (!orbitSample) continue;
layerState._catalog.set(noradId, {
name: entry.name,
@@ -131,10 +140,11 @@ export function createCatalog({ state: layerState, services, parts, source }) {
ucs: null,
satcat: null,
sensor: null,
orbitSample,
});
parts.rendering._addPoint(
noradId,
fromDegrees(pos.longitude, pos.latitude, pos.altitude),
reckonEarthFixed(orbitSample, nowMs, gmst, { x: 0, y: 0, z: 0 }),
style,
);
layerState._denseIds.push(noradId);
+80
View File
@@ -0,0 +1,80 @@
import { propagate } from 'satellite.js';
/** The Earth's gravitational parameter, km³/s², as SGP4's WGS72 constants. */
const MU_KM3_S2 = 398600.8;
/** Floats in one orbit sample: its time, then position, velocity,
* acceleration and jerk. */
export const ORBIT_SAMPLE_LENGTH = 13;
/**
* One SGP4 state of a satellite for dead reckoning: its inertial (TEME)
* position and velocity at `atMs`, with the two-body acceleration and its
* rate of change (jerk) there.
* Layout: [atMs, rx, ry, rz (km), vx, vy, vz (km/s), ax, ay, az (km/s²),
* jx, jy, jz (km/s³)].
* @param {object} satrec
* @param {number} atMs Epoch milliseconds.
* @param {Float64Array} [out]
* @returns {Float64Array|null} Null when SGP4 has no state for that time.
*/
export function sampleOrbit(
satrec,
atMs,
out = new Float64Array(ORBIT_SAMPLE_LENGTH),
) {
let state;
try {
state = propagate(satrec, new Date(atMs));
} catch {
return null;
}
const p = state?.position;
const v = state?.velocity;
if (!p || typeof p === 'boolean' || !v || typeof v === 'boolean') return null;
const r = Math.hypot(p.x, p.y, p.z);
if (!(r > 0) || !Number.isFinite(v.x + v.y + v.z)) return null;
const k = -MU_KM3_S2 / (r * r * r);
// d/dt of -μ r/|r|³: -μ (v/|r|³ - 3 (r·v) r/|r|⁵).
const radial = (3 * (p.x * v.x + p.y * v.y + p.z * v.z)) / (r * r);
out[0] = atMs;
out[1] = p.x;
out[2] = p.y;
out[3] = p.z;
out[4] = v.x;
out[5] = v.y;
out[6] = v.z;
out[7] = k * p.x;
out[8] = k * p.y;
out[9] = k * p.z;
out[10] = k * (v.x - radial * p.x);
out[11] = k * (v.y - radial * p.y);
out[12] = k * (v.z - radial * p.z);
return out;
}
/**
* Where a satellite is at `atMs`, reckoned from its sample along the inertial
* path (position, velocity, gravity and its change) and turned into the
* Earth-fixed frame by the Greenwich sidereal angle at that time. Over half a
* minute of world time the reckoned point stays within metres of SGP4.
* @param {Float64Array} sample From sampleOrbit.
* @param {number} atMs Epoch milliseconds.
* @param {number} gmst Greenwich mean sidereal angle at `atMs`, radians.
* @param {{x: number, y: number, z: number}} out Receives Earth-fixed metres.
* @returns {{x: number, y: number, z: number}} `out`.
*/
export function reckonEarthFixed(sample, atMs, gmst, out) {
const dt = (atMs - sample[0]) / 1000;
const half = 0.5 * dt * dt;
const sixth = (half * dt) / 3;
const x = sample[1] + sample[4] * dt + sample[7] * half + sample[10] * sixth;
const y = sample[2] + sample[5] * dt + sample[8] * half + sample[11] * sixth;
const z = sample[3] + sample[6] * dt + sample[9] * half + sample[12] * sixth;
const cos = Math.cos(gmst);
const sin = Math.sin(gmst);
out.x = (x * cos + y * sin) * 1000;
out.y = (-x * sin + y * cos) * 1000;
out.z = z * 1000;
return out;
}
+86
View File
@@ -0,0 +1,86 @@
// src/layers/satellites/motion.test.mjs — a satellite's point reckoned from
// one SGP4 sample stays on SGP4's track between samples.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { gstime, twoline2satrec } from 'satellite.js';
import { createOrbits } from './orbits.js';
import { reckonEarthFixed, sampleOrbit } from './motion.js';
const ISS = twoline2satrec(
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537',
);
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
const orbits = createOrbits({ state: {}, services: {}, parts: {} });
/** Where the layer has always drawn a satellite: SGP4, through geodetic. */
function drawnBySgp4(atMs) {
const pos = orbits.propagatePosition(ISS, new Date(atMs));
return Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
);
}
function reckoned(sample, atMs) {
return reckonEarthFixed(
sample,
atMs,
gstime(new Date(atMs)),
new Cesium.Cartesian3(),
);
}
test('at its own time the reckoned point is where SGP4 draws it', () => {
const sample = sampleOrbit(ISS, AT_MS);
const gap = Cesium.Cartesian3.distance(
reckoned(sample, AT_MS),
drawnBySgp4(AT_MS),
);
assert.ok(gap < 1, `${gap} m`);
});
test('between samples the point keeps to the SGP4 track', () => {
const sample = sampleOrbit(ISS, AT_MS);
for (const [seconds, withinM] of [
[0.016, 1],
[1, 2],
[10, 2],
[30, 10],
[60, 50],
]) {
const atMs = AT_MS + seconds * 1000;
const gap = Cesium.Cartesian3.distance(
reckoned(sample, atMs),
drawnBySgp4(atMs),
);
assert.ok(gap < withinM, `${seconds} s: ${gap} m`);
}
});
test('the point moves every frame, at orbital speed', () => {
const sample = sampleOrbit(ISS, AT_MS);
const a = reckoned(sample, AT_MS + 500);
const b = reckoned(sample, AT_MS + 516);
const speed = Cesium.Cartesian3.distance(a, b) / 0.016;
// ISS ground-relative speed: about 7.2–7.7 km/s.
assert.ok(speed > 7000 && speed < 8000, `${speed} m/s`);
});
test('reckoning backwards in time works as forwards', () => {
const sample = sampleOrbit(ISS, AT_MS);
const atMs = AT_MS - 30_000;
const gap = Cesium.Cartesian3.distance(
reckoned(sample, atMs),
drawnBySgp4(atMs),
);
assert.ok(gap < 10, `${gap} m`);
});
test('an element set SGP4 cannot propagate has no sample', () => {
const decayed = { ...ISS, error: 0 };
decayed.ecco = 2; // not an orbit
assert.equal(sampleOrbit(decayed, AT_MS), null);
});
+17 -1
View File
@@ -31,7 +31,16 @@ export const ISS_OVERLAY_SOURCE_OPTIONS = Object.freeze({
export const ORBIT_PATH_STEPS = 180;
// points per orbital path
/** How often every core satellite takes a fresh SGP4 sample (wall ms). */
export const POSITION_UPDATE_MS = 1000;
/**
* Between SGP4 samples every point is reckoned each frame from its last one
* (motion.js). A sample this far from the world time is taken again, so a
* point is never more than about 10 m off SGP4 however fast time plays.
*/
export const ORBIT_SAMPLE_HORIZON_MS = 30_000;
/** Beyond this from its sample a point is left where it is until sampled again. */
export const ORBIT_RECKON_LIMIT_MS = 120_000;
/** How far either side of now SGP4 on current element sets stays meaningful. */
export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
@@ -41,7 +50,6 @@ export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
* drifts a few degrees a day.
*/
export const ORBIT_REBAKE_MS = 30 * 60_000;
// re-propagate every 1s (SGP4 is smooth at this rate)
export const RING_ROTATION_MS = 1000;
// re-align baked orbit rings to current GMST every 1s
@@ -80,6 +88,14 @@ export const DENSE_GROUP_PATH = 'starlink';
export const DENSE_REFRESH_FRAMES = 300;
// full dense pass spread over ~300 frames (~5s @ 60fps)
/**
* The most dense extras sampled in one frame while time plays fast (~4 ms).
* Past about 10 minutes of world time a second the full dense set no longer
* fits within ORBIT_RECKON_LIMIT_MS, and its points move only as they are
* sampled.
*/
export const DENSE_SAMPLES_PER_FRAME_MAX = 2000;
export const DENSE_CREATE_CHUNK = 1500;
// satrec builds per macro-task while loading
+163
View File
@@ -0,0 +1,163 @@
// src/layers/satellites/reckon.test.mjs — every frame each shown point moves
// to where its satellite is at the world time; samples are taken again when
// time has moved far from them, and dense extras are sampled faster the
// faster time plays.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { twoline2satrec } from 'satellite.js';
import { createCatalog } from './catalog.js';
import { createOrbits } from './orbits.js';
import { createRendering } from './rendering.js';
import { sampleOrbit } from './motion.js';
import {
DENSE_REFRESH_FRAMES,
DENSE_SAMPLES_PER_FRAME_MAX,
ORBIT_RECKON_LIMIT_MS,
ORBIT_SAMPLE_HORIZON_MS,
} from './policy.js';
const ISS = twoline2satrec(
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537',
);
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
const orbits = createOrbits({ state: {}, services: {}, parts: {} });
/** A dot's point item that counts moves (a write of its `pos`). */
function point(show = true) {
let x = 0;
const item = {
show,
writes: 0,
pos: { y: 0, z: 0 },
get position() {
return item.pos;
},
};
Object.defineProperty(item.pos, 'x', {
enumerable: true,
get: () => x,
set(value) {
item.writes++;
x = value;
},
});
return item;
}
function scene(entries, { tracked = null } = {}) {
const state = {
_points: new Map(),
_catalog: new Map(),
_trackedNorad: tracked,
_denseIds: [],
_denseCursor: 0,
};
for (const [id, entry] of Object.entries(entries)) {
state._points.set(id, entry.point);
state._catalog.set(id, { satrec: ISS, group: 'core', ...entry.sat });
}
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
return { state, rendering };
}
function sgp4At(atMs) {
const pos = orbits.propagatePosition(ISS, new Date(atMs));
return Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
);
}
test('a shown point moves to its satellite at the world time; hidden and tracked ones do not', () => {
const shown = point();
const hidden = point(false);
const tracked = point();
const { rendering } = scene(
{
shown: { point: shown },
hidden: { point: hidden },
tracked: { point: tracked },
},
{ tracked: 'tracked' },
);
rendering._reckonPoints(AT_MS);
assert.ok(Cesium.Cartesian3.distance(shown.position, sgp4At(AT_MS)) < 1);
assert.equal(hidden.writes, 0);
assert.equal(tracked.writes, 0);
// The same time again (the clock paused): nothing is written.
rendering._reckonPoints(AT_MS);
assert.equal(shown.writes, 1);
// Shown while paused, a hidden point moves at once.
hidden.show = true;
rendering._reckonPoints(AT_MS);
assert.equal(hidden.writes, 1);
});
test('between samples the point keeps to the track; far from its sample, a core satellite is sampled again', () => {
const p = point();
const { state, rendering } = scene({ iss: { point: p } });
rendering._reckonPoints(AT_MS);
const sample = state._catalog.get('iss').orbitSample;
assert.equal(sample[0], AT_MS);
// Within the horizon the same sample moves it on.
const soon = AT_MS + ORBIT_SAMPLE_HORIZON_MS / 2;
rendering._reckonPoints(soon);
assert.equal(state._catalog.get('iss').orbitSample[0], AT_MS);
assert.ok(Cesium.Cartesian3.distance(p.position, sgp4At(soon)) < 5);
// A seek an hour back samples it again there.
const back = AT_MS - 3_600_000;
rendering._reckonPoints(back);
assert.equal(state._catalog.get('iss').orbitSample[0], back);
assert.ok(Cesium.Cartesian3.distance(p.position, sgp4At(back)) < 1);
});
test('a dense extra is left for its round-robin, and stays put once too far from its sample', () => {
const p = point();
const { rendering } = scene({
starlink: {
point: p,
sat: { group: 'dense', orbitSample: sampleOrbit(ISS, AT_MS) },
},
});
rendering._reckonPoints(AT_MS + ORBIT_SAMPLE_HORIZON_MS * 2);
assert.equal(p.writes, 1, 'reckoned from its own sample');
rendering._reckonPoints(AT_MS + ORBIT_RECKON_LIMIT_MS + 1);
assert.equal(p.writes, 1, 'too far: left where it is');
});
test('the dense slice grows with how fast the world time moves, up to its cap', () => {
const sampled = (count, worldStepMs) => {
const state = {
_denseIds: [],
_denseCursor: 0,
_catalog: new Map(),
_trackedNorad: null,
now: () => AT_MS,
};
for (let i = 0; i < count; i++) {
state._denseIds.push(String(i));
state._catalog.set(String(i), { satrec: ISS, group: 'dense' });
}
createCatalog({
state,
services: {},
parts: {},
source: {},
})._propagateDenseChunk(worldStepMs);
return [...state._catalog.values()].filter((sat) => sat.orbitSample).length;
};
// Real time: the set over DENSE_REFRESH_FRAMES frames.
assert.equal(sampled(3000, 16), Math.ceil(3000 / DENSE_REFRESH_FRAMES));
// A tenth of the horizon a frame: a tenth of the set.
assert.equal(sampled(3000, ORBIT_SAMPLE_HORIZON_MS / 10), 300);
// A seek, or the first frame: as many as the cap allows.
assert.equal(sampled(3000, Number.NaN), DENSE_SAMPLES_PER_FRAME_MAX);
assert.equal(sampled(1000, -ORBIT_SAMPLE_HORIZON_MS * 5), 1000);
});
+66 -19
View File
@@ -1,10 +1,12 @@
import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import { gstime } from 'satellite.js';
import { reckonEarthFixed, sampleOrbit } from './motion.js';
import {
ISS_NORAD,
ORBIT_REBAKE_MS,
ORBIT_RECKON_LIMIT_MS,
ORBIT_SAMPLE_HORIZON_MS,
POSITION_UPDATE_MS,
RING_ROTATION_MS,
} from './policy.js';
@@ -558,37 +560,76 @@ export function createRendering({
}
/**
* Propagate all CORE satellite positions and update their dots.
* (About 1,300 core satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms,
* fine at the 1s/200ms cadence.) Dense extras are
* excluded: they refresh on the round-robin budget in _propagateDenseChunk.
* Take a fresh SGP4 sample of every CORE satellite (motion.js); the points
* move from these each frame in _reckonPoints. (About 1,300 core
* satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms, fine at the
* 1s/200ms cadence.) Dense extras are excluded: they are sampled on the
* round-robin budget in _propagateDenseChunk.
* @returns {number} How many satellites were sampled.
*/
function _propagateAll() {
const now = new Date(layerState.now());
const nowMs = layerState.now();
let updated = 0;
for (const [noradId, sat] of layerState._catalog) {
for (const sat of layerState._catalog.values()) {
if (sat.group === 'dense') continue;
const pos = parts.orbits.propagatePosition(sat.satrec, now);
if (!pos) continue;
const point = layerState._points.get(noradId);
if (point) {
fromDegreesInto(pos.longitude, pos.latitude, pos.altitude, point.pos);
_markDirty(noradId);
updated++;
}
if (_sample(sat, nowMs)) updated++;
}
return updated;
}
/**
* Sample one satellite's orbit at `atMs` into its reused sample.
* @returns {boolean} Whether SGP4 had a state for that time.
*/
function _sample(sat, atMs) {
const sample = sampleOrbit(sat.satrec, atMs, sat.orbitSample);
if (!sample) return false;
sat.orbitSample = sample;
return true;
}
/**
* Move every shown dot to where its satellite is at the world time,
* reckoned from its last sample, so dots glide every frame between
* samples instead of stepping once a second; the moved dots go to the
* points set with the frame's other dot changes. A core sample more than
* ORBIT_SAMPLE_HORIZON_MS from the world time (time playing fast, or a
* seek) is taken again first; dense extras are resampled by their own
* round-robin. A hidden dot is moved when it is shown again, and the
* tracked satellite is placed by its per-frame path.
* @param {number} nowMs World time, epoch ms.
*/
function _reckonPoints(nowMs) {
const gmst = gstime(new Date(nowMs));
for (const [noradId, point] of layerState._points) {
if (!point.show || noradId === layerState._trackedNorad) continue;
const sat = layerState._catalog.get(noradId);
if (!sat || sat.reckonedAtMs === nowMs) continue;
let sample = sat.orbitSample;
if (
sat.group !== 'dense' &&
(!sample || Math.abs(nowMs - sample[0]) > ORBIT_SAMPLE_HORIZON_MS)
)
sample = _sample(sat, nowMs) ? sat.orbitSample : null;
if (!sample || Math.abs(nowMs - sample[0]) > ORBIT_RECKON_LIMIT_MS)
continue;
reckonEarthFixed(sample, nowMs, gmst, point.pos);
_markDirty(noradId);
sat.reckonedAtMs = nowMs;
}
}
/**
* Shared preRender tick (single definition for init + enable):
* - the tracked dot where the follow camera put it this frame,
* - core fleet propagation at 200ms-tracked / 1s-idle cadence,
* - dense extras on a per-frame round-robin budget,
* - core fleet SGP4 samples at 200ms-tracked / 1s-idle cadence,
* - dense extras sampled on a per-frame round-robin budget,
* - every dot reckoned from its sample each frame (motion.js),
* - tracked satellite's dot sample per frame (WS-D2),
* - orbit ring GMST re-alignment every ~1s (WS-D1),
* - the frame's dot changes sent to the points set.
@@ -637,7 +678,12 @@ export function createRendering({
layerState._lastPropagation = now;
}
if (layerState._params.showPoints) parts.catalog._propagateDenseChunk();
if (layerState._params.showPoints) {
const worldMs = layerState.now();
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
layerState._lastReckonMs = worldMs;
_reckonPoints(worldMs);
}
// Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
// with label + camera — runs after _propagateAll so the per-frame sample
@@ -831,6 +877,7 @@ export function createRendering({
_updateOrbitPathRotations,
_hideOrbitPath,
_propagateAll,
_reckonPoints,
_preRenderTick,
_updatePointFocus,
applySatellitePointFocusDeemphasis,
+4
View File
@@ -63,6 +63,10 @@ export function createState({ services }) {
state._lastPropagation = 0;
// The world time of the last frame that reckoned the points (motion.js),
// NaN before the first.
state._lastReckonMs = NaN;
state._lastRingRotation = 0;
state._lastFocusUpdate = 0;
+1 -1
View File
@@ -420,7 +420,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
// The tracked position propagates per evaluation through the per-frame
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
// Falls back to the dot's 1s-throttled position if SGP4 fails.
// Falls back to the dot's reckoned position if SGP4 fails.
const trackedPosition = () => {
const pos = _getTrackedFramePosition();
return pos
+4 -1
View File
@@ -101,7 +101,10 @@ test('the subject says whether its track is the heading or the course', () => {
test('a vessel without identity or position is not a subject', () => {
assert.equal(vesselCockpitInfo(null), null);
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
assert.equal(vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }), null);
assert.equal(
vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }),
null,
);
});
test('a vessel missing from recent refreshes reads as stale', () => {
+4 -2
View File
@@ -39,8 +39,9 @@ export function createIngestion({
* @returns {Promise<boolean>}
*/
async function loadAt(atMs, { signal = null, replace = false } = {}) {
// Whatever polls or loads for another time no longer applies.
if (replace && feed.loading) {
// Whatever polls or loads for another time no longer applies: the
// timeline asks for one time at a time.
if (feed.loading) {
feed.abort?.abort();
feed.loading = false;
feed.abort = null;
@@ -209,6 +210,7 @@ export function createIngestion({
reference: record.reference,
lat: record.latitude,
lon: record.longitude,
fixes: record.fixes,
name: record.name,
imo: record.imo,
type: record.type,
+53 -3
View File
@@ -1,14 +1,39 @@
/**
* Where a vessel is at world time `tMs` while the layer follows the world
* clock: between the fix it moved from and the fix it moved to, along the
* great circle; at the earlier fix before it, at the newer fix after it. A
* vessel is never projected past its newest fix.
* clock: on its own fixes around the time when its record carries them
* (`fixes`, see src/time/timelineFixes.js), else between the fix it moved
* from and the fix it moved to; along the great circle between two fixes, at
* the first before them and at the last after them. A vessel is never
* projected past its newest fix.
* @param {{lat: number, lon: number, motion?: {fromLat: number, fromLon: number,
* fromMs: number, toLat: number, toLon: number, toMs: number}|null}} record
* @param {number} tMs
* @returns {{lat: number, lon: number}}
*/
export function vesselPositionAt(record, tMs) {
const fixes = record?.fixes;
if (fixes?.length >= 2 && Number.isFinite(tMs)) {
const first = fixes[0];
const last = fixes[fixes.length - 1];
if (tMs <= first.atMs) return { lat: first.lat, lon: first.lon };
if (tMs >= last.atMs) return { lat: last.lat, lon: last.lon };
let low = 1;
let high = fixes.length - 1;
while (low < high) {
const mid = (low + high) >> 1;
if (fixes[mid].atMs < tMs) low = mid + 1;
else high = mid;
}
const a = fixes[low - 1];
const b = fixes[low];
return greatCircleAt(
a.lat,
a.lon,
b.lat,
b.lon,
b.atMs > a.atMs ? (tMs - a.atMs) / (b.atMs - a.atMs) : 1,
);
}
const motion = record?.motion;
if (
!motion ||
@@ -60,3 +85,28 @@ function unit(lat, lon) {
Math.sin(phi),
];
}
// Whether each fixes array moves, read once per array: records keep theirs
// until a snapshot brings new ones.
const moving = new WeakMap();
/**
* Whether a vessel's fixes (`record.fixes`) put it in more than one place,
* so following the clock moves it; a moored vessel's do not.
* @param {Array<{lat: number, lon: number}>|null|undefined} fixes
* @returns {boolean}
*/
export function fixesMove(fixes) {
if (!fixes?.length) return false;
let moves = moving.get(fixes);
if (moves === undefined) {
const [first] = fixes;
moves = fixes.some(
(fix) =>
Math.abs(fix.lat - first.lat) > 1e-6 ||
Math.abs(fix.lon - first.lon) > 1e-6,
);
moving.set(fixes, moves);
}
return moves;
}
+33 -1
View File
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { vesselPositionAt } from './motion.js';
import { fixesMove, vesselPositionAt } from './motion.js';
const record = {
lat: 1,
@@ -29,3 +29,35 @@ test('a vessel with no move is at its record', () => {
assert.equal(vesselPositionAt(still, 2_000), still);
assert.equal(vesselPositionAt({ ...still, motion: null }, 2_000).lat, 4);
});
test('a vessel with fixes around the time is placed on them, held at either end', () => {
const tracked = {
lat: 9,
lon: 9,
motion: record.motion,
fixes: [
{ atMs: 1_000, lat: 0, lon: 0, altitudeM: null },
{ atMs: 2_000, lat: 1, lon: 0, altitudeM: null },
{ atMs: 4_000, lat: 1, lon: 2, altitudeM: null },
],
};
assert.deepEqual(vesselPositionAt(tracked, 0), { lat: 0, lon: 0 });
assert.deepEqual(vesselPositionAt(tracked, 9_000), { lat: 1, lon: 2 });
const back = vesselPositionAt(tracked, 1_500);
assert.ok(Math.abs(back.lat - 0.5) < 1e-3 && Math.abs(back.lon) < 1e-6);
const on = vesselPositionAt(tracked, 3_000);
assert.ok(Math.abs(on.lat - 1) < 1e-3 && Math.abs(on.lon - 1) < 1e-3);
});
test('fixes that stay in one place do not move a vessel', () => {
const still = [
{ atMs: 0, lat: 1, lon: 2 },
{ atMs: 60_000, lat: 1, lon: 2 },
];
assert.equal(fixesMove(still), false);
assert.equal(
fixesMove([...still, { atMs: 90_000, lat: 1.001, lon: 2 }]),
true,
);
assert.equal(fixesMove(null), false);
});
+23 -2
View File
@@ -1,3 +1,7 @@
import {
mergeTimelineRuns,
readTimelineFixes,
} from '../../time/timelineFixes.js';
import {
PARTIAL_RETENTION_MS,
SELECTED_PIN_REFRESHES,
@@ -35,6 +39,9 @@ export function normalizeVessel(row) {
virtual: row.virtual === true,
lastPositionUtc: String(row.last_position_UTC || ''),
lastPositionEpoch: finiteNumber(row.last_position_epoch),
// Its own track around the time, from a snapshot at a time (see
// src/time/timelineFixes.js); null when the row carries none.
fixes: readTimelineFixes(row.fixes),
missedRefreshes: 0,
};
}
@@ -145,8 +152,22 @@ export class VesselRecords {
record.fixReceivedAtMs = next.fixReceivedAtMs;
record.fixFeedEpoch = next.fixFeedEpoch;
}
if (replace) record.motion = null;
else if (follow) record.motion = motionBetween(record, next);
if (replace) {
record.motion = null;
record.fixes = next.fixes;
} else if (follow) {
record.motion = motionBetween(record, next);
// Without fixes now, it is placed by its record, not by fixes
// that end before it.
record.fixes = next.fixes
? mergeTimelineRuns(
record.fixes ?? [],
next.fixes,
(fix) => fix.atMs,
(next.lastPositionEpoch ?? 0) * 1000,
)
: null;
} else record.fixes = null;
record.reference = next.reference;
record.mmsi = next.mmsi;
record.receivedAtMs = next.receivedAtMs;
+12
View File
@@ -187,3 +187,15 @@ test('an AIS row with no id is keyed by its MMSI; one with neither is unkeyed',
assert.equal(probe.store.byId.size, 0);
assert.equal(probe.store.unkeyed.length, 2);
});
const fixes = (...pairs) =>
pairs.map(([atMs, lat]) => ({ atMs, lat, lon: 4.05, altitudeM: null }));
test('following the clock, a vessel whose next record carries no fixes is placed by the record', () => {
const probe = setup();
probe.reconcile([row('111', { fixes: fixes([0, 1], [60_000, 2]) })], {
replace: true,
});
probe.reconcile([row('111', { lat: 3 })], { follow: true });
assert.equal(probe.store.byId.get('111').fixes, null);
});
+231 -4
View File
@@ -4,10 +4,11 @@ import { createVesselLayer } from './index.js';
import { VISIBILITY_UPDATE_MS } from './policy.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { layerPlacement } from '../../data/placementProvider.js';
import * as Cesium from 'cesium';
// Vessels move only when a poll lands, so the layer must let the scene idle:
// it asks for frames for forced passes and one trailing frame after the camera
// stops, and never schedules a frame from a pass the camera did not cause.
// The layer must let the scene idle: it asks for frames for forced passes,
// for vessels that move, and one trailing frame after the camera stops, and
// never schedules a frame from a pass nothing caused.
const noop = () => {};
@@ -78,7 +79,16 @@ function setup({ focusPassIsNeeded = () => false, placement = null } = {}) {
}
};
const frame = () => layer.testing._runVisibilityPassForTest();
return { layer, camera, requests, holds, timers, advance, frame };
return {
layer,
camera,
requests,
holds,
timers,
advance,
frame,
now: () => clock,
};
}
test('a parked camera schedules no frames after the cadence pass', () => {
@@ -117,6 +127,26 @@ test('a camera that stops inside the cadence gets exactly one trailing frame', (
assert.equal(timers.size, 0);
});
test('following the clock, a time moved inside the cadence gets one trailing frame', () => {
const { layer, requests, timers, advance, frame } = setup();
layer.testing._followClockForTest(1_000_000);
frame();
advance(100);
// A seek while paused: the camera is still, the time drawn is not.
layer.testing._followClockForTest(940_000);
frame();
assert.equal(timers.size, 1);
advance(VISIBILITY_UPDATE_MS);
assert.deepEqual(requests, ['ais-vessels-visibility']);
frame();
for (let i = 0; i < 20; i += 1) {
advance(100);
frame();
}
assert.deepEqual(requests, ['ais-vessels-visibility']);
assert.equal(timers.size, 0);
});
test('a forced pass requests its own frame', () => {
const { layer, requests } = setup();
layer.testing._runVisibilityPassForTest(true);
@@ -239,3 +269,200 @@ test('a placement that places nothing asks for no frames; one that places a draw
advance(1_000);
assert.deepEqual(requests, ['ais-vessels-placement']);
});
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel; a slow one once a second', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
let spot = { lat: 51.93, lon: 4.05 };
const { layer, camera, timers, advance, now } = setup({
placement: { layer: () => ({ place: () => spot }) },
});
// 20 km above the vessel, in a 1,000 px tall view about 57° tall.
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const record = { mmsi: '111', lat: 51.93, lon: 4.05 };
// Drawn: on the camera's side of the horizon.
const drawnVisual = (viewer) => {
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records: [record] });
layer.testing._prepareVesselVisualForTest(record).visible = true;
};
drawnVisual({ camera, scene: {}, canvas: { clientHeight: 1000 } });
// How long after a pass the next frame is asked for, once the vessel moved
// `dLat` in the 16 ms since the pass before.
const waitAfterStep = (dLat) => {
layer.testing._runPlacementPassForTest();
advance(1_000); // whatever frame that asked for comes and goes
assert.equal(timers.size, 0);
mono += 16;
spot = { lat: spot.lat + dLat, lon: spot.lon };
layer.testing._runPlacementPassForTest();
assert.equal(timers.size, 1);
const [timer] = [...timers.values()];
return timer.at - now();
};
// About 11 m in a frame, 20 km away: over half a pixel, so the next frame
// is asked for within the frame.
assert.ok(waitAfterStep(0.0001) <= 16);
// About 1 cm in a frame: half a pixel takes seconds, so once a second.
assert.equal(waitAfterStep(0.0000001), 1000);
// A 2D view 40 km across in 1,000 px: 11 m is over a quarter pixel, so the
// next frame comes within two frames.
camera.frustum = new Cesium.OrthographicOffCenterFrustum({
left: -20_000,
right: 20_000,
bottom: -20_000,
top: 20_000,
near: 1,
far: 1e8,
});
camera.viewMatrix = Cesium.Matrix4.IDENTITY;
drawnVisual({ camera, scene: {}, canvas: { clientWidth: 1000 } });
assert.ok(waitAfterStep(0.0001) <= 32);
});
test('following the clock moves drawn vessels in place each world time, prepares missing ones and leaves hidden ones be', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const { layer, camera, timers, advance } = setup();
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const motion = {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 60_000,
};
const vessel = (mmsi) => ({
mmsi,
lat: 51.94,
lon: 4.05,
motion: { ...motion },
});
const drawn = vessel('111');
const hidden = vessel('222');
const owned = vessel('333');
const missing = vessel('444');
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({
viewer,
records: [drawn, hidden, owned, missing],
});
const visuals = [drawn, hidden, owned].map((record) =>
layer.testing._prepareVesselVisualForTest(record),
);
// Drawn as an icon (on the camera's side of the horizon), hidden, and
// drawn by its model.
visuals[0].visible = true;
visuals[1].visible = false;
visuals[2].visible = false;
visuals[2].modelOwnsVisual = true;
const before = visuals.map((visual) => ({ ...visual.position }));
const positions = visuals.map((visual) => visual.position);
// The first pass also moves hidden vessels, so the next stays within
// HIDDEN_FOLLOW_MS of it.
layer.testing._runClockPassForTest(10_000);
mono += 16;
layer.testing._runClockPassForTest(20_000);
assert.equal(visuals[0].position, positions[0], 'written in place');
assert.notDeepEqual({ ...visuals[0].position }, before[0]);
assert.notDeepEqual({ ...visuals[2].position }, before[2], 'model moves');
const hiddenAt = { ...visuals[1].position };
assert.ok(
layer.testing._vesselVisualForTest(missing).position,
'a missing visual is prepared',
);
assert.equal(timers.size, 1, 'moving vessels ask for a frame');
// The hidden vessel waits for HIDDEN_FOLLOW_MS.
mono += 16;
layer.testing._runClockPassForTest(30_000);
assert.deepEqual({ ...visuals[1].position }, hiddenAt);
mono += 250;
layer.testing._runClockPassForTest(40_000);
assert.notDeepEqual({ ...visuals[1].position }, hiddenAt);
// The same world time again moves nothing and asks for no frame.
advance(1_000);
assert.equal(timers.size, 0);
const still = { ...visuals[0].position };
mono += 16;
layer.testing._runClockPassForTest(40_000);
assert.deepEqual({ ...visuals[0].position }, still);
assert.equal(timers.size, 0);
// Scrubbed back, a vessel moves back.
mono += 16;
layer.testing._runClockPassForTest(20_000);
assert.notDeepEqual({ ...visuals[0].position }, still);
// Each vessel moves once per world time: new fixes at the same world time
// are drawn when the snapshot that brings them prepares the visual.
const backAt = { ...visuals[0].position };
drawn.motion = { ...motion, toLat: 52 };
mono += 16;
layer.testing._runClockPassForTest(20_000);
assert.deepEqual({ ...visuals[0].position }, backAt);
// Past the newest fix, vessels hold still and ask for nothing.
mono += 16;
layer.testing._runClockPassForTest(70_000);
advance(1_000);
mono += 16;
layer.testing._runClockPassForTest(80_000);
assert.equal(timers.size, 0);
});
test('following the clock, a vessel draws no icon before it was there, and draws it once the time comes', (t) => {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const { layer, camera } = setup();
const viewer = { camera, scene: {} };
const { draw } = bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, icons: null });
const first = 1_000_000;
layer.testing._followClockForTest(first - 10 * 60_000);
layer.testing._reconcileVesselsForTest(viewer, [
{
mmsi: '111',
lat: 51.93,
lon: 4.05,
last_position_epoch: first / 1000,
fixes: [
{ atMs: first, lat: 51.93, lon: 4.05 },
{ atMs: first + 60_000, lat: 51.94, lon: 4.05 },
],
},
]);
const shown = () => {
const [set] = [...draw.sets.values()].filter(
(record) => record.kind === 'icons',
);
return set.items.get('111').show;
};
layer.testing._runVisibilityPassForTest(true);
assert.equal(shown(), false, 'ten minutes before its first fix');
layer.testing._followClockForTest(first - 30_000);
layer.testing._runVisibilityPassForTest(true);
assert.equal(shown(), true, 'half a minute before it: reaching it');
});
+212 -70
View File
@@ -9,7 +9,7 @@ import {
} from '../../data/vesselLabels.js';
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js';
import { distance, distanceSquared } from '../../geo/vector.js';
import { copyInto, distance, distanceSquared, vec } from '../../geo/vector.js';
import {
canvasOf,
drawOf,
@@ -29,7 +29,8 @@ import {
CARD_MIN_SEP_PX,
followsClock,
} from './policy.js';
import { vesselPositionAt } from './motion.js';
import { fixesMove, vesselPositionAt } from './motion.js';
import { TIMELINE_UNSEEN_MS } from '../../time/timelineFixes.js';
import {
fleetModelSet,
loadFleetModelSet,
@@ -38,10 +39,15 @@ import {
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { isAidToNavigation } from '../../data/vesselTypes.js';
/** How often vessels move on as the world clock plays (wall ms). */
const FOLLOW_POSITION_MS = 250;
/** A frame is asked for this often while a placement moves live vessels. */
/** A moving vessel's next frame is asked for once it would move this far on
* screen (pixels), so it glides when it moves visibly and the scene idles
* when it does not. */
const VESSEL_STEP_PX = 0.5;
/** A frame is asked for at least this often while any drawn vessel moves. */
const PLACEMENT_FRAME_MS = 1000;
/** How often vessels not drawn move on as the world clock plays (wall ms),
* so one that comes into view is judged where it is. */
const HIDDEN_FOLLOW_MS = 250;
/** The ship artwork's own raster size (px). */
const SHIP_ICON_PX = 32;
@@ -51,6 +57,9 @@ let instances = 0;
/** How often the vessels near enough for a model are gathered again (wall ms). */
const MODEL_CANDIDATES_MS = 500;
/** Scratch for where a moved vessel was drawn. */
const _movedFrom = vec();
export function createRendering({
vesselState,
services,
@@ -87,10 +96,8 @@ export function createRendering({
visual.position = anchorAt(lat, lon);
// A ship model's origin is its waterline: the sea surface, unlifted.
visual.waterline = anchorAt(lat, lon, 0);
if (services.placement) {
visual.drawnLat = lat;
visual.drawnLon = lon;
}
visual.drawnLat = lat;
visual.drawnLon = lon;
return visual;
}
@@ -255,10 +262,13 @@ export function createRendering({
function iconItem(record, visual) {
const selected = record === state.selectedRecord;
const courseDeg = vesselCourseDeg(record);
// Following the clock, not there yet at the time drawn.
visual.seen = seenYet(record);
return {
id: visual.iconId,
// Hidden while the bridge camera rides it, or its model draws it.
show: !isCockpitSubject(record) && !visual.modelOwnsVisual,
// Hidden while the bridge camera rides it, its model draws it, or it
// is not there yet.
show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen,
pos: visual.position,
image: shipIcon(record, selected),
size: [SHIP_ICON_PX, SHIP_ICON_PX],
@@ -289,7 +299,7 @@ export function createRendering({
state.icons.put({ ...iconItem(record, visual), focus: 1 });
if (visual.position)
visual.cullPosition = liftedForHorizon(visual.position);
visual.visible = isVisible(visual.cullPosition, occluder);
visual.visible = isVisible(visual.cullPosition, occluder, record);
}
/**
@@ -429,7 +439,7 @@ export function createRendering({
item.position = getVisual(record).waterline;
// An aid to navigation is a fixed mark: it does not turn to a heading.
item.headingDeg = item.spec?.fixed ? 0 : vesselCourseDeg(record);
item.show = record.id !== state.cockpitSubjectId;
item.show = record.id !== state.cockpitSubjectId && seenYet(record);
return item;
}
@@ -511,11 +521,11 @@ export function createRendering({
modelCandidatesAtMs = -Infinity;
}
// Vessels move only when a poll lands, so the layer does not hold the
// continuous render loop. Its passes run in preRender, which idle mode fires
// only for rendered frames: a forced pass (new data, selection) requests its
// frame, a frame that moved the camera but fell inside the 800 ms cadence
// leaves a trailing frame so the view the camera stopped on is always
// The layer does not hold the continuous render loop. Its passes run in
// preRender, which idle mode fires only for rendered frames: moving vessels
// ask for the frame that next moves them visibly (askMotionFrame), a forced
// pass (new data, selection) requests its frame, a frame that moved the
// camera but fell inside the 800 ms cadence leaves a trailing frame so the view the camera stopped on is always
// evaluated, and the continuous hold is kept only while focus emphasis is
// animating. The trailing frame is keyed to camera motion alone: the pass's
// own label publication requests a frame, and scheduling on that would loop.
@@ -523,71 +533,181 @@ export function createRendering({
if (state.preRenderRemover || !viewer) return;
state.preRenderRemover =
findFrame(viewer)?.on('preRender', () => {
if (followsClock(vesselState)) followClockPositions();
else if (services.placement && state.feed.enabled) followPlacements();
if (state.feed.enabled) {
if (followsClock(vesselState)) followClockPositions();
else if (services.placement) followPlacements();
}
updateVisibility();
if (state.feed.enabled) updateModels();
}) ?? null;
}
// As the world clock plays, vessels between two fixes move on along them.
let followedAtWallMs = -Infinity;
let followedAtMs = null;
// As the world clock plays, vessels between two fixes move on along them:
// drawn ones every frame, each once per world time, hidden ones (which may
// come into view) every HIDDEN_FOLLOW_MS.
let hiddenFollowedAtWallMs = -Infinity;
function followClockPositions() {
const wallMs = performance.now();
if (wallMs - followedAtWallMs < FOLLOW_POSITION_MS) return;
followedAtWallMs = wallMs;
const atMs = vesselState.worldNow();
if (atMs === followedAtMs) return;
followedAtMs = atMs;
const motion = startMotionPass();
const moveHidden =
motion.wallMs - hiddenFollowedAtWallMs >= HIDDEN_FOLLOW_MS;
if (moveHidden) hiddenFollowedAtWallMs = motion.wallMs;
for (const record of state.records.all) {
if (!record.motion) continue;
prepareRecordVisual(record);
syncRecordIcon(record);
if (!record.motion && !fixesMove(record.fixes)) continue;
let visual = visualRecords.get(record);
if (!visual?.position) {
visual = prepareRecordVisual(record);
visual.followedAtMs = atMs;
syncRecordIcon(record);
continue;
}
if (
visual.followedAtMs === atMs ||
(!drawnNow(record, visual) && !moveHidden)
)
continue;
visual.followedAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
// At either end of its fixes a vessel holds still.
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveDrawnVisual(record, visual, lat, lon, motion);
}
askMotionFrame(motion);
}
// Live with a host-supplied placement, vessels move on between refreshes:
// drawn where it places them at most every FOLLOW_POSITION_MS, with a frame
// asked for every PLACEMENT_FRAME_MS while it places any drawn vessel, so
// they move while the scene idles.
let placedAtWallMs = -Infinity;
let placing = false;
let placementFrameTimer = null;
// drawn where it places them every frame, with the next frame asked for
// as soon as a drawn vessel would move visibly, so they move while the
// scene idles.
function followPlacements() {
const wallMs = performance.now();
if (wallMs - placedAtWallMs >= FOLLOW_POSITION_MS) {
placedAtWallMs = wallMs;
placing = false;
const nowMs = vesselState._aisRuntime.now();
// Drawn vessels only, as a sprite or a model: a hidden one is placed
// again when it is drawn.
for (const record of state.records.all) {
const visual = visualRecords.get(record);
if (!visual?.position) continue;
const drawn =
(visual.visible && !isCockpitSubject(record)) ||
visual.modelOwnsVisual;
if (!drawn) continue;
const placed = services.placement.place(record.id, nowMs);
if (placed) placing = true;
const { lat, lon } = placed ?? record;
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveRecordVisual(record, visual, lat, lon);
}
const nowMs = vesselState._aisRuntime.now();
const motion = startMotionPass();
// Drawn vessels only, as a sprite or a model: a hidden one is placed
// again when it is drawn.
for (const record of state.records.all) {
const visual = visualRecords.get(record);
if (!visual?.position) continue;
if (!drawnNow(record, visual)) continue;
const placed = services.placement.place(record.id, nowMs);
if (placed) motion.moving = true;
const { lat, lon } = placed ?? record;
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveDrawnVisual(record, visual, lat, lon, motion);
}
if (placing && placementFrameTimer === null)
placementFrameTimer = vesselState._aisRuntime.setTimeout(() => {
placementFrameTimer = null;
if (state.feed.enabled && !followsClock(vesselState))
governorRequestRender('ais-vessels-placement');
}, PLACEMENT_FRAME_MS);
askMotionFrame(motion);
}
// One pass of moving vessels: whether any drawn vessel is moving, how far
// the fastest moved (as an angle seen from the camera, radians, and in
// metres), the pass's wall time and the wall time since the pass before.
let motionPassWallMs = null;
const motionPass = {
pose: undefined,
wallMs: 0,
sinceMs: 0,
moving: false,
angle: 0,
metres: 0,
};
function startMotionPass() {
const wallMs = performance.now();
// Read once, when a drawn vessel first moves in the pass.
motionPass.pose = undefined;
motionPass.wallMs = wallMs;
motionPass.sinceMs =
motionPassWallMs === null ? 0 : wallMs - motionPassWallMs;
motionPass.moving = false;
motionPass.angle = 0;
motionPass.metres = 0;
motionPassWallMs = wallMs;
return motionPass;
}
/** The camera's pose for a motion pass, read once in it (null without one). */
function motionPose(motion) {
if (motion.pose === undefined)
motion.pose = state.viewer
? (findCamera(state.viewer)?.pose() ?? null)
: null;
return motion.pose;
}
/** Whether a vessel is drawn now: its icon on the camera's side of the
* horizon and not the bridge camera's own vessel, or its model. */
function drawnNow(record, visual) {
return (
(visual.visible && !isCockpitSubject(record)) ||
Boolean(visual.modelOwnsVisual)
);
}
/** Move a drawn visual, noting how far it moved as seen from the camera. */
function moveDrawnVisual(record, visual, lat, lon, motion) {
const from = copyInto(visual.position, _movedFrom);
moveRecordVisual(record, visual, lat, lon);
if (!drawnNow(record, visual)) return;
motion.moving = true;
const metres = distance(from, visual.position);
motion.metres = Math.max(motion.metres, metres);
const eye = motionPose(motion)?.position;
if (!eye) return;
const range = distance(eye, from);
if (range > 0) motion.angle = Math.max(motion.angle, metres / range);
}
/** How far the fastest drawn vessel moved on screen in a pass (pixels):
* through the perspective view's angle, or across the 2D view's width
* (an orthographic projection's, `2 / m00` metres). */
function movedPixels(motion) {
const canvas = state.viewer ? canvasOf(state.viewer) : null;
const pose = motion.pose;
if (!canvas || !pose) return 0;
if (pose.fovy > 0 && canvas.clientHeight > 0)
return (
(motion.angle * canvas.clientHeight) / (2 * Math.tan(pose.fovy / 2))
);
if (pose.fovy > 0 || !(canvas.clientWidth > 0)) return 0;
let width = NaN;
try {
width = 2 / findCamera(state.viewer).matrices().projection[0];
} catch {
return 0;
}
return width > 0 ? (motion.metres * canvas.clientWidth) / width : 0;
}
// The timer for the next vessel frame while one is asked for, and when it
// is due (the AIS runtime's clock).
let placementFrameTimer = null;
let placementFrameDueMs = 0;
/**
* While a drawn vessel moves, ask for the next frame when the fastest one
* will have moved VESSEL_STEP_PX on screen at the speed this pass saw, and
* at most PLACEMENT_FRAME_MS away.
*/
function askMotionFrame(motion) {
if (!motion.moving) return;
let waitMs = PLACEMENT_FRAME_MS;
const movedPx = movedPixels(motion);
if (movedPx > 0 && motion.sinceMs > 0)
waitMs = Math.min(waitMs, (VESSEL_STEP_PX * motion.sinceMs) / movedPx);
// A frame already asked for no later than this one stands.
const runtime = vesselState._aisRuntime;
const dueMs = runtime.now() + waitMs;
if (placementFrameTimer !== null) {
if (placementFrameDueMs <= dueMs) return;
runtime.clearTimeout(placementFrameTimer);
}
placementFrameDueMs = dueMs;
placementFrameTimer = runtime.setTimeout(() => {
placementFrameTimer = null;
if (state.feed.enabled) governorRequestRender('ais-vessels-placement');
}, waitMs);
}
/** Stop asking for placement frames (the layer turned off or went away). */
function cancelPlacementFrame() {
placedAtWallMs = -Infinity;
placing = false;
motionPassWallMs = null;
if (placementFrameTimer === null) return;
vesselState._aisRuntime.clearTimeout(placementFrameTimer);
placementFrameTimer = null;
@@ -629,14 +749,21 @@ export function createRendering({
(regularPass || focusPass || !state.trailingVisibilityTimer)
? findCamera(state.viewer)?.pose()
: null;
// Following the clock, the time drawn decides which vessels are there
// yet: a time that moved since the last pass (a seek while paused) gets
// its pass too.
const worldMs = followsClock(vesselState) ? vesselState.worldNow() : null;
if (
!regularPass &&
pose &&
poseSignature(pose) !== vesselState._lastCamPoseSig
((pose && poseSignature(pose) !== vesselState._lastCamPoseSig) ||
worldMs !== state.visibilityWorldMs)
)
scheduleTrailingVisibilityPass(now);
if (!regularPass && !focusPass) return;
if (regularPass) state.lastVisibilityUpdate = now;
if (regularPass) {
state.lastVisibilityUpdate = now;
state.visibilityWorldMs = worldMs;
}
if (focusPass) state.lastFocusUpdate = now;
if (!state.records.all.length) {
// No records — flush any lingering card entries (vanished-feed case).
@@ -665,7 +792,9 @@ export function createRendering({
const labelCandidates = [];
for (const record of state.records.all) {
const visual = getVisual(record);
visual.visible = isVisible(visual.cullPosition, occluder);
visual.visible = isVisible(visual.cullPosition, occluder, record);
// A vessel the time drawn reaches (or leaves) shows (or hides) its icon.
if (visual.seen !== seenYet(record)) syncRecordIcon(record);
if (visual.visible) labelCandidates.push(record);
}
updateClusteredLabels(labelCandidates);
@@ -760,11 +889,23 @@ export function createRendering({
return pose?.position ? horizonFrom(pose.position) : null;
}
function isVisible(cullPosition, occluder) {
function isVisible(cullPosition, occluder, record) {
if (record && !seenYet(record)) return false;
if (!cullPosition || !occluder) return true;
return occluder.isPointVisible(cullPosition);
}
/** Whether a vessel is there at the time drawn: following the clock, not
* more than TIMELINE_UNSEEN_MS before its first fix. */
function seenYet(record) {
const first = record.fixes?.[0];
return (
!first ||
!followsClock(vesselState) ||
vesselState.worldNow() >= first.atMs - TIMELINE_UNSEEN_MS
);
}
/**
* Source selector for the shared world-overlay pipeline: the
* grid declutter picks which vessels get cards — one winner per screen-space
@@ -957,6 +1098,7 @@ export function createRendering({
cancelTrailingVisibilityPass,
cancelPlacementFrame,
followPlacements,
followClockPositions,
applyVesselFocusDeemphasis,
makeOccluder,
isVisible,
+2
View File
@@ -84,6 +84,8 @@ export function createVesselState({ source, services }) {
/** Pending timer that renders one frame after a cadence-skipped pass. */
trailingVisibilityTimer: null,
lastVisibilityUpdate: 0,
/** Following the clock, the world time the last visibility pass drew. */
visibilityWorldMs: null,
lastFocusUpdate: 0,
/** Sprites whose animated emphasis remains outside the 1.0 deadband. */
activeFocusCount: 0,
+23
View File
@@ -170,12 +170,32 @@ export function createTesting({
return components.rendering.prepareRecordVisual(record);
}
/** A record's visual (the record itself before it has one). Test-only seam. */
function _vesselVisualForTest(record) {
return components.rendering.getVisual(record);
}
/** Run one live placement pass (a host-supplied placement). Test-only seam. */
function _runPlacementPassForTest() {
components.rendering.followPlacements();
}
/** Run one world-clock pass at world time `atMs`. Test-only seam. */
function _runClockPassForTest(atMs) {
vesselState.worldNow = () => atMs;
components.rendering.followClockPositions();
}
/** Follow the world clock, standing at world time `atMs`. Test-only seam. */
function _followClockForTest(atMs) {
vesselState.timeline = { active: () => true };
vesselState.worldNow = () => atMs;
}
/** True while a trailing visibility frame is scheduled. Test-only seam. */
function _hasTrailingVisibilityPassForTest() {
@@ -204,6 +224,7 @@ export function createTesting({
return {
_bindVesselInteractionForTest,
_setVesselStateForTest,
_followClockForTest,
_setVesselOverlayHostForTest,
_updateVesselCardsForTest,
_reconcileVesselsForTest,
@@ -216,7 +237,9 @@ export function createTesting({
_vesselRecordForTest,
_runVisibilityPassForTest,
_prepareVesselVisualForTest,
_vesselVisualForTest,
_runPlacementPassForTest,
_runClockPassForTest,
_hasTrailingVisibilityPassForTest,
};
}
+4 -5
View File
@@ -66,11 +66,10 @@ export function createTracking({
continue;
visual.position = components.rendering.anchorPosition(record);
components.rendering.syncRecordIcon(record);
// A placed vessel is drawn again at its placement on the next pass.
if (services.placement) {
visual.drawnLat = NaN;
visual.drawnLon = NaN;
}
// A moving vessel is drawn again where it is on the next pass.
visual.drawnLat = NaN;
visual.drawnLon = NaN;
visual.followedAtMs = undefined;
}
// The rows moved with no poll behind them: draw the frame that shows it.
governorRequestRender('ais-vessels-refloor');
+36 -5
View File
@@ -16,8 +16,13 @@ import {
acquireInfraredMosaic,
processInfraredImage,
} from './infraredImage.js';
// Bounded display detail for the hourly, approximately 3 km global product.
// Bounded display detail for the hourly, approximately 3 km global product
// when it is drawn from one 2048 × 1024 mosaic.
const GLOBAL_TILE_MAXIMUM_LEVEL = 3;
// Detail of the tiled products when the feed does not name its own.
const TILE_MAXIMUM_LEVEL = 6;
// The deepest level a feed may name: about 150 m a pixel.
const SUPPLIED_MAXIMUM_LEVEL_LIMIT = 12;
// Six decoded 2048×1024 canvases (8 MiB each) bound the cache below 50 MiB.
const MAX_MOSAICS = 6;
const MAX_PREFETCH_TILES = 8;
@@ -89,10 +94,33 @@ function createGlobeRendering({
let prefetchJob = null;
let prefetchedKey = null;
/** The deepest level the feed's own tiles of `product` go to, or null. */
function suppliedLevel(product) {
if (!frameSource?.getTile) return null;
let level = null;
try {
level = frameSource.maximumLevel?.(product) ?? null;
} catch {
return null;
}
return Number.isInteger(level) &&
level >= 0 &&
level <= SUPPLIED_MAXIMUM_LEVEL_LIMIT
? level
: null;
}
/** Global clouds come from one mosaic unless the feed tiles them itself. */
function fromMosaic(product) {
return product === 'clouds' && suppliedLevel(product) === null;
}
function profile(product) {
return {
tileSize: 256,
maximumLevel: product === 'clouds' ? GLOBAL_TILE_MAXIMUM_LEVEL : 6,
maximumLevel:
suppliedLevel(product) ??
(product === 'clouds' ? GLOBAL_TILE_MAXIMUM_LEVEL : TILE_MAXIMUM_LEVEL),
};
}
@@ -287,7 +315,7 @@ function createGlobeRendering({
!snapshot.times.includes(time)
)
return false;
const global = snapshot.product === 'clouds';
const global = fromMosaic(snapshot.product);
const tiles = global ? [] : prefetchTiles(snapshot);
const supplied = !global && Boolean(frameSource?.getTile);
const urls = global || supplied ? [] : tileUrls(snapshot, time, tiles);
@@ -352,7 +380,7 @@ function createGlobeRendering({
lastError = null;
const { west, south, east, north } = snapshot.bounds;
const rectangle = { west, south, east, north };
const global = snapshot.product === 'clouds';
const global = fromMosaic(snapshot.product);
const frame = {
snapshot,
creditSnapshot,
@@ -500,7 +528,10 @@ function createGlobeRendering({
maxConcurrentRequests: 6,
}
: {}),
...(snapshot.product === 'clouds-regional'
// Infrared tiles get the display transfer the mosaic already
// carries.
...(snapshot.product === 'clouds-regional' ||
snapshot.product === 'clouds'
? {
// The transfer runs on the upright tile the renderer
// decoded.
+11 -1
View File
@@ -121,6 +121,10 @@ export function weatherTileUrl(product, time, { size } = {}) {
* degrees) a detail window of it. `getFrameTile` returns one `size`-pixel tile
* of the geographic tiling scheme, or null for a transparent tile. Rows run
* top-down (north first), as an image does. Both honour `signal`.
* `frameMaximumLevel` names the deepest level of that scheme the feed's tiles
* of a product hold detail at (0–12), or null for the layer's own: with it,
* global clouds are drawn from the feed's tiles to that level instead of from
* one 2048 × 1024 image.
* @typedef {object} WeatherFrameFeed
* @property {(request: { product: string, time: string,
* size: { width: number, height: number },
@@ -129,19 +133,25 @@ export function weatherTileUrl(product, time, { size } = {}) {
* @property {(request: { product: string, time: string, z: number, x: number,
* y: number, size: number, signal: AbortSignal })
* => Promise<WeatherPixels | null>} [getFrameTile]
* @property {(product: string) => number | null} [frameMaximumLevel]
*/
/**
* The frame source a feed provides, or null when it has neither method. A
* missing method is left undefined, so that path keeps the routes.
* @param {WeatherFrameFeed | undefined} feed
* @returns {{ getImage?: Function, getTile?: Function } | null}
* @returns {{ getImage?: Function, getTile?: Function,
* maximumLevel?: Function } | null}
*/
export function weatherFrameSource(feed) {
const image = typeof feed?.getFrameImage === 'function';
const tile = typeof feed?.getFrameTile === 'function';
if (!image && !tile) return null;
const level = typeof feed?.frameMaximumLevel === 'function';
return {
maximumLevel: level
? (product) => feed.frameMaximumLevel(product)
: undefined,
getImage: image
? ({ product, time, size, bbox = null, signal }) =>
feed.getFrameImage({ product, time, size, bbox, signal })
+7
View File
@@ -257,6 +257,13 @@ test('a frame source forwards exactly the documented requests to its feed', asyn
assert.equal(imagesOnly.getTile, undefined, 'tiles keep the tile route');
const tilesOnly = weatherFrameSource({ getFrameTile: feed.getFrameTile });
assert.equal(tilesOnly.getImage, undefined, 'images keep the image route');
assert.equal(tilesOnly.maximumLevel, undefined);
const leveled = weatherFrameSource({
getFrameTile: feed.getFrameTile,
frameMaximumLevel: (product) => (product === 'clouds' ? 6 : null),
});
assert.equal(leveled.maximumLevel('clouds'), 6);
assert.equal(leveled.maximumLevel('radar'), null);
});
test('supplied pixels report their drawn size, draw at the origin and close once', (t) => {
+144
View File
@@ -2739,6 +2739,99 @@ test('a frame source supplies regional tiles in place of the tile route, through
h.rendering.clear();
});
test('a frame source that names its tile detail draws global clouds from its tiles to that level', async () => {
let now = 0;
const requests = [];
const h = renderingHarness({
now: () => now,
fetchImpl: () => assert.fail('supplied clouds are not fetched'),
frameSource: {
getImage: () => assert.fail('no mosaic when the feed tiles clouds'),
getTile: async (request) => {
requests.push(request);
return suppliedTile();
},
maximumLevel: (product) => (product === 'clouds' ? 6 : 8),
},
});
h.viewer.scene.globe.tilesLoaded = false;
const loaded = h.rendering.setFrame(globalSnapshot, times[0]);
assert.equal(h.providers.length, 1);
const [provider] = h.providers;
assert.equal(typeof provider.spec.fetchTile, 'function', 'not the route');
assert.equal(provider.spec.maxLevel, 6);
await provider.requestImage(5, 3, 4, {});
assert.deepEqual(
[requests[0].product, requests[0].z, requests[0].x, requests[0].y],
['clouds', 4, 5, 3],
);
now = 500;
h.settle();
assert.equal(await loaded, true);
h.rendering.clear();
// Radar takes the level the feed names for it.
const radar = renderingHarness({
frameSource: {
getTile: async () => suppliedTile(),
maximumLevel: () => 8,
},
});
radar.rendering.setFrame(snapshot, times[0]);
assert.equal(radar.providers[0].spec.maxLevel, 8);
radar.rendering.clear();
});
test("a frame source naming no usable level keeps the layer's own detail", async () => {
for (const maximumLevel of [
() => null,
() => 13,
() => 2.5,
() => 'deep',
() => {
throw new Error('no level');
},
]) {
const h = renderingHarness({
frameSource: { getTile: async () => suppliedTile(), maximumLevel },
});
h.rendering.setFrame(snapshot, times[0]);
assert.equal(h.providers[0].spec.maxLevel, 6);
h.rendering.clear();
// Global clouds stay on the one image, cut to level 3.
let mosaics = 0;
const clouds = renderingHarness({
frameSource: {
getImage: async () => {
mosaics++;
return { width: 2048, height: 1024, close() {} };
},
getTile: () => assert.fail('clouds are not tiled without a level'),
maximumLevel,
},
});
await showMosaic(clouds, times[0]);
assert.equal(mosaics, 1);
assert.equal(clouds.providers[0].spec.maxLevel, 3);
clouds.rendering.clear();
}
// A level without tiles leaves global clouds on the mosaic.
let images = 0;
const h = renderingHarness({
frameSource: {
getImage: async () => {
images++;
return suppliedTile();
},
maximumLevel: () => 6,
},
});
h.rendering.setFrame(globalSnapshot, times[0]);
await flush();
assert.equal(images, 1);
h.rendering.clear();
});
test('a failed supplied tile fails the staged frame through the tile error', async () => {
const h = renderingHarness({
frameSource: {
@@ -2798,6 +2891,57 @@ test("supplied regional infrared tiles get the transfer upright, as the route's
}
});
test('global clouds tiles get the infrared transfer, and prefetch asks for tiles, not the image', async () => {
const hadBitmap = Object.hasOwn(globalThis, 'ImageBitmap');
const previous = globalThis.ImageBitmap;
globalThis.ImageBitmap = class ImageBitmap {
width = 256;
height = 256;
close() {}
};
try {
const requests = [];
const h = renderingHarness({
frameSource: {
getImage: () => assert.fail('no image when the feed tiles clouds'),
getTile: async (request) => {
requests.push(request);
return new globalThis.ImageBitmap();
},
maximumLevel: () => 6,
},
});
void h.rendering.setFrame(globalSnapshot, times[0]);
const [provider] = h.providers;
const decoded = await provider.requestImage(5, 3, 4, {});
const tile = await provider.spec.tileTransform(
{ x: 5, y: 3, level: 4 },
decoded,
);
assert.equal(tile.drawnWith, null, 'drawn upright, not flipped');
assert.ok(tile.pixels, 'the infrared transfer ran');
h.rendering.clear();
requests.length = 0;
const warm = renderingHarness({
frameSource: {
getImage: () => assert.fail('no image when the feed tiles clouds'),
getTile: async (request) => {
requests.push(request);
return new globalThis.ImageBitmap();
},
maximumLevel: () => 6,
},
});
assert.equal(await warm.rendering.prefetch(globalSnapshot, times[1]), true);
assert.ok(requests.length > 0, 'prefetch asked for tiles');
assert.ok(requests.every((request) => request.product === 'clouds'));
warm.rendering.clear();
} finally {
if (hadBitmap) globalThis.ImageBitmap = previous;
else delete globalThis.ImageBitmap;
}
});
test('tiled prefetch asks the frame source for the same level 0/1 tiles and releases them', async (t) => {
const requests = [];
const supplied = [];