ISS live telemetry, STATION and LIVE sections, Tiangong model, drawn through the renderer's draw port

Builds on the ISS 3D model (PR #1690) and brings it onto main's renderer
seam: the station models are items of a `models` draw set, posed by
heading, pitch and roll from the station's flight axes
(`headingPitchRollOfAxes`), with the camera, canvas and clicks read from
the renderer's ports; no satellites file reaches Cesium. The joint drivers
write column-major matrices into node poses the model part keeps, for a
renderer that can pose nodes; until the draw contract has that member the
models draw rigid.

- ISS joints take their angles from NASA's ISSLive telemetry, relayed by
  the server behind ISS_TELEMETRY_ENABLED.
- STATION and LIVE sections of Context replace the floating command panel
  and player; both collapse like the Radio section.
- Cockpit rides the ISS from mounts on its model; the LIVE page in the
  Cockpit briefing.
- Tiangong as a second station model, with computed joints.
- Installations: a label-box click selects the site.
This commit is contained in:
Denis Groshev committed 2026-11-16 18:39:39 +01:00
1 parent fd3ca679ec
commit 9cc077964f
103 files changed
+12033 -1775

No files matched your search

+1 -54
View File
@@ -5,6 +5,7 @@ import {
findQuery,
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { loadYouTubeApi } from './youtubeApi.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
const YOUTUBE_HOSTS = new Set([
@@ -98,60 +99,6 @@ export function bhoteEventText(value) {
let _xWidgetsPromise = null;
let _facebookSdkPromise = null;
let _facebookEmbedSequence = 0;
const youtubeApis = new WeakMap();
function loadYouTubeApi(documentRef, globalRef) {
if (typeof globalRef.YT?.Player === 'function')
return Promise.resolve(globalRef.YT);
if (youtubeApis.has(documentRef)) return youtubeApis.get(documentRef);
const pending = new Promise((resolve, reject) => {
const previous = globalRef.onYouTubeIframeAPIReady;
let timer;
let settled = false;
const script = documentRef.createElement('script');
const finish = (error) => {
if (settled) return;
settled = true;
globalRef.clearTimeout(timer);
if (globalRef.onYouTubeIframeAPIReady === ready)
globalRef.onYouTubeIframeAPIReady = previous;
if (error) {
script.remove();
reject(error);
} else resolve(globalRef.YT);
};
const ready = () => {
try {
previous?.();
} finally {
finish(
typeof globalRef.YT?.Player === 'function'
? null
: new Error('YouTube API unavailable'),
);
}
};
globalRef.onYouTubeIframeAPIReady = ready;
script.src = 'https://www.youtube.com/iframe_api';
script.async = true;
script.addEventListener(
'error',
() => finish(new Error('YouTube API unavailable')),
{ once: true },
);
timer = globalRef.setTimeout(
() => finish(new Error('YouTube API timed out')),
5000,
);
documentRef.head.append(script);
}).catch((error) => {
youtubeApis.delete(documentRef);
throw error;
});
youtubeApis.set(documentRef, pending);
return pending;
}
/** A trimmed clip follows provider time, never time spent loading its iframe. */
export function createTrimmedYouTubePlayback({
iframe,
+14 -2
View File
@@ -172,11 +172,23 @@ export const DATA_CREDITS = [
'ISS model: ' +
'<a href="https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/" target="_blank" rel="noopener">NASA 3D Resources</a> (JSC IGOAL)',
},
{
key: 'tiangong-model',
html:
"Tiangong model: made for God's Eye View; dimensions from " +
'<a href="https://doi.org/10.34133/space.0035" target="_blank" rel="noopener">Wang, Zhang &amp; Wang 2023</a> ' +
'(CC BY 4.0) and eoPortal',
},
{
key: 'nasa-iss-telemetry',
html: 'ISS joint telemetry (where switched on): NASA ISSLive, via Lightstreamer',
},
{
key: 'nasa-iss-live',
html:
'ISS live video: NASA, via ' +
'<a href="https://www.youtube.com/watch?v=ROboUHfPUrU" target="_blank" rel="noopener">YouTube</a>',
'ISS live video (LIVE section): NASA, via YouTube ' +
'(<a href="https://www.youtube.com/watch?v=ROboUHfPUrU" target="_blank" rel="noopener">exterior cameras</a>, ' +
'<a href="https://www.youtube.com/watch?v=M3HKLzjvKPc" target="_blank" rel="noopener">live video and audio</a>)',
},
{
key: 'ucs-satellite-database',
+83
View File
@@ -0,0 +1,83 @@
import { msg } from '../i18n/marker.js';
/**
* Live streams the app can show for a selected object: a fixed list, each
* entry a broadcast on a platform's own player (YouTube today), attached to
* the subjects it shows by key. Any layer can name its selected subject's
* keys (`getLiveSubjectKeys`), and the LIVE section in Context offers the
* streams that match; the satellites layer names the ISS as `station:iss`
* whichever of the station's catalog entries is selected.
*
* These are broadcasts in the platform's embedded player, not camera feeds:
* the CCTV layer is for those. A stream's id changes when its broadcaster
* restarts it, so each entry is one line to update.
*/
/** Where YouTube's embedded player is served from: the privacy-enhanced host. */
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
/** @typedef {{id: string, platform: 'youtube', videoId: string, title: string,
* owner: string, ownerUrl: string, subjects: readonly string[],
* note: string}} LiveStream */
/** @type {readonly LiveStream[]} */
export const LIVE_STREAMS = Object.freeze([
Object.freeze({
id: 'iss-exterior',
platform: 'youtube',
videoId: 'ROboUHfPUrU',
title: msg('Exterior cameras'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
Object.freeze({
id: 'iss-crew',
platform: 'youtube',
videoId: 'M3HKLzjvKPc',
title: msg('Live video and space-to-ground audio'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
]);
/**
* The streams attached to any of `subjectKeys`, in list order.
* @param {Iterable<string>|null|undefined} subjectKeys
* @param {readonly LiveStream[]} [streams]
* @returns {LiveStream[]}
*/
export function liveStreamsFor(subjectKeys, streams = LIVE_STREAMS) {
const keys = new Set(subjectKeys ?? []);
if (!keys.size) return [];
return streams.filter((stream) =>
stream.subjects.some((subject) => keys.has(subject)),
);
}
/** The video's own page, for the "Open on YouTube" link. */
export function youtubeWatchUrl(videoId) {
return `https://www.youtube.com/watch?v=${encodeURIComponent(videoId)}`;
}
/**
* The parameters the live player is created with: starts on creation (the
* player is built as soon as a subject with a stream is selected), muted so
* the browser lets it, inline on phones, no related videos, and the page's
* origin so the player API may be spoken to.
* @param {string} origin The page's origin.
* @returns {Record<string, string|number>}
*/
export function youtubeLivePlayerVars(origin) {
return {
autoplay: 1,
mute: 1,
playsinline: 1,
rel: 0,
enablejsapi: 1,
...(origin ? { origin } : {}),
};
}
+80
View File
@@ -0,0 +1,80 @@
// src/data/liveStreams.test.mjs — the fixed list of live streams and how a
// selected object's keys pick from it.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
LIVE_STREAMS,
YOUTUBE_EMBED_HOST,
liveStreamsFor,
youtubeLivePlayerVars,
youtubeWatchUrl,
} from './liveStreams.js';
test('every listed stream is a complete YouTube entry with a distinct id', () => {
assert.ok(LIVE_STREAMS.length >= 2, 'the ISS has two streams');
const ids = new Set(LIVE_STREAMS.map((stream) => stream.id));
assert.equal(ids.size, LIVE_STREAMS.length);
for (const stream of LIVE_STREAMS) {
assert.equal(stream.platform, 'youtube');
assert.match(stream.videoId, /^[\w-]{11}$/, `${stream.id} video id`);
assert.ok(stream.title.length > 0);
assert.ok(stream.owner.length > 0);
assert.match(stream.ownerUrl, /^https:\/\/www\.youtube\.com\//);
assert.ok(stream.subjects.length > 0, `${stream.id} names a subject`);
assert.ok(Object.isFrozen(stream), 'entries cannot be edited at run time');
}
});
test('the ISS streams attach to the station key, in list order', () => {
const found = liveStreamsFor(['station:iss']);
assert.deepEqual(
found.map((stream) => stream.id),
['iss-exterior', 'iss-crew'],
);
});
test('a key no stream names, or no keys at all, finds nothing', () => {
assert.deepEqual(liveStreamsFor(['satellites:25544']), []);
assert.deepEqual(liveStreamsFor([]), []);
assert.deepEqual(liveStreamsFor(null), []);
assert.deepEqual(liveStreamsFor(undefined), []);
});
test('a subject known by several keys gets the union, each stream once', () => {
const streams = [
{ id: 'a', subjects: ['x'] },
{ id: 'b', subjects: ['y', 'x'] },
{ id: 'c', subjects: ['z'] },
];
assert.deepEqual(
liveStreamsFor(new Set(['x', 'y']), streams).map((s) => s.id),
['a', 'b'],
);
});
test('the watch link is the video page on YouTube proper', () => {
assert.equal(
youtubeWatchUrl('ROboUHfPUrU'),
'https://www.youtube.com/watch?v=ROboUHfPUrU',
);
assert.equal(
youtubeWatchUrl('a b&c'),
'https://www.youtube.com/watch?v=a%20b%26c',
);
});
test('the player is created on the privacy-enhanced host, muted, with the API on', () => {
assert.equal(YOUTUBE_EMBED_HOST, 'https://www.youtube-nocookie.com');
const vars = youtubeLivePlayerVars('http://localhost:5190');
assert.equal(vars.autoplay, 1);
assert.equal(vars.mute, 1);
assert.equal(vars.playsinline, 1);
assert.equal(vars.rel, 0);
assert.equal(vars.enablejsapi, 1);
assert.equal(vars.origin, 'http://localhost:5190');
assert.equal(
'origin' in youtubeLivePlayerVars(undefined),
false,
'no origin is passed when the page has none',
);
});
+68
View File
@@ -0,0 +1,68 @@
/**
* YouTube's IFrame Player API, loaded once per document: the only in-page
* way to learn a player's state (playing, ended) and errors (video gone,
* embedding refused), which the live-stream player needs to tell an offline
* stream from one still loading. The page's script-src allows
* `https://www.youtube.com`.
*/
const youtubeApis = new WeakMap();
/**
* Load the API, or return the one already there.
* @param {Document} documentRef
* @param {object} globalRef The window: `YT`, `onYouTubeIframeAPIReady`,
* timers.
* @returns {Promise<object>} The `YT` namespace.
*/
export function loadYouTubeApi(documentRef, globalRef) {
if (typeof globalRef.YT?.Player === 'function')
return Promise.resolve(globalRef.YT);
if (youtubeApis.has(documentRef)) return youtubeApis.get(documentRef);
const pending = new Promise((resolve, reject) => {
const previous = globalRef.onYouTubeIframeAPIReady;
let timer;
let settled = false;
const script = documentRef.createElement('script');
const finish = (error) => {
if (settled) return;
settled = true;
globalRef.clearTimeout(timer);
if (globalRef.onYouTubeIframeAPIReady === ready)
globalRef.onYouTubeIframeAPIReady = previous;
if (error) {
script.remove();
reject(error);
} else resolve(globalRef.YT);
};
const ready = () => {
try {
previous?.();
} finally {
finish(
typeof globalRef.YT?.Player === 'function'
? null
: new Error('YouTube API unavailable'),
);
}
};
globalRef.onYouTubeIframeAPIReady = ready;
script.src = 'https://www.youtube.com/iframe_api';
script.async = true;
script.addEventListener(
'error',
() => finish(new Error('YouTube API unavailable')),
{ once: true },
);
timer = globalRef.setTimeout(
() => finish(new Error('YouTube API timed out')),
5000,
);
documentRef.head.append(script);
}).catch((error) => {
youtubeApis.delete(documentRef);
throw error;
});
youtubeApis.set(documentRef, pending);
return pending;
}
+123
View File
@@ -0,0 +1,123 @@
import { loadYouTubeApi } from './youtubeApi.js';
import { YOUTUBE_EMBED_HOST, youtubeLivePlayerVars } from './liveStreams.js';
/**
* One live stream in YouTube's embedded player, with its state read back
* through the player API: `loading` until the video plays, `playing`, and
* `offline` once the player says the video has ended, cannot be found or
* never starts. The player cannot say "this broadcast is off air" in so
* many words: a live stream that is off air is reported as a video that
* cannot play, or that never reaches playing, so both read as offline here.
* Embedding refused by the video's owner is `unavailable`, which no retry
* will change.
*/
/** A stream that has not started playing this long after its player was ready is offline. */
export const LIVE_START_TIMEOUT_MS = 25_000;
/** YouTube's player states. */
const ENDED = 0;
const PLAYING = 1;
/** Error codes: embedding not allowed on this page. */
const EMBED_REFUSED = new Set([101, 150]);
/**
* @param {{host: HTMLElement, videoId: string, documentRef?: Document,
* globalRef?: object, loadApi?: typeof loadYouTubeApi,
* onChange: (state: {state: 'loading'|'playing'|'offline'|'unavailable',
* reason: string|null}) => void}} options `host` is emptied and given the
* player's iframe.
* @returns {{destroy: () => void}}
*/
export function createYouTubeLivePlayer({
host,
videoId,
documentRef = globalThis.document,
globalRef = globalThis,
loadApi = loadYouTubeApi,
onChange,
}) {
let destroyed = false;
let player = null;
let timer = null;
let current = null;
const set = (state, reason = null) => {
if (destroyed || current === state) return;
current = state;
onChange({ state, reason });
};
const clearTimer = () => {
if (timer !== null) globalRef.clearTimeout(timer);
timer = null;
};
const armTimer = () => {
clearTimer();
timer = globalRef.setTimeout(() => {
timer = null;
if (current === 'loading') set('offline', 'timeout');
}, LIVE_START_TIMEOUT_MS);
};
set('loading');
host.replaceChildren();
const mount = documentRef.createElement('div');
host.append(mount);
loadApi(documentRef, globalRef).then(
(YT) => {
if (destroyed) return;
try {
player = new YT.Player(mount, {
host: YOUTUBE_EMBED_HOST,
videoId,
playerVars: youtubeLivePlayerVars(globalRef.location?.origin),
events: {
onReady: () => {
if (!destroyed) armTimer();
},
onStateChange: (event) => {
if (destroyed) return;
if (event?.data === PLAYING) {
clearTimer();
set('playing');
} else if (event?.data === ENDED) {
clearTimer();
set('offline', 'ended');
}
},
onError: (event) => {
if (destroyed) return;
clearTimer();
const code = Number(event?.data);
if (EMBED_REFUSED.has(code)) set('unavailable', `error-${code}`);
else set('offline', `error-${code}`);
},
},
});
// The API may never call onReady for a video it cannot load.
armTimer();
} catch {
set('offline', 'player');
}
},
() => {
if (!destroyed) set('unavailable', 'api');
},
);
return {
destroy() {
if (destroyed) return;
destroyed = true;
clearTimer();
try {
player?.destroy?.();
} catch {
// A player half-created has nothing to destroy.
}
player = null;
host.replaceChildren();
},
};
}
+188
View File
@@ -0,0 +1,188 @@
// src/data/youtubeLivePlayer.test.mjs — one live stream in YouTube's player,
// with the player API faked: its states and errors read back as the LIVE
// section's loading / playing / offline / unavailable.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
LIVE_START_TIMEOUT_MS,
createYouTubeLivePlayer,
} from './youtubeLivePlayer.js';
import { YOUTUBE_EMBED_HOST } from './liveStreams.js';
/** A stand-in for the panel's host element: counts what is put in it. */
function fakeHost() {
return {
children: [],
replaceChildren() {
this.children = [];
},
append(...nodes) {
this.children.push(...nodes);
},
};
}
/**
* The player as YouTube's API builds it: records its options and lets the
* test fire its events.
*/
function fakeApi() {
const players = [];
class Player {
constructor(mount, options) {
this.mount = mount;
this.options = options;
this.destroyed = 0;
players.push(this);
}
fire(name, data) {
this.options.events[name]?.({ data, target: this });
}
destroy() {
this.destroyed += 1;
}
}
return { YT: { Player }, players };
}
function fixture({ apiFails = false } = {}) {
const api = fakeApi();
const timers = [];
const globalRef = {
location: { origin: 'http://localhost:5190' },
setTimeout(callback, delay) {
const id = timers.length + 1;
timers.push({ id, callback, delay, cleared: false });
return id;
},
clearTimeout(id) {
const timer = timers.find((entry) => entry.id === id);
if (timer) timer.cleared = true;
},
};
const documentRef = { createElement: (tag) => ({ tag }) };
const states = [];
const host = fakeHost();
const player = createYouTubeLivePlayer({
host,
videoId: 'ROboUHfPUrU',
documentRef,
globalRef,
loadApi: () =>
apiFails ? Promise.reject(new Error('blocked')) : Promise.resolve(api.YT),
onChange: (state) => states.push(state),
});
// Let the API promise settle and the player be built.
const settle = () => new Promise((resolve) => setImmediate(resolve));
const pending = () => timers.filter((timer) => !timer.cleared);
return { api, timers, pending, states, host, player, settle };
}
test('the player is built on the privacy host with the live parameters, once the API loads', async () => {
const { api, states, host, settle } = fixture();
assert.deepEqual(states, [{ state: 'loading', reason: null }]);
assert.equal(host.children.length, 1, 'a mount for the iframe is placed');
await settle();
assert.equal(api.players.length, 1);
const { options } = api.players[0];
assert.equal(options.host, YOUTUBE_EMBED_HOST);
assert.equal(options.videoId, 'ROboUHfPUrU');
assert.equal(options.playerVars.enablejsapi, 1);
assert.equal(options.playerVars.mute, 1);
assert.equal(options.playerVars.origin, 'http://localhost:5190');
});
test('playing clears the start timer; the same state is not reported twice', async () => {
const { api, pending, states, settle } = fixture();
await settle();
const [player] = api.players;
player.fire('onReady');
assert.equal(pending().length, 1, 'one start timer is running');
assert.equal(pending()[0].delay, LIVE_START_TIMEOUT_MS);
player.fire('onStateChange', 1);
player.fire('onStateChange', 1);
assert.equal(pending().length, 0, 'the timer went when playback began');
assert.deepEqual(states.at(-1), { state: 'playing', reason: null });
assert.equal(states.length, 2);
});
test('a video that ends, or errors for any other reason, reads as offline', async () => {
const ended = fixture();
await ended.settle();
ended.api.players[0].fire('onStateChange', 0);
assert.deepEqual(ended.states.at(-1), { state: 'offline', reason: 'ended' });
const errored = fixture();
await errored.settle();
errored.api.players[0].fire('onError', 100);
assert.deepEqual(errored.states.at(-1), {
state: 'offline',
reason: 'error-100',
});
assert.equal(errored.pending().length, 0, 'the start timer is cleared');
});
test('embedding refused by the owner is unavailable, which no retry would change', async () => {
for (const code of [101, 150]) {
const { api, states, settle } = fixture();
await settle();
api.players[0].fire('onError', code);
assert.deepEqual(states.at(-1), {
state: 'unavailable',
reason: `error-${code}`,
});
}
});
test('a stream that never starts playing is offline when the start timer runs out', async () => {
const { api, pending, states, settle } = fixture();
await settle();
api.players[0].fire('onReady');
const [timer] = pending();
timer.callback();
assert.deepEqual(states.at(-1), { state: 'offline', reason: 'timeout' });
// Buffering states before the timer do not count as playing.
assert.equal(
states.some((entry) => entry.state === 'playing'),
false,
);
});
test('a timer that fires after playback began changes nothing', async () => {
const { api, timers, states, settle } = fixture();
await settle();
api.players[0].fire('onReady');
api.players[0].fire('onStateChange', 1);
for (const timer of timers) timer.callback();
assert.deepEqual(states.at(-1), { state: 'playing', reason: null });
});
test('an API that does not load leaves the stream unavailable', async () => {
const { states, settle } = fixture({ apiFails: true });
await settle();
assert.deepEqual(states.at(-1), { state: 'unavailable', reason: 'api' });
});
test('destroy empties the host, destroys the player and silences later events', async () => {
const { api, host, pending, player, states, settle } = fixture();
await settle();
const built = api.players[0];
built.fire('onReady');
player.destroy();
player.destroy();
assert.equal(built.destroyed, 1);
assert.equal(host.children.length, 0);
assert.equal(pending().length, 0);
const before = states.length;
built.fire('onStateChange', 1);
built.fire('onError', 150);
assert.equal(states.length, before, 'nothing is reported after destroy');
});
test('destroy before the API loads builds no player', async () => {
const { api, player, states, settle } = fixture();
player.destroy();
await settle();
assert.equal(api.players.length, 0);
assert.deepEqual(states, [{ state: 'loading', reason: null }]);
});