feat(cockpit): ride a tracked satellite in an orbital view

With a satellite tracked and no aircraft tracked, Cockpit can ride the
satellite. Entry needs only the Satellites layer; debris can be tracked but
not entered, and voice stays aircraft-only. Double-clicking the tracked
satellite or the entry buttons (reading ORBIT) enter it.

The camera sits on the satellite's per-frame SGP4 position and looks
straight down, turned to the ground track (north-up for a satellite with
none). The optical zoom steps 1x to 8x with a focus pull, the arrows tilt
the view up to 45 degrees off nadir, and Home or 0 returns to nadir. Off
nadir the tilt reads its total angle first and the swath readout becomes an
approximation marked with ≈. While in orbit the map leases flat Esri
imagery, the cloud pass stays off and the view opens in the optical style.

The orbital HUD names the satellite with its owner's flag (from the
flag-icons package, loaded per country) or an organisation badge, its
operator, class, NORAD and COSPAR ids and TLE epoch with the element lines
on request, altitude, orbital speed and the sub-satellite point. CURRENTLY
OVER names the country and its first-level division, or the sea, and from
8x the most prominent populated place nearby, looked up offline from the
bundled Natural Earth packs (populated places are a new pack). The
satellites layer hides the ridden satellite's own marks, dims the other
orbit rings and ignores scene clicks and Escape while held. Exit restores
the camera's field of view and the satellite's follow camera.

C no longer enters or leaves Cockpit, bridge or orbit: it is left to the
app-wide CCTV shortcut, and Escape or the exit button leave first person.
This commit is contained in:
Denis Groshev committed 2026-11-09 00:24:22 +01:00
1 parent a648c9b665
commit 048293fc2a
67 files changed
+6642 -172

No files matched your search

+318
View File
@@ -0,0 +1,318 @@
import * as Cesium from 'cesium';
import { satelliteClassText } from '../../data/satelliteClass.js';
import {
classifySatellite,
cosparIdFromTleLine1,
satelliteClassEnterable,
satelliteOperator,
satelliteOwner,
tleEpochMs,
} from './classes.js';
import { ISS_NORAD } from './policy.js';
/** The layer id a satellite subject carries through Cockpit events and state. */
export const SATELLITE_COCKPIT_LAYER_ID = 'satellites';
/**
* While the Cockpit rides a satellite, every other orbit ring (the ISS ring
* included) draws at this fraction of its normal alpha, so the rings stay
* legible without competing with the nadir picture.
*/
export const COCKPIT_ORBIT_DIM_FACTOR = 0.3;
/**
* Write an orbit ring's alpha as a multiple of the alpha it was built with.
* The ring's per-instance attributes exist only once Cesium has updated the
* primitive; until then nothing is written and the next tick retries.
* @param {{primitive: object, instanceId: string, baseColor: Cesium.Color,
* baseDepthFailColor: Cesium.Color, alphaFactor: number}} path
* @param {number} factor 1 restores the built colours exactly.
* @returns {boolean} True when the ring now carries `factor`.
*/
export function applyOrbitPathAlpha(path, factor) {
if (!path?.primitive || !path.baseColor) return false;
if ((path.alphaFactor ?? 1) === factor) return true;
let attributes;
try {
attributes = path.primitive.getGeometryInstanceAttributes?.(
path.instanceId,
);
} catch {
return false;
}
if (!attributes) return false;
const scaled = (color) => color.withAlpha(color.alpha * factor);
attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
factor === 1 ? path.baseColor : scaled(path.baseColor),
);
attributes.depthFailColor = Cesium.ColorGeometryInstanceAttribute.toValue(
factor === 1 ? path.baseDepthFailColor : scaled(path.baseDepthFailColor),
);
path.alphaFactor = factor;
return true;
}
/**
* Who and what a catalog entry is: class, COSPAR id, TLE, owner, operator.
* Fixed for the entry's life, so it is worked out once and kept on it.
* @param {number} noradId
* @param {object} sat Catalog entry.
*/
function satelliteIdentity(noradId, sat) {
if (sat.cockpitIdentity) return sat.cockpitIdentity;
const satelliteClass =
sat.satelliteClass ||
classifySatellite({ noradId, name: sat.name, group: sat.group });
const epochMs = tleEpochMs(sat.satrec);
const identity = Object.freeze({
satelliteClass,
cosparId: sat.satcat?.cosparId || cosparIdFromTleLine1(sat.line1),
tle:
sat.line1 && sat.line2 && epochMs !== null
? Object.freeze({ line1: sat.line1, line2: sat.line2, epochMs })
: null,
owner: freezeOwner(
satelliteOwner({ ucs: sat.ucs, satcat: sat.satcat, satelliteClass }),
),
operator: satelliteOperator({ ucs: sat.ucs, satelliteClass }),
});
sat.cockpitIdentity = identity;
return identity;
}
function freezeOwner(owner) {
return owner
? Object.freeze({
countryCode: owner.countryCode ?? null,
label: owner.label ?? null,
})
: null;
}
/**
* Normalize the tracked satellite and its per-frame fix into Cockpit subject
* info, in the shape every Cockpit subject kind shares.
* @param {number} noradId NORAD catalog number.
* @param {{name?: string, group?: string}|null} sat Catalog entry.
* @param {{latitude: number, longitude: number, altitude: number,
* speedMps?: number|null, groundTrackDeg?: number|null}|null} fix Per-frame
* SGP4 sample (orbits.js propagatePosition).
* @returns {object|null} Subject info, or null without a usable fix.
*/
export function satelliteCockpitInfo(noradId, sat, fix) {
if (!sat || !fix) return null;
const { latitude, longitude, altitude } = fix;
if (![latitude, longitude, altitude].every(Number.isFinite)) return null;
const isIss = noradId === ISS_NORAD;
const identity = satelliteIdentity(noradId, sat);
return {
kind: 'satellite',
layerId: SATELLITE_COCKPIT_LAYER_ID,
id: String(noradId),
noradId,
name: sat.name?.trim() || `SAT-${noradId}`,
// Localized at read time, as the vessel layer's type label is.
classLabel: satelliteClassText(identity.satelliteClass, sat.group, {
isIss,
}),
latitude,
longitude,
altitudeM: altitude,
// SGP4's TEME velocity: the inertial orbital speed, not ground speed.
velocityMps: Number.isFinite(fix.speedMps) ? fix.speedMps : null,
// Degrees clockwise from north; null for a geostationary satellite.
groundTrackDeg: Number.isFinite(fix.groundTrackDeg)
? fix.groundTrackDeg
: null,
stale: false,
// src/layers/satellites/classes.js: 'stations'|'imaging'|'telecom'|'starlink'|
// 'probes'|'debris'.
satelliteClass: identity.satelliteClass,
// Whether its class may be ridden in the orbital view (debris may not);
// the Cockpit's entry gate reads it (orbitEntryAllowed).
enterable: satelliteClassEnterable(identity.satelliteClass),
// International designator, e.g. '1998-067A'.
cosparId: identity.cosparId,
tle: identity.tle,
// { countryCode: ISO 3166-1 alpha-2 or null (organisations, joint
// owners), label: English name } or null.
owner: identity.owner,
operator: identity.operator,
};
}
/**
* The tracked satellite as a Cockpit orbital-view subject, and the hold that
* hides its own marks while the Cockpit camera rides it.
*
* While held, the tracked dot is hidden (it would sit on the lens), as are
* the point primitives of docked companions (they share the position within
* 2 km) and the subject's orbit ring: a nadir camera on the ring sees its far
* side, dimmed by the ring's depth-fail appearance, drawn straight across the
* Earth's disk. The detection overlay skips the subject too. The tracked
* card needs nothing here: its overlay source already hides in Cockpit mode.
* Every other orbit ring is dimmed to COCKPIT_ORBIT_DIM_FACTOR of its alpha
* while a subject is set; other satellites' points and labels stay as they
* are. Scene clicks and the layer's Escape are ignored while held, so the
* picture cannot untrack its own subject. Release restores exactly what the
* hold hid or dimmed.
*/
export function createCockpitSubject({ state: layerState, parts }) {
/** The subject is held only while it is the tracked satellite. */
function _cockpitHeld() {
return (
layerState._cockpitSubjectNorad !== null &&
layerState._cockpitSubjectNorad === layerState._trackedNorad
);
}
function _setPointShown(noradId, show) {
const point = layerState._points.get(noradId);
// Released points go back to their class's visibility.
if (point) point.show = show && parts.controls._classVisible(noradId);
}
/**
* Apply or release the hold. Idempotent, and cheap enough for the preRender
* tick, which re-applies it while held so catalog rebuilds, enable and the
* orbit toggle cannot re-show what the hold hides.
* @returns {void}
*/
function _syncCockpitSubjectVisuals() {
const held = _cockpitHeld();
const tracked = layerState._trackedNorad;
const dot = layerState._trackedEntity?.point;
if (held) {
if (dot) dot.show = false;
layerState._cockpitHiddenDot = true;
} else if (layerState._cockpitHiddenDot) {
if (dot) dot.show = true;
layerState._cockpitHiddenDot = false;
}
const hiddenPoints = layerState._cockpitHiddenPoints;
const companions = held ? layerState._dockedCompanions : new Set();
for (const noradId of [...hiddenPoints]) {
if (companions.has(noradId)) continue;
hiddenPoints.delete(noradId);
// The tracked primitive stays hidden: its entity draws the dot.
if (noradId !== tracked) _setPointShown(noradId, true);
}
for (const noradId of companions) {
if (noradId === tracked || hiddenPoints.has(noradId)) continue;
hiddenPoints.add(noradId);
_setPointShown(noradId, false);
}
const hiddenPath = layerState._cockpitHiddenPath;
if (hiddenPath !== null && (!held || hiddenPath !== tracked)) {
const path = layerState._orbitPaths.get(hiddenPath);
if (path)
path.primitive.show = parts.controls.satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
layerState._cockpitHiddenPath = null;
}
if (held) {
const path = layerState._orbitPaths.get(tracked);
if (path) {
path.primitive.show = false;
layerState._cockpitHiddenPath = tracked;
}
}
// Every other ring is dimmed for the whole session and restored on
// release; rebuilt rings arrive at full alpha and are dimmed again here.
const subject = layerState._cockpitSubjectNorad;
for (const [noradId, path] of layerState._orbitPaths) {
const dim = subject !== null && noradId !== subject;
applyOrbitPathAlpha(path, dim ? COCKPIT_ORBIT_DIM_FACTOR : 1);
}
}
const methods = {
/**
* The tracked satellite as Cockpit subject info, from the same per-frame
* SGP4 sample the dot and the follow camera use.
* @returns {{kind: 'satellite', layerId: 'satellites', id: string,
* noradId: number, name: string, classLabel: string,
* latitude: number, longitude: number, altitudeM: number,
* velocityMps: number|null, stale: false,
* satelliteClass: 'stations'|'imaging'|'telecom'|'starlink'|'probes'|'debris',
* cosparId: string|null,
* tle: {line1: string, line2: string, epochMs: number}|null,
* owner: {countryCode: string|null, label: string|null}|null,
* operator: string|null}|null} Null while the layer is off or nothing
* is tracked.
*/
getCockpitSubject() {
if (!layerState._enabled || layerState._trackedNorad === null)
return null;
const noradId = layerState._trackedNorad;
return satelliteCockpitInfo(
noradId,
layerState._catalog.get(noradId),
parts.tracking._getTrackedFramePosition(),
);
},
/**
* The tracked satellite's Earth-fixed position this frame: the per-frame
* cache the dot and follow camera read, never a separate propagation.
* @param {Cesium.Cartesian3} [result] Receives the position.
* @returns {Cesium.Cartesian3|null} Null while the layer is off, nothing
* is tracked or no sample has propagated.
*/
getCockpitPosition(result) {
if (!layerState._enabled || layerState._trackedNorad === null)
return null;
if (!parts.tracking._getTrackedFramePosition()) return null;
return Cesium.Cartesian3.clone(layerState._trackedFrameCartesian, result);
},
/**
* Mark the satellite whose position the Cockpit camera occupies, or
* release it. The hold applies while that satellite is tracked.
* @param {string|number|null} noradId Subject NORAD id, or null to release.
* @returns {boolean} Always true.
*/
setCockpitSubject(noradId) {
const next =
noradId === null || noradId === undefined
? null
: parts.tracking._normalizeTrackedNorad(noradId);
if (layerState._cockpitSubjectNorad === next) return true;
layerState._cockpitSubjectNorad = next;
_syncCockpitSubjectVisuals();
return true;
},
/**
* Put the follow camera back on the tracked satellite after the Cockpit
* released it, without re-tracking (no new selection or context events).
* @param {string|number} noradId The satellite the Cockpit rode.
* @returns {boolean} True when that satellite is still tracked and the
* follow camera was restored.
*/
refocusTrackedById(noradId) {
const id = parts.tracking._normalizeTrackedNorad(noradId);
const viewer = layerState._viewer;
const entity = layerState._trackedEntity;
if (
id === null ||
id !== layerState._trackedNorad ||
!viewer ||
!entity ||
!viewer.entities?.contains?.(entity)
)
return false;
viewer.camera?.cancelFlight?.();
viewer.trackedEntity = entity;
return true;
},
};
return { _cockpitHeld, _syncCockpitSubjectVisuals, methods };
}
@@ -0,0 +1,542 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createState } from './state.js';
import { createControls } from './controls.js';
import { createOrbits } from './orbits.js';
import { createLabels } from './labels.js';
import { createTracking } from './tracking.js';
import { createRendering } from './rendering.js';
import { createCatalog } from './catalog.js';
import { createLifecycle } from './lifecycle.js';
import { createInteraction } from './interaction.js';
import { createIngestion } from './ingestion.js';
import {
COCKPIT_ORBIT_DIM_FACTOR,
applyOrbitPathAlpha,
createCockpitSubject,
satelliteCockpitInfo,
} from './cockpitSubject.js';
import { groundTrackBearingDeg } from './orbits.js';
import { ISS_NORAD } from './policy.js';
const COMPANION = 25545;
const GPS = 32711;
function tle(name, id, motion = '15.48899044', inclination = ' 51.6326') {
// Owned synthetic element sets; never live requests. The station pair
// share elements, so the companion is docked to the ISS.
return `${name}\n1 ${id}U 98067A 26289.78971908 .00007803 00000+0 15012-3 0 9995\n2 ${id} ${inclination} 58.3278 0006748 271.9059 88.1156 ${motion}590607`;
}
const GROUP_TEXT = {
stations: [
tle('ISS (ZARYA)', ISS_NORAD),
tle('PROGRESS-MS 31', COMPANION),
].join('\n'),
'gps-ops': tle('GPS FIXTURE', GPS, ' 2.00563000', ' 55.0000'),
};
/** Whether the tracked entity draws its dot (an unset show is shown). */
function dotShown(f) {
const show = f.state._trackedEntity.point.show;
return show === undefined ? true : show.getValue();
}
const SATCAT_HEADER =
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER';
const SATCAT_TEXT = {
stations: [
SATCAT_HEADER,
`ISS (ZARYA),1998-067A,${ISS_NORAD},PAY,+,ISS`,
`PROGRESS-MS 31,2026-001A,${COMPANION},PAY,+,CIS`,
].join('\n'),
// No designator: the TLE's is used.
'gps-ops': [SATCAT_HEADER, `GPS FIXTURE,,${GPS},PAY,+,US`].join('\n'),
};
const UCS = new Map([
[
ISS_NORAD,
{
noradId: ISS_NORAD,
operator: 'NASA/Multinational',
operatorCountry: 'Multinational',
purpose: 'Space Science',
},
],
]);
async function fixture(t) {
const source = {
async readGroup(group) {
const text = GROUP_TEXT[group] || '';
return { ok: true, status: 200, text, stale: false };
},
async readSatcat(group) {
return { ok: true, status: 200, text: SATCAT_TEXT[group] || '' };
},
readUcs: async () => UCS,
};
const noop = () => {};
const services = {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
layerState: { isExplicitLayerStateOrigin: () => false },
focus: {
clearFocusTarget: noop,
publishFocusTargetFromCachedPosition: noop,
getFocusTarget: () => null,
focusNowMs: (now) => now,
focusPassIsNeeded: () => false,
},
context: {
clearTrackedSubjectContext: noop,
getContextStore: () => ({ entities: new Map() }),
refreshTrackedSubjectContext: noop,
selectTrackedSubjectContext: noop,
},
readout: { refreshTrackedReadout: noop },
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
};
const previousDocument = globalThis.document;
globalThis.document = new EventTarget();
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
for (const [name, factory] of Object.entries({
controls: createControls,
orbits: createOrbits,
labels: createLabels,
tracking: createTracking,
rendering: createRendering,
catalog: createCatalog,
interaction: createInteraction,
lifecycle: createLifecycle,
ingestion: createIngestion,
cockpit: createCockpitSubject,
})) {
parts[name] = factory(context);
}
const viewer = {
trackedEntity: undefined,
entities: new Cesium.EntityCollection(),
scene: {
canvas: new EventTarget(),
primitives: new Cesium.PrimitiveCollection(),
preRender: new Cesium.Event(),
frameState: { frameNumber: 1 },
},
trackedEntityChanged: new Cesium.Event(),
};
const { log, warn } = console;
console.log = noop;
console.warn = noop;
await parts.lifecycle.methods.init(viewer);
await parts.ingestion.methods.update(viewer);
parts.lifecycle.methods.enable(viewer);
// GPS is TELECOM, hidden by default; these tests need its point on screen.
parts.controls.methods.setParams({ classes: { telecom: true } });
Object.assign(console, { log, warn });
t.after(() => {
console.log = noop;
if (state._pointCollection) parts.lifecycle.methods.destroy(viewer);
console.log = log;
viewer.scene.primitives.destroy();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
const methods = { ...parts.controls.methods, ...parts.cockpit.methods };
return {
state,
parts,
viewer,
methods,
track(id) {
const log = console.log;
console.log = noop;
try {
return methods.trackById(id);
} finally {
console.log = log;
}
},
nextFrame() {
viewer.scene.frameState.frameNumber += 1;
parts.rendering._preRenderTick();
},
ring: (id) => state._orbitPaths.get(id)?.primitive,
detected: () =>
methods.getDetectableObjects().map((object) => object.sourceId),
};
}
test('no subject while the layer is off or nothing is tracked', async (t) => {
const f = await fixture(t);
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.methods.getCockpitPosition(), null);
assert.equal(f.track(ISS_NORAD), true);
f.state._enabled = false;
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.methods.getCockpitPosition(), null);
});
test('the tracked satellite is a subject read from the per-frame sample', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
const propagate = f.parts.orbits.propagatePosition;
let propagations = 0;
f.parts.orbits.propagatePosition = (...args) => {
propagations += 1;
return propagate(...args);
};
f.viewer.scene.frameState.frameNumber += 1;
const subject = f.methods.getCockpitSubject();
const position = f.methods.getCockpitPosition();
f.methods.getCockpitSubject();
assert.equal(propagations, 1, 'one SGP4 sample per frame for every reader');
assert.equal(subject.kind, 'satellite');
assert.equal(subject.layerId, 'satellites');
assert.equal(subject.id, String(ISS_NORAD));
assert.equal(subject.noradId, ISS_NORAD);
assert.equal(subject.name, 'ISS (ZARYA)');
assert.equal(subject.classLabel, 'STATIONS · ISS');
assert.equal(subject.stale, false);
assert.ok(subject.altitudeM > 150e3 && subject.altitudeM < 1000e3);
assert.ok(subject.velocityMps > 7000 && subject.velocityMps < 8000);
// The same point the tracked dot and follow camera use, as a copy.
const cached = f.state._trackedFrameCartesian;
assert.ok(Cesium.Cartesian3.equals(position, cached));
assert.notEqual(position, cached);
const target = new Cesium.Cartesian3();
assert.equal(f.methods.getCockpitPosition(target), target);
const geodetic = Cesium.Cartographic.fromCartesian(position);
assert.ok(
Math.abs(Cesium.Math.toDegrees(geodetic.latitude) - subject.latitude) <
1e-6,
);
f.parts.orbits.propagatePosition = propagate;
});
test('the subject says what it is, which TLE it flies, and who owns and runs it', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
const iss = f.methods.getCockpitSubject();
assert.equal(iss.satelliteClass, 'stations');
assert.equal(iss.cosparId, '1998-067A');
assert.match(iss.tle.line1, /^1 25544U/);
assert.match(iss.tle.line2, /^2 25544 /);
// Day 289.789… of 2026.
assert.ok(
Math.abs(
iss.tle.epochMs - (Date.UTC(2026, 0, 1) + 288.78971908 * 86_400_000),
) < 1000,
);
assert.deepEqual(
iss.owner,
{ countryCode: null, label: 'Multinational' },
'UCS before SATCAT',
);
assert.equal(iss.operator, 'NASA/Multinational');
assert.equal(
f.methods.getCockpitSubject().owner,
iss.owner,
'worked out once',
);
f.track(GPS);
const gps = f.methods.getCockpitSubject();
assert.equal(gps.satelliteClass, 'telecom');
assert.equal(
gps.cosparId,
'1998-067A',
'from TLE line 1 when SATCAT has none',
);
assert.deepEqual(gps.owner, { countryCode: 'US', label: 'United States' });
assert.equal(gps.operator, null);
// A bare catalog entry still answers every field.
const bare = satelliteCockpitInfo(
GPS,
{ name: 'X', group: 'gps-ops' },
{ latitude: 1, longitude: 2, altitude: 3 },
);
assert.equal(bare.satelliteClass, 'telecom');
// An imaging satellite CelesTrak lists among the brightest objects names
// its class, not the 'visual' group it came in.
const landsat = satelliteCockpitInfo(
49260,
{ name: 'LANDSAT 9', group: 'visual', satelliteClass: 'imaging' },
{ latitude: 1, longitude: 2, altitude: 3 },
);
assert.equal(landsat.classLabel, 'IMAGING');
assert.equal(bare.tle, null);
assert.equal(bare.owner, null);
assert.equal(bare.operator, null);
assert.equal(bare.cosparId, null);
});
test('a GNSS satellite carries its class and an orbital speed', async (t) => {
const f = await fixture(t);
f.track(GPS);
const subject = f.methods.getCockpitSubject();
assert.equal(subject.classLabel, 'TELECOM · GPS');
assert.ok(subject.altitudeM > 19e6 && subject.altitudeM < 21.5e6);
assert.ok(subject.velocityMps > 3500 && subject.velocityMps < 4200);
assert.equal(
satelliteCockpitInfo(
GPS,
{ name: 'X', group: 'gps-ops' },
{
latitude: 1,
longitude: 2,
altitude: 3,
},
).velocityMps,
null,
);
assert.equal(satelliteCockpitInfo(GPS, null, { latitude: 0 }), null);
});
test('holding the subject hides its dot, ring, docked companions and bracket', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
assert.ok(f.state._dockedCompanions.has(COMPANION));
assert.equal(dotShown(f), true);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.ok(f.detected().includes(ISS_NORAD));
assert.equal(f.methods.setCockpitSubject(String(ISS_NORAD)), true);
assert.equal(dotShown(f), false);
assert.equal(f.ring(ISS_NORAD).show, false);
assert.equal(f.state._points.get(COMPANION).show, false);
assert.equal(f.state._points.get(GPS).show, true);
assert.ok(!f.detected().includes(ISS_NORAD));
// Toggling orbits on again cannot bring the ring back while held.
f.methods.setParams({ showOrbits: true });
assert.equal(f.ring(ISS_NORAD).show, true);
f.nextFrame();
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.setCockpitSubject(null);
assert.equal(dotShown(f), true);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
// The tracked primitive stays hidden: the tracked entity draws the dot.
assert.equal(f.state._points.get(ISS_NORAD).show, false);
assert.ok(f.detected().includes(ISS_NORAD));
});
test('a subject that is not tracked holds nothing', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.methods.setCockpitSubject(ISS_NORAD);
f.nextFrame();
assert.equal(dotShown(f), true);
assert.equal(f.ring(GPS).show, true);
assert.equal(f.ring(ISS_NORAD).show, true);
});
test('untracking a held subject gives its marks back', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.stopTracking();
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
assert.equal(f.state._points.get(ISS_NORAD).show, true);
});
test('tracking without a Cockpit subject keeps its marks', async (t) => {
const f = await fixture(t);
f.track(GPS);
for (let i = 0; i < 3; i++) f.nextFrame();
assert.equal(dotShown(f), true);
assert.equal(f.ring(GPS).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
assert.equal(f.state._cockpitHiddenPoints.size, 0);
assert.equal(f.state._cockpitHiddenPath, null);
});
/**
* Give a ring the per-instance attributes Cesium creates on its first
* update, starting from the colours it was built with. Rings in this
* fixture are never rendered, so the test stands in for that update.
*/
function readyRing(f, id) {
const path = f.state._orbitPaths.get(id);
const attributes = {
color: Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.toValue(
path.baseDepthFailColor,
),
};
path.primitive.getGeometryInstanceAttributes = (instanceId) =>
instanceId === path.instanceId ? attributes : undefined;
return attributes;
}
/** A colour attribute's alpha byte. */
const alphaByte = (value) => value[3];
test('a Cockpit subject dims every other orbit ring and restores it exactly', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.nextFrame();
assert.ok(f.ring(ISS_NORAD), 'the ISS ring is drawn beside the tracked one');
const iss = readyRing(f, ISS_NORAD);
const gps = readyRing(f, GPS);
const builtColor = [...iss.color];
const builtDepthFail = [...iss.depthFailColor];
const gpsBuilt = [...gps.color];
f.methods.setCockpitSubject(GPS);
const dimmed = (byte) => Math.round(byte * COCKPIT_ORBIT_DIM_FACTOR);
assert.ok(Math.abs(alphaByte(iss.color) - dimmed(builtColor[3])) <= 1);
assert.ok(
Math.abs(alphaByte(iss.depthFailColor) - dimmed(builtDepthFail[3])) <= 1,
);
assert.deepEqual([...iss.color].slice(0, 3), builtColor.slice(0, 3));
assert.equal(f.ring(ISS_NORAD).show, true, 'other rings stay visible');
assert.equal(f.ring(GPS).show, false, 'the ridden ring stays hidden');
assert.deepEqual([...gps.color], gpsBuilt, 'the ridden ring is not dimmed');
// Other satellites' points stay as they are.
assert.equal(f.state._points.get(COMPANION).show, true);
// A rebuilt ring arrives at full alpha and is dimmed again on the tick.
f.parts.rendering._hideOrbitPath(ISS_NORAD);
f.parts.rendering._showOrbitPath(ISS_NORAD, Cesium.Color.YELLOW);
const rebuilt = readyRing(f, ISS_NORAD);
f.nextFrame();
assert.ok(alphaByte(rebuilt.color) < builtColor[3]);
f.methods.setCockpitSubject(null);
assert.deepEqual(
[...rebuilt.color],
[
...Cesium.ColorGeometryInstanceAttribute.toValue(
f.state._orbitPaths.get(ISS_NORAD).baseColor,
),
],
'released rings get their built colours back exactly',
);
assert.deepEqual(
[...rebuilt.depthFailColor],
[
...Cesium.ColorGeometryInstanceAttribute.toValue(
f.state._orbitPaths.get(ISS_NORAD).baseDepthFailColor,
),
],
);
assert.equal(f.ring(GPS).show, true);
assert.deepEqual([...gps.color], gpsBuilt);
});
test('a ring not yet updated by Cesium is dimmed once it is', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.methods.setCockpitSubject(GPS);
const path = f.state._orbitPaths.get(ISS_NORAD);
assert.equal(path.alphaFactor, 1, 'nothing written before the first update');
const iss = readyRing(f, ISS_NORAD);
f.nextFrame();
assert.equal(path.alphaFactor, COCKPIT_ORBIT_DIM_FACTOR);
assert.ok(alphaByte(iss.color) < 100);
assert.equal(applyOrbitPathAlpha(path, 1), true);
assert.deepEqual(
[...iss.color],
[...Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor)],
);
});
test('a held subject ignores the layer Escape; refocus restores the follow', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
f.parts.interaction._onKeyDown({ key: 'Escape' });
assert.equal(f.state._trackedNorad, ISS_NORAD, 'the Cockpit owns Escape');
// The Cockpit took the follow camera off the entity; refocus puts it back.
f.viewer.trackedEntity = undefined;
f.methods.setCockpitSubject(null);
assert.equal(f.methods.refocusTrackedById(GPS), false, 'not the tracked one');
assert.equal(f.viewer.trackedEntity, undefined);
assert.equal(f.methods.refocusTrackedById(String(ISS_NORAD)), true);
assert.equal(f.viewer.trackedEntity, f.state._trackedEntity);
assert.equal(f.state._trackedNorad, ISS_NORAD);
f.parts.interaction._onKeyDown({ key: 'Escape' });
assert.equal(f.state._trackedNorad, null, 'released, Escape untracks again');
assert.equal(f.methods.refocusTrackedById(ISS_NORAD), false);
});
test('the ground track bearing comes from the SGP4 velocity, less the Earth turning', () => {
const near = (actual, expected) =>
assert.ok(Math.abs(actual - expected) < 0.2, `${actual} vs ${expected}`);
// An ISS-like orbit (51.6°, 7.66 km/s) crossing the equator northbound at
// 0°E: inertially 38.4° from north, but the ground turns east beneath it,
// so the track runs closer to north.
const inclination = (51.6 * Math.PI) / 180;
const iss = {
position: { x: 6771, y: 0, z: 0 },
velocity: {
x: 0,
y: 7.66 * Math.cos(inclination),
z: 7.66 * Math.sin(inclination),
},
};
near(groundTrackBearingDeg(iss.position, iss.velocity, 0, 0, 0), 35.4);
// The same state given in TEME a quarter sidereal turn on (GMST 90°):
// still over 0°E, so the same ground track.
near(
groundTrackBearingDeg(
{ x: 0, y: 6771, z: 0 },
{ x: -iss.velocity.y, y: 0, z: iss.velocity.z },
Math.PI / 2,
0,
0,
),
35.4,
);
// Geostationary: it turns with the Earth, so there is no ground track.
assert.equal(
groundTrackBearingDeg(
{ x: 42164, y: 0, z: 0 },
{ x: 0, y: 3.0747, z: 0 },
0,
0,
0,
),
null,
);
assert.equal(groundTrackBearingDeg(iss.position, null, 0, 0, 0), null);
// The subject passes the sample's track through.
const sat = { name: 'X', group: 'stations' };
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
assert.equal(
satelliteCockpitInfo(1, sat, { ...fix, groundTrackDeg: 35.4 })
.groundTrackDeg,
35.4,
);
assert.equal(satelliteCockpitInfo(1, sat, fix).groundTrackDeg, null);
});
test('the subject says whether its class may be ridden', () => {
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
const subject = (satelliteClass) =>
satelliteCockpitInfo(1, { name: 'X', group: 'visual', satelliteClass }, fix);
assert.equal(subject('debris').enterable, false);
for (const satelliteClass of ['stations', 'imaging', 'telecom', 'starlink', 'probes'])
assert.equal(subject(satelliteClass).enterable, true, satelliteClass);
});
+6 -2
View File
@@ -48,12 +48,13 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Show or hide every point by its class. The tracked satellite's point
* stays hidden (its entity draws the dot). The ISS's ring and label go
* with its class.
* stays hidden (its entity draws the dot), as do points a Cockpit hold hid.
* The ISS's ring and label go with its class.
*/
function _applyClassVisibility() {
for (const [noradId, point] of layerState._points) {
if (noradId === layerState._trackedNorad) continue;
if (layerState._cockpitHiddenPoints?.has(noradId)) continue;
point.show = _classVisible(noradId);
}
_syncIssOrbit();
@@ -253,6 +254,9 @@ export function createControls({ state: layerState, services, parts, source }) {
// that card instead. Only members of the tracked cluster are affected —
// unrelated nearby satellites are never suppressed.
if (!isTracked && layerState._dockedCompanions.has(noradId)) continue;
// The Cockpit camera rides a held subject; a bracket on it would sit
// on the lens.
if (isTracked && parts.cockpit?._cockpitHeld()) continue;
const cat = layerState._catalog.get(noradId);
let object = layerState._detectionObjects.get(noradId);
if (!object) {
+3
View File
@@ -1,5 +1,6 @@
import { createControls } from './controls.js';
import { createCatalog } from './catalog.js';
import { createCockpitSubject } from './cockpitSubject.js';
import { createLabels } from './labels.js';
import { createOrbits } from './orbits.js';
import { createRendering } from './rendering.js';
@@ -29,9 +30,11 @@ export function createSatellitesLayer({ services, source }) {
parts.interaction = createInteraction(context);
parts.lifecycle = createLifecycle(context);
parts.ingestion = createIngestion(context);
parts.cockpit = createCockpitSubject(context);
return Object.assign(
{},
parts.controls.methods,
parts.cockpit.methods,
parts.lifecycle.methods,
parts.ingestion.methods,
{
+2
View File
@@ -118,6 +118,8 @@ export function createIngestion({
const satcat = layerState._satcat.get(noradId) || null;
if (satcat === sat.satcat) continue;
sat.satcat = satcat;
// The Cockpit identity (owner, COSPAR id) reads SATCAT too.
sat.cockpitIdentity = undefined;
const next = classifySatellite({
noradId,
name: sat.name,
+5
View File
@@ -10,6 +10,8 @@ export function createInteraction({
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
function _onKeyDown(e) {
// The Cockpit owns Escape while it rides the tracked satellite.
if (parts.cockpit?._cockpitHeld()) return;
if (layerState._enabled && e.key === 'Escape' && layerState._trackedNorad) {
parts.tracking._cancelPendingTrackingRestore();
parts.tracking._clearTracking(false, { origin: 'user' });
@@ -50,6 +52,9 @@ export function createInteraction({
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
if (!layerState._enabled) return;
// The Cockpit camera rides the tracked satellite: a click on the
// picture below must not untrack it or switch satellites.
if (parts.cockpit?._cockpitHeld()) return;
const picked = viewer.scene.pick(click.position);
if (picked) {
+4
View File
@@ -32,6 +32,10 @@ export function createLifecycle({
layerState._trackedFrameNumber = -1;
layerState._trackedFrameGeo = null;
layerState._trackedFrameNowForTest = null;
// The new catalog's points and rings carry no hold.
layerState._cockpitHiddenPoints = new Set();
layerState._cockpitHiddenPath = null;
layerState._cockpitHiddenDot = false;
layerState._lastFocusUpdate = 0;
layerState._activeFocusCount = 0;
layerState._enabled = false;
+62 -2
View File
@@ -15,6 +15,57 @@ import {
} from '../../sources/tle.js';
import { ORBIT_PATH_STEPS, ISS_NORAD } from './policy.js';
/** The Earth's rotation rate, rad/s (WGS84). */
const EARTH_ROTATION_RAD_S = 7.292115e-5;
/** Below this ground speed a satellite holds still over the ground (GEO), m/s. */
const GROUND_TRACK_MIN_SPEED_MPS = 10;
/**
* The ground track's bearing, degrees clockwise from north, from one SGP4
* state: the inertial velocity turned into the Earth-fixed frame, less the
* Earth's rotation under the satellite, read in the east/north plane at the
* sub-satellite point. Null without a velocity, or for a satellite that holds
* still over the ground (geostationary).
* @param {{x: number, y: number, z: number}} positionKm TEME position, km.
* @param {{x: number, y: number, z: number}|null} velocityKmS TEME velocity, km/s.
* @param {number} gmst Greenwich mean sidereal time, radians.
* @param {number} latitudeDeg Sub-satellite latitude.
* @param {number} longitudeDeg Sub-satellite longitude.
* @returns {number|null}
*/
export function groundTrackBearingDeg(
positionKm,
velocityKmS,
gmst,
latitudeDeg,
longitudeDeg,
) {
if (!positionKm || !velocityKmS || !Number.isFinite(gmst)) return null;
const cosG = Math.cos(gmst);
const sinG = Math.sin(gmst);
// TEME to Earth-fixed is a turn about z by GMST.
const rx = cosG * positionKm.x + sinG * positionKm.y;
const ry = -sinG * positionKm.x + cosG * positionKm.y;
const vx =
(cosG * velocityKmS.x + sinG * velocityKmS.y + EARTH_ROTATION_RAD_S * ry) *
1000;
const vy =
(-sinG * velocityKmS.x + cosG * velocityKmS.y - EARTH_ROTATION_RAD_S * rx) *
1000;
const vz = velocityKmS.z * 1000;
const φ = (latitudeDeg * Math.PI) / 180;
const λ = (longitudeDeg * Math.PI) / 180;
const east = -Math.sin(λ) * vx + Math.cos(λ) * vy;
const north =
-Math.sin(φ) * Math.cos(λ) * vx -
Math.sin(φ) * Math.sin(λ) * vy +
Math.cos(φ) * vz;
if (![east, north].every(Number.isFinite)) return null;
if (Math.hypot(east, north) < GROUND_TRACK_MIN_SPEED_MPS) return null;
return ((Math.atan2(east, north) * 180) / Math.PI + 360) % 360;
}
export function createOrbits({ state: layerState, services, parts, source }) {
/**
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
@@ -68,11 +119,20 @@ export function createOrbits({ state: layerState, services, parts, source }) {
? Math.hypot(velocity.x, velocity.y, velocity.z) * 1000
: null;
const latitude = degreesLat(geo.latitude);
const longitude = degreesLong(geo.longitude);
return {
longitude: degreesLong(geo.longitude),
latitude: degreesLat(geo.latitude),
longitude,
latitude,
altitude: geo.height * 1000, // km → meters
speedMps: Number.isFinite(speedMps) ? speedMps : null,
groundTrackDeg: groundTrackBearingDeg(
posVel.position,
velocity,
gmst,
latitude,
longitude,
),
};
} catch {
return null;
+17 -6
View File
@@ -47,21 +47,23 @@ export function createRendering({
if (basePositions.length < 2) return;
const pathColor = color || Cesium.Color.CYAN;
// Kept so the Cockpit's orbit dim (cockpitSubject.js) restores exactly.
const baseColor = pathColor.withAlpha(0.6);
const baseDepthFailColor = pathColor.withAlpha(0.35);
const instanceId = `satellite-orbit:${noradId}`;
const primitive = new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
id: instanceId,
geometry: new Cesium.PolylineGeometry({
positions: basePositions,
width: noradId === ISS_NORAD ? 2.5 : 2.0,
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.6),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.35),
),
color: Cesium.ColorGeometryInstanceAttribute.fromColor(baseColor),
depthFailColor:
Cesium.ColorGeometryInstanceAttribute.fromColor(baseDepthFailColor),
},
}),
appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
@@ -79,6 +81,11 @@ export function createRendering({
// GMST value (gstime is pure), so delta starts at exactly 0 and the
// initial identity modelMatrix is correct until the first ring tick.
gmstAtBake: gstime(bakeDate),
instanceId,
baseColor,
baseDepthFailColor,
// The alpha multiple last written to the instance (1: as built).
alphaFactor: 1,
});
}
@@ -204,6 +211,10 @@ export function createRendering({
}
}
// While the Cockpit rides the tracked satellite, keep its marks hidden.
if (layerState._cockpitSubjectNorad !== null)
parts.cockpit?._syncCockpitSubjectVisuals();
_updatePointFocus(now);
// Hidden standalone orbit primitives do not need GMST matrix writes while
+11
View File
@@ -173,6 +173,17 @@ export function createState({ services }) {
state._trackedFrameNowForTest = null;
// Cockpit orbital-view hold (cockpitSubject.js): the NORAD id the Cockpit
// camera rides, and what the hold hid so release restores exactly that.
state._cockpitSubjectNorad = null;
state._cockpitHiddenPoints = new Set();
state._cockpitHiddenPath = null;
state._cockpitHiddenDot = false;
// Scratch variables
state._scratchCartesian = new Cesium.Cartesian3();
+3
View File
@@ -120,6 +120,9 @@ export function createTracking({ state: layerState, services, parts, source }) {
}
layerState._trackedNorad = null;
parts.controls._syncIssOrbit?.();
// A held Cockpit subject that stops being tracked gets its marks back.
if (layerState._cockpitSubjectNorad !== null)
parts.cockpit?._syncCockpitSubjectVisuals();
parts.labels._syncIssOverlay();
clearTrackedSubjectContext('satellites');
layerState._contextRefreshedAtMs = 0;