Compute launch paths, cameras and colours without Cesium

The launches layer's path building, replay camera maths, policy constants,
state, marker colours and mission panel no longer import Cesium. Paths and
camera poses are plain ECEF points computed by the geo helpers with the
default renderer's own formulas in the same order, so trajectories, orbits
and camera framing land where they did. Geodesic interpolation moves from
the stub renderer into geo/geodesic (geodesicLine, solved once per
geodesic), and geo/sphere gains the renderer's sphere union.

Marker colours are renderer colours, with the panel's CSS from the same
palette. The rendering part, still Cesium for its entities, converts the
plain points where the entities take them, culls with the shared horizon
test, loads the unbound camera factory, and hands the panel the live
payload position directly instead of through the entity.

Camera, model, panel, paths, policy, policyHelpers and state leave the
allow-list.
This commit is contained in:
Sameh Khamis committed 2026-11-06 22:57:55 -08:00
1 parent 0782b073e2
commit a2503476de
19 files changed
+561 -548

No files matched your search

+7 -1
View File
@@ -1918,6 +1918,9 @@
"modules": [
"src/cyberSonar.js",
"src/layers/launches/camera.js",
"src/geo/sphere.js",
"src/geo/geodesic.js",
"src/layers/launches/geometry.js",
"src/layers/launches/controls.js",
"src/layers/launches/index.js",
"src/render/cesium/camera.js",
@@ -1934,6 +1937,7 @@
"src/layers/launches/launchPad.js",
"src/layers/launches/lifecycle.js",
"src/layers/launches/model.js",
"src/render/color.js",
"src/geo/index.js",
"src/layers/launches/orbitRendering.js",
"src/layers/launches/overlays.js",
@@ -1951,6 +1955,7 @@
"src/render/cesium/internals.js",
"src/render/cesium/common.js",
"src/layers/launches/rendering.js",
"src/geo/horizon.js",
"src/layers/launches/replay.js",
"src/data/followed.js",
"src/layers/launches/selection.js",
@@ -3138,6 +3143,7 @@
"src/layers/cctv/health.js",
"src/layers/cctv/hover.js",
"src/layers/cctv/index.js",
"src/layers/launches/geometry.js",
"src/layers/cctv/ingestion.js",
"src/layers/cctv/lifecycle.js",
"src/layers/cctv/model.js",
@@ -4082,6 +4088,7 @@
"src/layers/cctv/health.js",
"src/layers/cctv/hover.js",
"src/layers/cctv/index.js",
"src/layers/launches/geometry.js",
"src/layers/cctv/ingestion.js",
"src/layers/cctv/lifecycle.js",
"src/layers/cctv/model.js",
@@ -5878,7 +5885,6 @@
"src/render/stub/camera.js",
"src/geo/geodesic.js",
"src/render/camera/events.js",
"src/render/stub/geodesic.js",
"src/render/stub/viewRectangle.js",
"src/render/stub/orbits.js",
"src/render/input/router.js",
+3 -3
View File
@@ -570,9 +570,9 @@ test('latest roster input owns preview and restores the remaining owner on leave
});
test('assigns distinct stable colors to mission operators', () => {
assert.equal(missionMarkerColor({ provider: 'NASA', name: 'Science Flight' }).toCssColorString(), 'rgb(255,159,67)');
assert.equal(missionMarkerColor({ provider: 'SpaceX', name: 'Starlink Group' }).toCssColorString(), 'rgb(76,201,240)');
assert.equal(missionMarkerColor({ provider: 'Private Launch Co.', name: 'Test Flight' }).toCssColorString(), 'rgb(192,132,252)');
assert.deepEqual(missionMarkerColor({ provider: 'NASA', name: 'Science Flight' }), [255 / 255, 159 / 255, 67 / 255, 1]);
assert.deepEqual(missionMarkerColor({ provider: 'SpaceX', name: 'Starlink Group' }), [76 / 255, 201 / 255, 240 / 255, 1]);
assert.deepEqual(missionMarkerColor({ provider: 'Private Launch Co.', name: 'Test Flight' }), [192 / 255, 132 / 255, 252 / 255, 1]);
});
test('normalizes recent launches and preserves supplied trajectory/orbit data', () => {
+93
View File
@@ -148,3 +148,96 @@ export function geodesicInverse(lon1, lat1, lon2, lat2) {
export function surfaceDistance(start, end) {
return geodesicInverse(start.lon, start.lat, end.lon, end.lat).distance;
}
/**
* The WGS84 geodesic from (lon1, lat1) to (lon2, lat2), radians, solved once
* as the default renderer's `EllipsoidGeodesic` solves it: its length in
* metres, its start heading, and `at(fraction)`, the longitude and latitude
* (radians) that fraction of the way along it, by the series the renderer
* interpolates with, term for term. The longitude is not wrapped, as the
* renderer's is not.
*/
export function geodesicLine(lon1, lat1, lon2, lat2) {
const { distance, startHeading, uSquared } = geodesicInverse(
lon1,
lat1,
lon2,
lat2,
);
const cosH = Math.cos(startHeading);
const sinH = Math.sin(startHeading);
const tanU = (1 - FLATTENING) * Math.tan(lat1);
const cosU = 1 / Math.sqrt(1 + tanU * tanU);
const sinU = cosU * tanU;
const sigma1 = Math.atan2(tanU, cosH);
const sineAlpha = cosU * sinH;
const cos2Alpha = 1 - sineAlpha * sineAlpha;
const cosAlpha = Math.sqrt(cos2Alpha);
const u2 = uSquared / 4;
const u4 = u2 * u2;
const u6 = u4 * u2;
const u8 = u4 * u4;
const a0 = 1 + u2 - (3 * u4) / 4 + (5 * u6) / 4 - (175 * u8) / 64;
const a1 = 1 - u2 + (15 * u4) / 8 - (35 * u6) / 8;
const a2 = 1 - 3 * u2 + (35 * u4) / 4;
const a3 = 1 - 5 * u2;
const distanceRatio =
a0 * sigma1 -
(a1 * Math.sin(2 * sigma1) * u2) / 2 -
(a2 * Math.sin(4 * sigma1) * u4) / 16 -
(a3 * Math.sin(6 * sigma1) * u6) / 48 -
(Math.sin(8 * sigma1) * 5 * u8) / 512;
return {
distance,
startHeading,
at(fraction) {
const s = distanceRatio + (distance * fraction) / MINOR;
const cos2S = Math.cos(2 * s);
const cos4S = Math.cos(4 * s);
const cos6S = Math.cos(6 * s);
const sin2S = Math.sin(2 * s);
const sin4S = Math.sin(4 * s);
const sin6S = Math.sin(6 * s);
const sin8S = Math.sin(8 * s);
const s2 = s * s;
const s3 = s * s2;
let sigma =
(2 * s3 * u8 * cos2S) / 3 +
s *
(1 -
u2 +
(7 * u4) / 4 -
(15 * u6) / 4 +
(579 * u8) / 64 -
(u4 - (15 * u6) / 4 + (187 * u8) / 16) * cos2S -
((5 * u6) / 4 - (115 * u8) / 16) * cos4S -
(29 * u8 * cos6S) / 16) +
(u2 / 2 - u4 + (71 * u6) / 32 - (85 * u8) / 16) * sin2S +
((5 * u4) / 16 - (5 * u6) / 4 + (383 * u8) / 96) * sin4S -
s2 * ((u6 - (11 * u8) / 2) * sin2S + (5 * u8 * sin4S) / 2) +
((29 * u6) / 96 - (29 * u8) / 16) * sin6S +
(539 * u8 * sin8S) / 1536;
const theta = Math.asin(Math.sin(sigma) * cosAlpha);
const lat = Math.atan((MAJOR / MINOR) * Math.tan(theta));
sigma -= sigma1;
const cos2Sm = Math.cos(2 * sigma1 + sigma);
const sinSigma = Math.sin(sigma);
const cosSigma = Math.cos(sigma);
const lambda = Math.atan2(
sinSigma * sinH,
cosU * cosSigma - sinU * sinSigma * cosH,
);
const l =
lambda -
deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm);
return { lon: lon1 + l, lat };
},
};
}
/** `geodesicLine(lon1, lat1, lon2, lat2).at(fraction)`. */
export function geodesicAt(lon1, lat1, lon2, lat2, fraction) {
return geodesicLine(lon1, lat1, lon2, lat2).at(fraction);
}
+37 -1
View File
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test from 'node:test';
import { surfaceDistance } from './geodesic.js';
import { geodesicAt, surfaceDistance } from './geodesic.js';
test('surface distance matches the default renderer’s geodesic', () => {
let seed = 11;
@@ -45,3 +45,39 @@ test('the same point is no distance away, and nearly antipodal points still answ
);
assert.ok(Number.isFinite(far) && far > 1.9e7);
});
test('a point along the geodesic is the default renderer’s', () => {
let seed = 23;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const d = Math.PI / 180;
for (let i = 0; i < 200; i++) {
const start = new Cesium.Cartographic(
(random() * 360 - 180) * d,
(random() * 170 - 85) * d,
);
const reach = i % 2 ? 3 : 90;
const end = new Cesium.Cartographic(
start.longitude + (random() * 2 - 1) * reach * d,
Math.max(
-89,
Math.min(89, start.latitude / d + (random() * 2 - 1) * reach),
) * d,
);
const geodesic = new Cesium.EllipsoidGeodesic(start, end);
for (const fraction of [0, 0.25, 0.5, 0.9, 1]) {
const theirs = geodesic.interpolateUsingFraction(fraction);
const ours = geodesicAt(
start.longitude,
start.latitude,
end.longitude,
end.latitude,
fraction,
);
assert.ok(
Math.abs(ours.lon - theirs.longitude) <= 1e-12 &&
Math.abs(ours.lat - theirs.latitude) <= 1e-12,
`${i} @ ${fraction}: ${ours.lon},${ours.lat} vs ${theirs.longitude},${theirs.latitude}`,
);
}
}
});
+33
View File
@@ -81,3 +81,36 @@ export function sphereFromPoints(points) {
? { center: ritter, radius: ritterRadius }
: { center: naive, radius: naiveRadius };
}
/**
* The smallest sphere holding both spheres, by the default renderer's own
* method (`BoundingSphere.union`).
* @param {{center: {x: number, y: number, z: number}, radius: number}} left
* @param {{center: {x: number, y: number, z: number}, radius: number}} right
* @returns {{center: {x: number, y: number, z: number}, radius: number}}
*/
export function sphereUnion(left, right) {
const toRight = {
x: right.center.x - left.center.x,
y: right.center.y - left.center.y,
z: right.center.z - left.center.z,
};
const separation = Math.sqrt(
toRight.x * toRight.x + toRight.y * toRight.y + toRight.z * toRight.z,
);
if (left.radius >= separation + right.radius)
return { center: copy(left.center), radius: left.radius };
if (right.radius >= separation + left.radius)
return { center: copy(right.center), radius: right.radius };
// Halfway between the two tangent points, one on the far side of each.
const half = (left.radius + separation + right.radius) * 0.5;
const along = (-left.radius + half) / separation;
return {
center: {
x: toRight.x * along + left.center.x,
y: toRight.y * along + left.center.y,
z: toRight.z * along + left.center.z,
},
radius: half,
};
}
+30 -1
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test from 'node:test';
import { fromDegrees } from './ellipsoid.js';
import { sphereFromPoints } from './sphere.js';
import { sphereFromPoints, sphereUnion } from './sphere.js';
test('a sphere from points is the default renderer’s, to the bit', () => {
let seed = 7;
@@ -28,3 +28,32 @@ test('a sphere from points is the default renderer’s, to the bit', () => {
);
}
});
test('the union of two spheres is the default renderer’s, to the bit', () => {
const sphere = (x, y, z, radius) => ({ center: { x, y, z }, radius });
const cases = [
// Apart, overlapping, one inside the other either way, concentric.
[sphere(0, 0, 0, 6378137), sphere(4.2e7, 1e6, -3e5, 2.1e7)],
[sphere(1, 2, 3, 10), sphere(5, -4, 2, 8)],
[sphere(0, 0, 0, 6378137), sphere(1e5, 0, 0, 7000)],
[sphere(1e5, 0, 0, 7000), sphere(0, 0, 0, 6378137)],
[sphere(3, 3, 3, 5), sphere(3, 3, 3, 5)],
];
for (const [left, right] of cases) {
const ours = sphereUnion(left, right);
const theirs = Cesium.BoundingSphere.union(
new Cesium.BoundingSphere(
new Cesium.Cartesian3(left.center.x, left.center.y, left.center.z),
left.radius,
),
new Cesium.BoundingSphere(
new Cesium.Cartesian3(right.center.x, right.center.y, right.center.z),
right.radius,
),
);
assert.deepEqual(
[ours.center.x, ours.center.y, ours.center.z, ours.radius],
[theirs.center.x, theirs.center.y, theirs.center.z, theirs.radius],
);
}
});
+104 -152
View File
@@ -1,4 +1,25 @@
import * as Cesium from 'cesium';
import {
WGS84,
fromRadians,
toCartographicRadians,
} from '../../geo/ellipsoid.js';
import { geodesicInverse } from '../../geo/geodesic.js';
import { sphereFromPoints, sphereUnion } from '../../geo/sphere.js';
import {
PI_OVER_TWO,
add,
clamp,
clone,
cross,
dot,
negativePiToPi,
normalize,
scale,
sub,
toRadians,
zeroToTwoPi,
} from '../../geo/vector.js';
import { lerp, lerpPoint } from './geometry.js';
import {
REPLAY_ASCENT_CAMERA_OFFSET_RAD,
REPLAY_ORBIT_CAMERA_OFFSET_RAD,
@@ -17,26 +38,23 @@ export function createCamera({ state: layerState, services, parts, source }) {
function cameraHeadingForPath(path, progress, fallback = Math.PI) {
if (!path?.length) return fallback;
const current = parts.paths.samplePath(path, progress);
const currentCartographic =
Cesium.Ellipsoid.WGS84.cartesianToCartographic(current);
const currentCartographic = toCartographicRadians(current);
if (!currentCartographic) return fallback;
for (const step of [0.01, 0.025, 0.05, 0.1, 0.2]) {
const next = parts.paths.samplePath(path, Math.min(1, progress + step));
const nextCartographic =
Cesium.Ellipsoid.WGS84.cartesianToCartographic(next);
const nextCartographic = toCartographicRadians(next);
if (!nextCartographic) continue;
const geodesic = new Cesium.EllipsoidGeodesic(
currentCartographic,
nextCartographic,
const geodesic = geodesicInverse(
currentCartographic.lon,
currentCartographic.lat,
nextCartographic.lon,
nextCartographic.lat,
);
if (
geodesic.surfaceDistance > 10 &&
Number.isFinite(geodesic.startHeading)
) {
if (geodesic.distance > 10 && Number.isFinite(geodesic.startHeading)) {
// HeadingPitchRange positions the camera opposite its heading vector.
// Passing the forward path heading therefore keeps the camera behind
// the vehicle, with the remaining ascent receding into the scene.
return Cesium.Math.zeroToTwoPi(geodesic.startHeading);
return zeroToTwoPi(geodesic.startHeading);
}
}
return fallback;
@@ -44,14 +62,12 @@ export function createCamera({ state: layerState, services, parts, source }) {
/**
* Resolve the initial replay heading as a profile view of the path.
* @param {Cesium.Cartesian3[]} path Replay path.
* @param {Array<{x: number, y: number, z: number}>} path Replay path, ECEF.
* @returns {number} Heading perpendicular to the initial path direction.
*/
function replayInitialCameraHeading(path) {
return Cesium.Math.zeroToTwoPi(
cameraHeadingForPath(path, 0, Math.PI) + Cesium.Math.PI_OVER_TWO,
);
return zeroToTwoPi(cameraHeadingForPath(path, 0, Math.PI) + PI_OVER_TWO);
}
/**
@@ -59,14 +75,14 @@ export function createCamera({ state: layerState, services, parts, source }) {
* widen that rear-quarter angle as the orbit becomes visible.
* @param {number} pathHeading Forward path bearing in radians.
* @param {number} orbitBlend Normalized orbit-camera transition.
* @returns {number} Cesium HeadingPitchRange heading.
* @returns {number} Camera heading, as a heading-pitch-range offset takes it.
*/
function replayChaseCameraHeading(pathHeading, orbitBlend = 0) {
const blend = Cesium.Math.clamp(Number(orbitBlend) || 0, 0, 1);
return Cesium.Math.zeroToTwoPi(
const blend = clamp(Number(orbitBlend) || 0, 0, 1);
return zeroToTwoPi(
pathHeading +
Cesium.Math.lerp(
lerp(
REPLAY_ASCENT_CAMERA_OFFSET_RAD,
REPLAY_ORBIT_CAMERA_OFFSET_RAD,
blend,
@@ -77,8 +93,8 @@ export function createCamera({ state: layerState, services, parts, source }) {
/**
* Limit replay-camera yaw changes so a path heading wrap or insertion turn
* cannot swing the chase view through the front of the vehicle.
* @param {number} previous Previous Cesium heading in radians.
* @param {number} desired Desired Cesium heading in radians.
* @param {number} previous Previous camera heading in radians.
* @param {number} desired Desired camera heading in radians.
* @param {number} [maxStepRad] Maximum angular change for one rendered frame.
* @returns {number}
*/
@@ -86,29 +102,25 @@ export function createCamera({ state: layerState, services, parts, source }) {
function smoothReplayCameraHeading(
previous,
desired,
maxStepRad = Cesium.Math.toRadians(2),
maxStepRad = toRadians(2),
) {
if (!Number.isFinite(previous)) return Cesium.Math.zeroToTwoPi(desired);
if (!Number.isFinite(desired)) return Cesium.Math.zeroToTwoPi(previous);
const delta = Cesium.Math.negativePiToPi(desired - previous);
const step = Cesium.Math.clamp(
delta,
-Math.abs(maxStepRad),
Math.abs(maxStepRad),
);
return Cesium.Math.zeroToTwoPi(previous + step);
if (!Number.isFinite(previous)) return zeroToTwoPi(desired);
if (!Number.isFinite(desired)) return zeroToTwoPi(previous);
const delta = negativePiToPi(desired - previous);
const step = clamp(delta, -Math.abs(maxStepRad), Math.abs(maxStepRad));
return zeroToTwoPi(previous + step);
}
/**
* Blend from a global nadir view into an oblique local 3D view as the user
* approaches a selected launch site.
* @param {number} rangeM Camera distance from the launch-site anchor.
* @returns {number} Cesium camera pitch in radians.
* @returns {number} Camera pitch in radians.
*/
function missionZoomPitch(rangeM) {
const range = Math.max(0, Number(rangeM) || 0);
const blend = Cesium.Math.clamp(
const blend = clamp(
(Math.log(Math.max(range, MISSION_CLOSE_VIEW_RANGE_M)) -
Math.log(MISSION_CLOSE_VIEW_RANGE_M)) /
(Math.log(MISSION_GLOBE_VIEW_RANGE_M) -
@@ -116,11 +128,7 @@ export function createCamera({ state: layerState, services, parts, source }) {
0,
1,
);
return Cesium.Math.lerp(
Cesium.Math.toRadians(-42),
-Cesium.Math.PI_OVER_TWO,
blend,
);
return lerp(toRadians(-42), -PI_OVER_TWO, blend);
}
/**
@@ -133,71 +141,63 @@ export function createCamera({ state: layerState, services, parts, source }) {
function replayCameraView(state, altitudeM) {
const altitude = Math.max(0, Number(altitudeM) || 0);
const localRange = Cesium.Math.clamp(
const localRange = clamp(
REPLAY_INITIAL_RANGE_M + altitude * 0.7,
REPLAY_INITIAL_RANGE_M,
REPLAY_LOCAL_MAX_RANGE_M,
);
const rawContextBlend = Cesium.Math.clamp(
const rawContextBlend = clamp(
(altitude - 20000) / (REPLAY_CONTEXT_ALTITUDE_END_M - 20000),
0,
1,
);
const contextBlend =
rawContextBlend * rawContextBlend * (3 - 2 * rawContextBlend);
const contextRange = Cesium.Math.clamp(
const contextRange = clamp(
180000 + altitude * 3.8,
MISSION_CLOSE_VIEW_RANGE_M,
REPLAY_CONTEXT_MAX_RANGE_M,
);
const ascentRange = Cesium.Math.lerp(
localRange,
contextRange,
contextBlend,
);
const ascentPitch = Cesium.Math.lerp(
Cesium.Math.toRadians(-20),
Cesium.Math.toRadians(-34),
contextBlend,
);
const ascentRange = lerp(localRange, contextRange, contextBlend);
const ascentPitch = lerp(toRadians(-20), toRadians(-34), contextBlend);
if (state?.ascending) {
return { range: ascentRange, pitch: ascentPitch };
}
const rawBlend = Cesium.Math.clamp(
const rawBlend = clamp(
(Number(state?.phaseProgress) || 0) / REPLAY_ORBIT_PULLBACK_FRACTION,
0,
1,
);
const blend = rawBlend * rawBlend * (3 - 2 * rawBlend);
return {
range: Cesium.Math.lerp(ascentRange, REPLAY_ORBIT_GLOBE_RANGE_M, blend),
range: lerp(ascentRange, REPLAY_ORBIT_GLOBE_RANGE_M, blend),
// Keep an oblique tactical view of the complete orbit rather than ending
// in a nadir view. This also prevents the camera from appearing to
// return toward the launch site after insertion.
pitch: Cesium.Math.lerp(ascentPitch, Cesium.Math.toRadians(-45), blend),
pitch: lerp(ascentPitch, toRadians(-45), blend),
};
}
/**
* Move the orbit-follow target from the vehicle toward its sub-satellite
* globe anchor, keeping Earth centered while the vehicle remains in frame.
* @param {Cesium.Cartesian3} position Animated orbital position.
* Positions are ECEF `{x, y, z}`.
* @param {object} position Animated orbital position.
* @param {number} orbitBlend Normalized orbit-camera transition.
* @returns {Cesium.Cartesian3} Camera look-at target.
* @returns {object} Camera look-at target.
*/
function replayOrbitGlobeAnchor(position, orbitBlend = 0) {
if (!position) return position;
const blend = Cesium.Math.clamp(Number(orbitBlend) || 0, 0, 1);
if (blend <= 0) return Cesium.Cartesian3.clone(position);
const cartographic =
Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
if (!cartographic) return Cesium.Cartesian3.clone(position);
const blend = clamp(Number(orbitBlend) || 0, 0, 1);
if (blend <= 0) return clone(position);
const cartographic = toCartographicRadians(position);
if (!cartographic) return clone(position);
const altitude = Math.max(0, cartographic.height || 0);
return Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
Cesium.Math.lerp(altitude, altitude * 0.1, blend),
return fromRadians(
cartographic.lon,
cartographic.lat,
lerp(altitude, altitude * 0.1, blend),
);
}
@@ -208,24 +208,19 @@ export function createCamera({ state: layerState, services, parts, source }) {
* for a heading/pitch camera and lets compact-orbit vehicles leave the view as
* the camera rotates. Retaining a radial vehicle bias keeps the local frame
* stable while the wider camera range still contains Earth and the full orbit.
* @param {Cesium.Cartesian3} vehicleAnchor Globe-side anchor below the vehicle.
* @param {Cesium.Cartesian3|null} frameCenter Combined Earth/orbit frame center.
* Positions are ECEF `{x, y, z}`.
* @param {object} vehicleAnchor Globe-side anchor below the vehicle.
* @param {object|null} frameCenter Combined Earth/orbit frame center.
* @param {number} orbitBlend Normalized orbit-camera transition.
* @returns {Cesium.Cartesian3} Stable camera look-at target.
* @returns {object} Stable camera look-at target.
*/
function replayOrbitCameraTarget(vehicleAnchor, frameCenter, orbitBlend = 0) {
if (!vehicleAnchor) return vehicleAnchor;
if (!frameCenter) return Cesium.Cartesian3.clone(vehicleAnchor);
if (!frameCenter) return clone(vehicleAnchor);
const blend =
Cesium.Math.clamp(Number(orbitBlend) || 0, 0, 1) *
REPLAY_ORBIT_FRAME_CENTER_BLEND;
return Cesium.Cartesian3.lerp(
vehicleAnchor,
frameCenter,
blend,
new Cesium.Cartesian3(),
);
clamp(Number(orbitBlend) || 0, 0, 1) * REPLAY_ORBIT_FRAME_CENTER_BLEND;
return lerpPoint(vehicleAnchor, frameCenter, blend);
}
/**
@@ -233,12 +228,13 @@ export function createCamera({ state: layerState, services, parts, source }) {
* of the orbital plane and uses the vehicle radial as its visual up axis.
* Consequently the forward orbit tangent always projects toward screen-left
* instead of changing direction when local compass headings wrap near a pole.
* @param {Cesium.Cartesian3} position Current vehicle position.
* @param {Cesium.Cartesian3} tangentPosition Nearby forward path position.
* @param {Cesium.Cartesian3} target Camera look-at target.
* Positions and vectors are ECEF `{x, y, z}`.
* @param {object} position Current vehicle position.
* @param {object} tangentPosition Nearby forward path position.
* @param {object} target Camera look-at target.
* @param {number} range Camera distance from the target.
* @param {number} pitch Camera elevation below the local horizon.
* @returns {{destination: Cesium.Cartesian3, direction: Cesium.Cartesian3, up: Cesium.Cartesian3}|null}
* @returns {{destination: object, direction: object, up: object}|null}
*/
function replayOrbitCameraPose(
@@ -249,64 +245,26 @@ export function createCamera({ state: layerState, services, parts, source }) {
pitch,
) {
if (!position || !tangentPosition || !target) return null;
const radial = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.clone(position),
new Cesium.Cartesian3(),
);
const tangent = Cesium.Cartesian3.subtract(
tangentPosition,
position,
new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.magnitudeSquared(tangent) < 1) return null;
Cesium.Cartesian3.normalize(tangent, tangent);
const orbitNormal = Cesium.Cartesian3.cross(
radial,
tangent,
new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.magnitudeSquared(orbitNormal) < 1e-12) return null;
Cesium.Cartesian3.normalize(orbitNormal, orbitNormal);
const radial = normalize(position);
const offset = sub(tangentPosition, position);
if (dot(offset, offset) < 1) return null;
const tangent = normalize(offset);
const normal = cross(radial, tangent);
if (dot(normal, normal) < 1e-12) return null;
const orbitNormal = normalize(normal);
const distance = Math.max(1, Number(range) || 1);
const elevation = Cesium.Math.clamp(
const elevation = clamp(
Math.abs(Number(pitch) || 0),
Cesium.Math.toRadians(5),
Cesium.Math.toRadians(80),
);
const planeOffset = Cesium.Cartesian3.multiplyByScalar(
orbitNormal,
Math.cos(elevation) * distance,
new Cesium.Cartesian3(),
);
const radialOffset = Cesium.Cartesian3.multiplyByScalar(
radial,
Math.sin(elevation) * distance,
new Cesium.Cartesian3(),
);
const destination = Cesium.Cartesian3.add(
target,
planeOffset,
new Cesium.Cartesian3(),
);
Cesium.Cartesian3.add(destination, radialOffset, destination);
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, destination, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const radialAlongView = Cesium.Cartesian3.multiplyByScalar(
direction,
Cesium.Cartesian3.dot(radial, direction),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(
radial,
radialAlongView,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
toRadians(5),
toRadians(80),
);
const planeOffset = scale(orbitNormal, Math.cos(elevation) * distance);
const radialOffset = scale(radial, Math.sin(elevation) * distance);
const destination = add(add(target, planeOffset), radialOffset);
const direction = normalize(sub(target, destination));
const radialAlongView = scale(direction, dot(radial, direction));
const up = normalize(sub(radial, radialAlongView));
return { destination, direction, up };
}
@@ -315,22 +273,16 @@ export function createCamera({ state: layerState, services, parts, source }) {
* selected orbit. High-apogee missions cannot be composed from the vehicle's
* instantaneous altitude alone because the opposite side of the orbit may
* extend much farther from the globe.
* @param {Cesium.Cartesian3[]} orbitPath Selected orbit samples.
* @returns {Cesium.BoundingSphere} Combined Earth/orbit frame.
* @param {Array<{x: number, y: number, z: number}>} orbitPath Selected
* orbit samples, ECEF.
* @returns {{center: {x: number, y: number, z: number}, radius: number}}
* Combined Earth/orbit frame.
*/
function replayOrbitFrameSphere(orbitPath = []) {
const earth = new Cesium.BoundingSphere(
Cesium.Cartesian3.ZERO,
Cesium.Ellipsoid.WGS84.maximumRadius,
);
const earth = { center: { x: 0, y: 0, z: 0 }, radius: WGS84.radii.x };
if (!Array.isArray(orbitPath) || orbitPath.length < 2) return earth;
const orbit = Cesium.BoundingSphere.fromPoints(orbitPath);
return Cesium.BoundingSphere.union(
earth,
orbit,
new Cesium.BoundingSphere(),
);
return sphereUnion(earth, sphereFromPoints(orbitPath));
}
/**
@@ -351,13 +303,13 @@ export function createCamera({ state: layerState, services, parts, source }) {
const range = Math.max(0, Number(baseRange) || 0);
const altitude = Math.max(0, Number(altitudeM) || 0);
const frameRadius = Math.max(0, Number(frameRadiusM) || 0);
const blend = Cesium.Math.clamp(Number(orbitBlend) || 0, 0, 1);
const blend = clamp(Number(orbitBlend) || 0, 0, 1);
const globeAndVehicleRange = Math.max(
range,
altitude + Cesium.Ellipsoid.WGS84.maximumRadius * 2.4,
altitude + WGS84.radii.x * 2.4,
frameRadius * 3,
);
return Cesium.Math.lerp(range, globeAndVehicleRange, blend);
return lerp(range, globeAndVehicleRange, blend);
}
return {
cameraHeadingForPath,
+20
View File
@@ -0,0 +1,20 @@
/**
* The few interpolation helpers the launch paths and cameras share, written
* as the default renderer writes them so the paths land on the same points.
*/
/** `p` to `q` by `t`. */
export const lerp = (p, q, t) => (1.0 - t) * p + t * q;
/** ECEF `start` to `end` by `t`, as a new point. */
export const lerpPoint = (start, end, t) => ({
x: end.x * t + start.x * (1.0 - t),
y: end.y * t + start.y * (1.0 - t),
z: end.z * t + start.z * (1.0 - t),
});
/** `m` modulo `n`, in `n`'s sign. */
export function mod(m, n) {
if (Math.sign(m) === Math.sign(n) && Math.abs(m) < Math.abs(n)) return m;
return ((m % n) + n) % n;
}
+25 -21
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { hexColor } from '../../render/color.js';
import { msg } from '../../i18n/index.js';
import { WINDOW_DAYS } from './policy.js';
@@ -140,30 +140,33 @@ export function createModel({ state: layerState, services, parts, source }) {
* Select a stable marker color from the mission operator and payload name.
* Labels stay cyan so the layer remains visually coherent.
* @param {object} launch Normalized launch record.
* @returns {Cesium.Color}
* @returns {string} `#rrggbb`.
*/
function missionMarkerColor(launch) {
function missionMarkerHex(launch) {
const identity =
`${launch.provider || ''} ${launch.name || ''} ${launch.missionName || ''}`.toLowerCase();
if (/nasa|national aeronautics/.test(identity))
return Cesium.Color.fromCssColorString('#ff9f43');
if (/starlink|spacex|space exploration/.test(identity))
return Cesium.Color.fromCssColorString('#4cc9f0');
if (/rocket lab/.test(identity))
return Cesium.Color.fromCssColorString('#7bed9f');
if (/isro|indian space/.test(identity))
return Cesium.Color.fromCssColorString('#ff66c4');
if (/cnsa|china national|long march/.test(identity))
return Cesium.Color.fromCssColorString('#ffd166');
if (/blue origin/.test(identity))
return Cesium.Color.fromCssColorString('#a78bfa');
if (/ula|united launch alliance/.test(identity))
return Cesium.Color.fromCssColorString('#f97316');
if (/arianespace|esa|european space/.test(identity))
return Cesium.Color.fromCssColorString('#60a5fa');
if (launch.provider) return Cesium.Color.fromCssColorString('#c084fc');
return Cesium.Color.fromCssColorString('#22e6e6');
if (/nasa|national aeronautics/.test(identity)) return '#ff9f43';
if (/starlink|spacex|space exploration/.test(identity)) return '#4cc9f0';
if (/rocket lab/.test(identity)) return '#7bed9f';
if (/isro|indian space/.test(identity)) return '#ff66c4';
if (/cnsa|china national|long march/.test(identity)) return '#ffd166';
if (/blue origin/.test(identity)) return '#a78bfa';
if (/ula|united launch alliance/.test(identity)) return '#f97316';
if (/arianespace|esa|european space/.test(identity)) return '#60a5fa';
if (launch.provider) return '#c084fc';
return '#22e6e6';
}
/** The marker colour as a renderer colour, `[r, g, b, a]`. */
function missionMarkerColor(launch) {
return hexColor(missionMarkerHex(launch));
}
/** The marker colour as CSS, `rgb(r,g,b)`, for the mission panel. */
function missionMarkerCss(launch) {
const n = Number.parseInt(missionMarkerHex(launch).slice(1), 16);
return `rgb(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255})`;
}
/**
@@ -242,6 +245,7 @@ export function createModel({ state: layerState, services, parts, source }) {
normalizeLanding,
normalizeRecoveryStages,
missionMarkerColor,
missionMarkerCss,
normalizeRocketLaunches,
};
}
+7 -13
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { toCartographicRadians } from '../../geo/ellipsoid.js';
import { formatNumber, isolate, onLocaleChange, t } from '../../i18n/index.js';
import {
MISSION_CLOSE_VIEW_RANGE_M,
@@ -274,7 +274,7 @@ export function createPanel({ state: layerState, services, parts, source }) {
return {
index,
id: String(launch.id ?? ''),
color: parts.model.missionMarkerColor(launch).toCssColorString(),
color: parts.model.missionMarkerCss(launch),
label,
ariaLabel: t('Select {mission}', { mission: label }),
provider: launch.provider || t('UNSPECIFIED OPERATOR'),
@@ -319,18 +319,12 @@ export function createPanel({ state: layerState, services, parts, source }) {
const now = performance.now();
if (!force && now - layerState._lastPanelTelemetryMs < 250) return;
layerState._lastPanelTelemetryMs = now;
const satellite = layerState._dataSource.entities.getById(
`rocket-satellite:${layerState._selectedLaunchId}`,
);
const position = satellite?.position?.getValue(
Cesium.JulianDate.now(layerState._declutterTime),
);
const altitudeM = position
? Cesium.Cartographic.fromCartesian(position)?.height
: null;
const speedMps = layerState._satelliteTelemetry.get(
const telemetry = layerState._satelliteTelemetry.get(
layerState._selectedLaunchId,
)?.speedMps;
);
const position = telemetry?.position?.();
const altitudeM = position ? toCartographicRadians(position)?.height : null;
const speedMps = telemetry?.speedMps;
layerState._missionTelemetry = {
distance: Number.isFinite(altitudeM)
? t('{value} KM', {
+1 -1
View File
@@ -22,7 +22,7 @@ function fixture() {
previewMissionFromRoster: (launch) => calls.push(['preview', launch.id]),
},
model: {
missionMarkerColor: () => ({ toCssColorString: () => 'rgb(1, 2, 3)' }),
missionMarkerCss: () => 'rgb(1, 2, 3)',
},
selection: {
setSelectedMission: (id, isolate) => calls.push(['select', id, isolate]),
+149 -224
View File
@@ -1,4 +1,27 @@
import * as Cesium from 'cesium';
import {
WGS84,
fromDegrees,
fromRadians,
toCartographicRadians,
} from '../../geo/ellipsoid.js';
import { geodesicInverse, geodesicLine } from '../../geo/geodesic.js';
import {
PI_OVER_TWO,
add,
clamp,
cross,
distance,
dot,
magnitude,
negativePiToPi,
normalize,
scale,
sub,
toDegrees,
toRadians,
vec,
} from '../../geo/vector.js';
import { lerp, mod } from './geometry.js';
import { t } from '../../i18n/index.js';
import {
EARTH_ROTATION_RAD_PER_SEC,
@@ -6,6 +29,14 @@ import {
STAGE_REENTRY_ALTITUDE_M,
} from './policy.js';
/** Copy `from` into `to`, keeping `to`. */
function copyInto(from, to) {
to.x = from.x;
to.y = from.y;
to.z = from.z;
return to;
}
export function createPaths({ state: layerState, services, parts, source }) {
function orbitInsertionOffsetSeconds(launch) {
const events = (launch.timeline || []).filter(
@@ -31,10 +62,8 @@ export function createPaths({ state: layerState, services, parts, source }) {
function estimatedOrbitPeriodSeconds(orbitPath) {
if (!orbitPath?.length) return 5400;
const meanRadius =
orbitPath.reduce(
(total, point) => total + Cesium.Cartesian3.magnitude(point),
0,
) / orbitPath.length;
orbitPath.reduce((total, point) => total + magnitude(point), 0) /
orbitPath.length;
return 2 * Math.PI * Math.sqrt(meanRadius ** 3 / 3.986004418e14);
}
@@ -52,20 +81,16 @@ export function createPaths({ state: layerState, services, parts, source }) {
: orbitName.includes('medium')
? 20200000
: 550000;
const radius = Cesium.Ellipsoid.WGS84.maximumRadius + altitude;
const longitude = Cesium.Math.toRadians(launch.lon);
const latitude = Cesium.Math.toRadians(launch.lat);
const up = new Cesium.Cartesian3(
const radius = WGS84.radii.x + altitude;
const longitude = toRadians(launch.lon);
const latitude = toRadians(launch.lat);
const up = vec(
Math.cos(latitude) * Math.cos(longitude),
Math.cos(latitude) * Math.sin(longitude),
Math.sin(latitude),
);
const east = new Cesium.Cartesian3(
-Math.sin(longitude),
Math.cos(longitude),
0,
);
const north = new Cesium.Cartesian3(
const east = vec(-Math.sin(longitude), Math.cos(longitude), 0);
const north = vec(
-Math.sin(latitude) * Math.cos(longitude),
-Math.sin(latitude) * Math.sin(longitude),
Math.cos(latitude),
@@ -83,60 +108,30 @@ export function createPaths({ state: layerState, services, parts, source }) {
: isWesternNorthAmerica
? 190
: 90;
const launchAzimuth = Cesium.Math.toRadians(launchAzimuthDeg);
const forward = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.add(
Cesium.Cartesian3.multiplyByScalar(
north,
Math.cos(launchAzimuth),
new Cesium.Cartesian3(),
),
Cesium.Cartesian3.multiplyByScalar(
east,
Math.sin(launchAzimuth),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
const launchAzimuth = toRadians(launchAzimuthDeg);
const forward = normalize(
add(
scale(north, Math.cos(launchAzimuth)),
scale(east, Math.sin(launchAzimuth)),
),
new Cesium.Cartesian3(),
);
// A reconstructed orbit is an estimate, not a claim that the vehicle was
// inserted directly above the pad. Offset the orbital plane downrange by a
// small launch-to-insertion arc so a top-down view does not draw the entire
// orbit on top of the launch site. The ascent still joins this ring at its
// propagated insertion reference.
const insertionArc = Cesium.Math.toRadians(isPolar ? 8 : 12);
const orbitAnchor = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.add(
Cesium.Cartesian3.multiplyByScalar(
up,
Math.cos(insertionArc),
new Cesium.Cartesian3(),
),
Cesium.Cartesian3.multiplyByScalar(
forward,
Math.sin(insertionArc),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
const insertionArc = toRadians(isPolar ? 8 : 12);
const orbitAnchor = normalize(
add(
scale(up, Math.cos(insertionArc)),
scale(forward, Math.sin(insertionArc)),
),
new Cesium.Cartesian3(),
);
const planeNormal = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(orbitAnchor, forward, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const crossTrack = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(
planeNormal,
orbitAnchor,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const planeNormal = normalize(cross(orbitAnchor, forward));
const crossTrack = normalize(cross(planeNormal, orbitAnchor));
return Array.from({ length: 97 }, (_, index) => {
const angle = (index / 96) * Math.PI * 2;
return new Cesium.Cartesian3(
return vec(
radius *
(Math.cos(angle) * orbitAnchor.x + Math.sin(angle) * crossTrack.x),
radius *
@@ -151,22 +146,20 @@ export function createPaths({ state: layerState, services, parts, source }) {
if (!path?.length) return undefined;
// Degenerate returns clone into `result` when provided — handing back a
// path vertex would let an in-place caller mutate the path geometry.
if (path.length === 1)
return result ? Cesium.Cartesian3.clone(path[0], result) : path[0];
if (path.length === 1) return result ? copyInto(path[0], result) : path[0];
let distances = layerState._pathDistanceCache.get(path);
if (!distances) {
distances = new Float64Array(path.length);
for (let index = 1; index < path.length; index++) {
distances[index] =
distances[index - 1] +
Cesium.Cartesian3.distance(path[index - 1], path[index]);
distances[index - 1] + distance(path[index - 1], path[index]);
}
layerState._pathDistanceCache.set(path, distances);
}
const totalDistance = distances.at(-1);
if (!(totalDistance > 0))
return result ? Cesium.Cartesian3.clone(path[0], result) : path[0];
const targetDistance = Cesium.Math.clamp(progress, 0, 1) * totalDistance;
return result ? copyInto(path[0], result) : path[0];
const targetDistance = clamp(progress, 0, 1) * totalDistance;
let low = 1;
let high = distances.length - 1;
while (low < high) {
@@ -180,12 +173,14 @@ export function createPaths({ state: layerState, services, parts, source }) {
segmentDistance > 0
? (targetDistance - distances[index]) / segmentDistance
: 0;
return Cesium.Cartesian3.lerp(
path[index],
path[index + 1],
segmentProgress,
result || new Cesium.Cartesian3(),
);
// As the default renderer lerps: the end's share, plus the start's.
const start = path[index];
const end = path[index + 1];
const point = result || vec();
point.x = end.x * segmentProgress + start.x * (1.0 - segmentProgress);
point.y = end.y * segmentProgress + start.y * (1.0 - segmentProgress);
point.z = end.z * segmentProgress + start.z * (1.0 - segmentProgress);
return point;
}
/**
@@ -199,17 +194,19 @@ export function createPaths({ state: layerState, services, parts, source }) {
function orbitProgressAtTime(nowMs, periodSec) {
const period = Math.max(1, Number(periodSec) || 1);
return Cesium.Math.mod((Number(nowMs) || 0) / 1000, period) / period;
return mod((Number(nowMs) || 0) / 1000, period) / period;
}
/**
* Construct one continuous estimated climb from the pad to orbit insertion.
* Horizontal movement begins much more slowly than altitude gain, preserving
* the near-vertical launch appearance without a hard corner at 120 km.
* @param {Cesium.Cartesian3} launchPosition Launch-pad position.
* @param {Cesium.Cartesian3} insertionPosition Orbit insertion position.
* @param {{x: number, y: number, z: number}} launchPosition Launch-pad
* position, ECEF.
* @param {{x: number, y: number, z: number}} insertionPosition Orbit
* insertion position, ECEF.
* @param {number} [samples] Number of curve intervals.
* @returns {Cesium.Cartesian3[]}
* @returns {Array<{x: number, y: number, z: number}>}
*/
function reconstructedAscentPath(
@@ -217,24 +214,21 @@ export function createPaths({ state: layerState, services, parts, source }) {
insertionPosition,
samples = 512,
) {
const ellipsoid = Cesium.Ellipsoid.WGS84;
const origin = ellipsoid.cartesianToCartographic(launchPosition);
const insertion = ellipsoid.cartesianToCartographic(insertionPosition);
const origin = toCartographicRadians(launchPosition);
const insertion = toCartographicRadians(insertionPosition);
if (!origin || !insertion) return [launchPosition, insertionPosition];
const geodesic = new Cesium.EllipsoidGeodesic(
new Cesium.Cartographic(origin.longitude, origin.latitude),
new Cesium.Cartographic(insertion.longitude, insertion.latitude),
ellipsoid,
const geodesic = geodesicLine(
origin.lon,
origin.lat,
insertion.lon,
insertion.lat,
);
return Array.from({ length: samples + 1 }, (_, index) => {
const progress = index / samples;
if (index === 0) return launchPosition;
if (index === samples) return insertionPosition;
const horizontalProgress = progress ** 4;
const cartographic = geodesic.interpolateUsingFraction(
horizontalProgress,
new Cesium.Cartographic(),
);
const along = geodesic.at(horizontalProgress);
// Approximate the inertial eastward lead accumulated during a ten-minute
// ascent. The p³ envelope keeps liftoff nearly vertical, peaks during the
// upper climb, and returns to the fixed insertion endpoint.
@@ -242,34 +236,27 @@ export function createPaths({ state: layerState, services, parts, source }) {
EARTH_ROTATION_RAD_PER_SEC *
PROJECTED_ASCENT_ROTATION_SEC *
Math.sin(Math.PI * progress ** 3);
cartographic.longitude = Cesium.Math.negativePiToPi(
cartographic.longitude + rotationalLead,
return fromRadians(
negativePiToPi(along.lon + rotationalLead),
along.lat,
lerp(
Math.max(0, origin.height),
Math.max(0, insertion.height),
Math.sin(progress * PI_OVER_TWO),
),
);
cartographic.height = Cesium.Math.lerp(
Math.max(0, origin.height),
Math.max(0, insertion.height),
Math.sin(progress * Cesium.Math.PI_OVER_TWO),
);
return ellipsoid.cartographicToCartesian(cartographic);
});
}
function nearestOrbitIndex(orbitPath, referencePosition) {
if (!orbitPath?.length || !referencePosition) return 0;
const referenceDirection = Cesium.Cartesian3.normalize(
referencePosition,
new Cesium.Cartesian3(),
);
const referenceDirection = normalize(referencePosition);
let bestIndex = 0;
let bestDot = -Number.MAX_VALUE;
orbitPath.forEach((candidate, index) => {
const direction = Cesium.Cartesian3.normalize(
candidate,
new Cesium.Cartesian3(),
);
const dot = Cesium.Cartesian3.dot(referenceDirection, direction);
if (dot > bestDot) {
bestDot = dot;
const alignment = dot(referenceDirection, normalize(candidate));
if (alignment > bestDot) {
bestDot = alignment;
bestIndex = index;
}
});
@@ -280,44 +267,36 @@ export function createPaths({ state: layerState, services, parts, source }) {
if (!orbitPath?.length) return [];
const first = orbitPath[0];
const last = orbitPath.at(-1);
const isClosed =
orbitPath.length > 2 && Cesium.Cartesian3.distance(first, last) < 1000;
const isClosed = orbitPath.length > 2 && distance(first, last) < 1000;
const core = isClosed ? orbitPath.slice(0, -1) : orbitPath.slice();
if (!core.length) return orbitPath.slice();
const index = Cesium.Math.mod(insertionIndex, core.length);
const index = mod(insertionIndex, core.length);
const rotated = [...core.slice(index), ...core.slice(0, index)];
rotated.push(rotated[0]);
return rotated;
}
function surfaceSafeSegment(startPosition, endPosition) {
const ellipsoid = Cesium.Ellipsoid.WGS84;
const start = ellipsoid.cartesianToCartographic(startPosition);
const end = ellipsoid.cartesianToCartographic(endPosition);
const start = toCartographicRadians(startPosition);
const end = toCartographicRadians(endPosition);
if (!start || !end) return [startPosition, endPosition];
const geodesic = new Cesium.EllipsoidGeodesic(
new Cesium.Cartographic(start.longitude, start.latitude),
new Cesium.Cartographic(end.longitude, end.latitude),
ellipsoid,
);
const geodesic = geodesicLine(start.lon, start.lat, end.lon, end.lat);
// Replay advances in real time across this path. Keep the geometry
// surface-safe, but give the animated marker and chase camera enough
// samples that they do not visibly pause at long segment boundaries.
const steps = Cesium.Math.clamp(
Math.ceil(geodesic.surfaceDistance / 75000),
2,
256,
);
const steps = clamp(Math.ceil(geodesic.distance / 75000), 2, 256);
const positions = [];
for (let index = 0; index <= steps; index++) {
const fraction = index / steps;
const eased = fraction * fraction * (3 - 2 * fraction);
const cartographic = geodesic.interpolateUsingFraction(
fraction,
new Cesium.Cartographic(),
const along = geodesic.at(fraction);
positions.push(
fromRadians(
along.lon,
along.lat,
lerp(start.height, end.height, eased),
),
);
cartographic.height = Cesium.Math.lerp(start.height, end.height, eased);
positions.push(ellipsoid.cartographicToCartesian(cartographic));
}
positions[0] = startPosition;
positions[positions.length - 1] = endPosition;
@@ -341,23 +320,13 @@ export function createPaths({ state: layerState, services, parts, source }) {
function blendAscentIntoOrbitTangent(ascentPath, orbitPath, insertionIndex) {
if (!ascentPath?.length || ascentPath.length < 4 || !orbitPath?.length)
return ascentPath;
const ellipsoid = Cesium.Ellipsoid.WGS84;
const transferEnd = orbitPath[insertionIndex];
const nextOrbit = orbitPath[(insertionIndex + 1) % orbitPath.length];
const orbitTangent = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(
nextOrbit,
transferEnd,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const orbitTangent = normalize(sub(nextOrbit, transferEnd));
if (
Cesium.Cartesian3.equalsEpsilon(
orbitTangent,
Cesium.Cartesian3.ZERO,
1e-8,
)
Math.abs(orbitTangent.x) <= 1e-8 &&
Math.abs(orbitTangent.y) <= 1e-8 &&
Math.abs(orbitTangent.z) <= 1e-8
)
return ascentPath;
@@ -371,77 +340,38 @@ export function createPaths({ state: layerState, services, parts, source }) {
const altitudeEnvelope = ascentPath
.slice(blendStart)
.map((position) =>
Math.max(0, ellipsoid.cartesianToCartographic(position)?.height || 0),
Math.max(0, toCartographicRadians(position)?.height || 0),
);
const ascentTangent = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(start, previous, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const chordLength = Math.max(
Cesium.Cartesian3.distance(start, transferEnd),
1000,
);
const ascentTangent = normalize(sub(start, previous));
const chordLength = Math.max(distance(start, transferEnd), 1000);
const handleLength = chordLength * 0.28;
const controlA = Cesium.Cartesian3.add(
start,
Cesium.Cartesian3.multiplyByScalar(
ascentTangent,
handleLength,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const controlB = Cesium.Cartesian3.add(
transferEnd,
Cesium.Cartesian3.multiplyByScalar(
orbitTangent,
-handleLength,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const controlA = add(start, scale(ascentTangent, handleLength));
const controlB = add(transferEnd, scale(orbitTangent, -handleLength));
for (let index = 0; index <= blendCount; index++) {
const progress = index / blendCount;
const inverse = 1 - progress;
const point = new Cesium.Cartesian3();
Cesium.Cartesian3.multiplyByScalar(start, inverse ** 3, point);
Cesium.Cartesian3.add(
point,
Cesium.Cartesian3.multiplyByScalar(
controlA,
3 * inverse ** 2 * progress,
new Cesium.Cartesian3(),
const point = add(
add(
add(
scale(start, inverse ** 3),
scale(controlA, 3 * inverse ** 2 * progress),
),
scale(controlB, 3 * inverse * progress ** 2),
),
point,
);
Cesium.Cartesian3.add(
point,
Cesium.Cartesian3.multiplyByScalar(
controlB,
3 * inverse * progress ** 2,
new Cesium.Cartesian3(),
),
point,
);
Cesium.Cartesian3.add(
point,
Cesium.Cartesian3.multiplyByScalar(
transferEnd,
progress ** 3,
new Cesium.Cartesian3(),
),
point,
scale(transferEnd, progress ** 3),
);
// A Cartesian Bézier is a chord in world space and can pass through the
// ellipsoid when its orbit-tangent handle is long. Preserve the original
// climb's smooth altitude envelope while retaining the Bézier's horizontal
// curvature and tangent-aligned insertion.
const cartographic = ellipsoid.cartesianToCartographic(point);
const cartographic = toCartographicRadians(point);
const minimumHeight = altitudeEnvelope[index] ?? 0;
if (cartographic && cartographic.height < minimumHeight) {
cartographic.height = minimumHeight;
ascentPath[blendStart + index] =
ellipsoid.cartographicToCartesian(cartographic);
ascentPath[blendStart + index] = fromRadians(
cartographic.lon,
cartographic.lat,
minimumHeight,
);
} else {
ascentPath[blendStart + index] = point;
}
@@ -454,11 +384,12 @@ export function createPaths({ state: layerState, services, parts, source }) {
* Build a globe-safe ascent ending at the nearest point on the selected orbit.
* The returned orbit is rotated to begin at that same insertion point so the
* animated marker cannot jump between ascent and orbital phases.
* @param {Cesium.Cartesian3} launchPosition Launch-site position.
* @param {Cesium.Cartesian3[]} trajectoryPositions Optional upstream stage fixes.
* @param {Cesium.Cartesian3[]} orbitPath Selected satellite or estimated orbit.
* @param {Cesium.Cartesian3|null} [insertionReference] Propagated or estimated insertion position.
* @returns {{ascentPath: Cesium.Cartesian3[], animatedOrbitPath: Cesium.Cartesian3[], insertionIndex: number}}
* Positions are ECEF `{x, y, z}`.
* @param {object} launchPosition Launch-site position.
* @param {object[]} trajectoryPositions Optional upstream stage fixes.
* @param {object[]} orbitPath Selected satellite or estimated orbit.
* @param {object|null} [insertionReference] Propagated or estimated insertion position.
* @returns {{ascentPath: object[], animatedOrbitPath: object[], insertionIndex: number}}
*/
function buildMissionPaths(
@@ -499,16 +430,17 @@ export function createPaths({ state: layerState, services, parts, source }) {
return { lat: launch.lat, lon: launch.lon, accuracy: 'PAD / RTLS' };
}
if (!(stage.downrangeKm > 0) || !insertionPosition) return null;
const ellipsoid = Cesium.Ellipsoid.WGS84;
const start = Cesium.Cartographic.fromDegrees(launch.lon, launch.lat);
const insertion = ellipsoid.cartesianToCartographic(insertionPosition);
const lat1 = toRadians(launch.lat);
const lon1 = toRadians(launch.lon);
const insertion = toCartographicRadians(insertionPosition);
if (!insertion) return null;
const geodesic = new Cesium.EllipsoidGeodesic(start, insertion, ellipsoid);
const bearing = geodesic.startHeading;
const angularDistance =
(stage.downrangeKm * 1000) / ellipsoid.maximumRadius;
const lat1 = start.latitude;
const lon1 = start.longitude;
const bearing = geodesicInverse(
lon1,
lat1,
insertion.lon,
insertion.lat,
).startHeading;
const angularDistance = (stage.downrangeKm * 1000) / WGS84.radii.x;
const lat = Math.asin(
Math.sin(lat1) * Math.cos(angularDistance) +
Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(bearing),
@@ -520,8 +452,8 @@ export function createPaths({ state: layerState, services, parts, source }) {
Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat),
);
return {
lat: Cesium.Math.toDegrees(lat),
lon: Cesium.Math.toDegrees(Cesium.Math.negativePiToPi(lon)),
lat: toDegrees(lat),
lon: toDegrees(negativePiToPi(lon)),
accuracy: t('EST. DOWNRANGE'),
};
}
@@ -533,28 +465,21 @@ export function createPaths({ state: layerState, services, parts, source }) {
stageCount,
) {
if (!ascentPath?.length || !endpoint) return [];
const progress = Cesium.Math.clamp(
const progress = clamp(
0.28 + (stageIndex / Math.max(stageCount, 1)) * 0.34,
0.28,
0.68,
);
const separation = samplePath(ascentPath, progress);
const destination = Cesium.Cartesian3.fromDegrees(
endpoint.lon,
endpoint.lat,
12,
);
const destination = fromDegrees(endpoint.lon, endpoint.lat, 12);
return surfaceSafeSegment(separation, destination);
}
function atmosphericReentryIndex(path) {
if (!path?.length) return 0;
const ellipsoid = Cesium.Ellipsoid.WGS84;
for (let index = 1; index < path.length; index++) {
const previousHeight = ellipsoid.cartesianToCartographic(
path[index - 1],
)?.height;
const height = ellipsoid.cartesianToCartographic(path[index])?.height;
const previousHeight = toCartographicRadians(path[index - 1])?.height;
const height = toCartographicRadians(path[index])?.height;
if (
Number.isFinite(previousHeight) &&
Number.isFinite(height) &&
+4 -4
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { TWO_PI, toRadians } from '../../geo/vector.js';
export const WINDOW_DAYS = 30;
@@ -48,9 +48,9 @@ export const REPLAY_ORBIT_GLOBE_RANGE_M = 18000000;
export const REPLAY_ORBIT_PULLBACK_FRACTION = 0.2;
export const REPLAY_ASCENT_CAMERA_OFFSET_RAD = Cesium.Math.toRadians(30);
export const REPLAY_ASCENT_CAMERA_OFFSET_RAD = toRadians(30);
export const REPLAY_ORBIT_CAMERA_OFFSET_RAD = Cesium.Math.toRadians(45);
export const REPLAY_ORBIT_CAMERA_OFFSET_RAD = toRadians(45);
export const REPLAY_ORBIT_FRAME_CENTER_BLEND = 0.45;
@@ -64,7 +64,7 @@ export const MAX_POST_TLE_RETRIES = 1;
export const POST_TLE_RETRY_DELAY_MS = 1500;
export const EARTH_ROTATION_RAD_PER_SEC = Cesium.Math.TWO_PI / 86164.0905;
export const EARTH_ROTATION_RAD_PER_SEC = TWO_PI / 86164.0905;
export const PROJECTED_ASCENT_ROTATION_SEC = 600;
+6 -7
View File
@@ -1,6 +1,6 @@
import * as Cesium from 'cesium';
import { PI_OVER_TWO } from '../../geo/vector.js';
import { t } from '../../i18n/index.js';
import { cameraOf } from '../../render/cesium/camera.js';
import { cameraOf } from '../../render/rendererOf.js';
import {
SATELLITE_STANDALONE_DEFAULTS,
LAUNCH_PAD_ZONE_MAX_CAMERA_HEIGHT_M,
@@ -226,13 +226,12 @@ export function createPolicyHelpers({
function previewMissionFromRoster(launch) {
if (!layerState._viewer || !launch || layerState._selectedLaunchId) return;
const range = parts.panel.missionHoverPreviewRange(
layerState._viewer.camera.positionCartographic?.height,
);
cameraOf(layerState._viewer).flyToBounds(
const camera = cameraOf(layerState._viewer);
const range = parts.panel.missionHoverPreviewRange(camera.pose().height);
camera.flyToBounds(
{ center: { lon: launch.lon, lat: launch.lat }, radius: 0 },
{
offset: { heading: 0, pitch: -Cesium.Math.PI_OVER_TWO, range },
offset: { heading: 0, pitch: -PI_OVER_TWO, range },
durationS: 0.8,
easing: 'cubicInOut',
},
+41 -17
View File
@@ -1,4 +1,8 @@
import * as Cesium from 'cesium';
// Still Cesium for its entities, so this layer loads the unbound camera
// factory its other parts reach the renderer through.
import '../../render/cesium/camera.js';
import { horizonFrom } from '../../geo/horizon.js';
import {
TRAJECTORY_STAGE_COLORS,
REPLAY_ORBIT_DURATION_SEC,
@@ -14,6 +18,17 @@ export function createRendering({
}) {
const { getSatelliteOrbitTrack, findSatelliteOrbitTrackInTle } =
services.satellites;
const declutterTime = new Cesium.JulianDate();
/** A plain ECEF point (the paths are plain) as the entities take one. */
const cartesian = (point) => Cesium.Cartesian3.clone(point);
const cartesians = (points) => points.map(cartesian);
/** A launch's marker colour, for the entities. */
function markerColor(launch) {
const [r, g, b, a] = parts.model.missionMarkerColor(launch);
return new Cesium.Color(r, g, b, a);
}
function setGraphicVisibility(graphic, visible, time) {
if (!graphic) return;
@@ -32,10 +47,9 @@ export function createRendering({
return;
}
parts.panel.updateMissionTelemetry();
const time = Cesium.JulianDate.now(layerState._declutterTime);
layerState._declutterOccluder.cameraPosition =
layerState._viewer.scene.camera.positionWC;
parts.overlays.updateReplayVehicleOverlay(layerState._declutterOccluder);
const time = Cesium.JulianDate.now(declutterTime);
const occluder = horizonFrom(layerState._viewer.scene.camera.positionWC);
parts.overlays.updateReplayVehicleOverlay(occluder);
parts.overlays.refreshSelectedMissionOverlayText();
for (const entity of layerState._dataSource.entities.values) {
if (!entity.show) continue;
@@ -44,7 +58,7 @@ export function createRendering({
if (!id) continue;
const position = entity.position.getValue(time);
let horizonVisible = Boolean(
position && layerState._declutterOccluder.isPointVisible(position),
position && occluder.isPointVisible(position),
);
const launchAnchor = entity.id.startsWith('rocket-launch:');
if (launchAnchor) {
@@ -114,8 +128,8 @@ export function createRendering({
position,
point: {
pixelSize: 5,
color: parts.model.missionMarkerColor(launch),
outlineColor: parts.model.missionMarkerColor(launch),
color: markerColor(launch),
outlineColor: markerColor(launch),
outlineWidth: 0,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
@@ -175,7 +189,9 @@ export function createRendering({
layerState._dataSource.entities.add({
id: `rocket-trajectory:${launch.id}:${index}`,
polyline: {
positions: parts.paths.surfaceSafePath(segment.positions),
positions: cartesians(
parts.paths.surfaceSafePath(segment.positions),
),
width: 2,
material: Cesium.Color.fromCssColorString(
TRAJECTORY_STAGE_COLORS[index % TRAJECTORY_STAGE_COLORS.length],
@@ -307,7 +323,7 @@ export function createRendering({
layerState._dataSource.entities.add({
id: `rocket-reentry-recovery:${launch.id}:${stageIndex}`,
polyline: {
positions: path,
positions: cartesians(path),
width: 2,
material: new Cesium.PolylineDashMaterialProperty({
color: color.withAlpha(0.82),
@@ -328,7 +344,7 @@ export function createRendering({
layerState._dataSource.entities.add({
id: `rocket-reentry:${launch.id}:${stageIndex}`,
polyline: {
positions: reentryPath,
positions: cartesians(reentryPath),
width: 2.5,
material: new Cesium.PolylineDashMaterialProperty({
color:
@@ -346,7 +362,7 @@ export function createRendering({
source: 'Estimated 100 km atmospheric interface',
},
});
const reentryPosition = path[reentryIndex];
const reentryPosition = cartesian(path[reentryIndex]);
overlayRecord.elementEntryFactories.push(() =>
parts.overlays.createRocketMissionElementOverlayEntry({
id: `reentry:${launch.id}:${stageIndex}`,
@@ -360,7 +376,7 @@ export function createRendering({
}
layerState._dataSource.entities.add({
id: `rocket-recovery-end:${launch.id}:${stageIndex}`,
position: path.at(-1),
position: cartesian(path.at(-1)),
point: {
pixelSize: 4,
color,
@@ -395,7 +411,14 @@ export function createRendering({
orbitCurrent.altitude,
);
const liveTime = new Date();
const liveTelemetry = { speedMps: null };
const liveTelemetry = {
speedMps: null,
// Where the entity draws the payload now, for the mission panel.
position: () => {
updateLiveState();
return livePosition;
},
};
layerState._satelliteTelemetry.set(launch.id, liveTelemetry);
let liveFrameNumber = -1;
const fallbackPeriodSec =
@@ -486,7 +509,7 @@ export function createRendering({
layerState._dataSource.entities.add({
id: `rocket-orbit:${launch.id}`,
polyline: {
positions: orbitPath,
positions: cartesians(orbitPath),
// The 3 px canvas gives the periodic dot room to read as round; the
// shader masks the ten intervening dashes down to a thin center stroke.
width: 3,
@@ -504,7 +527,7 @@ export function createRendering({
},
});
}
const orbitLabelBakePosition = ascentPath.at(-1);
const orbitLabelBakePosition = cartesian(ascentPath.at(-1));
let orbitLabelPosition = orbitLabelBakePosition;
const primitivePath = layerState._missionOrbitPrimitives.get(launch.id);
if (primitivePath) {
@@ -528,9 +551,10 @@ export function createRendering({
);
const replayPosition = new Cesium.CallbackProperty(() => {
const state = getReplayState();
return state.ascending
const sample = state.ascending
? parts.paths.samplePath(ascentPath, state.phaseProgress)
: parts.paths.samplePath(animatedOrbitPath, state.phaseProgress);
return sample && cartesian(sample);
}, false);
layerState._dataSource.entities.add({
id: `rocket-vehicle:${launch.id}`,
@@ -547,7 +571,7 @@ export function createRendering({
layerState._dataSource.entities.add({
id: `rocket-transfer:${launch.id}`,
polyline: {
positions: ascentPath,
positions: cartesians(ascentPath),
width: 1.5,
// The animated vehicle uses Cartesian interpolation between these
// exact samples. Prevent Cesium from replacing each segment with a
-9
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export function createState({ services }) {
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
services.overlays;
@@ -136,13 +134,6 @@ export function createState({ services }) {
state._missionOrbitPrimitives = new Map();
state._declutterTime = new Cesium.JulianDate();
state._declutterOccluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
new Cesium.Cartesian3(),
);
state._missionRingDate = new Date(0);
state._missionOrbitPatternRegistered = false;
-7
View File
@@ -74,20 +74,13 @@
"src/layers/ghostMaps/index.js",
"src/layers/installations/namedMarkers.js",
"src/layers/installations/rendering.js",
"src/layers/launches/camera.js",
"src/layers/launches/launchPad.js",
"src/layers/launches/lifecycle.js",
"src/layers/launches/model.js",
"src/layers/launches/orbitRendering.js",
"src/layers/launches/overlays.js",
"src/layers/launches/panel.js",
"src/layers/launches/paths.js",
"src/layers/launches/policy.js",
"src/layers/launches/policyHelpers.js",
"src/layers/launches/rendering.js",
"src/layers/launches/replay.js",
"src/layers/launches/selection.js",
"src/layers/launches/state.js",
"src/layers/localAdsb/index.js",
"src/layers/localAdsb/models.js",
"src/layers/localAdsb/motion.js",
+1 -1
View File
@@ -44,7 +44,7 @@ import {
zeroToTwoPi,
} from './math.js';
import { createCameraEvents } from '../camera/events.js';
import { geodesicAt } from './geodesic.js';
import { geodesicAt } from '../../geo/geodesic.js';
const DEFAULT_FOV = Math.PI / 3;
const MOVE_END_WAIT_MS = 500;
-86
View File
@@ -1,86 +0,0 @@
/**
* @module render/stub/geodesic
* @description The point a fraction of the way along the WGS84 geodesic
* between two places: Vincenty's inverse formula (`geo/geodesic`), then
* the series the default renderer interpolates with, term for term, so a
* rectangle's centre matches its to floating-point noise.
*/
import { deltaLambda, geodesicInverse as inverse } from '../../geo/geodesic.js';
import { WGS84 } from './math.js';
const A = WGS84.radii.x;
const B = WGS84.radii.z;
const F = (A - B) / A;
/**
* The longitude and latitude (radians) `fraction` of the way along the
* geodesic from (lon1, lat1) to (lon2, lat2).
*/
export function geodesicAt(lon1, lat1, lon2, lat2, fraction) {
const { distance, startHeading, uSquared } = inverse(lon1, lat1, lon2, lat2);
const cosH = Math.cos(startHeading);
const sinH = Math.sin(startHeading);
const tanU = (1 - F) * Math.tan(lat1);
const cosU = 1 / Math.sqrt(1 + tanU * tanU);
const sinU = cosU * tanU;
const sigma1 = Math.atan2(tanU, cosH);
const sineAlpha = cosU * sinH;
const cos2Alpha = 1 - sineAlpha * sineAlpha;
const cosAlpha = Math.sqrt(cos2Alpha);
const u2 = uSquared / 4;
const u4 = u2 * u2;
const u6 = u4 * u2;
const u8 = u4 * u4;
const a0 = 1 + u2 - (3 * u4) / 4 + (5 * u6) / 4 - (175 * u8) / 64;
const a1 = 1 - u2 + (15 * u4) / 8 - (35 * u6) / 8;
const a2 = 1 - 3 * u2 + (35 * u4) / 4;
const a3 = 1 - 5 * u2;
const distanceRatio =
a0 * sigma1 -
(a1 * Math.sin(2 * sigma1) * u2) / 2 -
(a2 * Math.sin(4 * sigma1) * u4) / 16 -
(a3 * Math.sin(6 * sigma1) * u6) / 48 -
(Math.sin(8 * sigma1) * 5 * u8) / 512;
const s = distanceRatio + (distance * fraction) / B;
const cos2S = Math.cos(2 * s);
const cos4S = Math.cos(4 * s);
const cos6S = Math.cos(6 * s);
const sin2S = Math.sin(2 * s);
const sin4S = Math.sin(4 * s);
const sin6S = Math.sin(6 * s);
const sin8S = Math.sin(8 * s);
const s2 = s * s;
const s3 = s * s2;
let sigma =
(2 * s3 * u8 * cos2S) / 3 +
s *
(1 -
u2 +
(7 * u4) / 4 -
(15 * u6) / 4 +
(579 * u8) / 64 -
(u4 - (15 * u6) / 4 + (187 * u8) / 16) * cos2S -
((5 * u6) / 4 - (115 * u8) / 16) * cos4S -
(29 * u8 * cos6S) / 16) +
(u2 / 2 - u4 + (71 * u6) / 32 - (85 * u8) / 16) * sin2S +
((5 * u4) / 16 - (5 * u6) / 4 + (383 * u8) / 96) * sin4S -
s2 * ((u6 - (11 * u8) / 2) * sin2S + (5 * u8 * sin4S) / 2) +
((29 * u6) / 96 - (29 * u8) / 16) * sin6S +
(539 * u8 * sin8S) / 1536;
const theta = Math.asin(Math.sin(sigma) * cosAlpha);
const lat = Math.atan((A / B) * Math.tan(theta));
sigma -= sigma1;
const cos2Sm = Math.cos(2 * sigma1 + sigma);
const sinSigma = Math.sin(sigma);
const cosSigma = Math.cos(sigma);
const lambda = Math.atan2(
sinSigma * sinH,
cosU * cosSigma - sinU * sinSigma * cosH,
);
const l =
lambda -
deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm);
return { lon: lon1 + l, lat };
}