diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index c907c87f2..2e59cc36a 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1939,6 +1939,7 @@ "src/layers/satellites/orbits.js", "src/layers/satellites/records.js", "src/layers/satellites/policy.js", + "src/render/color.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", "src/layers/satellites/state.js", diff --git a/src/layers/satellites/catalog.js b/src/layers/satellites/catalog.js index f4a347af2..70cf03812 100644 --- a/src/layers/satellites/catalog.js +++ b/src/layers/satellites/catalog.js @@ -1,5 +1,5 @@ -import * as Cesium from 'cesium'; import { twoline2satrec } from 'satellite.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js'; import { DENSE_REFRESH_FRAMES, @@ -39,14 +39,12 @@ export function createCatalog({ state: layerState, services, parts, source }) { const noradId = layerState._denseIds[layerState._denseCursor++]; if (noradId === layerState._trackedNorad) continue; // per-frame tracked path owns it const sat = layerState._catalog.get(noradId); - const point = layerState._points.get(noradId); - if (!sat || !point) continue; + if (!sat || !layerState._points.has(noradId)) continue; const pos = parts.orbits.propagatePosition(sat.satrec, now); if (pos) { - point.position = Cesium.Cartesian3.fromDegrees( - pos.longitude, - pos.latitude, - pos.altitude, + parts.rendering._movePoint( + noradId, + fromDegrees(pos.longitude, pos.latitude, pos.altitude), ); } } @@ -59,7 +57,7 @@ export function createCatalog({ state: layerState, services, parts, source }) { */ async function _loadDenseCatalog({ signal = null } = {}) { - if (!layerState._viewer || !layerState._pointCollection) + if (!layerState._viewer || !parts.rendering._hasPointCollection()) return { status: 'source-unavailable', reason: 'layer-unavailable' }; layerState._denseLoadController?.abort(); const resourceController = new AbortController(); @@ -105,7 +103,7 @@ export function createCatalog({ state: layerState, services, parts, source }) { if ( token !== layerState._denseLoadToken || layerState._params.catalog !== 'dense' || - !layerState._pointCollection + !parts.rendering._hasPointCollection() ) { return { status: 'superseded', reason: 'dense-load-superseded' }; } @@ -125,20 +123,11 @@ export function createCatalog({ state: layerState, services, parts, source }) { group: 'dense', launchYear: tleLineLaunchYear(entry.line1), }); - const point = layerState._pointCollection.add({ - position: Cesium.Cartesian3.fromDegrees( - pos.longitude, - pos.latitude, - pos.altitude, - ), - pixelSize: style.pixelSize, - color: style.color, - outlineColor: style.outlineColor, - outlineWidth: style.outlineWidth, - scaleByDistance: new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6), - id: noradId, - }); - layerState._points.set(noradId, point); + parts.rendering._addPoint( + noradId, + fromDegrees(pos.longitude, pos.latitude, pos.altitude), + style, + ); layerState._denseIds.push(noradId); layerState._denseStale ||= Boolean(res.stale); added++; @@ -221,10 +210,7 @@ export function createCatalog({ state: layerState, services, parts, source }) { parts.tracking._clearTracking(); } for (const noradId of layerState._denseIds) { - const point = layerState._points.get(noradId); - if (point && layerState._pointCollection) - layerState._pointCollection.remove(point); - layerState._points.delete(noradId); + parts.rendering._removePoint(noradId); layerState._catalog.delete(noradId); } layerState._denseIds = []; diff --git a/src/layers/satellites/controls.js b/src/layers/satellites/controls.js index f3327b332..230523b83 100644 --- a/src/layers/satellites/controls.js +++ b/src/layers/satellites/controls.js @@ -3,7 +3,7 @@ import { satelliteClassLabel, satelliteClassLegend, } from '../../data/satelliteClass.js'; -import * as Cesium from 'cesium'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; import { t } from '../../i18n/index.js'; import { ISS_NORAD, POINT_STYLES } from './policy.js'; @@ -14,7 +14,7 @@ export function createControls({ state: layerState, services, parts, source }) { * Resolve the canonical point style for a satellite. * @param {number} noradId NORAD catalog number. * @param {string|undefined} group Catalog group tag (see CATALOG_GROUPS / 'dense'). - * @returns {{ pixelSize: number, color: Cesium.Color, outlineColor: Cesium.Color, outlineWidth: number }} + * @returns {{ pixelSize: number, color: number[], outlineColor: number[], outlineWidth: number }} */ function _pointStyleFor(noradId, group) { @@ -102,8 +102,7 @@ export function createControls({ state: layerState, services, parts, source }) { refreshInterval: 5 * 60 * 1000, getDetectableObjects(options = {}) { - if (!layerState._pointCollection || !layerState._pointCollection.show) - return []; + if (!parts.rendering._pointsShown()) return []; // Dense extras are points-only: excluded from the detection overlay. const eligibleCount = Math.max( 1, @@ -118,7 +117,7 @@ export function createControls({ state: layerState, services, parts, source }) { const result = []; let idx = 0; - for (const [noradId, point] of layerState._points) { + for (const noradId of layerState._points.keys()) { if ( layerState._denseIds.length > 0 && layerState._catalog.get(noradId)?.group === 'dense' @@ -127,7 +126,8 @@ export function createControls({ state: layerState, services, parts, source }) { const shouldTake = (idx - start) % stride === 0; idx++; if (!shouldTake) continue; - if (!point.position) continue; + const position = parts.rendering._pointPosition(noradId); + if (!position) continue; const isTracked = noradId === layerState._trackedNorad; // A docked companion sits at the tracked subject's own position, so its // mark and label would stack underneath the tracked card. It is listed on @@ -150,7 +150,7 @@ export function createControls({ state: layerState, services, parts, source }) { }; layerState._detectionObjects.set(noradId, object); } - object.position = point.position; + object.position = position; object.skipLabel = isTracked; result.push(object); if (result.length >= maxCount) break; @@ -162,7 +162,7 @@ export function createControls({ state: layerState, services, parts, source }) { * Find a satellite by exact NORAD id (numeric string) or case-insensitive * name substring. Position is freshly propagated via SGP4. * @param {string|number} query NORAD id or partial name. - * @returns {{ noradId: number, name: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number }|null} + * @returns {{ noradId: number, name: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number }|null} */ findByQuery(query) { if ( @@ -196,11 +196,7 @@ export function createControls({ state: layerState, services, parts, source }) { return { noradId, name: sat.name.trim(), - position: Cesium.Cartesian3.fromDegrees( - pos.longitude, - pos.latitude, - pos.altitude, - ), + position: fromDegrees(pos.longitude, pos.latitude, pos.altitude), latitude: pos.latitude, longitude: pos.longitude, altitudeM: pos.altitude, @@ -211,7 +207,7 @@ export function createControls({ state: layerState, services, parts, source }) { * Get positions of currently rendered satellites from per-point state * (no SGP4 re-propagation). * @param {number} [maxCount=300] Maximum entries to return. - * @returns {Array<{ id: number, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number }>} + * @returns {Array<{ id: number, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number }>} */ getAllPositions(maxCount = 300) { const result = []; @@ -219,24 +215,25 @@ export function createControls({ state: layerState, services, parts, source }) { const cap = Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 300; - for (const [noradId, point] of layerState._points) { + for (const noradId of layerState._points.keys()) { if (result.length >= cap) break; - if (!point.position) continue; + const position = parts.rendering._pointPosition(noradId); + if (!position) continue; // Dense extras are points-only — keep voice/framing lists to the core catalog. if ( layerState._denseIds.length > 0 && layerState._catalog.get(noradId)?.group === 'dense' ) continue; - const carto = Cesium.Cartographic.fromCartesian(point.position); + const carto = toLonLatH(position); if (!carto) continue; const sat = layerState._catalog.get(noradId); result.push({ id: noradId, label: sat ? sat.name.trim() : String(noradId), - position: point.position, - latitude: Cesium.Math.toDegrees(carto.latitude), - longitude: Cesium.Math.toDegrees(carto.longitude), + position, + latitude: carto.lat, + longitude: carto.lon, altitudeM: carto.height, }); } @@ -403,19 +400,21 @@ export function createControls({ state: layerState, services, parts, source }) { } if (params.showPoints !== undefined) { layerState._params.showPoints = params.showPoints !== false; - if (layerState._pointCollection) - layerState._pointCollection.show = satelliteVisualsVisible( + parts.rendering._setPointsShown( + satelliteVisualsVisible( layerState._enabled, layerState._params.showPoints, - ); + ), + ); } if (params.showOrbits !== undefined) { layerState._params.showOrbits = params.showOrbits !== false; - for (const path of layerState._orbitPaths.values()) - path.primitive.show = satelliteVisualsVisible( + parts.rendering._setOrbitPathsShown( + satelliteVisualsVisible( layerState._enabled, layerState._params.showOrbits, - ); + ), + ); parts.labels._syncIssOverlay(); } if (catalogChanged && catalog === 'dense') { diff --git a/src/layers/satellites/index.js b/src/layers/satellites/index.js index 16e1de512..7417dfa13 100644 --- a/src/layers/satellites/index.js +++ b/src/layers/satellites/index.js @@ -38,7 +38,7 @@ export function createSatellitesLayer({ services, source }) { satelliteVisualsVisible: parts.controls.satelliteVisualsVisible, satelliteCatalogModeChanged: parts.controls.satelliteCatalogModeChanged, createIssOverlayEntry: parts.labels.createIssOverlayEntry, - orbitFrameModelMatrix: parts.orbits.orbitFrameModelMatrix, + orbitFrameModelMatrix: parts.rendering.orbitFrameModelMatrix, _setTrackedSatelliteRefreshStateForTest: parts.testing._setTrackedSatelliteRefreshStateForTest, _setSatelliteTrackingRefreshOutcomeForTest: diff --git a/src/layers/satellites/ingestion.js b/src/layers/satellites/ingestion.js index d2cc16e15..e4577d107 100644 --- a/src/layers/satellites/ingestion.js +++ b/src/layers/satellites/ingestion.js @@ -1,6 +1,6 @@ import { twoline2satrec } from 'satellite.js'; -import * as Cesium from 'cesium'; import { msg } from '../../i18n/index.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js'; import { CATALOG_GROUPS, ISS_NORAD, POINT_STYLES } from './policy.js'; @@ -84,11 +84,8 @@ export function createIngestion({ : null; // Clear existing - layerState._pointCollection.removeAll(); - layerState._points.clear(); - for (const path of layerState._orbitPaths.values()) - viewer.scene.primitives.remove(path.primitive); - layerState._orbitPaths.clear(); + parts.rendering._clearPoints(); + parts.rendering._clearOrbitPaths(viewer); layerState._catalog.clear(); // The detection overlay caches one record per satellite and stamps its // id/class at creation only. A rebuild can re-tag a satellite (a failed @@ -139,32 +136,21 @@ export function createIngestion({ const pos = parts.orbits.propagatePosition(satrec, now); if (!pos) continue; - const cartesian = Cesium.Cartesian3.fromDegrees( - pos.longitude, - pos.latitude, - pos.altitude, + // Add its dot (styling from the shared table, WS-D3) + parts.rendering._addPoint( + noradId, + fromDegrees(pos.longitude, pos.latitude, pos.altitude), + parts.controls._pointStyleFor(noradId, entry.group), ); - - // Add point primitive (styling from the shared table, WS-D3) - const style = parts.controls._pointStyleFor(noradId, entry.group); - const point = layerState._pointCollection.add({ - position: cartesian, - pixelSize: style.pixelSize, - color: style.color, - outlineColor: style.outlineColor, - outlineWidth: style.outlineWidth, - scaleByDistance: new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6), - id: noradId, - }); - - layerState._points.set(noradId, point); } // Show ISS orbital path by default if (layerState._catalog.has(ISS_NORAD)) { parts.rendering._showOrbitPath(ISS_NORAD, POINT_STYLES.iss.color); - const issPath = layerState._orbitPaths.get(ISS_NORAD); - if (issPath) issPath.primitive.show = layerState._params.showOrbits; + parts.rendering._setOrbitPathShown( + ISS_NORAD, + layerState._params.showOrbits, + ); parts.labels._syncIssOverlay(); } diff --git a/src/layers/satellites/ingestion.test.mjs b/src/layers/satellites/ingestion.test.mjs index beea1a518..c4c4529ea 100644 --- a/src/layers/satellites/ingestion.test.mjs +++ b/src/layers/satellites/ingestion.test.mjs @@ -18,14 +18,15 @@ function tleSet(name, field) { ].join('\n'); } +// Orbit tracks hand their path to the renderer; positions pass through here. +const orbitParts = { + rendering: { _rendererPositions: (positions) => positions }, +}; + function ingestionFor(catalogText) { const state = { _trackingRefreshEpoch: 0, _activeUpdateControllers: new Set(), - _pointCollection: { - removeAll() {}, - add: (point) => point, - }, _points: new Map(), _orbitPaths: new Map(), _catalog: new Map(), @@ -41,7 +42,19 @@ function ingestionFor(catalogText) { }, labels: { _syncIssOverlay() {} }, controls: { _pointStyleFor: () => ({}) }, - rendering: { _showOrbitPath() {} }, + rendering: { + _clearPoints() { + state._points.clear(); + }, + _clearOrbitPaths() { + state._orbitPaths.clear(); + }, + _addPoint(noradId, position) { + state._points.set(noradId, { position }); + }, + _showOrbitPath() {}, + _setOrbitPathShown() {}, + }, tracking: { async _reconcileTrackedSubjectContext() {}, _applyPendingTrackingRestore() {}, @@ -54,7 +67,7 @@ function ingestionFor(catalogText) { }, }; const { methods } = createIngestion({ state, services: {}, parts, source }); - return { state, update: () => methods.update({ scene: {} }) }; + return { state, update: () => methods.update({}) }; } test('every Alpha-5 satellite keeps its own catalog entry through dedupe', async (t) => { @@ -92,7 +105,7 @@ test('a mission payload does not match a loaded satellite from another launch ye ].join('\n'), ); await update(); - const { getSatelliteOrbitTrack } = createOrbits({ state }); + const { getSatelliteOrbitTrack } = createOrbits({ state, parts: orbitParts }); const track = (launchTime) => getSatelliteOrbitTrack('Sirius SXM-11', { launchTime }); assert.equal(track('2026-06-29T02:25:00Z')?.noradId, 69728); @@ -110,7 +123,7 @@ test('a satellite with a blank designator keeps matching by name', async (t) => ].join('\n'), ); await update(); - const { getSatelliteOrbitTrack } = createOrbits({ state }); + const { getSatelliteOrbitTrack } = createOrbits({ state, parts: orbitParts }); assert.equal(tleLineLaunchYear('1 69728U 26208.65166678'), null); assert.equal( getSatelliteOrbitTrack('Sirius SXM-11', { diff --git a/src/layers/satellites/interaction.js b/src/layers/satellites/interaction.js index 5c84eb372..29fbc0093 100644 --- a/src/layers/satellites/interaction.js +++ b/src/layers/satellites/interaction.js @@ -49,17 +49,14 @@ export function createInteraction({ if (picked) { // Clicking tracked entity itself — ignore - if (picked.id === layerState._trackedEntity) return; + if (parts.rendering._pickIsTrackedEntity(picked)) return; // Check if it's a satellite point (id is NORAD catalog number) - const prim = picked.primitive; - if (prim && prim.id != null) { - const noradId = Number(prim.id); - if (!isNaN(noradId) && layerState._catalog.has(noradId)) { - parts.tracking._cancelPendingTrackingRestore(); - parts.tracking._trackSatellite(noradId, { origin: 'user' }); - return; - } + const noradId = parts.rendering._pickedPointId(picked); + if (noradId !== null && layerState._catalog.has(noradId)) { + parts.tracking._cancelPendingTrackingRestore(); + parts.tracking._trackSatellite(noradId, { origin: 'user' }); + return; } } diff --git a/src/layers/satellites/labels.js b/src/layers/satellites/labels.js index c62bbb308..512634892 100644 --- a/src/layers/satellites/labels.js +++ b/src/layers/satellites/labels.js @@ -38,7 +38,7 @@ export function createLabels({ state: layerState, services, parts, source }) { /** Cached ISS point only; never performs a fresh SGP4 propagation. */ function _issDisplayCached() { - return layerState._points.get(ISS_NORAD)?.position || null; + return parts.rendering._pointPosition(ISS_NORAD); } /** @@ -63,11 +63,13 @@ export function createLabels({ state: layerState, services, parts, source }) { let changed = false; let found = 0; const next = new Set(); - for (const [noradId, point] of layerState._points) { - if (noradId === layerState._trackedNorad || !point?.position) continue; - const dx = point.position.x - trackedPosition.x; - const dy = point.position.y - trackedPosition.y; - const dz = point.position.z - trackedPosition.z; + for (const noradId of layerState._points.keys()) { + if (noradId === layerState._trackedNorad) continue; + const position = parts.rendering._pointPosition(noradId); + if (!position) continue; + const dx = position.x - trackedPosition.x; + const dy = position.y - trackedPosition.y; + const dz = position.z - trackedPosition.z; if (dx * dx + dy * dy + dz * dz > radiusSq) continue; next.add(noradId); found++; diff --git a/src/layers/satellites/lifecycle.js b/src/layers/satellites/lifecycle.js index 9bba63b12..2041067f1 100644 --- a/src/layers/satellites/lifecycle.js +++ b/src/layers/satellites/lifecycle.js @@ -1,4 +1,4 @@ -import * as Cesium from 'cesium'; +import { frameOf } from '../../render/rendererOf.js'; import { ISS_OVERLAY_SOURCE_ID } from './policy.js'; export function createLifecycle({ @@ -11,10 +11,17 @@ export function createLifecycle({ const { holdContinuousRender, releaseContinuousRender } = services.render; const { registerPickOwner, unregisterPickOwner } = services.picking; + /** Run the shared per-frame tick before each frame draws. */ + function onEachFrame(frame) { + return frame.on('preRender', () => parts.rendering._preRenderTick()); + } + const methods = { // Catalog data refresh; propagation remains preRender-owned. async init(viewer) { + // Asked first: a viewer without one fails before anything is built. + const frame = frameOf(viewer); parts.catalog._abortActiveUpdates(); clearFocusTarget('satellites'); layerState._viewer = viewer; @@ -47,17 +54,14 @@ export function createLifecycle({ layerState._denseError = null; layerState._catalogRevision++; - // Point primitives for satellite dots - layerState._pointCollection = new Cesium.PointPrimitiveCollection(); - viewer.scene.primitives.add(layerState._pointCollection); + // The collection the satellite dots draw in + parts.rendering._attach(viewer); parts.interaction._installClickHandler(viewer); // Pre-render listener for real-time position updates // (fleet propagation + tracked per-frame dot + orbit ring GMST rotation) - layerState._preRenderListener = viewer.scene.preRender.addEventListener( - parts.rendering._preRenderTick, - ); + layerState._preRenderListener = onEachFrame(frame); console.log('[Data:Satellites] Initialized'); }, @@ -65,18 +69,19 @@ export function createLifecycle({ enable(viewer) { layerState._enabled = true; holdContinuousRender('satellites'); // per-frame animator (perf wave 2) - if (layerState._pointCollection) - layerState._pointCollection.show = - parts.controls.satelliteVisualsVisible( - layerState._enabled, - layerState._params.showPoints, - ); - // Orbit ring primitives + persistent ISS host label — show them - for (const path of layerState._orbitPaths.values()) - path.primitive.show = parts.controls.satelliteVisualsVisible( + parts.rendering._setPointsShown( + parts.controls.satelliteVisualsVisible( + layerState._enabled, + layerState._params.showPoints, + ), + ); + // Orbit rings + persistent ISS host label — show them + parts.rendering._setOrbitPathsShown( + parts.controls.satelliteVisualsVisible( layerState._enabled, layerState._params.showOrbits, - ); + ), + ); parts.labels._syncIssOverlay(); // Re-attach input handlers and preRender propagation parts.interaction._installClickHandler(viewer); @@ -87,9 +92,7 @@ export function createLifecycle({ return Number.isFinite(norad) && layerState._points.has(norad); }); if (!layerState._preRenderListener && viewer) { - layerState._preRenderListener = viewer.scene.preRender.addEventListener( - parts.rendering._preRenderTick, - ); + layerState._preRenderListener = onEachFrame(frameOf(viewer)); } parts.tracking._applyPendingTrackingRestore(); }, @@ -99,9 +102,8 @@ export function createLifecycle({ parts.tracking._cancelPendingTrackingRestore(); layerState._enabled = false; releaseContinuousRender('satellites'); - if (layerState._pointCollection) layerState._pointCollection.show = false; - for (const path of layerState._orbitPaths.values()) - path.primitive.show = false; + parts.rendering._setPointsShown(false); + parts.rendering._setOrbitPathsShown(false); parts.tracking._clearTracking(); parts.labels._syncIssOverlay(); // Remove click handler + keydown listener + preRender propagation while disabled @@ -139,14 +141,8 @@ export function createLifecycle({ } layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID); layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false); - if (layerState._pointCollection) { - viewer.scene.primitives.remove(layerState._pointCollection); - layerState._pointCollection = null; - } - // Orbit ring primitives are removed (and destroyed) here - for (const path of layerState._orbitPaths.values()) { - viewer.scene.primitives.remove(path.primitive); - } + // The dots' collection and the orbit rings go (and are destroyed) + parts.rendering._detach(viewer); layerState._points.clear(); layerState._detectionObjects.clear(); layerState._orbitPaths.clear(); diff --git a/src/layers/satellites/offCesium.test.mjs b/src/layers/satellites/offCesium.test.mjs new file mode 100644 index 000000000..a7c3269a7 --- /dev/null +++ b/src/layers/satellites/offCesium.test.mjs @@ -0,0 +1,172 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { satelliteClassColor } from '../../data/satelliteClass.js'; +import satellitesLayer, { + _clearSatelliteLabelLifecycleForTest, + _setSatelliteLabelLifecycleStateForTest, +} from '../../data/satellites.js'; +import { + POINT_STYLES, + TRACK_VIEW_FROM_LEO, + TRACKED_ORBIT_COLOR, +} from './policy.js'; +import { createRendering } from './rendering.js'; + +const rgba = (color) => [color.red, color.green, color.blue, color.alpha]; + +test('point styles keep the colours the dots were drawn in', () => { + const outline = rgba(Cesium.Color.WHITE.withAlpha(0.3)); + const expected = { + iss: Cesium.Color.fromCssColorString('#ff4444'), + dense: Cesium.Color.fromCssColorString( + satelliteClassColor('dense'), + ).withAlpha(0.9), + }; + for (const [group, style] of Object.entries(POINT_STYLES)) { + const color = + expected[group] ?? + Cesium.Color.fromCssColorString(satelliteClassColor(group)); + assert.deepEqual([...style.color], rgba(color), `${group} colour`); + assert.deepEqual([...style.outlineColor], outline, `${group} outline`); + } + assert.deepEqual([...TRACKED_ORBIT_COLOR], rgba(Cesium.Color.YELLOW)); + assert.deepEqual( + { ...TRACK_VIEW_FROM_LEO }, + { + x: -450000, + y: -450000, + z: 350000, + }, + ); +}); + +test('positions read back from the drawn dots match the Cesium geodetic conversion', () => { + const position = Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000); + const point = { position, show: true }; + _setSatelliteLabelLifecycleStateForTest({ + viewer: { scene: { frameState: { frameNumber: 1 } } }, + satrec: null, + point, + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + }); + try { + const [row] = satellitesLayer.getAllPositions(); + const carto = Cesium.Cartographic.fromCartesian(position); + assert.equal(row.id, 25544); + assert.equal(row.position, position, 'the drawn position itself'); + assert.ok( + Math.abs(row.latitude - Cesium.Math.toDegrees(carto.latitude)) < 1e-9, + ); + assert.ok( + Math.abs(row.longitude - Cesium.Math.toDegrees(carto.longitude)) < 1e-9, + ); + assert.ok(Math.abs(row.altitudeM - carto.height) < 1e-6); + } finally { + _clearSatelliteLabelLifecycleForTest(); + } +}); + +test('only the rendering part drives Cesium', () => { + const offList = [ + 'catalog', + 'controls', + 'index', + 'ingestion', + 'interaction', + 'labels', + 'lifecycle', + 'orbits', + 'policy', + 'records', + 'source', + 'state', + 'testing', + 'tracking', + ]; + const forbidden = [ + /from 'cesium'/, + /render\/cesium\//, + /\bCesium\./, + /viewer\??\.entities\b/, + /\.scene\b/, + /\bscene\./, + /\.primitive\b/, + // The dots and rings are the rendering part's: ids only elsewhere. + /_pointCollection\./, + /_points\.(get|values|entries|forEach)\b/, + /of (layerState|state)\._points\)/, + /_orbitPaths\.(get|values|entries|forEach)\b/, + ]; + for (const name of offList) { + const source = readFileSync( + new URL(`./${name}.js`, import.meta.url), + 'utf8', + ); + for (const pattern of forbidden) + assert.doesNotMatch(source, pattern, `${name}.js: ${pattern}`); + } +}); + +test('the rendering part draws the dots and rings in Cesium colours', () => { + const added = []; + const state = { + _points: new Map(), + _orbitPaths: new Map(), + _catalog: new Map([[25544, { satrec: {} }]]), + _pointCollection: { add: (options) => ({ ...options }) }, + _viewer: { scene: { primitives: { add: (p) => added.push(p) } } }, + }; + const path = [ + { x: 7e6, y: 0, z: 0 }, + { x: 0, y: 7e6, z: 0 }, + { x: -7e6, y: 0, z: 0 }, + ]; + const rendering = createRendering({ + state, + services: { focus: {} }, + parts: { orbits: { computeOrbitPath: () => path } }, + }); + rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss); + const point = state._points.get(25544); + assert.ok(point.position instanceof Cesium.Cartesian3); + assert.deepEqual( + [point.position.x, point.position.y, point.position.z], + [1, 2, 3], + ); + assert.ok(point.color instanceof Cesium.Color); + assert.deepEqual( + rgba(point.color), + rgba(Cesium.Color.fromCssColorString('#ff4444')), + ); + assert.deepEqual( + rgba(point.outlineColor), + rgba(Cesium.Color.WHITE.withAlpha(0.3)), + ); + assert.equal(point.pixelSize, 12); + assert.equal(point.outlineWidth, 2); + assert.equal(point.id, 25544); + assert.ok( + Cesium.NearFarScalar.equals( + point.scaleByDistance, + new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6), + ), + ); + + rendering._showOrbitPath(25544, TRACKED_ORBIT_COLOR); + assert.equal(added.length, 1); + const instance = added[0].geometryInstances; + assert.deepEqual( + [...instance.attributes.color.value], + [255, 255, 0, Cesium.Color.floatToByte(0.6)], + ); + assert.ok( + instance.geometry._positions.every((p) => p instanceof Cesium.Cartesian3), + ); + assert.ok( + rendering + ._rendererPositions(path) + .every((p, i) => p instanceof Cesium.Cartesian3 && p.x === path[i].x), + ); +}); diff --git a/src/layers/satellites/orbits.js b/src/layers/satellites/orbits.js index a2bfbd939..a00ad2a63 100644 --- a/src/layers/satellites/orbits.js +++ b/src/layers/satellites/orbits.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { gstime, propagate, @@ -13,35 +12,10 @@ import { parseTleText, tleLineLaunchYear, } from '../../sources/tle.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; import { ORBIT_PATH_STEPS, ISS_NORAD } from './policy.js'; export function createOrbits({ state: layerState, services, parts, source }) { - /** - * Build the rigid ECEF transform that keeps an orbit path baked at one GMST - * aligned with live SGP4 positions propagated at another epoch. - * @param {number} gmstAtBake GMST used when the path positions were baked. - * @param {Date} nowDate Epoch whose rotating-Earth frame should be displayed. - * @param {Cesium.Matrix4} [result] Optional matrix to update in place. - * @returns {Cesium.Matrix4} Z-rotation from bake-time ECEF to current ECEF. - */ - - function orbitFrameModelMatrix( - gmstAtBake, - nowDate, - result = new Cesium.Matrix4(), - ) { - const deltaGmst = gstime(nowDate) - gmstAtBake; - const rotation = Cesium.Matrix3.fromRotationZ( - -deltaGmst, - layerState._scratchRingRotation, - ); - return Cesium.Matrix4.fromRotationTranslation( - rotation, - Cesium.Cartesian3.ZERO, - result, - ); - } - /** * Parse TLE text into array of { name, line1, line2 } objects. */ @@ -85,7 +59,7 @@ export function createOrbits({ state: layerState, services, parts, source }) { } /** - * Compute full orbital path as array of Cartesian3 positions. + * Compute full orbital path as ECEF `{x, y, z}` positions, metres. * Steps around one full orbit based on the satellite's mean motion. */ @@ -107,7 +81,7 @@ export function createOrbits({ state: layerState, services, parts, source }) { if (!posVel.position || typeof posVel.position === 'boolean') continue; const geo = eciToGeodetic(posVel.position, fixedGmst); positions.push( - Cesium.Cartesian3.fromDegrees( + fromDegrees( degreesLong(geo.longitude), degreesLat(geo.latitude), geo.height * 1000, @@ -279,7 +253,10 @@ export function createOrbits({ state: layerState, services, parts, source }) { name: String(name || '').trim(), current, periodSec: orbitalPeriodSeconds(satrec), - orbitPath: computeOrbitPath(satrec, referenceDate), + // Handed to the renderer's own polylines by the launches layer. + orbitPath: parts.rendering._rendererPositions( + computeOrbitPath(satrec, referenceDate), + ), gmstAtBake: gstime(referenceDate), positionAt: (date) => propagatePosition(satrec, date), }; @@ -292,7 +269,7 @@ export function createOrbits({ state: layerState, services, parts, source }) { * @param {string} tleText Three-line-element catalog text. * @param {string} query Mission or payload name. * @param {{launchTime?: string|null}} [options] Optional launch epoch for namesake rejection. - * @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Cesium.Cartesian3[],positionAt:function(Date):object|null}|null} + * @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Array<{x:number,y:number,z:number}>,positionAt:function(Date):object|null}|null} */ function findSatelliteOrbitTrackInTle(tleText, query, options = {}) { @@ -326,7 +303,7 @@ export function createOrbits({ state: layerState, services, parts, source }) { * Return the current propagated position and one-orbit path for a catalog satellite. * @param {string|number} query NORAD id or mission/payload name. * @param {{launchTime?: string|null}} [options] Optional launch epoch used to reject namesakes from another launch year. - * @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Cesium.Cartesian3[],positionAt:function(Date):object|null}|null} + * @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Array<{x:number,y:number,z:number}>,positionAt:function(Date):object|null}|null} */ function getSatelliteOrbitTrack(query, options = {}) { @@ -361,7 +338,6 @@ export function createOrbits({ state: layerState, services, parts, source }) { return orbitTrackFromRecord(sat.name, sat.satrec); } return { - orbitFrameModelMatrix, parseTLE, propagatePosition, orbitalPeriodSeconds, diff --git a/src/layers/satellites/policy.js b/src/layers/satellites/policy.js index e7ea5456d..0542c7d4a 100644 --- a/src/layers/satellites/policy.js +++ b/src/layers/satellites/policy.js @@ -1,5 +1,5 @@ -import * as Cesium from 'cesium'; import { satelliteClassColor } from '../../data/satelliteClass.js'; +import { hexColor } from '../../render/color.js'; /** * Satellite Orbits — Real-time positions via CelesTrak TLE + SGP4 propagation. @@ -7,7 +7,7 @@ import { satelliteClassColor } from '../../data/satelliteClass.js'; * Loads six CelesTrak groups (~840 sats): stations, visual, GPS, GLONASS, * Galileo, and the geosynchronous belt. Optional dense mode (setParams * catalog:'dense') adds the Starlink shell as points-only extras. - * Renders positions via PointPrimitiveCollection, orbital paths as polylines. + * Renders positions as points, orbital paths as polylines. * Click any satellite to track it with camera follow + orbital path. * * ISS gets special treatment: larger point, persistent host label, path shown by default. @@ -71,11 +71,14 @@ export const DENSE_CREATE_CHUNK = 1500; * High orbits (MEO nav / GEO belt) scale this up so the ring stays in frame. */ -export const TRACK_VIEW_FROM_LEO = new Cesium.Cartesian3( - -450000, - -450000, - 350000, -); +export const TRACK_VIEW_FROM_LEO = Object.freeze({ + x: -450000, + y: -450000, + z: 350000, +}); + +/** The tracked satellite's orbit ring. */ +export const TRACKED_ORBIT_COLOR = Object.freeze([1, 1, 0, 1]); export const HIGH_ORBIT_ALTITUDE_M = 2000000; @@ -90,14 +93,16 @@ export const TRACK_VIEW_FROM_HIGH_SCALE = 4; * Colors come from `satelliteClass.js` so the dot, the class label on the * card, and the legend swatch on the layer row can never disagree. Only * pixelSize/outline live here — those encode per-group prominence, not class. - * Converted once at module load; per-point color is a plain primitive - * attribute, so classification costs nothing per frame. + * Colours are the render contract's `[r, g, b, a]` (0..1); the rendering + * part turns each style into the renderer's own colours once. */ -const POINT_OUTLINE = Cesium.Color.WHITE.withAlpha(0.3); +const POINT_OUTLINE = Object.freeze([1, 1, 1, 0.3]); -const _classColor = (group) => - Cesium.Color.fromCssColorString(satelliteClassColor(group)); +const rgba = (hex, alpha = 1) => Object.freeze(hexColor(hex, alpha)); + +const _classColor = (group, alpha = 1) => + rgba(satelliteClassColor(group), alpha); export const POINT_STYLES = { // The ISS keeps its own long-standing red hero styling rather than the @@ -106,7 +111,7 @@ export const POINT_STYLES = { // Its card still reads "STATION · ISS", so the class stays legible. iss: { pixelSize: 12, - color: Cesium.Color.fromCssColorString('#ff4444'), + color: rgba('#ff4444'), outlineColor: POINT_OUTLINE, outlineWidth: 2, }, @@ -151,7 +156,7 @@ export const POINT_STYLES = { // Dense-mode extras (Starlink): dim, small, points-only. dense: { pixelSize: 3, - color: _classColor('dense').withAlpha(0.9), + color: _classColor('dense', 0.9), outlineColor: POINT_OUTLINE, outlineWidth: 0, }, diff --git a/src/layers/satellites/records.js b/src/layers/satellites/records.js index d4fb4d076..21901298d 100644 --- a/src/layers/satellites/records.js +++ b/src/layers/satellites/records.js @@ -1,5 +1,5 @@ -import * as Cesium from 'cesium'; import { satelliteClassLabel } from '../../data/satelliteClass.js'; +import { toLonLatH } from '../../geo/ellipsoid.js'; import { ISS_NORAD } from './policy.js'; /** @@ -62,13 +62,13 @@ export function createRecords({ state, parts }) { speedMps: Number.isFinite(pos.speedMps) ? pos.speedMps : null, }; } - const point = state._points.get(noradId); - if (!point?.position) return null; - const carto = Cesium.Cartographic.fromCartesian(point.position); + const position = parts.rendering._pointPosition(noradId); + if (!position) return null; + const carto = toLonLatH(position); if (!carto) return null; return { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), + lat: carto.lat, + lon: carto.lon, altitudeM: carto.height, speedMps: null, }; diff --git a/src/layers/satellites/rendering.js b/src/layers/satellites/rendering.js index 08e4396bc..b51399f0e 100644 --- a/src/layers/satellites/rendering.js +++ b/src/layers/satellites/rendering.js @@ -1,7 +1,40 @@ import * as Cesium from 'cesium'; +// The camera and frame ports over a viewer with no renderer bound, for the +// tracking and lifecycle parts that follow and tick through them. +import '../../render/cesium/camera.js'; +import '../../render/cesium/frame.js'; +import { toCartesian } from '../../render/cesium/common.js'; +import { toColor as cesiumColor } from '../../render/cesium/draw.js'; import { gstime } from 'satellite.js'; import { ISS_NORAD, POSITION_UPDATE_MS, RING_ROTATION_MS } from './policy.js'; +/** + * The satellites layer's Cesium side: the point collection and its point + * primitives, the baked orbit-ring primitives, the tracked entity the follow + * camera and the tracked card read, and the per-frame tick that moves them. + * The other parts hand it render-contract values (ECEF `{x, y, z}`, colours + * as `[r, g, b, a]`) and never touch these objects themselves. + */ + +/** Points shrink with distance as they always have. */ +const POINT_SCALE_BY_DISTANCE = new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6); + +/** Each policy style once in Cesium's colours (styles are module constants). */ +const cesiumStyles = new WeakMap(); +function cesiumStyleOf(style) { + let converted = cesiumStyles.get(style); + if (!converted) { + converted = { + pixelSize: style.pixelSize, + color: cesiumColor(style.color), + outlineColor: cesiumColor(style.outlineColor), + outlineWidth: style.outlineWidth, + }; + cesiumStyles.set(style, converted); + } + return converted; +} + export function createRendering({ state: layerState, services, @@ -15,8 +48,217 @@ export function createRendering({ nearFarScalarValueAtDistance, advanceSpriteFocus, focusAlphaNeedsWrite, + publishFocusTargetFromCachedPosition, } = services.focus; + const scratchFocusScreen = new Cesium.Cartesian2(); + const scratchRingRotation = new Cesium.Matrix3(); + // The tracked satellite's per-frame ECEF sample (WS-D2), shared with the + // tracked entity, the follow camera and the tracked card. Tracking writes + // its x/y/z; it stays one Cesium value for the readers that take it. + layerState._trackedFrameCartesian = new Cesium.Cartesian3(); + + /** + * Build the rigid ECEF transform that keeps an orbit path baked at one GMST + * aligned with live SGP4 positions propagated at another epoch. + * @param {number} gmstAtBake GMST used when the path positions were baked. + * @param {Date} nowDate Epoch whose rotating-Earth frame should be displayed. + * @param {Cesium.Matrix4} [result] Optional matrix to update in place. + * @returns {Cesium.Matrix4} Z-rotation from bake-time ECEF to current ECEF. + */ + + function orbitFrameModelMatrix( + gmstAtBake, + nowDate, + result = new Cesium.Matrix4(), + ) { + const deltaGmst = gstime(nowDate) - gmstAtBake; + const rotation = Cesium.Matrix3.fromRotationZ( + -deltaGmst, + scratchRingRotation, + ); + return Cesium.Matrix4.fromRotationTranslation( + rotation, + Cesium.Cartesian3.ZERO, + result, + ); + } + + /** ECEF `{x, y, z}` positions as the renderer's own. */ + function _rendererPositions(positions) { + return positions.map(toCartesian); + } + + /** The scene's rendered-frame number, the tracked sample's cache key. */ + function _drawnFrameNumber() { + return layerState._viewer?.scene?.frameState?.frameNumber ?? -1; + } + + /** Add the point collection the satellite dots draw in. */ + function _attach(viewer) { + layerState._pointCollection = new Cesium.PointPrimitiveCollection(); + viewer.scene.primitives.add(layerState._pointCollection); + } + + /** Remove the point collection and every orbit ring from `viewer`. */ + function _detach(viewer) { + if (layerState._pointCollection) { + viewer.scene.primitives.remove(layerState._pointCollection); + layerState._pointCollection = null; + } + // Orbit ring primitives are removed (and destroyed) here + for (const path of layerState._orbitPaths.values()) { + viewer.scene.primitives.remove(path.primitive); + } + } + + /** Whether there is a point collection to draw satellites in. */ + function _hasPointCollection() { + return Boolean(layerState._pointCollection); + } + + /** Whether the satellite dots are shown. */ + function _pointsShown() { + return Boolean(layerState._pointCollection?.show); + } + + function _setPointsShown(show) { + if (layerState._pointCollection) layerState._pointCollection.show = show; + } + + function _setOrbitPathsShown(show) { + for (const path of layerState._orbitPaths.values()) + path.primitive.show = show; + } + + function _setOrbitPathShown(noradId, show) { + const path = layerState._orbitPaths.get(noradId); + if (path) path.primitive.show = show; + } + + /** Remove every orbit ring from `viewer`'s scene. */ + function _clearOrbitPaths(viewer) { + for (const path of layerState._orbitPaths.values()) + viewer.scene.primitives.remove(path.primitive); + layerState._orbitPaths.clear(); + } + + /** + * Draw one satellite's dot. + * @param {number} noradId + * @param {{x: number, y: number, z: number}} position ECEF metres. + * @param {object} style A `POINT_STYLES` entry. + */ + function _addPoint(noradId, position, style) { + const look = cesiumStyleOf(style); + const point = layerState._pointCollection.add({ + position: toCartesian(position), + pixelSize: look.pixelSize, + color: look.color, + outlineColor: look.outlineColor, + outlineWidth: look.outlineWidth, + scaleByDistance: POINT_SCALE_BY_DISTANCE, + id: noradId, + }); + layerState._points.set(noradId, point); + } + + /** Move a drawn dot to ECEF `position`; false when it has none. */ + function _movePoint(noradId, position) { + const point = layerState._points.get(noradId); + if (!point) return false; + point.position = position; // primitive setter clones + return true; + } + + function _removePoint(noradId) { + const point = layerState._points.get(noradId); + if (point && layerState._pointCollection) + layerState._pointCollection.remove(point); + layerState._points.delete(noradId); + } + + /** Remove every dot. */ + function _clearPoints() { + layerState._pointCollection.removeAll(); + layerState._points.clear(); + } + + /** Where a dot is drawn (ECEF), or null. */ + function _pointPosition(noradId) { + return layerState._points.get(noradId)?.position || null; + } + + /** Hide a dot while the tracked entity draws it. */ + function _hidePoint(noradId) { + const point = layerState._points.get(noradId); + if (point) point.show = false; + } + + /** Show a dot again in its group's style (WS-D3). */ + function _restorePoint(noradId, style) { + const point = layerState._points.get(noradId); + if (!point) return; + const look = cesiumStyleOf(style); + point.show = true; + point.pixelSize = look.pixelSize; + point.color = look.color; + point.outlineColor = look.outlineColor; + point.outlineWidth = look.outlineWidth; + point.disableDepthTestDistance = 0; + } + + /** + * Add the tracked satellite's entity: it owns a point graphic so the + * follow camera can resolve a bounding sphere (a label-only entity left + * the camera stranded), and the tracked card reads its entity record. + * @param {{position: () => object, viewFrom: {x: number, y: number, + * z: number}}} options `position` is evaluated every time it is read. + * @returns {object} The entity. + */ + function _addTrackedEntity({ position, viewFrom }) { + return layerState._viewer.entities.add({ + position: new Cesium.CallbackProperty(position, false), + viewFrom: toCartesian(viewFrom), + point: { + pixelSize: 14, + color: Cesium.Color.YELLOW, + outlineColor: Cesium.Color.WHITE, + outlineWidth: 2, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + } + + function _removeTrackedEntity(entity) { + layerState._viewer.entities.remove(entity); + } + + /** Whether a scene pick is the tracked satellite's entity. */ + function _pickIsTrackedEntity(picked) { + return picked?.id === layerState._trackedEntity; + } + + /** + * The NORAD id a scene pick's point primitive carries, or null. Any + * primitive with a numeric id answers; the caller checks the catalog. + */ + function _pickedPointId(picked) { + const prim = picked?.primitive; + if (!prim || prim.id == null) return null; + const noradId = Number(prim.id); + return isNaN(noradId) ? null : noradId; + } + + /** Publish the tracked satellite's focus rectangle from its cached position. */ + function _publishTrackedFocus(target) { + publishFocusTargetFromCachedPosition({ + ...target, + scene: layerState._viewer?.scene, + camera: layerState._viewer?.camera, + }); + } + /** * Show orbital path for a satellite. * @@ -43,10 +285,12 @@ export function createRendering({ if (!sat || !layerState._viewer) return; const bakeDate = new Date(); - const basePositions = parts.orbits.computeOrbitPath(sat.satrec, bakeDate); + const basePositions = _rendererPositions( + parts.orbits.computeOrbitPath(sat.satrec, bakeDate), + ); if (basePositions.length < 2) return; - const pathColor = color || Cesium.Color.CYAN; + const pathColor = color ? cesiumColor(color) : Cesium.Color.CYAN; const primitive = new Cesium.Primitive({ geometryInstances: new Cesium.GeometryInstance({ @@ -115,7 +359,7 @@ export function createRendering({ for (const path of layerState._orbitPaths.values()) { if (!path.primitive) continue; - parts.orbits.orbitFrameModelMatrix( + orbitFrameModelMatrix( path.gmstAtBake, nowDate, path.primitive.modelMatrix, @@ -239,14 +483,16 @@ export function createRendering({ Cesium.SceneTransforms.worldToWindowCoordinates( scene, position, - layerState._scratchFocusScreen, + scratchFocusScreen, ), cameraDistanceFor: (position) => Cesium.Cartesian3.distance(camera.positionWC, position), baseColorFor: (noradId) => - parts.controls._pointStyleFor( - noradId, - layerState._catalog.get(noradId)?.group, + cesiumStyleOf( + parts.controls._pointStyleFor( + noradId, + layerState._catalog.get(noradId)?.group, + ), ).color, }); layerState._activeFocusCount = result.activeCount; @@ -309,6 +555,29 @@ export function createRendering({ return { writes, transitioning, activeCount, ran: true }; } return { + orbitFrameModelMatrix, + _rendererPositions, + _drawnFrameNumber, + _attach, + _detach, + _hasPointCollection, + _pointsShown, + _setPointsShown, + _setOrbitPathsShown, + _setOrbitPathShown, + _clearOrbitPaths, + _addPoint, + _movePoint, + _removePoint, + _clearPoints, + _pointPosition, + _hidePoint, + _restorePoint, + _addTrackedEntity, + _removeTrackedEntity, + _publishTrackedFocus, + _pickIsTrackedEntity, + _pickedPointId, _showOrbitPath, _updateOrbitPathRotations, _hideOrbitPath, diff --git a/src/layers/satellites/stale.test.mjs b/src/layers/satellites/stale.test.mjs index 9cca23610..5c957e69b 100644 --- a/src/layers/satellites/stale.test.mjs +++ b/src/layers/satellites/stale.test.mjs @@ -10,6 +10,8 @@ import { createOrbits } from './orbits.js'; import { createLabels } from './labels.js'; import { createTracking } from './tracking.js'; import { createRendering } from './rendering.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fakeSceneFrame } from '../../testSupport/fakeCesiumScene.mjs'; import { createCatalog } from './catalog.js'; import { createLifecycle } from './lifecycle.js'; import { createInteraction } from './interaction.js'; @@ -115,8 +117,10 @@ async function fixture(t) { }, trackedEntityChanged: new Cesium.Event(), }; + const unbind = bindRenderer(viewer, { frame: fakeSceneFrame(viewer) }); await parts.lifecycle.methods.init(viewer); t.after(async () => { + unbind(); if (state._pointCollection) parts.lifecycle.methods.destroy(viewer); viewer.scene.primitives.destroy(); if (previousDocument === undefined) delete globalThis.document; diff --git a/src/layers/satellites/state.js b/src/layers/satellites/state.js index 0838377f9..df297a17c 100644 --- a/src/layers/satellites/state.js +++ b/src/layers/satellites/state.js @@ -1,5 +1,3 @@ -import * as Cesium from 'cesium'; - export function createState({ services }) { const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } = services.overlays; @@ -25,8 +23,8 @@ export function createState({ services }) { state._detectionObjects = new Map(); - // noradId → { primitive, gmstAtBake } - // primitive is a one-instance Cesium.Primitive holding the ring baked in ECEF + // noradId → { primitive, gmstAtBake }, owned by the rendering part: + // primitive is a one-instance primitive holding the ring baked in ECEF // at gmstAtBake; the preRender tick re-aligns it to current GMST by updating // its modelMatrix (rigid Z-rotation — no geometry rebuild, WS-D1). @@ -62,8 +60,6 @@ export function createState({ services }) { state._activeFocusCount = 0; - state._scratchFocusScreen = new Cesium.Cartesian2(); - state._enabled = false; // Click-to-track state @@ -88,7 +84,7 @@ export function createState({ services }) { state._clickSubscription = null; - /** @type {Cesium.Event.RemoveCallback|null} trackedEntityChanged listener disposer (cross-layer untrack) */ + /** @type {(() => void)|null} follow-changed listener disposer (cross-layer untrack) */ state._trackedEntityChangedRemove = null; @@ -140,25 +136,20 @@ export function createState({ services }) { // Per-frame cache for the tracked satellite (WS-D2): dot, host readout, camera, and // getTrackedInfo all read one SGP4 sample per rendered frame, keyed on - // scene.frameState.frameNumber, so they never diverge in epoch. + // the rendered-frame number, so they never diverge in epoch. state._trackedFrameNumber = -1; state._trackedFrameGeo = null; // { longitude, latitude, altitude } or null - state._trackedFrameCartesian = new Cesium.Cartesian3(); + // The matching ECEF sample; the rendering part creates it. + state._trackedFrameCartesian = null; /** Optional deterministic clock used only by the production-frame test seam. */ state._trackedFrameNowForTest = null; - // Scratch variables - - state._scratchCartesian = new Cesium.Cartesian3(); - - state._scratchRingRotation = new Cesium.Matrix3(); - /** Update the explicit model only when the rounded altitude line changes. */ /** Epoch of the last shared-context refresh for the tracked satellite. */ diff --git a/src/layers/satellites/testing.js b/src/layers/satellites/testing.js index e0f394a50..eb7fb09e8 100644 --- a/src/layers/satellites/testing.js +++ b/src/layers/satellites/testing.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { ISS_NORAD, ISS_OVERLAY_SOURCE_ID } from './policy.js'; export function createTesting({ state: layerState, services, parts, source }) { @@ -81,7 +80,7 @@ export function createTesting({ state: layerState, services, parts, source }) { return layerState._trackedFrameCartesian; } - /** Invoke the same callback registered on `scene.preRender` in production. */ + /** Invoke the same per-frame tick the frame port runs in production. */ function _runSatellitePreRenderForTest() { parts.rendering._preRenderTick(); @@ -177,7 +176,11 @@ export function createTesting({ state: layerState, services, parts, source }) { [ ISS_NORAD, { - primitive: { show: true, modelMatrix: new Cesium.Matrix4() }, + // A stand-in ring: shown, at the identity 4x4 (column-major). + primitive: { + show: true, + modelMatrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + }, gmstAtBake: 0, }, ], diff --git a/src/layers/satellites/tracking.js b/src/layers/satellites/tracking.js index b04a59b54..e9beb09e9 100644 --- a/src/layers/satellites/tracking.js +++ b/src/layers/satellites/tracking.js @@ -1,7 +1,8 @@ -import { cameraOf } from '../../render/cesium/camera.js'; +import { cameraOf } from '../../render/rendererOf.js'; import { entityFollowTarget, stopFollowing } from '../../data/followed.js'; -import * as Cesium from 'cesium'; import { satelliteClassLabel } from '../../data/satelliteClass.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { clone, copyInto, scale } from '../../geo/vector.js'; import { t } from '../../i18n/index.js'; import { formatQuantity, unitLabel } from '../../ui/unitLabels.js'; import { @@ -10,12 +11,12 @@ import { HIGH_ORBIT_ALTITUDE_M, TRACK_VIEW_FROM_HIGH_SCALE, TRACK_VIEW_FROM_LEO, + TRACKED_ORBIT_COLOR, } from './policy.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; export function createTracking({ state: layerState, services, parts, source }) { - const { clearFocusTarget, publishFocusTargetFromCachedPosition } = - services.focus; + const { clearFocusTarget } = services.focus; const { clearTrackedSubjectContext, getContextStore, @@ -89,22 +90,15 @@ export function createTracking({ state: layerState, services, parts, source }) { const clearedNorad = layerState._trackedNorad; clearFocusTarget('satellites', layerState._trackedNorad); - const lastPos = layerState._points.get(layerState._trackedNorad); - - // Re-show the primitive (hidden while the tracked entity rendered the dot) - // and restore the original group palette from the shared style table (WS-D3) - if (lastPos) { - const style = parts.controls._pointStyleFor( + // Re-show the dot (hidden while the tracked entity rendered it) and + // restore the original group palette from the shared style table (WS-D3) + parts.rendering._restorePoint( + layerState._trackedNorad, + parts.controls._pointStyleFor( layerState._trackedNorad, layerState._catalog.get(layerState._trackedNorad)?.group, - ); - lastPos.show = true; - lastPos.pixelSize = style.pixelSize; - lastPos.color = style.color; - lastPos.outlineColor = style.outlineColor; - lastPos.outlineWidth = style.outlineWidth; - lastPos.disableDepthTestDistance = 0; - } + ), + ); // Invalidate the per-frame tracked-position cache (WS-D2) layerState._trackedFrameNumber = -1; @@ -118,7 +112,7 @@ export function createTracking({ state: layerState, services, parts, source }) { stopFollowing(layerState._viewer); layerState._followTarget = null; if (layerState._trackedEntity) { - layerState._viewer.entities.remove(layerState._trackedEntity); + parts.rendering._removeTrackedEntity(layerState._trackedEntity); layerState._trackedEntity = null; } layerState._trackedNorad = null; @@ -147,8 +141,7 @@ export function createTracking({ state: layerState, services, parts, source }) { const sat = layerState._catalog.get(layerState._trackedNorad); if (!sat) return null; - const frameNumber = - layerState._viewer?.scene?.frameState?.frameNumber ?? -1; + const frameNumber = parts.rendering._drawnFrameNumber(); if ( frameNumber === -1 || frameNumber !== layerState._trackedFrameNumber || @@ -162,11 +155,8 @@ export function createTracking({ state: layerState, services, parts, source }) { ); if (!pos) return layerState._trackedFrameGeo; // propagation hiccup — keep last good sample layerState._trackedFrameGeo = pos; - Cesium.Cartesian3.fromDegrees( - pos.longitude, - pos.latitude, - pos.altitude, - undefined, + copyInto( + fromDegrees(pos.longitude, pos.latitude, pos.altitude), layerState._trackedFrameCartesian, ); layerState._trackedFrameNumber = frameNumber; @@ -190,11 +180,9 @@ export function createTracking({ state: layerState, services, parts, source }) { const trackedPointDiameterPx = 14 + 4; // point plus its 2 px outline on both sides // Exact SGP4 frame cache only: dot, host readout, camera, and focus rectangle all // share one epoch, avoiding a second propagation phase and its old jitter. - publishFocusTargetFromCachedPosition({ + parts.rendering._publishTrackedFocus({ ownerLayer: 'satellites', id: layerState._trackedNorad, - scene: layerState._viewer?.scene, - camera: layerState._viewer?.camera, displayPosition: layerState._trackedFrameCartesian, widthPx: Math.max(trackedPointDiameterPx, Math.min(260, labelWidthPx)), // Union of the 14 px point and the two-line label shifted 18 px upward. @@ -407,35 +395,32 @@ export function createTracking({ state: layerState, services, parts, source }) { function _trackSatellite(noradId, { origin = 'programmatic' } = {}) { _clearTracking(false, { origin }); - const point = layerState._points.get(noradId); const sat = layerState._catalog.get(noradId); - if (!point || !sat) return; + if (!layerState._points.has(noradId) || !sat) return; layerState._trackedNorad = noradId; layerState._trackedFrameNumber = -1; layerState._trackedFrameGeo = null; parts.labels._syncIssOverlay(); - // Hide the primitive — the tracked ENTITY renders the dot below. The - // entity must own a point graphic so the Viewer's tracking camera can - // resolve a bounding sphere and engage viewFrom (a label-only entity - // left the camera stranded; this mirrors the proven flights pattern). - point.show = false; + // Hide the dot — the tracked ENTITY renders it below. The entity must + // own a point graphic so the tracking camera can resolve a bounding + // sphere and engage viewFrom (a label-only entity left the camera + // stranded; this mirrors the proven flights pattern). + parts.rendering._hidePoint(noradId); // Show orbital path - parts.rendering._showOrbitPath(noradId, Cesium.Color.YELLOW); + parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR); // Tracked entity 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 point primitive's 1s-throttled position if SGP4 fails. + // Falls back to the dot's 1s-throttled position if SGP4 fails. const trackedPosition = () => { const pos = _getTrackedFramePosition(); - return pos ? layerState._trackedFrameCartesian : point.position; + return pos + ? layerState._trackedFrameCartesian + : parts.rendering._pointPosition(noradId); }; - const positionProperty = new Cesium.CallbackProperty( - trackedPosition, - false, - ); const name = sat.name.trim(); @@ -447,22 +432,11 @@ export function createTracking({ state: layerState, services, parts, source }) { initialPos && initialPos.altitude > HIGH_ORBIT_ALTITUDE_M ? TRACK_VIEW_FROM_HIGH_SCALE : 1; - const viewFrom = Cesium.Cartesian3.multiplyByScalar( - TRACK_VIEW_FROM_LEO, - viewScale, - new Cesium.Cartesian3(), - ); + const viewFrom = scale(TRACK_VIEW_FROM_LEO, viewScale); - layerState._trackedEntity = layerState._viewer.entities.add({ - position: positionProperty, + layerState._trackedEntity = parts.rendering._addTrackedEntity({ + position: trackedPosition, viewFrom, - point: { - pixelSize: 14, - color: Cesium.Color.YELLOW, - outlineColor: Cesium.Color.WHITE, - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, }); entityRecord(layerState._trackedEntity).selectionOrigin = origin; entityRecord(layerState._trackedEntity).trackedId = `satellites:${noradId}`; @@ -470,17 +444,18 @@ export function createTracking({ state: layerState, services, parts, source }) { _trackedDisplayCached; _updateTrackedSatelliteLabelModel(initialPos?.altitude ?? null); + const dotPosition = parts.rendering._pointPosition(noradId); _emitAwarenessEvent('gev:awareness-subject-selected', { layerId: 'satellites', id: noradId, label: name, - position: Cesium.Cartesian3.clone(point.position), + position: dotPosition ? clone(dotPosition) : undefined, origin, }); selectTrackedSubjectContext(_contextSubjectMetadata(noradId, initialPos)); layerState._contextRefreshedAtMs = Date.now(); - // Cesium's own frame for a fast mover (AUTODETECT), as the tracked entity + // The renderer's own frame for a fast mover (autodetect), as the tracked entity // had; no close-range rules at orbital distances. layerState._followTarget = entityFollowTarget(layerState._trackedEntity, { position: trackedPosition, diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 0831a9c76..9f28bc44f 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -71,17 +71,7 @@ "src/layers/radio/lifecycle.js", "src/layers/radio/rendering.js", "src/layers/recentImagery/rendering.js", - "src/layers/satellites/catalog.js", - "src/layers/satellites/controls.js", - "src/layers/satellites/ingestion.js", - "src/layers/satellites/lifecycle.js", - "src/layers/satellites/orbits.js", - "src/layers/satellites/policy.js", - "src/layers/satellites/records.js", "src/layers/satellites/rendering.js", - "src/layers/satellites/state.js", - "src/layers/satellites/testing.js", - "src/layers/satellites/tracking.js", "src/layers/traffic/animation.js", "src/layers/traffic/lifecycle.js", "src/layers/traffic/rendering.js",