Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1b764ca31 | ||
|
|
6fee084d77 | ||
|
|
2965706b7e | ||
|
|
243aa3bbce | ||
|
|
7983a6875f | ||
|
|
6507da1610 | ||
|
|
a47b5d3d92 | ||
|
|
bd90b4a21f | ||
|
|
d0344d5d17 | ||
|
|
deb840e9bd | ||
|
|
d2b0cc5008 | ||
|
|
822c69944c | ||
|
|
f2608f1172 |
@@ -1,4 +1,6 @@
|
||||
# Editor configuration, see https://editorconfig.org
|
||||
# Source: @avalon-vanguard/config. EditorConfig cannot extend a file, so each repo commits a copy:
|
||||
# cp node_modules/@avalon-vanguard/config/.editorconfig .editorconfig
|
||||
root = true
|
||||
|
||||
[*]
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
name: CI
|
||||
|
||||
# Gitea port of .github/workflows/ci.yml, through the organisation's shared workflow
|
||||
# (avalon-vanguard/ci, node.yml): lint, typecheck, unit tests, production build, then the
|
||||
# Playwright suite. Same triggers: pull requests and the branches they merge into, plus manual
|
||||
# dispatch.
|
||||
#
|
||||
# A .gitea/workflows directory makes Gitea ignore .github/workflows, so pages.yml,
|
||||
# data-refresh.yml and junie-review.yml now run on GitHub only, until they are ported.
|
||||
on:
|
||||
push:
|
||||
branches: [main, develop]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
# A second push to the same branch makes the first run's answer irrelevant.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
uses: avalon-vanguard/ci/.gitea/workflows/node.yml@v1
|
||||
# Pas d'e2e pour l'instant : la carte 3D rendue en logiciel par Chromium, sur ng serve,
|
||||
# dépasse le runner du VPS (17 tests, 7 en échec par délai dépassé en 16,8 min). À
|
||||
# remettre (e2e: true) une fois le runner capable de les passer.
|
||||
secrets: inherit
|
||||
@@ -0,0 +1 @@
|
||||
@avalon-vanguard:registry=https://git.avalonvanguard.com/api/packages/avalon-vanguard/npm/
|
||||
@@ -1,12 +1 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"singleQuote": true,
|
||||
"overrides": [
|
||||
{
|
||||
"files": "*.html",
|
||||
"options": {
|
||||
"parser": "angular"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
"@avalon-vanguard/config/prettier/angular"
|
||||
|
||||
@@ -53,19 +53,9 @@ in it is measured and what is not.
|
||||

|
||||
|
||||
**System view** — selecting a star flies the camera continuously into its system rather than
|
||||
cutting to a new scene. The Sun gets the real solar-system bodies, moving on JPL's mean orbital
|
||||
elements — Standish's for the planets, JPL SSD's satellite table for the moons, the Small-Body
|
||||
Database for Ceres, Eris, Haumea and Makemake — and turned by the IAU's rotational elements
|
||||
(Eris, Haumea, Makemake and Nereid, which have none, at their measured days about their orbit
|
||||
normals, and Hyperion, which tumbles, not at all), Earth by the IERS Earth Rotation Angle; a
|
||||
tidally locked moon's prime meridian turns at its JPL mean motion, and its pole's terms that turn
|
||||
within 5 per cent of a multiple of its node's rate at that multiple of its JPL node rate, both
|
||||
re-phased to the IAU's values on 2025-01-01 (the Moon's and Phobos's are left as the IAU has them,
|
||||
and so are the circles Ariel's, Umbriel's, Titania's and Oberon's poles go round on, at rates none
|
||||
of their nodes has), and Iapetus's pole follows its orbit normal
|
||||
(`lockedToOrbit`), so each keeps its face to its planet from AD 1 to 3000; other
|
||||
cutting to a new scene. The Sun gets the real solar-system bodies from JPL Horizons; other
|
||||
stars get their confirmed exoplanets. Orbits are drawn as ellipses and bodies are propagated
|
||||
along them by a Kepler solver to the date on the map's clock. Under them, a dashed grid marks out
|
||||
along them by a Kepler solver against the current epoch. Under them, a dashed grid marks out
|
||||
round distances in AU — 5 AU rings for the solar system, 0.01 AU rings for TRAPPIST-1 — with a
|
||||
drop line from each body, so eccentricity and inclination read against a circular reference
|
||||
instead of having to be inferred from a shape in space. The camera frames that grid rather than
|
||||
@@ -119,8 +109,7 @@ its own readout, so a stale image is visible as one.
|
||||
both backends. Their size is angular rather than world-space — real stars are unresolvable
|
||||
point sources, so apparent size should follow brightness, not distance.
|
||||
- **One reference frame, from three sources.** HYG gives star positions in equatorial J2000.
|
||||
JPL gives the planets' orbital elements against the ecliptic, tilted 23.4° away, and the moons'
|
||||
against the ecliptic (the Moon), a Laplace plane, or their planet's equator (Uranus's and Pluto's). The Exoplanet
|
||||
JPL Horizons reports orbital elements against the ecliptic, tilted 23.4° away. The Exoplanet
|
||||
Archive measures inclination from the *plane of the sky* — perpendicular to our line of sight
|
||||
to each host star, which is why transiting planets cluster at 90°. Each set of elements is
|
||||
rotated from its own reference plane into the scene's equatorial frame, so a direction means
|
||||
@@ -145,11 +134,9 @@ its own readout, so a stale image is visible as one.
|
||||
|
||||
### On surfaces that were never photographed
|
||||
|
||||
Twenty-eight bodies here are wrapped in real photography: the Sun, the eight planets and the Moon,
|
||||
and eighteen moons and dwarf planets in mission mosaics, grey where no probe has seen them
|
||||
(`src/assets/textures/README.md`). Everything else is not, and no exoplanet ever will be on
|
||||
current instruments: none has had its surface imaged. The five large moons of Uranus and a few
|
||||
small bodies have no map in this asset set either.
|
||||
Fifteen bodies here have a real photograph. Everything else does not, and never will on current
|
||||
instruments: no exoplanet's surface has ever been imaged, and a few of the solar system's own
|
||||
moons have no usable map in this asset set either.
|
||||
|
||||
Those bodies get a surface reasoned from what *has* been measured, in a chain that is worth
|
||||
following because every link is standard:
|
||||
@@ -213,7 +200,7 @@ re-runs are cheap and offline-friendly; set `ETL_FORCE_REFRESH=1` to bypass the
|
||||
| Script | Source | Output |
|
||||
| --- | --- | --- |
|
||||
| `fetchStars.ts` | HYG database, plus any other positional catalogue wired in (see below) | `stars.bin`, `stars-meta.bin`, `stars-index.json` |
|
||||
| `fetchSolarSystem.ts` | JPL SSD mean elements (Standish's planets, the satellite table), the Small-Body Database, NAIF's PCK, JPL Horizons | `bodies.json` |
|
||||
| `fetchSolarSystem.ts` | JPL Horizons / SSD | `bodies.json` |
|
||||
| `fetchExoplanets.ts` | NASA Exoplanet Archive (TAP) | `exoplanets.json` |
|
||||
| `fetchDeepSky.ts` | OpenNGC | `deepsky.json` |
|
||||
|
||||
@@ -337,7 +324,7 @@ plugin's own files are kept so it can be listed from a marketplace of its own la
|
||||
## Data credits
|
||||
|
||||
Star catalogue: [HYG database](https://github.com/astronexus/HYG-Database) (Hipparcos, Yale
|
||||
Bright Star, Gliese) — 68 388 stars within 250 pc. Solar-system orbits: JPL approximate planetary mean elements (Standish), JPL SSD satellite mean elements and the JPL Small-Body Database; rotation: the IAU WGCCRE 2015 report via NAIF's pck00011, with a locked moon's W and its pole's terms within 5 per cent of its node's rate re-rated to its JPL mean elements (but the Moon's and Phobos's) and Iapetus's pole carried round its orbit normal, and for Earth the IERS Conventions 2010; physical data, and the positions the orbits are checked against: NASA/JPL Horizons. Exoplanets: NASA Exoplanet
|
||||
Bright Star, Gliese) — 68 388 stars within 250 pc. Solar-system ephemerides: NASA/JPL Horizons. Exoplanets: NASA Exoplanet
|
||||
Archive. Deep-sky objects: [OpenNGC](https://github.com/mattiaverga/OpenNGC). Body and skybox
|
||||
imagery: NASA/JPL/USGS public domain and Solar System Scope (CC BY 4.0) — per-file provenance
|
||||
is recorded in `src/assets/textures/README.md`.
|
||||
is recorded in `src/app/shared/rendering/texture-catalog.ts`.
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// @ts-check
|
||||
const { defineConfig } = require('eslint/config');
|
||||
const avalonBase = require('@avalon-vanguard/config/eslint');
|
||||
const avalonAngular = require('@avalon-vanguard/config/eslint/angular');
|
||||
|
||||
module.exports = defineConfig([
|
||||
{
|
||||
// Build, test and Playwright output (see .gitignore): ESLint does not read .gitignore.
|
||||
ignores: [
|
||||
'dist/**',
|
||||
'coverage/**',
|
||||
'.angular/**',
|
||||
'node_modules/**',
|
||||
'out-tsc/**',
|
||||
'tools/etl/.cache/**',
|
||||
'e2e/test-output/**',
|
||||
'test-results/**',
|
||||
'playwright-report/**',
|
||||
'blob-report/**',
|
||||
],
|
||||
},
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
extends: [avalonBase, avalonAngular.typescript],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{ type: 'attribute', prefix: 'app', style: 'camelCase' },
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{ type: 'element', prefix: 'app', style: 'kebab-case' },
|
||||
],
|
||||
},
|
||||
},
|
||||
avalonAngular.templates,
|
||||
]);
|
||||
@@ -7,11 +7,13 @@
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test",
|
||||
"lint": "eslint .",
|
||||
"etl": "tsx tools/etl/build.ts",
|
||||
"etl:typecheck": "tsc -p tools/etl/tsconfig.json --noEmit",
|
||||
"e2e": "playwright test",
|
||||
"e2e:typecheck": "tsc -p e2e/tsconfig.json --noEmit",
|
||||
"worker:typecheck": "tsc -p tsconfig.worker.json --noEmit"
|
||||
"worker:typecheck": "tsc -p tsconfig.worker.json --noEmit",
|
||||
"typecheck": "npm run etl:typecheck && npm run e2e:typecheck && npm run worker:typecheck"
|
||||
},
|
||||
"private": true,
|
||||
"packageManager": "npm@11.12.1",
|
||||
@@ -33,16 +35,21 @@
|
||||
"@angular/build": "^22.0.6",
|
||||
"@angular/cli": "^22.0.6",
|
||||
"@angular/compiler-cli": "^22.0.0",
|
||||
"@avalon-vanguard/config": "^1.0.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@tailwindcss/postcss": "^4.3.2",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/three": "^0.185.1",
|
||||
"angular-eslint": "^22.5.0",
|
||||
"eslint": "^10.10.0",
|
||||
"jsdom": "^28.0.0",
|
||||
"postcss": "^8.5.19",
|
||||
"prettier": "^3.8.1",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"tsx": "^4.23.1",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.70.0",
|
||||
"vitest": "^4.0.8"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"local>avalon-vanguard/renovate-config",
|
||||
"local>avalon-vanguard/renovate-config:angular"
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { NgZone } from '@angular/core';
|
||||
import { Injector, NgZone, runInInjectionContext } from '@angular/core';
|
||||
import * as THREE from 'three/webgpu';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
@@ -10,7 +10,8 @@ import { EngineService } from './engine.service';
|
||||
* arithmetic that keeps them showing the same thing.
|
||||
*/
|
||||
function engineWithCameras(): { engine: EngineService; perspective: THREE.PerspectiveCamera; orthographic: THREE.OrthographicCamera } {
|
||||
const engine = new EngineService({ runOutsideAngular: (fn: () => unknown) => fn() } as unknown as NgZone);
|
||||
const zone = { runOutsideAngular: (fn: () => unknown) => fn() } as unknown as NgZone;
|
||||
const engine = runInInjectionContext(Injector.create({ providers: [{ provide: NgZone, useValue: zone }] }), () => new EngineService());
|
||||
const perspective = new THREE.PerspectiveCamera(50, 16 / 9, 0.1, 1000);
|
||||
const orthographic = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 1000);
|
||||
// The two cameras are private, because nothing outside should choose between them by hand.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, NgZone } from '@angular/core';
|
||||
import { inject, Injectable, NgZone } from '@angular/core';
|
||||
import * as THREE from 'three/webgpu';
|
||||
|
||||
export type EngineTickCallback = (deltaSeconds: number, elapsedSeconds: number) => void;
|
||||
@@ -20,6 +20,7 @@ export type SceneCamera = THREE.PerspectiveCamera | THREE.OrthographicCamera;
|
||||
*/
|
||||
@Injectable()
|
||||
export class EngineService {
|
||||
private readonly ngZone = inject(NgZone);
|
||||
private readonly clock = new THREE.Clock(false);
|
||||
private readonly tickCallbacks = new Set<EngineTickCallback>();
|
||||
|
||||
@@ -36,8 +37,6 @@ export class EngineService {
|
||||
private projection: Projection = 'perspective';
|
||||
private running = false;
|
||||
|
||||
constructor(private readonly ngZone: NgZone) {}
|
||||
|
||||
get isInitialized(): boolean {
|
||||
return !!this.renderer;
|
||||
}
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
import * as THREE from 'three/webgpu';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { DataLoaderService, StarField } from '../../core/data/data-loader.service';
|
||||
import { EngineService, EngineTickCallback } from '../../core/engine/engine.service';
|
||||
import { BodyRecord } from '../../shared/models/body.model';
|
||||
import { ExoplanetRecord } from '../../shared/models/exoplanet.model';
|
||||
import { StarRecord } from '../../shared/models/star.model';
|
||||
import { bodyPageView } from '../../shared/rendering/body-orientation';
|
||||
import { TimeStore } from '../../shared/state/time.store';
|
||||
import { BodyDetailSceneComponent } from './body-detail-scene.component';
|
||||
|
||||
// jsdom has no ResizeObserver; the page only uses it to follow real layout changes.
|
||||
(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver ??= class {
|
||||
observe(): void {}
|
||||
disconnect(): void {}
|
||||
};
|
||||
|
||||
const SUN: StarRecord = { id: 0, name: 'Sol', x: 0, y: 0, z: 0, magnitude: -26.7, spectralType: 'G2V', colorIndex: 0.656 };
|
||||
|
||||
// Earth and Saturn as bodies.json carries them: Standish's elements and the IAU's.
|
||||
const EARTH: BodyRecord = {
|
||||
id: 'earth', systemStarId: 0, name: 'Earth', kind: 'planet', radiusKm: 6371, orbitSource: 'test',
|
||||
orbit: {semiMajorAxisAu: 1.00000018, eccentricity: 0.01673163, inclinationDeg: -0.00054346, longitudeOfAscendingNodeDeg: -5.11260389, argumentOfPeriapsisDeg: 108.04266274, meanAnomalyAtEpochDeg: -2.4631431299999917, epochJd: 2451545},
|
||||
rates: {meanMotionDegPerDay: 0.9856091187759068, longitudeOfAscendingNodeDegPerDay: -0.000006604751813826146, argumentOfPeriapsisDegPerDay: 0.000015309819575633124},
|
||||
rotationalElements: {poleRaDeg: [0, -0.641, 0], poleDecDeg: [90, -0.557, 0], primeMeridianDeg: [190.147, 360.9856235, 0]}
|
||||
};
|
||||
const SATURN: BodyRecord = {
|
||||
id: 'saturn', systemStarId: 0, name: 'Saturn', kind: 'planet', radiusKm: 58232, orbitSource: 'test',
|
||||
orbit: {semiMajorAxisAu: 9.54149883, eccentricity: 0.05550825, inclinationDeg: 2.49424102, longitudeOfAscendingNodeDeg: 113.63998702, argumentOfPeriapsisDeg: -20.778626390000014, meanAnomalyAtEpochDeg: -42.78564733999999, epochJd: 2451545},
|
||||
rates: {meanMotionDegPerDay: 0.033459683702669406, longitudeOfAscendingNodeDegPerDay: -0.000006848734291581108, argumentOfPeriapsisDegPerDay: 0.000021682266940451745},
|
||||
rotationalElements: {poleRaDeg: [40.589, -0.036, 0], poleDecDeg: [83.537, -0.004, 0], primeMeridianDeg: [38.9, 810.7939024, 0]}
|
||||
};
|
||||
// Eris and Hyperion as they are shipped for this page's purposes: no IAU model, so their pages keep
|
||||
// their own light; Eris's day is measured, and Hyperion tumbles and has none.
|
||||
const ERIS: BodyRecord = { ...EARTH, id: 'eris', name: 'Eris', kind: 'dwarf', radiusKm: 1163, rotationalElements: undefined, rotationPeriodHours: 378.504 };
|
||||
const HYPERION: BodyRecord = { ...ERIS, id: 'hyperion', name: 'Hyperion', kind: 'moon', radiusKm: 135, parentBodyId: 'saturn', rotationPeriodHours: undefined };
|
||||
// Mercury as shipped, but its 0.01-degree libration: its Sun is never 0.034 degrees off its equator.
|
||||
const MERCURY: BodyRecord = {
|
||||
id: 'mercury', systemStarId: 0, name: 'Mercury', kind: 'planet', radiusKm: 2439.4, orbitSource: 'test',
|
||||
orbit: {semiMajorAxisAu: 0.38709843, eccentricity: 0.20563661, inclinationDeg: 7.00559432, longitudeOfAscendingNodeDeg: 48.33961819, argumentOfPeriapsisDeg: 29.118100759999997, meanAnomalyAtEpochDeg: 174.79394829, epochJd: 2451545},
|
||||
rates: {meanMotionDegPerDay: 4.092338805372484, longitudeOfAscendingNodeDegPerDay: -0.0000033440607802874744, argumentOfPeriapsisDegPerDay: 0.000007708198494182067},
|
||||
rotationalElements: {poleRaDeg: [281.0103, -0.0328, 0], poleDecDeg: [61.4155, -0.0049, 0], primeMeridianDeg: [329.5988, 6.1385108, 0]}
|
||||
};
|
||||
const BODIES = [EARTH, SATURN, ERIS, HYPERION, MERCURY];
|
||||
// An exoplanet round the Sun's record, which is all the page needs of its host.
|
||||
const EXOPLANET: ExoplanetRecord = { id: 'x b', hostStarId: 0, hostStarName: 'Sol', name: 'X b', orbit: { semiMajorAxisAu: 0.05 } };
|
||||
|
||||
/** Stands in for the WebGPU engine: a scene, a camera, and the tick hook, driven by hand. */
|
||||
class FakeEngineService {
|
||||
private readonly scene = new THREE.Scene();
|
||||
private readonly camera = new THREE.PerspectiveCamera(50, 1, 0.1, 100);
|
||||
private readonly callbacks = new Set<EngineTickCallback>();
|
||||
|
||||
async init(): Promise<void> {}
|
||||
getScene(): THREE.Scene {
|
||||
return this.scene;
|
||||
}
|
||||
getCamera(): THREE.PerspectiveCamera {
|
||||
return this.camera;
|
||||
}
|
||||
onTick(callback: EngineTickCallback): () => void {
|
||||
this.callbacks.add(callback);
|
||||
return () => this.callbacks.delete(callback);
|
||||
}
|
||||
start(): void {}
|
||||
resize(): void {}
|
||||
dispose(): void {}
|
||||
tick(deltaSeconds: number): void {
|
||||
for (const callback of this.callbacks) {
|
||||
callback(deltaSeconds, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FakeDataLoaderService {
|
||||
loadStars(): Promise<StarField> {
|
||||
return Promise.resolve({ stars: [SUN], positions: new Float32Array([0, 0, 0]) });
|
||||
}
|
||||
loadBodies(): Promise<BodyRecord[]> {
|
||||
return Promise.resolve(BODIES);
|
||||
}
|
||||
loadExoplanets(): Promise<ExoplanetRecord[]> {
|
||||
return Promise.resolve([EXOPLANET]);
|
||||
}
|
||||
}
|
||||
|
||||
async function flushAsync(turns = 8): Promise<void> {
|
||||
for (let i = 0; i < turns; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
describe('BodyDetailSceneComponent', () => {
|
||||
let engine: FakeEngineService;
|
||||
let page: { planet: THREE.Mesh; ring?: THREE.Mesh; sunLight: THREE.DirectionalLight };
|
||||
let time: TimeStore;
|
||||
let route: BehaviorSubject<ReturnType<typeof convertToParamMap>>;
|
||||
|
||||
let fixture: ComponentFixture<BodyDetailSceneComponent>;
|
||||
|
||||
/** Opens a body's page at a date; `whole` keeps the page's own template, dock and panel included. */
|
||||
async function open(id: string, date = '2025-06-01T12:00Z', whole = false): Promise<void> {
|
||||
engine = new FakeEngineService();
|
||||
route = new BehaviorSubject(convertToParamMap({ id }));
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BodyDetailSceneComponent],
|
||||
providers: [
|
||||
{ provide: DataLoaderService, useClass: FakeDataLoaderService },
|
||||
{ provide: ActivatedRoute, useValue: { paramMap: route } },
|
||||
{ provide: Router, useValue: { navigate: vi.fn().mockResolvedValue(true) } }
|
||||
]
|
||||
}).overrideComponent(BodyDetailSceneComponent, {
|
||||
// The scene alone, unless asked: the info panel and the dock are tested on their own.
|
||||
set: whole ? { providers: [{ provide: EngineService, useValue: engine }] } : { providers: [{ provide: EngineService, useValue: engine }], imports: [], template: '<canvas #canvas></canvas>' }
|
||||
});
|
||||
time = TestBed.inject(TimeStore);
|
||||
time.setRate(0);
|
||||
time.setDate(new Date(date));
|
||||
fixture = TestBed.createComponent(BodyDetailSceneComponent);
|
||||
fixture.detectChanges();
|
||||
await flushAsync();
|
||||
page = fixture.componentInstance as unknown as typeof page;
|
||||
engine.tick(0.016);
|
||||
}
|
||||
|
||||
beforeEach(() => TestBed.resetTestingModule());
|
||||
|
||||
it('lays Saturn’s rings in its equator on the page, where audit #47 found them 17 degrees off it', async () => {
|
||||
await open('saturn');
|
||||
const ring = page.ring!;
|
||||
ring.updateWorldMatrix(true, false);
|
||||
const normal = new THREE.Vector3().fromBufferAttribute(ring.geometry.attributes['normal'], 0).transformDirection(ring.matrixWorld);
|
||||
const pole = new THREE.Vector3(0, 1, 0).applyQuaternion(page.planet.quaternion);
|
||||
expect(normal.angleTo(pole)).toBeLessThan(1e-6);
|
||||
});
|
||||
|
||||
it('turns Earth on its page as it stands at the map’s date, under its real Sun', async () => {
|
||||
await open('earth');
|
||||
const planet = new THREE.Quaternion();
|
||||
const sun = new THREE.Vector3();
|
||||
expect(bodyPageView(EARTH, BODIES, time.julianDate(), Math.atan2(4, 5), planet, sun)).toBe(true);
|
||||
expect(page.planet.quaternion.angleTo(planet)).toBeLessThan(1e-9);
|
||||
expect(page.sunLight.position.clone().normalize().angleTo(sun)).toBeLessThan(1e-9);
|
||||
});
|
||||
|
||||
it('follows the clock once the page is open, as it runs or is set', async () => {
|
||||
await open('earth');
|
||||
time.setDate(new Date('2025-06-01T18:00Z'));
|
||||
engine.tick(0.016);
|
||||
const planet = new THREE.Quaternion();
|
||||
expect(bodyPageView(EARTH, BODIES, time.julianDate(), Math.atan2(4, 5), planet, new THREE.Vector3())).toBe(true);
|
||||
// Six hours on, a quarter turn of Earth: a page frozen at its first frame is 90 degrees out.
|
||||
expect(page.planet.quaternion.angleTo(planet)).toBeLessThan(1e-9);
|
||||
});
|
||||
|
||||
it('puts the page’s own light back when the next body shown has no IAU model to place its Sun', async () => {
|
||||
await open('earth');
|
||||
expect(page.sunLight.position.distanceTo(new THREE.Vector3(4, 3, 5))).toBeGreaterThan(0.1);
|
||||
route.next(convertToParamMap({ id: 'eris' }));
|
||||
await flushAsync();
|
||||
engine.tick(0.016);
|
||||
expect(page.sunLight.position.distanceTo(new THREE.Vector3(4, 3, 5))).toBeLessThan(1e-9);
|
||||
});
|
||||
|
||||
it('puts the sphere back at rest when the next body shown does not turn: Hyperion after Earth', async () => {
|
||||
await open('earth');
|
||||
expect(page.planet.quaternion.angleTo(new THREE.Quaternion())).toBeGreaterThan(0.1);
|
||||
route.next(convertToParamMap({ id: 'hyperion' }));
|
||||
await flushAsync();
|
||||
engine.tick(0.016);
|
||||
engine.tick(0.016);
|
||||
expect(page.planet.quaternion.angleTo(new THREE.Quaternion())).toBeLessThan(1e-9);
|
||||
});
|
||||
|
||||
it('turns a body whose day is measured but not its pole at that day on the map’s clock: Eris a sixth of a turn in 63.084 hours', async () => {
|
||||
await open('eris');
|
||||
const start = page.planet.rotation.y;
|
||||
// The clock stands (the page is opened at rate 0): so does Eris, where it used to turn for show.
|
||||
engine.tick(1);
|
||||
expect(page.planet.rotation.y).toBe(start);
|
||||
time.setDate(new Date(Date.parse('2025-06-01T12:00Z') + (378.504 / 6) * 3600000));
|
||||
engine.tick(0.016);
|
||||
const turned = (((page.planet.rotation.y - start) / (2 * Math.PI)) % 1 + 1) % 1;
|
||||
expect(turned).toBeCloseTo(1 / 6, 6);
|
||||
// Pole up, as the system view turns it about its orbit's normal.
|
||||
expect(new THREE.Vector3(0, 1, 0).applyQuaternion(page.planet.quaternion).y).toBeCloseTo(1, 12);
|
||||
});
|
||||
|
||||
it('turns an exoplanet slowly for show, clock or no clock: the catalogue carries no day for it', async () => {
|
||||
await open('x b');
|
||||
const start = page.planet.rotation.y;
|
||||
// The clock stands; a second of the page's own time is 0.08 radians.
|
||||
engine.tick(1);
|
||||
expect(page.planet.rotation.y - start).toBeCloseTo(0.08, 12);
|
||||
});
|
||||
|
||||
it('says on its dock the date the body is drawn for, and nothing at the present, and offers the clock', async () => {
|
||||
await open('saturn', '2032-06-01T12:00Z', true);
|
||||
fixture.detectChanges();
|
||||
const host = fixture.nativeElement as HTMLElement;
|
||||
expect(host.querySelector('[data-testid="hud-date"]')?.textContent).toContain('2032-06-01');
|
||||
expect([...host.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent?.trim())).toContain('Clock');
|
||||
time.reset();
|
||||
engine.tick(0.016);
|
||||
fixture.detectChanges();
|
||||
expect(host.querySelector('[data-testid="hud-date"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('opens Saturn on the face of its rings the Sun lights: the south, from 2025 to 2039', async () => {
|
||||
await open('saturn', '2032-06-01T12:00Z');
|
||||
const camera = engine.getCamera();
|
||||
// The Sun 26.7 degrees south of the rings, and the camera with it rather than 11 degrees north.
|
||||
expect(page.sunLight.position.y).toBeLessThan(0);
|
||||
expect(camera.position.y).toBeLessThan(0);
|
||||
|
||||
route.next(convertToParamMap({ id: 'earth' }));
|
||||
await flushAsync();
|
||||
engine.tick(0.016);
|
||||
// June: Earth's Sun is in the north, and so is the camera again.
|
||||
expect(page.sunLight.position.y).toBeGreaterThan(0);
|
||||
expect(camera.position.y).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('follows the Sun across Saturn’s equator when the clock is set past the 2039 equinox, and aims at Saturn in that same frame', async () => {
|
||||
await open('saturn', '2032-06-01T12:00Z');
|
||||
const camera = engine.getCamera();
|
||||
expect(camera.position.y).toBeLessThan(0);
|
||||
// What the page's own Clock tab does: 2045, the Sun 25.7 degrees north of the rings.
|
||||
time.setDate(new Date('2045-06-01T12:00Z'));
|
||||
engine.tick(0.016);
|
||||
expect(page.sunLight.position.y).toBeGreaterThan(0);
|
||||
expect(camera.position.y).toBeGreaterThan(0);
|
||||
// The frame drawn straight after the move: aimed from where the camera was, it had Saturn 22.6
|
||||
// degrees off the middle of the view.
|
||||
const toSaturn = new THREE.Vector3().sub(camera.position);
|
||||
expect(camera.getWorldDirection(new THREE.Vector3()).angleTo(toSaturn)).toBeLessThan(1e-9);
|
||||
});
|
||||
|
||||
it('opens the next body shown on its own Sun’s side, wherever the reader left the camera: Earth after Saturn in December', async () => {
|
||||
await open('saturn', '2032-12-01T12:00Z');
|
||||
const camera = engine.getCamera();
|
||||
expect(camera.position.y).toBeLessThan(0);
|
||||
// Taken north by the reader, over Saturn's unlit ring face.
|
||||
camera.position.y = 0.6;
|
||||
engine.tick(0.016);
|
||||
expect(camera.position.y).toBeGreaterThan(0);
|
||||
|
||||
route.next(convertToParamMap({ id: 'earth' }));
|
||||
await flushAsync();
|
||||
engine.tick(0.016);
|
||||
// December: Earth's Sun is south, as Saturn's was, so only the side chosen afresh moves the camera.
|
||||
expect(page.sunLight.position.y).toBeLessThan(0);
|
||||
expect(camera.position.y).toBeLessThan(0);
|
||||
});
|
||||
|
||||
it('leaves the camera on its side while the Sun only grazes the equator: Mercury through two crossings', async () => {
|
||||
// The Sun is south of Mercury's equator on 2026-10-20, north from about 1 November, and south
|
||||
// again from about 6 December, never more than 0.034 degrees either side.
|
||||
await open('mercury', '2026-10-20T00:00Z');
|
||||
const camera = engine.getCamera();
|
||||
expect(page.sunLight.position.y).toBeLessThan(0);
|
||||
expect(camera.position.y).toBeLessThan(0);
|
||||
const sunSides = new Set<number>();
|
||||
for (let day = 1; day <= 60; day++) {
|
||||
time.setDate(new Date(Date.parse('2026-10-20T00:00Z') + day * 86400000));
|
||||
engine.tick(0.016);
|
||||
sunSides.add(Math.sign(page.sunLight.position.y));
|
||||
expect(camera.position.y).toBeLessThan(0);
|
||||
}
|
||||
expect([...sunSides].sort()).toEqual([-1, 1]);
|
||||
});
|
||||
|
||||
it('leaves the camera where the reader orbits it while the Sun stays on one side', async () => {
|
||||
await open('saturn', '2032-06-01T12:00Z');
|
||||
const camera = engine.getCamera();
|
||||
// Taken over the rings, to their unlit face, on purpose.
|
||||
camera.position.y = 0.6;
|
||||
engine.tick(0.016);
|
||||
expect(camera.position.y).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AfterViewInit, Component, ElementRef, OnDestroy, signal, viewChild } from '@angular/core';
|
||||
import { AfterViewInit, Component, ElementRef, inject, OnDestroy, signal, viewChild } from '@angular/core';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { Subscription } from 'rxjs';
|
||||
import * as THREE from 'three/webgpu';
|
||||
@@ -6,16 +6,14 @@ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
||||
|
||||
import { DataLoaderService } from '../../core/data/data-loader.service';
|
||||
import { EngineService } from '../../core/engine/engine.service';
|
||||
import { bodyPageView } from '../../shared/rendering/body-orientation';
|
||||
import { planetTexture } from '../../shared/rendering/procedural-planet-texture';
|
||||
import { applyMilkyWaySkybox, createGlowSprite } from '../../shared/rendering/skybox';
|
||||
import { atmosphereColorFor, bodyTexturePath, loadCachedTexture, MILKY_WAY_SKYBOX_PATH, saturnRing } from '../../shared/rendering/texture-catalog';
|
||||
import { atmosphereColorFor, bodyTexturePath, loadCachedTexture, MILKY_WAY_SKYBOX_PATH, SATURN_RING_TEXTURE_PATH } from '../../shared/rendering/texture-catalog';
|
||||
import { BodyRecord } from '../../shared/models/body.model';
|
||||
import { ExoplanetRecord } from '../../shared/models/exoplanet.model';
|
||||
import { StarRecord } from '../../shared/models/star.model';
|
||||
import { Bookmark } from '../../shared/state/bookmarks.store';
|
||||
import { NavigationStore } from '../../shared/state/navigation.store';
|
||||
import { TimeStore } from '../../shared/state/time.store';
|
||||
import { ChevronIconComponent } from '../../shared/ui/chevron-icon.component';
|
||||
import { HudDockComponent } from '../hud/hud-dock.component';
|
||||
import { BodyDetailViewModel } from './body-detail.model';
|
||||
@@ -26,18 +24,6 @@ import { InfoPanelComponent } from './info-panel.component';
|
||||
const GAS_GIANT_IDS = new Set(['jupiter', 'saturn', 'uranus', 'neptune']);
|
||||
/** The body is drawn at unit radius here, so the halo's extent is its multiple directly. */
|
||||
const GLOW_SCALE = 2.6;
|
||||
/** Where the page's light stands, and the Sun with it wherever the body's real one is known. */
|
||||
const SUN_LIGHT_POSITION = new THREE.Vector3(4, 3, 5);
|
||||
/**
|
||||
* How far from the equator the Sun must stand, as the sine of its latitude, before the camera
|
||||
* follows it across: 3 degrees. The side is for Saturn's rings, lit on one face only, whose Sun
|
||||
* goes 26.7 degrees either side. Mercury's never leaves the equator by more than 0.034 degrees
|
||||
* and crosses it 8.3 times a year, which moved the camera from one side to the other every 1.45
|
||||
* seconds at a month a second, both sides lit alike; Venus's reaches 2.6 and the Moon's 1.6.
|
||||
* Earth's and Saturn's pages still follow their seasons, a week and half a year after each
|
||||
* equinox (2025-03-28 and 2039-08-03, measured).
|
||||
*/
|
||||
const SUN_SIDE_MIN_SINE = Math.sin((3 * Math.PI) / 180);
|
||||
|
||||
/**
|
||||
* Separate, focused route for inspecting a single planet/moon/exoplanet: its own scene/camera
|
||||
@@ -72,16 +58,19 @@ const SUN_SIDE_MIN_SINE = Math.sin((3 * Math.PI) / 180);
|
||||
</a>
|
||||
</div>
|
||||
}
|
||||
<!-- Search, what has been kept and the clock: there is no scene readout here, the info
|
||||
panel is the reading, and the panel's own control is what keeps this body. A solar-system
|
||||
body is drawn at the clock's date and turns at its rate, so both are shown and can be set
|
||||
here; an exoplanet, whose day the catalogue does not carry, turns for show whatever the
|
||||
clock says. -->
|
||||
<app-hud-dock [date]="date()" [clock]="true" (bookmarkChosen)="goToBookmark($event)" />
|
||||
<!-- Search and what has been kept: there is no scene readout here, the info panel is
|
||||
the reading, and the panel's own control is what keeps this body. -->
|
||||
<app-hud-dock (bookmarkChosen)="goToBookmark($event)" />
|
||||
</div>
|
||||
`
|
||||
})
|
||||
export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
private readonly engine = inject(EngineService);
|
||||
private readonly dataLoader = inject(DataLoaderService);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly navigationStore = inject(NavigationStore);
|
||||
|
||||
/** A kept place, revisited from this page: a star means leaving it for the map. */
|
||||
goToBookmark(bookmark: Bookmark): void {
|
||||
if (bookmark.kind === 'star') {
|
||||
@@ -98,9 +87,6 @@ export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
private scene?: THREE.Scene;
|
||||
private planet?: THREE.Mesh;
|
||||
private planetMaterial?: THREE.MeshStandardMaterial;
|
||||
private sunLight?: THREE.DirectionalLight;
|
||||
/** The solar-system record behind the body shown, which is what can be turned by its real pole. */
|
||||
private body?: BodyRecord;
|
||||
private ring?: THREE.Mesh;
|
||||
private glow?: THREE.Sprite;
|
||||
private resizeObserver?: ResizeObserver;
|
||||
@@ -114,19 +100,6 @@ export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
|
||||
readonly viewModel = signal<BodyDetailViewModel | undefined>(undefined);
|
||||
readonly notFound = signal(false);
|
||||
/** The date the body is drawn for, as the dock's strip prints it; empty at the present. */
|
||||
readonly date = signal('');
|
||||
/** The side of the equator the Sun stood on at the last frame, 1 north or -1 south; 0 once a body is shown. */
|
||||
private sunSide = 0;
|
||||
|
||||
constructor(
|
||||
private readonly engine: EngineService,
|
||||
private readonly dataLoader: DataLoaderService,
|
||||
private readonly route: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
private readonly navigationStore: NavigationStore,
|
||||
private readonly time: TimeStore
|
||||
) {}
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
void this.bootstrap();
|
||||
@@ -192,8 +165,8 @@ export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
}
|
||||
|
||||
// Real photography wherever it exists, and a surface derived from the body's own measured
|
||||
// properties wherever it does not — which is every exoplanet, since none has had its
|
||||
// surface imaged, and the handful of moons no probe returned a usable map of.
|
||||
// properties wherever it does not — which is every exoplanet, since none has ever been
|
||||
// imaged, and the handful of moons no probe returned a usable map of.
|
||||
const realTexturePath = bodyTexturePath(viewModel.id);
|
||||
this.planetMaterial.map = realTexturePath ? loadCachedTexture(realTexturePath) : planetTexture(viewModel.appearance);
|
||||
// The texture supplies its own colour, so the base stays white rather than tinting it twice.
|
||||
@@ -201,19 +174,12 @@ export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
// A fluid envelope scatters light more evenly than a solid surface does.
|
||||
this.planetMaterial.roughness = GAS_GIANT_IDS.has(viewModel.id) || viewModel.appearance.palette.structure === 'banded' ? 0.55 : 0.85;
|
||||
this.planetMaterial.needsUpdate = true;
|
||||
// Back to the page's own light and a sphere at rest; `tick` turns both where the IAU says how.
|
||||
this.body = this.bodies.find((body) => body.id === viewModel.id);
|
||||
this.planet?.rotation.set(0, 0, 0);
|
||||
this.sunLight?.position.copy(SUN_LIGHT_POSITION);
|
||||
this.sunSide = 0;
|
||||
|
||||
this.disposeRing();
|
||||
this.disposeGlow();
|
||||
if (this.scene) {
|
||||
if (viewModel.id === 'saturn' && this.body) {
|
||||
// Flat in the page's horizontal, which is Saturn's equator: the planet is drawn pole up, at
|
||||
// unit radius. They used to reach 2.6 radii out; the outermost ring the texture draws is 2.42.
|
||||
this.ring = saturnRing(this.body.radiusKm, 1);
|
||||
if (viewModel.id === 'saturn') {
|
||||
this.ring = this.buildSaturnRing();
|
||||
this.scene.add(this.ring);
|
||||
}
|
||||
const atmosphereColor = atmosphereColorFor(viewModel.id);
|
||||
@@ -224,6 +190,37 @@ export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saturn's rings, built from a real ring-transparency map. `RingGeometry`'s default UVs wrap
|
||||
* around the angle rather than the radius, so the per-vertex U is remapped to distance from
|
||||
* center — the standard fix for sampling a radially-varying ring texture correctly.
|
||||
*/
|
||||
private buildSaturnRing(): THREE.Mesh {
|
||||
const geometry = new THREE.RingGeometry(1.4, 2.6, 128, 1);
|
||||
const position = geometry.attributes['position'];
|
||||
const uv = geometry.attributes['uv'];
|
||||
const vertex = new THREE.Vector3();
|
||||
for (let i = 0; i < position.count; i++) {
|
||||
vertex.fromBufferAttribute(position, i);
|
||||
const radialFraction = THREE.MathUtils.clamp((vertex.length() - 1.4) / (2.6 - 1.4), 0, 1);
|
||||
uv.setXY(i, radialFraction, 1);
|
||||
}
|
||||
|
||||
const ringTexture = loadCachedTexture(SATURN_RING_TEXTURE_PATH);
|
||||
const material = new THREE.MeshBasicMaterial({
|
||||
map: ringTexture,
|
||||
alphaMap: ringTexture,
|
||||
transparent: true,
|
||||
opacity: 0.85,
|
||||
side: THREE.DoubleSide,
|
||||
depthWrite: false
|
||||
});
|
||||
|
||||
const ring = new THREE.Mesh(geometry, material);
|
||||
ring.rotation.x = Math.PI / 2 - THREE.MathUtils.degToRad(17);
|
||||
return ring;
|
||||
}
|
||||
|
||||
private disposeRing(): void {
|
||||
if (!this.ring) {
|
||||
return;
|
||||
@@ -269,12 +266,11 @@ export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
this.controls.maxDistance = 12;
|
||||
|
||||
scene.add(new THREE.AmbientLight(0xffffff, 0.35));
|
||||
this.sunLight = new THREE.DirectionalLight(0xfff4e0, 1.6);
|
||||
this.sunLight.position.copy(SUN_LIGHT_POSITION);
|
||||
scene.add(this.sunLight);
|
||||
const sunLight = new THREE.DirectionalLight(0xfff4e0, 1.6);
|
||||
sunLight.position.set(4, 3, 5);
|
||||
scene.add(sunLight);
|
||||
|
||||
const geometry = new THREE.SphereGeometry(1, 64, 48);
|
||||
const viewModel = this.viewModel();
|
||||
this.planetMaterial = new THREE.MeshStandardMaterial({
|
||||
// White, always: the map that arrives a moment later carries the colour, whether it is a
|
||||
// photograph or a surface derived from the body's own measurements.
|
||||
@@ -290,46 +286,11 @@ export class BodyDetailSceneComponent implements AfterViewInit, OnDestroy {
|
||||
this.engine.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* A body the IAU gives rotational elements for is turned as it is at the map's date, under its
|
||||
* real Sun, at the rate the map's clock runs (see `bodyPageView`). Eris, Haumea, Makemake and
|
||||
* Nereid, whose day is measured but whose pole is not, turn pole up at that day on the same
|
||||
* clock, as the system view turns them; Hyperion, which tumbles, is left still, as it is there.
|
||||
* An exoplanet turns slowly for show, as the page always turned it.
|
||||
*/
|
||||
private tick(deltaSeconds: number): void {
|
||||
this.controls?.update();
|
||||
this.date.set(this.time.atNow() ? '' : this.time.date().toISOString().slice(0, 10));
|
||||
if (!this.planet || !this.sunLight) {
|
||||
return;
|
||||
}
|
||||
const sunAzimuth = Math.atan2(SUN_LIGHT_POSITION.x, SUN_LIGHT_POSITION.z);
|
||||
if (this.body && bodyPageView(this.body, this.bodies, this.time.julianDate(), sunAzimuth, this.planet.quaternion, this.sunLight.position)) {
|
||||
this.sunLight.position.multiplyScalar(SUN_LIGHT_POSITION.length());
|
||||
} else if (this.body?.rotationPeriodHours !== undefined) {
|
||||
// Counted from the orbit's epoch, as `spinFor` counts: where the meridian starts is unknown.
|
||||
const turns = ((this.time.julianDate() - this.body.orbit.epochJd) * 24) / this.body.rotationPeriodHours;
|
||||
this.planet.rotation.set(0, (turns % 1) * 2 * Math.PI, 0);
|
||||
} else if (!this.body) {
|
||||
if (this.planet) {
|
||||
this.planet.rotation.y += deltaSeconds * 0.08;
|
||||
}
|
||||
const sunLatitudeSine = this.sunLight.position.y / this.sunLight.position.length();
|
||||
const sunSide = this.sunSide !== 0 && Math.abs(sunLatitudeSine) < SUN_SIDE_MIN_SINE ? this.sunSide : sunLatitudeSine < 0 ? -1 : 1;
|
||||
if (sunSide !== this.sunSide) {
|
||||
// Above or below the equator, whichever side the Sun is on, when a body is shown and again
|
||||
// whenever the Sun is well across it (SUN_SIDE_MIN_SINE), as the clock runs or is set: held
|
||||
// above it, the page opened Saturn on the unlit face of its rings from 2025 until 2039, while
|
||||
// the Sun is south of them — the face Earth does not see either — and the Clock set to 2045
|
||||
// left it on the other one. Between crossings the camera is the reader's to orbit where they like.
|
||||
this.sunSide = sunSide;
|
||||
const camera = this.engine.getCamera();
|
||||
camera.position.y = Math.abs(camera.position.y) * sunSide;
|
||||
// Aimed again before this frame is drawn: the controls aimed it from where it was, and the
|
||||
// frame drawn from here otherwise had the body 22.6 degrees off the middle of the view.
|
||||
if (this.controls) {
|
||||
camera.lookAt(this.controls.target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private observeResize(canvas: HTMLCanvasElement): void {
|
||||
|
||||
@@ -20,8 +20,6 @@ export interface BodyDetailViewModel {
|
||||
*/
|
||||
hostStarId?: number;
|
||||
radiusKm?: number;
|
||||
/** A triaxial body's semi-axes, where `radiusKm` is the mean of them; see `BodyRecord.semiAxesKm`. */
|
||||
semiAxesKm?: readonly [number, number, number];
|
||||
massEarth?: number;
|
||||
discoveryYear?: number;
|
||||
orbit: Partial<OrbitalElements>;
|
||||
@@ -34,11 +32,10 @@ export interface BodyDetailViewModel {
|
||||
appearance: PlanetAppearance;
|
||||
/** True when a real photograph is being shown rather than the derived surface. */
|
||||
hasPhotography: boolean;
|
||||
/** An exoplanet photographed by direct imaging, as a point of light; see `ExoplanetRecord.imaged`. */
|
||||
imaged?: boolean;
|
||||
/**
|
||||
* Sidereal orbital period. For a solar-system body, 360 degrees over JPL's published mean
|
||||
* motion; for an exoplanet, the archive's period where it published one, and undefined where not.
|
||||
* Sidereal orbital period. Measured where the archive published one; otherwise derived from the
|
||||
* semi-major axis for heliocentric orbits, where the central mass is known exactly. Undefined
|
||||
* when neither applies — see `heliocentricPeriodDays`.
|
||||
*/
|
||||
orbitalPeriodDays?: number;
|
||||
/**
|
||||
@@ -47,6 +44,4 @@ export interface BodyDetailViewModel {
|
||||
* derived surface as a photograph.
|
||||
*/
|
||||
orbitalPeriodSource?: 'measured' | 'derived';
|
||||
/** Where the orbit comes from and the span it holds over; see `BodyRecord.orbitSource`. */
|
||||
orbitSource?: string;
|
||||
}
|
||||
|
||||
@@ -31,11 +31,7 @@ export interface BodyReadouts {
|
||||
export function bodyReadouts(body: BodyDetailViewModel): BodyReadouts {
|
||||
const measured: Readout[] = [];
|
||||
if (body.radiusKm !== undefined) {
|
||||
// A triaxial body is drawn as the sphere of its volume; a radius alone would hide its shape.
|
||||
measured.push({ label: body.semiAxesKm ? 'Mean radius' : 'Radius', value: formatRadiusKm(body.radiusKm) });
|
||||
}
|
||||
if (body.semiAxesKm) {
|
||||
measured.push({ label: 'Semi-axes', value: `${body.semiAxesKm.map((axis) => axis.toLocaleString('en-GB')).join(' × ')} km` });
|
||||
measured.push({ label: 'Radius', value: formatRadiusKm(body.radiusKm) });
|
||||
}
|
||||
if (body.massEarth !== undefined) {
|
||||
measured.push({ label: 'Mass', value: formatMassEarth(body.massEarth) });
|
||||
@@ -47,9 +43,7 @@ export function bodyReadouts(body: BodyDetailViewModel): BodyReadouts {
|
||||
measured.push({ label: 'Eccentricity', value: body.orbit.eccentricity.toFixed(3) });
|
||||
}
|
||||
if (body.orbit.inclinationDeg !== undefined) {
|
||||
// Its size: Standish fits Earth's as -0.00054 degrees, which is the same orbit as +0.00054 with
|
||||
// the node half a turn round, and printed as it stands read "-0.00°".
|
||||
measured.push({ label: 'Inclination', value: `${Math.abs(body.orbit.inclinationDeg).toFixed(2)}°` });
|
||||
measured.push({ label: 'Inclination', value: `${body.orbit.inclinationDeg.toFixed(2)}°` });
|
||||
}
|
||||
// The period sits under whichever heading its provenance calls for. Same number, same field —
|
||||
// a published period is an observation and a computed one is not.
|
||||
@@ -71,33 +65,18 @@ export function bodyReadouts(body: BodyDetailViewModel): BodyReadouts {
|
||||
derived.push({ label: 'Bulk density', value: formatDensity(body.appearance.bulkDensityGramsPerCm3) });
|
||||
}
|
||||
|
||||
const provenance = body.orbitSource ? `${provenanceFor(body)} Orbit: ${body.orbitSource}.` : provenanceFor(body);
|
||||
return { kindLabel: KIND_LABELS[body.kind], measured, derived, provenance };
|
||||
return { kindLabel: KIND_LABELS[body.kind], measured, derived, provenance: provenanceFor(body) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The derived surface is a reasoned illustration, and a panel of real measurements sitting next
|
||||
* to it is exactly the context in which it could be mistaken for another one.
|
||||
*
|
||||
* A moon or dwarf planet drawn this way has been imaged — Voyager 2 photographed Uranus's five
|
||||
* large moons, Proteus and Nereid, Cassini Hyperion, and Hubble sees Eris, Haumea and Makemake as
|
||||
* points — but has no global map this app can use. So have the hundred or so exoplanets the
|
||||
* archive flags as imaged, HR 8799's four among them, though only as points of light beside their
|
||||
* star — and one of them has a map, not used here: Luhman 16 b, a brown dwarf, mapped by Doppler
|
||||
* imaging (Crossfield et al. 2014, Nature 505, 654). Only the other exoplanets, known from what they
|
||||
* do to starlight, have no image at all.
|
||||
*/
|
||||
function provenanceFor(body: BodyDetailViewModel): string {
|
||||
if (body.hasPhotography) {
|
||||
return 'Surface: NASA/ESA/USGS photography.';
|
||||
}
|
||||
const why =
|
||||
body.kind !== 'exoplanet'
|
||||
? 'no global map of this world is used here'
|
||||
: body.imaged
|
||||
? 'it has been imaged only as a point of light beside its star, and no map of it is used here'
|
||||
: 'no image of this world exists';
|
||||
return body.appearance.equilibriumTemperatureK === null
|
||||
? `Surface illustrated from this body’s measured size and mass. Its host star is not in the catalogue, so no temperature could be derived. Not an observation — ${why}.`
|
||||
: `Surface illustrated from the measurements above — size, density and the temperature derived from its star’s output and its orbit. Not an observation — ${why}.`;
|
||||
? 'Surface illustrated from this body’s measured size and mass. Its host star is not in the catalogue, so no temperature could be derived. Not an observation — no image of this world exists.'
|
||||
: 'Surface illustrated from the measurements above — size, density and the temperature derived from its star’s output and its orbit. Not an observation — no image of this world exists.';
|
||||
}
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { BodyRecord, OrbitalElements } from '../../shared/models/body.model';
|
||||
import { ExoplanetRecord } from '../../shared/models/exoplanet.model';
|
||||
import { StarRecord, SUN_STAR_ID } from '../../shared/models/star.model';
|
||||
import { bodyReadouts } from './body-readouts';
|
||||
import { buildBodyViewModel } from './body-view-model';
|
||||
import { buildBodyViewModel, heliocentricPeriodDays } from './body-view-model';
|
||||
|
||||
const orbit = (overrides: Partial<OrbitalElements> = {}): OrbitalElements => ({
|
||||
semiMajorAxisAu: 1,
|
||||
@@ -38,9 +34,6 @@ const earth: BodyRecord = {
|
||||
kind: 'planet',
|
||||
radiusKm: 6371,
|
||||
orbit: orbit(),
|
||||
// Standish's mean longitude rate, 35 999.373 degrees a century.
|
||||
rates: { meanMotionDegPerDay: 35999.37306329 / 36525, longitudeOfAscendingNodeDegPerDay: 0, argumentOfPeriapsisDegPerDay: 0 },
|
||||
orbitSource: 'JPL approximate mean elements (Standish), fit for 3000 BC to AD 3000',
|
||||
};
|
||||
const luna: BodyRecord = {
|
||||
id: 'luna',
|
||||
@@ -50,74 +43,45 @@ const luna: BodyRecord = {
|
||||
radiusKm: 1737,
|
||||
parentBodyId: 'earth',
|
||||
orbit: orbit({ semiMajorAxisAu: 0.00257 }),
|
||||
// JPL SSD's sidereal mean motion for the Moon.
|
||||
rates: { meanMotionDegPerDay: 13.176358, longitudeOfAscendingNodeDegPerDay: -0.05299, argumentOfPeriapsisDegPerDay: 0.16435 },
|
||||
orbitSource: 'JPL SSD satellite mean elements, epoch 2000 Jan 1',
|
||||
};
|
||||
|
||||
describe('heliocentricPeriodDays', () => {
|
||||
it('recovers a known period from the semi-major axis alone', () => {
|
||||
// P² = a³ in these units, so Earth must come back a year.
|
||||
expect(heliocentricPeriodDays(earth)).toBeCloseTo(365.25, 1);
|
||||
});
|
||||
|
||||
it('scales as the three-halves power', () => {
|
||||
const jupiter: BodyRecord = {
|
||||
...earth,
|
||||
id: 'jupiter',
|
||||
name: 'Jupiter',
|
||||
orbit: orbit({ semiMajorAxisAu: 5.2044 }),
|
||||
};
|
||||
// Jupiter's real sidereal period is 4332.6 days.
|
||||
expect(heliocentricPeriodDays(jupiter)).toBeCloseTo(4335, -1);
|
||||
});
|
||||
|
||||
it('refuses to compute a period for a moon', () => {
|
||||
// A moon's elements are relative to its planet, whose mass is not in the catalogue — the
|
||||
// same arithmetic would be wrong by the ratio of that planet's mass to the Sun's.
|
||||
expect(heliocentricPeriodDays(luna)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildBodyViewModel', () => {
|
||||
const catalogues = { bodies: [earth, luna], exoplanets: [] as ExoplanetRecord[], stars: [sun] };
|
||||
|
||||
it('gives a planet the sidereal year its published mean motion goes round in', () => {
|
||||
it('marks a period computed from the semi-major axis as derived', () => {
|
||||
const model = buildBodyViewModel('earth', catalogues);
|
||||
expect(model?.orbitalPeriodSource).toBe('measured');
|
||||
expect(model?.orbitalPeriodDays).toBeCloseTo(365.2564, 4);
|
||||
expect(model?.orbitalPeriodSource).toBe('derived');
|
||||
expect(model?.orbitalPeriodDays).toBeCloseTo(365.25, 1);
|
||||
});
|
||||
|
||||
it('gives a moon its period too, from the same mean motion that carries it round', () => {
|
||||
// The card used to refuse, while the scene turned the Moon round the Earth all the same.
|
||||
it('leaves a moon without a period rather than inventing one', () => {
|
||||
const model = buildBodyViewModel('luna', catalogues);
|
||||
expect(model?.orbitalPeriodSource).toBe('measured');
|
||||
expect(model?.orbitalPeriodDays).toBeCloseTo(27.32166, 5);
|
||||
});
|
||||
|
||||
it('prints the size of an inclination fitted below zero, as the same orbit with its node turned half round', () => {
|
||||
const tilted: BodyRecord = { ...earth, orbit: orbit({ inclinationDeg: -0.00054346 }) };
|
||||
const model = buildBodyViewModel('earth', { ...catalogues, bodies: [tilted] })!;
|
||||
expect(bodyReadouts(model).measured.find((row) => row.label === 'Inclination')?.value).toBe('0.00°');
|
||||
});
|
||||
|
||||
it('prints the eccentricity measured for a moon whose orbit keeps an older one', () => {
|
||||
const hyperion: BodyRecord = { ...luna, id: 'hyperion', orbit: orbit({ eccentricity: 0.0232 }), measuredEccentricity: 0.105 };
|
||||
const model = buildBodyViewModel('hyperion', { ...catalogues, bodies: [earth, hyperion] })!;
|
||||
expect(bodyReadouts(model).measured.find((row) => row.label === 'Eccentricity')?.value).toBe('0.105');
|
||||
});
|
||||
|
||||
it('gives a triaxial body its semi-axes beside its mean radius, not a radius alone', () => {
|
||||
// As shipped: Haumea's shape (Ortiz et al. 2017) travels from the ETL's spec to its card.
|
||||
const shipped: BodyRecord[] = JSON.parse(readFileSync(`${process.cwd()}/src/assets/data/bodies.json`, 'utf8'));
|
||||
const haumea = shipped.find((body) => body.id === 'haumea')!;
|
||||
const measured = bodyReadouts(buildBodyViewModel('haumea', { ...catalogues, bodies: [earth, haumea] })!).measured;
|
||||
expect(measured.find((row) => row.label === 'Mean radius')?.value).toBe('798 km');
|
||||
expect(measured.find((row) => row.label === 'Semi-axes')?.value).toBe('1,161 × 852 × 513 km');
|
||||
expect(measured.find((row) => row.label === 'Radius')).toBeUndefined();
|
||||
// Every other body keeps its one radius.
|
||||
expect(bodyReadouts(buildBodyViewModel('earth', catalogues)!).measured.find((row) => row.label === 'Radius')?.value).toBe('6,371 km');
|
||||
});
|
||||
|
||||
it('says where the orbit comes from, in the card’s provenance', () => {
|
||||
expect(bodyReadouts(buildBodyViewModel('luna', catalogues)!).provenance).toContain('Orbit: JPL SSD satellite mean elements, epoch 2000 Jan 1.');
|
||||
});
|
||||
|
||||
it('says a moon without a map is illustrated, without saying it was never imaged', () => {
|
||||
// luna has no map under that id. Voyager and Cassini photographed every moon drawn this way.
|
||||
const provenance = bodyReadouts(buildBodyViewModel('luna', catalogues)!).provenance;
|
||||
expect(provenance).toContain('Not an observation — no global map of this world is used here.');
|
||||
expect(provenance).not.toContain('no image of this world exists');
|
||||
});
|
||||
|
||||
it('says an exoplanet the archive does not flag as imaged has no image', () => {
|
||||
const exoplanet: ExoplanetRecord = { id: 'x', hostStarId: SUN_STAR_ID, hostStarName: 'Sol', name: 'X b', orbit: { semiMajorAxisAu: 0.05 } };
|
||||
const model = buildBodyViewModel('x', { bodies: [], exoplanets: [exoplanet], stars: [sun] })!;
|
||||
expect(bodyReadouts(model).provenance).toContain('Not an observation — no image of this world exists.');
|
||||
});
|
||||
|
||||
it('says a directly imaged exoplanet was seen as a point of light, not that no image of it exists', () => {
|
||||
// HR 8799 b: photographed beside its star at Gemini and Keck (Marois et al. 2008).
|
||||
const exoplanet: ExoplanetRecord = { id: 'HR 8799 b', hostStarId: SUN_STAR_ID, hostStarName: 'HR 8799', name: 'HR 8799 b', imaged: true, orbit: { semiMajorAxisAu: 68 } };
|
||||
const provenance = bodyReadouts(buildBodyViewModel('HR 8799 b', { bodies: [], exoplanets: [exoplanet], stars: [sun] })!).provenance;
|
||||
expect(provenance).toContain('Not an observation — it has been imaged only as a point of light beside its star, and no map of it is used here.');
|
||||
expect(provenance).not.toContain('no image of this world exists');
|
||||
expect(model?.orbitalPeriodDays).toBeUndefined();
|
||||
expect(model?.orbitalPeriodSource).toBeUndefined();
|
||||
});
|
||||
|
||||
it('marks a published exoplanet period as measured, not derived', () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { luminositySolar } from '../../shared/astro/stellar';
|
||||
import { bodyTexturePath } from '../../shared/rendering/texture-catalog';
|
||||
import { BodyRecord } from '../../shared/models/body.model';
|
||||
import { ExoplanetRecord } from '../../shared/models/exoplanet.model';
|
||||
import { StarRecord } from '../../shared/models/star.model';
|
||||
import { StarRecord, SUN_STAR_ID } from '../../shared/models/star.model';
|
||||
import { BodyDetailViewModel } from './body-detail.model';
|
||||
|
||||
/** Everything the view model is assembled from — the three catalogues, already loaded. */
|
||||
@@ -41,10 +41,7 @@ export function buildBodyViewModel(id: string, catalogues: BodyCatalogues): Body
|
||||
const body = catalogues.bodies.find((candidate) => candidate.id === id);
|
||||
if (body) {
|
||||
const hostStar = catalogues.stars.find((star) => star.id === body.systemStarId);
|
||||
// The period the map draws, moons included: JPL's own mean motion, which is also what
|
||||
// carries the body round the scene. Europa's card had no period at all while the scene
|
||||
// turned it round Jupiter in 3.55 days.
|
||||
const periodDays = 360 / body.rates.meanMotionDegPerDay;
|
||||
const periodDays = heliocentricPeriodDays(body);
|
||||
return {
|
||||
id: body.id,
|
||||
name: body.name,
|
||||
@@ -52,13 +49,11 @@ export function buildBodyViewModel(id: string, catalogues: BodyCatalogues): Body
|
||||
hostStarName: hostStar?.name ?? 'Unknown star',
|
||||
hostStarId: body.systemStarId,
|
||||
radiusKm: body.radiusKm,
|
||||
semiAxesKm: body.semiAxesKm,
|
||||
orbit: body.measuredEccentricity === undefined ? body.orbit : { ...body.orbit, eccentricity: body.measuredEccentricity },
|
||||
orbit: body.orbit,
|
||||
appearance: appearanceForBody(body, catalogues.bodies, luminosityOf(hostStar)),
|
||||
hasPhotography: bodyTexturePath(body.id) !== undefined,
|
||||
orbitalPeriodDays: periodDays,
|
||||
orbitalPeriodSource: 'measured',
|
||||
orbitSource: body.orbitSource,
|
||||
orbitalPeriodSource: periodDays === undefined ? undefined : 'derived',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,7 +74,6 @@ export function buildBodyViewModel(id: string, catalogues: BodyCatalogues): Body
|
||||
orbit: exoplanet.orbit,
|
||||
appearance: appearanceForExoplanet(exoplanet, luminosityOf(hostStar)),
|
||||
hasPhotography: bodyTexturePath(exoplanet.id) !== undefined,
|
||||
imaged: exoplanet.imaged,
|
||||
// `periodDays` is populated for none of the shipped records, and deriving one would need the
|
||||
// host star's mass, which is equally absent. Left undefined rather than assuming a solar-mass
|
||||
// host, which would silently mis-state the period of every planet around an M dwarf.
|
||||
@@ -87,3 +81,19 @@ export function buildBodyViewModel(id: string, catalogues: BodyCatalogues): Body
|
||||
orbitalPeriodSource: exoplanet.periodDays === undefined ? undefined : 'measured',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Kepler's third law for a body orbiting the Sun: P² = a³ with P in years and a in AU, which
|
||||
* holds exactly in these units because the Sun's mass is the unit of mass.
|
||||
*
|
||||
* Only for heliocentric orbits. A moon's elements are relative to its parent planet, whose mass
|
||||
* the catalogue does not carry, so the same arithmetic there would be wrong by the ratio of the
|
||||
* planet's mass to the Sun's — a factor of a thousand for Jupiter.
|
||||
*/
|
||||
export function heliocentricPeriodDays(body: BodyRecord): number | undefined {
|
||||
if (body.parentBodyId !== undefined || body.systemStarId !== SUN_STAR_ID) {
|
||||
return undefined;
|
||||
}
|
||||
const a = body.orbit.semiMajorAxisAu;
|
||||
return a > 0 ? Math.pow(a, 1.5) * 365.25 : undefined;
|
||||
}
|
||||
|
||||
@@ -98,6 +98,8 @@ import { ReadoutSectionsComponent } from './readout-sections.component';
|
||||
export class InfoPanelComponent {
|
||||
readonly body = input.required<BodyDetailViewModel>();
|
||||
|
||||
private readonly router = inject(Router);
|
||||
|
||||
readonly bookmarks = inject(BookmarksStore);
|
||||
|
||||
private readonly articles = inject(ArticleService);
|
||||
@@ -105,7 +107,7 @@ export class InfoPanelComponent {
|
||||
readonly article = signal<Article | null>(null);
|
||||
readonly aboutState = signal<'idle' | 'loading' | 'none' | 'unavailable'>('idle');
|
||||
|
||||
constructor(private readonly router: Router) {
|
||||
constructor() {
|
||||
// The panel is reused as the route's parameter changes, so what was asked about one body
|
||||
// must not still be showing under the next one's name.
|
||||
effect(() => {
|
||||
|
||||
@@ -6,21 +6,16 @@ import { afterEach, beforeEach, describe, expect, it, MockInstance, vi } from 'v
|
||||
import { DataLoaderService, StarField } from '../../core/data/data-loader.service';
|
||||
import { EngineService, EngineTickCallback } from '../../core/engine/engine.service';
|
||||
import { BodyRecord } from '../../shared/models/body.model';
|
||||
import { GM_SUN_AU3_PER_DAY2 } from '../../shared/astro/constants';
|
||||
import { keplerRates } from '../../shared/astro/kepler';
|
||||
import { DeepSkyRecord } from '../../shared/models/deepsky.model';
|
||||
import { ExoplanetRecord } from '../../shared/models/exoplanet.model';
|
||||
import { StarRecord } from '../../shared/models/star.model';
|
||||
import { NavigationStore } from '../../shared/state/navigation.store';
|
||||
import { TimeStore } from '../../shared/state/time.store';
|
||||
import { LinkBudget } from '../../shared/astro/jump-links';
|
||||
import { HudDisplay } from '../hud/hud-dock.component';
|
||||
import { GalaxySystemSceneComponent } from './galaxy-system-scene.component';
|
||||
import { galacticNormal } from './grid-plane';
|
||||
import { JumpLinkRenderer } from './jump-link-renderer';
|
||||
import { StarFieldRenderer } from './star-field-renderer';
|
||||
import { systemFramingDistanceAu } from './system-framing';
|
||||
import { SystemOrbitsRenderer } from './system-orbits-renderer';
|
||||
import { LabeledPoint, StarLabelOverlay } from './star-label-overlay';
|
||||
|
||||
// jsdom does not implement ResizeObserver; the component only uses it to react to real
|
||||
@@ -68,8 +63,7 @@ const EARTH: BodyRecord = {
|
||||
argumentOfPeriapsisDeg: 0,
|
||||
meanAnomalyAtEpochDeg: 0,
|
||||
epochJd: 2451545.0
|
||||
},
|
||||
rates: keplerRates(1, GM_SUN_AU3_PER_DAY2), orbitSource: 'test'
|
||||
}
|
||||
};
|
||||
|
||||
/** Minimal stand-in for `EngineService` that skips real WebGPU/WebGL initialization entirely,
|
||||
@@ -610,7 +604,7 @@ describe('GalaxySystemSceneComponent camera-flight transitions', () => {
|
||||
}
|
||||
|
||||
it('links the stars being drawn, and asks again once a new set of them holds still', async () => {
|
||||
const links = vi.fn((_rangePc: number, _drawn: Uint32Array) => Promise.resolve(new Float32Array(0)));
|
||||
const links = vi.fn<LinkScene['routing']['links']>(() => Promise.resolve(new Float32Array(0)));
|
||||
const component = linkScene(links);
|
||||
await settle();
|
||||
expect(links).toHaveBeenCalledTimes(1);
|
||||
@@ -631,7 +625,7 @@ describe('GalaxySystemSceneComponent camera-flight transitions', () => {
|
||||
});
|
||||
|
||||
it('asks for as much of the graph as a million pixels of line make, around where the view is centred', async () => {
|
||||
const links = vi.fn((_rangePc: number, _drawn: Uint32Array, _budget?: LinkBudget) => Promise.resolve(new Float32Array(0)));
|
||||
const links = vi.fn<LinkScene['routing']['links']>(() => Promise.resolve(new Float32Array(0)));
|
||||
Object.defineProperty((fixture.nativeElement as HTMLElement).querySelector('canvas')!, 'clientHeight', { value: 1080 });
|
||||
// A screen scaled to 200%: 1080 CSS pixels are 2160 drawn ones, and the lines are drawn in those.
|
||||
engine.pixelRatio = 2;
|
||||
@@ -647,7 +641,7 @@ describe('GalaxySystemSceneComponent camera-flight transitions', () => {
|
||||
|
||||
it('asks again once the view has zoomed past the budget it asked with, though the drawn stars are the same', async () => {
|
||||
// All three stars fit the star budget, so the drawn set never changes: only the budget can.
|
||||
const links = vi.fn((_rangePc: number, _drawn: Uint32Array, _budget?: LinkBudget) => Promise.resolve(new Float32Array(0)));
|
||||
const links = vi.fn<LinkScene['routing']['links']>(() => Promise.resolve(new Float32Array(0)));
|
||||
Object.defineProperty((fixture.nativeElement as HTMLElement).querySelector('canvas')!, 'clientHeight', { value: 1080 });
|
||||
const component = linkScene(links);
|
||||
await advanceFrames(engine, 0.3);
|
||||
@@ -664,7 +658,7 @@ describe('GalaxySystemSceneComponent camera-flight transitions', () => {
|
||||
});
|
||||
|
||||
it('asks for no graph from inside a system, where distances are in astronomical units', async () => {
|
||||
const links = vi.fn((_rangePc: number, _drawn: Uint32Array, _budget?: LinkBudget) => Promise.resolve(new Float32Array(0)));
|
||||
const links = vi.fn<LinkScene['routing']['links']>(() => Promise.resolve(new Float32Array(0)));
|
||||
navigationStore.selectStar(SUN.id);
|
||||
await flushAsync();
|
||||
await advanceFrames(engine, 2.5);
|
||||
@@ -701,7 +695,7 @@ describe('GalaxySystemSceneComponent camera-flight transitions', () => {
|
||||
});
|
||||
|
||||
it('gives a view on the move a new graph at least every quarter second, rather than waiting for it to stop', async () => {
|
||||
const links = vi.fn((_rangePc: number, _drawn: Uint32Array) => Promise.resolve(new Float32Array(0)));
|
||||
const links = vi.fn<LinkScene['routing']['links']>(() => Promise.resolve(new Float32Array(0)));
|
||||
const component = linkScene(links);
|
||||
await settle();
|
||||
|
||||
@@ -834,111 +828,6 @@ describe('GalaxySystemSceneComponent camera-flight transitions', () => {
|
||||
expect(navigationStore.viewLevel()).toBe('system');
|
||||
});
|
||||
|
||||
it('says where a system’s orbits come from, and for the Sun how long they hold', async () => {
|
||||
const note = (): string => (fixture.componentInstance as unknown as { hudNote: () => string }).hudNote();
|
||||
navigationStore.selectStar(SUN.id);
|
||||
await flushAsync();
|
||||
await advanceFrames(engine, 2.5);
|
||||
expect(note()).toMatch(/^Orbits propagated from JPL mean elements, the planets’ fit for 3000 BC to AD 3000 and the moons’ checked from 1950 to 2100, and the SBDB’s osculating ones for Ceres, Eris, Haumea and Makemake, checked over the same span, to now, \d{4}-\d\d-\d\d \d\d:\d\d UTC\.$/);
|
||||
|
||||
navigationStore.selectStar(ALPHA_CENTAURI.id);
|
||||
await flushAsync();
|
||||
await advanceFrames(engine, 5);
|
||||
expect(note()).toMatch(/^Orbits propagated from published elements to now, \d{4}-\d\d-\d\d \d\d:\d\d UTC\.$/);
|
||||
});
|
||||
|
||||
it('turns the Sun about its IAU pole, once in 25.38 days', async () => {
|
||||
const time = TestBed.inject(TimeStore);
|
||||
time.setRate(0);
|
||||
time.setDate(new Date('2026-01-01T00:00Z'));
|
||||
navigationStore.selectStar(SUN.id);
|
||||
await flushAsync();
|
||||
await advanceFrames(engine, 2.5);
|
||||
const sun = (): THREE.Object3D => (fixture.componentInstance as unknown as { starMarker: THREE.Object3D }).starMarker;
|
||||
const turned = (local: THREE.Vector3): THREE.Vector3 => local.applyQuaternion(sun().getWorldQuaternion(new THREE.Quaternion()));
|
||||
|
||||
// The sphere's +Y, which MAP_TO_BODY carries onto the body's pole, at RA 286.13, Dec 63.87.
|
||||
const ra = (286.13 * Math.PI) / 180;
|
||||
const dec = (63.87 * Math.PI) / 180;
|
||||
const pole = new THREE.Vector3(Math.cos(dec) * Math.cos(ra), Math.cos(dec) * Math.sin(ra), Math.sin(dec));
|
||||
expect(turned(new THREE.Vector3(0, 1, 0)).angleTo(pole)).toBeLessThan(1e-6);
|
||||
|
||||
const before = turned(new THREE.Vector3(1, 0, 0));
|
||||
time.setDate(new Date('2026-01-02T00:00Z'));
|
||||
await advanceFrames(engine, 0.1);
|
||||
expect((turned(new THREE.Vector3(1, 0, 0)).angleTo(before) * 180) / Math.PI).toBeCloseTo(14.1844, 3);
|
||||
});
|
||||
|
||||
it('names the date the system is drawn for once the clock is set to one', async () => {
|
||||
const note = (): string => (fixture.componentInstance as unknown as { hudNote: () => string }).hudNote();
|
||||
TestBed.inject(TimeStore).setDate(new Date('2020-12-21T18:00Z'));
|
||||
navigationStore.selectStar(SUN.id);
|
||||
await flushAsync();
|
||||
await advanceFrames(engine, 2.5);
|
||||
// The great conjunction, to the minute: not "now", and not a date the reader has to find.
|
||||
expect(note()).toMatch(/ to 2020-12-21 18:00 UTC\.$/);
|
||||
});
|
||||
|
||||
describe('with Eris, whose aphelion runs past the grid', () => {
|
||||
type FramedScene = { bodies: BodyRecord[]; controls: { target: THREE.Vector3 }; systemRenderer: SystemOrbitsRenderer; systemGroup: THREE.Group };
|
||||
// Its 67.9 AU axis gives the grid an 80 AU outer ring; at aphelion it is 97.7 AU out.
|
||||
const ERIS: BodyRecord = {
|
||||
...EARTH, id: 'eris', name: 'Eris', kind: 'dwarf', radiusKm: 1163,
|
||||
orbit: { ...EARTH.orbit, semiMajorAxisAu: 67.934, eccentricity: 0.4382 }, rates: keplerRates(67.934, GM_SUN_AU3_PER_DAY2)
|
||||
};
|
||||
|
||||
async function enterTheSun(aspect: number): Promise<FramedScene> {
|
||||
const component = fixture.componentInstance as unknown as FramedScene;
|
||||
component.bodies = [EARTH, ERIS];
|
||||
engine.getPerspectiveCamera().aspect = aspect;
|
||||
navigationStore.selectStar(SUN.id);
|
||||
await flushAsync();
|
||||
await advanceFrames(engine, 2.5);
|
||||
return component;
|
||||
}
|
||||
|
||||
it('frames the furthest the system draws, Eris’s aphelion, not the ring inside it nor its semi-major axis', async () => {
|
||||
const component = await enterTheSun(1);
|
||||
const camera = engine.getPerspectiveCamera();
|
||||
expect(component.systemRenderer.outermostRadiusAu).toBeCloseTo(67.934 * 1.4382, 9);
|
||||
// 234.7 AU; framed on the 67.9 AU axis the camera would stand at 163 AU and Eris arrive off screen.
|
||||
expect(camera.position.distanceTo(component.controls.target)).toBeCloseTo(
|
||||
systemFramingDistanceAu(component.systemRenderer.outermostRadiusAu, { fovDegrees: camera.fov, aspect: camera.aspect }),
|
||||
6
|
||||
);
|
||||
});
|
||||
|
||||
it('holds Earth to its 3-pixel floor at the arrival framing, where its true radius is far under a pixel', async () => {
|
||||
Object.defineProperty((fixture.nativeElement as HTMLElement).querySelector('canvas')!, 'clientHeight', { value: 1000 });
|
||||
const component = await enterTheSun(1.6);
|
||||
const earth = component.systemRenderer.members.find((member) => member.id === 'earth')!.marker as THREE.Mesh;
|
||||
const pixelAu = (2 * engine.visibleHalfHeight(engine.getCamera().position.distanceTo(earth.getWorldPosition(new THREE.Vector3())))) / 1000;
|
||||
expect((earth.scale.x * (earth.geometry as THREE.SphereGeometry).parameters.radius) / pixelAu).toBeCloseTo(3, 3);
|
||||
});
|
||||
|
||||
it('leaves the system outwards even from a phone’s framing, which stands past the 400 AU it used to fly to', async () => {
|
||||
const component = await enterTheSun(390 / 844);
|
||||
const camera = engine.getCamera();
|
||||
const arrival = camera.position.length();
|
||||
expect(arrival).toBeGreaterThan(500);
|
||||
|
||||
navigationStore.selectStar(null);
|
||||
await flushAsync(1);
|
||||
// Until the swap: it flew 508 AU in to 400, and the system grew on screen while the reader left it.
|
||||
let previous = arrival;
|
||||
for (let frame = 0; frame < 100 && component.systemGroup.visible; frame++) {
|
||||
engine.tick(0.05);
|
||||
await flushAsync(1);
|
||||
if (component.systemGroup.visible) {
|
||||
expect(camera.position.length()).toBeGreaterThanOrEqual(previous - 1e-9);
|
||||
previous = camera.position.length();
|
||||
}
|
||||
}
|
||||
expect(component.systemGroup.visible).toBe(false);
|
||||
expect(previous).toBeGreaterThan(arrival);
|
||||
});
|
||||
});
|
||||
|
||||
it('performs the floating-origin recenter: the camera lands close to the AU-space origin, not out at parsec-scale coordinates', async () => {
|
||||
navigationStore.selectStar(ALPHA_CENTAURI.id);
|
||||
await flushAsync();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as THREE from 'three/webgpu';
|
||||
|
||||
import { GALACTIC_BASIS_EQUATORIAL, SUN_HEIGHT_ABOVE_MIDPLANE_PC } from '../../shared/astro/galaxy';
|
||||
import { GALACTIC_BASIS_EQUATORIAL } from '../../shared/astro/galaxy';
|
||||
|
||||
const SEGMENTS_PER_RING = 180;
|
||||
|
||||
|
||||
@@ -87,9 +87,9 @@ export function createRandom(seed: number): () => number {
|
||||
|
||||
/** Standard normal sample, by the polar form of Box-Muller. */
|
||||
function gaussian(random: () => number): number {
|
||||
let u = 0;
|
||||
let v = 0;
|
||||
let s = 0;
|
||||
let u: number;
|
||||
let v: number;
|
||||
let s: number;
|
||||
do {
|
||||
u = random() * 2 - 1;
|
||||
v = random() * 2 - 1;
|
||||
|
||||
@@ -172,25 +172,6 @@ describe('StarFieldRenderer', () => {
|
||||
renderer.dispose();
|
||||
});
|
||||
|
||||
it('ignores a star just outside the frame, however close the pointer gets to the edge', () => {
|
||||
// Its hit area is the drawn size plus a slop, so near an edge that area reaches past the
|
||||
// frame — and a system nobody can see is not one a click should fly into.
|
||||
const offScreen = [star({ id: 9, x: 0, y: 0, z: -10, magnitude: -2 })];
|
||||
const renderer = new StarFieldRenderer(offScreen, packPositions(offScreen));
|
||||
const centre = new THREE.Vector3(0, 0, -10).project(camera);
|
||||
expect(renderer.pickAt(new THREE.Vector2(centre.x, centre.y), camera, camera.aspect)).toBe(9);
|
||||
|
||||
// The same star, just outside the top of the frame: its centre at NDC 1.01, its disc ending at
|
||||
// 1.0033. A click at 0.995 is within its hit radius (0.0167) — so without the frame test this
|
||||
// picks it — while none of the star is on screen.
|
||||
const above = [star({ id: 9, x: 0, y: 10 * Math.tan((camera.fov * Math.PI) / 360) * 1.01, z: -10, magnitude: -2 })];
|
||||
const outside = new StarFieldRenderer(above, packPositions(above));
|
||||
|
||||
expect(outside.pickAt(new THREE.Vector2(0, 0.995), camera, camera.aspect)).toBeUndefined();
|
||||
renderer.dispose();
|
||||
outside.dispose();
|
||||
});
|
||||
|
||||
it('picks the star nearest the pointer when several are in view', () => {
|
||||
const spread = [
|
||||
star({ id: 1, x: 0, y: 0, z: -10 }),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { BrightnessIndex, brightnessIndex, Positioned } from '../../shared/astro
|
||||
import { spectralTypeToColorIndex } from '../../shared/astro/spectral';
|
||||
import { SceneCamera } from '../../core/engine/engine.service';
|
||||
import { StarRecord } from '../../shared/models/star.model';
|
||||
import { PIXELS_TO_ANGULAR_SIZE, REFERENCE_FOV_DEGREES, REFERENCE_VIEWPORT_HEIGHT_PX } from './angular-size';
|
||||
import { PIXELS_TO_ANGULAR_SIZE, REFERENCE_FOV_DEGREES } from './angular-size';
|
||||
|
||||
/** Apparent star diameters, in pixels at {@link REFERENCE_VIEWPORT_HEIGHT_PX}. */
|
||||
const MIN_POINT_SIZE = 1.5;
|
||||
@@ -406,11 +406,6 @@ export class StarFieldRenderer {
|
||||
* needed: each star is tested against the size it is actually drawn at, so the hit area matches
|
||||
* what the user sees at every zoom level instead of being over-permissive up close and
|
||||
* sub-pixel at the far end of the camera's range.
|
||||
*
|
||||
* Only stars on screen can be picked. The hit area is the drawn size plus a slop of
|
||||
* {@link PICK_NDC_SLOP}, and near an edge that slop reaches past the frame: a click in the
|
||||
* last few pixels of the view used to be able to fly into a system whose star was outside it,
|
||||
* with nothing on screen to explain where it had gone.
|
||||
*/
|
||||
pickAt(pointerNdc: THREE.Vector2, camera: SceneCamera, aspect: number): number | undefined {
|
||||
// What a unit of angular size is worth on screen. Under perspective the field of view sets
|
||||
@@ -434,16 +429,10 @@ export class StarFieldRenderer {
|
||||
if (projected.z < -1 || projected.z > 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A sprite square in view space projects to an ellipse in NDC: the same half-extent in y,
|
||||
// divided by the aspect ratio in x. Scaling dx by the aspect makes the comparison circular.
|
||||
const drawnRadius = (0.5 * sizes[index]) / tanHalfFov;
|
||||
// Off screen if no part of the drawn disc is inside the frame. Tested before the slop is
|
||||
// added: the slop is forgiveness for an imprecise click on a star you can see, not a reach
|
||||
// past the edge to one you cannot.
|
||||
if (Math.abs(projected.x) - drawnRadius / aspect > 1 || Math.abs(projected.y) - drawnRadius > 1) {
|
||||
continue;
|
||||
}
|
||||
const ndcRadius = drawnRadius + PICK_NDC_SLOP;
|
||||
const ndcRadius = (0.5 * sizes[index]) / tanHalfFov + PICK_NDC_SLOP;
|
||||
const dx = (projected.x - pointerNdc.x) * aspect;
|
||||
const dy = projected.y - pointerNdc.y;
|
||||
const score = Math.hypot(dx, dy) / ndcRadius;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { eclipticToEquatorial, OBLIQUITY_J2000_DEG } from '../../shared/astro/co
|
||||
import {
|
||||
bodyMarkerRadiusAu,
|
||||
DEFAULT_STAR_MARKER_RADIUS_AU,
|
||||
starGlowExtentAu,
|
||||
starMarkerRadiusAu,
|
||||
systemFrameRadiusAu,
|
||||
systemFramingDistanceAu,
|
||||
@@ -18,10 +19,6 @@ import {
|
||||
const TRAPPIST_1 = { innermost: 0.01154, outermost: 0.06189 };
|
||||
const GL_357 = { innermost: 0.035, outermost: 0.204 };
|
||||
const SOLAR = { innermost: 0.387, outermost: 30.07 };
|
||||
/** The solar system as the map draws it: out to Eris's semi-major axis, 67.93 AU. */
|
||||
const SOLAR_TO_ERIS = { innermost: 0.387, outermost: 67.93 };
|
||||
/** Eris's aphelion, a(1 + e) = 67.934 x 1.4382: past the 80 AU ring its semi-major axis gives. */
|
||||
const ERIS_APHELION_AU = 97.7;
|
||||
|
||||
describe('starMarkerRadiusAu', () => {
|
||||
it('never reaches the innermost orbit', () => {
|
||||
@@ -116,12 +113,107 @@ describe('systemFramingDistanceAu', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('starGlowExtentAu', () => {
|
||||
/** A typical viewport, so a screen-space claim can be made in pixels rather than in ratios. */
|
||||
const REFERENCE_VIEWPORT_HALF_HEIGHT_PX = 450;
|
||||
|
||||
/** The halo's visual radius, in AU, at the distance this system is framed from. */
|
||||
function haloRadiusAu(innermostAu: number, outermostAu: number, glowScale = 1): number {
|
||||
// The sprite's extent is its full width, so half of it is what reaches out from the star.
|
||||
return starGlowExtentAu(starMarkerRadiusAu(innermostAu), frameRadiusFor(outermostAu), glowScale) / 2;
|
||||
}
|
||||
|
||||
function frameRadiusFor(outermostAu: number): number {
|
||||
const rings = systemGridRingsAu(outermostAu);
|
||||
return systemFrameRadiusAu(systemFramingDistanceAu(rings[rings.length - 1]));
|
||||
}
|
||||
|
||||
/** Apparent size on screen, as a fraction of the frame's half-height. */
|
||||
function apparentFraction(innermostAu: number, outermostAu: number, glowScale = 1): number {
|
||||
return haloRadiusAu(innermostAu, outermostAu, glowScale) / frameRadiusFor(outermostAu);
|
||||
}
|
||||
|
||||
function apparentPixels(innermostAu: number, outermostAu: number): number {
|
||||
return apparentFraction(innermostAu, outermostAu) * REFERENCE_VIEWPORT_HALF_HEIGHT_PX;
|
||||
}
|
||||
|
||||
it('scales with the star for a compact system, where the star is already big enough', () => {
|
||||
// A tight frame relative to the star, so the star's own multiple is what decides.
|
||||
const marker = 0.02;
|
||||
const tightFrame = 0.5;
|
||||
expect(starGlowExtentAu(marker, tightFrame)).toBeCloseTo(marker * 3.2, 9);
|
||||
expect(starGlowExtentAu(marker * 2, tightFrame)).toBeCloseTo(marker * 2 * 3.2, 9);
|
||||
});
|
||||
|
||||
it('floors against the frame once the star would otherwise vanish into it', () => {
|
||||
// A star sized against a close-in orbit, framed from far enough out to hold a wide system:
|
||||
// the multiple of the star is nothing, so the frame decides instead.
|
||||
const tinyStar = 0.001;
|
||||
const wideFrame = 56;
|
||||
expect(starGlowExtentAu(tinyStar, wideFrame)).toBeGreaterThan(tinyStar * 3.2 * 100);
|
||||
});
|
||||
|
||||
it('keeps the Sun visible at the distance that frames the solar system', () => {
|
||||
// The case that prompted this: the solar system spans a factor of a hundred from Mercury to
|
||||
// Pluto, so a disc that stays clear of Mercury is about a pixel across once Pluto is in view.
|
||||
expect(apparentPixels(0.387, 39.288)).toBeGreaterThan(4);
|
||||
});
|
||||
|
||||
it('leaves the inner orbits clear of the halo', () => {
|
||||
// The other half of the same trade. Venus and Earth have to stay legible as rings around the
|
||||
// star, which bounds the halo from above just as visibility bounds it from below.
|
||||
const halo = haloRadiusAu(0.387, 39.288);
|
||||
const VENUS_AU = 0.723;
|
||||
const EARTH_AU = 1;
|
||||
expect(halo).toBeLessThan(VENUS_AU);
|
||||
expect(halo).toBeLessThan(EARTH_AU);
|
||||
});
|
||||
|
||||
it('cannot clear Mercury as well, and does not pretend to', () => {
|
||||
// Mercury's orbit is 0.7% of the framed radius — about three pixels — so it is inside any
|
||||
// halo big enough to see. Pinned so the trade is a decision rather than an oversight.
|
||||
expect(haloRadiusAu(0.387, 39.288)).toBeGreaterThan(0.387);
|
||||
});
|
||||
|
||||
it('holds the floor across every system scale the datasets contain', () => {
|
||||
// A compact system's star is genuinely large relative to its own system and keeps the bigger
|
||||
// halo; the floor is not there to equalise them, only to stop the wide ones disappearing.
|
||||
for (const [innermost, outermost] of [
|
||||
[0.387, 39.288],
|
||||
[0.035, 0.204],
|
||||
[0.01154, 0.06189],
|
||||
[1.2, 12.4]
|
||||
]) {
|
||||
expect(apparentPixels(innermost, outermost)).toBeGreaterThan(4);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not blot out the system it sits in', () => {
|
||||
for (const [innermost, outermost] of [
|
||||
[0.387, 39.288],
|
||||
[0.035, 0.204],
|
||||
[0.01154, 0.06189]
|
||||
]) {
|
||||
expect(apparentFraction(innermost, outermost)).toBeLessThan(0.2);
|
||||
}
|
||||
});
|
||||
|
||||
it('dims for a star drawn from a colour rather than a photograph, but never below the floor', () => {
|
||||
// Above the floor the multiplier applies...
|
||||
expect(starGlowExtentAu(1, 10, 0.6)).toBeLessThan(starGlowExtentAu(1, 10, 1));
|
||||
// ...and at the floor it cannot dim a star into invisibility.
|
||||
expect(starGlowExtentAu(0.001, 56, 0.6)).toBe(starGlowExtentAu(0.001, 56, 1));
|
||||
});
|
||||
|
||||
it('falls back to the star alone when there is no frame to measure against', () => {
|
||||
for (const frame of [0, -1, Number.NaN]) {
|
||||
expect(starGlowExtentAu(0.2, frame)).toBeCloseTo(0.2 * 3.2, 9);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('the grid and the framing together', () => {
|
||||
/**
|
||||
* The grid's half of what the scene composes: rings from the orbits, then a distance from the outer
|
||||
* ring. The scene frames the larger of that ring and the furthest aphelion (`outermostRadiusAu`),
|
||||
* which the Eris test below frames where it runs past the ring, and the scene's own spec checks.
|
||||
*/
|
||||
/** What the scene actually composes: rings from the orbits, then a distance from the rings. */
|
||||
function fit(outermostOrbitAu: number, viewport?: SystemViewport): { ring: number; frame: number } {
|
||||
const rings = systemGridRingsAu(outermostOrbitAu);
|
||||
const ring = rings[rings.length - 1];
|
||||
@@ -131,15 +223,14 @@ describe('the grid and the framing together', () => {
|
||||
const VIEWPORTS: SystemViewport[] = [
|
||||
{ fovDegrees: 50, aspect: 1.78 },
|
||||
{ fovDegrees: 50, aspect: 1 },
|
||||
{ fovDegrees: 50, aspect: 0.6 },
|
||||
{ fovDegrees: 50, aspect: 390 / 844 } // a phone held upright
|
||||
{ fovDegrees: 50, aspect: 0.6 }
|
||||
];
|
||||
|
||||
it('leaves the outermost ring clear of the frame edge at every scale and window shape', () => {
|
||||
// The whole point of framing against the grid rather than the orbits: before this, 368 of
|
||||
// the 371 systems in the datasets drew a grid wider than the view that was meant to hold it.
|
||||
for (const viewport of VIEWPORTS) {
|
||||
for (const { outermost } of [TRAPPIST_1, GL_357, SOLAR, SOLAR_TO_ERIS, { outermost: 1 }, { outermost: 12.4 }]) {
|
||||
for (const { outermost } of [TRAPPIST_1, GL_357, SOLAR, { outermost: 1 }, { outermost: 12.4 }]) {
|
||||
const { ring, frame } = fit(outermost, viewport);
|
||||
expect(ring).toBeLessThan(frame);
|
||||
expect(ring / frame).toBeLessThan(0.93);
|
||||
@@ -147,14 +238,6 @@ describe('the grid and the framing together', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves Eris’s aphelion its whole margin in every window shape, a phone held upright included', () => {
|
||||
// The scene frames the aphelion where it runs past the ring. Under the old 500 AU ceiling the
|
||||
// phone would hold it at 0.907 of the half-width instead of 1 / 1.12 = 0.893.
|
||||
for (const viewport of VIEWPORTS) {
|
||||
expect(ERIS_APHELION_AU / systemFrameRadiusAu(systemFramingDistanceAu(ERIS_APHELION_AU, viewport), viewport)).toBeLessThan(0.9);
|
||||
}
|
||||
});
|
||||
|
||||
it('still encloses the outermost orbit, so no planet sits off the edge of the grid', () => {
|
||||
for (const { outermost } of [TRAPPIST_1, GL_357, SOLAR, { outermost: 1 }, { outermost: 12.4 }]) {
|
||||
expect(fit(outermost).ring).toBeGreaterThan(outermost);
|
||||
@@ -195,41 +278,54 @@ describe('star and framing together', () => {
|
||||
|
||||
describe('bodyMarkerRadiusAu', () => {
|
||||
const EARTH_RADIUS_KM = 6371;
|
||||
const KM_PER_AU = 149597870.7;
|
||||
const SOLAR_SPAN_AU = 30.07;
|
||||
|
||||
it('draws a body at its true size', () => {
|
||||
expect(bodyMarkerRadiusAu(EARTH_RADIUS_KM)).toBeCloseTo(EARTH_RADIUS_KM / KM_PER_AU, 12);
|
||||
expect(bodyMarkerRadiusAu(696340)).toBeCloseTo(0.00465, 5); // the Sun
|
||||
it('scales in proportion to the system span', () => {
|
||||
const wide = bodyMarkerRadiusAu(EARTH_RADIUS_KM, SOLAR_SPAN_AU);
|
||||
const compact = bodyMarkerRadiusAu(EARTH_RADIUS_KM, SOLAR_SPAN_AU / 100);
|
||||
|
||||
expect(compact / wide).toBeCloseTo(0.01, 6);
|
||||
});
|
||||
|
||||
it('keeps a moon smaller than its planet and outside it, which the exaggeration did not', () => {
|
||||
// Jupiter and Ganymede both ran past the old 0.09 AU ceiling and came out one size, so
|
||||
// Ganymede orbited inside Jupiter; Phobos and Triton sat entirely within Mars and Neptune.
|
||||
const jupiter = bodyMarkerRadiusAu(69911);
|
||||
const ganymede = bodyMarkerRadiusAu(2634);
|
||||
const callisto = bodyMarkerRadiusAu(2410);
|
||||
const GANYMEDE_SEMI_MAJOR_AXIS_AU = 0.007155;
|
||||
|
||||
expect(ganymede).toBeLessThan(jupiter);
|
||||
expect(callisto).toBeLessThan(ganymede);
|
||||
expect(jupiter + ganymede).toBeLessThan(GANYMEDE_SEMI_MAJOR_AXIS_AU);
|
||||
it('keeps a marker far smaller than the orbits it sits on, at any scale', () => {
|
||||
// A fixed 0.09 AU marker inside Gl 357's 0.204 AU system was wider than the orbits, so one
|
||||
// planet swallowed the whole view.
|
||||
for (const span of [0.06, 0.204, 1, 30.07, 800]) {
|
||||
expect(bodyMarkerRadiusAu(EARTH_RADIUS_KM, span)).toBeLessThan(span / 5);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps Phobos outside Mars, where a marker scaled to the system buried it', () => {
|
||||
const PHOBOS_SEMI_MAJOR_AXIS_AU = 0.00006268;
|
||||
it('gives compact and wide systems the same apparent marker size', () => {
|
||||
const apparent = (span: number) => bodyMarkerRadiusAu(EARTH_RADIUS_KM, span) / systemFramingDistanceAu(span);
|
||||
|
||||
expect(bodyMarkerRadiusAu(3390) + bodyMarkerRadiusAu(11.27)).toBeLessThan(PHOBOS_SEMI_MAJOR_AXIS_AU);
|
||||
expect(apparent(0.204)).toBeCloseTo(apparent(10), 6);
|
||||
});
|
||||
|
||||
it('still renders a bigger body as a bigger marker', () => {
|
||||
expect(bodyMarkerRadiusAu(69911)).toBeGreaterThan(bodyMarkerRadiusAu(1188));
|
||||
const jupiter = bodyMarkerRadiusAu(69911, SOLAR_SPAN_AU);
|
||||
const pluto = bodyMarkerRadiusAu(1188, SOLAR_SPAN_AU);
|
||||
|
||||
expect(jupiter).toBeGreaterThan(pluto);
|
||||
});
|
||||
|
||||
it('falls back to an Earth for a body with no published radius', () => {
|
||||
for (const nothing of [undefined, 0, -1]) {
|
||||
expect(bodyMarkerRadiusAu(nothing as number | undefined)).toBeCloseTo(EARTH_RADIUS_KM / KM_PER_AU, 12);
|
||||
it('falls back to the smallest marker for a body with no known radius', () => {
|
||||
const unknown = bodyMarkerRadiusAu(undefined, SOLAR_SPAN_AU);
|
||||
const pluto = bodyMarkerRadiusAu(1188, SOLAR_SPAN_AU);
|
||||
|
||||
expect(unknown).toBeGreaterThan(0);
|
||||
expect(unknown).toBeLessThanOrEqual(pluto);
|
||||
});
|
||||
|
||||
it('treats a missing span as the reference scale rather than collapsing to zero', () => {
|
||||
for (const span of [0, -5, Number.NaN]) {
|
||||
expect(bodyMarkerRadiusAu(EARTH_RADIUS_KM, span)).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves the solar system essentially as it was before scaling', () => {
|
||||
// The constants were tuned at this span, so the scale factor here is ~1.
|
||||
expect(bodyMarkerRadiusAu(EARTH_RADIUS_KM, SOLAR_SPAN_AU)).toBeCloseTo(0.09, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('systemGridRingsAu', () => {
|
||||
|
||||
@@ -27,6 +27,31 @@ export const DEFAULT_STAR_MARKER_RADIUS_AU = 0.2;
|
||||
*/
|
||||
const STAR_RADIUS_TO_INNERMOST_ORBIT = 0.45;
|
||||
|
||||
/**
|
||||
* Halo extent as a multiple of the star's own radius, and the floor on that extent as a
|
||||
* fraction of the framed radius.
|
||||
*
|
||||
* The floor is what keeps a star visible. A system's star is sized against its *innermost*
|
||||
* orbit — it must never swallow its closest planet — while the camera is placed to frame the
|
||||
* *outermost* ring, and those differ by a factor of a hundred in the solar system. At the
|
||||
* distance that fits Pluto in view, a disc that stays clear of Mercury is about one pixel
|
||||
* across; there is no radius that satisfies both, because the information genuinely does not
|
||||
* fit on one screen at that zoom.
|
||||
*
|
||||
* The halo resolves it, because light is not a surface: a glow that reaches past the innermost
|
||||
* orbit does not claim the star is that large, it claims the star is bright. So the disc stays
|
||||
* honest to the orbits and the halo is floored against the frame.
|
||||
*
|
||||
* The floor is set by what it must not cover. Its visual radius is half the extent, so a floor
|
||||
* of `f` puts the halo's edge at `f / 2` of the frame radius — and the orbits it has to leave
|
||||
* legible sit at their own fraction of that same radius. In the solar system, framed to hold
|
||||
* Pluto, Venus's orbit is at 1.3% of the frame radius and Earth's at 1.8%, so a floor of 2%
|
||||
* leaves both of them outside the halo. Mercury's, at 0.7%, is inside it — and would be at any
|
||||
* halo large enough to see, since the orbit itself is only a few pixels wide there.
|
||||
*/
|
||||
const STAR_GLOW_TO_MARKER = 3.2;
|
||||
const MIN_STAR_GLOW_TO_FRAME = 0.02;
|
||||
|
||||
/**
|
||||
* Clear space left around the framed radius, as a fraction of it. The camera backs off this
|
||||
* much further than the geometry strictly needs, so the outermost ring sits inside the frame
|
||||
@@ -61,17 +86,13 @@ const MIN_FRAMING_DISTANCE_AU = 0.06;
|
||||
/**
|
||||
* Ceiling on the framing distance, so a distant companion does not push the star to a dot.
|
||||
*
|
||||
* Generous enough to frame the solar system out to Eris in any window a reader holds: Eris's
|
||||
* aphelion, 97.7 AU, the furthest it draws, needs 235 AU on a landscape display and 508 on a 390
|
||||
* by 844 phone once the camera's real field of view is accounted for, and 600 holds it down to an
|
||||
* aspect of 0.39. At 500, framed on the 80 AU grid ring inside that aphelion, a phone arrived with
|
||||
* Eris's orbit 3.5 px from the edge; at 200, which framed Pluto's 40 AU ring, a portrait window
|
||||
* arrived with Eris off screen, and a phone with Makemake too. Only genuinely pathological systems
|
||||
* reach it now — the handful with directly-imaged companions hundreds of AU out — and those still
|
||||
* arrive framed on their inner region, with the orbit controls reaching far enough to pull back
|
||||
* to the rest.
|
||||
* Generous enough to frame the solar system out to Pluto in any window shape, which needs 120 AU
|
||||
* on a landscape display and 140 on a portrait one once the camera's real field of view is
|
||||
* accounted for. Only genuinely pathological systems reach it now — the handful with
|
||||
* directly-imaged companions hundreds of AU out — and those still arrive framed on their inner
|
||||
* region, with the orbit controls reaching far enough to pull back to the rest.
|
||||
*/
|
||||
const MAX_FRAMING_DISTANCE_AU = 600;
|
||||
const MAX_FRAMING_DISTANCE_AU = 200;
|
||||
|
||||
/** Framing for a star with no known planets, where there is nothing to fit. */
|
||||
const EMPTY_SYSTEM_FRAMING_DISTANCE_AU = 3;
|
||||
@@ -129,6 +150,20 @@ export function systemFrameRadiusAu(distanceAu: number, viewport: SystemViewport
|
||||
return distanceAu * tightHalfExtent(viewport);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extent (AU) of the star's glow sprite — how wide it is drawn, not its radius.
|
||||
*
|
||||
* Normally a multiple of the star's own radius, so a compact system keeps the corona it has.
|
||||
* Floored against the framed radius, so a star framed from far enough out to hold its whole
|
||||
* system still reads as a bright point rather than disappearing into it. `glowScale` lets a
|
||||
* caller dim the halo for stars drawn without a real photograph.
|
||||
*/
|
||||
export function starGlowExtentAu(markerRadiusAu: number, frameRadiusAu: number, glowScale = 1): number {
|
||||
const fromStar = markerRadiusAu * STAR_GLOW_TO_MARKER * glowScale;
|
||||
const fromFrame = Number.isFinite(frameRadiusAu) && frameRadiusAu > 0 ? frameRadiusAu * MIN_STAR_GLOW_TO_FRAME : 0;
|
||||
return Math.max(fromStar, fromFrame);
|
||||
}
|
||||
|
||||
/**
|
||||
* Distance (AU) to settle the camera at so that `framedRadiusAu` fits in view with a margin
|
||||
* around it.
|
||||
@@ -139,9 +174,8 @@ export function systemFrameRadiusAu(distanceAu: number, viewport: SystemViewport
|
||||
* was tuned by eye against a 55-degree field, and the engine's camera is 50 — which left the
|
||||
* grid overflowing the frame in 368 of the 371 systems the datasets contain.
|
||||
*
|
||||
* Callers pass the outermost thing actually drawn: the reference grid's outer ring, which runs past
|
||||
* every semi-major axis by construction, or an eccentric orbit's aphelion where that runs past the
|
||||
* ring, as Eris's does.
|
||||
* Callers pass the outermost thing actually drawn, which is the reference grid's outer ring
|
||||
* rather than the outermost orbit — the ring is always the wider of the two, by construction.
|
||||
*/
|
||||
export function systemFramingDistanceAu(framedRadiusAu: number, viewport: SystemViewport = DEFAULT_SYSTEM_VIEWPORT): number {
|
||||
if (!Number.isFinite(framedRadiusAu) || framedRadiusAu <= 0) {
|
||||
@@ -189,35 +223,32 @@ export function systemGridRingsAu(outermostOrbitAu: number): number[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* A body is drawn at its true size. Astronomical Unit in kilometres, and what a body with neither
|
||||
* a radius nor a mass to estimate one from is drawn as: an Earth, for want of anything better —
|
||||
* exoplanets with a mass and no radius get an estimate from their mass before they reach here.
|
||||
* Span of the solar system, in AU, used as the reference every other system's marker sizes are
|
||||
* scaled against. The marker constants below were tuned by eye at this scale.
|
||||
*/
|
||||
const KM_PER_AU = 149597870.7;
|
||||
const DEFAULT_BODY_RADIUS_KM = 6371;
|
||||
const REFERENCE_SYSTEM_SPAN_AU = 30;
|
||||
|
||||
/** Exaggerated (non-physical) marker sizes at the reference scale, so planets stay visible. */
|
||||
const MIN_MARKER_RADIUS_AU = 0.012;
|
||||
const MAX_MARKER_RADIUS_AU = 0.09;
|
||||
/** Physical radius (km) that maps to one AU of marker radius before clamping. */
|
||||
const MARKER_RADIUS_KM_PER_AU = 18000;
|
||||
|
||||
/**
|
||||
* The Sun's own radius, in AU — the one star whose size this map knows.
|
||||
* Radius (AU) to draw a planet, moon or exoplanet marker at, scaled to the system it sits in.
|
||||
*
|
||||
* Every other star is drawn at {@link starMarkerRadiusAu}, a size derived from its innermost
|
||||
* orbit rather than measured, because no stellar radius reaches the app: the catalogue carries
|
||||
* positions, magnitudes and colours. Gaia publishes `radius_gspphot` for most of what is drawn
|
||||
* here, and until the ETL fetches it, a system's star is the one body in the view that is not
|
||||
* to scale.
|
||||
* Marker sizes are deliberately exaggerated — a true-scale Earth would be invisible next to its
|
||||
* own orbit — but the exaggeration has to be relative to the system, not absolute. Fixed AU
|
||||
* sizes tuned against the solar system's 30 AU span become grotesque in a system a hundredth
|
||||
* that size: a marker of 0.09 AU inside a 0.2 AU system is wider than the orbits it sits on, so
|
||||
* a single planet swallows the entire view.
|
||||
*
|
||||
* Scaling by the span keeps every system looking like the solar system does: orbits legible,
|
||||
* planets as small dots on them.
|
||||
*/
|
||||
export const SUN_RADIUS_AU = 696340 / KM_PER_AU;
|
||||
export function bodyMarkerRadiusAu(radiusKm: number | undefined, systemSpanAu: number): number {
|
||||
const span = Number.isFinite(systemSpanAu) && systemSpanAu > 0 ? systemSpanAu : REFERENCE_SYSTEM_SPAN_AU;
|
||||
const atReferenceScale = radiusKm ? clamp(radiusKm / MARKER_RADIUS_KM_PER_AU, MIN_MARKER_RADIUS_AU, MAX_MARKER_RADIUS_AU) : MIN_MARKER_RADIUS_AU;
|
||||
|
||||
/**
|
||||
* Radius (AU) to draw a planet, moon or exoplanet marker at: its own, unexaggerated.
|
||||
*
|
||||
* Sizes used to be exaggerated and scaled to the system span, which is what made a moon the size
|
||||
* of its planet — Jupiter and Ganymede both ran past the ceiling and were drawn at one radius, so
|
||||
* every moon orbited inside its parent. True scale needs no rule to prevent that: physics already
|
||||
* puts a moon outside the planet it orbits, and the Sun at a hundredth of Mercury’s orbit.
|
||||
*
|
||||
* What true scale costs is visibility at the framing that holds a whole system, where every body
|
||||
* is sub-pixel. That is paid for on screen instead, in pixels, by the scene's `keepMarkersLegible`.
|
||||
*/
|
||||
export function bodyMarkerRadiusAu(radiusKm: number | undefined): number {
|
||||
return (radiusKm && radiusKm > 0 ? radiusKm : DEFAULT_BODY_RADIUS_KM) / KM_PER_AU;
|
||||
return atReferenceScale * (span / REFERENCE_SYSTEM_SPAN_AU);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import * as THREE from 'three/webgpu';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { DEFAULT_EPOCH_JD, GM_SUN_AU3_PER_DAY2, ttMinusUtSeconds } from '../../shared/astro/constants';
|
||||
import { keplerRates } from '../../shared/astro/kepler';
|
||||
import { eclipticToEquatorial, laplacePlaneToEquatorial, OBLIQUITY_J2000_DEG } from '../../shared/astro/coordinates';
|
||||
import { orientationAt } from '../../shared/astro/rotational-elements';
|
||||
import { DEFAULT_EPOCH_JD } from '../../shared/astro/constants';
|
||||
import { eclipticToEquatorial, OBLIQUITY_J2000_DEG } from '../../shared/astro/coordinates';
|
||||
import { BodyRecord } from '../../shared/models/body.model';
|
||||
import { ExoplanetRecord } from '../../shared/models/exoplanet.model';
|
||||
import { SystemOrbitsRenderer } from './system-orbits-renderer';
|
||||
import { bodyTexturePath, loadCachedTexture } from '../../shared/rendering/texture-catalog';
|
||||
import { bodyMarkerRadiusAu } from './system-framing';
|
||||
|
||||
/** The clock's UT date that names a TDB one: TT - UT, which moves by under a second a year, earlier. */
|
||||
const utOf = (jdTdb: number): number => jdTdb - ttMinusUtSeconds(jdTdb) / 86400;
|
||||
|
||||
/** TRAPPIST-1 b: a real short-period planet around a 0.09 solar-mass red dwarf. */
|
||||
const TRAPPIST_1B_SEMI_MAJOR_AXIS_AU = 0.01154;
|
||||
@@ -174,8 +164,7 @@ describe('SystemOrbitsRenderer exoplanet propagation', () => {
|
||||
argumentOfPeriapsisDeg: 0,
|
||||
meanAnomalyAtEpochDeg: 0,
|
||||
epochJd: DEFAULT_EPOCH_JD
|
||||
},
|
||||
rates: keplerRates(1, GM_SUN_AU3_PER_DAY2), orbitSource: 'test'
|
||||
}
|
||||
};
|
||||
|
||||
it('places an ecliptic orbit in the ecliptic plane of the equatorial scene', () => {
|
||||
@@ -212,8 +201,7 @@ describe('SystemOrbitsRenderer exoplanet propagation', () => {
|
||||
// A body at ecliptic longitude 0 sits on the +X axis in both frames, so it must not move.
|
||||
const atEquinox: BodyRecord = { ...EARTH, orbit: { ...EARTH.orbit, eccentricity: 0 } };
|
||||
const renderer = new SystemOrbitsRenderer([atEquinox], []);
|
||||
// The clock's UT date whose TDB is the elements' epoch.
|
||||
renderer.update(utOf(DEFAULT_EPOCH_JD));
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
|
||||
const p = renderer.members[0].marker.position;
|
||||
expect(p.x).toBeCloseTo(1, 6);
|
||||
@@ -246,9 +234,7 @@ describe('SystemOrbitsRenderer exoplanet propagation', () => {
|
||||
name: 'Jupiter',
|
||||
kind: 'planet',
|
||||
radiusKm: 69911,
|
||||
orbit: { semiMajorAxisAu: 5.2, eccentricity: 0.048, inclinationDeg: 1.3, longitudeOfAscendingNodeDeg: 100, argumentOfPeriapsisDeg: 275, meanAnomalyAtEpochDeg: 20, epochJd: DEFAULT_EPOCH_JD },
|
||||
rates: keplerRates(5.2, GM_SUN_AU3_PER_DAY2),
|
||||
orbitSource: 'test'
|
||||
orbit: { semiMajorAxisAu: 5.2, eccentricity: 0.048, inclinationDeg: 1.3, longitudeOfAscendingNodeDeg: 100, argumentOfPeriapsisDeg: 275, meanAnomalyAtEpochDeg: 20, epochJd: DEFAULT_EPOCH_JD }
|
||||
};
|
||||
|
||||
/** The grid and the tethers are the only line objects the renderer adds outside a pivot. */
|
||||
@@ -386,622 +372,3 @@ describe('SystemOrbitsRenderer exoplanet propagation', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('rotation without IAU elements', () => {
|
||||
/** A body with a day of 23.934 h and no pole: Eris, Haumea and Makemake are drawn this way. */
|
||||
function spinning(overrides: Partial<BodyRecord> = {}): BodyRecord {
|
||||
return {
|
||||
id: 'earth',
|
||||
systemStarId: 0,
|
||||
name: 'Earth',
|
||||
kind: 'planet',
|
||||
radiusKm: 6371,
|
||||
orbit: { semiMajorAxisAu: 1, eccentricity: 0.0167, inclinationDeg: 0, longitudeOfAscendingNodeDeg: 0, argumentOfPeriapsisDeg: 0, meanAnomalyAtEpochDeg: 0, epochJd: DEFAULT_EPOCH_JD },
|
||||
rates: keplerRates(1, GM_SUN_AU3_PER_DAY2), orbitSource: 'test',
|
||||
rotationPeriodHours: 23.934,
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
/** How far the marker has turned about its own axis between two dates, in degrees. */
|
||||
function turnedDegrees(body: BodyRecord, afterDays: number): number {
|
||||
const renderer = new SystemOrbitsRenderer([body], [], undefined, 1);
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
const start = renderer.members[0].marker.quaternion.clone();
|
||||
renderer.update(DEFAULT_EPOCH_JD + afterDays);
|
||||
const turn = start.invert().multiply(renderer.members[0].marker.quaternion);
|
||||
const axis = new THREE.Vector3();
|
||||
const angle = 2 * Math.acos(Math.min(1, Math.abs(turn.w)));
|
||||
turn.normalize();
|
||||
axis.set(turn.x, turn.y, turn.z);
|
||||
const signed = axis.y >= 0 ? angle : -angle;
|
||||
return (signed * 180) / Math.PI;
|
||||
}
|
||||
|
||||
it('turns a body once per its own sidereal day', () => {
|
||||
// A full turn in 23.934 h, so a quarter of that is a quarter turn.
|
||||
expect(Math.abs(turnedDegrees(spinning(), 23.934 / 96))).toBeCloseTo(90, 1);
|
||||
});
|
||||
|
||||
/**
|
||||
* Which way a body spins in the world: its angular velocity projected on its orbit's normal.
|
||||
* Positive is prograde, turning the same way it goes round; negative is retrograde.
|
||||
*/
|
||||
function spinSense(body: BodyRecord): number {
|
||||
const renderer = new SystemOrbitsRenderer([body], [], undefined, 1);
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
const start = renderer.members[0].marker.quaternion.clone();
|
||||
renderer.update(DEFAULT_EPOCH_JD + 0.01);
|
||||
const turn = renderer.members[0].marker.quaternion.clone().multiply(start.invert());
|
||||
const axis = new THREE.Vector3(turn.x, turn.y, turn.z).multiplyScalar(Math.sign(turn.w));
|
||||
return axis.normalize().dot(new THREE.Vector3(0, 0, 1).applyQuaternion(renderer.referenceFrame));
|
||||
}
|
||||
|
||||
it('turns it about its orbit’s normal, backwards for a negative period', () => {
|
||||
expect(spinSense(spinning({ rotationPeriodHours: -23.934 }))).toBeLessThan(-0.99);
|
||||
expect(spinSense(spinning({ rotationPeriodHours: 23.934 }))).toBeGreaterThan(0.99);
|
||||
});
|
||||
|
||||
it('turns Nereid, as shipped, once in the 11.594 hours Kepler measured: a sixth of a turn in 1.93 hours', () => {
|
||||
const shipped: BodyRecord[] = JSON.parse(readFileSync(`${process.cwd()}/src/assets/data/bodies.json`, 'utf8'));
|
||||
const renderer = new SystemOrbitsRenderer(shipped.filter((body) => body.id === 'neptune' || body.id === 'nereid'), []);
|
||||
const nereid = renderer.members.find((member) => member.id === 'nereid')!.marker;
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
const start = nereid.quaternion.clone();
|
||||
renderer.update(DEFAULT_EPOCH_JD + 11.594 / 6 / 24);
|
||||
expect((nereid.quaternion.angleTo(start) * 180) / Math.PI).toBeCloseTo(60, 1);
|
||||
});
|
||||
|
||||
it('leaves a body with no published rotation still', () => {
|
||||
// Hyperion, which tumbles: an invented period would be a claim.
|
||||
const renderer = new SystemOrbitsRenderer([spinning({ rotationPeriodHours: undefined })], [], undefined, 1);
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
const start = renderer.members[0].marker.quaternion.clone();
|
||||
renderer.update(DEFAULT_EPOCH_JD + 40);
|
||||
|
||||
expect(renderer.members[0].marker.quaternion.angleTo(start)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('outermostRadiusAu', () => {
|
||||
function drawn(axis: number, eccentricity: number): BodyRecord {
|
||||
return {
|
||||
id: 'eris', systemStarId: 0, name: 'Eris', kind: 'dwarf', radiusKm: 1163, orbitSource: 'test',
|
||||
orbit: { semiMajorAxisAu: axis, eccentricity, inclinationDeg: 44, longitudeOfAscendingNodeDeg: 36, argumentOfPeriapsisDeg: 151, meanAnomalyAtEpochDeg: 0, epochJd: DEFAULT_EPOCH_JD },
|
||||
rates: keplerRates(axis, GM_SUN_AU3_PER_DAY2)
|
||||
};
|
||||
}
|
||||
|
||||
it('reaches as far as an eccentric orbit goes past the grid: Eris’s aphelion, 97.7 AU, not the 80 AU ring', () => {
|
||||
const renderer = new SystemOrbitsRenderer([drawn(67.934, 0.4382)], []);
|
||||
expect(renderer.outermostRadiusAu).toBeCloseTo(67.934 * 1.4382, 9);
|
||||
renderer.dispose();
|
||||
});
|
||||
|
||||
it('reaches an exoplanet’s aphelion too: HD 20782 b’s, 1.66 times its 1.6 AU ring', () => {
|
||||
// The most eccentric of the 303 exoplanet systems with an orbit past their ring, counted on
|
||||
// exoplanets.json (a = 1.3649 AU, e = 0.95).
|
||||
const renderer = new SystemOrbitsRenderer([], [exoplanet({ id: 'HD 20782 b', name: 'HD 20782 b', orbit: { semiMajorAxisAu: 1.3649, eccentricity: 0.95 } })]);
|
||||
expect(renderer.outermostRadiusAu).toBeCloseTo(1.3649 * 1.95, 9);
|
||||
renderer.dispose();
|
||||
});
|
||||
|
||||
it('is the grid’s outer ring where every orbit stays inside it', () => {
|
||||
const renderer = new SystemOrbitsRenderer([drawn(30, 0.01)], []);
|
||||
expect(renderer.outermostRadiusAu).toBe(35);
|
||||
renderer.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('photographs', () => {
|
||||
it('puts them on their bodies once loaded, one a frame, so the GPU is not handed every map at once, and in their own colours', () => {
|
||||
// Ids no other test here draws, since the loaded textures are shared through the cache.
|
||||
const ids = ['ganymede', 'callisto'];
|
||||
const records: BodyRecord[] = ids.map((id, index) => ({
|
||||
id, systemStarId: 0, name: id, kind: 'planet', radiusKm: 2500, orbitSource: 'test',
|
||||
orbit: { semiMajorAxisAu: 1 + index, eccentricity: 0, inclinationDeg: 0, longitudeOfAscendingNodeDeg: 0, argumentOfPeriapsisDeg: 0, meanAnomalyAtEpochDeg: 0, epochJd: DEFAULT_EPOCH_JD },
|
||||
rates: keplerRates(1 + index, GM_SUN_AU3_PER_DAY2)
|
||||
}));
|
||||
const renderer = new SystemOrbitsRenderer(records, []);
|
||||
const materials = (): THREE.MeshStandardMaterial[] => renderer.members.map((member) => (member.marker as THREE.Mesh).material as THREE.MeshStandardMaterial);
|
||||
const maps = (): Array<THREE.Texture | null> => materials().map((material) => material.map);
|
||||
const colours = (): number[] => materials().map((material) => material.color.getHex());
|
||||
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
expect(maps()).toEqual([null, null]); // not loaded yet: jsdom never loads an image
|
||||
// Until then each is its kind's flat colour, a planet's pale blue.
|
||||
expect(colours()).toEqual([new THREE.Color(0.55, 0.75, 1).getHex(), new THREE.Color(0.55, 0.75, 1).getHex()]);
|
||||
|
||||
for (const id of ids) {
|
||||
loadCachedTexture(bodyTexturePath(id)!).image = { width: 2, height: 1 };
|
||||
}
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
expect(maps().filter(Boolean)).toHaveLength(1);
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
expect(maps()).toEqual(ids.map((id) => loadCachedTexture(bodyTexturePath(id)!)));
|
||||
// The material multiplies its map by its colour: left pale blue, every planet's photograph would
|
||||
// be tinted, Mars's red cut by 45 per cent.
|
||||
expect(colours()).toEqual([0xffffff, 0xffffff]);
|
||||
renderer.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('markers', () => {
|
||||
it('draws every body on the one sphere, scaled to its radius, and leaves that sphere when a system is left', () => {
|
||||
const records: BodyRecord[] = [2500, 60000].map((radiusKm, index) => ({
|
||||
id: `body-${index}`, systemStarId: 0, name: `Body ${index}`, kind: 'planet', radiusKm, orbitSource: 'test',
|
||||
orbit: { semiMajorAxisAu: 1 + index, eccentricity: 0, inclinationDeg: 0, longitudeOfAscendingNodeDeg: 0, argumentOfPeriapsisDeg: 0, meanAnomalyAtEpochDeg: 0, epochJd: DEFAULT_EPOCH_JD },
|
||||
rates: keplerRates(1 + index, GM_SUN_AU3_PER_DAY2)
|
||||
}));
|
||||
const renderer = new SystemOrbitsRenderer(records, [exoplanet({ radiusEarth: 1.1 })], undefined, 1);
|
||||
const meshes = renderer.members.map((member) => member.marker as THREE.Mesh);
|
||||
expect(new Set(meshes.map((mesh) => mesh.geometry)).size).toBe(1);
|
||||
[2500, 60000, 1.1 * 6371].forEach((radiusKm, index) => {
|
||||
const sphere = meshes[index].geometry as THREE.SphereGeometry;
|
||||
expect(meshes[index].scale.x * sphere.parameters.radius).toBeCloseTo(bodyMarkerRadiusAu(radiusKm), 12);
|
||||
});
|
||||
const disposed = vi.fn();
|
||||
meshes[0].geometry.addEventListener('dispose', disposed);
|
||||
renderer.dispose();
|
||||
expect(disposed).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('derived surfaces', () => {
|
||||
const maps = (renderer: SystemOrbitsRenderer): Array<THREE.Texture | null> =>
|
||||
renderer.members.map((member) => ((member.marker as THREE.Mesh).material as THREE.MeshStandardMaterial).map);
|
||||
const nextTask = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const twoPlanets = (): SystemOrbitsRenderer =>
|
||||
new SystemOrbitsRenderer([], [exoplanet({ radiusEarth: 1.1 }), exoplanet({ id: 'TRAPPIST-1 c', name: 'TRAPPIST-1 c', radiusEarth: 1.0 })], undefined, 1);
|
||||
|
||||
it('paints them after the system is built, one a task, so entering a system is not held up, and in their own colours', async () => {
|
||||
const colours = (renderer: SystemOrbitsRenderer): number[] =>
|
||||
renderer.members.map((member) => ((member.marker as THREE.Mesh).material as THREE.MeshStandardMaterial).color.getHex());
|
||||
const renderer = twoPlanets();
|
||||
expect(maps(renderer)).toEqual([null, null]);
|
||||
// Until then each is its kind's flat colour, an exoplanet's magenta.
|
||||
expect(colours(renderer)).toEqual([new THREE.Color(0.85, 0.4, 0.85).getHex(), new THREE.Color(0.85, 0.4, 0.85).getHex()]);
|
||||
await nextTask();
|
||||
expect(maps(renderer).filter(Boolean)).toHaveLength(1);
|
||||
await nextTask();
|
||||
expect(maps(renderer).every(Boolean)).toBe(true);
|
||||
// Left magenta, every derived surface would be multiplied by it, its green cut by 60 per cent.
|
||||
expect(colours(renderer)).toEqual([0xffffff, 0xffffff]);
|
||||
renderer.dispose();
|
||||
});
|
||||
|
||||
it('builds a body still waiting for its surface without three warning of an undefined map', () => {
|
||||
const warn = vi.spyOn(console, 'warn');
|
||||
twoPlanets().dispose();
|
||||
expect(warn.mock.calls.flat().join(' ')).not.toContain("parameter 'map'");
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('paints nothing once the system is left', async () => {
|
||||
const renderer = twoPlanets();
|
||||
renderer.dispose();
|
||||
await nextTask();
|
||||
expect(maps(renderer)).toEqual([null, null]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exoplanet size without a measured radius', () => {
|
||||
const radiusOf = (overrides: Partial<ExoplanetRecord>): number => {
|
||||
const renderer = new SystemOrbitsRenderer([], [exoplanet(overrides)], undefined, 1);
|
||||
return renderer.members[0].marker.userData['radiusAu'];
|
||||
};
|
||||
const EARTH_AU = 6371 / 149597870.7;
|
||||
|
||||
it('draws a giant known only by its mass at about Jupiter’s size, not at an Earth', () => {
|
||||
// 14 Her b: 2 829 Earth masses, no radius. It used to come out the size of the Earth.
|
||||
expect(radiusOf({ radiusEarth: undefined, massEarth: 2829 }) / EARTH_AU).toBeCloseTo(11.2, 1);
|
||||
});
|
||||
|
||||
it('keeps a measured radius over any estimate', () => {
|
||||
expect(radiusOf({ radiusEarth: 1.88, massEarth: 2829 }) / EARTH_AU).toBeCloseTo(1.88, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('solar-system bodies against Horizons', () => {
|
||||
// The records the app ships, read from bodies.json with their IAU rotational elements, and
|
||||
// Horizons' own positions for them (ICRF, AU; heliocentric for the planets, planet-centred for the
|
||||
// moons) at dates across 1950-2100, so the whole path — the ETL's reading of the mean elements,
|
||||
// their rates, the Laplace planes and the scene's frame — is checked against JPL's ephemeris rather
|
||||
// than against itself. A hand copy of the records stood here, and an ETL that dropped Standish's a,
|
||||
// e and i rates or Io's and Europa's backward periapses passed the whole suite on the data it
|
||||
// wrote. Horizons' dates are TDB and the renderer's are the clock's UT, so each is handed over
|
||||
// TT - UT earlier: 69.184 s today, 29 in 1950.
|
||||
const SHIPPED: BodyRecord[] = JSON.parse(readFileSync(`${process.cwd()}/src/assets/data/bodies.json`, 'utf8'));
|
||||
// Mimas and Phobos among them for the terms of their IAU W that are motion along the orbit: the
|
||||
// Mimas-Tethys libration and Phobos's tidal acceleration (see `orbitalTermsOfPrimeMeridian`).
|
||||
const IDS = ['earth', 'jupiter', 'saturn', 'neptune', 'pluto', 'moon', 'io', 'europa', 'titan', 'triton', 'uranus', 'titania', 'charon', 'venus', 'mars', 'mimas', 'phobos'];
|
||||
// Each ceiling sits just above what these elements measure on that date: Earth 0.003 degrees,
|
||||
// Jupiter 0.063, Saturn 0.164, Pluto 0.054, the Moon 0.72 (no mean ellipse has its evection or
|
||||
// variation), Io 0.021, Europa 0.036, Titan 0.014, Triton 0.137, Titania 0.62 (against Uranus's
|
||||
// equator, 120 years from its 1980 epoch), Charon 0.37, Mimas 2.24 on 2026 May 27, when its libration has it
|
||||
// 44 degrees ahead of its mean motion (43.3 without the term), and Phobos 1.25 in 2100 (11.1 without its
|
||||
// tidal acceleration).
|
||||
const HORIZONS: Array<[id: string, jd: number, x: number, y: number, z: number, maxDeg: number]> = [
|
||||
['earth', 2488069.5, -0.1574071329883954, 0.890666220858489, 0.3859132211165683, 0.02],
|
||||
// AD 3000, the end of the clock's window and of Standish's fit: the Earth-Moon barycentre and
|
||||
// Saturn's, 0.005 and 0.065 degrees out. Without Standish's rates for a, e and i they were 0.129
|
||||
// and 0.412, which no date between 1950 and 2100 shows (at most 0.036, Saturn in 2100).
|
||||
['earth', 2816787.5, 0.06574092668156256, 0.9022934196570718, 0.3887693148519465, 0.02],
|
||||
['saturn', 2816787.5, 8.434780522117482, 3.87565654130078, 1.235068259814154, 0.1],
|
||||
['jupiter', 2433282.5, 3.406605247558555, -3.425997624196318, -1.551719750032203, 0.1],
|
||||
['saturn', 2478938.5, -3.51309768447752, -8.723317933082274, -3.452662390556131, 0.25],
|
||||
['pluto', 2442413.5, -29.2488165026956, -7.1421817246801, 6.58403957591589, 0.1],
|
||||
['moon', 2469807.5, 0.00240364781322315, 0.0006554283236619424, 0.0004472719300783614, 2],
|
||||
['io', 2433282.5, 0.0004488349204269952, 0.002519633434577752, 0.00120678715190893, 0.05],
|
||||
['europa', 2433282.5, 0.004084372287322533, -0.001665375585011311, -0.0007673072324795899, 0.1],
|
||||
['titan', 2488069.5, 0.007800850235156121, -0.001556932380983438, -0.0006078959246502567, 0.05],
|
||||
['triton', 2488069.5, -0.001421151845853369, -0.0001894510477241482, 0.001888790702926415, 0.2],
|
||||
['titania', 2488069.5, -0.00151919968294745, -0.0003387914082135071, 0.002465657830788125, 0.75],
|
||||
['charon', 2488069.5, -0.00003046411046017432, -0.000009404114448552256, 0.0001270457155789907, 0.5],
|
||||
['mimas', 2461187.5, -3.840685116962088e-4, 1.182766232573268e-3, -2.006928678577268e-5, 3],
|
||||
['phobos', 2488069.5, 4.269855297288105e-5, -2.759158950396543e-5, -3.816269137755616e-5, 1.5],
|
||||
];
|
||||
|
||||
function record(id: string): BodyRecord {
|
||||
const { kind, orbit, rates, laplacePole, parentBodyId, massRatio, rotationalElements } = SHIPPED.find((body) => body.id === id)!;
|
||||
return { id, systemStarId: 0, name: id, radiusKm: 1000, orbitSource: 'test', kind, orbit, rates, laplacePole, parentBodyId, massRatio, rotationalElements };
|
||||
}
|
||||
|
||||
const renderer = new SystemOrbitsRenderer(IDS.map(record), []);
|
||||
|
||||
for (const [id, jd, x, y, z, maxDeg] of HORIZONS) {
|
||||
it(`puts ${id} within ${maxDeg} degrees of Horizons on JD ${jd}`, () => {
|
||||
renderer.update(utOf(jd));
|
||||
const drawn = renderer.members.find((member) => member.id === id)!.marker.position;
|
||||
const angleDeg = (drawn.angleTo(new THREE.Vector3(x, y, z)) * 180) / Math.PI;
|
||||
expect(angleDeg).toBeLessThan(maxDeg);
|
||||
});
|
||||
}
|
||||
|
||||
it('puts Pluto where Horizons has it round its barycentre with Charon, 2 131 km out and opposite Charon', () => {
|
||||
// Horizons, Pluto (999) from the Pluto-system barycentre (9), on JD 2488069.5 TDB (2100).
|
||||
const horizons = new THREE.Vector3(0.000003313612032581019, 0.000001023040948538272, -0.00001381793390079716);
|
||||
renderer.update(utOf(2488069.5));
|
||||
const charon = renderer.members.find((member) => member.id === 'charon')!.marker;
|
||||
const barycentre = charon.parent!.position;
|
||||
const pluto = renderer.members.find((member) => member.id === 'pluto')!.marker.position.clone().sub(barycentre);
|
||||
const charonFromBarycentre = charon.position;
|
||||
|
||||
expect((pluto.angleTo(horizons) * 180) / Math.PI).toBeLessThan(0.5);
|
||||
expect(pluto.length() * 149597870.7).toBeCloseTo(horizons.length() * 149597870.7, -1);
|
||||
// Opposite, at the inverse of their mass ratio.
|
||||
expect((pluto.angleTo(charonFromBarycentre) * 180) / Math.PI).toBeCloseTo(180, 6);
|
||||
expect(charonFromBarycentre.length() / pluto.length()).toBeCloseTo(1 / 0.1220485755631374, 6);
|
||||
});
|
||||
|
||||
it('draws Pluto’s own orbit round the barycentre, in the plane it is going round in', () => {
|
||||
const charon = renderer.members.find((member) => member.id === 'charon')!.marker;
|
||||
const [charonLine, plutoLine] = charon.parent!.children.filter((child) => child.name === 'orbit-line');
|
||||
for (const days of [0, 3000, 30000]) {
|
||||
renderer.update(DEFAULT_EPOCH_JD + days);
|
||||
const pluto = renderer.members.find((member) => member.id === 'pluto')!.marker.position.clone().sub(charon.parent!.position);
|
||||
const normal = new THREE.Vector3(0, 0, 1).applyQuaternion(plutoLine.quaternion);
|
||||
expect(Math.abs(pluto.clone().normalize().dot(normal))).toBeLessThan(1e-9);
|
||||
// A near-circle 2 131 km across, a ninth of Charon's.
|
||||
expect(Math.abs(plutoLine.scale.x) * 0.00013095774631236113).toBeCloseTo(pluto.length(), 8);
|
||||
expect(charonLine.scale.x / Math.abs(plutoLine.scale.x)).toBeCloseTo(1 / 0.1220485755631374, 9);
|
||||
}
|
||||
});
|
||||
|
||||
it('turns a planet’s drawn orbit with its node, so Mars stays on its own line two thousand years out', () => {
|
||||
// At AD 1 a line fixed at J2000 has Mars 3.3 million km from it, 0.5 million out of its plane.
|
||||
const mars = renderer.members.find((member) => member.id === 'mars')!.marker;
|
||||
const line = renderer.object.children[renderer.object.children.indexOf(mars) - 1];
|
||||
expect(line.name).toBe('orbit-line');
|
||||
for (const days of [0, -730000]) {
|
||||
renderer.update(DEFAULT_EPOCH_JD + days);
|
||||
const normal = new THREE.Vector3(0, 0, 1).applyQuaternion(line.quaternion);
|
||||
expect(Math.abs(mars.position.clone().normalize().dot(normal))).toBeLessThan(1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
/** How far a top-level body is from its own drawn orbit line, in AU: from the nearest of its chords. */
|
||||
function offLineAu(id: string): number {
|
||||
const marker = renderer.members.find((member) => member.id === id)!.marker;
|
||||
const line = renderer.object.children[renderer.object.children.indexOf(marker) - 1] as THREE.Line;
|
||||
expect(line.name).toBe('orbit-line');
|
||||
line.updateMatrixWorld();
|
||||
const position = line.geometry.getAttribute('position');
|
||||
const vertex = (index: number): THREE.Vector3 => new THREE.Vector3().fromBufferAttribute(position, index).applyMatrix4(line.matrixWorld);
|
||||
const chord = new THREE.Line3();
|
||||
const closest = new THREE.Vector3();
|
||||
let nearest = Number.POSITIVE_INFINITY;
|
||||
for (let index = 0; index + 1 < position.count; index++) {
|
||||
nearest = Math.min(nearest, chord.set(vertex(index), vertex(index + 1)).closestPointToPoint(marker.position, true, closest).distanceTo(marker.position));
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
it('redraws a planet’s orbit as its axis and eccentricity drift, so Saturn and Mars stay on their lines at AD 1', () => {
|
||||
// What is left is the 128 chords' own sag from the true ellipse, which depends on where the
|
||||
// planet falls between two points: at most 0.0032 AU for Saturn, near aphelion, and 0.00055 for
|
||||
// Mars. Measured 0.0017 AU for Saturn and 0.0005 for Mars at AD 1, and 0.0011 for Saturn at
|
||||
// J2000. Drawn at J2000's shape at AD 1, the lines were 0.054 AU from Saturn and 0.0022 from Mars.
|
||||
const saturnLine = renderer.object.children[renderer.object.children.indexOf(renderer.members.find((member) => member.id === 'saturn')!.marker) - 1] as THREE.Line;
|
||||
renderer.update(DEFAULT_EPOCH_JD);
|
||||
const drawnVersion = (saturnLine.geometry.getAttribute('position') as THREE.BufferAttribute).version;
|
||||
for (const [id, days, maxAu] of [['saturn', -730000, 0.0035], ['mars', -730000, 0.0006], ['saturn', 0, 0.0035]] as const) {
|
||||
renderer.update(DEFAULT_EPOCH_JD + days);
|
||||
expect(offLineAu(id)).toBeLessThan(maxAu);
|
||||
if (days !== 0) {
|
||||
// Handed to the GPU again, which uploads a buffer only when its version rises: the points
|
||||
// rewritten on the CPU alone leave J2000's ellipse on screen.
|
||||
expect((saturnLine.geometry.getAttribute('position') as THREE.BufferAttribute).version).toBeGreaterThan(drawnVersion);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('turns the Moon’s drawn orbit with its node, so the Moon stays on its own line', () => {
|
||||
// Half the node's 18.6-year turn on, the ellipse drawn at the epoch has the Moon 10 degrees off
|
||||
// its plane at the worst.
|
||||
const moon = renderer.members.find((member) => member.id === 'moon')!.marker;
|
||||
const line = moon.parent!.children.find((child) => child.name === 'orbit-line')!;
|
||||
for (const days of [0, 1700, 3397, 3400]) {
|
||||
renderer.update(DEFAULT_EPOCH_JD + days);
|
||||
const normal = new THREE.Vector3(0, 0, 1).applyQuaternion(line.quaternion);
|
||||
expect(Math.abs(moon.position.clone().normalize().dot(normal))).toBeLessThan(1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
const JUNE_1_2025_NOON_UTC = 2460828.0;
|
||||
|
||||
/**
|
||||
* The tilt of a body's drawn spin from the orbit it is drawn going round, in degrees: its angular
|
||||
* velocity, read off the sphere a quarter of an hour apart, against its orbit line's normal. Past
|
||||
* 90 is a body turning backwards against its orbit.
|
||||
*/
|
||||
function drawnObliquity(id: string): number {
|
||||
const marker = renderer.members.find((member) => member.id === id)!.marker;
|
||||
const line = renderer.object.children[renderer.object.children.indexOf(marker) - 1];
|
||||
expect(line.name).toBe('orbit-line');
|
||||
renderer.update(JUNE_1_2025_NOON_UTC);
|
||||
const start = marker.quaternion.clone();
|
||||
renderer.update(JUNE_1_2025_NOON_UTC + 0.01);
|
||||
const turn = marker.quaternion.clone().multiply(start.invert());
|
||||
const spin = new THREE.Vector3(turn.x, turn.y, turn.z).multiplyScalar(Math.sign(turn.w));
|
||||
return (spin.angleTo(new THREE.Vector3(0, 0, 1).applyQuaternion(line.quaternion)) * 180) / Math.PI;
|
||||
}
|
||||
|
||||
it('turns Venus, Uranus and Pluto backwards against their orbits, at the tilts Horizons gives the first two', () => {
|
||||
// Pluto's Horizons page gives no tilt; 119.6 is the one its IAU pole makes with its orbit, so for
|
||||
// Pluto this checks that its pole and W are drawn as the kernel gives them, not the pole itself.
|
||||
// The IAU names a planet's north pole by the side of the solar system it lies on, so Venus's W
|
||||
// and Uranus's run backwards; Pluto's pole follows the right-hand rule instead, and points
|
||||
// south. Either way the spin read off the drawn sphere is past 90 degrees from the orbit's pole.
|
||||
expect(drawnObliquity('venus')).toBeCloseTo(177.3, 0);
|
||||
expect(drawnObliquity('uranus')).toBeCloseTo(97.77, 0);
|
||||
expect(drawnObliquity('pluto')).toBeCloseTo(119.6, 0);
|
||||
expect(drawnObliquity('earth')).toBeCloseTo(23.44, 0);
|
||||
});
|
||||
|
||||
/**
|
||||
* Where on its drawn sphere a body faces a point, as east longitude and latitude on its map: read
|
||||
* from the texture coordinates where a ray from that point meets the sphere, so the map's own
|
||||
* convention is part of what is measured.
|
||||
*/
|
||||
function facing(id: string, point: THREE.Vector3): { eastDeg: number; latDeg: number } {
|
||||
const marker = renderer.members.find((member) => member.id === id)!.marker as THREE.Mesh;
|
||||
const centre = worldPosition(id);
|
||||
const towards = point.clone().sub(centre).normalize();
|
||||
const radius = marker.userData['radiusAu'];
|
||||
const hit = new THREE.Raycaster(centre.clone().addScaledVector(towards, radius * 4), towards.clone().negate()).intersectObject(marker)[0];
|
||||
return { eastDeg: (hit.uv!.x - 0.5) * 360, latDeg: (hit.uv!.y - 0.5) * 180 };
|
||||
}
|
||||
|
||||
function worldPosition(id: string): THREE.Vector3 {
|
||||
const marker = renderer.members.find((member) => member.id === id)!.marker;
|
||||
marker.updateWorldMatrix(true, false);
|
||||
return marker.getWorldPosition(new THREE.Vector3());
|
||||
}
|
||||
|
||||
/** Degrees between two longitudes, the short way round. */
|
||||
const apart = (a: number, b: number): number => Math.abs(((((a - b) % 360) + 540) % 360) - 180);
|
||||
|
||||
/** Where the IAU puts a body's prime meridian at a TDB date, in the scene. */
|
||||
function iauPrimeMeridian(id: string, jdTdb: number): THREE.Vector3 {
|
||||
const { poleRaDeg, poleDecDeg, primeMeridianDeg } = orientationAt(SHIPPED.find((body) => body.id === id)!.rotationalElements!, jdTdb);
|
||||
const w = (primeMeridianDeg * Math.PI) / 180;
|
||||
const meridian = laplacePlaneToEquatorial({ x: Math.cos(w), y: Math.sin(w), z: 0 }, { raDeg: poleRaDeg, decDeg: poleDecDeg });
|
||||
return new THREE.Vector3(meridian.x, meridian.y, meridian.z);
|
||||
}
|
||||
|
||||
/** The drawn sphere's longitude 0 on its equator: +X of the sphere as `SphereGeometry` wraps its map. */
|
||||
function drawnPrimeMeridian(id: string): THREE.Vector3 {
|
||||
return new THREE.Vector3(1, 0, 0).applyQuaternion(renderer.members.find((member) => member.id === id)!.marker.quaternion);
|
||||
}
|
||||
|
||||
it('turns Jupiter at AD 1000 by its W at that date’s TT, 1 574 s after the UT the clock names', () => {
|
||||
// Espenak and Meeus's ΔT for JD 2086307.5, 1 January 1000 in the Julian calendar, where TT - UT was 23 times what it is today: held
|
||||
// at today's 69 s, Jupiter was drawn 15 degrees short of its W.
|
||||
const jdUt = 2086307.5;
|
||||
renderer.update(jdUt);
|
||||
expect((drawnPrimeMeridian('jupiter').angleTo(iauPrimeMeridian('jupiter', jdUt + 1574.1 / 86400)) * 180) / Math.PI).toBeLessThan(0.01);
|
||||
});
|
||||
|
||||
it('turns Earth by the UT the clock names, which is its turning: at AD 1000 the Sun stands over Horizons’ point', () => {
|
||||
// Horizons' sub-solar longitude from the Sun (observer quantity 14, TIME_TYPE=UT) on JD 2086455,
|
||||
// 1.0510 E, is Earth as it was 8.454 minutes before. Turned by the IAU's W at UT + 69.184 s, as it
|
||||
// was, the drawn face was 2.3 degrees off (2.0 at UT itself); taken at TDB, which turns it ΔT
|
||||
// (6.6 degrees) further the same way, 8.6.
|
||||
renderer.update(2086455 - 8.45437443 / 1440);
|
||||
expect(apart(facing('earth', new THREE.Vector3()).eastDeg, 1.05101)).toBeLessThan(0.15);
|
||||
});
|
||||
|
||||
it('lights Earth where the Sun really stands: within 4 degrees of Greenwich at noon UTC', () => {
|
||||
// The equation of time is all that separates them: on 1 June 2025 it puts the Sun over 0.53 W,
|
||||
// and the drawn sphere has it over 0.52 W.
|
||||
renderer.update(JUNE_1_2025_NOON_UTC);
|
||||
expect(Math.abs(facing('earth', new THREE.Vector3()).eastDeg)).toBeLessThan(4);
|
||||
});
|
||||
|
||||
// Horizons' sub-Earth latitude on Saturn (observer quantity 14, from Earth's centre), which is
|
||||
// planetodetic: taken back to planetocentric through the flattening, it is the angle the rings are
|
||||
// opened to Earth by. Measured: 26.963, 0.075 and -7.764 degrees drawn, against 26.966, 0.042 and
|
||||
// -7.813.
|
||||
const SATURN_FLATTENING = 0.09796;
|
||||
const RING_OPENING: Array<[date: string, jd: number, planetodeticDeg: number]> = [
|
||||
['16 October 2017, near their widest', 2458042.5, 32.017423],
|
||||
['23 March 2025, as Earth crossed their plane', 2460757.5, 0.051359],
|
||||
['24 September 2026, the south face turned to Earth', 2461307.5, -9.571756]
|
||||
];
|
||||
|
||||
const saturnRingMesh = (): THREE.Mesh => renderer.members.find((member) => member.id === 'saturn')!.marker.children[0] as THREE.Mesh;
|
||||
|
||||
/** The ring's face normal in the scene, read off its own geometry rather than its transform. */
|
||||
function ringNormal(ring: THREE.Mesh): THREE.Vector3 {
|
||||
ring.updateWorldMatrix(true, false);
|
||||
return new THREE.Vector3().fromBufferAttribute(ring.geometry.attributes['normal'], 0).transformDirection(ring.matrixWorld);
|
||||
}
|
||||
|
||||
for (const [date, jd, planetodeticDeg] of RING_OPENING) {
|
||||
it(`opens Saturn's rings to Earth as far as Horizons has them on ${date}`, () => {
|
||||
renderer.update(jd);
|
||||
const normal = ringNormal(saturnRingMesh());
|
||||
const toEarth = worldPosition('earth').sub(worldPosition('saturn')).normalize();
|
||||
const openingDeg = (Math.asin(normal.dot(toEarth)) * 180) / Math.PI;
|
||||
const expectedDeg = (Math.atan((1 - SATURN_FLATTENING) ** 2 * Math.tan((planetodeticDeg * Math.PI) / 180)) * 180) / Math.PI;
|
||||
expect(Math.abs(openingDeg - expectedDeg)).toBeLessThan(0.1);
|
||||
});
|
||||
}
|
||||
|
||||
it('picks Saturn through its rings', () => {
|
||||
renderer.update(JUNE_1_2025_NOON_UTC);
|
||||
const ring = saturnRingMesh();
|
||||
const normal = ringNormal(ring);
|
||||
const inRingPlane = new THREE.Vector3().fromBufferAttribute(ring.geometry.attributes['position'], 0).transformDirection(ring.matrixWorld);
|
||||
// Straight down onto the B ring, 100 000 km out: nowhere near the planet itself.
|
||||
const onRing = worldPosition('saturn').addScaledVector(inRingPlane, 100000 / 149597870.7);
|
||||
const [hit] = new THREE.Raycaster(onRing.clone().addScaledVector(normal, 0.01), normal.clone().negate()).intersectObjects(renderer.pickableObjects);
|
||||
expect(hit.object).toBe(ring);
|
||||
expect(renderer.memberForObject(hit.object)?.id).toBe('saturn');
|
||||
});
|
||||
|
||||
// Horizons' observer quantities 14 and 15 at 2025-06-01 12:00 UTC, from Earth's centre (from the
|
||||
// Sun's, for Earth): the sub-observer and sub-solar longitude and latitude, east-positive for
|
||||
// Earth and the Moon and west-positive for Mars and Jupiter, as each is printed. Horizons gives
|
||||
// each body as it was when the light now arriving left it, so it is drawn that much earlier. Its
|
||||
// latitudes are planetodetic, on the body's flattened figure, which a sphere does not have, so the
|
||||
// drawn latitude is put on that figure before they are compared: without it they differ by what
|
||||
// the flattening makes of them, 0.14 degrees on Earth, 0.26 on Mars and 0.33 on Jupiter.
|
||||
//
|
||||
// Measured: every longitude within 0.09 degrees and every latitude within 0.03, but for the
|
||||
// Moon's face towards Earth, 0.70 and 0.09 out because its mean orbit is (its evection alone is
|
||||
// 1.27 degrees); its face towards the Sun is within 0.002. Io's face towards Jupiter is 0.012 out:
|
||||
// with its orbit taken at the clock's UTC and its spin at TDB it was 0.175, the 69 s between them.
|
||||
const SUB_POINTS: Array<[id: string, observer: string | undefined, lightMinutes: number, west: boolean, flattening: number, observerLon: number, observerLat: number, sunLon: number, sunLat: number, maxObserverDeg: number]> = [
|
||||
['earth', undefined, 8.43351424, false, 1 / 298.257, 1.5855, 22.261204, 1.579501, 22.260426, 0.1],
|
||||
['mars', 'earth', 14.13295841, true, 1 - 3376.2 / 3396.19, 307.365389, 21.27653, 269.287887, 25.451264, 0.1],
|
||||
['moon', 'earth', 0.02150549, false, 0, 7.256763, -3.462104, 116.285934, 1.503004, 0.8],
|
||||
['jupiter', 'earth', 50.70337676, true, 1 - 66854 / 71492, 251.139846, 2.58787, 247.855871, 2.572658, 0.1],
|
||||
['io', 'jupiter', 0.02340584, true, 0, 359.964094, -0.002537, 355.673108, 2.26528, 0.05]
|
||||
];
|
||||
|
||||
for (const [id, observer, lightMinutes, west, flattening, observerLon, observerLat, sunLon, sunLat, maxObserverDeg] of SUB_POINTS) {
|
||||
it(`faces ${observer ?? 'the Sun'} and the Sun with the points Horizons gives on ${id}`, () => {
|
||||
renderer.update(JUNE_1_2025_NOON_UTC - lightMinutes / 1440);
|
||||
const seen = facing(id, observer ? worldPosition(observer) : new THREE.Vector3());
|
||||
const lit = facing(id, new THREE.Vector3());
|
||||
const east = (longitude: number): number => (west ? -longitude : longitude);
|
||||
const planetodetic = (latDeg: number): number => (Math.atan(Math.tan((latDeg * Math.PI) / 180) / (1 - flattening) ** 2) * 180) / Math.PI;
|
||||
expect(apart(seen.eastDeg, east(observerLon))).toBeLessThan(maxObserverDeg);
|
||||
expect(Math.abs(planetodetic(seen.latDeg) - observerLat)).toBeLessThan(maxObserverDeg);
|
||||
expect(apart(lit.eastDeg, east(sunLon))).toBeLessThan(0.1);
|
||||
expect(Math.abs(planetodetic(lit.latDeg) - sunLat)).toBeLessThan(0.05);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('locked moons across the clock’s window', () => {
|
||||
// As shipped, pole, W and all: the IAU gives each a W fitted near the present, and its rate is
|
||||
// not quite its orbit's, nor Iapetus's pole a line for twenty centuries.
|
||||
const shipped: BodyRecord[] = JSON.parse(readFileSync(`${process.cwd()}/src/assets/data/bodies.json`, 'utf8'));
|
||||
const renderer = new SystemOrbitsRenderer(
|
||||
shipped.filter((body) => ['jupiter', 'saturn', 'uranus', 'neptune', 'europa', 'ganymede', 'callisto', 'mimas', 'rhea', 'iapetus', 'miranda', 'triton', 'proteus'].includes(body.id)),
|
||||
[]
|
||||
);
|
||||
|
||||
/** Degrees between two lines, the way a spin axis and an orbit normal are compared: Miranda turns backwards against the IAU's pole. */
|
||||
function linesApartDeg(a: THREE.Vector3, b: THREE.Vector3): number {
|
||||
return (Math.acos(Math.min(1, Math.abs(a.clone().normalize().dot(b.clone().normalize())))) * 180) / Math.PI;
|
||||
}
|
||||
|
||||
/** A moon's drawn spin axis and the normal of its drawn orbit line, in the scene's ICRF frame. */
|
||||
function axisAndOrbitNormal(id: string): { axis: THREE.Vector3; normal: THREE.Vector3 } {
|
||||
const moon = renderer.members.find((member) => member.id === id)!.marker;
|
||||
const line = moon.parent!.children.find((child) => child.name === 'orbit-line')!;
|
||||
return { axis: new THREE.Vector3(0, 1, 0).applyQuaternion(moon.quaternion), normal: new THREE.Vector3(0, 0, 1).applyQuaternion(line.quaternion) };
|
||||
}
|
||||
|
||||
/** East longitude, on its map, of the point on a moon's drawn sphere that faces its planet. */
|
||||
function facingPlanet(id: string): number {
|
||||
const moon = renderer.members.find((member) => member.id === id)!.marker;
|
||||
// Its position is from the planet, which is its pivot; SphereGeometry wraps u = atan2(z, -x) / 2 pi.
|
||||
const toPlanet = moon.position.clone().negate().applyQuaternion(moon.quaternion.clone().invert());
|
||||
const u = Math.atan2(toPlanet.z, -toPlanet.x) / (2 * Math.PI);
|
||||
return ((((u - 0.5) * 360) % 360) + 540) % 360 - 180;
|
||||
}
|
||||
|
||||
it('keeps Proteus, Miranda, Mimas and Iapetus facing their planets at AD 1 and AD 3000', () => {
|
||||
// Measured: Proteus 2.6 degrees at most over AD 1-3000, Miranda 2.4, Mimas 8.9, Iapetus 16 (9.4
|
||||
// of it the lag of the row its orbit is drawn from). On the IAU's own W and Iapetus's straight
|
||||
// pole they were 146, 23, 49 and 87 degrees at AD 1.
|
||||
for (const jd of [1721425.5, 2816787.4]) {
|
||||
renderer.update(jd);
|
||||
expect(Math.abs(facingPlanet('proteus'))).toBeLessThan(3);
|
||||
expect(Math.abs(facingPlanet('miranda'))).toBeLessThan(3);
|
||||
expect(Math.abs(facingPlanet('mimas'))).toBeLessThan(9.5);
|
||||
expect(Math.abs(facingPlanet('iapetus'))).toBeLessThan(16.5);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the axes of Mimas and Iapetus on their drawn orbits’ normals, as a Cassini state holds them, at AD 1, today and AD 3000', () => {
|
||||
// Measured over AD 1-3000: Mimas 0.44 degrees at most, Iapetus 0.74. With Iapetus's pole on
|
||||
// its Laplace pole, 8.3 off at every date.
|
||||
for (const jd of [1721425.5, 2460676.5, 2816787.4]) {
|
||||
renderer.update(jd);
|
||||
for (const id of ['mimas', 'iapetus']) {
|
||||
const { axis, normal } = axisAndOrbitNormal(id);
|
||||
expect(linesApartDeg(axis, normal)).toBeLessThan(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('turns the poles of Europa, Ganymede, Callisto, Rhea, Miranda and Triton round with their drawn nodes, at AD 1, today and AD 3000', () => {
|
||||
// Each pole goes round on a term of its node's angle, re-rated to the node's drawn rate (see
|
||||
// `lockedToOrbit`), each node at JPL's current rate. Measured at these dates: at most 0.23
|
||||
// degrees (Miranda). On the IAU's rates Rhea is 0.73, Miranda 0.51 and Triton 0.42, and on the
|
||||
// archived table's node periods Callisto 0.48 and Miranda 0.42.
|
||||
for (const jd of [1721425.5, 2460676.5, 2816787.4]) {
|
||||
renderer.update(jd);
|
||||
for (const id of ['europa', 'ganymede', 'callisto', 'rhea', 'miranda', 'triton']) {
|
||||
const { axis, normal } = axisAndOrbitNormal(id);
|
||||
expect(linesApartDeg(axis, normal), id).toBeLessThan(0.25);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('draws Miranda’s orbit, and turns its axis, where Horizons has its orbit in 1601 and 2390', () => {
|
||||
// Horizons' osculating orbit normal (ura184, ICRF), averaged over three of Miranda's orbits about
|
||||
// each date; it wobbles 0.01 degrees about that. The drawn node turns at JPL's current 17.787-year
|
||||
// period (see `nodePeriodYears` in the ETL); on the archived table's 17.727, which the IAU's pole
|
||||
// was once turned after too, the drawn orbit was 2.1 degrees from Horizons' at both dates and the
|
||||
// axis 2.4 at 1601. A date this far back is TDB less some two minutes; the node moves 0.004 degrees in that.
|
||||
const HORIZONS_NORMALS: Array<[jd: number, raDeg: number, decDeg: number]> = [
|
||||
[2305813.5, 72.83137, 16.17526],
|
||||
[2594102.5, 81.27691, 17.43782]
|
||||
];
|
||||
for (const [jd, raDeg, decDeg] of HORIZONS_NORMALS) {
|
||||
renderer.update(jd);
|
||||
const [ra, dec] = [(raDeg * Math.PI) / 180, (decDeg * Math.PI) / 180];
|
||||
const horizons = new THREE.Vector3(Math.cos(dec) * Math.cos(ra), Math.cos(dec) * Math.sin(ra), Math.sin(dec));
|
||||
const { axis, normal } = axisAndOrbitNormal('miranda');
|
||||
expect(linesApartDeg(normal, horizons)).toBeLessThan(0.5);
|
||||
expect(linesApartDeg(axis, horizons)).toBeLessThan(0.5);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import * as THREE from 'three/webgpu';
|
||||
|
||||
import { appearanceForBody, appearanceForExoplanet } from '../../shared/astro/body-appearance';
|
||||
import { gmForParent } from '../../shared/astro/constants';
|
||||
import { PlanetAppearance } from '../../shared/astro/planet-appearance';
|
||||
import { planetTexture } from '../../shared/rendering/procedural-planet-texture';
|
||||
import { bodyTexturePath, loadCachedTexture, saturnRing } from '../../shared/rendering/texture-catalog';
|
||||
import { isPropagatableOrbit, keplerRates, meanElementsAt, orbitEllipsePoints, positionAtEpoch, resolveGravitationalParameter, resolveOrbitalElements } from '../../shared/astro/kepler';
|
||||
import { MARKER_TEXTURE_HEIGHT, MARKER_TEXTURE_WIDTH, planetTexture } from '../../shared/rendering/procedural-planet-texture';
|
||||
import { isPropagatableOrbit, orbitEllipsePoints, propagateOrbit, resolveGravitationalParameter, resolveOrbitalElements } from '../../shared/astro/kepler';
|
||||
import { CartesianCoordinates, OBLIQUITY_J2000_DEG } from '../../shared/astro/coordinates';
|
||||
import { tdbFromUtc } from '../../shared/astro/constants';
|
||||
import { BodyRecord, MeanElementRates, OrbitalElements, RotationalElements } from '../../shared/models/body.model';
|
||||
import { bodyOrientation, poleFrame } from '../../shared/rendering/body-orientation';
|
||||
import { BodyRecord, OrbitalElements } from '../../shared/models/body.model';
|
||||
import { bodyMarkerRadiusAu, systemGridRingsAu } from './system-framing';
|
||||
import { PolarGridPlane, TetherField } from './grid-plane';
|
||||
import { ExoplanetRecord } from '../../shared/models/exoplanet.model';
|
||||
@@ -20,8 +18,6 @@ export interface SystemMember {
|
||||
id: string;
|
||||
kind: SystemMemberKind;
|
||||
marker: THREE.Object3D;
|
||||
/** For a moon, the id of the body it orbits: what its drawn size is held against. */
|
||||
parentId?: string;
|
||||
}
|
||||
|
||||
const PLANET_COLOR = new THREE.Color(0.55, 0.75, 1.0);
|
||||
@@ -46,38 +42,11 @@ const SYSTEM_TETHER_OPACITY = 0.3;
|
||||
|
||||
/**
|
||||
* Rotation carrying the **ecliptic** frame into the scene's equatorial one — a turn of the
|
||||
* obliquity about the shared vernal-equinox axis. The planets' and the Moon's mean elements are
|
||||
* given against the J2000 ecliptic, so this is their frame.
|
||||
* obliquity about the shared vernal-equinox axis. Solar-system elements come from Horizons
|
||||
* against the ecliptic, so this is their frame.
|
||||
*/
|
||||
const ECLIPTIC_FRAME = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), OBLIQUITY_J2000_DEG * DEG_TO_RAD);
|
||||
|
||||
/**
|
||||
* Rotation carrying a moon's element frame into the scene: its local Laplace plane where JPL
|
||||
* gives one, the ecliptic otherwise. {@link poleFrame} builds it from the axes
|
||||
* `laplacePlaneToEquatorial` sends, so the scene and the ETL's check against Horizons share the
|
||||
* one conversion.
|
||||
*/
|
||||
function moonFrame(body: BodyRecord): THREE.Quaternion {
|
||||
return body.laplacePole ? poleFrame(body.laplacePole) : ECLIPTIC_FRAME.clone();
|
||||
}
|
||||
|
||||
const X_AXIS = new THREE.Vector3(1, 0, 0);
|
||||
const Z_AXIS = new THREE.Vector3(0, 0, 1);
|
||||
const scratchTurn = new THREE.Quaternion();
|
||||
|
||||
/**
|
||||
* Sets `target` to the rotation carrying an orbit's own plane, periapsis along +X, into the
|
||||
* scene: the argument of periapsis, then the inclination, then the node, as
|
||||
* `positionAtTrueAnomaly` turns a point, and then the frame the elements are measured in.
|
||||
*/
|
||||
function orientOrbit(target: THREE.Quaternion, elements: OrbitalElements, frame: THREE.Quaternion): THREE.Quaternion {
|
||||
return target
|
||||
.copy(frame)
|
||||
.multiply(scratchTurn.setFromAxisAngle(Z_AXIS, elements.longitudeOfAscendingNodeDeg * DEG_TO_RAD))
|
||||
.multiply(scratchTurn.setFromAxisAngle(X_AXIS, elements.inclinationDeg * DEG_TO_RAD))
|
||||
.multiply(scratchTurn.setFromAxisAngle(Z_AXIS, elements.argumentOfPeriapsisDeg * DEG_TO_RAD));
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotation carrying the frame an **exoplanet's** elements are measured in into the scene.
|
||||
*
|
||||
@@ -122,18 +91,21 @@ function colorForKind(kind: SystemMemberKind): THREE.Color {
|
||||
/** Marks orbit lines so the whole layer can be toggled without touching the bodies. */
|
||||
const ORBIT_LINE_NAME = 'orbit-line';
|
||||
|
||||
/**
|
||||
* The orbit's ellipse, drawn in its own plane and turned into place by the line's quaternion (see
|
||||
* {@link orientOrbit}), which `update` sets again each tick: a node and a periapsis that turn cost
|
||||
* a quaternion rather than a new geometry. The Moon's node goes right round in 18.6 years, so an
|
||||
* ellipse fixed at one date has the Moon up to 2 sin 5.16° of its distance, 69 000 km, off its own
|
||||
* line nine years on.
|
||||
*
|
||||
* The shape is redrawn by {@link reshapeOrbitLine} as the planets' axes and eccentricities drift.
|
||||
*/
|
||||
function buildOrbitLine(elements: OrbitalElements, kind: SystemMemberKind, frame: THREE.Quaternion): THREE.Line {
|
||||
const points = orbitEllipsePoints(elements);
|
||||
const positions = new Float32Array(points.length * 3);
|
||||
const scratch = new THREE.Vector3();
|
||||
points.forEach((point, index) => {
|
||||
// Elements are measured against their source's own reference plane; `frame` rotates that
|
||||
// plane into the scene's equatorial one.
|
||||
const { x, y, z } = scratch.set(point.x, point.y, point.z).applyQuaternion(frame);
|
||||
positions[index * 3] = x;
|
||||
positions[index * 3 + 1] = y;
|
||||
positions[index * 3 + 2] = z;
|
||||
});
|
||||
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute('position', new THREE.BufferAttribute(ellipseInItsPlane(elements, new Float32Array((ORBIT_LINE_SEGMENTS + 1) * 3)), 3));
|
||||
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
|
||||
|
||||
const material = new THREE.LineBasicMaterial({
|
||||
color: colorForKind(kind),
|
||||
@@ -143,214 +115,45 @@ function buildOrbitLine(elements: OrbitalElements, kind: SystemMemberKind, frame
|
||||
|
||||
const line = new THREE.Line(geometry, material);
|
||||
line.name = ORBIT_LINE_NAME;
|
||||
line.userData = { semiMajorAxisAu: elements.semiMajorAxisAu, eccentricity: elements.eccentricity };
|
||||
orientOrbit(line.quaternion, elements, frame);
|
||||
return line;
|
||||
}
|
||||
|
||||
const ORBIT_LINE_SEGMENTS = 128;
|
||||
|
||||
/** The orbit's ellipse in its own plane, periapsis along +X, written into `positions`. */
|
||||
function ellipseInItsPlane(elements: OrbitalElements, positions: Float32Array): Float32Array {
|
||||
orbitEllipsePoints({ ...elements, inclinationDeg: 0, longitudeOfAscendingNodeDeg: 0, argumentOfPeriapsisDeg: 0 }, ORBIT_LINE_SEGMENTS).forEach((point, index) => {
|
||||
positions[index * 3] = point.x;
|
||||
positions[index * 3 + 1] = point.y;
|
||||
positions[index * 3 + 2] = point.z;
|
||||
});
|
||||
return positions;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far, in AU, an orbit's drawn ellipse may be from its current one before it is drawn again:
|
||||
* well under the 128 chords' own sag from the true curve, at most 0.00055 AU for Mars and 0.0032
|
||||
* for Saturn, near aphelion, where points spaced evenly in true anomaly lie furthest apart.
|
||||
* A marker sphere, surfaced with the body's own derived appearance rather than a flat category
|
||||
* colour — so a system reads as a set of distinct worlds at a glance, and the colour of each is
|
||||
* a consequence of its measurements rather than of which list it came from.
|
||||
*
|
||||
* The texture is tiny (see `MARKER_TEXTURE_WIDTH`): a marker is a few pixels across, so what
|
||||
* survives is essentially its average colour, and generating it costs well under a millisecond.
|
||||
*/
|
||||
const ORBIT_RESHAPE_AU = 1e-4;
|
||||
|
||||
/**
|
||||
* Draws an orbit line's ellipse again once the axis and eccentricity it was drawn with have drifted
|
||||
* from `elements`' by more than {@link ORBIT_RESHAPE_AU}. Standish's rates move Saturn's
|
||||
* eccentricity 0.0064 in twenty centuries, and left at J2000's, the line passed 0.056 AU, 8.4
|
||||
* million km, from Saturn at AD 1; Jupiter 0.016 AU there, Pluto 0.021 at AD 3000. The moons' and
|
||||
* the exoplanets' elements carry no such rates, so their lines are drawn once.
|
||||
*/
|
||||
function reshapeOrbitLine(line: THREE.Line, elements: OrbitalElements): void {
|
||||
const drawn = line.userData as { semiMajorAxisAu: number; eccentricity: number };
|
||||
const driftAu = Math.abs(elements.semiMajorAxisAu - drawn.semiMajorAxisAu) + elements.semiMajorAxisAu * Math.abs(elements.eccentricity - drawn.eccentricity);
|
||||
if (driftAu <= ORBIT_RESHAPE_AU) {
|
||||
return;
|
||||
}
|
||||
const position = line.geometry.getAttribute('position') as THREE.BufferAttribute;
|
||||
ellipseInItsPlane(elements, position.array as Float32Array);
|
||||
position.needsUpdate = true;
|
||||
line.geometry.computeBoundingSphere();
|
||||
line.userData = { semiMajorAxisAu: elements.semiMajorAxisAu, eccentricity: elements.eccentricity };
|
||||
}
|
||||
|
||||
/**
|
||||
* A marker sphere, surfaced with the body's own photograph where one has ever been taken, and
|
||||
* with a texture derived from its measurements where none has — and lit by its star either way,
|
||||
* so a world shows the day and night it actually has.
|
||||
*
|
||||
* The photographs were already in the repository, used only by the detail page: the system view
|
||||
* drew every body from a 32 by 16 pixel procedural texture instead, which at a few pixels across
|
||||
* was indistinguishable from its average colour and, once the camera closed in, was a blur. A
|
||||
* marker can now fill the frame, so it takes the real image at the size the detail page uses.
|
||||
*
|
||||
* A derived texture is not painted here but handed to `deferSurface`, which paints it after the
|
||||
* system is built: at about 4.4 ms each, the twenty bodies the solar system gained with its dwarf
|
||||
* planets and smaller moons lengthened the task that enters it from 78-94 ms to 177-228. Until
|
||||
* then the body is its kind's flat colour.
|
||||
*
|
||||
* A photograph is handed to `deferPhotograph`, which puts it on the body once it has loaded, one a
|
||||
* frame: a texture is copied to the GPU in the first frame that draws it, and the 28 maps, which
|
||||
* arrive within 40 ms of each other, made that one frame a 160-210 ms task on entering the Sun's
|
||||
* system (copyExternalImageToTexture, about 38 megapixels of JPEG: nine maps at 2048 by 1024, the
|
||||
* Sun's among them, Jupiter's at 3840 by 1920, and eighteen smaller).
|
||||
*
|
||||
* Every marker is the one unit sphere, {@link MARKER_SPHERE}, scaled to the body's radius, which
|
||||
* it also keeps as `userData.radiusAu`: built one a body, the 38 spheres of the Sun's system took
|
||||
* 12 ms of the 15 ms the renderer took to build and, with their upload, made a return to the
|
||||
* system a long task of 52 to 70 ms, where the 18 bodies before had made none.
|
||||
*/
|
||||
function buildMarker(
|
||||
id: string | undefined,
|
||||
kind: SystemMemberKind,
|
||||
radiusKm: number | undefined,
|
||||
appearance: PlanetAppearance | undefined,
|
||||
deferSurface: (paint: () => void) => void,
|
||||
deferPhotograph: (material: THREE.MeshStandardMaterial, texture: THREE.Texture) => void
|
||||
): THREE.Mesh {
|
||||
const photograph = id ? bodyTexturePath(id) : undefined;
|
||||
// null, not undefined, until there is one: three warns "parameter 'map' has value of
|
||||
// undefined" for every body built so, eleven of them on entering the Sun's system.
|
||||
const material = new THREE.MeshStandardMaterial({
|
||||
map: null,
|
||||
color: colorForKind(kind),
|
||||
roughness: 1,
|
||||
metalness: 0
|
||||
});
|
||||
if (photograph) {
|
||||
deferPhotograph(material, loadCachedTexture(photograph));
|
||||
} else if (appearance) {
|
||||
deferSurface(() => {
|
||||
// 128 by 64, not the detail page's 512 by 256: that size costs about 60 ms a body on the
|
||||
// main thread, for a disc that is a few pixels across until the camera is on top of it.
|
||||
material.map = planetTexture(appearance, { width: 128, height: 64 });
|
||||
material.color.set(0xffffff);
|
||||
material.needsUpdate = true;
|
||||
});
|
||||
}
|
||||
const marker = new THREE.Mesh(MARKER_SPHERE, material);
|
||||
const radiusAu = bodyMarkerRadiusAu(radiusKm);
|
||||
marker.scale.setScalar(radiusAu);
|
||||
marker.userData = { radiusAu };
|
||||
return marker;
|
||||
}
|
||||
|
||||
/**
|
||||
* The star's own light, at the centre of the system it lights.
|
||||
*
|
||||
* `decay` is 0, which is not what light does: a point source falls off with the square of the
|
||||
* distance, and under that law Neptune, at 30.2 AU, receives about a six-thousandth of what
|
||||
* Mercury does at 0.39 AU and reads as black. The map is a set of worlds to look at rather than a
|
||||
* light meter, so each is lit as a photograph of it would be — the same concession the pixel
|
||||
* floor makes for size. What the light does carry truthfully is which side is day: every body
|
||||
* shows its lit face toward the star, and the terminator falls where it really falls.
|
||||
*
|
||||
* White, at π: a Lambertian surface returns intensity / π of its texture where the light falls
|
||||
* square on it, so π gives back the photograph itself at the point facing the star, and less
|
||||
* towards the limb. A warm tint or a smaller figure darkened the photographs below what they are.
|
||||
*/
|
||||
function starLight(): THREE.PointLight {
|
||||
const light = new THREE.PointLight(0xffffff, Math.PI, 0, 0);
|
||||
light.position.set(0, 0, 0);
|
||||
return light;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sphere segments. On a UV sphere the silhouette seen down the pole is the ring of width segments
|
||||
* and the one seen from the side is the meridian profile, so height at half the width makes the
|
||||
* error the same from every direction: at 64 by 32 a body filling the screen — Jupiter reaches
|
||||
* 641 px of radius in the plan view — strays under a pixel from its true circle.
|
||||
*/
|
||||
const MARKER_WIDTH_SEGMENTS = 64;
|
||||
const MARKER_HEIGHT_SEGMENTS = 32;
|
||||
/** Shared by every marker of every system, so it is never disposed; see `buildMarker`. */
|
||||
const MARKER_SPHERE = new THREE.SphereGeometry(1, MARKER_WIDTH_SEGMENTS, MARKER_HEIGHT_SEGMENTS);
|
||||
|
||||
/**
|
||||
* A drawn radius, in Earth radii, for an exoplanet that has a mass and no measured radius — 1 076
|
||||
* of the 1 692 drawn, most of them found by radial velocity, and most of those giants: their
|
||||
* median is 315 Earth masses. Drawn at an Earth, as they were, a nine-Jupiter-mass planet came out
|
||||
* smaller than its system's super-Earth.
|
||||
*
|
||||
* A rough power law, capped at Jupiter's radius: giants from a third of a Jupiter mass to ten are
|
||||
* all about Jupiter's size, since past that point added mass compresses rather than inflates. It
|
||||
* sets a size to draw, not a figure to print — the readout still says the radius is unknown.
|
||||
*/
|
||||
function radiusFromMassEarth(massEarth: number | null | undefined): number | undefined {
|
||||
return massEarth && massEarth > 0 ? Math.min(JUPITER_RADIUS_EARTH, massEarth ** 0.55) : undefined;
|
||||
}
|
||||
const JUPITER_RADIUS_EARTH = 11.2;
|
||||
|
||||
/** Local axis a sphere is built around, and what the spin is applied about. */
|
||||
const SPIN_AXIS = new THREE.Vector3(0, 1, 0);
|
||||
const HOURS_PER_DAY = 24;
|
||||
|
||||
/**
|
||||
* How a body the IAU gives no rotational elements for is turned at a given date — Eris, Haumea,
|
||||
* Makemake and Nereid, whose periods are measured (Makemake's only to a factor of two, see its
|
||||
* spec in `fetchSolarSystem.ts`) and whose poles are not: at its own sidereal rate, about
|
||||
* its orbit's normal, backwards for a negative period. None of them has an obliquity, so none is
|
||||
* applied. The phase is arbitrary: each body starts at its elements' epoch in the shortest
|
||||
* rotation of +Y onto its axis, and turns from there. Exoplanets have no published rotation at
|
||||
* all, and are left still.
|
||||
*
|
||||
* Every other body is turned by {@link bodyOrientation}.
|
||||
*/
|
||||
function spinFor(elements: OrbitalElements, frame: THREE.Quaternion, rotationPeriodHours: number, daysSinceEpoch: number): THREE.Quaternion {
|
||||
const node = elements.longitudeOfAscendingNodeDeg * DEG_TO_RAD;
|
||||
const inclination = elements.inclinationDeg * DEG_TO_RAD;
|
||||
const axis = new THREE.Vector3(Math.sin(inclination) * Math.sin(node), -Math.sin(inclination) * Math.cos(node), Math.cos(inclination)).applyQuaternion(frame);
|
||||
const turns = (daysSinceEpoch * HOURS_PER_DAY) / rotationPeriodHours;
|
||||
return new THREE.Quaternion()
|
||||
.setFromUnitVectors(SPIN_AXIS, axis)
|
||||
.multiply(new THREE.Quaternion().setFromAxisAngle(SPIN_AXIS, turns * 2 * Math.PI));
|
||||
function buildMarker(kind: SystemMemberKind, radiusKm: number | undefined, systemSpanAu: number, appearance: PlanetAppearance | undefined): THREE.Mesh {
|
||||
const geometry = new THREE.SphereGeometry(bodyMarkerRadiusAu(radiusKm, systemSpanAu), 16, 12);
|
||||
const material = appearance
|
||||
? new THREE.MeshBasicMaterial({ map: planetTexture(appearance, { width: MARKER_TEXTURE_WIDTH, height: MARKER_TEXTURE_HEIGHT }) })
|
||||
: new THREE.MeshBasicMaterial({ color: colorForKind(kind) });
|
||||
return new THREE.Mesh(geometry, material);
|
||||
}
|
||||
|
||||
interface TrackedTopLevelBody {
|
||||
id: string;
|
||||
kind: SystemMemberKind;
|
||||
elements: OrbitalElements;
|
||||
rates: MeanElementRates;
|
||||
gmAu3PerDay2: number;
|
||||
marker: THREE.Mesh;
|
||||
orbitLine: THREE.Line;
|
||||
/** Rotation from this body's own element frame into the scene's equatorial one. */
|
||||
frame: THREE.Quaternion;
|
||||
/** AU position last computed for this body; moons read their parent's here. */
|
||||
position: THREE.Vector3;
|
||||
/** Sidereal rotation, where the catalogue publishes one; negative is retrograde. */
|
||||
rotationPeriodHours?: number;
|
||||
rotationalElements?: RotationalElements;
|
||||
}
|
||||
|
||||
interface TrackedMoon {
|
||||
id: string;
|
||||
elements: OrbitalElements;
|
||||
rates: MeanElementRates;
|
||||
gmAu3PerDay2: number;
|
||||
marker: THREE.Mesh;
|
||||
orbitLine: THREE.Line;
|
||||
frame: THREE.Quaternion;
|
||||
pivot: THREE.Group;
|
||||
parentId: string;
|
||||
rotationPeriodHours?: number;
|
||||
rotationalElements?: RotationalElements;
|
||||
/**
|
||||
* Where the moon and its planet go round a barycentre outside the planet (Charon): the moon's
|
||||
* mass over the planet's, and the planet's own small orbit round that point.
|
||||
*/
|
||||
barycentre?: { massRatio: number; parentOrbitLine: THREE.Line };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -372,12 +175,10 @@ export class SystemOrbitsRenderer {
|
||||
*/
|
||||
readonly referenceFrame: THREE.Quaternion;
|
||||
/**
|
||||
* How far (AU) from the star the system draws anything, or 0 where it draws nothing: what the
|
||||
* camera has to frame. The reference grid's outer ring, which runs 15 per cent past the largest
|
||||
* semi-major axis, unless an eccentric orbit reaches further at its aphelion — Eris's, 97.7 AU,
|
||||
* does past the solar system's 80 AU ring, and some orbit does in 303 of the 1 190 exoplanet systems.
|
||||
* Outer radius (AU) of the reference grid, or 0 where there is none. This — not the outermost
|
||||
* orbit — is the widest thing the system draws, so it is what the camera has to frame.
|
||||
*/
|
||||
readonly outermostRadiusAu: number;
|
||||
readonly gridOuterRadiusAu: number;
|
||||
|
||||
private readonly topLevelBodies: TrackedTopLevelBody[] = [];
|
||||
private readonly moons: TrackedMoon[] = [];
|
||||
@@ -389,22 +190,6 @@ export class SystemOrbitsRenderer {
|
||||
* following them each tick costs no allocation at all.
|
||||
*/
|
||||
private tetherPoints: readonly THREE.Vector3[] = [];
|
||||
/** Derived surfaces still to paint, one a task, once the constructor is done; see `buildMarker`. */
|
||||
private readonly surfacesToPaint: Array<() => void> = [];
|
||||
private surfaceTimer?: ReturnType<typeof setTimeout>;
|
||||
private readonly deferSurface = (paint: () => void): void => {
|
||||
this.surfacesToPaint.push(paint);
|
||||
this.surfaceTimer ??= setTimeout(this.paintNextSurface, 0);
|
||||
};
|
||||
private readonly paintNextSurface = (): void => {
|
||||
this.surfacesToPaint.shift()?.();
|
||||
this.surfaceTimer = this.surfacesToPaint.length > 0 ? setTimeout(this.paintNextSurface, 0) : undefined;
|
||||
};
|
||||
/** Photographs still to put on their bodies, one a frame once loaded; see `buildMarker`. */
|
||||
private readonly photographsToShow: Array<{ material: THREE.MeshStandardMaterial; texture: THREE.Texture }> = [];
|
||||
private readonly deferPhotograph = (material: THREE.MeshStandardMaterial, texture: THREE.Texture): void => {
|
||||
this.photographsToShow.push({ material, texture });
|
||||
};
|
||||
|
||||
constructor(
|
||||
bodies: readonly BodyRecord[],
|
||||
@@ -421,11 +206,12 @@ export class SystemOrbitsRenderer {
|
||||
const members: SystemMember[] = [];
|
||||
const topLevelBodiesById = new Map<string, BodyRecord>();
|
||||
|
||||
const topLevelOrbits = [
|
||||
...bodies.filter((body) => !body.parentBodyId).map(({ orbit }) => ({ axis: orbit.semiMajorAxisAu, eccentricity: orbit.eccentricity })),
|
||||
...exoplanets.filter((exoplanet) => isPropagatableOrbit(exoplanet.orbit)).map(({ orbit }) => ({ axis: orbit.semiMajorAxisAu!, eccentricity: orbit.eccentricity ?? 0 }))
|
||||
].filter(({ axis }) => Number.isFinite(axis) && axis > 0);
|
||||
const topLevelAxes = topLevelOrbits.map(({ axis }) => axis);
|
||||
// Measured before anything is built, because marker sizes are scaled against the span and
|
||||
// the markers are created as the bodies are added.
|
||||
const topLevelAxes = [
|
||||
...bodies.filter((body) => !body.parentBodyId).map((body) => body.orbit.semiMajorAxisAu),
|
||||
...exoplanets.filter((exoplanet) => isPropagatableOrbit(exoplanet.orbit)).map((exoplanet) => exoplanet.orbit.semiMajorAxisAu!)
|
||||
].filter((axis) => Number.isFinite(axis) && axis > 0);
|
||||
this.maxTopLevelSemiMajorAxisAu = topLevelAxes.length > 0 ? Math.max(...topLevelAxes) : 0;
|
||||
this.minTopLevelSemiMajorAxisAu = topLevelAxes.length > 0 ? Math.min(...topLevelAxes) : 0;
|
||||
|
||||
@@ -441,16 +227,7 @@ export class SystemOrbitsRenderer {
|
||||
}
|
||||
// A body reaches here only when it has no parentBodyId, so `kind` is 'planet' or 'dwarf'.
|
||||
const kind: SystemMemberKind = body.kind;
|
||||
const tracked = this.addTopLevelBody(body.id, kind, body.orbit, body.rates, body.radiusKm, ECLIPTIC_FRAME, appearanceForBody(body, bodies, hostLuminositySolar), { periodHours: body.rotationPeriodHours, elements: body.rotationalElements });
|
||||
if (body.id === 'saturn') {
|
||||
// A child of the sphere, so it lies in the equator the IAU pole turns the sphere into and
|
||||
// is scaled with it where the marker is held to its pixel floor. Jupiter's, Uranus's and
|
||||
// Neptune's rings are left out: dark, narrow or dusty, they are too faint to see here.
|
||||
// In the sphere's own units, its radius being 1.
|
||||
const ring = saturnRing(body.radiusKm, 1);
|
||||
tracked.marker.add(ring);
|
||||
this.trackDisposable(ring.geometry, ring.material as THREE.Material);
|
||||
}
|
||||
const tracked = this.addTopLevelBody(body.id, kind, body.orbit, gmForParent(undefined), body.radiusKm, ECLIPTIC_FRAME, appearanceForBody(body, bodies, hostLuminositySolar));
|
||||
members.push({ id: body.id, kind, marker: tracked.marker });
|
||||
}
|
||||
|
||||
@@ -463,8 +240,8 @@ export class SystemOrbitsRenderer {
|
||||
if (!parentTracked) {
|
||||
continue; // orphaned moon reference; skip rather than crash.
|
||||
}
|
||||
const moon = this.addMoon(body.id, body.orbit, body.rates, body.radiusKm, parentTracked, moonFrame(body), appearanceForBody(body, bodies, hostLuminositySolar), { periodHours: body.rotationPeriodHours, elements: body.rotationalElements }, body.massRatio);
|
||||
members.push({ id: body.id, kind: 'moon', marker: moon.marker, parentId: parent.id });
|
||||
const moon = this.addMoon(body.id, body.orbit, gmForParent(body.parentBodyId), body.radiusKm, parentTracked, ECLIPTIC_FRAME, appearanceForBody(body, bodies, hostLuminositySolar));
|
||||
members.push({ id: body.id, kind: 'moon', marker: moon.marker });
|
||||
}
|
||||
|
||||
// Every exoplanet in a system shares the same line of sight, so the frame is built once.
|
||||
@@ -479,28 +256,27 @@ export class SystemOrbitsRenderer {
|
||||
continue;
|
||||
}
|
||||
const elements = resolveOrbitalElements(exoplanet.orbit);
|
||||
const radiusEarth = exoplanet.radiusEarth ?? radiusFromMassEarth(exoplanet.massEarth);
|
||||
const radiusKm = radiusEarth ? radiusEarth * EARTH_RADIUS_KM : undefined;
|
||||
// Not the Sun's: that assumes a solar-mass host for every system, and most exoplanet hosts
|
||||
// are red dwarfs a fraction of the Sun's mass.
|
||||
const radiusKm = exoplanet.radiusEarth ? exoplanet.radiusEarth * EARTH_RADIUS_KM : undefined;
|
||||
// Not `gmForParent(undefined)`: that assumes a solar-mass host for every system, and
|
||||
// most exoplanet hosts are red dwarfs a fraction of the Sun's mass.
|
||||
const gm = resolveGravitationalParameter({
|
||||
semiMajorAxisAu: exoplanet.orbit.semiMajorAxisAu,
|
||||
periodDays: exoplanet.periodDays,
|
||||
hostStarMassSolar: exoplanet.hostStarMassSolar
|
||||
});
|
||||
const tracked = this.addTopLevelBody(exoplanet.id, 'exoplanet', elements, keplerRates(elements.semiMajorAxisAu, gm), radiusKm, exoplanetFrame, appearanceForExoplanet(exoplanet, hostLuminositySolar));
|
||||
const tracked = this.addTopLevelBody(exoplanet.id, 'exoplanet', elements, gm, radiusKm, exoplanetFrame, appearanceForExoplanet(exoplanet, hostLuminositySolar));
|
||||
members.push({ id: exoplanet.id, kind: 'exoplanet', marker: tracked.marker });
|
||||
}
|
||||
|
||||
this.members = members;
|
||||
|
||||
// Which plane the system is read against follows from where its elements came from. Only the
|
||||
// Sun has JPL bodies and no system has both, so this is a choice between the two rather
|
||||
// Sun has Horizons bodies and no system has both, so this is a choice between the two rather
|
||||
// than a compromise: the ecliptic if there are solar-system bodies, the sky plane otherwise.
|
||||
this.referenceFrame = bodies.some((body) => !body.parentBodyId) ? ECLIPTIC_FRAME.clone() : exoplanetFrame;
|
||||
|
||||
const rings = systemGridRingsAu(this.maxTopLevelSemiMajorAxisAu);
|
||||
this.outermostRadiusAu = Math.max(rings.length > 0 ? rings[rings.length - 1] : 0, ...topLevelOrbits.map(({ axis, eccentricity }) => axis * (1 + eccentricity)));
|
||||
this.gridOuterRadiusAu = rings.length > 0 ? rings[rings.length - 1] : 0;
|
||||
if (rings.length > 0) {
|
||||
this.grid = new PolarGridPlane({
|
||||
ringRadii: rings,
|
||||
@@ -523,30 +299,14 @@ export class SystemOrbitsRenderer {
|
||||
|
||||
this.object.add(this.grid.object, this.tethers.object);
|
||||
}
|
||||
// The star lights its own system. The star marker itself is unlit — it is the source, not a
|
||||
// surface — so nothing here changes how it is drawn.
|
||||
this.object.add(starLight());
|
||||
}
|
||||
|
||||
/**
|
||||
* Recomputes every marker's position for the given Julian date, UTC as the map's clock gives it:
|
||||
* the orbits are taken at its TDB, as the spins are. Call once per tick.
|
||||
*/
|
||||
/** Recomputes every marker's position for the given Julian date. Call once per tick. */
|
||||
update(epochJd: number): void {
|
||||
this.showNextPhotograph();
|
||||
const jdTdb = tdbFromUtc(epochJd);
|
||||
for (const body of this.topLevelBodies) {
|
||||
const current = meanElementsAt(body.elements, body.rates, jdTdb);
|
||||
const orbital = positionAtEpoch(current);
|
||||
const orbital = propagateOrbit(body.elements, body.gmAu3PerDay2, epochJd);
|
||||
body.position.set(orbital.x, orbital.y, orbital.z).applyQuaternion(body.frame);
|
||||
body.marker.position.copy(body.position);
|
||||
orientOrbit(body.orbitLine.quaternion, current, body.frame);
|
||||
reshapeOrbitLine(body.orbitLine, current);
|
||||
if (body.rotationalElements) {
|
||||
bodyOrientation(body.rotationalElements, epochJd, body.marker.quaternion, body.id === 'earth');
|
||||
} else if (body.rotationPeriodHours) {
|
||||
body.marker.quaternion.copy(spinFor(current, body.frame, body.rotationPeriodHours, jdTdb - body.elements.epochJd));
|
||||
}
|
||||
}
|
||||
|
||||
for (const moon of this.moons) {
|
||||
@@ -555,23 +315,8 @@ export class SystemOrbitsRenderer {
|
||||
continue;
|
||||
}
|
||||
moon.pivot.position.copy(parent.position);
|
||||
const current = meanElementsAt(moon.elements, moon.rates, jdTdb);
|
||||
const orbital = positionAtEpoch(current);
|
||||
const orbital = propagateOrbit(moon.elements, moon.gmAu3PerDay2, epochJd);
|
||||
moon.marker.position.set(orbital.x, orbital.y, orbital.z).applyQuaternion(moon.frame);
|
||||
orientOrbit(moon.orbitLine.quaternion, current, moon.frame);
|
||||
if (moon.barycentre) {
|
||||
// The planet's elements place the pair's barycentre, which is where the pivot is: the
|
||||
// planet sits the moon's share of their separation back from it, the moon the rest out.
|
||||
const { massRatio, parentOrbitLine } = moon.barycentre;
|
||||
parent.marker.position.copy(parent.position).addScaledVector(moon.marker.position, -massRatio / (1 + massRatio));
|
||||
moon.marker.position.multiplyScalar(1 / (1 + massRatio));
|
||||
parentOrbitLine.quaternion.copy(moon.orbitLine.quaternion);
|
||||
}
|
||||
if (moon.rotationalElements) {
|
||||
bodyOrientation(moon.rotationalElements, epochJd, moon.marker.quaternion);
|
||||
} else if (moon.rotationPeriodHours) {
|
||||
moon.marker.quaternion.copy(spinFor(current, moon.frame, moon.rotationPeriodHours, jdTdb - moon.elements.epochJd));
|
||||
}
|
||||
}
|
||||
|
||||
// Moons are left out: their tether would land within a marker's width of their planet's and
|
||||
@@ -579,24 +324,9 @@ export class SystemOrbitsRenderer {
|
||||
this.tethers?.setTargets(this.tetherPoints);
|
||||
}
|
||||
|
||||
/** Puts the first photograph that has loaded on its body: one texture for the GPU a frame. */
|
||||
private showNextPhotograph(): void {
|
||||
const index = this.photographsToShow.findIndex(({ texture }) => texture.image);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
const [{ material, texture }] = this.photographsToShow.splice(index, 1);
|
||||
material.map = texture;
|
||||
material.color.set(0xffffff);
|
||||
material.needsUpdate = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up which system member a marker object belongs to (e.g. from a raycast hit), or a part
|
||||
* of one: a ray through Saturn's rings picks Saturn.
|
||||
*/
|
||||
/** Looks up which system member a marker object belongs to (e.g. from a raycast hit). */
|
||||
memberForObject(object: THREE.Object3D): SystemMember | undefined {
|
||||
return this.members.find((member) => member.marker === object || member.marker === object.parent);
|
||||
return this.members.find((member) => member.marker === object);
|
||||
}
|
||||
|
||||
/** All marker objects, for raycasting. */
|
||||
@@ -620,15 +350,10 @@ export class SystemOrbitsRenderer {
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
clearTimeout(this.surfaceTimer);
|
||||
this.surfacesToPaint.length = 0;
|
||||
this.photographsToShow.length = 0;
|
||||
this.grid?.dispose();
|
||||
this.tethers?.dispose();
|
||||
for (const { geometry, material } of this.disposables) {
|
||||
if (geometry !== MARKER_SPHERE) {
|
||||
geometry.dispose();
|
||||
}
|
||||
geometry.dispose();
|
||||
material.dispose();
|
||||
}
|
||||
// Detach as well as dispose. A star-to-star hop builds a new renderer and drops the old
|
||||
@@ -643,19 +368,18 @@ export class SystemOrbitsRenderer {
|
||||
id: string,
|
||||
kind: SystemMemberKind,
|
||||
elements: OrbitalElements,
|
||||
rates: MeanElementRates,
|
||||
gmAu3PerDay2: number,
|
||||
radiusKm: number | undefined,
|
||||
frame: THREE.Quaternion,
|
||||
appearance?: PlanetAppearance,
|
||||
rotation?: { periodHours?: number; elements?: RotationalElements }
|
||||
appearance?: PlanetAppearance
|
||||
): TrackedTopLevelBody {
|
||||
const orbitLine = buildOrbitLine(elements, kind, frame);
|
||||
const marker = buildMarker(id, kind, radiusKm, appearance, this.deferSurface, this.deferPhotograph);
|
||||
const marker = buildMarker(kind, radiusKm, this.maxTopLevelSemiMajorAxisAu, appearance);
|
||||
this.object.add(orbitLine, marker);
|
||||
this.trackDisposable(orbitLine.geometry, orbitLine.material as THREE.Material);
|
||||
this.trackDisposable(marker.geometry, marker.material as THREE.Material);
|
||||
|
||||
const tracked: TrackedTopLevelBody = { id, kind, elements, rates, marker, orbitLine, frame, position: new THREE.Vector3(), rotationPeriodHours: rotation?.periodHours, rotationalElements: rotation?.elements };
|
||||
const tracked: TrackedTopLevelBody = { id, kind, elements, gmAu3PerDay2, marker, frame, position: new THREE.Vector3() };
|
||||
this.topLevelBodies.push(tracked);
|
||||
return tracked;
|
||||
}
|
||||
@@ -663,36 +387,21 @@ export class SystemOrbitsRenderer {
|
||||
private addMoon(
|
||||
id: string,
|
||||
elements: OrbitalElements,
|
||||
rates: MeanElementRates,
|
||||
gmAu3PerDay2: number,
|
||||
radiusKm: number | undefined,
|
||||
parent: TrackedTopLevelBody,
|
||||
frame: THREE.Quaternion,
|
||||
appearance?: PlanetAppearance,
|
||||
rotation?: { periodHours?: number; elements?: RotationalElements },
|
||||
massRatio?: number
|
||||
appearance?: PlanetAppearance
|
||||
): TrackedMoon {
|
||||
const pivot = new THREE.Group();
|
||||
const orbitLine = buildOrbitLine(elements, 'moon', frame);
|
||||
const marker = buildMarker(id, 'moon', radiusKm, appearance, this.deferSurface, this.deferPhotograph);
|
||||
const marker = buildMarker('moon', radiusKm, this.maxTopLevelSemiMajorAxisAu, appearance);
|
||||
pivot.add(orbitLine, marker);
|
||||
this.object.add(pivot);
|
||||
this.trackDisposable(orbitLine.geometry, orbitLine.material as THREE.Material);
|
||||
this.trackDisposable(marker.geometry, marker.material as THREE.Material);
|
||||
|
||||
let barycentre: TrackedMoon['barycentre'];
|
||||
if (massRatio !== undefined) {
|
||||
// Both orbits are the relative one, scaled: the moon's by the planet's share of the mass,
|
||||
// the planet's by the moon's share and turned half round, since it is always opposite.
|
||||
// Charon's then spans 17 460 km of radius, Pluto's 2 131, and neither passes through Pluto.
|
||||
orbitLine.scale.setScalar(1 / (1 + massRatio));
|
||||
const parentOrbitLine = buildOrbitLine(elements, parent.kind, frame);
|
||||
parentOrbitLine.scale.setScalar(-massRatio / (1 + massRatio));
|
||||
pivot.add(parentOrbitLine);
|
||||
this.trackDisposable(parentOrbitLine.geometry, parentOrbitLine.material as THREE.Material);
|
||||
barycentre = { massRatio, parentOrbitLine };
|
||||
}
|
||||
|
||||
const moon: TrackedMoon = { id, elements, rates, marker, orbitLine, frame, pivot, parentId: parent.id, rotationPeriodHours: rotation?.periodHours, rotationalElements: rotation?.elements, barycentre };
|
||||
const moon: TrackedMoon = { id, elements, gmAu3PerDay2, marker, frame, pivot, parentId: parent.id };
|
||||
this.moons.push(moon);
|
||||
return moon;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { Router } from '@angular/router';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { DataLoaderService } from '../../core/data/data-loader.service';
|
||||
import { BookmarksStore } from '../../shared/state/bookmarks.store';
|
||||
import { TimeStore } from '../../shared/state/time.store';
|
||||
import { DEFAULT_HUD_DISPLAY, HudDisplay, HudDockComponent } from './hud-dock.component';
|
||||
|
||||
// jsdom has no matchMedia, which the dock reads once, at import: this one answers from `viewport`.
|
||||
const viewport = vi.hoisted(() => {
|
||||
const state = { wide: true };
|
||||
window.matchMedia = (() => ({ get matches() { return state.wide; } })) as unknown as typeof window.matchMedia;
|
||||
return state;
|
||||
});
|
||||
|
||||
class EmptyDataLoaderService {
|
||||
loadStars() {
|
||||
return Promise.resolve({ stars: [], positions: new Float32Array(0) });
|
||||
@@ -84,17 +76,6 @@ describe('HudDockComponent', () => {
|
||||
expect(tabNames()).toEqual(['Search', 'Readout', 'Routes', 'Bookmarks', 'Display']);
|
||||
});
|
||||
|
||||
it('offers the clock alone, as a Clock tab, to a surface with no layers', () => {
|
||||
fixture.componentRef.setInput('clock', true);
|
||||
fixture.componentRef.setInput('defaultTab', 'display');
|
||||
fixture.detectChanges();
|
||||
expect(tabNames()).toEqual(['Search', 'Bookmarks', 'Clock']);
|
||||
const panel = host().querySelector('#dock-panel-display')!;
|
||||
expect(panel.querySelector('[role="radiogroup"][aria-label="Clock rate"]')).not.toBeNull();
|
||||
expect(panel.querySelector('#clock-date')).not.toBeNull();
|
||||
expect(panel.textContent).not.toContain('Layers');
|
||||
});
|
||||
|
||||
it('opens the default tab on mount and renders the readout from its inputs', () => {
|
||||
setReadout();
|
||||
fixture.componentRef.setInput('defaultTab', 'readout');
|
||||
@@ -160,7 +141,7 @@ describe('HudDockComponent', () => {
|
||||
fixture.componentRef.setInput('defaultTab', 'display');
|
||||
fixture.detectChanges();
|
||||
const pressed = [...host().querySelectorAll('[aria-pressed]')].map((b) => `${b.textContent?.trim()}=${b.getAttribute('aria-pressed')}`);
|
||||
expect(pressed).toEqual(['Labels=true', 'Orbits=true', 'Grid=false', 'Deep sky=true', 'Sky=true', 'Systems=true', 'Jump links=false', 'Plan view=false', 'Backwards=false']);
|
||||
expect(pressed).toEqual(['Labels=true', 'Orbits=true', 'Grid=false', 'Deep sky=true', 'Sky=true', 'Systems=true', 'Jump links=false', 'Plan view=false']);
|
||||
});
|
||||
|
||||
it('says how to keep a place, rather than showing an empty list', () => {
|
||||
@@ -385,168 +366,4 @@ describe('HudDockComponent', () => {
|
||||
expect(host().querySelector<HTMLInputElement>('#route-to')!.value).toBe('Sirius');
|
||||
expect(host().querySelector<HTMLInputElement>('#route-range')!.value).toBe('6');
|
||||
});
|
||||
|
||||
describe('clock', () => {
|
||||
let time: TimeStore;
|
||||
|
||||
beforeEach(() => {
|
||||
time = TestBed.inject(TimeStore);
|
||||
fixture.componentRef.setInput('display', DEFAULT_HUD_DISPLAY);
|
||||
fixture.componentRef.setInput('defaultTab', 'display');
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
function button(name: string): HTMLButtonElement {
|
||||
return [...host().querySelectorAll<HTMLButtonElement>('#dock-panel-display button')].find((b) => b.textContent?.trim() === name)!;
|
||||
}
|
||||
|
||||
function radio(name: string): HTMLInputElement {
|
||||
return [...host().querySelectorAll('#dock-panel-display label')].find((l) => l.textContent?.trim() === name)!.querySelector('input')!;
|
||||
}
|
||||
|
||||
it('runs the same rates backwards, and keeps the direction when the rate changes', () => {
|
||||
button('Backwards').click();
|
||||
fixture.detectChanges();
|
||||
expect(time.rate()).toBe(-1);
|
||||
expect(button('Backwards').getAttribute('aria-pressed')).toBe('true');
|
||||
// Still real time: the direction is not a fifth rate.
|
||||
expect(radio('Real time').checked).toBe(true);
|
||||
|
||||
radio('1 d/s').click();
|
||||
fixture.detectChanges();
|
||||
expect(time.rate()).toBe(-86_400);
|
||||
expect(radio('1 d/s').checked).toBe(true);
|
||||
|
||||
button('Backwards').click();
|
||||
fixture.detectChanges();
|
||||
expect(time.rate()).toBe(86_400);
|
||||
expect(button('Backwards').getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
it('opens the date field on the clock’s date, named and held to the window the elements hold for', () => {
|
||||
const field = host().querySelector<HTMLInputElement>('#clock-date')!;
|
||||
|
||||
expect(field.type).toBe('datetime-local');
|
||||
expect(field.value).toBe(time.date().toISOString().slice(0, 16));
|
||||
expect(host().querySelector('label[for="clock-date"]')?.textContent?.trim()).toBe('Date (UTC)');
|
||||
expect(field.min).toBe('0001-01-01T00:00');
|
||||
expect(field.max).toBe('3000-01-01T00:00');
|
||||
expect(host().querySelector(`#${field.getAttribute('aria-describedby')}`)?.textContent).toContain('AD 1 to AD 3000');
|
||||
});
|
||||
|
||||
it('jumps the clock to the date submitted, read as UTC', () => {
|
||||
// Five and a half hours from UTC, so a field read as local time lands elsewhere: in UTC itself,
|
||||
// where CI runs, the two readings are the same instant and this could not tell them apart.
|
||||
vi.stubEnv('TZ', 'Asia/Kolkata');
|
||||
const field = host().querySelector<HTMLInputElement>('#clock-date')!;
|
||||
field.value = '2020-12-21T18:00';
|
||||
button('Go').click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(time.date().toISOString().slice(0, 16)).toBe('2020-12-21T18:00');
|
||||
expect(time.atNow()).toBe(false);
|
||||
|
||||
// Back to now puts the field back on the present too, not on the date left behind.
|
||||
button('Back to now').click();
|
||||
fixture.detectChanges();
|
||||
expect(time.atNow()).toBe(true);
|
||||
expect(host().querySelector<HTMLInputElement>('#clock-date')!.value).toBe(time.date().toISOString().slice(0, 16));
|
||||
});
|
||||
|
||||
it('folds the sheet away on a phone once a date is set, so the system it covered can be seen', () => {
|
||||
viewport.wide = false;
|
||||
try {
|
||||
host().querySelector<HTMLInputElement>('#clock-date')!.value = '2020-12-21T18:00';
|
||||
button('Go').click();
|
||||
fixture.detectChanges();
|
||||
expect(host().querySelector('#dock-panel-display')).toBeNull();
|
||||
} finally {
|
||||
viewport.wide = true;
|
||||
}
|
||||
});
|
||||
|
||||
it('hands focus to the tab that folded, not to the page, so Enter opens the panel again', () => {
|
||||
viewport.wide = false;
|
||||
try {
|
||||
const field = host().querySelector<HTMLInputElement>('#clock-date')!;
|
||||
field.focus();
|
||||
field.value = '2020-12-21T18:00';
|
||||
button('Go').click();
|
||||
fixture.detectChanges();
|
||||
expect(document.activeElement?.id).toBe('dock-tab-display');
|
||||
} finally {
|
||||
viewport.wide = true;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the date strip on screen on a phone: the tabs give way to it, and scroll', () => {
|
||||
// At 360 px the system view's five tabs take 397 px, and pushed the strip past the right
|
||||
// edge, where nothing scrolls: after Go on a phone the date was nowhere on screen.
|
||||
fixture.componentRef.setInput('date', '2020-12-21');
|
||||
fixture.componentRef.setInput('range', '417 AU');
|
||||
fixture.detectChanges();
|
||||
const tabs = host().querySelector('[role="tablist"]')!.classList;
|
||||
expect(tabs.contains('min-w-0') && tabs.contains('overflow-x-auto')).toBe(true);
|
||||
// Its own scrollbar, where the browser draws one, thin and dark: a desktop's default was a
|
||||
// light bar 15 px tall across the dock.
|
||||
expect(tabs.contains('scheme-dark') && tabs.contains('[scrollbar-width:thin]')).toBe(true);
|
||||
expect(host().querySelector('[data-testid="hud-date"]')!.classList.contains('shrink-0')).toBe(true);
|
||||
// The range keeps its width where it is shown, or '417 AU' wraps and the row grows 20 px; on a
|
||||
// phone it is not shown, where at the present it took the Display tab out of sight.
|
||||
const range = [...host().querySelectorAll('p')].find((p) => p.textContent?.includes('Range'))!.classList;
|
||||
expect(range.contains('shrink-0') && range.contains('max-sm:hidden')).toBe(true);
|
||||
});
|
||||
|
||||
it('brings the tab that matters back into view once the date strip has narrowed the tabs', () => {
|
||||
// jsdom lays nothing out; what is checked is which tab is asked to be in view, and when.
|
||||
const scrolled: string[] = [];
|
||||
HTMLElement.prototype.scrollIntoView = function (this: HTMLElement) {
|
||||
scrolled.push(this.id);
|
||||
};
|
||||
try {
|
||||
// On a phone: the tab focus went back to, which after Go sat wholly out of sight.
|
||||
viewport.wide = false;
|
||||
host().querySelector<HTMLInputElement>('#clock-date')!.value = '2020-12-21T18:00';
|
||||
button('Go').click();
|
||||
fixture.detectChanges();
|
||||
scrolled.length = 0;
|
||||
fixture.componentRef.setInput('date', '2020-12-21');
|
||||
fixture.detectChanges();
|
||||
expect(scrolled).toEqual(['dock-tab-display']);
|
||||
// On a wider window, where the panel stays open: its tab, focus being in the panel.
|
||||
viewport.wide = true;
|
||||
fixture.componentRef.setInput('date', '');
|
||||
fixture.detectChanges();
|
||||
tab('Display').click();
|
||||
fixture.detectChanges();
|
||||
host().querySelector<HTMLInputElement>('#clock-date')!.focus();
|
||||
scrolled.length = 0;
|
||||
fixture.componentRef.setInput('date', '2020-12-21');
|
||||
fixture.detectChanges();
|
||||
expect(scrolled).toEqual(['dock-tab-display']);
|
||||
} finally {
|
||||
viewport.wide = true;
|
||||
delete (HTMLElement.prototype as Partial<HTMLElement>).scrollIntoView;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the panel open on a wide screen, where it covers little of the scene', () => {
|
||||
host().querySelector<HTMLInputElement>('#clock-date')!.value = '2020-12-21T18:00';
|
||||
button('Go').click();
|
||||
fixture.detectChanges();
|
||||
expect(host().querySelector('#dock-panel-display')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('fills the date field again with the clock’s date when the panel is opened again', () => {
|
||||
time.setDate(new Date('2020-12-21T18:00Z'));
|
||||
fixture.componentInstance.toggleTab('display');
|
||||
fixture.detectChanges();
|
||||
fixture.componentInstance.toggleTab('display');
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(host().querySelector<HTMLInputElement>('#clock-date')!.value).toBe('2020-12-21T18:00');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,28 +1,9 @@
|
||||
import {
|
||||
afterRenderEffect,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
ElementRef,
|
||||
HostListener,
|
||||
inject,
|
||||
input,
|
||||
OnInit,
|
||||
output,
|
||||
signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { ChangeDetectionStrategy, Component, computed, ElementRef, HostListener, inject, input, OnInit, output, signal, viewChild } from '@angular/core';
|
||||
|
||||
import { Bookmark, BookmarksStore } from '../../shared/state/bookmarks.store';
|
||||
import { CLOCK_WINDOW, TIME_RATES, TimeStore } from '../../shared/state/time.store';
|
||||
import { BookmarkIconComponent } from '../../shared/ui/bookmark-icon.component';
|
||||
import { SearchComponent } from '../search/search.component';
|
||||
import {
|
||||
RouteRequest,
|
||||
RouteResult,
|
||||
RoutesPanelComponent,
|
||||
RouteStarOption,
|
||||
} from './routes-panel.component';
|
||||
import { RouteRequest, RouteResult, RoutesPanelComponent, RouteStarOption } from './routes-panel.component';
|
||||
|
||||
export interface HudReadout {
|
||||
readonly label: string;
|
||||
@@ -50,16 +31,7 @@ export interface HudDisplay {
|
||||
readonly plan: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_HUD_DISPLAY: HudDisplay = {
|
||||
labels: true,
|
||||
orbits: true,
|
||||
grid: true,
|
||||
deepSky: true,
|
||||
sky: true,
|
||||
systems: true,
|
||||
jumpLinks: false,
|
||||
plan: false,
|
||||
};
|
||||
export const DEFAULT_HUD_DISPLAY: HudDisplay = { labels: true, orbits: true, grid: true, deepSky: true, sky: true, systems: true, jumpLinks: false, plan: false };
|
||||
|
||||
const DISPLAY_LAYERS: readonly { key: keyof HudDisplay; label: string }[] = [
|
||||
{ key: 'labels', label: 'Labels' },
|
||||
@@ -69,26 +41,17 @@ const DISPLAY_LAYERS: readonly { key: keyof HudDisplay; label: string }[] = [
|
||||
{ key: 'sky', label: 'Sky' },
|
||||
{ key: 'systems', label: 'Systems' },
|
||||
{ key: 'jumpLinks', label: 'Jump links' },
|
||||
{ key: 'plan', label: 'Plan view' },
|
||||
{ key: 'plan', label: 'Plan view' }
|
||||
];
|
||||
|
||||
export type DockTab = 'search' | 'readout' | 'routes' | 'bookmarks' | 'display';
|
||||
|
||||
const TAB_LABELS: Record<DockTab, string> = {
|
||||
search: 'Search',
|
||||
readout: 'Readout',
|
||||
routes: 'Routes',
|
||||
bookmarks: 'Bookmarks',
|
||||
display: 'Display',
|
||||
};
|
||||
const TAB_LABELS: Record<DockTab, string> = { search: 'Search', readout: 'Readout', routes: 'Routes', bookmarks: 'Bookmarks', display: 'Display' };
|
||||
|
||||
/** Tailwind's `sm` breakpoint: below it the dock is a bare tab strip and its panel is a sheet. */
|
||||
const WIDE_VIEWPORT = '(min-width: 640px)';
|
||||
/** One live query, read on every pointer-down, rather than a new MediaQueryList per read. */
|
||||
const wideViewportQuery =
|
||||
typeof window !== 'undefined' && typeof window.matchMedia === 'function'
|
||||
? window.matchMedia(WIDE_VIEWPORT)
|
||||
: null;
|
||||
const wideViewportQuery = typeof window !== 'undefined' && typeof window.matchMedia === 'function' ? window.matchMedia(WIDE_VIEWPORT) : null;
|
||||
|
||||
function isWideViewport(): boolean {
|
||||
return wideViewportQuery?.matches ?? true;
|
||||
@@ -111,10 +74,7 @@ function isWideViewport(): boolean {
|
||||
selector: 'app-hud-dock',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [BookmarkIconComponent, RoutesPanelComponent, SearchComponent],
|
||||
host: {
|
||||
class:
|
||||
'pointer-events-none fixed inset-x-2 bottom-2 z-20 block font-body sm:inset-x-6 sm:bottom-6',
|
||||
},
|
||||
host: { class: 'pointer-events-none fixed inset-x-2 bottom-2 z-20 block font-body sm:inset-x-6 sm:bottom-6' },
|
||||
template: `
|
||||
<!-- The column is transparent to the pointer and each surface in it opts back in: it is as
|
||||
wide as the strip and as tall as the open panel, so a solid one would swallow every
|
||||
@@ -125,55 +85,29 @@ function isWideViewport(): boolean {
|
||||
locking on, once per switch, never per keystroke. -->
|
||||
@switch (tab) {
|
||||
@case ('search') {
|
||||
<section
|
||||
id="dock-panel-search"
|
||||
role="tabpanel"
|
||||
aria-labelledby="dock-tab-search"
|
||||
class="hud-acquire pointer-events-auto mb-2 w-full max-w-xl"
|
||||
>
|
||||
<section id="dock-panel-search" role="tabpanel" aria-labelledby="dock-tab-search" class="hud-acquire pointer-events-auto mb-2 w-full max-w-xl">
|
||||
<app-search (picked)="onPicked()" />
|
||||
</section>
|
||||
}
|
||||
@case ('readout') {
|
||||
<section
|
||||
id="dock-panel-readout"
|
||||
role="tabpanel"
|
||||
aria-labelledby="dock-tab-readout"
|
||||
class="hud-acquire hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-lg px-4 py-3"
|
||||
>
|
||||
<section id="dock-panel-readout" role="tabpanel" aria-labelledby="dock-tab-readout" class="hud-acquire hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-lg px-4 py-3">
|
||||
<p class="type-label text-muted">{{ eyebrow() }}</p>
|
||||
<div class="mt-1 flex items-start gap-2">
|
||||
<p
|
||||
data-testid="hud-title"
|
||||
class="min-w-0 flex-1 text-lg font-bold tracking-[0.04em] text-text uppercase"
|
||||
>
|
||||
{{ title() }}
|
||||
</p>
|
||||
<p data-testid="hud-title" class="min-w-0 flex-1 text-lg font-bold tracking-[0.04em] text-text uppercase">{{ title() }}</p>
|
||||
<!-- Against null, not against falsiness: the Sun's catalogue id is 0, and a
|
||||
truthiness test is what would quietly make the Solar System the one
|
||||
system nobody could keep. -->
|
||||
@if (keepableStarId() !== null) {
|
||||
<button
|
||||
type="button"
|
||||
[attr.aria-label]="
|
||||
(bookmarks.has('star', keepableStarId()!) ? 'Forget ' : 'Keep ') + title()
|
||||
"
|
||||
[attr.aria-pressed]="bookmarks.has('star', keepableStarId()!)"
|
||||
(click)="
|
||||
bookmarks.toggle({ kind: 'star', id: keepableStarId()!, name: title() })
|
||||
"
|
||||
class="shrink-0 p-1 transition-colors focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
[class]="
|
||||
bookmarks.has('star', keepableStarId()!)
|
||||
? 'text-accent'
|
||||
: 'text-muted hover:text-accent'
|
||||
"
|
||||
>
|
||||
<app-bookmark-icon
|
||||
class="h-3.5 w-3.5"
|
||||
[kept]="bookmarks.has('star', keepableStarId()!)"
|
||||
/>
|
||||
</button>
|
||||
type="button"
|
||||
[attr.aria-label]="(bookmarks.has('star', keepableStarId()!) ? 'Forget ' : 'Keep ') + title()"
|
||||
[attr.aria-pressed]="bookmarks.has('star', keepableStarId()!)"
|
||||
(click)="bookmarks.toggle({ kind: 'star', id: keepableStarId()!, name: title() })"
|
||||
class="shrink-0 p-1 transition-colors focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
[class]="bookmarks.has('star', keepableStarId()!) ? 'text-accent' : 'text-muted hover:text-accent'"
|
||||
>
|
||||
<app-bookmark-icon class="h-3.5 w-3.5" [kept]="bookmarks.has('star', keepableStarId()!)" />
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@if (subtitle()) {
|
||||
@@ -183,54 +117,30 @@ function isWideViewport(): boolean {
|
||||
<dl class="mt-3 flex flex-wrap gap-x-6 gap-y-1">
|
||||
@for (readout of readouts(); track readout.label) {
|
||||
<div>
|
||||
<dt class="type-label text-muted">
|
||||
{{ readout.label }}
|
||||
@if (readout.derived) {
|
||||
<span class="text-accent/80" aria-hidden="true">*</span>
|
||||
}
|
||||
</dt>
|
||||
<dt class="type-label text-muted">{{ readout.label }}@if (readout.derived) {<span class="text-accent/80" aria-hidden="true">*</span>}</dt>
|
||||
<dd class="mt-0.5 text-sm text-text tabular-nums">{{ readout.value }}</dd>
|
||||
</div>
|
||||
}
|
||||
</dl>
|
||||
}
|
||||
@if (note() || hasDerived()) {
|
||||
<p
|
||||
class="mt-3 border-t border-border/40 pt-2 text-[10px] leading-relaxed text-muted"
|
||||
>
|
||||
@if (hasDerived()) {
|
||||
<span class="text-accent/80">*</span> Derived, not catalogued.
|
||||
}
|
||||
{{ note() }}
|
||||
</p>
|
||||
<p class="mt-3 border-t border-border/40 pt-2 text-[10px] leading-relaxed text-muted">@if (hasDerived()) {<span class="text-accent/80">*</span> Derived, not catalogued. }{{ note() }}</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
@case ('bookmarks') {
|
||||
<section
|
||||
id="dock-panel-bookmarks"
|
||||
role="tabpanel"
|
||||
aria-labelledby="dock-tab-bookmarks"
|
||||
class="hud-acquire hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-lg"
|
||||
>
|
||||
<section id="dock-panel-bookmarks" role="tabpanel" aria-labelledby="dock-tab-bookmarks" class="hud-acquire hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-lg">
|
||||
@if (bookmarks.bookmarks().length) {
|
||||
<ul class="max-h-64 divide-y divide-border/25 overflow-y-auto">
|
||||
@for (
|
||||
bookmark of bookmarks.bookmarks();
|
||||
track bookmark.kind + ':' + bookmark.id
|
||||
) {
|
||||
@for (bookmark of bookmarks.bookmarks(); track bookmark.kind + ':' + bookmark.id) {
|
||||
<li class="flex items-stretch">
|
||||
<button
|
||||
type="button"
|
||||
(click)="onBookmarkChosen(bookmark)"
|
||||
class="flex min-w-0 flex-1 items-baseline gap-3 px-3 py-2 text-left transition-colors hover:bg-accent/8 focus-visible:bg-accent/12 focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate text-sm text-text">{{
|
||||
bookmark.name
|
||||
}}</span>
|
||||
<span class="type-label shrink-0 text-muted">{{
|
||||
bookmark.kind === 'star' ? 'System' : 'Body'
|
||||
}}</span>
|
||||
<span class="min-w-0 flex-1 truncate text-sm text-text">{{ bookmark.name }}</span>
|
||||
<span class="type-label shrink-0 text-muted">{{ bookmark.kind === 'star' ? 'System' : 'Body' }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -238,15 +148,7 @@ function isWideViewport(): boolean {
|
||||
(click)="bookmarks.remove(bookmark.kind, bookmark.id)"
|
||||
class="shrink-0 border-l border-border/25 px-3 text-muted transition-colors hover:bg-accent/8 hover:text-accent focus-visible:text-accent focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
>
|
||||
<svg
|
||||
class="h-3 w-3"
|
||||
viewBox="0 0 14 14"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<svg class="h-3 w-3" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true">
|
||||
<path d="M3 3l8 8M11 3l-8 8" />
|
||||
</svg>
|
||||
</button>
|
||||
@@ -255,136 +157,29 @@ function isWideViewport(): boolean {
|
||||
</ul>
|
||||
} @else {
|
||||
<p class="px-3 py-3 text-sm text-muted">
|
||||
Nothing kept yet. The
|
||||
<app-bookmark-icon class="inline-block h-3.5 w-3.5 -mb-0.5 text-accent" /> on a
|
||||
readout or a body keeps it here, in this browser.
|
||||
Nothing kept yet. The <app-bookmark-icon class="inline-block h-3.5 w-3.5 -mb-0.5 text-accent" /> on a readout or a body keeps it here, in this browser.
|
||||
</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
@case ('display') {
|
||||
<section
|
||||
id="dock-panel-display"
|
||||
role="tabpanel"
|
||||
aria-labelledby="dock-tab-display"
|
||||
class="hud-acquire hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-lg px-4 py-3"
|
||||
>
|
||||
@if (display()) {
|
||||
<p class="type-label text-muted">Layers</p>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
@for (layer of layers; track layer.key) {
|
||||
<button
|
||||
type="button"
|
||||
[attr.aria-pressed]="isOn(layer.key)"
|
||||
(click)="toggleLayer(layer.key)"
|
||||
class="type-label flex items-center gap-2 border px-3 py-1.5 transition-colors focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
[class]="
|
||||
isOn(layer.key)
|
||||
? 'border-accent/60 bg-accent/12 text-accent hover:bg-accent/18'
|
||||
: 'border-border/60 text-muted hover:border-border hover:text-text'
|
||||
"
|
||||
>
|
||||
<!-- The state mark: a filled tick when the layer is drawn, hollow when it is not. -->
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="h-1.5 w-1.5 border border-current"
|
||||
[class.bg-current]="isOn(layer.key)"
|
||||
></span>
|
||||
{{ layer.label }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- The clock. Orbits and rotations are both functions of a date, so this is the
|
||||
difference between a still picture and an orrery. -->
|
||||
<p class="type-label text-muted" [class.mt-4]="display()">Clock</p>
|
||||
<!-- Radios rather than buttons: the rates are one-of-four, and the native control
|
||||
carries that to a screen reader and to the arrow keys without any script. -->
|
||||
<div
|
||||
class="mt-2 flex flex-wrap items-center gap-2"
|
||||
role="radiogroup"
|
||||
aria-label="Clock rate"
|
||||
>
|
||||
<!-- A rate is picked by its size and the toggle after the radios says which way it
|
||||
runs, so a month a second backwards is the same radio as forwards. -->
|
||||
@for (rate of timeRates; track rate.secondsPerSecond) {
|
||||
<label
|
||||
class="type-label cursor-pointer border px-3 py-1.5 transition-colors has-[:focus-visible]:outline has-[:focus-visible]:outline-1 has-[:focus-visible]:-outline-offset-1 has-[:focus-visible]:outline-accent"
|
||||
[class]="
|
||||
Math.abs(time.rate()) === rate.secondsPerSecond
|
||||
? 'border-accent/60 bg-accent/12 text-accent hover:bg-accent/18'
|
||||
: 'border-border/60 text-muted hover:border-border hover:text-text'
|
||||
"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="clock-rate"
|
||||
class="sr-only"
|
||||
[value]="rate.secondsPerSecond"
|
||||
[checked]="Math.abs(time.rate()) === rate.secondsPerSecond"
|
||||
(change)="time.setRate(Math.sign(time.rate()) * rate.secondsPerSecond)"
|
||||
/>
|
||||
{{ rate.label }}
|
||||
</label>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
[attr.aria-pressed]="time.rate() < 0"
|
||||
(click)="time.setRate(-time.rate())"
|
||||
class="type-label flex items-center gap-2 border px-3 py-1.5 transition-colors focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
[class]="
|
||||
time.rate() < 0
|
||||
? 'border-accent/60 bg-accent/12 text-accent hover:bg-accent/18'
|
||||
: 'border-border/60 text-muted hover:border-border hover:text-text'
|
||||
"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="h-1.5 w-1.5 border border-current"
|
||||
[class.bg-current]="time.rate() < 0"
|
||||
></span>
|
||||
Backwards
|
||||
</button>
|
||||
@if (!time.atNow()) {
|
||||
<section id="dock-panel-display" role="tabpanel" aria-labelledby="dock-tab-display" class="hud-acquire hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-lg px-4 py-3">
|
||||
<p class="type-label text-muted">Layers</p>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
@for (layer of layers; track layer.key) {
|
||||
<button
|
||||
type="button"
|
||||
(click)="backToNow()"
|
||||
class="type-label border border-border/60 px-3 py-1.5 text-muted transition-colors hover:border-accent/70 hover:text-accent focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
[attr.aria-pressed]="isOn(layer.key)"
|
||||
(click)="toggleLayer(layer.key)"
|
||||
class="type-label flex items-center gap-2 border px-3 py-1.5 transition-colors focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
[class]="isOn(layer.key) ? 'border-accent/60 bg-accent/12 text-accent hover:bg-accent/18' : 'border-border/60 text-muted hover:border-border hover:text-text'"
|
||||
>
|
||||
Back to now
|
||||
<!-- The state mark: a filled tick when the layer is drawn, hollow when it is not. -->
|
||||
<span aria-hidden="true" class="h-1.5 w-1.5 border border-current" [class.bg-current]="isOn(layer.key)"></span>
|
||||
{{ layer.label }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<!-- A form, so Enter in the field goes there and the browser holds the field to its
|
||||
min and max before anything is submitted. Submitted rather than applied on each
|
||||
change: Chrome reports a year typed digit by digit as 0002, 0020, 0202 and 2020,
|
||||
and the sky would jump through every one. -->
|
||||
<form class="mt-2 flex flex-wrap items-center gap-2" (submit)="goToDate($event)">
|
||||
<label for="clock-date" class="type-label text-muted">Date (UTC)</label>
|
||||
<input
|
||||
id="clock-date"
|
||||
name="date"
|
||||
type="datetime-local"
|
||||
required
|
||||
[min]="clockWindow.min"
|
||||
[max]="clockWindow.max"
|
||||
[value]="dateField()"
|
||||
aria-describedby="clock-date-window"
|
||||
class="hud-surface min-w-0 flex-1 px-2.5 py-1 text-sm text-text tabular-nums caret-accent scheme-dark focus:border-accent focus:outline-none sm:flex-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
class="type-label border border-border/60 px-3 py-1.5 text-muted transition-colors hover:border-accent/70 hover:text-accent focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent"
|
||||
>
|
||||
Go
|
||||
</button>
|
||||
<!-- One line: on a phone the panel is a sheet over the system it sets the date of, and
|
||||
each card already says how far its own orbit strays. -->
|
||||
<p id="clock-date-window" class="w-full text-[10px] text-muted">
|
||||
AD 1 to AD 3000, where the planets’ elements hold.
|
||||
</p>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
@@ -395,13 +190,7 @@ function isWideViewport(): boolean {
|
||||
back with what it had, so it is not acquiring anything — and for the 380 ms the wipe
|
||||
runs, its clip path swallows clicks on the suggestions it just brought back. -->
|
||||
@if (routing()) {
|
||||
<section
|
||||
id="dock-panel-routes"
|
||||
role="tabpanel"
|
||||
aria-labelledby="dock-tab-routes"
|
||||
[hidden]="activeTab() !== 'routes'"
|
||||
class="hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-xl px-4 py-3"
|
||||
>
|
||||
<section id="dock-panel-routes" role="tabpanel" aria-labelledby="dock-tab-routes" [hidden]="activeTab() !== 'routes'" class="hud-brackets hud-surface pointer-events-auto mb-2 w-full max-w-xl px-4 py-3">
|
||||
<app-routes-panel
|
||||
[result]="routeResult()"
|
||||
[pending]="routePending()"
|
||||
@@ -416,15 +205,7 @@ function isWideViewport(): boolean {
|
||||
}
|
||||
|
||||
<div class="hud-brackets hud-surface pointer-events-auto flex w-full items-stretch">
|
||||
<!-- The tabs give way to the date and the range, and scroll: the five of the system view
|
||||
take 397 px, and on a portrait phone they pushed the date off the right edge. Where
|
||||
the browser draws a scrollbar of its own, it is a thin dark one: on a desktop window
|
||||
under 770 px wide its default was a light bar 15 px tall across the dark dock. -->
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label="Dock"
|
||||
class="flex min-w-0 scheme-dark items-stretch divide-x divide-border/40 overflow-x-auto [scrollbar-width:thin]"
|
||||
>
|
||||
<div role="tablist" aria-label="Dock" class="flex items-stretch divide-x divide-border/40">
|
||||
@for (tab of tabs(); track tab) {
|
||||
<button
|
||||
type="button"
|
||||
@@ -434,41 +215,21 @@ function isWideViewport(): boolean {
|
||||
[attr.aria-controls]="activeTab() === tab ? 'dock-panel-' + tab : null"
|
||||
(click)="toggleTab(tab)"
|
||||
class="type-eyebrow px-3 py-2 transition-colors focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-accent sm:px-4"
|
||||
[class]="
|
||||
activeTab() === tab
|
||||
? 'bg-accent/15 text-accent'
|
||||
: 'text-muted hover:bg-accent/8 hover:text-accent'
|
||||
"
|
||||
[class]="activeTab() === tab ? 'bg-accent/15 text-accent' : 'text-muted hover:bg-accent/8 hover:text-accent'"
|
||||
>
|
||||
{{ tabLabel(tab) }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<!-- Only while the map is away from the present: at the present the date is
|
||||
today's, which the reader's own machine already says. -->
|
||||
@if (date()) {
|
||||
<p
|
||||
class="ml-auto flex shrink-0 items-baseline gap-2 border-l border-border/40 px-3 py-2 sm:px-4"
|
||||
data-testid="hud-date"
|
||||
>
|
||||
<span class="type-label text-muted">Date</span>
|
||||
<span class="text-sm text-accent tabular-nums">{{ date() }}</span>
|
||||
</p>
|
||||
}
|
||||
<!-- Not on a phone, where it never showed before the tabs gave way to it: kept, its 121 px
|
||||
took the Display tab out of sight at the present, the state the map opens in. -->
|
||||
@if (range()) {
|
||||
<p
|
||||
class="flex shrink-0 items-baseline gap-2 border-l border-border/40 px-3 py-2 max-sm:hidden sm:px-4"
|
||||
[class.ml-auto]="!date()"
|
||||
>
|
||||
<p class="ml-auto flex items-baseline gap-2 border-l border-border/40 px-3 py-2 sm:px-4">
|
||||
<span class="type-label text-muted">Range</span>
|
||||
<span class="text-sm text-accent tabular-nums">{{ range() }}</span>
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
`
|
||||
})
|
||||
export class HudDockComponent implements OnInit {
|
||||
/** Readout panel contents. An empty title means there is nothing to read out, and no tab for it. */
|
||||
@@ -480,15 +241,8 @@ export class HudDockComponent implements OnInit {
|
||||
readonly note = input('');
|
||||
/** Camera range, pre-formatted by the scene, which is the only thing that knows the units. */
|
||||
readonly range = input('');
|
||||
/** The date the sky is drawn for; empty while the map is drawn for the present. */
|
||||
readonly date = input('');
|
||||
/**
|
||||
* Layer state; `null` means the surface has no layers to toggle, and no Display tab unless it
|
||||
* has the clock.
|
||||
*/
|
||||
/** Layer state; `null` means the surface has no layers to toggle and no Display tab. */
|
||||
readonly display = input<HudDisplay | null>(null);
|
||||
/** The clock without the layers, for a surface that is drawn at its date: the tab is then "Clock". */
|
||||
readonly clock = input(false);
|
||||
/** Which panel is open on a wide viewport when the dock mounts. */
|
||||
readonly defaultTab = input<DockTab | null>(null);
|
||||
/** Routing: what the scene found, what it offers for the fields, and where the view is. */
|
||||
@@ -517,49 +271,22 @@ export class HudDockComponent implements OnInit {
|
||||
// Always offered, even with nothing in it: it is the only place that says the map can keep
|
||||
// anything at all, and a tab that appears once you already know is a tab that never taught.
|
||||
'bookmarks',
|
||||
...(this.display() || this.clock() ? (['display'] as const) : []),
|
||||
...(this.display() ? (['display'] as const) : [])
|
||||
]);
|
||||
|
||||
readonly activeTab = signal<DockTab | null>(null);
|
||||
|
||||
readonly bookmarks = inject(BookmarksStore);
|
||||
readonly time = inject(TimeStore);
|
||||
readonly timeRates = TIME_RATES;
|
||||
readonly clockWindow = CLOCK_WINDOW;
|
||||
protected readonly Math = Math;
|
||||
/**
|
||||
* What the date field holds when the panel opens: the clock's date at that moment. Not bound to
|
||||
* the running clock, which would rewrite the field under the reader's typing on every render.
|
||||
*/
|
||||
readonly dateField = signal('');
|
||||
|
||||
private readonly search = viewChild(SearchComponent);
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
|
||||
private readonly dateShown = computed(() => this.date() !== '');
|
||||
/**
|
||||
* The tab list gives way to the date strip but keeps its scroll, so once the strip is drawn the
|
||||
* tab that matters can be wholly out of sight: after Go on a phone, the tab focus went back to
|
||||
* (0 of its 79 px at 360, 390 and 412 wide), and on a desktop window 640 to 770 px wide, the tab
|
||||
* of the panel left open. Brought back into view whenever the strip comes or goes: the focused
|
||||
* tab, else the selected one.
|
||||
*/
|
||||
private readonly keepTabInView = afterRenderEffect(() => {
|
||||
this.dateShown();
|
||||
const list = this.host.nativeElement.querySelector('[role="tablist"]');
|
||||
const focused = document.activeElement;
|
||||
const tab = focused && list?.contains(focused) ? focused : list?.querySelector('[aria-selected="true"]');
|
||||
// Optional: jsdom, which the unit tests run in, lays nothing out and has no scrollIntoView.
|
||||
tab?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.activeTab.set(isWideViewport() ? this.defaultTab() : null);
|
||||
this.fillDateField();
|
||||
}
|
||||
|
||||
tabLabel(tab: DockTab): string {
|
||||
return tab === 'display' && !this.display() ? 'Clock' : TAB_LABELS[tab];
|
||||
return TAB_LABELS[tab];
|
||||
}
|
||||
|
||||
isOn(key: keyof HudDisplay): boolean {
|
||||
@@ -568,35 +295,6 @@ export class HudDockComponent implements OnInit {
|
||||
|
||||
toggleTab(tab: DockTab): void {
|
||||
this.activeTab.set(this.activeTab() === tab ? null : tab);
|
||||
this.fillDateField();
|
||||
}
|
||||
|
||||
/** The field's value is read as UTC, which is what the strip and the note print dates in. */
|
||||
goToDate(event: SubmitEvent): void {
|
||||
event.preventDefault();
|
||||
const field = (event.target as HTMLFormElement).elements.namedItem('date') as HTMLInputElement;
|
||||
if (this.time.setDate(new Date(`${field.value}Z`))) {
|
||||
// The field now says what the signal behind it does, so a later reset that fills it with
|
||||
// the present is a change the binding writes back, not one it drops as the same value.
|
||||
this.dateField.set(field.value);
|
||||
// On a phone the sheet covers the system it has just set the date of: at 360 by 640 every
|
||||
// orbit lies behind it. The thing to look at is now the scene, as after a search.
|
||||
// Focus goes back to the tab that folded, not to the page: the form it was in is gone.
|
||||
if (!isWideViewport()) {
|
||||
const tab = this.activeTab();
|
||||
this.activeTab.set(null);
|
||||
this.host.nativeElement.querySelector<HTMLElement>(`#dock-tab-${tab}`)?.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
backToNow(): void {
|
||||
this.time.reset();
|
||||
this.fillDateField();
|
||||
}
|
||||
|
||||
private fillDateField(): void {
|
||||
this.dateField.set(this.time.date().toISOString().slice(0, 16));
|
||||
}
|
||||
|
||||
toggleLayer(key: keyof HudDisplay): void {
|
||||
@@ -633,10 +331,7 @@ export class HudDockComponent implements OnInit {
|
||||
return;
|
||||
}
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (
|
||||
target &&
|
||||
(target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)
|
||||
) {
|
||||
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
@@ -648,11 +343,7 @@ export class HudDockComponent implements OnInit {
|
||||
/** On a narrow viewport the panel is a sheet over the scene: tapping the scene folds it away. */
|
||||
@HostListener('document:pointerdown', ['$event'])
|
||||
onDocumentPointerDown(event: PointerEvent): void {
|
||||
if (
|
||||
this.activeTab() &&
|
||||
!isWideViewport() &&
|
||||
!this.host.nativeElement.contains(event.target as Node)
|
||||
) {
|
||||
if (this.activeTab() && !isWideViewport() && !this.host.nativeElement.contains(event.target as Node)) {
|
||||
this.activeTab.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ const MATCH_SUBSTRING = 1;
|
||||
const NO_MATCH = 0;
|
||||
|
||||
/**
|
||||
* Order for results that match equally well. Solar-system bodies are a few dozen named worlds
|
||||
* Order for results that match equally well. Solar-system bodies are eighteen famous objects
|
||||
* and win ties outright; a star outranks an exoplanet because searching a name like "Proxima"
|
||||
* is usually an attempt to reach the system rather than one particular planet in it.
|
||||
*/
|
||||
|
||||
@@ -34,9 +34,7 @@ const IO: BodyRecord = {
|
||||
argumentOfPeriapsisDeg: 0,
|
||||
meanAnomalyAtEpochDeg: 0,
|
||||
epochJd: 2451545.0
|
||||
},
|
||||
rates: { meanMotionDegPerDay: 203.4889583, longitudeOfAscendingNodeDegPerDay: 0, argumentOfPeriapsisDegPerDay: 0 },
|
||||
orbitSource: 'test'
|
||||
}
|
||||
};
|
||||
|
||||
const PROXIMA_B: ExoplanetRecord = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, computed, ElementRef, output, signal, viewChild } from '@angular/core';
|
||||
import { Component, computed, ElementRef, inject, output, signal, viewChild } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
import { DataLoaderService } from '../../core/data/data-loader.service';
|
||||
@@ -80,6 +80,10 @@ const KIND_LABELS: Record<SearchResultKind, string> = {
|
||||
`
|
||||
})
|
||||
export class SearchComponent {
|
||||
private readonly dataLoader = inject(DataLoaderService);
|
||||
private readonly navigationStore = inject(NavigationStore);
|
||||
private readonly router = inject(Router);
|
||||
|
||||
readonly query = signal('');
|
||||
/** Fires once a result has been chosen and navigation kicked off — the dock uses it to hand
|
||||
* the view back to the readout, since the thing to look at is now the scene, not the box. */
|
||||
@@ -109,11 +113,7 @@ export class SearchComponent {
|
||||
readonly matchTotal = computed(() => this.matches().length);
|
||||
readonly results = computed(() => this.matches().slice(0, MAX_RESULTS));
|
||||
|
||||
constructor(
|
||||
private readonly dataLoader: DataLoaderService,
|
||||
private readonly navigationStore: NavigationStore,
|
||||
private readonly router: Router
|
||||
) {
|
||||
constructor() {
|
||||
void this.buildIndex();
|
||||
}
|
||||
|
||||
|
||||
@@ -5,13 +5,12 @@ import { ExoplanetRecord } from '../models/exoplanet.model';
|
||||
import { appearanceForBody, appearanceForExoplanet, heliocentricDistanceAu } from './body-appearance';
|
||||
import { DEFAULT_EPOCH_JD } from './constants';
|
||||
|
||||
const RATES = { meanMotionDegPerDay: 1, longitudeOfAscendingNodeDegPerDay: 0, argumentOfPeriapsisDegPerDay: 0 };
|
||||
const ORBIT = { eccentricity: 0, inclinationDeg: 0, longitudeOfAscendingNodeDeg: 0, argumentOfPeriapsisDeg: 0, meanAnomalyAtEpochDeg: 0, epochJd: DEFAULT_EPOCH_JD };
|
||||
|
||||
const JUPITER: BodyRecord = { id: 'jupiter', systemStarId: 0, name: 'Jupiter', kind: 'planet', radiusKm: 69911, orbit: { ...ORBIT, semiMajorAxisAu: 5.204 }, rates: RATES, orbitSource: 'test' };
|
||||
const JUPITER: BodyRecord = { id: 'jupiter', systemStarId: 0, name: 'Jupiter', kind: 'planet', radiusKm: 69911, orbit: { ...ORBIT, semiMajorAxisAu: 5.204 } };
|
||||
/** Europa's own orbit is around Jupiter: 671,000 km, which is 0.00449 AU. */
|
||||
const EUROPA: BodyRecord = { id: 'europa', systemStarId: 0, name: 'Europa', kind: 'moon', radiusKm: 1560, parentBodyId: 'jupiter', orbit: { ...ORBIT, semiMajorAxisAu: 0.00449 }, rates: RATES, orbitSource: 'test' };
|
||||
const EARTH: BodyRecord = { id: 'earth', systemStarId: 0, name: 'Earth', kind: 'planet', radiusKm: 6371, orbit: { ...ORBIT, semiMajorAxisAu: 1 }, rates: RATES, orbitSource: 'test' };
|
||||
const EUROPA: BodyRecord = { id: 'europa', systemStarId: 0, name: 'Europa', kind: 'moon', radiusKm: 1560, parentBodyId: 'jupiter', orbit: { ...ORBIT, semiMajorAxisAu: 0.00449 } };
|
||||
const EARTH: BodyRecord = { id: 'earth', systemStarId: 0, name: 'Earth', kind: 'planet', radiusKm: 6371, orbit: { ...ORBIT, semiMajorAxisAu: 1 } };
|
||||
const ORPHAN: BodyRecord = { ...EUROPA, id: 'orphan', parentBodyId: 'nowhere' };
|
||||
|
||||
const BODIES = [JUPITER, EUROPA, EARTH, ORPHAN];
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { tdbFromUtc, ttMinusUtSeconds } from './constants';
|
||||
|
||||
const jd = (year: number, month = 1, day = 1): number => Date.UTC(year, month - 1, day) / 86400000 + 2440587.5;
|
||||
|
||||
describe('ttMinusUtSeconds', () => {
|
||||
it('follows the historical record before 1972: within 1 per cent of Horizons at AD 1, 6 per cent at AD 1000, 0.2 s in 1950', () => {
|
||||
// Horizons' TDB - UT (observer quantity 30) on JD 1721600, 2086455 and 2433282.5.
|
||||
expect(Math.abs(ttMinusUtSeconds(1721600) - 10465.73)).toBeLessThan(105);
|
||||
expect(Math.abs(ttMinusUtSeconds(2086455) - 1658.0)).toBeLessThan(100);
|
||||
expect(Math.abs(ttMinusUtSeconds(2433282.5) - 28.93)).toBeLessThan(0.2);
|
||||
});
|
||||
|
||||
it('counts the leap seconds from 1972, and holds the last from 2017 on', () => {
|
||||
expect(ttMinusUtSeconds(jd(1972, 6, 30))).toBe(42.184);
|
||||
expect(ttMinusUtSeconds(jd(1972, 7, 1))).toBe(43.184);
|
||||
expect(ttMinusUtSeconds(jd(2016, 12, 31))).toBe(68.184);
|
||||
expect(ttMinusUtSeconds(jd(2017, 1, 1))).toBe(69.184);
|
||||
expect(ttMinusUtSeconds(jd(2999, 1, 1))).toBe(69.184);
|
||||
});
|
||||
|
||||
it('joins its polynomials without a jump of more than 0.3 s, the 0.25 s at 1600 the worst', () => {
|
||||
for (const year of [500, 1600, 1700, 1800, 1860, 1900, 1920, 1941, 1961]) {
|
||||
const at = 2451544.5 + (year - 2000) * 365.2425;
|
||||
expect(Math.abs(ttMinusUtSeconds(at + 0.01) - ttMinusUtSeconds(at - 0.01))).toBeLessThan(0.3);
|
||||
}
|
||||
});
|
||||
|
||||
it('hands over from the polynomial to the leap seconds at the start of 1972, 0.07 s apart', () => {
|
||||
// The switch is placed by the calendar, not by a 365.2425-day year, so it is sampled on either
|
||||
// side of midnight; the last day of 1971 must still be the polynomial's 42.25 s, not the table's
|
||||
// 42.184, or the switch has moved earlier; and midnight itself must already be the table's, or it
|
||||
// has moved later, which the step alone cannot see once both samples fall on the polynomial.
|
||||
const start = jd(1972);
|
||||
expect(ttMinusUtSeconds(start)).toBe(42.184);
|
||||
expect(Math.abs(ttMinusUtSeconds(start) - ttMinusUtSeconds(start - 1e-6))).toBeLessThan(0.1);
|
||||
expect(Math.abs(ttMinusUtSeconds(jd(1971, 12, 31)) - 42.2485)).toBeLessThan(0.01);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tdbFromUtc', () => {
|
||||
it('puts the clock’s date that far on', () => {
|
||||
expect((tdbFromUtc(jd(2025)) - jd(2025)) * 86400).toBeCloseTo(69.184, 3);
|
||||
expect((tdbFromUtc(2086455) - 2086455) * 86400).toBeCloseTo(ttMinusUtSeconds(2086455), 3);
|
||||
});
|
||||
});
|
||||
@@ -19,84 +19,31 @@ export const DEFAULT_EPOCH_JD = 2451545.0;
|
||||
*/
|
||||
export const GM_SUN_AU3_PER_DAY2 = 0.01720209895 * 0.01720209895;
|
||||
|
||||
/** The first day of each month UTC took a leap second at the start of, from its 10 s of 1972. */
|
||||
const LEAP_SECONDS_FROM = [
|
||||
[1972, 7], [1973, 1], [1974, 1], [1975, 1], [1976, 1], [1977, 1], [1978, 1], [1979, 1], [1980, 1], [1981, 7],
|
||||
[1982, 7], [1983, 7], [1985, 7], [1988, 1], [1990, 1], [1991, 1], [1992, 7], [1993, 7], [1994, 7], [1996, 1],
|
||||
[1997, 7], [1999, 1], [2006, 1], [2009, 1], [2012, 7], [2015, 7], [2017, 1]
|
||||
].map(([year, month]) => Date.UTC(year, month - 1, 1) / 86400000 + 2440587.5);
|
||||
const JD_1972 = Date.UTC(1972, 0, 1) / 86400000 + 2440587.5;
|
||||
/**
|
||||
* Approximate planet/Sun mass ratios for the major planets that host moons in `bodies.json`.
|
||||
* Used to derive each planet's gravitational parameter (for propagating its moons) as
|
||||
* `GM_SUN_AU3_PER_DAY2 * massRatio`. Precise enough for visualization; not JPL-grade.
|
||||
*/
|
||||
const PLANET_TO_SUN_MASS_RATIO: Record<string, number> = {
|
||||
earth: 3.003e-6,
|
||||
mars: 3.227e-7,
|
||||
jupiter: 9.545e-4,
|
||||
saturn: 2.857e-4,
|
||||
uranus: 4.365e-5,
|
||||
neptune: 5.151e-5
|
||||
};
|
||||
|
||||
/**
|
||||
* TT - UT, in seconds, at a date on the map's clock: how far Earth's turning, which UT counts,
|
||||
* has fallen behind the uniform time the ephemerides run on.
|
||||
*
|
||||
* From 1972 the clock is UTC, held to within 0.9 s of UT by leap seconds, and TT - UTC is exact:
|
||||
* 32.184 s plus TAI - UTC, which is the 10 s UTC started from in 1972 and the 27 leap seconds taken
|
||||
* since, 37 s from 2017. After the last, at the start of 2017, it is held at 69.184 s, as Horizons
|
||||
* holds it: no one knows the leap seconds to come. Before 1972 it is ΔT from the Espenak-Meeus
|
||||
* polynomials (NASA's Five Millennium Canon, 2006), which fit the historical record of eclipses and
|
||||
* occultations: 10 570 s at AD 1, 1 574 at AD 1000, 29 in 1950. As published they join within
|
||||
* 0.26 s (at 1600; 0.16 s at 1700, under 0.09 s elsewhere), and the last meets the leap-second
|
||||
* table 0.07 s apart. Held at 69 s there, as it was, every spin but Earth's was a turn of
|
||||
* (ΔT - 69 s) times its rate out, 15 degrees for Jupiter at AD 1000 and 106 at AD 1, and the Moon
|
||||
* 0.21 to 0.26 and 1.44 to 1.79 degrees along its orbit, as its eccentric orbit carries it faster
|
||||
* or slower through those hours.
|
||||
* Gravitational parameter (AU^3/day^2) to use when propagating a body's orbit: the Sun's
|
||||
* for planets/dwarfs/exoplanets, or the host planet's (derived from its Sun mass ratio) for
|
||||
* moons. Falls back to the Sun's GM if `parentBodyId` isn't a known planet.
|
||||
*/
|
||||
export function ttMinusUtSeconds(jdUt: number): number {
|
||||
if (jdUt >= JD_1972) {
|
||||
return 32.184 + 10 + LEAP_SECONDS_FROM.filter((from) => jdUt >= from).length;
|
||||
export function gmForParent(parentBodyId: string | undefined): number {
|
||||
if (!parentBodyId) {
|
||||
return GM_SUN_AU3_PER_DAY2;
|
||||
}
|
||||
const y = 2000 + (jdUt - 2451544.5) / 365.2425;
|
||||
if (y < 500) {
|
||||
const u = y / 100;
|
||||
return 10583.6 - 1014.41 * u + 33.78311 * u ** 2 - 5.952053 * u ** 3 - 0.1798452 * u ** 4 + 0.022174192 * u ** 5 + 0.0090316521 * u ** 6;
|
||||
}
|
||||
if (y < 1600) {
|
||||
const u = (y - 1000) / 100;
|
||||
return 1574.2 - 556.01 * u + 71.23472 * u ** 2 + 0.319781 * u ** 3 - 0.8503463 * u ** 4 - 0.005050998 * u ** 5 + 0.0083572073 * u ** 6;
|
||||
}
|
||||
if (y < 1700) {
|
||||
const t = y - 1600;
|
||||
return 120 - 0.9808 * t - 0.01532 * t ** 2 + t ** 3 / 7129;
|
||||
}
|
||||
if (y < 1800) {
|
||||
const t = y - 1700;
|
||||
return 8.83 + 0.1603 * t - 0.0059285 * t ** 2 + 0.00013336 * t ** 3 - t ** 4 / 1174000;
|
||||
}
|
||||
if (y < 1860) {
|
||||
const t = y - 1800;
|
||||
return 13.72 - 0.332447 * t + 0.0068612 * t ** 2 + 0.0041116 * t ** 3 - 0.00037436 * t ** 4 + 0.0000121272 * t ** 5 - 0.0000001699 * t ** 6 + 0.000000000875 * t ** 7;
|
||||
}
|
||||
if (y < 1900) {
|
||||
const t = y - 1860;
|
||||
return 7.62 + 0.5737 * t - 0.251754 * t ** 2 + 0.01680668 * t ** 3 - 0.0004473624 * t ** 4 + t ** 5 / 233174;
|
||||
}
|
||||
if (y < 1920) {
|
||||
const t = y - 1900;
|
||||
return -2.79 + 1.494119 * t - 0.0598939 * t ** 2 + 0.0061966 * t ** 3 - 0.000197 * t ** 4;
|
||||
}
|
||||
if (y < 1941) {
|
||||
const t = y - 1920;
|
||||
return 21.2 + 0.84493 * t - 0.0761 * t ** 2 + 0.0020936 * t ** 3;
|
||||
}
|
||||
if (y < 1961) {
|
||||
const t = y - 1950;
|
||||
return 29.07 + 0.407 * t - t ** 2 / 233 + t ** 3 / 2547;
|
||||
}
|
||||
const t = y - 1975;
|
||||
return 45.45 + 1.067 * t - t ** 2 / 260 - t ** 3 / 718;
|
||||
}
|
||||
|
||||
/**
|
||||
* The TDB date every element set here is evaluated at, for a date on the map's clock, which is
|
||||
* UT: Standish's T_eph, the SSD satellite and SBDB epochs and the IAU's d and T all run on TDB.
|
||||
* Positions and spins both go through this, so a locked moon's face and the orbit it is drawn on
|
||||
* are taken at the same instant; taken at the clock's date, the orbits ran 69 s behind the spins,
|
||||
* which is 0.9 degrees of Phobos's orbit and 0.16 of Io's.
|
||||
*/
|
||||
export function tdbFromUtc(jdUtc: number): number {
|
||||
return jdUtc + ttMinusUtSeconds(jdUtc) / 86400;
|
||||
const massRatio = PLANET_TO_SUN_MASS_RATIO[parentBodyId];
|
||||
return massRatio ? GM_SUN_AU3_PER_DAY2 * massRatio : GM_SUN_AU3_PER_DAY2;
|
||||
}
|
||||
|
||||
/** Converts a JS `Date` into a Julian date (days), for driving the Kepler propagator "now". */
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
distanceBetween,
|
||||
eclipticToEquatorial,
|
||||
equatorialToEcliptic,
|
||||
laplacePlaneToEquatorial,
|
||||
OBLIQUITY_J2000_DEG,
|
||||
parallaxMasToParsecs,
|
||||
parseSexagesimal,
|
||||
@@ -207,26 +206,6 @@ describe('eclipticToEquatorial', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('laplacePlaneToEquatorial', () => {
|
||||
const RAD = Math.PI / 180;
|
||||
/** Jupiter's moons' Laplace pole, as JPL gives it for Io. */
|
||||
const POLE = { raDeg: 268.057, decDeg: 64.495 };
|
||||
|
||||
it('sends the plane’s own pole to the right ascension and declination it is named by', () => {
|
||||
const pole = laplacePlaneToEquatorial({ x: 0, y: 0, z: 1 }, POLE);
|
||||
expect(Math.asin(pole.z) / RAD).toBeCloseTo(POLE.decDeg, 9);
|
||||
expect(((Math.atan2(pole.y, pole.x) / RAD) + 360) % 360).toBeCloseTo(POLE.raDeg, 9);
|
||||
});
|
||||
|
||||
it('counts the node from where the plane rises through the equator, 90 degrees past the pole', () => {
|
||||
const node = laplacePlaneToEquatorial({ x: 1, y: 0, z: 0 }, POLE);
|
||||
expect(node.z).toBeCloseTo(0, 12);
|
||||
expect(((Math.atan2(node.y, node.x) / RAD) + 360) % 360).toBeCloseTo((POLE.raDeg + 90) % 360, 9);
|
||||
// Rising: a quarter-turn on along the plane is north of the equator.
|
||||
expect(laplacePlaneToEquatorial({ x: 0, y: 1, z: 0 }, POLE).z).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('equatorialToEcliptic', () => {
|
||||
it('is the exact inverse of eclipticToEquatorial', () => {
|
||||
for (const point of [
|
||||
|
||||
@@ -59,8 +59,8 @@ export const OBLIQUITY_J2000_DEG = 23.4392911;
|
||||
*
|
||||
* The app has to span both because its two sources disagree. Star positions come from HYG as
|
||||
* equatorial coordinates, which `raDecDistanceToXyz` produces and which the galaxy view renders
|
||||
* directly. The planets' and the Moon's orbital elements are JPL mean elements against the J2000
|
||||
* ecliptic. The two are tilted
|
||||
* directly. Orbital elements come from JPL Horizons, whose default reference plane for element
|
||||
* output is the ecliptic — the ETL never overrides it. The two are tilted
|
||||
* {@link OBLIQUITY_J2000_DEG} apart about the shared vernal-equinox axis, so orbits have to be
|
||||
* rotated before they can share a scene with the stars.
|
||||
*/
|
||||
@@ -78,29 +78,6 @@ export function eclipticToEquatorial(position: CartesianCoordinates): CartesianC
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates a vector from a moon's local **Laplace plane** frame into the equatorial one.
|
||||
*
|
||||
* JPL gives the giant planets' moons against the plane their orbits precess about, which lies
|
||||
* between the planet's equator and its orbit, and names it by its pole. The frame's x axis is
|
||||
* where that plane rises through the ICRF equator, at right ascension 90 degrees past the pole's,
|
||||
* which is what the node is counted from; its z axis is the pole, 90 degrees less its declination
|
||||
* away from the celestial one. Read against the ecliptic instead, Io was up to 2.8 degrees from
|
||||
* where Horizons has it between 1950 and 2100, Phobos 54 and Titan 127: their nodes are counted
|
||||
* from a different line altogether.
|
||||
*/
|
||||
export function laplacePlaneToEquatorial(position: CartesianCoordinates, pole: { raDeg: number; decDeg: number }): CartesianCoordinates {
|
||||
const tilt = (90 - pole.decDeg) * DEG_TO_RAD;
|
||||
const node = (pole.raDeg + 90) * DEG_TO_RAD;
|
||||
const y = position.y * Math.cos(tilt) - position.z * Math.sin(tilt);
|
||||
const z = position.y * Math.sin(tilt) + position.z * Math.cos(tilt);
|
||||
return {
|
||||
x: position.x * Math.cos(node) - y * Math.sin(node),
|
||||
y: position.x * Math.sin(node) + y * Math.cos(node),
|
||||
z
|
||||
};
|
||||
}
|
||||
|
||||
/** Inverse of {@link eclipticToEquatorial}. */
|
||||
export function equatorialToEcliptic(position: CartesianCoordinates): CartesianCoordinates {
|
||||
const obliquity = OBLIQUITY_J2000_DEG * DEG_TO_RAD;
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { extractGmKm3PerS2, extractObliquityDeg, extractRadiusKm, extractRotationPeriodHours, isTidallyLocked } from './horizons-page';
|
||||
|
||||
// Lines as the Horizons pages print them.
|
||||
const JUPITER = ` Vol. Mean Radius (km) = 69911+-6 Flattening = 0.06487
|
||||
Sid. rot. period (III)= 9h 55m 29.711 s Sid. rot. rate (rad/s)= 0.00017585`;
|
||||
const MIRANDA = ` Radius (km) = 240x234.2x232.9 Density (g cm^-3) = 1.18 +- 0.05
|
||||
GM (km^3/s^2) = 4.3 +- 0.2 Geometric Albedo = 0.27
|
||||
Eccentricity, e = 0.0027 Rotational period = Synchronous`;
|
||||
const CHARON = ` GM (km^3/s^2) = 106.10 +- 0.3 Density (g cm^-3) = 1.853 +- 0.004
|
||||
Radius (km, IAU2015) = 606 +- 0.5 Geometric albedo = `;
|
||||
const PLUTO = ` GM (planet) km^3/s^2 = 869.326 Density (R=1195 km) = 1.86 g/cm^3
|
||||
Vol. mean radius (km) = 1188.3+-1.6 Mass ratio (Mc/Mp) = 0.122`;
|
||||
const PHOEBE = ` Radius (km) = 106.6 +- 1.1 Density (g/cm^3)= 1.633 +- 0.049
|
||||
Eccentricity, e = 0.1635 Rotational period = 9h 16.438 m`;
|
||||
const HYPERION = ` Mean Radius (km) = 133 +- 8 Density (g/cm^3) = 0.569 +- 0.108
|
||||
Eccentricity, e = 0.0232 Rotational period = Chaotic`;
|
||||
|
||||
describe('Horizons page radius', () => {
|
||||
it('reads a volumetric mean radius', () => {
|
||||
expect(extractRadiusKm(PLUTO)).toBe(1188.3);
|
||||
});
|
||||
|
||||
it('reads the radius Charon states against IAU 2015', () => {
|
||||
expect(extractRadiusKm(CHARON)).toBe(606);
|
||||
});
|
||||
|
||||
it('gives a triaxial body the radius of the sphere of its volume, not its longest axis', () => {
|
||||
// (240 × 234.2 × 232.9)^(1/3); the IAU's mean radius for Miranda is 235.8.
|
||||
expect(extractRadiusKm(MIRANDA)).toBeCloseTo(235.7, 1);
|
||||
// Phobos spaces its axes out; it was drawn at its longest, 13.1 km, against the IAU's 11.08.
|
||||
expect(extractRadiusKm(' Radius (km) = 13.1 x11.1 x9.3 Density (g cm^-3) = 1.90')).toBeCloseTo(11.06, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Horizons page rotation', () => {
|
||||
it('reads hours, minutes and seconds', () => {
|
||||
expect(extractRotationPeriodHours(JUPITER)).toBeCloseTo(9.925, 3);
|
||||
});
|
||||
|
||||
it('reads hours and minutes, as Phoebe states them', () => {
|
||||
expect(extractRotationPeriodHours(PHOEBE)).toBeCloseTo(9 + 16.438 / 60, 6);
|
||||
});
|
||||
|
||||
it('finds no period where the spin is chaotic', () => {
|
||||
expect(extractRotationPeriodHours(HYPERION)).toBeUndefined();
|
||||
expect(isTidallyLocked(HYPERION)).toBe(false);
|
||||
expect(isTidallyLocked(MIRANDA)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Horizons page GM', () => {
|
||||
it('reads a moon’s GM and Pluto’s, which are written differently', () => {
|
||||
expect(extractGmKm3PerS2(CHARON)).toBe(106.1);
|
||||
expect(extractGmKm3PerS2(PLUTO)).toBe(869.326);
|
||||
expect(extractGmKm3PerS2(HYPERION)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Horizons page obliquity', () => {
|
||||
it('reads the arcminutes Mercury gives its tilt in, and the degrees every other page uses', () => {
|
||||
expect(extractObliquityDeg(" Obliquity to orbit[1] = 2.11' +/- 0.1' Hill's sphere rad. Rp = 94.4 ")).toBeCloseTo(2.11 / 60, 9);
|
||||
expect(extractObliquityDeg(' Obliquity to orbit = 25.19 deg Max. angular diam. = 17.9"')).toBe(25.19);
|
||||
});
|
||||
});
|
||||
@@ -1,107 +0,0 @@
|
||||
/**
|
||||
* Reads the physical-data block at the top of a JPL Horizons object page, which the ETL fetches
|
||||
* (see `tools/etl/lib/horizons.ts`). Every page is written by hand, so each quantity is stated in
|
||||
* several ways; the patterns below are the ones the bodies in `bodies.json` actually use.
|
||||
*/
|
||||
|
||||
/**
|
||||
* What follows the `=`: one radius, or a triaxial body's three semi-axes as `240x234.2x232.9`,
|
||||
* as Miranda's and Ariel's pages give them.
|
||||
*/
|
||||
const RADIUS_VALUE = String.raw`=\s*([\d.]+(?:\s*x\s*[\d.]+)*)`;
|
||||
const RADIUS_PATTERNS = [
|
||||
new RegExp(String.raw`Vol\.?\s*mean\s*radius[^=]*${RADIUS_VALUE}`, 'i'),
|
||||
new RegExp(String.raw`Mean\s*radius[^=]*${RADIUS_VALUE}`, 'i'),
|
||||
new RegExp(String.raw`Radius\s*\(IAU\)[^=]*${RADIUS_VALUE}`, 'i'),
|
||||
// Charon's page says `Radius (km, IAU2015) = 606`.
|
||||
new RegExp(String.raw`Radius,?\s*\(km(?:,\s*IAU\s*2015)?\)\s*${RADIUS_VALUE}`, 'i'),
|
||||
new RegExp(String.raw`Radius\s*\(gravity\),?\s*km\s*${RADIUS_VALUE}`, 'i')
|
||||
];
|
||||
|
||||
/**
|
||||
* How each page states how fast the body turns, in the order they are tried.
|
||||
*
|
||||
* The rate in radians per second is preferred wherever it appears: it is unambiguous and it is
|
||||
* signed: Venus and Uranus carry a negative one. A period in hours and minutes comes next, as the
|
||||
* giant planets and Phoebe state it, then one in hours or days, and finally the word most moons
|
||||
* carry instead of a number, Synchronous. Not all do — the Moon's page gives a rate, Titan's
|
||||
* nothing — so the caller treats every moon it lists as locked whatever its page says.
|
||||
*/
|
||||
const ROTATION_RATE_PATTERN = /Rot(?:ational)?\.?\s*Rate\s*[(,]\s*rad\/s\s*\)?\s*=\s*(-?[\d.]+)/i;
|
||||
/**
|
||||
* `9h 55m 29.711 s`, as Jupiter and Saturn state it, and `9h 16.438 m`, as Phoebe does: read as
|
||||
* a period in hours alone, Phoebe turned once in 9 hours instead of 9.274.
|
||||
*/
|
||||
const SEXAGESIMAL_ROTATION_PATTERN = /(?:Sid(?:ereal|\.)?\s*rot\.?|Rotation(?:al)?)\s*period[^=]*=\s*(\d+)\s*h\s*([\d.]+)\s*m(?:\s*([\d.]+)\s*s)?/i;
|
||||
const ROTATION_PERIOD_PATTERNS = [
|
||||
/Sid(?:ereal|\.)?\s*rot\.?\s*period[^=]*=\s*(-?[\d.]+)(?:\+-[\d.]+)?\s*(h|hr|hrs|d|day|days)\b/i,
|
||||
/Rotation(?:al)?\s*period[^=]*=\s*(-?[\d.]+)\s*(h|hr|hrs|d|day|days)\b/i
|
||||
];
|
||||
const SYNCHRONOUS_PATTERN = /Rotation(?:al)?\s*period\s*=?\s*:?\s*Synchronous/i;
|
||||
/** `25.19 deg` on most pages, `2.11' +/- 0.1'` in arcminutes on Mercury's. */
|
||||
const OBLIQUITY_PATTERN = /Obliquity\s*to\s*orbit[^=]*=\s*(-?[\d.]+)\s*(')?/i;
|
||||
/** `GM (km^3/s^2) = 106.10` on a moon's page, `GM (planet) km^3/s^2 = 869.326` on Pluto's. */
|
||||
const GM_PATTERN = /GM\s*(?:\(planet\)\s*)?,?\s*\(?km\^3\/s\^2\)?\s*=\s*([\d.]+)/i;
|
||||
|
||||
const HOURS_PER_DAY = 24;
|
||||
const SECONDS_PER_HOUR = 3600;
|
||||
|
||||
/**
|
||||
* True where the page gives no number because the body keeps one face to its parent, so its day
|
||||
* is its orbit. The period itself is then the orbit's, which the caller takes from the body's
|
||||
* mean motion.
|
||||
*/
|
||||
export function isTidallyLocked(text: string): boolean {
|
||||
return SYNCHRONOUS_PATTERN.test(text);
|
||||
}
|
||||
|
||||
/** Sidereal rotation period, in hours, from whichever form the page states it in. */
|
||||
export function extractRotationPeriodHours(text: string): number | undefined {
|
||||
const rate = text.match(ROTATION_RATE_PATTERN);
|
||||
if (rate && Number(rate[1]) !== 0) {
|
||||
return (2 * Math.PI) / (Number(rate[1]) * SECONDS_PER_HOUR);
|
||||
}
|
||||
const sexagesimal = text.match(SEXAGESIMAL_ROTATION_PATTERN);
|
||||
if (sexagesimal) {
|
||||
return Number(sexagesimal[1]) + Number(sexagesimal[2]) / 60 + Number(sexagesimal[3] ?? 0) / SECONDS_PER_HOUR;
|
||||
}
|
||||
for (const pattern of ROTATION_PERIOD_PATTERNS) {
|
||||
const match = text.match(pattern);
|
||||
if (match) {
|
||||
const hours = Number(match[1]) * (match[2].toLowerCase().startsWith('d') ? HOURS_PER_DAY : 1);
|
||||
return Number.isFinite(hours) && hours !== 0 ? hours : undefined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tilt of the rotation axis from the orbit, in degrees. Mercury's page gives its tilt in
|
||||
* arcminutes, which read as degrees made it 2.11 where the IAU's pole puts it at 0.034.
|
||||
*/
|
||||
export function extractObliquityDeg(text: string): number | undefined {
|
||||
const match = text.match(OBLIQUITY_PATTERN);
|
||||
return match ? Number(match[1]) / (match[2] ? 60 : 1) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mean radius in km. For a triaxial body, the radius of the sphere of the same volume, the cube
|
||||
* root of the three semi-axes' product, which is how the IAU states a mean radius: Miranda's
|
||||
* 240 x 234.2 x 232.9 km is 235.7, where the first figure alone overstated it by 2 per cent.
|
||||
*/
|
||||
export function extractRadiusKm(text: string): number | undefined {
|
||||
for (const pattern of RADIUS_PATTERNS) {
|
||||
const match = text.match(pattern);
|
||||
if (match) {
|
||||
const axes = match[1].split('x').map(Number);
|
||||
return axes.reduce((product, axis) => product * axis, 1) ** (1 / axes.length);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The body's own GM, in km³/s², where the page publishes one. */
|
||||
export function extractGmKm3PerS2(text: string): number | undefined {
|
||||
const match = text.match(GM_PATTERN);
|
||||
return match ? Number(match[1]) : undefined;
|
||||
}
|
||||
@@ -168,7 +168,8 @@ describe('minimumRangeBetween', () => {
|
||||
expect(minimumRangeBetween(knotAndChain(), 0, CHAIN_END, 8).rangePc).toBeCloseTo(1, 1);
|
||||
});
|
||||
|
||||
it('stops bisecting where a search gave up, and hands back a range that does work', { timeout: 30_000 }, () => {
|
||||
// 7,5 s sur un poste récent, autour de 30 s sur le runner Gitea du VPS : 90 s de marge.
|
||||
it('stops bisecting where a search gave up, and hands back a range that does work', { timeout: 90_000 }, () => {
|
||||
// Below the chain's own hop of a parsec, the crowd is still one connected piece and larger than
|
||||
// the budget, so those probes give up. Reading a give-up as "no chain at this range" is what
|
||||
// used to report ranges up to 29% wider than needed, and went on paying for probes whose
|
||||
|
||||
@@ -4,11 +4,9 @@ import { GM_SUN_AU3_PER_DAY2, DEFAULT_EPOCH_JD } from './constants';
|
||||
import {
|
||||
gravitationalParameterFromPeriod,
|
||||
isPropagatableOrbit,
|
||||
meanElementsAt,
|
||||
meanMotionRadPerDay,
|
||||
orbitEllipsePoints,
|
||||
orbitalPeriodDays,
|
||||
positionAtEpoch,
|
||||
positionAtTrueAnomaly,
|
||||
propagateOrbit,
|
||||
resolveGravitationalParameter,
|
||||
@@ -133,46 +131,6 @@ describe('propagateOrbit', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('meanElementsAt', () => {
|
||||
/** A circle in the reference plane, prograde (0) or retrograde (180), whose node turns. */
|
||||
function circle(inclinationDeg: number) {
|
||||
return { semiMajorAxisAu: 1, eccentricity: 0, inclinationDeg, longitudeOfAscendingNodeDeg: 0, argumentOfPeriapsisDeg: 0, meanAnomalyAtEpochDeg: 0, epochJd: DEFAULT_EPOCH_JD };
|
||||
}
|
||||
const RATES = { meanMotionDegPerDay: 10, longitudeOfAscendingNodeDegPerDay: 0.5, argumentOfPeriapsisDegPerDay: 0.2 };
|
||||
|
||||
/** Longitude in the reference plane a day on, in degrees, signed. */
|
||||
function longitudeAfterOneDay(inclinationDeg: number): number {
|
||||
const { x, y } = positionAtEpoch(meanElementsAt(circle(inclinationDeg), RATES, DEFAULT_EPOCH_JD + 1));
|
||||
return (Math.atan2(y, x) * 180) / Math.PI;
|
||||
}
|
||||
|
||||
it('goes round at its mean motion however its node and periapsis turn', () => {
|
||||
expect(longitudeAfterOneDay(0)).toBeCloseTo(10, 9);
|
||||
});
|
||||
|
||||
it('goes round a retrograde orbit backwards at the same rate, the node’s turning added back', () => {
|
||||
// Taking the node off as for a prograde orbit made this 9 degrees, and Triton drifted a
|
||||
// degree a year from where Horizons has it.
|
||||
expect(longitudeAfterOneDay(180)).toBeCloseTo(-10, 9);
|
||||
});
|
||||
|
||||
it('turns the node and periapsis at their own rates, and dates the result', () => {
|
||||
const later = meanElementsAt(circle(0), RATES, DEFAULT_EPOCH_JD + 4);
|
||||
expect(later.longitudeOfAscendingNodeDeg).toBeCloseTo(2, 12);
|
||||
expect(later.argumentOfPeriapsisDeg).toBeCloseTo(0.8, 12);
|
||||
expect(later.epochJd).toBe(DEFAULT_EPOCH_JD + 4);
|
||||
});
|
||||
|
||||
it('adds Standish’s b T² + c cos(fT) + s sin(fT) to the mean anomaly', () => {
|
||||
const terms = { b: -0.00012452, c: 0.0606406, s: -0.35635438, f: 38.35125 };
|
||||
const T = 0.7;
|
||||
const withTerms = meanElementsAt(circle(0), { ...RATES, meanAnomalyTerms: terms }, DEFAULT_EPOCH_JD + T * 36525);
|
||||
const without = meanElementsAt(circle(0), RATES, DEFAULT_EPOCH_JD + T * 36525);
|
||||
const f = (terms.f * T * Math.PI) / 180;
|
||||
expect(withTerms.meanAnomalyAtEpochDeg - without.meanAnomalyAtEpochDeg).toBeCloseTo(terms.b * T * T + terms.c * Math.cos(f) + terms.s * Math.sin(f), 9);
|
||||
});
|
||||
});
|
||||
|
||||
describe('orbitEllipsePoints', () => {
|
||||
it('samples a closed loop whose distances stay within the periapsis/apoapsis bounds', () => {
|
||||
const elements = resolveOrbitalElements({ semiMajorAxisAu: 5, eccentricity: 0.4 });
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { CartesianCoordinates } from './coordinates';
|
||||
import { DEFAULT_EPOCH_JD, GM_SUN_AU3_PER_DAY2 } from './constants';
|
||||
import { MeanElementRates, OrbitalElements } from '../models/body.model';
|
||||
import { OrbitalElements } from '../models/body.model';
|
||||
|
||||
const DEG_TO_RAD = Math.PI / 180;
|
||||
const TWO_PI = Math.PI * 2;
|
||||
const DAYS_PER_JULIAN_CENTURY = 36525;
|
||||
|
||||
/**
|
||||
* Fills in the elements the Kepler propagator needs but that some sources (e.g. exoplanets,
|
||||
@@ -209,63 +208,17 @@ export function positionAtTrueAnomaly(elements: OrbitalElements, trueAnomalyRad:
|
||||
}
|
||||
|
||||
/**
|
||||
* The rates of an orbit that only goes round: Kepler's mean motion from the central mass, with
|
||||
* nothing turning. What an exoplanet has, since the archive publishes no precession.
|
||||
*/
|
||||
export function keplerRates(semiMajorAxisAu: number, gmAu3PerDay2: number): MeanElementRates {
|
||||
return {
|
||||
meanMotionDegPerDay: meanMotionRadPerDay(semiMajorAxisAu, gmAu3PerDay2) / DEG_TO_RAD,
|
||||
longitudeOfAscendingNodeDegPerDay: 0,
|
||||
argumentOfPeriapsisDegPerDay: 0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The elements at `epochJdEval`, each moved from its epoch at its own rate, and returned with that
|
||||
* date as their epoch — so {@link positionAtEpoch} places the body, and the node and periapsis
|
||||
* say where to draw the orbit it is on.
|
||||
*
|
||||
* The mean anomaly is what is left of the body's motion once the node and periapsis have turned:
|
||||
* `meanMotionDegPerDay` is how fast it goes round in space, and a periapsis that has moved on is
|
||||
* that much further to reach. On a retrograde orbit, past 90 degrees, the body runs against the
|
||||
* direction the node is counted in, so the node's turning is added back rather than taken off.
|
||||
* Taken off, Triton — whose node turns half a degree a year — drifted a degree a year from where
|
||||
* Horizons has it, 105 degrees by 2100.
|
||||
*/
|
||||
export function meanElementsAt(elements: OrbitalElements, rates: MeanElementRates, epochJdEval: number): OrbitalElements {
|
||||
const days = epochJdEval - elements.epochJd;
|
||||
const node = rates.longitudeOfAscendingNodeDegPerDay * days;
|
||||
const periapsis = rates.argumentOfPeriapsisDegPerDay * days;
|
||||
const nodeAlongOrbit = elements.inclinationDeg > 90 ? -node : node;
|
||||
const terms = rates.meanAnomalyTerms;
|
||||
const centuries = days / DAYS_PER_JULIAN_CENTURY;
|
||||
const extra = terms
|
||||
? terms.b * centuries * centuries + terms.c * Math.cos(terms.f * centuries * DEG_TO_RAD) + terms.s * Math.sin(terms.f * centuries * DEG_TO_RAD)
|
||||
: 0;
|
||||
return {
|
||||
semiMajorAxisAu: elements.semiMajorAxisAu + (rates.semiMajorAxisAuPerDay ?? 0) * days,
|
||||
eccentricity: elements.eccentricity + (rates.eccentricityPerDay ?? 0) * days,
|
||||
inclinationDeg: elements.inclinationDeg + (rates.inclinationDegPerDay ?? 0) * days,
|
||||
longitudeOfAscendingNodeDeg: elements.longitudeOfAscendingNodeDeg + node,
|
||||
argumentOfPeriapsisDeg: elements.argumentOfPeriapsisDeg + periapsis,
|
||||
meanAnomalyAtEpochDeg: elements.meanAnomalyAtEpochDeg + rates.meanMotionDegPerDay * days - periapsis - nodeAlongOrbit + extra,
|
||||
epochJd: epochJdEval
|
||||
};
|
||||
}
|
||||
|
||||
/** Where `elements` put the body at their own epoch (AU, relative to the central body). */
|
||||
export function positionAtEpoch(elements: OrbitalElements): CartesianCoordinates {
|
||||
const eccentricAnomalyRad = solveEccentricAnomaly(elements.meanAnomalyAtEpochDeg * DEG_TO_RAD, elements.eccentricity);
|
||||
return positionAtTrueAnomaly(elements, trueAnomalyFromEccentricAnomaly(eccentricAnomalyRad, elements.eccentricity));
|
||||
}
|
||||
|
||||
/**
|
||||
* Propagates `elements` to Julian date `epochJdEval` around a central mass, returning the body's
|
||||
* position (AU) relative to its central body, as opposed to {@link orbitEllipsePoints} which
|
||||
* Propagates `elements` to Julian date `epochJdEval`, returning the body's position (AU)
|
||||
* relative to its central body. This is the app's "current epoch" evaluation used for live
|
||||
* (and future time-scrubbable) positions, as opposed to {@link orbitEllipsePoints} which
|
||||
* samples the fixed orbit shape independent of time.
|
||||
*/
|
||||
export function propagateOrbit(elements: OrbitalElements, gmAu3PerDay2: number, epochJdEval: number): CartesianCoordinates {
|
||||
return positionAtEpoch(meanElementsAt(elements, keplerRates(elements.semiMajorAxisAu, gmAu3PerDay2), epochJdEval));
|
||||
const meanMotion = meanMotionRadPerDay(elements.semiMajorAxisAu, gmAu3PerDay2);
|
||||
const meanAnomalyRad = elements.meanAnomalyAtEpochDeg * DEG_TO_RAD + meanMotion * (epochJdEval - elements.epochJd);
|
||||
const eccentricAnomalyRad = solveEccentricAnomaly(meanAnomalyRad, elements.eccentricity);
|
||||
const trueAnomalyRad = trueAnomalyFromEccentricAnomaly(eccentricAnomalyRad, elements.eccentricity);
|
||||
return positionAtTrueAnomaly(elements, trueAnomalyRad);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { parsePlanetMeanElements, parseSatelliteMeanElements, parseSmallBodyElements, SbdbAnswer } from './mean-elements';
|
||||
|
||||
/** Standish's p_elem_t2.txt, cut to the lines that matter here, as JPL published them. */
|
||||
const TABLE_2 = `Keplerian elements and their rates, with respect to the mean ecliptic and equinox of J2000,
|
||||
valid for the time-interval 3000 BC -- 3000 AD. NOTE: the computation of M for Jupiter through
|
||||
Pluto *must* be augmented by the additional terms given in Table 2b (below).
|
||||
|
||||
EM Bary 1.00000018 0.01673163 -0.00054346 100.46691572 102.93005885 -5.11260389
|
||||
-0.00000003 -0.00003661 -0.01337178 35999.37306329 0.31795260 -0.24123856
|
||||
Jupiter 5.20248019 0.04853590 1.29861416 34.33479152 14.27495244 100.29282654
|
||||
-0.00002864 0.00018026 -0.00322699 3034.90371757 0.18199196 0.13024619
|
||||
Pluto 39.48686035 0.24885238 17.14104260 238.96535011 224.09702598 110.30167986
|
||||
0.00449751 0.00006016 0.00000501 145.18042903 -0.00968827 -0.00809981
|
||||
|
||||
Table 2b.
|
||||
Jupiter -0.00012452 0.06064060 -0.35635438 38.35125000
|
||||
Pluto -0.01262724
|
||||
`;
|
||||
|
||||
/** The satellite page's markup around three rows, as the 2021 page served it. */
|
||||
const SATELLITES = `
|
||||
<td align="left" nowrap><b>Satellites of Earth</b></td>
|
||||
<td align="right" nowrap><b>jump to:</b> <a href="#earth">Earth</a>, <a href="#mars">Mars</a></td>
|
||||
<H3>Mean <a href="?glossary&term=ecliptic">ecliptic</a> orbital elements</H3>
|
||||
Epoch 2000 Jan. 1.50 TT<BR>
|
||||
<TR ALIGN=right><TD ALIGN=left>Moon</TD>
|
||||
<TD>384400.</TD><TD>0.0554</TD><TD>318.15</TD><TD>135.27</TD><TD>5.16</TD><TD>125.08</TD>
|
||||
<TD>13.176358</TD><TD>27.322</TD><TD>5.997</TD><TD>18.600</TD>
|
||||
<TD ALIGN=right><A HREF="#ref1">1</A></TD></TR>
|
||||
<td align="left" nowrap><b>Satellites of Jupiter</b></td>
|
||||
<td align="right" nowrap><b>jump to:</b> <a href="#earth">Earth</a>, <a href="#mars">Mars</a></td>
|
||||
<H3>Mean orbital elements referred to the local <a href="?glossary&term=lp">Laplace planes</a></H3>
|
||||
Epoch 1997 Jan. 16.00 TT<BR>
|
||||
<TR ALIGN=right><TD ALIGN=left>Io</TD><TD>421800.</TD><TD>0.0041</TD>
|
||||
<TD>84.129</TD><TD>342.021</TD><TD>0.036</TD><TD>43.977</TD><TD>203.4889583</TD>
|
||||
<TD>1.769</TD><TD>1.625</TD><TD>7.420</TD><TD>268.057</TD><TD>64.495</TD>
|
||||
<TD>0.000</TD>
|
||||
<TD ALIGN=right><A HREF="#ref11">11</A></TD></TR>
|
||||
<td align="left" nowrap><b>Satellites of Neptune</b></td>
|
||||
<td align="right" nowrap><b>jump to:</b> <a href="#earth">Earth</a>, <a href="#mars">Mars</a></td>
|
||||
<H3>Mean orbital elements referred to the local <a href="?glossary&term=lp">Laplace planes</a></H3>
|
||||
Epoch 2000 Jan. 1.50 TT<BR>
|
||||
<TR ALIGN=right><TD ALIGN=left>Triton</TD><TD>354759.</TD><TD>0.0000</TD>
|
||||
<TD>66.142</TD><TD>352.257</TD><TD>156.865</TD><TD>177.608</TD>
|
||||
<TD>61.2572638</TD><TD>5.877</TD><TD>386.371</TD><TD>687.446</TD>
|
||||
<TD>299.456</TD><TD>43.414</TD><TD>0.010</TD>
|
||||
<TD ALIGN=right><A HREF="#ref54">54</A></TD></TR>
|
||||
<td align="left" nowrap><b>Satellites of Uranus</b></td>
|
||||
<td align="right" nowrap><b>jump to:</b> <a href="#earth">Earth</a>, <a href="#mars">Mars</a></td>
|
||||
<H3>Mean equatorial orbital elements</H3>
|
||||
Epoch 1980 Jan. 1.0 TT<BR>
|
||||
<TR ALIGN=right><TD ALIGN=left>Titania</TD><TD>436300.</TD><TD>0.0011</TD>
|
||||
<TD>284.400</TD><TD>24.614</TD><TD>0.079</TD><TD>99.771</TD><TD>41.3514246</TD>
|
||||
<TD>8.706</TD><TD>161.525</TD><TD>195.369</TD>
|
||||
<TD ALIGN=right><A HREF="#ref10">10</A></TD></TR>
|
||||
`;
|
||||
|
||||
/** Ceres as the SBDB API answers `sstr=Ceres&phys-par=1&full-prec=1`, cut to what is read. */
|
||||
const CERES: SbdbAnswer = {
|
||||
orbit: {
|
||||
epoch: '2461200.5',
|
||||
elements: [
|
||||
{ name: 'e', value: '.07969229514816586' },
|
||||
{ name: 'a', value: '2.765552595034094' },
|
||||
{ name: 'q', value: '2.545159361382861' },
|
||||
{ name: 'i', value: '10.58802780183462' },
|
||||
{ name: 'om', value: '80.24862682043221' },
|
||||
{ name: 'w', value: '73.29421453021587' },
|
||||
{ name: 'ma', value: '274.4193463761342' },
|
||||
{ name: 'tp', value: '2461599.841466614066' },
|
||||
{ name: 'per', value: '1679.853119758983' },
|
||||
{ name: 'n', value: '.21430445064843' },
|
||||
{ name: 'ad', value: '2.985945828685327' }
|
||||
]
|
||||
},
|
||||
phys_par: [
|
||||
{ name: 'H', value: '3.34' },
|
||||
{ name: 'diameter', value: '939.4' },
|
||||
{ name: 'GM', value: '62.6284' },
|
||||
{ name: 'rot_per', value: '9.074170' }
|
||||
]
|
||||
};
|
||||
|
||||
describe('parsePlanetMeanElements', () => {
|
||||
it('turns Standish’s longitudes into the argument of periapsis and mean anomaly', () => {
|
||||
const { orbit } = parsePlanetMeanElements(TABLE_2, 'jupiter');
|
||||
expect(orbit.argumentOfPeriapsisDeg).toBeCloseTo(14.27495244 - 100.29282654, 8);
|
||||
expect(orbit.meanAnomalyAtEpochDeg).toBeCloseTo(34.33479152 - 14.27495244, 8);
|
||||
expect(orbit.epochJd).toBe(2451545);
|
||||
});
|
||||
|
||||
it('gives the rates per day, the mean motion being the mean longitude’s', () => {
|
||||
const { rates } = parsePlanetMeanElements(TABLE_2, 'earth');
|
||||
// 35 999.373 degrees a century is the sidereal year.
|
||||
expect(360 / rates.meanMotionDegPerDay).toBeCloseTo(365.2564, 4);
|
||||
expect(rates.argumentOfPeriapsisDegPerDay * 36525).toBeCloseTo(0.3179526 + 0.24123856, 8);
|
||||
// And every other rate the row gives, a century's worth: dropped, Saturn moved 0.66 degrees by
|
||||
// AD 1 without its node's and 0.36 by AD 3000 without its a, e and i, where no date from 1950 to
|
||||
// 2100 shows more than 0.036.
|
||||
expect(rates.longitudeOfAscendingNodeDegPerDay * 36525).toBeCloseTo(-0.24123856, 8);
|
||||
expect(rates.semiMajorAxisAuPerDay! * 36525).toBeCloseTo(-0.00000003, 8);
|
||||
expect(rates.eccentricityPerDay! * 36525).toBeCloseTo(-0.00003661, 8);
|
||||
expect(rates.inclinationDegPerDay! * 36525).toBeCloseTo(-0.01337178, 8);
|
||||
});
|
||||
|
||||
it('carries Table 2b’s terms for Jupiter and beyond, and none for the inner planets', () => {
|
||||
expect(parsePlanetMeanElements(TABLE_2, 'jupiter').rates.meanAnomalyTerms).toEqual({ b: -0.00012452, c: 0.0606406, s: -0.35635438, f: 38.35125 });
|
||||
expect(parsePlanetMeanElements(TABLE_2, 'earth').rates.meanAnomalyTerms).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reads Pluto’s row, not the note above the table that starts a line with its name', () => {
|
||||
const pluto = parsePlanetMeanElements(TABLE_2, 'pluto');
|
||||
expect(pluto.orbit.semiMajorAxisAu).toBe(39.48686035);
|
||||
expect(pluto.rates.meanAnomalyTerms).toEqual({ b: -0.01262724, c: 0, s: 0, f: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSatelliteMeanElements', () => {
|
||||
it('reads a Laplace-plane row with its pole and its section’s epoch', () => {
|
||||
const io = parseSatelliteMeanElements(SATELLITES, 'Jupiter', 'Io', true);
|
||||
expect(io.laplacePole).toEqual({ raDeg: 268.057, decDeg: 64.495 });
|
||||
expect(io.orbit.epochJd).toBe(2450464.5);
|
||||
expect(io.rates.meanMotionDegPerDay).toBe(203.4889583);
|
||||
expect(io.orbitSource).toBe('JPL SSD satellite mean elements, epoch 1997 Jan 16');
|
||||
});
|
||||
|
||||
it('reads the Moon against the ecliptic, with no pole', () => {
|
||||
const moon = parseSatelliteMeanElements(SATELLITES, 'Earth', 'Moon', false);
|
||||
expect(moon.laplacePole).toBeUndefined();
|
||||
expect(moon.orbit.epochJd).toBe(2451545);
|
||||
expect(moon.orbit.semiMajorAxisAu * 149597870.7).toBeCloseTo(384400, 3);
|
||||
});
|
||||
|
||||
it('regresses a prograde node and advances a periapsis, as the planet’s oblateness turns them', () => {
|
||||
const { rates } = parseSatelliteMeanElements(SATELLITES, 'Earth', 'Moon', false);
|
||||
expect(rates.longitudeOfAscendingNodeDegPerDay).toBeCloseTo(-360 / (18.6 * 365.25), 9);
|
||||
expect(rates.argumentOfPeriapsisDegPerDay).toBeCloseTo(360 / (5.997 * 365.25), 9);
|
||||
});
|
||||
|
||||
it('advances the node of a retrograde orbit', () => {
|
||||
const { rates } = parseSatelliteMeanElements(SATELLITES, 'Neptune', 'Triton', false);
|
||||
expect(rates.longitudeOfAscendingNodeDegPerDay).toBeCloseTo(360 / (687.446 * 365.25), 9);
|
||||
});
|
||||
|
||||
it('reads a section referred to the planet’s equator against the pole it is given', () => {
|
||||
const pole = { raDeg: 77.311, decDeg: 15.175 };
|
||||
const titania = parseSatelliteMeanElements(SATELLITES, 'Uranus', 'Titania', false, pole);
|
||||
expect(titania.laplacePole).toEqual(pole);
|
||||
expect(titania.orbit.epochJd).toBe(2444239.5);
|
||||
expect(titania.rates.meanMotionDegPerDay).toBe(41.3514246);
|
||||
// Read as ecliptic elements, which is what a missing pole would mean, Titania is 88 degrees
|
||||
// from Horizons on 2025-01-01.
|
||||
expect(() => parseSatelliteMeanElements(SATELLITES, 'Uranus', 'Titania', false)).toThrow(/equator/);
|
||||
expect(() => parseSatelliteMeanElements(SATELLITES, 'Jupiter', 'Io', true, pole)).toThrow(/equator/);
|
||||
});
|
||||
|
||||
it('turns the periapsis backwards where a resonance holds it', () => {
|
||||
const { rates } = parseSatelliteMeanElements(SATELLITES, 'Jupiter', 'Io', true);
|
||||
expect(rates.argumentOfPeriapsisDegPerDay).toBeCloseTo(-360 / (1.625 * 365.25), 9);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSmallBodyElements', () => {
|
||||
it('carries a dwarf planet on its osculating elements at their own mean motion', () => {
|
||||
const ceres = parseSmallBodyElements(CERES);
|
||||
expect(ceres.orbit).toEqual({
|
||||
semiMajorAxisAu: 2.765552595034094,
|
||||
eccentricity: 0.07969229514816586,
|
||||
inclinationDeg: 10.58802780183462,
|
||||
longitudeOfAscendingNodeDeg: 80.24862682043221,
|
||||
argumentOfPeriapsisDeg: 73.29421453021587,
|
||||
meanAnomalyAtEpochDeg: 274.4193463761342,
|
||||
epochJd: 2461200.5
|
||||
});
|
||||
expect(ceres.rates).toEqual({ meanMotionDegPerDay: 0.21430445064843, longitudeOfAscendingNodeDegPerDay: 0, argumentOfPeriapsisDegPerDay: 0 });
|
||||
expect(ceres.laplacePole).toBeUndefined();
|
||||
expect(ceres.orbitSource).toBe('JPL SBDB osculating elements, epoch 2026 Jun 9');
|
||||
});
|
||||
|
||||
it('takes half the diameter as the radius, and the rotation period in hours', () => {
|
||||
const ceres = parseSmallBodyElements(CERES);
|
||||
expect(ceres.radiusKm).toBe(469.7);
|
||||
expect(ceres.rotationPeriodHours).toBe(9.07417);
|
||||
});
|
||||
|
||||
it('leaves out what the answer does not publish', () => {
|
||||
const eris = parseSmallBodyElements({ ...CERES, phys_par: [{ name: 'rot_per', value: '25.9' }] });
|
||||
expect(eris.radiusKm).toBeUndefined();
|
||||
expect(eris.rotationPeriodHours).toBe(25.9);
|
||||
});
|
||||
});
|
||||
@@ -1,223 +0,0 @@
|
||||
import { MeanElementRates, OrbitalElements } from '../models/body.model';
|
||||
|
||||
/**
|
||||
* Reads JPL's two tables of mean orbital elements, which the ETL fetches (see
|
||||
* `tools/etl/lib/mean-elements.ts`), into the elements and rates `bodies.json` carries.
|
||||
*/
|
||||
|
||||
const KM_PER_AU = 149597870.7;
|
||||
const J2000_JD = 2451545.0;
|
||||
const DAYS_PER_JULIAN_CENTURY = 36525;
|
||||
const DAYS_PER_JULIAN_YEAR = 365.25;
|
||||
|
||||
const PLANET_ORBIT_SOURCE = 'JPL approximate mean elements (Standish), fit for 3000 BC to AD 3000';
|
||||
|
||||
export interface MeanOrbit {
|
||||
orbit: OrbitalElements;
|
||||
rates: MeanElementRates;
|
||||
laplacePole?: { raDeg: number; decDeg: number };
|
||||
orbitSource: string;
|
||||
}
|
||||
|
||||
/** Table 2a's name for each planet; Earth's row is the Earth-Moon barycentre, 4 700 km off Earth. */
|
||||
const PLANET_ROW_NAMES: Record<string, string> = {
|
||||
mercury: 'Mercury',
|
||||
venus: 'Venus',
|
||||
earth: 'EM Bary',
|
||||
mars: 'Mars',
|
||||
jupiter: 'Jupiter',
|
||||
saturn: 'Saturn',
|
||||
uranus: 'Uranus',
|
||||
neptune: 'Neptune',
|
||||
pluto: 'Pluto'
|
||||
};
|
||||
|
||||
function numbers(text: string): number[] {
|
||||
return text.trim().split(/\s+/).map(Number);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads one planet's row pair from Table 2a, and its Table 2b terms where it has them. The
|
||||
* elements are Standish's own — a, e, I, mean longitude L, longitude of perihelion ϖ, node Ω —
|
||||
* turned into the argument of periapsis ϖ - Ω and mean anomaly L - ϖ the propagator takes.
|
||||
*/
|
||||
export function parsePlanetMeanElements(text: string, bodyId: string): MeanOrbit {
|
||||
const name = PLANET_ROW_NAMES[bodyId];
|
||||
const lines = text.split(/\r?\n/);
|
||||
// A row is the name followed by a number: the notes above the table start a line with "Pluto" too.
|
||||
const rows = lines.flatMap((line, index) => (name && new RegExp(`^${name}\\s+-?[\\d.]`).test(line) ? [index] : []));
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`No row for ${bodyId} in Standish's Table 2a.`);
|
||||
}
|
||||
const values = [...numbers(lines[rows[0]].slice(name.length)), ...numbers(lines[rows[0] + 1])];
|
||||
if (values.length !== 12 || !values.every(Number.isFinite)) {
|
||||
throw new Error(`Standish's Table 2a rows for ${name} did not parse: ${values.join(' ')}`);
|
||||
}
|
||||
const [a, e, inclination, meanLongitude, perihelion, node, aRate, eRate, inclinationRate, meanLongitudeRate, perihelionRate, nodeRate] = values;
|
||||
// Table 2b repeats the name further down, with b, c, s, f (Pluto has b alone).
|
||||
const extra = rows[1] === undefined ? undefined : numbers(lines[rows[1]].slice(name.length));
|
||||
const [b = 0, c = 0, s = 0, f = 0] = extra ?? [];
|
||||
|
||||
return {
|
||||
orbit: {
|
||||
semiMajorAxisAu: a,
|
||||
eccentricity: e,
|
||||
inclinationDeg: inclination,
|
||||
longitudeOfAscendingNodeDeg: node,
|
||||
argumentOfPeriapsisDeg: perihelion - node,
|
||||
meanAnomalyAtEpochDeg: meanLongitude - perihelion,
|
||||
epochJd: J2000_JD
|
||||
},
|
||||
rates: {
|
||||
meanMotionDegPerDay: meanLongitudeRate / DAYS_PER_JULIAN_CENTURY,
|
||||
longitudeOfAscendingNodeDegPerDay: nodeRate / DAYS_PER_JULIAN_CENTURY,
|
||||
argumentOfPeriapsisDegPerDay: (perihelionRate - nodeRate) / DAYS_PER_JULIAN_CENTURY,
|
||||
semiMajorAxisAuPerDay: aRate / DAYS_PER_JULIAN_CENTURY,
|
||||
eccentricityPerDay: eRate / DAYS_PER_JULIAN_CENTURY,
|
||||
inclinationDegPerDay: inclinationRate / DAYS_PER_JULIAN_CENTURY,
|
||||
...(extra ? { meanAnomalyTerms: { b, c, s, f } } : {})
|
||||
},
|
||||
orbitSource: PLANET_ORBIT_SOURCE
|
||||
};
|
||||
}
|
||||
|
||||
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
|
||||
/** `1997 Jan. 16.00` as a Julian date. TT and TDB differ by under two milliseconds. */
|
||||
function julianDate(year: number, month: string, day: number): number {
|
||||
const monthIndex = MONTHS.indexOf(month);
|
||||
if (monthIndex < 0) {
|
||||
throw new Error(`Unknown month ${month}.`);
|
||||
}
|
||||
return Date.UTC(year, monthIndex, 1) / 86400000 + 2440587.5 + day - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads one moon's row from the satellite page: `a e w M i node n P Pw Pnode`, then the Laplace
|
||||
* pole `RA Dec Tilt` where the section is referred to one, then a reference number.
|
||||
*
|
||||
* The page gives the two precession periods as magnitudes, so their sense is supplied here. A
|
||||
* node driven by the planet's oblateness regresses on a prograde orbit and advances on a
|
||||
* retrograde one, and the orbit's inclination says which. A periapsis advances — except where a
|
||||
* resonance forces the eccentricity, which `apsidesRegress` names: Io's and Europa's are held to
|
||||
* the line of their conjunctions, which turns backwards at 2 n(Europa) - n(Io) = 0.74 degrees a
|
||||
* day, and that is exactly the 1.625- and 1.394-year periods the table gives for them. Read as
|
||||
* advancing, Io was 0.9 degrees out and Europa 2.1.
|
||||
*
|
||||
* Uranus's and Pluto's sections are referred to the planet's equator instead, and the page does
|
||||
* not print its pole, so the caller passes it as `equatorPole`: the elements are then read
|
||||
* against that pole exactly as against a Laplace plane's.
|
||||
*/
|
||||
export function parseSatelliteMeanElements(
|
||||
html: string,
|
||||
planetName: string,
|
||||
moonName: string,
|
||||
apsidesRegress: boolean,
|
||||
equatorPole?: { raDeg: number; decDeg: number }
|
||||
): MeanOrbit {
|
||||
const text = html.replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/\s+/g, ' ');
|
||||
const section = text.indexOf(`Satellites of ${planetName} jump to`);
|
||||
if (section < 0) {
|
||||
throw new Error(`No section for the satellites of ${planetName}.`);
|
||||
}
|
||||
const row = text.slice(section).match(new RegExp(` ${moonName} ((?:-?[\\d.]+ )+)`));
|
||||
if (!row || row.index === undefined) {
|
||||
throw new Error(`No row for ${moonName} among the satellites of ${planetName}.`);
|
||||
}
|
||||
const before = text.slice(section, section + row.index);
|
||||
const epoch = [...before.matchAll(/Epoch (\d{4}) (\w{3})\. ([\d.]+) T/g)].at(-1);
|
||||
if (!epoch) {
|
||||
throw new Error(`No epoch above ${moonName}'s row.`);
|
||||
}
|
||||
// The nearest heading above the row says which plane its section is referred to; the ecliptic
|
||||
// where there is none.
|
||||
const [plane] = ['Mean ecliptic', 'Laplace plane', 'Mean equatorial'].sort((x, y) => before.lastIndexOf(y) - before.lastIndexOf(x));
|
||||
const laplace = plane === 'Laplace plane';
|
||||
const equatorial = plane === 'Mean equatorial';
|
||||
if (equatorial !== (equatorPole !== undefined)) {
|
||||
throw new Error(`${moonName}'s elements are ${equatorial ? '' : 'not '}referred to ${planetName}'s equator, and its pole was ${equatorPole ? '' : 'not '}given.`);
|
||||
}
|
||||
const values = numbers(row[1]);
|
||||
const expected = laplace ? 14 : 11;
|
||||
if (values.length !== expected || !values.every(Number.isFinite)) {
|
||||
throw new Error(`${moonName}'s row has ${values.length} numbers, ${expected} expected: ${row[1]}`);
|
||||
}
|
||||
const [aKm, e, periapsis, meanAnomaly, inclination, node, meanMotion, , periapsisPeriodYears, nodePeriodYears, raDeg, decDeg] = values;
|
||||
const nodeSense = inclination > 90 ? 1 : -1;
|
||||
const periapsisSense = apsidesRegress ? -1 : 1;
|
||||
const perDay = (periodYears: number): number => (periodYears > 0 ? 360 / (periodYears * DAYS_PER_JULIAN_YEAR) : 0);
|
||||
|
||||
return {
|
||||
orbit: {
|
||||
semiMajorAxisAu: aKm / KM_PER_AU,
|
||||
eccentricity: e,
|
||||
inclinationDeg: inclination,
|
||||
longitudeOfAscendingNodeDeg: node,
|
||||
argumentOfPeriapsisDeg: periapsis,
|
||||
meanAnomalyAtEpochDeg: meanAnomaly,
|
||||
epochJd: julianDate(Number(epoch[1]), epoch[2], Number(epoch[3]))
|
||||
},
|
||||
rates: {
|
||||
meanMotionDegPerDay: meanMotion,
|
||||
longitudeOfAscendingNodeDegPerDay: nodeSense * perDay(nodePeriodYears),
|
||||
argumentOfPeriapsisDegPerDay: periapsisSense * perDay(periapsisPeriodYears)
|
||||
},
|
||||
...(laplace ? { laplacePole: { raDeg, decDeg } } : equatorPole ? { laplacePole: equatorPole } : {}),
|
||||
orbitSource: `JPL SSD satellite mean elements, epoch ${epoch[1]} ${epoch[2]} ${Math.floor(Number(epoch[3]))}`
|
||||
};
|
||||
}
|
||||
|
||||
/** What this reads of a JPL Small-Body Database answer (`sbdb.api?sstr=…&phys-par=1&full-prec=1`). */
|
||||
export interface SbdbAnswer {
|
||||
orbit: { epoch: string; elements: Array<{ name: string; value: string | null }> };
|
||||
phys_par?: Array<{ name: string; value: string | null }>;
|
||||
}
|
||||
|
||||
export interface SmallBody extends MeanOrbit {
|
||||
radiusKm?: number;
|
||||
rotationPeriodHours?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A dwarf planet from the Small-Body Database: its osculating heliocentric elements against the
|
||||
* J2000 ecliptic, the frame Standish's are in, carried round at their own mean motion n with
|
||||
* nothing turning. Standish's tables stop at Pluto and JPL publishes no mean elements for the
|
||||
* others, so these are exact on their epoch and drift from it — for Ceres, whose orbit Jupiter
|
||||
* pulls on, by degrees within decades; see the ETL's check against Horizons.
|
||||
*
|
||||
* Radius and spin come from the same answer where it has them: half the published diameter, and
|
||||
* the rotation period, in hours.
|
||||
*/
|
||||
export function parseSmallBodyElements(answer: SbdbAnswer): SmallBody {
|
||||
const element = (name: string): number => {
|
||||
const value = Number(answer.orbit.elements.find((candidate) => candidate.name === name)?.value ?? NaN);
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error(`The SBDB answer has no element ${name}.`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
const physical = (name: string): number | undefined => {
|
||||
const value = Number(answer.phys_par?.find((candidate) => candidate.name === name)?.value ?? NaN);
|
||||
return Number.isFinite(value) ? value : undefined;
|
||||
};
|
||||
const epochJd = Number(answer.orbit.epoch);
|
||||
const epoch = new Date((epochJd - 2440587.5) * 86400000);
|
||||
const diameterKm = physical('diameter');
|
||||
const rotationPeriodHours = physical('rot_per');
|
||||
|
||||
return {
|
||||
orbit: {
|
||||
semiMajorAxisAu: element('a'),
|
||||
eccentricity: element('e'),
|
||||
inclinationDeg: element('i'),
|
||||
longitudeOfAscendingNodeDeg: element('om'),
|
||||
argumentOfPeriapsisDeg: element('w'),
|
||||
meanAnomalyAtEpochDeg: element('ma'),
|
||||
epochJd
|
||||
},
|
||||
rates: { meanMotionDegPerDay: element('n'), longitudeOfAscendingNodeDegPerDay: 0, argumentOfPeriapsisDegPerDay: 0 },
|
||||
orbitSource: `JPL SBDB osculating elements, epoch ${epoch.getUTCFullYear()} ${MONTHS[epoch.getUTCMonth()]} ${epoch.getUTCDate()}`,
|
||||
...(diameterKm !== undefined ? { radiusKm: diameterKm / 2 } : {}),
|
||||
...(rotationPeriodHours !== undefined ? { rotationPeriodHours } : {})
|
||||
};
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { meanElementsAt } from './kepler';
|
||||
import { orbitalTermsOfPrimeMeridian, orientationAt, parsePckRotationalElements } from './rotational-elements';
|
||||
import { MeanElementRates, OrbitalElements, RotationalElements } from '../models/body.model';
|
||||
|
||||
// Excerpts of pck00011.tpc as NAIF publishes it: prose, then data blocks.
|
||||
const KERNEL = String.raw`KPL/PCK
|
||||
|
||||
The portion of the file preceding the first data block is treated
|
||||
as a comment.
|
||||
|
||||
\begindata
|
||||
|
||||
BODY399_POLE_RA = ( 0. -0.641 0. )
|
||||
BODY399_POLE_DEC = ( 90. -0.557 0. )
|
||||
BODY399_PM = ( 190.147 360.9856235 0. )
|
||||
|
||||
\begintext
|
||||
|
||||
A data block starts with the \begindata token only when that token
|
||||
sits on a line by itself, so BODY399_PM = ( 1 2 3 ) here is prose.
|
||||
|
||||
\begindata
|
||||
|
||||
BODY301_POLE_RA = ( 269.9949 0.0031 0. )
|
||||
BODY301_POLE_DEC = ( 66.5392 0.0130 0. )
|
||||
BODY301_PM = ( 38.3213 13.17635815 -1.4D-12 )
|
||||
|
||||
BODY899_POLE_RA = ( 299.36 0. 0. )
|
||||
BODY899_POLE_DEC = ( 43.46 0. 0. )
|
||||
BODY899_PM = ( 249.978 541.1397757 0. )
|
||||
BODY899_NUT_PREC_RA = ( 0.70 0. 0. 0. 0. 0. 0. 0. )
|
||||
BODY899_NUT_PREC_DEC = ( -0.51 0. 0. 0. 0. 0. 0. 0. )
|
||||
BODY899_NUT_PREC_PM = ( -0.48 0. 0. 0. 0. 0. 0. 0. )
|
||||
BODY8_NUT_PREC_ANGLES = ( 357.85 52.316
|
||||
323.92 62606.6 )
|
||||
|
||||
BODY199_POLE_RA = ( 281.0103 -0.0328 0. )
|
||||
BODY199_POLE_DEC = ( 61.4155 -0.0049 0. )
|
||||
BODY199_PM = ( 329.5988 6.1385108 0. )
|
||||
BODY199_NUT_PREC_RA = ( 0. 0. )
|
||||
BODY199_NUT_PREC_DEC = ( 0. 0. )
|
||||
BODY199_NUT_PREC_PM = ( 0.01067257
|
||||
-0.00112309 )
|
||||
BODY1_NUT_PREC_ANGLES = ( 174.7910857 0.14947253587500003E+06
|
||||
349.5821714 0.29894507175000006E+06 )
|
||||
|
||||
BODY401_POLE_RA = ( 317.67071657 -0.10844326 0. )
|
||||
BODY401_POLE_DEC = ( 52.88627266 -0.06134706 0. )
|
||||
BODY401_PM = ( 35.18774440 1128.84475928
|
||||
9.536137031212154e-09 )
|
||||
BODY401_NUT_PREC_RA = ( -1.78428399 )
|
||||
BODY401_NUT_PREC_DEC = ( -1.07516537 )
|
||||
BODY401_NUT_PREC_PM = ( 1.42421769
|
||||
-1.143 )
|
||||
BODY4_MAX_PHASE_DEGREE = 2
|
||||
BODY4_NUT_PREC_ANGLES = (
|
||||
190.72646643 15917.10818695 0
|
||||
189.63271560 41215158.18420050 12.711923222 )
|
||||
|
||||
\begintext
|
||||
`;
|
||||
|
||||
describe('parsePckRotationalElements', () => {
|
||||
it('reads a pole and a prime meridian from the data blocks, not from the prose around them', () => {
|
||||
expect(parsePckRotationalElements(KERNEL, 399)).toEqual({
|
||||
elements: { poleRaDeg: [0, -0.641, 0], poleDecDeg: [90, -0.557, 0], primeMeridianDeg: [190.147, 360.9856235, 0] },
|
||||
skippedDeg: []
|
||||
});
|
||||
});
|
||||
|
||||
it('reads the exponent the Fortran way, as the Moon’s quadratic is written', () => {
|
||||
expect(parsePckRotationalElements(KERNEL, 301)!.elements.primeMeridianDeg).toEqual([38.3213, 13.17635815, -1.4e-12]);
|
||||
});
|
||||
|
||||
it('pairs each periodic term with its system’s angle', () => {
|
||||
expect(parsePckRotationalElements(KERNEL, 899)!.elements.terms).toEqual([{ angleDeg: [357.85, 52.316], ra: 0.7, dec: -0.51, pm: -0.48 }]);
|
||||
});
|
||||
|
||||
it('reads angles to the degree the system states, Phobos’s quadratic among them', () => {
|
||||
expect(parsePckRotationalElements(KERNEL, 401)!.elements.terms).toEqual([
|
||||
{ angleDeg: [190.72646643, 15917.10818695, 0], ra: -1.78428399, dec: -1.07516537, pm: 1.42421769 },
|
||||
{ angleDeg: [189.6327156, 41215158.1842005, 12.711923222], ra: 0, dec: 0, pm: -1.143 }
|
||||
]);
|
||||
});
|
||||
|
||||
it('leaves out a term under a hundredth of a degree, and says how large it was', () => {
|
||||
const mercury = parsePckRotationalElements(KERNEL, 199)!;
|
||||
|
||||
expect(mercury.elements.terms).toEqual([{ angleDeg: [174.7910857, 149472.53587500003], ra: 0, dec: 0, pm: 0.01067257 }]);
|
||||
expect(mercury.skippedDeg).toEqual([0.00112309]);
|
||||
});
|
||||
|
||||
it('gives nothing for a body the kernel has no model for', () => {
|
||||
expect(parsePckRotationalElements(KERNEL, 802)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('orientationAt', () => {
|
||||
const J2000 = 2451545.0;
|
||||
|
||||
it('turns the prime meridian at its rate per day and moves the pole at its rate per century', () => {
|
||||
const earth = parsePckRotationalElements(KERNEL, 399)!.elements;
|
||||
|
||||
const epoch = orientationAt(earth, J2000);
|
||||
expect([epoch.poleRaDeg, epoch.poleDecDeg]).toEqual([0, 90]);
|
||||
expect(epoch.primeMeridianDeg).toBeCloseTo(190.147, 9);
|
||||
const century = orientationAt(earth, J2000 + 36525);
|
||||
expect(century.poleRaDeg).toBeCloseTo(-0.641, 12);
|
||||
expect(century.poleDecDeg).toBeCloseTo(90 - 0.557, 12);
|
||||
expect(orientationAt(earth, J2000 + 1).primeMeridianDeg).toBeCloseTo(190.147 + 360.9856235 - 360, 9);
|
||||
});
|
||||
|
||||
it('adds a term as a sine to the right ascension and the meridian and a cosine to the declination', () => {
|
||||
const neptune = parsePckRotationalElements(KERNEL, 899)!.elements;
|
||||
const days = 9000;
|
||||
const angle = ((357.85 + (52.316 * days) / 36525) * Math.PI) / 180;
|
||||
const drawn = orientationAt(neptune, J2000 + days);
|
||||
|
||||
expect(drawn.poleRaDeg).toBeCloseTo(299.36 + 0.7 * Math.sin(angle), 12);
|
||||
expect(drawn.poleDecDeg).toBeCloseTo(43.46 - 0.51 * Math.cos(angle), 12);
|
||||
expect(drawn.primeMeridianDeg).toBeCloseTo((249.978 + 541.1397757 * days - 0.48 * Math.sin(angle)) % 360, 6);
|
||||
});
|
||||
|
||||
it('carries the quadratic in the meridian and in the angle, which is how Phobos falls inward', () => {
|
||||
const phobos = parsePckRotationalElements(KERNEL, 401)!.elements;
|
||||
const days = 36525;
|
||||
const first = (190.72646643 + 15917.10818695) * (Math.PI / 180);
|
||||
const second = (189.6327156 + 41215158.1842005 + 12.711923222) * (Math.PI / 180);
|
||||
const expected = 35.1877444 + 1128.84475928 * days + 9.536137031212154e-9 * days * days + 1.42421769 * Math.sin(first) - 1.143 * Math.sin(second);
|
||||
|
||||
expect(orientationAt(phobos, J2000 + days).primeMeridianDeg).toBeCloseTo(((expected % 360) + 360) % 360, 5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('orbitalTermsOfPrimeMeridian', () => {
|
||||
const J2000 = 2451545.0;
|
||||
// Mimas's and Phobos's rows and W as pck00011.tpc and JPL's table give them, with each mean
|
||||
// motion set to W's rate, so that only the terms can part the two.
|
||||
const MIMAS: RotationalElements = {
|
||||
poleRaDeg: [40.66, -0.036],
|
||||
poleDecDeg: [83.52, -0.004],
|
||||
primeMeridianDeg: [333.46, 381.994555, 0],
|
||||
terms: [
|
||||
{ angleDeg: [177.4, -36505.5], ra: 13.56, dec: -1.53, pm: -13.48 },
|
||||
{ angleDeg: [316.45, 506.2], ra: 0, dec: 0, pm: -44.85 }
|
||||
]
|
||||
};
|
||||
const PHOBOS: RotationalElements = {
|
||||
poleRaDeg: [317.67071657, -0.10844326, 0],
|
||||
poleDecDeg: [52.88627266, -0.06134706, 0],
|
||||
primeMeridianDeg: [35.1877444, 1128.84475928, 9.536137031212154e-9]
|
||||
};
|
||||
const orbit = (epochJd: number): OrbitalElements => ({
|
||||
semiMajorAxisAu: 0.001,
|
||||
eccentricity: 0.02,
|
||||
inclinationDeg: 1.5,
|
||||
longitudeOfAscendingNodeDeg: 170,
|
||||
argumentOfPeriapsisDeg: 60,
|
||||
meanAnomalyAtEpochDeg: 10,
|
||||
epochJd
|
||||
});
|
||||
|
||||
/** The moon's mean longitude less W, which a locked moon holds still whatever the date. */
|
||||
function lead(elements: RotationalElements, epochJd: number, angleRate: number | undefined, jd: number): number {
|
||||
const { meanAnomalyTerms, meanMotionDegPerDay, meanAnomalyDeg } = orbitalTermsOfPrimeMeridian(elements, epochJd, angleRate);
|
||||
const start = orbit(epochJd);
|
||||
const rates: MeanElementRates = {
|
||||
meanMotionDegPerDay: elements.primeMeridianDeg[1] + meanMotionDegPerDay,
|
||||
longitudeOfAscendingNodeDegPerDay: -1,
|
||||
argumentOfPeriapsisDegPerDay: 2,
|
||||
meanAnomalyTerms
|
||||
};
|
||||
const moved = meanElementsAt({ ...start, meanAnomalyAtEpochDeg: start.meanAnomalyAtEpochDeg + meanAnomalyDeg }, rates, jd);
|
||||
const longitude = moved.longitudeOfAscendingNodeDeg + moved.argumentOfPeriapsisDeg + moved.meanAnomalyAtEpochDeg;
|
||||
// W with the pole's nodding term left out: that one is the pole's, not the orbit's.
|
||||
const w = orientationAt({ ...elements, terms: elements.terms?.filter((term) => term.angleDeg[1] === angleRate) }, jd).primeMeridianDeg;
|
||||
return (((longitude - w) % 360) + 540) % 360 - 180;
|
||||
}
|
||||
|
||||
it('moves Mimas along its orbit by the libration its W carries, over the 71 years it takes', () => {
|
||||
const atEpoch = lead(MIMAS, J2000, 506.2, J2000);
|
||||
for (const years of [-130, -40, 17.8, 35.5, 100]) {
|
||||
expect(lead(MIMAS, J2000, 506.2, J2000 + years * 365.25)).toBeCloseTo(atEpoch, 8);
|
||||
}
|
||||
});
|
||||
|
||||
it('speeds Phobos up by the tidal quadratic its W carries about J2000, from a row whose epoch is 1950', () => {
|
||||
const epoch = 2433282.5;
|
||||
const atEpoch = lead(PHOBOS, epoch, undefined, epoch);
|
||||
for (const years of [-150, 0, 50, 100, 150, 400]) {
|
||||
expect(lead(PHOBOS, epoch, undefined, J2000 + years * 365.25)).toBeCloseTo(atEpoch, 6);
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a term W does not carry', () => {
|
||||
expect(() => orbitalTermsOfPrimeMeridian(PHOBOS, J2000, 506.2)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,171 +0,0 @@
|
||||
import { RotationalElements } from '../models/body.model';
|
||||
|
||||
/**
|
||||
* Reads the IAU WGCCRE 2015 rotational elements from NAIF's text kernel `pck00011.tpc`, which the
|
||||
* ETL fetches (see `tools/etl/lib/pck.ts`), and evaluates them at a date.
|
||||
*/
|
||||
|
||||
const J2000_JD = 2451545.0;
|
||||
const DAYS_PER_JULIAN_CENTURY = 36525;
|
||||
const DEG_TO_RAD = Math.PI / 180;
|
||||
|
||||
/**
|
||||
* The smallest periodic term kept, in degrees. A term turns the body, or tips its pole, by at most
|
||||
* its amplitude, and the largest a body is ever drawn is Jupiter filling the screen at 641 px of
|
||||
* radius, where 0.01 degrees moves a point on its surface by 0.11 px. In `pck00011.tpc` this
|
||||
* leaves out 32 terms: Mercury's four smaller librations (0.0011 degrees and less), eight of the
|
||||
* Moon's thirteen (0.0072 and less), the thirteen short-period terms of Mars's pole and meridian
|
||||
* (0.00024 and less; its three 0.42-1.59 degree long-period ones stay), one of Phobos's (0.0063),
|
||||
* Jupiter's five (0.0022 and less) and one of Europa's (0.009). Mimas's 44.85-degree libration,
|
||||
* Triton's 32-degree precession and Miranda's 4.4 are kept, down to Triton's 0.01.
|
||||
*/
|
||||
export const MIN_PERIODIC_TERM_DEG = 0.01;
|
||||
|
||||
/**
|
||||
* Every `NAME = ( values )` assignment in the kernel's data blocks. A data block runs from a line
|
||||
* holding only `\begindata` to one holding only `\begintext`; the kernel's own prose mentions both
|
||||
* tokens mid-sentence, which is why they are only read alone on a line. Exponents are written
|
||||
* the Fortran way, `-1.4D-12`.
|
||||
*/
|
||||
function pckVariables(text: string): Map<string, number[]> {
|
||||
const data = text
|
||||
.split(/^\s*\\begindata\s*$/m)
|
||||
.slice(1)
|
||||
.map((block) => block.split(/^\s*\\begintext\s*$/m)[0])
|
||||
.join('\n');
|
||||
const variables = new Map<string, number[]>();
|
||||
for (const [, name, value] of data.matchAll(/(\w+)\s*=\s*(\([^)]*\)|\S+)/g)) {
|
||||
variables.set(
|
||||
name,
|
||||
value
|
||||
.replace(/[()]/g, ' ')
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.filter(Boolean)
|
||||
.map((token) => Number(token.replace(/d/i, 'e')))
|
||||
);
|
||||
}
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* One body's elements, by its NAIF id: 399 for Earth, 301 for the Moon, 2000001 for Ceres.
|
||||
* Undefined where the kernel has none.
|
||||
*
|
||||
* The periodic terms' angles belong to the planet's whole system, `BODY5_NUT_PREC_ANGLES` for
|
||||
* Jupiter and its moons, each a polynomial in T whose degree `BODYn_MAX_PHASE_DEGREE` gives: 1
|
||||
* unless stated, 2 for Mars, where Phobos's angle carries the tidal acceleration that is drawing
|
||||
* it in. A term is kept if any of its three amplitudes reaches {@link MIN_PERIODIC_TERM_DEG};
|
||||
* the largest amplitude of each term left out comes back in `skippedDeg`, for the ETL to say so.
|
||||
*/
|
||||
export function parsePckRotationalElements(text: string, naifId: number): { elements: RotationalElements; skippedDeg: number[] } | undefined {
|
||||
const variables = pckVariables(text);
|
||||
const poleRaDeg = variables.get(`BODY${naifId}_POLE_RA`);
|
||||
const poleDecDeg = variables.get(`BODY${naifId}_POLE_DEC`);
|
||||
const primeMeridianDeg = variables.get(`BODY${naifId}_PM`);
|
||||
if (!poleRaDeg || !poleDecDeg || !primeMeridianDeg) {
|
||||
return undefined;
|
||||
}
|
||||
if (![...poleRaDeg, ...poleDecDeg, ...primeMeridianDeg].every(Number.isFinite)) {
|
||||
throw new Error(`Body ${naifId}'s pole or prime meridian did not parse.`);
|
||||
}
|
||||
|
||||
const ra = variables.get(`BODY${naifId}_NUT_PREC_RA`) ?? [];
|
||||
const dec = variables.get(`BODY${naifId}_NUT_PREC_DEC`) ?? [];
|
||||
const pm = variables.get(`BODY${naifId}_NUT_PREC_PM`) ?? [];
|
||||
const system = naifId < 1000 ? Math.floor(naifId / 100) : undefined;
|
||||
const angles = system === undefined ? [] : (variables.get(`BODY${system}_NUT_PREC_ANGLES`) ?? []);
|
||||
const coefficients = (variables.get(`BODY${system}_MAX_PHASE_DEGREE`)?.[0] ?? 1) + 1;
|
||||
|
||||
const terms: NonNullable<RotationalElements['terms']> = [];
|
||||
const skippedDeg: number[] = [];
|
||||
for (let index = 0; index < Math.max(ra.length, dec.length, pm.length); index++) {
|
||||
const term = { ra: ra[index] ?? 0, dec: dec[index] ?? 0, pm: pm[index] ?? 0 };
|
||||
const largest = Math.max(Math.abs(term.ra), Math.abs(term.dec), Math.abs(term.pm));
|
||||
if (largest === 0) {
|
||||
continue;
|
||||
}
|
||||
if (largest < MIN_PERIODIC_TERM_DEG) {
|
||||
skippedDeg.push(largest);
|
||||
continue;
|
||||
}
|
||||
const angleDeg = angles.slice(index * coefficients, (index + 1) * coefficients);
|
||||
if (angleDeg.length !== coefficients || !angleDeg.every(Number.isFinite)) {
|
||||
throw new Error(`Body ${naifId}'s periodic term ${index + 1} has no angle among BODY${system}_NUT_PREC_ANGLES.`);
|
||||
}
|
||||
terms.push({ angleDeg, ...term });
|
||||
}
|
||||
|
||||
return {
|
||||
elements: { poleRaDeg, poleDecDeg, primeMeridianDeg, ...(terms.length > 0 ? { terms } : {}) },
|
||||
skippedDeg
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Sun's, which is no `BodyRecord` but the system's star marker: NAIF body 10 in pck00011.tpc,
|
||||
* the WGCCRE 2015 pole at RA 286.13, Dec 63.87 and W = 84.176 + 14.1844 d, a sidereal day of 25.38
|
||||
* days at the Carrington latitude. The ETL checks them against the kernel.
|
||||
*/
|
||||
export const SUN_ROTATIONAL_ELEMENTS: RotationalElements = { poleRaDeg: [286.13, 0, 0], poleDecDeg: [63.87, 0, 0], primeMeridianDeg: [84.176, 14.1844, 0] };
|
||||
|
||||
function polynomial(coefficients: readonly number[], x: number): number {
|
||||
return (coefficients[0] ?? 0) + (coefficients[1] ?? 0) * x + (coefficients[2] ?? 0) * x * x;
|
||||
}
|
||||
|
||||
/** The pole's right ascension and declination and the prime meridian W, in degrees, at a TDB Julian date. */
|
||||
export function orientationAt(elements: RotationalElements, jdTdb: number): { poleRaDeg: number; poleDecDeg: number; primeMeridianDeg: number } {
|
||||
const days = jdTdb - J2000_JD;
|
||||
const centuries = days / DAYS_PER_JULIAN_CENTURY;
|
||||
let poleRaDeg = polynomial(elements.poleRaDeg, centuries);
|
||||
let poleDecDeg = polynomial(elements.poleDecDeg, centuries);
|
||||
let primeMeridianDeg = polynomial(elements.primeMeridianDeg, days);
|
||||
for (const term of elements.terms ?? []) {
|
||||
const angle = polynomial(term.angleDeg, centuries) * DEG_TO_RAD;
|
||||
poleRaDeg += term.ra * Math.sin(angle);
|
||||
poleDecDeg += term.dec * Math.cos(angle);
|
||||
primeMeridianDeg += term.pm * Math.sin(angle);
|
||||
}
|
||||
return { poleRaDeg, poleDecDeg, primeMeridianDeg: ((primeMeridianDeg % 360) + 360) % 360 };
|
||||
}
|
||||
|
||||
/**
|
||||
* What a locked moon's W says of its going round that a row of mean elements leaves out, as terms
|
||||
* of that row. W follows the moon's mean longitude, so a term of W that is the moon running ahead
|
||||
* of and behind its mean motion, rather than its pole nodding, is its orbit's too. Two are here,
|
||||
* and JPL's satellite table has a column for neither: Mimas's -44.85 degrees and Tethys's +2.23 on
|
||||
* the angle that turns 506.2 degrees a century, the 71-year libration of their 4:2 resonance, and
|
||||
* Phobos's quadratic, 12.72 degrees per century squared about J2000, the tidal acceleration
|
||||
* drawing it in. Carried by W and not by the orbit, they left the drawn Mimas up to 45 degrees from
|
||||
* where Horizons has it and its face as far from Saturn, and Phobos 11 degrees out by 2100.
|
||||
*
|
||||
* `angleRateDegPerCentury` names the term by its angle's rate; W's quadratic, where it has one, is
|
||||
* always taken. Both come back about `epochJd`, which is where `meanAnomalyTerms` counts T from:
|
||||
* the sine as its `c` and `s`, and the quadratic re-centred from J2000 onto that epoch, as `b` plus
|
||||
* what the re-centring adds to the mean motion and to the mean anomaly at the epoch.
|
||||
*/
|
||||
export function orbitalTermsOfPrimeMeridian(
|
||||
elements: RotationalElements,
|
||||
epochJd: number,
|
||||
angleRateDegPerCentury?: number
|
||||
): { meanAnomalyTerms: { b: number; c: number; s: number; f: number }; meanMotionDegPerDay: number; meanAnomalyDeg: number } {
|
||||
const epochCenturies = (epochJd - J2000_JD) / DAYS_PER_JULIAN_CENTURY;
|
||||
// W turns clockwise about the pole the IAU names where its rate is negative; the orbit does not.
|
||||
const sense = Math.sign(elements.primeMeridianDeg[1]);
|
||||
const quadratic = sense * (elements.primeMeridianDeg[2] ?? 0) * DAYS_PER_JULIAN_CENTURY * DAYS_PER_JULIAN_CENTURY;
|
||||
let sine = { c: 0, s: 0, f: 0 };
|
||||
if (angleRateDegPerCentury !== undefined) {
|
||||
const term = elements.terms?.find((candidate) => candidate.angleDeg[1] === angleRateDegPerCentury);
|
||||
if (!term || (term.angleDeg[2] ?? 0) !== 0) {
|
||||
throw new Error(`No term of W turns linearly at ${angleRateDegPerCentury} degrees a century.`);
|
||||
}
|
||||
const phase = (term.angleDeg[0] + term.angleDeg[1] * epochCenturies) * DEG_TO_RAD;
|
||||
sine = { c: sense * term.pm * Math.sin(phase), s: sense * term.pm * Math.cos(phase), f: term.angleDeg[1] };
|
||||
}
|
||||
// q (T + T0)², T from the epoch and T0 the epoch from J2000, is q T² + 2 q T0 T + q T0².
|
||||
return {
|
||||
meanAnomalyTerms: { b: quadratic, ...sine },
|
||||
meanMotionDegPerDay: (2 * quadratic * epochCenturies) / DAYS_PER_JULIAN_CENTURY,
|
||||
meanAnomalyDeg: quadratic * epochCenturies * epochCenturies
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Keplerian orbital elements at a reference epoch. Positions are derived client-side by
|
||||
* propagating these elements forward/backward from `epochJd` (see `shared/astro/kepler.ts`),
|
||||
* rather than fetching per-frame positions.
|
||||
* Osculating Keplerian orbital elements at a reference epoch. Positions are derived
|
||||
* client-side by propagating these elements forward/backward from `epochJd` (see
|
||||
* `shared/astro/kepler.ts`), rather than fetching per-frame positions.
|
||||
*/
|
||||
export interface OrbitalElements {
|
||||
semiMajorAxisAu: number;
|
||||
@@ -14,127 +14,19 @@ export interface OrbitalElements {
|
||||
}
|
||||
|
||||
/**
|
||||
* How a body's mean elements move away from their epoch, per day.
|
||||
*
|
||||
* Mean elements rather than one osculating set, because the map's clock runs decades in minutes.
|
||||
* An osculating orbit is exact at its instant and drifts from then on: fed to Kepler with a mass
|
||||
* ratio, the Moon's went round in 27.70 days instead of 27.32 and was 66 degrees out after a year.
|
||||
* A mean set carries its own measured motion, and the slow turning of its node and periapsis, so
|
||||
* it holds for as long as its source was fit over.
|
||||
*/
|
||||
export interface MeanElementRates {
|
||||
/**
|
||||
* How fast the body goes round in space, in degrees per day: the rate of its mean longitude.
|
||||
* 360 over this is its sidereal period.
|
||||
*/
|
||||
meanMotionDegPerDay: number;
|
||||
longitudeOfAscendingNodeDegPerDay: number;
|
||||
argumentOfPeriapsisDegPerDay: number;
|
||||
semiMajorAxisAuPerDay?: number;
|
||||
eccentricityPerDay?: number;
|
||||
inclinationDegPerDay?: number;
|
||||
/**
|
||||
* Standish's extra terms in the mean anomaly of Jupiter and beyond, `b T² + c cos(f T) +
|
||||
* s sin(f T)` degrees, with T in Julian centuries from the epoch and f in degrees per century:
|
||||
* the great-inequality wobble his 3000 BC to AD 3000 fit needs on top of its linear rates.
|
||||
*/
|
||||
meanAnomalyTerms?: { b: number; c: number; s: number; f: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* A solar-system planet, moon, or dwarf planet: JPL mean orbital elements, and JPL Horizons
|
||||
* physical data. `systemStarId` links back to the HYG star index (the Sun, see `SUN_STAR_ID`).
|
||||
* A solar-system planet, moon, or dwarf planet, sourced from JPL Horizons/SSD orbital
|
||||
* elements. `systemStarId` links back to the HYG star index (the Sun, see `SUN_STAR_ID`).
|
||||
*/
|
||||
export interface BodyRecord {
|
||||
id: string;
|
||||
systemStarId: number;
|
||||
name: string;
|
||||
kind: 'planet' | 'moon' | 'dwarf';
|
||||
/** Mean radius: for a triaxial body, the radius of the sphere of its volume, which is how it is drawn. */
|
||||
radiusKm: number;
|
||||
/**
|
||||
* A triaxial body's three semi-axes, in km, largest first, where its shape is too far from a
|
||||
* sphere for one radius to say it: Haumea's 1161 x 852 x 513 (Ortiz et al. 2017), whose mean
|
||||
* radius is 798.
|
||||
*/
|
||||
semiAxesKm?: readonly [number, number, number];
|
||||
/** Mean elements at `orbit.epochJd`, moving at `rates`. */
|
||||
orbit: OrbitalElements;
|
||||
rates: MeanElementRates;
|
||||
/**
|
||||
* The pole of the plane a moon's elements are measured against, where that is its local
|
||||
* Laplace plane or, for Uranus's and Pluto's moons, the planet's equator: right ascension and
|
||||
* declination in the ICRF. The node is then counted from where that plane crosses the ICRF
|
||||
* equator. Absent means the J2000 ecliptic, as for the planets and the Moon.
|
||||
*/
|
||||
laplacePole?: { raDeg: number; decDeg: number };
|
||||
/** Where the elements come from and the span they hold over, as the card prints it. */
|
||||
orbitSource: string;
|
||||
/**
|
||||
* The eccentricity the card prints, where it is not the orbit's own: Hyperion's row in the table
|
||||
* its orbit is drawn from gives 0.0232, under a quarter of the 0.105 JPL's current table (SAT441)
|
||||
* and Horizons (0.074 to 0.132 from 1980 to 2100) give. The older row still places Hyperion
|
||||
* nearer where Horizons has it than the same row with 0.105 does, so the orbit keeps it.
|
||||
*/
|
||||
measuredEccentricity?: number;
|
||||
/**
|
||||
* For `kind: 'moon'`, the `id` of the planet it orbits — its `orbit` is expressed
|
||||
* relative to that planet, not heliocentrically. Undefined for planets/dwarfs.
|
||||
*/
|
||||
parentBodyId?: string;
|
||||
/**
|
||||
* For a moon heavy enough that it and its planet go round a point outside the planet — Charon,
|
||||
* an eighth of Pluto's mass, puts it 2 100 km from Pluto's centre, 900 km above its surface —
|
||||
* the moon's mass over the planet's, from the GMs on their Horizons pages. The planet's own
|
||||
* elements then place that barycentre, as Standish's "Pluto" does, and both bodies are drawn
|
||||
* going round it. Absent for every other moon.
|
||||
*/
|
||||
massRatio?: number;
|
||||
/**
|
||||
* How the body turns on its own axis: the sidereal rotation period in hours, negative where
|
||||
* Horizons gives a negative rate (Venus, Uranus), and the tilt of that axis from its orbital
|
||||
* plane — which past 90 degrees already says the turn is retrograde.
|
||||
*
|
||||
* For a locked moon the period is its orbit's, from the mean motion that carries it round. Where
|
||||
* the source states none, or one a later measurement overturns, it is the one the body's ETL spec
|
||||
* carries: Nereid's K2 light curve, Eris's lock to Dysnomia. Absent only for Hyperion, which
|
||||
* tumbles — the view leaves it still rather than spinning it at an invented rate.
|
||||
*/
|
||||
rotationPeriodHours?: number;
|
||||
obliquityDeg?: number;
|
||||
/**
|
||||
* Where the body's pole points and which way its prime meridian faces at any date, from the IAU
|
||||
* WGCCRE 2015 report (Archinal et al. 2018) as NAIF's `pck00011.tpc` carries it, but that a locked
|
||||
* moon's W, and its pole's terms that turn within 5 per cent of a multiple of its node's rate, turn
|
||||
* at its drawn orbit's rates and Iapetus's pole goes round with its orbit's, so they keep their
|
||||
* faces to their planets, and their poles round their orbits', over the clock's AD 1 to 3000 (see
|
||||
* `lockedToOrbit` in the ETL). The Moon's and Phobos's, whose W has a quadratic, are the IAU's
|
||||
* whole, and so are the terms Ariel's, Umbriel's, Titania's and Oberon's poles go round on, which
|
||||
* turn at none of their nodes' multiples. Where present it alone sets how the body is drawn, and
|
||||
* the ETL checks the period and obliquity above against it. Absent where the report gives none: Hyperion tumbles, and Nereid,
|
||||
* Eris, Haumea and Makemake have no model.
|
||||
*/
|
||||
rotationalElements?: RotationalElements;
|
||||
}
|
||||
|
||||
/**
|
||||
* The IAU's rotational elements for one body: polynomials in time, plus periodic terms.
|
||||
*
|
||||
* The pole's right ascension and declination are in degrees in the ICRF, `[c0, c1, c2]` for
|
||||
* `c0 + c1 T + c2 T²`, T in Julian centuries from J2000.0 TDB. The prime meridian W is the angle
|
||||
* along the body's equator, anticlockwise seen from above that pole, from where the equator rises
|
||||
* through the ICRF equator to the body's longitude 0, `c0 + c1 d + c2 d²` with d in days. A
|
||||
* negative rate turns the body clockwise about the pole the IAU names: Venus, Uranus and its
|
||||
* moons, Triton.
|
||||
*/
|
||||
export interface RotationalElements {
|
||||
poleRaDeg: number[];
|
||||
poleDecDeg: number[];
|
||||
primeMeridianDeg: number[];
|
||||
/**
|
||||
* Each adds `ra sin θ` to the right ascension, `dec cos θ` to the declination and `pm sin θ` to
|
||||
* W, θ being `angleDeg[0] + angleDeg[1] T + angleDeg[2] T²`. The smallest are left out; see
|
||||
* `parsePckRotationalElements`.
|
||||
*/
|
||||
terms?: Array<{ angleDeg: number[]; ra: number; dec: number; pm: number }>;
|
||||
}
|
||||
|
||||
@@ -12,11 +12,6 @@ export interface ExoplanetRecord {
|
||||
radiusEarth?: number;
|
||||
massEarth?: number;
|
||||
discoveryYear?: number;
|
||||
/**
|
||||
* True where the archive flags the planet as detected by imaging (`ima_flag`): photographed as a
|
||||
* point of light beside its star, as HR 8799's four planets were. Absent for every other planet.
|
||||
*/
|
||||
imaged?: true;
|
||||
/**
|
||||
* Measured orbital period in days (`pl_orbper`). Together with the semi-major axis this
|
||||
* pins the host star's gravitational parameter exactly, so the planet can be propagated at
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import * as THREE from 'three/webgpu';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { tdbFromUtc } from '../astro/constants';
|
||||
import { eclipticToEquatorial } from '../astro/coordinates';
|
||||
import { meanElementsAt, positionAtEpoch } from '../astro/kepler';
|
||||
import { BodyRecord } from '../models/body.model';
|
||||
import { bodyOrientation, bodyPageView } from './body-orientation';
|
||||
|
||||
// Earth (the Earth-Moon barycentre's mean elements) and the Moon as bodies.json carries them.
|
||||
const EARTH: BodyRecord = {
|
||||
id: 'earth', systemStarId: 0, name: 'Earth', kind: 'planet', radiusKm: 6371, orbitSource: 'test',
|
||||
orbit: {semiMajorAxisAu: 1.00000018, eccentricity: 0.01673163, inclinationDeg: -0.00054346, longitudeOfAscendingNodeDeg: -5.11260389, argumentOfPeriapsisDeg: 108.04266274, meanAnomalyAtEpochDeg: -2.4631431299999917, epochJd: 2451545},
|
||||
rates: {meanMotionDegPerDay: 0.9856091187759068, longitudeOfAscendingNodeDegPerDay: -0.000006604751813826146, argumentOfPeriapsisDegPerDay: 0.000015309819575633124, semiMajorAxisAuPerDay: -8.213552361396303e-13, eccentricityPerDay: -1.002327173169062e-9, inclinationDegPerDay: -3.6609938398357287e-7},
|
||||
rotationalElements: {poleRaDeg: [0, -0.641, 0], poleDecDeg: [90, -0.557, 0], primeMeridianDeg: [190.147, 360.9856235, 0]}
|
||||
};
|
||||
const MOON: BodyRecord = {
|
||||
id: 'moon', systemStarId: 0, name: 'Moon', kind: 'moon', radiusKm: 1737.4, orbitSource: 'test', parentBodyId: 'earth',
|
||||
orbit: {semiMajorAxisAu: 0.0025695552897999907, eccentricity: 0.0554, inclinationDeg: 5.16, longitudeOfAscendingNodeDeg: 125.08, argumentOfPeriapsisDeg: 318.15, meanAnomalyAtEpochDeg: 135.27, epochJd: 2451545},
|
||||
rates: {meanMotionDegPerDay: 13.176358, longitudeOfAscendingNodeDegPerDay: -0.052990660396105185, argumentOfPeriapsisDegPerDay: 0.164353223839846},
|
||||
rotationalElements: {poleRaDeg: [269.9949, 0.0031, 0], poleDecDeg: [66.5392, 0.013, 0], primeMeridianDeg: [38.3213, 13.17635815, -1.4e-12], terms: [{angleDeg: [125.045, -1935.5364525], ra: -3.8787, dec: 1.5419, pm: 3.561}, {angleDeg: [250.089, -3871.072905], ra: -0.1204, dec: 0.0239, pm: 0.1208}, {angleDeg: [260.008, 475263.3328725], ra: 0.07, dec: -0.0278, pm: -0.0642}, {angleDeg: [176.625, 487269.629985], ra: -0.0172, dec: 0.0068, pm: 0.0158}, {angleDeg: [357.529, 35999.0509575], ra: 0, dec: 0, pm: 0.0252}]}
|
||||
};
|
||||
const BODIES = [EARTH, MOON];
|
||||
const JUNE_1_2025_NOON_UTC = 2460828.0;
|
||||
/** The page's light, at (4, 3, 5): 38.7 degrees round from the camera's side. */
|
||||
const SUN_AZIMUTH = Math.atan2(4, 5);
|
||||
|
||||
/** The point of the page's sphere, as east longitude and latitude on its map, that faces the Sun. */
|
||||
function subSolarPoint(body: BodyRecord, jdUtc: number): { eastDeg: number; latDeg: number } {
|
||||
const sphere = new THREE.Mesh(new THREE.SphereGeometry(1, 64, 32));
|
||||
const sun = new THREE.Vector3();
|
||||
expect(bodyPageView(body, BODIES, jdUtc, SUN_AZIMUTH, sphere.quaternion, sun)).toBe(true);
|
||||
sphere.updateMatrixWorld();
|
||||
const hit = new THREE.Raycaster(sun.clone().multiplyScalar(4), sun.clone().negate()).intersectObject(sphere)[0];
|
||||
return { eastDeg: (hit.uv!.x - 0.5) * 360, latDeg: (hit.uv!.y - 0.5) * 180 };
|
||||
}
|
||||
|
||||
describe('bodyPageView', () => {
|
||||
it('lights the same face of Earth on its page: within 4 degrees of Greenwich at noon UTC, and where Horizons has it', () => {
|
||||
expect(Math.abs(subSolarPoint(EARTH, JUNE_1_2025_NOON_UTC).eastDeg)).toBeLessThan(4);
|
||||
// Horizons' sub-solar point from the Sun, 1.5795 E and 22.2604 N, is Earth as it was 8.43
|
||||
// minutes before, when the light arriving then left the Sun; its latitude is geodetic, on the
|
||||
// flattened Earth, where the sphere's is geocentric: 0.14 degrees apart at this latitude.
|
||||
const horizons = subSolarPoint(EARTH, JUNE_1_2025_NOON_UTC - 8.43351424 / 1440);
|
||||
const geodetic = (Math.atan(Math.tan((horizons.latDeg * Math.PI) / 180) / (1 - 1 / 298.257) ** 2) * 180) / Math.PI;
|
||||
expect(Math.abs(horizons.eastDeg - 1.579501)).toBeLessThan(0.1);
|
||||
expect(Math.abs(geodetic - 22.260426)).toBeLessThan(0.05);
|
||||
});
|
||||
|
||||
it('lights Earth’s face where Horizons does at the far end of the clock too: AD 1000 and AD 1', () => {
|
||||
// Horizons' sub-solar longitude from the Sun (observer quantity 14, TIME_TYPE=UT), Earth taken
|
||||
// one light-time back: 1.0510 E on JD 2086455 and 1.5606 E on JD 1721600. The IAU's W, taken at
|
||||
// UT + 69.184 s as it was, drew them 2.3 and 4.6 degrees west of that (2.0 and 4.3 at UT itself).
|
||||
for (const [jdUt, lightMinutes, eastDeg] of [[2086455, 8.45437443, 1.05101], [1721600, 8.45020842, 1.560644]]) {
|
||||
expect(Math.abs(subSolarPoint(EARTH, jdUt - lightMinutes / 1440).eastDeg - eastDeg)).toBeLessThan(0.15);
|
||||
}
|
||||
});
|
||||
|
||||
it('takes a moon’s Sun from where it and its planet are: the Moon’s sub-solar point is Horizons’', () => {
|
||||
const moon = subSolarPoint(MOON, JUNE_1_2025_NOON_UTC);
|
||||
// 116.2859 E and 1.5030 N, seen from Earth's centre.
|
||||
expect(Math.abs(moon.eastDeg - 116.285934)).toBeLessThan(0.1);
|
||||
expect(Math.abs(moon.latDeg - 1.503004)).toBeLessThan(0.05);
|
||||
});
|
||||
|
||||
it('takes the Sun where it stands at the same TDB instant the body is turned for, and Earth turned as the system view turns it', () => {
|
||||
// Earth's own sphere, turned as the system view turns it (by UT, see `bodyOrientation`), and
|
||||
// the Sun seen from Earth's mean place at the clock's date taken to TDB: the page must light that
|
||||
// same point of its map, today and at AD 1000, when TT was 1 574 s past UT.
|
||||
for (const jdUt of [JUNE_1_2025_NOON_UTC, 2086307.5]) {
|
||||
const planet = new THREE.Quaternion();
|
||||
const sun = new THREE.Vector3();
|
||||
bodyPageView(EARTH, BODIES, jdUt, SUN_AZIMUTH, planet, sun);
|
||||
const place = eclipticToEquatorial(positionAtEpoch(meanElementsAt(EARTH.orbit, EARTH.rates, tdbFromUtc(jdUt))));
|
||||
const expected = new THREE.Vector3(-place.x, -place.y, -place.z).normalize().applyQuaternion(bodyOrientation(EARTH.rotationalElements!, jdUt, undefined, true).invert());
|
||||
expect(sun.clone().applyQuaternion(planet.clone().invert()).angleTo(expected)).toBeLessThan(1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the pole up and the Sun where the page’s light stands, turning the body under it', () => {
|
||||
const planet = new THREE.Quaternion();
|
||||
const sun = new THREE.Vector3();
|
||||
for (const hours of [0, 6, 12]) {
|
||||
bodyPageView(EARTH, BODIES, JUNE_1_2025_NOON_UTC + hours / 24, SUN_AZIMUTH, planet, sun);
|
||||
expect(new THREE.Vector3(0, 1, 0).applyQuaternion(planet).angleTo(new THREE.Vector3(0, 1, 0))).toBeLessThan(1e-9);
|
||||
expect(Math.atan2(sun.x, sun.z)).toBeCloseTo(SUN_AZIMUTH, 9);
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves a body with no elements to the page, as it was', () => {
|
||||
const planet = new THREE.Quaternion(0.1, 0.2, 0.3, 0.9).normalize();
|
||||
const before = planet.clone();
|
||||
const sun = new THREE.Vector3(4, 3, 5);
|
||||
|
||||
expect(bodyPageView({ ...EARTH, rotationalElements: undefined }, BODIES, JUNE_1_2025_NOON_UTC, SUN_AZIMUTH, planet, sun)).toBe(false);
|
||||
expect(planet.equals(before)).toBe(true);
|
||||
expect(sun.toArray()).toEqual([4, 3, 5]);
|
||||
});
|
||||
});
|
||||
@@ -1,115 +0,0 @@
|
||||
import * as THREE from 'three/webgpu';
|
||||
|
||||
import { tdbFromUtc } from '../astro/constants';
|
||||
import { CartesianCoordinates, eclipticToEquatorial, laplacePlaneToEquatorial } from '../astro/coordinates';
|
||||
import { meanElementsAt, positionAtEpoch } from '../astro/kepler';
|
||||
import { orientationAt } from '../astro/rotational-elements';
|
||||
import { BodyRecord, RotationalElements } from '../models/body.model';
|
||||
|
||||
const DEG_TO_RAD = Math.PI / 180;
|
||||
const Y_AXIS = new THREE.Vector3(0, 1, 0);
|
||||
const Z_AXIS = new THREE.Vector3(0, 0, 1);
|
||||
|
||||
/**
|
||||
* How a surface map sits on a sphere, settled once for every map the app wraps.
|
||||
*
|
||||
* `THREE.SphereGeometry` is built round +Y and runs its u coordinate eastward, anticlockwise seen
|
||||
* from +Y, from a seam on -X: u = 0.5 faces +X and u = 0.75 faces -Z. Every photograph in
|
||||
* `texture-catalog.ts` is an equirectangular map centred on longitude 0 with east to the right —
|
||||
* Greenwich is in the middle of Earth's; on Mars's, Olympus Mons (226.2 E, which is -133.8) sits a
|
||||
* little over a third of the width left of centre; on the Moon's, Mare Crisium (59 E) is right of
|
||||
* centre and Mare Orientale (95 W) left of it; on Mercury's, the rayed crater Kuiper (31.5 W, 11 S)
|
||||
* is just left of centre and below the equator; on Venus's, Maxwell Montes (65.2 N, 3.3 E) is the
|
||||
* brightest spot, high and just right of centre — Solar System Scope ships that map turned half
|
||||
* round, south up, and it is kept turned back. A map labelled in west longitude, as most planets'
|
||||
* are, is still drawn with east to the right, as any map of a sphere seen from outside is; only its
|
||||
* numbers run the other way. So longitude 0 is +X and 90 E is -Z, and a quarter turn about X
|
||||
* carries that onto the IAU's body-fixed frame: pole +Z, prime meridian +X, 90 E +Y.
|
||||
*
|
||||
* The derived surfaces have no meridian of their own, and take the same convention.
|
||||
*/
|
||||
export const MAP_TO_BODY = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI / 2);
|
||||
|
||||
const scratchMatrix = new THREE.Matrix4();
|
||||
const scratchAxes = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];
|
||||
const scratchTurn = new THREE.Quaternion();
|
||||
|
||||
/**
|
||||
* Sets `target` to the rotation carrying a frame whose +Z is `pole` and whose +X is where its
|
||||
* equator rises through the ICRF equator into the ICRF: the frame the IAU counts W in, and the
|
||||
* one JPL refers a moon's Laplace plane to — so both go through {@link laplacePlaneToEquatorial}.
|
||||
*/
|
||||
export function poleFrame(pole: { raDeg: number; decDeg: number }, target = new THREE.Quaternion()): THREE.Quaternion {
|
||||
const [x, y, z] = scratchAxes.map((axis, index) => {
|
||||
const turned = laplacePlaneToEquatorial({ x: index === 0 ? 1 : 0, y: index === 1 ? 1 : 0, z: index === 2 ? 1 : 0 }, pole);
|
||||
return axis.set(turned.x, turned.y, turned.z);
|
||||
});
|
||||
return target.setFromRotationMatrix(scratchMatrix.makeBasis(x, y, z));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets `target` to the rotation carrying a sphere, wrapped in its map as `SphereGeometry` wraps it,
|
||||
* into the ICRF at the map's own clock: the map onto the body's frame, turned by W about the pole,
|
||||
* and on to where the pole points.
|
||||
*
|
||||
* The clock is UT and the IAU's elements run on TDB, 69.184 s ahead today and 1 574 s at AD 1000;
|
||||
* in 69 s Earth turns 0.29 degrees, Jupiter 0.70 and Phobos 0.90, so the date is taken to TDB here
|
||||
* (see `tdbFromUtc`). Earth, `followsUt`, is the one exception: its turning is what UT counts, so
|
||||
* it is turned by the IERS Earth Rotation Angle at the clock's date (IERS Conventions 2010, eq.
|
||||
* 5.15), counted from the node its W starts at, 90 degrees past its pole's right ascension. The
|
||||
* IAU's W for Earth, fitted to today, runs 6.3e-6 degrees a day slow of that once its pole's drift
|
||||
* is counted: taken at UT + 69.184 s, as it was, it left Earth's lit face 2.3 degrees off Horizons at
|
||||
* AD 1000 and 4.5 to 4.6 over AD 1 (2.0, and 4.2 to 4.3, at UT itself). Taken at TDB, it would
|
||||
* have turned ΔT further, 44 degrees at AD 1.
|
||||
*/
|
||||
export function bodyOrientation(elements: RotationalElements, jdUtc: number, target = new THREE.Quaternion(), followsUt = false): THREE.Quaternion {
|
||||
const { poleRaDeg, poleDecDeg, primeMeridianDeg } = orientationAt(elements, tdbFromUtc(jdUtc));
|
||||
const turnDeg = followsUt ? 360 * (0.779057273264 + 1.00273781191135448 * (jdUtc - 2451545)) - 90 - poleRaDeg : primeMeridianDeg;
|
||||
return poleFrame({ raDeg: poleRaDeg, decDeg: poleDecDeg }, target)
|
||||
.multiply(scratchTurn.setFromAxisAngle(Z_AXIS, turnDeg * DEG_TO_RAD))
|
||||
.multiply(MAP_TO_BODY);
|
||||
}
|
||||
|
||||
/** Where a body is from the Sun at a date, in the ICRF, AU: a moon's planet's place plus its own. */
|
||||
function heliocentricPosition(body: BodyRecord, bodies: readonly BodyRecord[], jdUtc: number): CartesianCoordinates {
|
||||
const jdTdb = tdbFromUtc(jdUtc);
|
||||
const own = positionAtEpoch(meanElementsAt(body.orbit, body.rates, jdTdb));
|
||||
const parent = body.parentBodyId ? bodies.find((candidate) => candidate.id === body.parentBodyId) : undefined;
|
||||
if (!parent) {
|
||||
return eclipticToEquatorial(own);
|
||||
}
|
||||
const offset = body.laplacePole ? laplacePlaneToEquatorial(own, body.laplacePole) : eclipticToEquatorial(own);
|
||||
const centre = eclipticToEquatorial(positionAtEpoch(meanElementsAt(parent.orbit, parent.rates, jdTdb)));
|
||||
return { x: centre.x + offset.x, y: centre.y + offset.y, z: centre.z + offset.z };
|
||||
}
|
||||
|
||||
const scratchPage = new THREE.Quaternion();
|
||||
const scratchPageTurn = new THREE.Quaternion();
|
||||
const scratchBody = new THREE.Quaternion();
|
||||
|
||||
/**
|
||||
* How the body page shows a body the IAU gives elements for: pole up, as the page has always
|
||||
* drawn it, turned as it really is at the map's date against a Sun held at `sunAzimuthRad` round
|
||||
* that pole — where the page's light has always stood, so the camera still opens on the day side.
|
||||
* The Sun's height above the equator is its real one, and the face it lights is the real one:
|
||||
* seen from the body, the Sun sits over the same point of its map as in the system view. What the
|
||||
* page gives up is the stars, which do not turn with the body.
|
||||
*
|
||||
* Sets `planet` to the sphere's rotation and `sun` to the unit direction of the Sun in the page's
|
||||
* frame. Returns false, touching neither, for a body without elements.
|
||||
*/
|
||||
export function bodyPageView(body: BodyRecord, bodies: readonly BodyRecord[], jdUtc: number, sunAzimuthRad: number, planet: THREE.Quaternion, sun: THREE.Vector3): boolean {
|
||||
const elements = body.rotationalElements;
|
||||
if (!elements) {
|
||||
return false;
|
||||
}
|
||||
const { poleRaDeg, poleDecDeg } = orientationAt(elements, tdbFromUtc(jdUtc));
|
||||
// From the ICRF into the body's frame with its pole on +Y, before the turn about that pole.
|
||||
const toPage = poleFrame({ raDeg: poleRaDeg, decDeg: poleDecDeg }, scratchPage).multiply(MAP_TO_BODY).invert();
|
||||
const position = heliocentricPosition(body, bodies, jdUtc);
|
||||
sun.set(-position.x, -position.y, -position.z).normalize().applyQuaternion(toPage);
|
||||
const turn = scratchPageTurn.setFromAxisAngle(Y_AXIS, sunAzimuthRad - Math.atan2(sun.x, sun.z));
|
||||
sun.applyQuaternion(turn);
|
||||
planet.copy(turn).multiply(toPage).multiply(bodyOrientation(elements, jdUtc, scratchBody, body.id === 'earth'));
|
||||
return true;
|
||||
}
|
||||
@@ -115,11 +115,12 @@ describe('renderPlanetTexture', () => {
|
||||
it('produces no NaN or out-of-range bytes for any class', () => {
|
||||
for (const planetClass of ALL_CLASSES) {
|
||||
const pixels = renderPlanetTexture(appearanceOf(planetClass, { polarCapExtentDeg: 30 }), SIZE);
|
||||
for (const value of pixels) {
|
||||
expect(Number.isInteger(value)).toBe(true);
|
||||
expect(value).toBeGreaterThanOrEqual(0);
|
||||
expect(value).toBeLessThanOrEqual(255);
|
||||
}
|
||||
// One assertion per class, not three per byte: 245 760 expect() calls ran past the
|
||||
// default 5 s timeout on a slower CI machine.
|
||||
const firstBad = pixels.findIndex(
|
||||
(value) => !Number.isInteger(value) || value < 0 || value > 255,
|
||||
);
|
||||
expect(firstBad, planetClass).toBe(-1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
/// <reference types="node" />
|
||||
// Node, for the one test that reads a map's bytes from disk.
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import * as THREE from 'three/webgpu';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { bodyTexturePath, saturnRing } from './texture-catalog';
|
||||
|
||||
describe('bodyTexturePath', () => {
|
||||
it('wraps the moons and dwarf planets that have a mission mosaic in it', () => {
|
||||
const mapped = ['phobos', 'deimos', 'io', 'europa', 'ganymede', 'callisto', 'mimas', 'enceladus', 'tethys', 'dione', 'rhea', 'titan', 'iapetus', 'phoebe', 'triton', 'ceres', 'pluto', 'charon'];
|
||||
for (const id of mapped) {
|
||||
expect(bodyTexturePath(id)).toBe(`assets/textures/bodies/${id}.jpg`);
|
||||
}
|
||||
});
|
||||
|
||||
it('wraps Venus in the map turned north up, the one checked for Maxwell Montes', () => {
|
||||
// As the Solar System Scope pack ships it, venus.jpg is the Magellan map turned half round:
|
||||
// Maxwell Montes, 65.2 N 3.3 E in the IAU Gazetteer, was its brightest point at 63 S 9 W. The
|
||||
// file turned back puts it at 63.7 N 8.3 E; see assets/textures/README.md. No decoder runs
|
||||
// here, so the check is pinned to those bytes.
|
||||
expect(bodyTexturePath('venus')).toBe('assets/textures/bodies/venus.jpg');
|
||||
const bytes = readFileSync(`${process.cwd()}/src/assets/textures/bodies/venus.jpg`);
|
||||
expect(createHash('sha256').update(bytes).digest('hex')).toBe('4528b8e9a3cf880d80e8a5321a3001e8792bc18f266c06f3456a6bd8475e021d');
|
||||
});
|
||||
|
||||
it('leaves the bodies with no map it could check to their derived surface', () => {
|
||||
for (const id of ['miranda', 'ariel', 'umbriel', 'titania', 'oberon', 'hyperion', 'eris']) {
|
||||
expect(bodyTexturePath(id)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('saturnRing', () => {
|
||||
const SATURN_RADIUS_KM = 58232;
|
||||
|
||||
/** Each vertex's distance from the centre, in km, beside the texture coordinate it samples. */
|
||||
function radiiAndU(ring: THREE.Mesh, kmPerUnit: number): Array<{ km: number; u: number; y: number }> {
|
||||
const position = ring.geometry.attributes['position'];
|
||||
const uv = ring.geometry.attributes['uv'];
|
||||
const vertex = new THREE.Vector3();
|
||||
return Array.from({ length: position.count }, (_, i) => {
|
||||
vertex.fromBufferAttribute(position, i);
|
||||
return { km: vertex.length() * kmPerUnit, u: uv.getX(i), y: vertex.y };
|
||||
});
|
||||
}
|
||||
|
||||
it('reaches from 69 400 to 141 000 km, drawn against the planet at whatever size it is drawn', () => {
|
||||
for (const drawnRadius of [1, 3.9e-4]) {
|
||||
const radii = radiiAndU(saturnRing(SATURN_RADIUS_KM, drawnRadius), SATURN_RADIUS_KM / drawnRadius).map(({ km }) => km);
|
||||
expect(Math.min(...radii)).toBeCloseTo(69400, 0);
|
||||
expect(Math.max(...radii)).toBeCloseTo(141000, 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('is lit, and seen from either face', () => {
|
||||
// An unlit ring shows no day and night; one drawn from its front face alone vanishes when Earth
|
||||
// is on its south side, as on 24 September 2026.
|
||||
const material = saturnRing(SATURN_RADIUS_KM, 1).material as THREE.Material;
|
||||
expect(material).toBeInstanceOf(THREE.MeshStandardMaterial);
|
||||
expect(material.side).toBe(THREE.DoubleSide);
|
||||
});
|
||||
|
||||
it('lies in the equator of a sphere built round +Y', () => {
|
||||
for (const { y } of radiiAndU(saturnRing(SATURN_RADIUS_KM, 1), SATURN_RADIUS_KM)) {
|
||||
expect(Math.abs(y)).toBeLessThan(1e-12);
|
||||
}
|
||||
});
|
||||
|
||||
it('samples the strip outwards, so its B ring starts at 92 000 km and its A ring ends at 136 775', () => {
|
||||
// Where the strip's alpha jumps: 404.5 and 1 204 of its 1 280 px.
|
||||
const vertices = radiiAndU(saturnRing(SATURN_RADIUS_KM, 1), SATURN_RADIUS_KM);
|
||||
const inner = vertices.reduce((a, b) => (b.km < a.km ? b : a));
|
||||
const outer = vertices.reduce((a, b) => (b.km > a.km ? b : a));
|
||||
const uAt = (km: number): number => inner.u + ((km - inner.km) / (outer.km - inner.km)) * (outer.u - inner.u);
|
||||
expect(Math.abs(uAt(92000) * 1280 - 404.5)).toBeLessThan(1.5);
|
||||
expect(Math.abs(uAt(136775) * 1280 - 1204)).toBeLessThan(1.5);
|
||||
});
|
||||
});
|
||||
@@ -4,25 +4,18 @@ import * as THREE from 'three/webgpu';
|
||||
* Real NASA/ESA/USGS photography baked into `src/assets/textures/bodies/` at build time,
|
||||
* keyed by the same ids used in `bodies.json`.
|
||||
*
|
||||
* Only surface *maps* belong here: equirectangular images, twice as wide as tall, that wrap a
|
||||
* sphere. Everything else — every exoplanet, since the few imaged were seen only as points of
|
||||
* light, and every moon
|
||||
* or dwarf planet with no such map in the repository — falls through to
|
||||
* `procedural-planet-texture.ts`, which derives a surface from the body's own measured size,
|
||||
* mass, orbit and host star instead.
|
||||
* This map is the whole of what has actually been photographed. Everything else — every
|
||||
* exoplanet, since not one has ever been imaged, and the moons no probe returned a usable map
|
||||
* of — falls through to `procedural-planet-texture.ts`, which derives a surface from the body's
|
||||
* own measured size, mass, orbit and host star instead.
|
||||
*
|
||||
* Io, Pluto, Titan and Deimos used to be listed with square photographs of them: pictures of a
|
||||
* lit disc against black sky, not maps, which wrapped round a sphere put black sky on a fifth to a
|
||||
* third of the surface. All four are now global mosaics like the other moons'.
|
||||
*
|
||||
* Provenance (CC BY 4.0 Solar System Scope, via Wikimedia Commons — see each file's Commons page
|
||||
* for the original credit line): mercury/venus/earth/mars/saturn/uranus/neptune/moon/sun/
|
||||
* saturn-ring/skybox — Solar System Scope texture pack; jupiter — Solar System Scope 8k pack.
|
||||
*
|
||||
* The moons', Ceres's and Pluto's are public-domain mission mosaics from USGS Astrogeology and the
|
||||
* PDS, each put in the same frame — longitude 0 in the middle, east to the right — and each
|
||||
* measured, in `assets/textures/README.md`. Where a probe saw only part of a body (Pluto, Charon,
|
||||
* Triton, Phoebe, the Galilean poles), the rest is a flat grey, never invented terrain.
|
||||
* Provenance (all public domain NASA/JPL or CC BY 4.0 Solar System Scope, via Wikimedia
|
||||
* Commons — see each file's Commons page for the original credit line):
|
||||
* mercury/venus/earth/mars/saturn/uranus/neptune/moon/sun/saturn-ring/skybox — Solar System
|
||||
* Scope texture pack (CC BY 4.0); jupiter — Solar System Scope 8k pack (CC BY 4.0); pluto —
|
||||
* NASA/JHUAPL/SwRI New Horizons true-color mosaic; deimos — NASA/JPL/University of Arizona
|
||||
* MRO HiRISE; io — NASA/JPL Galileo highest-resolution true-color mosaic; titan — NASA/JPL
|
||||
* Cassini true-color view.
|
||||
*/
|
||||
const BODY_TEXTURE_PATHS: Record<string, string> = {
|
||||
mercury: 'assets/textures/bodies/mercury.jpg',
|
||||
@@ -33,25 +26,11 @@ const BODY_TEXTURE_PATHS: Record<string, string> = {
|
||||
saturn: 'assets/textures/bodies/saturn.jpg',
|
||||
uranus: 'assets/textures/bodies/uranus.jpg',
|
||||
neptune: 'assets/textures/bodies/neptune.jpg',
|
||||
pluto: 'assets/textures/bodies/pluto.jpg',
|
||||
moon: 'assets/textures/bodies/moon.jpg',
|
||||
phobos: 'assets/textures/bodies/phobos.jpg',
|
||||
deimos: 'assets/textures/bodies/deimos.jpg',
|
||||
io: 'assets/textures/bodies/io.jpg',
|
||||
europa: 'assets/textures/bodies/europa.jpg',
|
||||
ganymede: 'assets/textures/bodies/ganymede.jpg',
|
||||
callisto: 'assets/textures/bodies/callisto.jpg',
|
||||
mimas: 'assets/textures/bodies/mimas.jpg',
|
||||
enceladus: 'assets/textures/bodies/enceladus.jpg',
|
||||
tethys: 'assets/textures/bodies/tethys.jpg',
|
||||
dione: 'assets/textures/bodies/dione.jpg',
|
||||
rhea: 'assets/textures/bodies/rhea.jpg',
|
||||
titan: 'assets/textures/bodies/titan.jpg',
|
||||
iapetus: 'assets/textures/bodies/iapetus.jpg',
|
||||
phoebe: 'assets/textures/bodies/phoebe.jpg',
|
||||
triton: 'assets/textures/bodies/triton.jpg',
|
||||
ceres: 'assets/textures/bodies/ceres.jpg',
|
||||
pluto: 'assets/textures/bodies/pluto.jpg',
|
||||
charon: 'assets/textures/bodies/charon.jpg'
|
||||
titan: 'assets/textures/bodies/titan.jpg'
|
||||
};
|
||||
|
||||
/** The Sun isn't a `BodyRecord` (it's the system's star marker), so it's looked up separately. */
|
||||
@@ -79,54 +58,6 @@ export function atmosphereColorFor(id: string): THREE.ColorRepresentation | unde
|
||||
return ATMOSPHERE_BY_ID[id];
|
||||
}
|
||||
|
||||
/**
|
||||
* The radii, in km from Saturn's centre, that `saturn_ring.png`'s left and right edges stand for.
|
||||
*
|
||||
* The strip runs straight out from its left edge to its right, and read off its alpha the ring
|
||||
* edges fall where one scale puts them: the C ring's inner edge (74 490 km) at 91 of its 1 280 px,
|
||||
* the B ring's inner edge (92 000) at 404.5 and outer (117 580) at 860, the A ring's outer edge
|
||||
* (136 775) at 1 204 and the F ring (140 180) at 1 267.5 — all within 1.8 px of 55.9 km a pixel.
|
||||
* The one miss is the Cassini Division's outer edge (122 170), which the strip draws 30 px (1 700
|
||||
* km) too far in. The edges are not the 74 500 and 140 220 km of the C ring and the F ring: sized to
|
||||
* those, the B ring's inner edge would sit 3 300 km out.
|
||||
*/
|
||||
export const SATURN_RING_INNER_KM = 69_400;
|
||||
export const SATURN_RING_OUTER_KM = 141_000;
|
||||
|
||||
/**
|
||||
* Saturn's rings, flat in the equator of a sphere built round +Y — its XZ plane — and sized
|
||||
* against the planet as drawn: `drawnRadius` for Saturn's `planetRadiusKm`, so the rings keep their
|
||||
* true proportion to the planet wherever it is drawn and however it is scaled.
|
||||
*
|
||||
* `RingGeometry`'s own UVs wrap round the angle, so u is set to the distance from the centre instead,
|
||||
* which is the way the strip runs. Lit, from both faces: the face turned to the Sun is lit by the
|
||||
* height of the Sun above the ring plane, and the other falls dark. Nothing in the app casts a
|
||||
* shadow, so neither the planet on the rings nor the rings on the planet do.
|
||||
*/
|
||||
export function saturnRing(planetRadiusKm: number, drawnRadius: number): THREE.Mesh {
|
||||
const unitsPerKm = drawnRadius / planetRadiusKm;
|
||||
const inner = SATURN_RING_INNER_KM * unitsPerKm;
|
||||
const outer = SATURN_RING_OUTER_KM * unitsPerKm;
|
||||
const geometry = new THREE.RingGeometry(inner, outer, 128, 1).rotateX(-Math.PI / 2);
|
||||
const position = geometry.attributes['position'];
|
||||
const uv = geometry.attributes['uv'];
|
||||
const vertex = new THREE.Vector3();
|
||||
for (let i = 0; i < position.count; i++) {
|
||||
vertex.fromBufferAttribute(position, i);
|
||||
uv.setXY(i, THREE.MathUtils.clamp((vertex.length() - inner) / (outer - inner), 0, 1), 1);
|
||||
}
|
||||
// The strip's own alpha is the rings' opacity: dense in the B ring, thin in the C ring.
|
||||
const material = new THREE.MeshStandardMaterial({
|
||||
map: loadCachedTexture(SATURN_RING_TEXTURE_PATH),
|
||||
transparent: true,
|
||||
side: THREE.DoubleSide,
|
||||
depthWrite: false,
|
||||
roughness: 1,
|
||||
metalness: 0
|
||||
});
|
||||
return new THREE.Mesh(geometry, material);
|
||||
}
|
||||
|
||||
const textureLoader = new THREE.TextureLoader();
|
||||
const loadedTextures = new Map<string, THREE.Texture>();
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ export class BookmarksStore {
|
||||
}
|
||||
|
||||
private read(): Bookmark[] {
|
||||
let raw: string | null = null;
|
||||
let raw: string | null;
|
||||
try {
|
||||
raw = localStorage.getItem(STORAGE_KEY);
|
||||
} catch {
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { TimeStore } from './time.store';
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
const START = new Date('2026-09-22T12:00:00Z');
|
||||
|
||||
describe('TimeStore', () => {
|
||||
let time: TimeStore;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(START);
|
||||
time = new TimeStore();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('keeps the world’s own time until asked otherwise', () => {
|
||||
const opened = time.julianDate();
|
||||
vi.advanceTimersByTime(10_000);
|
||||
|
||||
expect(time.julianDate() - opened).toBeCloseTo(10_000 / MS_PER_DAY, 9);
|
||||
expect(time.date().toISOString()).toBe('2026-09-22T12:00:10.000Z');
|
||||
});
|
||||
|
||||
it('runs the sky faster without moving where it starts from', () => {
|
||||
const opened = time.julianDate();
|
||||
time.setRate(3600);
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
// A second of watching is an hour of sky, and the date did not jump when the rate changed.
|
||||
expect(time.julianDate() - opened).toBeCloseTo(1 / 24, 9);
|
||||
});
|
||||
|
||||
it('carries on from where it had got to when the rate changes again', () => {
|
||||
time.setRate(86_400);
|
||||
vi.advanceTimersByTime(2000); // two days of sky
|
||||
const afterTwoDays = time.julianDate();
|
||||
|
||||
time.setRate(1);
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
// Slowing down keeps the two days: it does not rewind to the wall clock.
|
||||
expect(time.julianDate() - afterTwoDays).toBeCloseTo(1000 / MS_PER_DAY, 9);
|
||||
expect(time.julianDate() - afterTwoDays).toBeLessThan(1 / 24);
|
||||
});
|
||||
|
||||
it('runs the date backwards at a negative rate', () => {
|
||||
time.setRate(-86_400);
|
||||
const before = time.julianDate();
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
expect(time.julianDate() - before).toBeCloseTo(-1, 9);
|
||||
});
|
||||
|
||||
it('knows the map is away from now even once it is back at real time', () => {
|
||||
expect(time.atNow()).toBe(true);
|
||||
time.setRate(2_629_800);
|
||||
vi.advanceTimersByTime(5000);
|
||||
time.setRate(1);
|
||||
|
||||
// Real time, months ahead: the rate says nothing about where the clock stands.
|
||||
expect(time.atNow()).toBe(false);
|
||||
time.reset();
|
||||
expect(time.atNow()).toBe(true);
|
||||
});
|
||||
|
||||
it('comes back to now, at real time', () => {
|
||||
time.setRate(2_629_800);
|
||||
vi.advanceTimersByTime(5000); // months away
|
||||
expect(time.date().getUTCFullYear()).toBeGreaterThan(START.getUTCFullYear());
|
||||
|
||||
time.reset();
|
||||
|
||||
expect(time.rate()).toBe(1);
|
||||
// Now, not the moment the store was built: five seconds of wall clock have passed.
|
||||
expect(time.date().toISOString()).toBe(new Date(START.getTime() + 5000).toISOString());
|
||||
});
|
||||
|
||||
it('jumps to a date and carries on from it at the rate it was running at', () => {
|
||||
vi.advanceTimersByTime(5000); // five seconds before the jump, which it must not add on
|
||||
expect(time.setDate(new Date('2020-12-21T18:00Z'))).toBe(true);
|
||||
// Away from now although still at real time: the rate never changed, the date did.
|
||||
expect(time.atNow()).toBe(false);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(time.date().toISOString()).toBe('2020-12-21T18:00:01.000Z');
|
||||
|
||||
time.setRate(3600);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(time.date().toISOString()).toBe('2020-12-21T19:00:01.000Z');
|
||||
});
|
||||
|
||||
it('stops a running clock at either end of the window, at real time turned back into it', () => {
|
||||
time.setDate(new Date('0001-01-10T00:00Z'));
|
||||
time.setRate(-2_629_800); // a month a second, backwards
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(time.date().toISOString()).toBe('0001-01-01T00:00:00.000Z');
|
||||
expect(time.rate()).toBe(1);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(time.date().toISOString()).toBe('0001-01-01T00:00:01.000Z');
|
||||
|
||||
time.setDate(new Date('2999-12-01T00:00Z'));
|
||||
time.setRate(2_629_800);
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(time.date().toISOString()).toBe('3000-01-01T00:00:00.000Z');
|
||||
expect(time.rate()).toBe(-1);
|
||||
});
|
||||
|
||||
it('refuses a date the planets’ elements were never fitted for, and stays where it was', () => {
|
||||
const before = time.date().toISOString();
|
||||
|
||||
expect(time.setDate(new Date('3000-01-01T00:01Z'))).toBe(false);
|
||||
expect(time.setDate(new Date(Date.UTC(-100, 0, 1)))).toBe(false); // 101 BC
|
||||
expect(time.setDate(new Date('not a date'))).toBe(false);
|
||||
expect(time.date().toISOString()).toBe(before);
|
||||
expect(time.atNow()).toBe(true);
|
||||
|
||||
// Both ends are in: the first day a date input can hold, and the end of Standish's fit.
|
||||
expect(time.setDate(new Date('0001-01-01T00:00Z'))).toBe(true);
|
||||
expect(time.date().toISOString()).toBe('0001-01-01T00:00:00.000Z');
|
||||
expect(time.setDate(new Date('3000-01-01T00:00Z'))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,137 +0,0 @@
|
||||
import { Injectable, signal } from '@angular/core';
|
||||
|
||||
import { dateToJulianDate } from '../astro/constants';
|
||||
|
||||
/**
|
||||
* How fast the map's clock runs, in seconds of sky per second of wall clock.
|
||||
*
|
||||
* The map is built on propagated orbits and published rotation periods, both of which are
|
||||
* functions of a date — so the only thing standing between it and a working orrery is the number
|
||||
* on this list. At real time nothing appears to move: Earth turns 15 degrees an hour and takes a
|
||||
* year to go round, and a reader watching for a minute sees a still picture.
|
||||
*
|
||||
* An hour a second is the rate at which rotation reads — Jupiter turns once every ten seconds of
|
||||
* watching. A day a second is the rate at which the inner planets read. A month a second carries
|
||||
* the outer ones, at which point the inner four are a blur, which is honest: that is what the
|
||||
* solar system does.
|
||||
*/
|
||||
export const TIME_RATES = [
|
||||
{ label: 'Real time', secondsPerSecond: 1 },
|
||||
{ label: '1 h/s', secondsPerSecond: 3600 },
|
||||
{ label: '1 d/s', secondsPerSecond: 86_400 },
|
||||
{ label: '1 mo/s', secondsPerSecond: 2_629_800 },
|
||||
] as const;
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
const JULIAN_DATE_AT_EPOCH = 2440587.5;
|
||||
|
||||
/**
|
||||
* The dates the clock can be set to, as `datetime-local` values read as UTC.
|
||||
*
|
||||
* The end is where Standish's Table 2, the mean elements that carry the planets, stops being
|
||||
* fitted: it covers 3000 BC to AD 3000, and every planet was within 0.29 degrees of Horizons at
|
||||
* each date measured out to 3000. The start is not the fit's but the date input's, which cannot
|
||||
* go before 0001-01-01. Both are proleptic Gregorian, as a `Date` is, so before 1582 they part from
|
||||
* the Julian-calendar dates history gives: two days behind them at AD 1, level from AD 200 to 300,
|
||||
* ten days ahead by 1582. Pluto, on Standish's elements too, holds with them; the moons and the four
|
||||
* dwarf planets from the SBDB hold for far less of it: each of their cards says how
|
||||
* far its orbit strays from Horizons from 1950 to 2100 (Ceres 7.1 degrees there, 11.6 by 2200 and
|
||||
* 39 by 1600).
|
||||
*/
|
||||
export const CLOCK_WINDOW = { min: '0001-01-01T00:00', max: '3000-01-01T00:00' } as const;
|
||||
const WINDOW_MS = {
|
||||
min: Date.parse(`${CLOCK_WINDOW.min}Z`),
|
||||
max: Date.parse(`${CLOCK_WINDOW.max}Z`),
|
||||
};
|
||||
const WINDOW_JD = {
|
||||
min: WINDOW_MS.min / MS_PER_DAY + JULIAN_DATE_AT_EPOCH,
|
||||
max: WINDOW_MS.max / MS_PER_DAY + JULIAN_DATE_AT_EPOCH,
|
||||
};
|
||||
|
||||
/**
|
||||
* The date the map is drawn for.
|
||||
*
|
||||
* Read every frame rather than held in a signal: it changes continuously, and a signal that
|
||||
* changed sixty times a second would ask the whole HUD to re-render for a number nothing is
|
||||
* watching. The rate *is* a signal, since a reader sets it and the controls read it back.
|
||||
*
|
||||
* Changing the rate re-anchors instead of rewinding: the date carries on from where it had got
|
||||
* to, so speeding up and slowing down never jumps the sky. A negative rate runs the same clock
|
||||
* backwards: every orbit and every rotation is a function of the date, so going back is the same
|
||||
* sum with the sign turned.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class TimeStore {
|
||||
readonly rate = signal<number>(TIME_RATES[0].secondsPerSecond);
|
||||
/**
|
||||
* Whether the map is drawn for the present. Not the same as a rate of one: after an excursion at
|
||||
* a month a second, real time carries on from months ahead, and the map is still away from now.
|
||||
*/
|
||||
readonly atNow = signal(true);
|
||||
|
||||
private anchorJd = dateToJulianDate();
|
||||
private anchorWallMs = Date.now();
|
||||
|
||||
/**
|
||||
* Julian date for this instant, at the rate the reader chose, held to {@link CLOCK_WINDOW}: a
|
||||
* clock run past either end stops there, at real time turned back into the window, as if the
|
||||
* reader had set that date. Unheld, a month a second carried it past AD 3000, where the planets'
|
||||
* elements were never fitted, and before AD 1, where `toISOString` writes a six-digit year the
|
||||
* date strip, the note and the date field cut in the wrong places ("-000001-12-01 00 UTC").
|
||||
*/
|
||||
julianDate(): number {
|
||||
const jd = this.anchorJd + ((Date.now() - this.anchorWallMs) * this.rate()) / MS_PER_DAY;
|
||||
if (jd >= WINDOW_JD.min && jd <= WINDOW_JD.max) {
|
||||
return jd;
|
||||
}
|
||||
this.anchorJd = jd < WINDOW_JD.min ? WINDOW_JD.min : WINDOW_JD.max;
|
||||
this.anchorWallMs = Date.now();
|
||||
this.rate.set(jd < WINDOW_JD.min ? 1 : -1);
|
||||
return this.anchorJd;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same instant as a date, for anything that prints it.
|
||||
*
|
||||
* Rounded to the millisecond, which is all a `Date` holds: a Julian date near 2 461 000 has
|
||||
* about a twentieth of a millisecond of resolution left in a double, and `new Date` truncates
|
||||
* what is left rather than rounding it, so ten seconds came back as 9.999.
|
||||
*/
|
||||
date(): Date {
|
||||
return new Date(Math.round((this.julianDate() - JULIAN_DATE_AT_EPOCH) * MS_PER_DAY));
|
||||
}
|
||||
|
||||
setRate(secondsPerSecond: number): void {
|
||||
this.anchorJd = this.julianDate();
|
||||
this.anchorWallMs = Date.now();
|
||||
this.rate.set(secondsPerSecond);
|
||||
if (secondsPerSecond !== 1) {
|
||||
this.atNow.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Jumps the clock to a date, from which it carries on at whatever rate it was running at.
|
||||
* Refuses one outside {@link CLOCK_WINDOW}, rather than draw planets where elements that were
|
||||
* never fitted there put them.
|
||||
*/
|
||||
setDate(date: Date): boolean {
|
||||
const ms = date.getTime();
|
||||
// Written so that NaN, an unparsable field, fails it too.
|
||||
if (!(ms >= WINDOW_MS.min && ms <= WINDOW_MS.max)) {
|
||||
return false;
|
||||
}
|
||||
this.anchorJd = dateToJulianDate(date);
|
||||
this.anchorWallMs = Date.now();
|
||||
this.atNow.set(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Back to now, at real time — the state the map opens in. */
|
||||
reset(): void {
|
||||
this.anchorJd = dateToJulianDate();
|
||||
this.anchorWallMs = Date.now();
|
||||
this.rate.set(TIME_RATES[0].secondsPerSecond);
|
||||
this.atNow.set(true);
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
# Body textures
|
||||
|
||||
`bodies/` holds the surface maps `src/app/shared/rendering/texture-catalog.ts` wraps round the
|
||||
bodies, keyed by their ids in `bodies.json`. Every map is simple cylindrical (equirectangular),
|
||||
360 by 180 degrees, twice as wide as tall, with **longitude 0 in the middle and east to the right**,
|
||||
which is the frame `MAP_TO_BODY` in `body-orientation.ts` puts onto the IAU body frame. The IAU
|
||||
prime meridian (W) then turns longitude 0 to where it belongs at any date.
|
||||
|
||||
## Solar System Scope (CC BY 4.0)
|
||||
|
||||
`mercury`, `venus`, `earth`, `mars`, `saturn`, `uranus`, `neptune`, `moon`, `sun`, `saturn_ring`
|
||||
and the skybox come from the Solar System Scope texture pack, and `jupiter` from its 8k pack, via
|
||||
Wikimedia Commons. See each file's Commons page for the original credit line.
|
||||
|
||||
`venus.jpg` is kept turned 180 degrees from the pack's file, which is the Magellan radar map with
|
||||
south up and east to the left: there Maxwell Montes (65.2 N, 3.3 E in the IAU Gazetteer), the
|
||||
brightest feature north or south of 50 degrees, sat at 63 S, 9 W, with Lakshmi Planum east of it
|
||||
instead of west. Turned back (PIL `ROTATE_180`, re-saved on the file's own quantisation tables, 0.03
|
||||
grey levels from the exact turn), its brightest point is at 63.7 N, 8.3 E, with Lakshmi to the west.
|
||||
`texture-catalog.spec.ts` pins the checked file's SHA-256.
|
||||
|
||||
`saturn_ring.png` is a 1 280 by 78 px strip. Its x axis runs straight out from Saturn: read off its
|
||||
alpha, the C ring's inner edge (74 490 km) is at px 91, the B ring's inner and outer edges (92 000
|
||||
and 117 580 km) at 404.5 and 860, the A ring's outer edge (136 775 km) at 1 204 and the F ring
|
||||
(140 180 km) at 1 267.5, all within 1.8 px of 55.9 km a pixel. So its left edge stands for
|
||||
69 400 km and its right edge for 141 000 km (`SATURN_RING_INNER_KM`, `SATURN_RING_OUTER_KM`). The
|
||||
Cassini Division's outer edge (122 170 km) is drawn 30 px (1 700 km) too far in.
|
||||
|
||||
## Mission mosaics (public domain)
|
||||
|
||||
Each was downloaded from the URL below and processed the same way (script:
|
||||
`build_maps.py`, kept with the measurements outside the repository):
|
||||
|
||||
1. Pixels the source leaves unmapped (value 0 in every band, its no-data value) are set to one
|
||||
flat grey: the mean of the mapped surface. They are never filled with invented terrain. Titan's
|
||||
source marks its largest gap another way, with a flat grey of its own (147 and 148, its two
|
||||
commonest values; "the uniform gray area in the northern hemisphere indicates a gap in the
|
||||
imaging coverage", PIA19658), which the table counts as unmapped too: 1.09% of `titan.jpg`'s
|
||||
pixels, 0.87% of the sphere, where its zeros alone were 0.02%.
|
||||
2. Downsampled by area averaging (PIL `BOX`) to 2 048 by 1 024 for bodies over 1 000 km in radius
|
||||
and 1 024 by 512 for the rest.
|
||||
3. Rolled half a turn where the source is centred on longitude 180, so longitude 0 is in the
|
||||
middle. Every source already has east to the right. The centre was read from each file's
|
||||
GeoTIFF tags (central meridian plus the tie point of its left edge), not from its label: Rhea's
|
||||
and Enceladus's labels say `CENTER_LONGITUDE = 180` over an image centred on 0.
|
||||
4. Saved as JPEG at quality 85 (Europa 82, to stay under 400 KB), greyscale where the source is.
|
||||
|
||||
Each was then checked by eye against the IAU Gazetteer: the named feature lies where its
|
||||
coordinates put it on the processed map. "Black" is the share of pixels darker than 8 of 255 after
|
||||
processing; the disc photographs dropped in PR #33 were 20-43% black sky.
|
||||
|
||||
Their brightness is the mosaics' own, contrast-stretched frame by frame to show terrain: it places
|
||||
features, not albedo. Iapetus shows it most. Its leading hemisphere, Cassini Regio, has an albedo of
|
||||
0.03-0.05 and its trailing one 0.5-0.6 (NASA), about a tenth; on `iapetus.jpg`, between 30 S and
|
||||
30 N, the leading side (30-150 W) averages 83.4 of 255 and the trailing (30-150 E) 108.2, a ratio of
|
||||
0.77, as in the USGS source (83.3 and 108.1) and the DLR PDS map. So the drawn Iapetus is a shade
|
||||
darker on one side, where the real one is coal against snow. No map here was rescaled to published
|
||||
photometry.
|
||||
|
||||
| Map | Source | Mission, credit | Checked against | Unmapped (grey) | Black | Size |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `phobos.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Phobos_Viking_Mosaic_40ppd_DLRcontrol.tif) Phobos Viking Mosaic 40ppd (DLR controlled) | Viking Orbiter, with Mars Express images; P. Stooke after Simonelli et al. 1993, PDS Stooke Small Bodies Maps | Stickney (1 N, 49 W) | 0.03% | 0.008% | 1024x512, 119 KB |
|
||||
| `deimos.jpg` | [PDS SBN](https://sbnarchive.psi.edu/pds3/multi_mission/MULTI_SA_MULTI_6_STOOKEMAPS_V3_0/document/m2deimos/deimos_cyl_viking_mro.jpg) Stooke Small Bodies Maps V3.0, Deimos simple cylindrical mosaic, 20 px/deg | Viking Orbiter, with MRO HiRISE; P. Stooke and colleagues, control after P. Thomas (Cornell) | Swift (12.5 N, 1.8 E); the set's leading and trailing sheets (see below) | 0% | 0% | 1024x512, 55 KB |
|
||||
| `io.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Io_GalileoSSI-Voyager_Global_Mosaic_ClrMerge_1km.tif) Io Galileo SSI-Voyager Global Mosaic, colour merge, 1 km | Galileo SSI and Voyager; USGS Astrogeology | Pele, Loki, Prometheus | 0.02% | 0% | 2048x1024, 283 KB |
|
||||
| `europa.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Europa_Voyager_GalileoSSI_global_mosaic_500m.tif) Europa Voyager-Galileo SSI Global Mosaic 500 m | Voyager and Galileo SSI; Archinal et al., USGS | Pwyll (25 S, 271 W) | 4.33% (polar gaps) | 0% | 2048x1024, 386 KB |
|
||||
| `ganymede.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Ganymede_Voyager_GalileoSSI_Global_ClrMosaic_1435m.tif) Ganymede Voyager-Galileo SSI Colour Global Mosaic 1.4 km | Voyager and Galileo SSI; USGS | Osiris, Tros, Galileo Regio | 3.63% (polar gaps) | 0% | 2048x1024, 363 KB |
|
||||
| `callisto.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Callisto_Voyager_GalileoSSI_global_mosaic_1km.tif) Callisto Voyager-Galileo SSI Global Mosaic 1 km | Voyager and Galileo SSI; USGS | Valhalla, Asgard | 3.90% (polar gaps) | 0% | 2048x1024, 344 KB |
|
||||
| `mimas.jpg` | [PDS](https://planetarydata.jpl.nasa.gov/img/data/carto/coiss_3006/extras/full/images/SM_1M_0_0_SIMP.IMG.png) COISS_3006, Cassini ISS cartographic map of Mimas | Cassini ISS; DLR and FU Berlin (Roatsch et al.), NASA PDS | Herschel (1 N, 112 W) | 0.01% | 0.042% | 1024x512, 155 KB |
|
||||
| `enceladus.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Enceladus_Cassini_mosaic_global_110m.tif) Enceladus Cassini Global Mosaic 110 m | Cassini ISS; NASA/JPL/Space Science Institute | Ali Baba, Aladdin, Salih | 0.06% | 0.020% | 1024x512, 168 KB |
|
||||
| `tethys.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Tethys_Cassini_mosaic_global_293m.tif) Tethys Cassini Global Mosaic 293 m | Cassini ISS; NASA/JPL/Space Science Institute | Odysseus, Penelope | 0.04% | 0.009% | 1024x512, 182 KB |
|
||||
| `dione.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Dione_Cassini_Voyager_mosaic_global_154m.tif) Dione Cassini-Voyager Global Mosaic 154 m | Cassini ISS and Voyager; NASA/JPL/Space Science Institute | Creusa, Evander | 0.18% | 0.011% | 1024x512, 195 KB |
|
||||
| `rhea.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Rhea_Cassini_Voyager_mosaic_global_417m.tif) Rhea Cassini-Voyager Global Mosaic 417 m | Cassini ISS and Voyager; NASA/JPL/Space Science Institute | Inktomi, Tirawa | 0% | 0.003% | 1024x512, 128 KB |
|
||||
| `titan.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Titan_ISS_P19658_Mosaic_Global_4km.tif) Titan Cassini ISS Global Mosaic 4 km (938 nm, through the haze) | Cassini ISS; NASA/JPL-Caltech/SSI | Xanadu, Shangri-La, Belet | 1.1% (48-68 N, 37 W to 25 E: the source's own flat grey, see step 1) | 0.078% | 2048x1024, 294 KB |
|
||||
| `iapetus.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Iapetus_Cassini_Voyager_mosaic_global_783m.tif) Iapetus Cassini-Voyager Global Mosaic 783 m | Cassini ISS and Voyager; NASA/JPL/Space Science Institute | Cassini Regio (leading side, 90 W), Engelier | 0% | 0.019% | 1024x512, 159 KB |
|
||||
| `phoebe.jpg` | [PDS](https://planetarydata.jpl.nasa.gov/img/data/carto/coiss_3001/extras/full/images/SP_1M_0_0_SIMP.IMG.png) COISS_3001, Cassini ISS cartographic map of Phoebe | Cassini ISS; DLR and FU Berlin (Roatsch et al.), NASA PDS | Jason (16 N, 318 W) | 20.41% (the north) | 0.344% (shadows) | 1024x512, 78 KB |
|
||||
| `triton.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Triton_Voyager2_ClrMosaic_GlobalFill_600m.tif) Triton Voyager 2 Global Colour Mosaic 600 m (PIA18668) | Voyager 2; P. Schenk, NASA/JPL/LPI | Leviathan Patera; southern cap | 38.59% (the north Voyager 2 never saw) | 0% | 2048x1024, 205 KB |
|
||||
| `ceres.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Ceres_Dawn_FC_DLR_global_20ppd_Oct2015.tif) Ceres Dawn FC Global Mosaic, HAMO, Oct 2015 | Dawn Framing Camera; DLR, NASA/JPL | Occator (20 N, 239 E), Haulani (6 N, 11 E) | 3.60% (south pole) | 0.049% | 1024x512, 165 KB |
|
||||
| `pluto.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Pluto_NewHorizons_Global_Mosaic_300m_Jul2017_8bit.tif) Pluto New Horizons LORRI-MVIC Global Mosaic 300 m | New Horizons; NASA/JHUAPL/SwRI/LPI | Sputnik Planitia (175 E, across 180), Cthulhu, Burney | 31.92% (the south, in winter dark in 2015) | 0.501% (Cthulhu) | 2048x1024, 297 KB |
|
||||
| `charon.jpg` | [USGS](https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/Charon_NewHorizons_Global_Mosaic_300m_Jul2017_8bit.tif) Charon New Horizons LORRI-MVIC Global Mosaic 300 m | New Horizons; NASA/JHUAPL/SwRI/LPI | Mordor Macula (north pole), Organa | 34.02% (the south) | 0.549% (Mordor) | 1024x512, 72 KB |
|
||||
|
||||
Licence: every source above is NASA mission imagery, published by USGS Astrogeology or the NASA
|
||||
PDS. The USGS metadata gives access constraints of "public domain" (Io, Triton, Enceladus,
|
||||
Tethys, Dione, Rhea, Iapetus, Ganymede, Phobos) or "none" (the rest), with the use constraint
|
||||
"please cite authors", which the credits column does. Io's colour is Galileo's violet, green and 756 nm
|
||||
filters, which USGS says the eye would see "similar but much more muted"; Ganymede's is the
|
||||
Galileo and Voyager colour mosaic; Triton's is orange, violet and ultraviolet shown as red, green
|
||||
and blue (Smith et al. 1989). Phoebe is irregular (a 106.6 km sphere here), and its map keeps the
|
||||
deep shadows of a single flyby. Phobos's source notes that where images lit
|
||||
from opposite sides meet, the seam was blended for appearance, not geometry. Deimos's map is from
|
||||
the NASA PDS Small Bodies Node archive (MULTI-SA-MULTI-6-STOOKEMAPS-V3.0), which states no use
|
||||
restriction; the credit column cites its author.
|
||||
|
||||
Deimos's map says only "0 longitude at the center", not which way longitude runs, and USGS's own
|
||||
copy of the older version (`wms_basemaps/Deimos/deimoscyl4.jgw`) is georeferenced with longitude 0
|
||||
at its left edge instead. Its frame was settled on the body. Read with longitude 0 in the middle
|
||||
and east to the right, and drawn as a globe seen from outside, north up, the hemisphere centred at
|
||||
90 E matches, unmirrored, the sheet of the same set that Stooke titles "trailing side" and numbers
|
||||
270 (270 W), and the one centred at 90 W matches his "leading side" at 90. A synchronous prograde
|
||||
moon trails at 90 E and leads at 90 W, so that reading is the right one; read the USGS way, the
|
||||
two sheets would land on the wrong hemispheres. A 1 km depression lies at Swift's Gazetteer
|
||||
position (12.5 N, 1.8 E), near the middle; Voltaire (22 N, 3.5 W, 1.9 km) could not be picked out.
|
||||
|
||||
Longitudes follow each body's IAU prime meridian, which the checks above confirm on the maps. For
|
||||
Pluto and Charon that is the right-hand-rule pole of the WGCCRE 2015 report, which New Horizons'
|
||||
maps also use: the Charon-facing hemisphere is centred on longitude 0 and Sputnik Planitia sits on
|
||||
the far side, near 180.
|
||||
|
||||
## Left out
|
||||
|
||||
- **Miranda, Ariel, Umbriel, Titania, Oberon.** Voyager 2 saw only their southern hemispheres,
|
||||
and no public-domain map of them exists at USGS or the PDS. The best maps (P. Schenk 2020, USRA
|
||||
repository, hdl.handle.net/20.500.11753/1687) carry no licence.
|
||||
- **Hyperion, Nereid, Proteus, Eris, Haumea, Makemake.** No public-domain photographic map in
|
||||
simple cylindrical projection (Hyperion's USGS basemap is a relief rendering, not a mosaic).
|
||||
|
Before Width: | Height: | Size: 344 KiB |
|
Before Width: | Height: | Size: 165 KiB |
|
Before Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 195 KiB |
|
Before Width: | Height: | Size: 168 KiB |
|
Before Width: | Height: | Size: 386 KiB |
|
Before Width: | Height: | Size: 363 KiB |
|
Before Width: | Height: | Size: 159 KiB |
|
Before Width: | Height: | Size: 283 KiB After Width: | Height: | Size: 1.9 MiB |
|
Before Width: | Height: | Size: 154 KiB |
|
Before Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 298 KiB After Width: | Height: | Size: 334 KiB |
|
Before Width: | Height: | Size: 128 KiB |
|
Before Width: | Height: | Size: 182 KiB |
|
Before Width: | Height: | Size: 294 KiB After Width: | Height: | Size: 251 KiB |
|
Before Width: | Height: | Size: 205 KiB |
|
Before Width: | Height: | Size: 234 KiB After Width: | Height: | Size: 235 KiB |
@@ -1,17 +1,12 @@
|
||||
import { statSync } from 'node:fs';
|
||||
|
||||
import { BodyRecord, OrbitalElements, RotationalElements } from '../../src/app/shared/models/body.model';
|
||||
import { eclipticToEquatorial, laplacePlaneToEquatorial, raDecToUnitVector } from '../../src/app/shared/astro/coordinates';
|
||||
import { meanElementsAt, positionAtEpoch } from '../../src/app/shared/astro/kepler';
|
||||
import { orientationAt } from '../../src/app/shared/astro/rotational-elements';
|
||||
import { BodyRecord } from '../../src/app/shared/models/body.model';
|
||||
import { DeepSkyRecord } from '../../src/app/shared/models/deepsky.model';
|
||||
import { ExoplanetRecord } from '../../src/app/shared/models/exoplanet.model';
|
||||
import { StarRecord, SUN_STAR_ID } from '../../src/app/shared/models/star.model';
|
||||
import { fetchDeepSky } from './fetchDeepSky';
|
||||
import { fetchExoplanets } from './fetchExoplanets';
|
||||
import { fetchSolarSystem, FREELY_SPINNING_MOONS, offsetFromTrackDeg } from './fetchSolarSystem';
|
||||
import { TrackPoint } from './lib/horizons';
|
||||
import { subPlanetLongitudeDeg } from './lib/locked-spin';
|
||||
import { fetchSolarSystem } from './fetchSolarSystem';
|
||||
import { BYTES_PER_STAR_META, BYTES_PER_STAR_POSITION, decodeStarCatalog, encodeStarCatalog } from '../../src/app/shared/models/star-catalog';
|
||||
import { fetchStars } from './fetchStars';
|
||||
import { describeSources } from './sources/registry';
|
||||
@@ -135,353 +130,23 @@ function validateMerge(stars: StarRecord[]): void {
|
||||
console.log(` ${survivors} HYG stars have no Gaia counterpart; ${twins} unmerged cross-catalogue pairs within an arcsecond.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* How far a body's mean elements may put it from where Horizons has it, on the one date the ETL
|
||||
* asks Horizons about (2025-01-01), seen from the Sun for a planet and from its planet for a moon.
|
||||
*
|
||||
* Measured on this catalogue: the planets at most 0.10 degrees (Uranus; Standish's own stated
|
||||
* error for his fit is 2 000 arcseconds, 0.56 degrees), the moons at most 1.41 (the Moon, whose
|
||||
* evection and variation, 1.27 and 0.66 degrees, no mean ellipse has). What this catches is a
|
||||
* table read wrongly: a moon read against the ecliptic instead of its Laplace plane, a node run the
|
||||
* wrong way, or a column taken for its neighbour, which put Triton 26 degrees out. Io's periapsis
|
||||
* run forwards put it 0.9 out here, which passes; {@link TRACK_OFFSET_CEILINGS_DEG} catches that.
|
||||
*/
|
||||
const MAX_PLANET_OFFSET_DEG = 0.25;
|
||||
/** Measured on this catalogue: at most 0.0151 (Phoebe and the Moon) once Hyperion prints its current 0.105. */
|
||||
const MAX_ECCENTRICITY_OFFSET = 0.03;
|
||||
const MAX_MOON_OFFSET_DEG = 2.5;
|
||||
const KM_PER_AU = 149597870.7;
|
||||
const DEG_TO_RAD = Math.PI / 180;
|
||||
|
||||
/**
|
||||
* The moons whose table row cannot come within that on this one date, each with a ceiling just
|
||||
* above its offset here (Hyperion 9.41, Iapetus 9.56, Nereid 2.58); see
|
||||
* {@link TRACK_OFFSET_CEILINGS_DEG} for what they reach from 1950 to 2100. Hyperion's was 21, its
|
||||
* worst over twelve dates, which let a row misread by twice its offset through.
|
||||
*/
|
||||
const MOON_OFFSET_CEILINGS_DEG: Record<string, number> = { hyperion: 10, iapetus: 11, nereid: 3 };
|
||||
|
||||
/**
|
||||
* How far a moon's or dwarf planet's orbit may stray from Horizons from 1950 to 2100, sampled every
|
||||
* other day (Nereid and Hyperion daily). One date showed each at its best: twelve New Year's Days
|
||||
* gave Nereid 2.6 degrees, and 2025-01-01 alone is all the check above sees. Each card says how
|
||||
* far its own orbit strays over the span (`fetchSolarSystem`), and this holds that figure to
|
||||
* account.
|
||||
*
|
||||
* Measured on this catalogue: at most 2.62 degrees (the Moon, 2010 March 27: no mean ellipse has
|
||||
* its evection or variation; Phoebe reaches 2.58 in 1969, where "within 2.0" was once claimed for
|
||||
* it). Five need their own:
|
||||
*
|
||||
* - Hyperion, 22.23 (2055 Feb 26): held in a 4:3 resonance by Titan; the row's eccentricity,
|
||||
* 0.0232, is less than a quarter of the 0.105 JPL's current table gives.
|
||||
* - Nereid, 11.19 (2039 Nov 1): an eccentricity of 0.75, the largest here, which a mean ellipse
|
||||
* follows least well near periapsis, where the true anomaly runs ten times faster than the mean;
|
||||
* its 360-day year kept every New Year's Day far from one.
|
||||
* - Iapetus, 10.34: the row sits 9.4 degrees behind Horizons at its own epoch, 2000 Jan 1.5, and
|
||||
* keeps that offset; its plane agrees with Horizons' to 0.07 degrees and its period to 0.001 per
|
||||
* cent, so the fault is in the row's longitude, which this has no second source to correct.
|
||||
* - Mimas, 7.42: its orbit carries the 44-degree libration of its resonance with Tethys (see
|
||||
* `orbitFromW` in `fetchSolarSystem.ts`), but not the rest of what Horizons integrates.
|
||||
* - Ceres, 7.12 (1953): the SBDB's elements are osculating, exact at 2026 Jun 9 and drifting
|
||||
* either side; 1.9 by 2050, 5.3 by 2100, and 39 at 1600 on Horizons' own figures.
|
||||
*
|
||||
* And four are held tighter than the rest, each where one reading of its row is all that keeps it
|
||||
* close, and without it the card would quietly restate itself under the general ceiling:
|
||||
*
|
||||
* - Tethys, 0.28, which takes the other half of that libration, 2.23 degrees, from its W. Without
|
||||
* it Tethys strays 2.09.
|
||||
* - Io, 0.07, and Europa, 0.23, whose periapses turn backwards, held by the Laplace resonance at
|
||||
* 2n(Europa) - n(Io), -0.7395 degrees a day (`apsidesRegress`). Read as advancing, Io strays 0.96
|
||||
* and Europa 2.24, and their cards said "within 1.0" and "within 2.3".
|
||||
* - Callisto, 0.08, whose node turns at JPL's current rate and its periapsis's longitude at the
|
||||
* row's (`nodePeriodYears`). On the row's argument its periapsis moves 44 degrees by 2100 and it
|
||||
* strays 0.71; on the row's node, 0.19.
|
||||
*/
|
||||
const MAX_TRACK_OFFSET_DEG = 3;
|
||||
const TRACK_OFFSET_CEILINGS_DEG: Record<string, number> = { hyperion: 23, nereid: 12, iapetus: 11, mimas: 8, ceres: 8, tethys: 0.5, io: 0.2, europa: 0.5, callisto: 0.15 };
|
||||
|
||||
/**
|
||||
* The bodies the IAU WGCCRE 2015 report gives no rotational elements for: Hyperion tumbles, and
|
||||
* Nereid, Eris, Haumea and Makemake have no model. Every other body must carry them, or the
|
||||
* kernel was read wrongly and the body would be drawn on an invented pole.
|
||||
*/
|
||||
const WITHOUT_ROTATIONAL_ELEMENTS = new Set(['hyperion', 'nereid', 'eris', 'haumea', 'makemake']);
|
||||
|
||||
/**
|
||||
* The one moon drawn still: Hyperion, whose page says "Rotational period = Chaotic". Every other
|
||||
* moon without a lock has a measured day; Nereid's page states none, and it was drawn still until
|
||||
* its K2 light curve's 11.594 hours was taken (see its spec).
|
||||
*/
|
||||
const TUMBLING = new Set(['hyperion']);
|
||||
|
||||
/**
|
||||
* How far the IAU's day, 360 degrees over W's rate, may be from the period the body's record
|
||||
* carries, as a fraction of it. That period is not always a second source:
|
||||
*
|
||||
* - The eight planets and Phoebe: the one Horizons states. Measured on this catalogue: at most
|
||||
* 1.8e-5 (Jupiter's System III, 9.92492 hours against 9.92510). Neptune is 0.89 per cent out,
|
||||
* because the report takes 15.9663 hours from the cloud features Karkoschka (2011) tracked, where
|
||||
* Horizons keeps Voyager's radio period, 16.11.
|
||||
* - Pluto and Ceres: the IAU's own rate restated. Horizons' 153.29335198 hours for Pluto is 360 over
|
||||
* its W (8.5e-12), and the SBDB's 9.074170 for Ceres, which Horizons prints too, is noted as
|
||||
* derived from the report's 952.1532 degrees a day (3.3e-10).
|
||||
* - The 22 locked moons: their orbit's period, from JPL's satellite table, not a figure from their
|
||||
* Horizons pages ("Synchronous" on eighteen of them, nothing on Titan's or Proteus's). Their W is
|
||||
* turned at that rate (see `lockedToOrbit`, which first holds the kernel's own rate to it within
|
||||
* 1e-5), so here they are 0, but for the Moon and Phobos, whose W keeps its own rate and its
|
||||
* quadratic (1.1e-8 and 3.1e-7).
|
||||
*
|
||||
* What this catches is a rate read in the wrong unit or for the wrong body: Oberon's day for
|
||||
* Titania's is 55 per cent out.
|
||||
*/
|
||||
const MAX_DAY_OFFSET = 1e-4;
|
||||
const DAY_OFFSET_CEILINGS: Record<string, number> = { neptune: 0.01 };
|
||||
|
||||
/**
|
||||
* How far the tilt of the IAU's spin axis from the orbit may be from the obliquity Horizons
|
||||
* states. The axis is the IAU's pole, turned end for end where W runs backwards: the report names
|
||||
* a planet's north pole by the side of the solar system it lies on, whichever way the planet turns.
|
||||
* Measured on this catalogue: at most 0.058 degrees (Venus, 177.358 against 177.3). Taken as the
|
||||
* pole alone, Venus comes out at 2.6 degrees and Uranus at 82.2, which is what this catches.
|
||||
*
|
||||
* Pluto's Horizons page states no obliquity: its 119.6 is worked out from the IAU pole itself (see
|
||||
* `BodySpec.obliquityDeg`), so for Pluto this checks only that the kernel's pole and W were read as
|
||||
* written, not the pole against a second source.
|
||||
*/
|
||||
const MAX_OBLIQUITY_OFFSET_DEG = 0.1;
|
||||
|
||||
/**
|
||||
* How far from its planet a locked moon's drawn face may turn: the east longitude, on the IAU's
|
||||
* body-fixed frame, of the direction to the planet from where the mean elements put the moon,
|
||||
* sampled every 135 days over the clock's AD 1 to 3000. Every locked moon's W turns at its orbit's
|
||||
* own rate (see `lockedToOrbit`); at the IAU's own rates, and sampled only from 1950 to 2100, this
|
||||
* let Proteus turn its far side to Neptune at AD 1 (146 degrees), Iapetus 87 degrees, Mimas 52 and
|
||||
* Miranda 23, on dates the clock offers.
|
||||
*
|
||||
* Measured on this catalogue: at most 5.36 degrees (Titan) but for three. The Moon 7.62, at AD 1:
|
||||
* its longitude swings 6.3 either way with its eccentricity, Horizons' too, and W's quadratic, the
|
||||
* tidal slowing its orbit here does not carry, adds 0.75 by then. Mimas 8.89: about 6.3 off on
|
||||
* average because the IAU's W and JPL's mean longitude disagree, and swung 2.3 either way (2e) by
|
||||
* its eccentricity. None of that is Mimas: its measured physical libration is 0.84 degrees
|
||||
* (Tajeddine et al. 2014, Science 346, 322), and W carries none; Horizons, on the same W against its
|
||||
* integrated orbit, runs from -2.7 to 12.7 degrees over 1950-2100 with the 71-year S5 term the
|
||||
* orbit here cancels. Iapetus 15.95, whose row sits 9.4 degrees behind Horizons. What this catches
|
||||
* is an orbit and a W that go round at different rates: the tidal acceleration W carried and the
|
||||
* orbit did not turned Phobos 13.8 degrees from Mars by 2100, and the Mimas-Tethys libration Mimas
|
||||
* 54.5.
|
||||
*/
|
||||
const MAX_SUB_PLANET_LONGITUDE_DEG = 7;
|
||||
const SUB_PLANET_CEILINGS_DEG: Record<string, number> = { moon: 8, mimas: 9.5, iapetus: 16.5 };
|
||||
/**
|
||||
* How far a locked moon's spin axis may lean from the normal of the orbit it is drawn going round,
|
||||
* over the same dates. A locked moon sits in a Cassini state, its axis on its orbit normal as the
|
||||
* node carries both round the Laplace pole, and the IAU's pole goes round on a term of the node's
|
||||
* angle; at the rate the IAU's source had for it and not the drawn orbit's, Rhea's axis is 0.77
|
||||
* degrees off by AD 1 and Triton's 0.51, and an Iapetus pole left on the Laplace pole is 8.30 off
|
||||
* at every date (see `lockedToOrbit`).
|
||||
*
|
||||
* Measured on this catalogue: at most 0.97 degrees (Tethys, whose IAU pole sits 0.69 from its orbit
|
||||
* normal today; Titan 0.94, whose pole the IAU holds still while its node turns in 687 years) but
|
||||
* for four. The Moon 6.98, its real 6.7-degree tilt to its orbit. Phobos 1.81 and Deimos 1.74, and
|
||||
* Proteus 1.09: their IAU poles nod with Mars's and Neptune's precessing poles, the Laplace poles
|
||||
* their orbits are drawn round are fixed.
|
||||
*
|
||||
* And six are held tighter, each where its node terms turned at the node's rate, or its node at
|
||||
* JPL's current rate, are what keep it close: Europa 0.13, Ganymede 0.16, Callisto 0.22, Rhea 0.17,
|
||||
* Miranda 0.23 and Triton 0.15. On the IAU's rates they are 0.33, 0.21, 0.33, 0.77, 0.59 and 0.51,
|
||||
* on a tolerance of 1 per cent Callisto and Rhea are left there, on the node's angle alone and not
|
||||
* its harmonics Triton is 0.29, and on the archived table's node periods Callisto is 0.56 and
|
||||
* Miranda 0.42: all under the general ceiling.
|
||||
*/
|
||||
const MAX_AXIS_FROM_ORBIT_DEG = 1;
|
||||
const AXIS_FROM_ORBIT_CEILINGS_DEG: Record<string, number> = {
|
||||
moon: 7.1,
|
||||
phobos: 2,
|
||||
deimos: 2,
|
||||
proteus: 1.2,
|
||||
europa: 0.25,
|
||||
ganymede: 0.25,
|
||||
callisto: 0.25,
|
||||
rhea: 0.25,
|
||||
miranda: 0.25,
|
||||
triton: 0.25
|
||||
};
|
||||
/** The clock's window, AD 1 to 3000 (`CLOCK_WINDOW` in `time.store.ts`), as Julian dates. */
|
||||
const CLOCK_START_JD = Date.parse('0001-01-01T00:00Z') / 86400000 + 2440587.5;
|
||||
const CLOCK_END_JD = Date.parse('3000-01-01T00:00Z') / 86400000 + 2440587.5;
|
||||
const LOCK_DATES_JD = Array.from({ length: Math.floor((CLOCK_END_JD - CLOCK_START_JD) / 135) + 1 }, (_, index) => CLOCK_START_JD + index * 135);
|
||||
|
||||
function angleBetweenDeg(a: { x: number; y: number; z: number }, b: { x: number; y: number; z: number }): number {
|
||||
const cosine = (a.x * b.x + a.y * b.y + a.z * b.z) / (Math.hypot(a.x, a.y, a.z) * Math.hypot(b.x, b.y, b.z));
|
||||
return (Math.acos(Math.min(1, Math.max(-1, cosine))) * 180) / Math.PI;
|
||||
}
|
||||
|
||||
/** Degrees between a body's spin axis — its IAU pole, turned over where W runs backwards — and the normal of the orbit it is drawn going round, at a TDB date. */
|
||||
function axisFromOrbitDeg(body: BodyRecord, rotation: RotationalElements, jd: number): number {
|
||||
const pole = orientationAt(rotation, jd);
|
||||
const pointing = raDecToUnitVector(pole.poleRaDeg / 15, pole.poleDecDeg);
|
||||
const sense = Math.sign(rotation.primeMeridianDeg[1]);
|
||||
const axis = { x: sense * pointing.x, y: sense * pointing.y, z: sense * pointing.z };
|
||||
const { inclinationDeg, longitudeOfAscendingNodeDeg } = meanElementsAt(body.orbit, body.rates, jd);
|
||||
const tilt = inclinationDeg * DEG_TO_RAD;
|
||||
const node = longitudeOfAscendingNodeDeg * DEG_TO_RAD;
|
||||
const normal = { x: Math.sin(tilt) * Math.sin(node), y: -Math.sin(tilt) * Math.cos(node), z: Math.cos(tilt) };
|
||||
return angleBetweenDeg(axis, body.laplacePole ? laplacePlaneToEquatorial(normal, body.laplacePole) : eclipticToEquatorial(normal));
|
||||
}
|
||||
|
||||
function validateBodies(bodies: BodyRecord[], horizonsOrbits: Map<string, OrbitalElements>, horizonsTracks: Map<string, TrackPoint[]>): void {
|
||||
function validateBodies(bodies: BodyRecord[]): void {
|
||||
assertCondition(bodies.length > 0, 'No solar-system bodies were produced.');
|
||||
|
||||
const ids = new Set(bodies.map((body) => body.id));
|
||||
assertCondition(ids.size === bodies.length, 'Duplicate body ids were found.');
|
||||
|
||||
const offsets: string[] = [];
|
||||
const spins: string[] = [];
|
||||
for (const body of bodies) {
|
||||
const orbitValues = Object.values(body.orbit);
|
||||
assertCondition(orbitValues.every(Number.isFinite), `Body ${body.id} has non-finite orbital elements.`);
|
||||
assertCondition(body.rates.meanMotionDegPerDay > 0, `Body ${body.id} has no mean motion.`);
|
||||
|
||||
// Horizons' elements are osculating, exact at their own epoch; both sets are placed there.
|
||||
const horizons = horizonsOrbits.get(body.id);
|
||||
assertCondition(horizons !== undefined, `Body ${body.id} has no Horizons elements to be checked against.`);
|
||||
const truth = eclipticToEquatorial(positionAtEpoch(horizons!));
|
||||
const mean = positionAtEpoch(meanElementsAt(body.orbit, body.rates, horizons!.epochJd));
|
||||
const offset = angleBetweenDeg(body.laplacePole ? laplacePlaneToEquatorial(mean, body.laplacePole) : eclipticToEquatorial(mean), truth);
|
||||
const ceiling = body.kind === 'moon' ? (MOON_OFFSET_CEILINGS_DEG[body.id] ?? MAX_MOON_OFFSET_DEG) : MAX_PLANET_OFFSET_DEG;
|
||||
assertCondition(
|
||||
offset <= ceiling,
|
||||
`${body.name}'s mean elements put it ${offset.toFixed(2)} degrees from where Horizons has it (at most ${ceiling} expected) — the elements were read wrongly.`
|
||||
);
|
||||
offsets.push(`${body.id} ${offset.toFixed(3)}`);
|
||||
|
||||
// Standish's fit names its own span; every other orbit is measured over 1950-2100, and says so.
|
||||
const track = horizonsTracks.get(body.id);
|
||||
assertCondition(
|
||||
(track !== undefined) === !body.orbitSource.startsWith('JPL approximate mean elements (Standish)'),
|
||||
`${body.name}'s orbit, "${body.orbitSource}", ${track ? 'names its own span' : 'names no span it holds over'}.`
|
||||
);
|
||||
// JPL's satellite table carries no periodic terms: a moon's are from its IAU W, and its card
|
||||
// names the kernel they come from as well as the table.
|
||||
assertCondition(
|
||||
!body.parentBodyId || !body.rates.meanAnomalyTerms || body.orbitSource.includes('NAIF pck00011'),
|
||||
`${body.name}'s orbit carries terms taken from its IAU W, and its card, "${body.orbitSource}", credits only the table.`
|
||||
);
|
||||
if (track) {
|
||||
const worst = Math.max(...track.map((point) => offsetFromTrackDeg(body, point)));
|
||||
const trackCeiling = TRACK_OFFSET_CEILINGS_DEG[body.id] ?? MAX_TRACK_OFFSET_DEG;
|
||||
const stated = Number(body.orbitSource.match(/within ([\d.]+) degrees of Horizons/)?.[1]);
|
||||
assertCondition(
|
||||
worst <= trackCeiling && stated >= worst,
|
||||
`${body.name}'s mean elements put it up to ${worst.toFixed(2)} degrees from Horizons between 1950 and 2100 (at most ${trackCeiling} expected), and its card says "${body.orbitSource}".`
|
||||
);
|
||||
offsets.push(`${body.id} ${worst.toFixed(2)} at worst`);
|
||||
}
|
||||
// The card prints this under "Measured". An osculating eccentricity swings about its mean — the
|
||||
// Moon's by 0.015 here, Phoebe's by as much — but not by the 0.087 Hyperion's older row was out.
|
||||
const printed = body.measuredEccentricity ?? body.orbit.eccentricity;
|
||||
assertCondition(
|
||||
Math.abs(printed - horizons!.eccentricity) <= MAX_ECCENTRICITY_OFFSET,
|
||||
`${body.name}'s card gives an eccentricity of ${printed}, where Horizons' osculating orbit has ${horizons!.eccentricity.toFixed(4)} (at most ${MAX_ECCENTRICITY_OFFSET} apart expected).`
|
||||
);
|
||||
|
||||
// A radius of 0 is what a page whose radius no pattern reads comes out as — Charon's did.
|
||||
assertCondition(body.radiusKm > 0, `Body ${body.id} has no radius; its page states it in a form the ETL does not read.`);
|
||||
// A triaxial body's card gives its mean radius beside its semi-axes, so the two must agree: the
|
||||
// radius of the sphere of the same volume. Measured: Haumea's 797.6 against 797.62.
|
||||
if (body.semiAxesKm) {
|
||||
const volumeRadius = Math.cbrt(body.semiAxesKm[0] * body.semiAxesKm[1] * body.semiAxesKm[2]);
|
||||
assertCondition(
|
||||
Math.abs(volumeRadius / body.radiusKm - 1) < 0.001,
|
||||
`${body.name}'s radius, ${body.radiusKm} km, is not the mean of its semi-axes ${body.semiAxesKm.join(' x ')}, ${volumeRadius.toFixed(1)} km.`
|
||||
);
|
||||
}
|
||||
|
||||
const rotation = body.rotationalElements;
|
||||
assertCondition(
|
||||
(rotation === undefined) === WITHOUT_ROTATIONAL_ELEMENTS.has(body.id),
|
||||
`Body ${body.id} ${rotation ? 'has' : 'has no'} IAU rotational elements, which the report ${rotation ? 'does not give' : 'gives'} for it.`
|
||||
);
|
||||
if (rotation) {
|
||||
const rate = rotation.primeMeridianDeg[1];
|
||||
if (body.rotationPeriodHours !== undefined) {
|
||||
const dayOffset = Math.abs(((360 / Math.abs(rate)) * 24) / Math.abs(body.rotationPeriodHours) - 1);
|
||||
const dayCeiling = DAY_OFFSET_CEILINGS[body.id] ?? MAX_DAY_OFFSET;
|
||||
assertCondition(
|
||||
dayOffset <= dayCeiling,
|
||||
`${body.name}'s IAU day, ${((360 / Math.abs(rate)) * 24).toFixed(5)} hours, is ${dayOffset.toExponential(2)} of its length from the ${Math.abs(body.rotationPeriodHours).toFixed(5)} its record carries (at most ${dayCeiling} expected).`
|
||||
);
|
||||
spins.push(`${body.id} day ${dayOffset.toExponential(1)}`);
|
||||
}
|
||||
if (body.obliquityDeg !== undefined) {
|
||||
const obliquity = axisFromOrbitDeg(body, rotation, horizons!.epochJd);
|
||||
assertCondition(
|
||||
Math.abs(obliquity - body.obliquityDeg) <= MAX_OBLIQUITY_OFFSET_DEG,
|
||||
`${body.name}'s IAU spin axis is ${obliquity.toFixed(3)} degrees from its orbit's pole, where ${body.id === 'pluto' ? 'its IAU pole' : 'Horizons'} gives an obliquity of ${body.obliquityDeg} (at most ${MAX_OBLIQUITY_OFFSET_DEG} apart expected) — the pole or the sense of W was read wrongly.`
|
||||
);
|
||||
spins.push(`${body.id} tilt ${obliquity.toFixed(3)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (body.kind === 'moon') {
|
||||
const parent = bodies.find((candidate) => candidate.id === body.parentBodyId);
|
||||
assertCondition(parent !== undefined, `Moon ${body.id} has no valid parentBodyId.`);
|
||||
const orbitHours = (360 / body.rates.meanMotionDegPerDay) * 24;
|
||||
if (FREELY_SPINNING_MOONS.has(body.id)) {
|
||||
// Hyperion tumbles, and has no period; Nereid turns in 11.594 hours against a 360-day orbit,
|
||||
// and Phoebe in 9.27 against 550 days. A lock here would be the rule below misapplied.
|
||||
assertCondition(
|
||||
body.rotationPeriodHours !== undefined || TUMBLING.has(body.id),
|
||||
`Moon ${body.id} is drawn not turning, and is not known to tumble: its day was measured somewhere, find it.`
|
||||
);
|
||||
assertCondition(
|
||||
body.rotationPeriodHours === undefined || Math.abs(body.rotationPeriodHours - orbitHours) > orbitHours * 0.1,
|
||||
`Moon ${body.id} does not keep one face to its planet, yet turns once in ${body.rotationPeriodHours} hours against an orbit of ${orbitHours}.`
|
||||
);
|
||||
} else {
|
||||
// Every other moon here is tidally locked, and drawn by its orbit and its IAU W: the two
|
||||
// have to agree, or its face turns away from its planet.
|
||||
assertCondition(rotation !== undefined, `Moon ${body.id} is locked but has no W to keep its face to its planet by.`);
|
||||
const ceiling = SUB_PLANET_CEILINGS_DEG[body.id] ?? MAX_SUB_PLANET_LONGITUDE_DEG;
|
||||
const worst = Math.max(...LOCK_DATES_JD.map((jd) => Math.abs(subPlanetLongitudeDeg(body, rotation!, jd))));
|
||||
assertCondition(
|
||||
worst <= ceiling,
|
||||
`Moon ${body.id} turns its face up to ${worst.toFixed(2)} degrees from its planet between AD 1 and 3000 (at most ${ceiling} expected) — its orbit and its W disagree.`
|
||||
);
|
||||
spins.push(`${body.id} faces ${worst.toFixed(2)}`);
|
||||
const axisCeiling = AXIS_FROM_ORBIT_CEILINGS_DEG[body.id] ?? MAX_AXIS_FROM_ORBIT_DEG;
|
||||
const worstAxis = Math.max(...LOCK_DATES_JD.map((jd) => axisFromOrbitDeg(body, rotation!, jd)));
|
||||
assertCondition(
|
||||
worstAxis <= axisCeiling,
|
||||
`Moon ${body.id}'s spin axis leans up to ${worstAxis.toFixed(2)} degrees from its orbit's normal between AD 1 and 3000 (at most ${axisCeiling} expected) — its pole does not go round with its node.`
|
||||
);
|
||||
spins.push(`${body.id} axis ${worstAxis.toFixed(2)}`);
|
||||
}
|
||||
if (body.massRatio !== undefined) {
|
||||
// The pair's barycentre, which the planet's elements place, must lie outside the planet —
|
||||
// that is why the two are drawn going round it — and nearer the planet than the moon.
|
||||
const offsetKm = (body.orbit.semiMajorAxisAu * KM_PER_AU * body.massRatio) / (1 + body.massRatio);
|
||||
assertCondition(
|
||||
body.massRatio > 0 && body.massRatio < 1 && offsetKm > parent!.radiusKm,
|
||||
`${body.name}'s mass ratio ${body.massRatio} puts its barycentre ${offsetKm.toFixed(0)} km from ${parent!.name}'s centre, which is not between its surface, ${parent!.radiusKm} km out, and the moon.`
|
||||
);
|
||||
}
|
||||
assertCondition(!!body.parentBodyId && ids.has(body.parentBodyId), `Moon ${body.id} has no valid parentBodyId.`);
|
||||
}
|
||||
}
|
||||
|
||||
const planetCount = bodies.filter((body) => body.kind === 'planet').length;
|
||||
assertCondition(planetCount === 8, `Expected 8 planets, found ${planetCount}.`);
|
||||
const dwarfCount = bodies.filter((body) => body.kind === 'dwarf').length;
|
||||
assertCondition(dwarfCount === 5, `Expected the IAU's 5 dwarf planets, found ${dwarfCount}.`);
|
||||
// Eris keeps one face to Dysnomia, whose orbit takes 15.78590 days (Holler et al. 2021); its light
|
||||
// curve gives 15.771 +/- 0.008 (Bernstein et al. 2023). The SBDB still gives 25.9 hours.
|
||||
const erisDays = (bodies.find((body) => body.id === 'eris')?.rotationPeriodHours ?? NaN) / 24;
|
||||
assertCondition(
|
||||
Math.abs(erisDays / 15.7859 - 1) < 0.002,
|
||||
`Eris turns once in ${erisDays.toFixed(3)} days; it is locked to Dysnomia's 15.786-day orbit — the SBDB's 25.9-hour period, which it flags as possibly 30 per cent wrong, was taken.`
|
||||
);
|
||||
console.log(` mean elements against Horizons, degrees: ${offsets.join(', ')}.`);
|
||||
console.log(` IAU rotation against each record's day and tilt (see MAX_DAY_OFFSET for where each comes from; day as a fraction of it, tilt and a locked moon's face in degrees): ${spins.join(', ')}.`);
|
||||
}
|
||||
|
||||
function validateExoplanets(exoplanets: ExoplanetRecord[], starIds: Set<number>): void {
|
||||
@@ -518,24 +183,8 @@ function validateExoplanets(exoplanets: ExoplanetRecord[], starIds: Set<number>)
|
||||
const withPeriod = exoplanets.filter((exoplanet) => exoplanet.periodDays !== undefined).length;
|
||||
const withHostMass = exoplanets.filter((exoplanet) => exoplanet.hostStarMassSolar !== undefined).length;
|
||||
console.log(` ${withPeriod}/${exoplanets.length} have a measured period, ${withHostMass} a host star mass.`);
|
||||
|
||||
// The planets photographed by direct imaging, whose card must not say no image of them exists.
|
||||
// Measured: 101 of 101 flagged in the archive, and not transiting, are in the catalogue. What this
|
||||
// catches is the join by name failing, which would put every one of them back under "no image".
|
||||
const imaged = exoplanets.filter((exoplanet) => exoplanet.imaged).length;
|
||||
assertCondition(imaged >= MIN_IMAGED_EXOPLANETS, `Only ${imaged} exoplanets are marked as imaged (at least ${MIN_IMAGED_EXOPLANETS} expected).`);
|
||||
// And the one the flag is wrong on, which the count cannot see: a 2.68-day transiting hot Jupiter
|
||||
// 0.15 mas from its star, flagged for the companion star a survey imaged beside it. Its record
|
||||
// carries neither a period nor an axis, so no separation check could catch it either.
|
||||
assertCondition(
|
||||
!exoplanets.some((exoplanet) => exoplanet.id === 'WASP-108 b' && exoplanet.imaged),
|
||||
'WASP-108 b is marked as imaged; it transits, and only a companion star beside it was imaged (Bohn et al. 2020).'
|
||||
);
|
||||
console.log(` ${imaged} were imaged directly.`);
|
||||
}
|
||||
|
||||
const MIN_IMAGED_EXOPLANETS = 95;
|
||||
|
||||
const UNIT_VECTOR_TOLERANCE = 1e-6;
|
||||
|
||||
function validateDeepSky(objects: DeepSkyRecord[]): void {
|
||||
@@ -585,7 +234,7 @@ async function build(): Promise<void> {
|
||||
|
||||
const stars = await fetchStars();
|
||||
console.log();
|
||||
const { bodies, horizonsOrbits, horizonsTracks } = await fetchSolarSystem();
|
||||
const bodies = await fetchSolarSystem();
|
||||
console.log();
|
||||
const exoplanets = await fetchExoplanets(stars);
|
||||
console.log();
|
||||
@@ -595,7 +244,7 @@ async function build(): Promise<void> {
|
||||
console.log('Validating output...');
|
||||
validateStars(stars);
|
||||
validateMerge(stars);
|
||||
validateBodies(bodies, horizonsOrbits, horizonsTracks);
|
||||
validateBodies(bodies);
|
||||
validateExoplanets(exoplanets, new Set(stars.map((star) => star.id)));
|
||||
validateDeepSky(deepSky);
|
||||
|
||||
|
||||
@@ -41,16 +41,6 @@ const TAP_URL = `${TAP_BASE_URL}?query=${TAP_QUERY}`;
|
||||
// silently wrong rather than visibly broken.
|
||||
const CACHE_FILE = `exoplanet-archive-ps-${createHash('sha1').update(TAP_URL).digest('hex').slice(0, 8)}.csv`;
|
||||
|
||||
// The planets the archive flags as detected by imaging (`ima_flag`): 101 of them in September 2026,
|
||||
// HR 8799's four and 51 Eri b among them, and bet Pic c and eps Ind A b, found by radial velocity
|
||||
// and imaged since. Asked for on its own, so adding it did not refetch the table above and move
|
||||
// every other planet to a newer snapshot. A transiting planet is left out: the one flagged,
|
||||
// WASP-108 b, takes its flag from Bohn et al. 2020, a VLT/SPHERE survey of transiting planets' host
|
||||
// stars that imaged a 0.35 solar-mass companion 0.124" from its star. The planet goes round in 2.68
|
||||
// days, 0.04 AU out, 0.15 mas at its 259 pc, and no imager has resolved it.
|
||||
const IMAGED_URL = `${TAP_BASE_URL}?query=select+pl_name+from+ps+where+default_flag=1+and+ima_flag=1+and+tran_flag=0+order+by+pl_name&format=csv`;
|
||||
const IMAGED_CACHE_FILE = `exoplanet-archive-imaged-${createHash('sha1').update(IMAGED_URL).digest('hex').slice(0, 8)}.csv`;
|
||||
|
||||
/**
|
||||
* Downloads confirmed exoplanets from the NASA Exoplanet Archive (`Planetary Systems` TAP
|
||||
* table), cross-references each host star to the HYG index, and writes `exoplanets.json`.
|
||||
@@ -62,7 +52,6 @@ export async function fetchExoplanets(stars?: StarRecord[]): Promise<ExoplanetRe
|
||||
|
||||
const csv = await fetchTextCached(TAP_URL, CACHE_FILE);
|
||||
const rows = parseCsvObjects(csv);
|
||||
const imaged = new Set(parseCsvObjects(await fetchTextCached(IMAGED_URL, IMAGED_CACHE_FILE)).map((row) => row['pl_name']));
|
||||
|
||||
let matched = 0;
|
||||
const exoplanets: ExoplanetRecord[] = rows.map((row, index) => {
|
||||
@@ -91,7 +80,6 @@ export async function fetchExoplanets(stars?: StarRecord[]): Promise<ExoplanetRe
|
||||
radiusEarth: parseOptionalNumber(row['pl_rade']),
|
||||
massEarth: parseOptionalNumber(row['pl_bmasse']),
|
||||
discoveryYear: parseOptionalNumber(row['disc_year']),
|
||||
imaged: imaged.has(row['pl_name']) || undefined,
|
||||
// The period was already being downloaded and thrown away. With the semi-major axis it
|
||||
// determines the host's gravitational parameter, so keeping it is the difference between
|
||||
// propagating a planet at its real rate and pretending every host is the Sun.
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
import { writeFileSync } from 'node:fs';
|
||||
|
||||
import { BodyRecord, OrbitalElements } from '../../src/app/shared/models/body.model';
|
||||
import { BodyRecord } from '../../src/app/shared/models/body.model';
|
||||
import { SUN_STAR_ID } from '../../src/app/shared/models/star.model';
|
||||
import { fetchHorizonsBody, fetchHorizonsTrack, TRACK_START_YEAR, TRACK_STOP_YEAR, TrackPoint } from './lib/horizons';
|
||||
import { eclipticToEquatorial, laplacePlaneToEquatorial } from '../../src/app/shared/astro/coordinates';
|
||||
import { meanElementsAt, positionAtEpoch } from '../../src/app/shared/astro/kepler';
|
||||
import { MeanOrbit, parsePlanetMeanElements, parseSatelliteMeanElements, parseSmallBodyElements } from '../../src/app/shared/astro/mean-elements';
|
||||
import { fetchPlanetMeanElementsText, fetchSatelliteMeanElementsHtml, fetchSmallBodyAnswer } from './lib/mean-elements';
|
||||
import { MIN_PERIODIC_TERM_DEG, orbitalTermsOfPrimeMeridian, parsePckRotationalElements, SUN_ROTATIONAL_ELEMENTS } from '../../src/app/shared/astro/rotational-elements';
|
||||
import { fetchPckText } from './lib/pck';
|
||||
import { lockedToOrbit } from './lib/locked-spin';
|
||||
import { fetchHorizonsBody } from './lib/horizons';
|
||||
import { dataPath, ensureDataDir } from './lib/paths';
|
||||
|
||||
const HOURS_PER_DAY = 24;
|
||||
const DAYS_PER_JULIAN_YEAR = 365.25;
|
||||
|
||||
interface BodySpec {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -22,100 +12,8 @@ interface BodySpec {
|
||||
horizonsCommand: string;
|
||||
center: string;
|
||||
parentBodyId?: string;
|
||||
/**
|
||||
* Obliquity to orbit, in degrees, where the Horizons page states none. Pluto's is from the IAU
|
||||
* WGCCRE 2015 pole (RA 132.99, Dec -6.16), 119.6 degrees: past 90, so it turns retrograde.
|
||||
*/
|
||||
obliquityDeg?: number;
|
||||
/** The periapsis turns backwards; see `parseSatelliteMeanElements`. */
|
||||
apsidesRegress?: boolean;
|
||||
/** The pole of the planet's equator, where JPL gives its moons against that plane. */
|
||||
equatorPole?: { raDeg: number; decDeg: number };
|
||||
/** The Small-Body Database's name for a dwarf planet past Standish's tables: its orbit comes from there. */
|
||||
sbdb?: string;
|
||||
/** A measured mean radius, in km, for a body neither Horizons nor the SBDB gives one for. */
|
||||
radiusKm?: number;
|
||||
/** A triaxial body's semi-axes, in km, largest first, where its card should give its shape; see `BodyRecord.semiAxesKm`. */
|
||||
semiAxesKm?: [number, number, number];
|
||||
/** A measured sidereal day, in hours, where a later measurement overturns the one its source gives. */
|
||||
rotationPeriodHours?: number;
|
||||
/** The eccentricity for the card, where the row the orbit is drawn from gives an outdated one; see `BodyRecord.measuredEccentricity`. */
|
||||
measuredEccentricity?: number;
|
||||
/** A moon that does not keep one face to its planet: its page's own spin, or none, is kept. */
|
||||
spinsFreely?: boolean;
|
||||
/** A moon heavy enough to move its planet round their barycentre visibly; see `BodyRecord.massRatio`. */
|
||||
barycentric?: boolean;
|
||||
/**
|
||||
* Corrections to a row of the satellite table, each where the row disagrees with JPL's own
|
||||
* Horizons ephemeris and the reason is known; see the specs that carry them.
|
||||
*/
|
||||
nodeOffsetDeg?: number;
|
||||
epochJd?: number;
|
||||
periodDays?: number;
|
||||
/**
|
||||
* The node's period, in Julian years, where the row's is out of date. The archived table the rows
|
||||
* are read from (see `fetchSatelliteMeanElementsHtml`) has older node periods for four moons than
|
||||
* JPL's current one (ssd.jpl.nasa.gov/sats/elem), and Horizons and the IAU agree with the current
|
||||
* ones: Miranda 17.787 years there (URA182) against the row's 17.727, Ganymede 137.812 (JUP365)
|
||||
* against 132.654, Callisto 577.264 against 338.82, Titan 687.370 (SAT441) against 704.60. Fitted
|
||||
* to Horizons' osculating elements on Uranus's equator over 1601-2399, Miranda's node turns
|
||||
* 2023.97 degrees a century (rms 0.04): the current table's 2023.95, the IAU's U11 2024.22, the
|
||||
* row's 2030.80. On the row's rate Miranda's drawn orbit was 2.0 degrees from Horizons' at 1601
|
||||
* and 2.1 at 2399, and the axis `lockedToOrbit` turned after it 2.4 at 1601; on this one, at most 0.12 and 0.34 over 1601-2399.
|
||||
*
|
||||
* The row's periapsis turns at its argument's rate from that node, and it is the longitude, node
|
||||
* plus argument, the row gives the rate of: Callisto's turns 68.7 degrees a century in the row and
|
||||
* 67.2 in the current table, where their arguments turn at 175.0 and 129.5. So the argument takes
|
||||
* up what the node's rate gives: on the new node and the row's argument, Callisto's periapsis
|
||||
* moved 44 degrees by 2100 and Callisto strayed 0.71 degrees from Horizons over 1950-2100 (0.19
|
||||
* before); keeping the row's longitude, 0.08.
|
||||
*/
|
||||
nodePeriodYears?: number;
|
||||
/**
|
||||
* The terms of the IAU's W that are this locked moon's motion along its orbit, which its row has
|
||||
* no column for: W's quadratic, and the term whose angle turns at `angleRateDegPerCentury`, if
|
||||
* given. See `orbitalTermsOfPrimeMeridian`.
|
||||
*/
|
||||
orbitFromW?: { angleRateDegPerCentury?: number };
|
||||
/** A locked moon whose pole is carried round with its orbit's, as Iapetus's; see `lockedToOrbit`. */
|
||||
poleFollowsOrbit?: boolean;
|
||||
/**
|
||||
* Days between the Horizons positions the orbit is checked against from 1950 to 2100; 2 unless
|
||||
* the error changes faster than that. Nereid, at an eccentricity of 0.75, sweeps through its
|
||||
* periapsis, where the mean ellipse is furthest out, in days; Hyperion, on a row whose
|
||||
* eccentricity is a quarter of its real one, peaks within a day too (22.23 degrees sampled daily
|
||||
* where every other day gave 22.14).
|
||||
*/
|
||||
trackStepDays?: number;
|
||||
}
|
||||
|
||||
/** S5 in pck00011.tpc, 316.45 + 506.2 T: the libration of Mimas and Tethys in their 4:2 resonance. */
|
||||
const MIMAS_TETHYS_LIBRATION = { angleRateDegPerCentury: 506.2 };
|
||||
|
||||
/**
|
||||
* Mimas's node period, 0.986 years in both JPL's tables, is given to three figures: anywhere from
|
||||
* 36 493 to 36 530 degrees a century. It takes the IAU's S3, 36 505.5, which a fit to Horizons'
|
||||
* osculating elements on Saturn's equator over 1750-2249, 36 506.7, is 1.2 from; the row's figure,
|
||||
* 36 511.2, is 4.5.
|
||||
*/
|
||||
const MIMAS_NODE_PERIOD_YEARS = 36000 / 36505.5;
|
||||
|
||||
/**
|
||||
* The poles of the equators JPL refers Uranus's and Pluto's moons to, from the IAU WGCCRE 2015
|
||||
* report, each taken at the end the table's inclinations are measured from (Titania 0.079
|
||||
* degrees, Charon 0.080): the end the moons go round anticlockwise. For Pluto that is the pole
|
||||
* the IAU gives, 132.993 / -6.163, which for dwarf planets follows the right-hand rule. For
|
||||
* Uranus the IAU gives the other end, 257.311 / -15.175, named north because it lies on the
|
||||
* ecliptic's north side; the table measures inclinations from 77.311 / 15.175 but counts its
|
||||
* nodes from where the equator rises through the ICRF equator going round the IAU's pole, which
|
||||
* is 180 degrees from where it rises going round this one: hence Uranus's moons' 180-degree node
|
||||
* offset. Read with this pole and no offset, Ariel was 180 degrees from Horizons at every date
|
||||
* from 1980 to 2100; read against the IAU's pole, anywhere from 1 to 179.
|
||||
*/
|
||||
const URANUS_EQUATOR_POLE = { raDeg: 77.311, decDeg: 15.175 };
|
||||
const PLUTO_EQUATOR_POLE = { raDeg: 132.993, decDeg: -6.163 };
|
||||
const URANUS_MOON = { kind: 'moon', center: '500@799', parentBodyId: 'uranus', equatorPole: URANUS_EQUATOR_POLE, nodeOffsetDeg: 180 } as const;
|
||||
|
||||
// Sun-centered planets/dwarf, then their major moons (planetocentric elements).
|
||||
const BODY_SPECS: BodySpec[] = [
|
||||
{ id: 'mercury', name: 'Mercury', kind: 'planet', horizonsCommand: '199', center: '500@10' },
|
||||
@@ -126,96 +24,26 @@ const BODY_SPECS: BodySpec[] = [
|
||||
{ id: 'saturn', name: 'Saturn', kind: 'planet', horizonsCommand: '699', center: '500@10' },
|
||||
{ id: 'uranus', name: 'Uranus', kind: 'planet', horizonsCommand: '799', center: '500@10' },
|
||||
{ id: 'neptune', name: 'Neptune', kind: 'planet', horizonsCommand: '899', center: '500@10' },
|
||||
{ id: 'pluto', name: 'Pluto', kind: 'dwarf', horizonsCommand: '999', center: '500@10', obliquityDeg: 119.6 },
|
||||
{ id: 'ceres', name: 'Ceres', kind: 'dwarf', horizonsCommand: '1;', center: '500@10', sbdb: 'Ceres' },
|
||||
// Eris, Haumea and Makemake have no radius in the SBDB, the Horizons pages ("RAD= n.a.") or the
|
||||
// IAU WGCCRE 2015 report, so each carries its stellar-occultation measurement. Eris: 1163 km,
|
||||
// Sicardy et al. 2011 (Nature 478, 493). Haumea is triaxial, 1161 x 852 x 513 km, Ortiz et al.
|
||||
// 2017 (Nature 550, 219); drawn as a sphere, at the radius of the sphere of the same volume.
|
||||
// Makemake: 1434 km across its equator and 1422 across its projected pole, Brown 2013 (ApJ 767,
|
||||
// L7); the same mean.
|
||||
//
|
||||
// Eris's day is not the SBDB's 25.9 hours, a light curve of partial coverage (Roe et al. 2008) the
|
||||
// SBDB itself flags as "may be wrong by 30 percent or so": it turns once in 15.771 +/- 0.008 days
|
||||
// (Bernstein et al. 2023, PSJ 4, 115), locked to Dysnomia's 15.786-day orbit (Szakáts et al.
|
||||
// 2023, A&A 669, L3). On the SBDB's figure it turned 14.6 times too fast.
|
||||
//
|
||||
// Makemake's day, the SBDB's 22.83 hours, carries the same flag and is not settled either: it is
|
||||
// the double-peaked reading Hromakina et al. 2019 (A&A 625, A46) give as "possible" of a light
|
||||
// curve that repeats every 11.4 hours. Kiss et al. 2024 (ApJL, arXiv:2410.22544) find that 11.40
|
||||
// +/- 0.08 hour single peak again with TESS and Gaia, cannot confirm the 22.8, and take 11.4 as
|
||||
// their default. Neither overturns the other; the SBDB's 22.83 is kept, and may be twice the day.
|
||||
{ id: 'eris', name: 'Eris', kind: 'dwarf', horizonsCommand: '136199;', center: '500@10', sbdb: 'Eris', radiusKm: 1163, rotationPeriodHours: 15.771 * 24 },
|
||||
{ id: 'haumea', name: 'Haumea', kind: 'dwarf', horizonsCommand: '136108;', center: '500@10', sbdb: 'Haumea', radiusKm: 797.6, semiAxesKm: [1161, 852, 513] },
|
||||
{ id: 'makemake', name: 'Makemake', kind: 'dwarf', horizonsCommand: '136472;', center: '500@10', sbdb: 'Makemake', radiusKm: 715 },
|
||||
{ id: 'pluto', name: 'Pluto', kind: 'dwarf', horizonsCommand: '999', center: '500@10' },
|
||||
{ id: 'moon', name: 'Moon', kind: 'moon', horizonsCommand: '301', center: '500@399', parentBodyId: 'earth' },
|
||||
{ id: 'phobos', name: 'Phobos', kind: 'moon', horizonsCommand: '401', center: '500@499', parentBodyId: 'mars', orbitFromW: {} },
|
||||
{ id: 'phobos', name: 'Phobos', kind: 'moon', horizonsCommand: '401', center: '500@499', parentBodyId: 'mars' },
|
||||
{ id: 'deimos', name: 'Deimos', kind: 'moon', horizonsCommand: '402', center: '500@499', parentBodyId: 'mars' },
|
||||
{ id: 'io', name: 'Io', kind: 'moon', horizonsCommand: '501', center: '500@599', parentBodyId: 'jupiter', apsidesRegress: true },
|
||||
{ id: 'europa', name: 'Europa', kind: 'moon', horizonsCommand: '502', center: '500@599', parentBodyId: 'jupiter', apsidesRegress: true },
|
||||
{ id: 'ganymede', name: 'Ganymede', kind: 'moon', horizonsCommand: '503', center: '500@599', parentBodyId: 'jupiter', nodePeriodYears: 137.812 },
|
||||
{ id: 'callisto', name: 'Callisto', kind: 'moon', horizonsCommand: '504', center: '500@599', parentBodyId: 'jupiter', nodePeriodYears: 577.264 },
|
||||
{ id: 'mimas', name: 'Mimas', kind: 'moon', horizonsCommand: '601', center: '500@699', parentBodyId: 'saturn', orbitFromW: MIMAS_TETHYS_LIBRATION, nodePeriodYears: MIMAS_NODE_PERIOD_YEARS },
|
||||
{ id: 'enceladus', name: 'Enceladus', kind: 'moon', horizonsCommand: '602', center: '500@699', parentBodyId: 'saturn' },
|
||||
{ id: 'tethys', name: 'Tethys', kind: 'moon', horizonsCommand: '603', center: '500@699', parentBodyId: 'saturn', orbitFromW: MIMAS_TETHYS_LIBRATION },
|
||||
{ id: 'dione', name: 'Dione', kind: 'moon', horizonsCommand: '604', center: '500@699', parentBodyId: 'saturn' },
|
||||
{ id: 'rhea', name: 'Rhea', kind: 'moon', horizonsCommand: '605', center: '500@699', parentBodyId: 'saturn' },
|
||||
{ id: 'titan', name: 'Titan', kind: 'moon', horizonsCommand: '606', center: '500@699', parentBodyId: 'saturn', nodePeriodYears: 687.37 },
|
||||
// Hyperion tumbles ("Rotational period = Chaotic") and Phoebe, captured, turns in 9.27 hours.
|
||||
// Hyperion's eccentricity is 0.105 in JPL's current table (ssd.jpl.nasa.gov/sats/elem, SAT441).
|
||||
{ id: 'hyperion', name: 'Hyperion', kind: 'moon', horizonsCommand: '607', center: '500@699', parentBodyId: 'saturn', spinsFreely: true, measuredEccentricity: 0.105, trackStepDays: 1 },
|
||||
{ id: 'iapetus', name: 'Iapetus', kind: 'moon', horizonsCommand: '608', center: '500@699', parentBodyId: 'saturn', poleFollowsOrbit: true },
|
||||
// Phoebe's row gives n = 0.6569114 degrees a day as the table defines it, the rate of its mean
|
||||
// longitude, node plus periapsis plus mean anomaly, and its P, 548.02 days, is 360 over that. Its
|
||||
// sidereal period is 550.30 (its Horizons page and JPL's current table, SAT441): n less twice its
|
||||
// node's rate, 0.6541855, against 360 / 550.30391 = 0.6541840. Triton's row gives its sidereal
|
||||
// rate as n instead, and the propagator reads a retrograde moon's n as that (see
|
||||
// `meanElementsAt`): on the row's n Phoebe ran twice its node's rate too fast, 25 degrees from
|
||||
// Horizons by 2025 and 100 by 2075. On the sidereal period it is within 2.6 from 1950 to 2100
|
||||
// (2.58 in 1969). The table's note on misstated retrograde mean motions is about another source,
|
||||
// Jacobson 2000 on Jupiter's outer moons, and says the table carries the corrected values.
|
||||
{ id: 'phoebe', name: 'Phoebe', kind: 'moon', horizonsCommand: '609', center: '500@699', parentBodyId: 'saturn', spinsFreely: true, periodDays: 550.30391 },
|
||||
{ id: 'miranda', name: 'Miranda', horizonsCommand: '705', ...URANUS_MOON, nodePeriodYears: 17.787 },
|
||||
{ id: 'ariel', name: 'Ariel', horizonsCommand: '701', ...URANUS_MOON },
|
||||
{ id: 'umbriel', name: 'Umbriel', horizonsCommand: '702', ...URANUS_MOON },
|
||||
{ id: 'titania', name: 'Titania', horizonsCommand: '703', ...URANUS_MOON },
|
||||
{ id: 'oberon', name: 'Oberon', horizonsCommand: '704', ...URANUS_MOON },
|
||||
{ id: 'triton', name: 'Triton', kind: 'moon', horizonsCommand: '801', center: '500@899', parentBodyId: 'neptune' },
|
||||
// Nereid's eccentric orbit, 0.75, cannot hold a face to Neptune. Its page states no spin, but
|
||||
// Kepler's K2 light curve gives 11.594 +/- 0.017 hours, confirming the short periods measured
|
||||
// from the ground (Kiss et al. 2016, MNRAS 457, 2908; arXiv:1601.02395). No pole is known.
|
||||
{ id: 'nereid', name: 'Nereid', kind: 'moon', horizonsCommand: '802', center: '500@899', parentBodyId: 'neptune', spinsFreely: true, rotationPeriodHours: 11.594, trackStepDays: 1 },
|
||||
{ id: 'proteus', name: 'Proteus', kind: 'moon', horizonsCommand: '808', center: '500@899', parentBodyId: 'neptune' },
|
||||
// Pluto's section prints its epoch as 2000 Jan 1.0; JPL's current table gives Charon's as
|
||||
// 2000-01-01.5, and read at 1.0 Charon sat 27.8 to 28.2 degrees — half a day of its motion is
|
||||
// 28.2 — from Horizons at every date from 1980 to 2100. At 1.5 it is within 0.4.
|
||||
{ id: 'charon', name: 'Charon', kind: 'moon', horizonsCommand: '901', center: '500@999', parentBodyId: 'pluto', equatorPole: PLUTO_EQUATOR_POLE, epochJd: 2451545.0, barycentric: true }
|
||||
{ id: 'io', name: 'Io', kind: 'moon', horizonsCommand: '501', center: '500@599', parentBodyId: 'jupiter' },
|
||||
{ id: 'europa', name: 'Europa', kind: 'moon', horizonsCommand: '502', center: '500@599', parentBodyId: 'jupiter' },
|
||||
{ id: 'ganymede', name: 'Ganymede', kind: 'moon', horizonsCommand: '503', center: '500@599', parentBodyId: 'jupiter' },
|
||||
{ id: 'callisto', name: 'Callisto', kind: 'moon', horizonsCommand: '504', center: '500@599', parentBodyId: 'jupiter' },
|
||||
{ id: 'titan', name: 'Titan', kind: 'moon', horizonsCommand: '606', center: '500@699', parentBodyId: 'saturn' },
|
||||
{ id: 'triton', name: 'Triton', kind: 'moon', horizonsCommand: '801', center: '500@899', parentBodyId: 'neptune' }
|
||||
];
|
||||
|
||||
/** The moons whose day is not their orbit; `build.ts` holds every other moon to its lock. */
|
||||
export const FREELY_SPINNING_MOONS = new Set(BODY_SPECS.filter((spec) => spec.spinsFreely).map((spec) => spec.id));
|
||||
|
||||
/**
|
||||
* Writes `bodies.json` for the major planets, the five dwarf planets, and every moon in JPL's
|
||||
* mean-element table more than 100 km in mean radius — Phoebe, at 106.6, the smallest: JPL's
|
||||
* mean orbital elements for where they go, or the SBDB's osculating ones where there are none,
|
||||
* JPL Horizons for their size and spin, and the IAU's rotational elements for where their poles
|
||||
* point and which face is where. Horizons' osculating elements for the same date come back
|
||||
* alongside, for `build.ts` to check the mean ones against.
|
||||
* Queries JPL Horizons for the osculating orbital elements (and mean radius, where
|
||||
* reported) of the major planets, Pluto, and a curated set of major moons, and writes
|
||||
* `bodies.json`.
|
||||
*/
|
||||
export async function fetchSolarSystem(): Promise<{ bodies: BodyRecord[]; horizonsOrbits: Map<string, OrbitalElements>; horizonsTracks: Map<string, TrackPoint[]> }> {
|
||||
console.log(`Fetching ${BODY_SPECS.length} solar-system bodies from JPL (mean elements, Horizons, NAIF's PCK)...`);
|
||||
export async function fetchSolarSystem(): Promise<BodyRecord[]> {
|
||||
console.log(`Fetching ${BODY_SPECS.length} solar-system bodies from JPL Horizons...`);
|
||||
const bodies: BodyRecord[] = [];
|
||||
const horizonsOrbits = new Map<string, OrbitalElements>();
|
||||
const horizonsTracks = new Map<string, TrackPoint[]>();
|
||||
const planetElements = await fetchPlanetMeanElementsText();
|
||||
const satelliteElements = await fetchSatelliteMeanElementsHtml();
|
||||
const pck = await fetchPckText();
|
||||
// The app turns the Sun by elements it carries itself; they must be the kernel's.
|
||||
if (JSON.stringify(parsePckRotationalElements(pck, 10)?.elements) !== JSON.stringify(SUN_ROTATIONAL_ELEMENTS)) {
|
||||
throw new Error(`The Sun's rotational elements in the app, ${JSON.stringify(SUN_ROTATIONAL_ELEMENTS)}, are not the kernel's.`);
|
||||
}
|
||||
const gmById = new Map<string, number | undefined>();
|
||||
|
||||
for (const spec of BODY_SPECS) {
|
||||
const result = await fetchHorizonsBody({
|
||||
@@ -224,122 +52,25 @@ export async function fetchSolarSystem(): Promise<{ bodies: BodyRecord[]; horizo
|
||||
cacheKey: `horizons-${spec.id}.txt`
|
||||
});
|
||||
|
||||
horizonsOrbits.set(spec.id, result.orbit);
|
||||
gmById.set(spec.id, result.gmKm3PerS2);
|
||||
|
||||
// NAIF numbers a small body 2 000 000 past its catalogue number: Ceres, "1;" to Horizons, is 2000001.
|
||||
const naifId = spec.horizonsCommand.endsWith(';') ? 2_000_000 + Number.parseInt(spec.horizonsCommand, 10) : Number(spec.horizonsCommand);
|
||||
const rotation = parsePckRotationalElements(pck, naifId);
|
||||
if (!rotation) {
|
||||
console.warn(` no IAU rotational elements for ${spec.name}; its pole and meridian are not known.`);
|
||||
} else if (rotation.skippedDeg.length > 0) {
|
||||
console.log(` ${spec.name}: ${rotation.skippedDeg.length} periodic terms under ${MIN_PERIODIC_TERM_DEG} degrees left out, the largest ${Math.max(...rotation.skippedDeg)}.`);
|
||||
}
|
||||
|
||||
const parentName = BODY_SPECS.find((candidate) => candidate.id === spec.parentBodyId)?.name;
|
||||
const smallBody = spec.sbdb ? parseSmallBodyElements(await fetchSmallBodyAnswer(spec.sbdb, `sbdb-${spec.id}.json`)) : undefined;
|
||||
const read: MeanOrbit =
|
||||
smallBody ??
|
||||
(parentName
|
||||
? parseSatelliteMeanElements(satelliteElements, parentName, spec.name, spec.apsidesRegress ?? false, spec.equatorPole)
|
||||
: parsePlanetMeanElements(planetElements, spec.id));
|
||||
const nodeRate = spec.nodePeriodYears
|
||||
? Math.sign(read.rates.longitudeOfAscendingNodeDegPerDay) * (360 / (spec.nodePeriodYears * DAYS_PER_JULIAN_YEAR))
|
||||
: read.rates.longitudeOfAscendingNodeDegPerDay;
|
||||
const corrected: MeanOrbit = {
|
||||
...read,
|
||||
orbit: {
|
||||
...read.orbit,
|
||||
longitudeOfAscendingNodeDeg: read.orbit.longitudeOfAscendingNodeDeg + (spec.nodeOffsetDeg ?? 0),
|
||||
epochJd: spec.epochJd ?? read.orbit.epochJd
|
||||
},
|
||||
rates: {
|
||||
...read.rates,
|
||||
...(spec.periodDays ? { meanMotionDegPerDay: 360 / spec.periodDays } : {}),
|
||||
longitudeOfAscendingNodeDegPerDay: nodeRate,
|
||||
// The periapsis's longitude keeps the row's rate; see `nodePeriodYears`.
|
||||
argumentOfPeriapsisDegPerDay: read.rates.argumentOfPeriapsisDegPerDay + (read.rates.longitudeOfAscendingNodeDegPerDay - nodeRate)
|
||||
}
|
||||
};
|
||||
if (spec.orbitFromW && !rotation) {
|
||||
throw new Error(`${spec.name}'s orbit takes terms from a W the kernel does not give.`);
|
||||
}
|
||||
const fromW = spec.orbitFromW && orbitalTermsOfPrimeMeridian(rotation!.elements, corrected.orbit.epochJd, spec.orbitFromW.angleRateDegPerCentury);
|
||||
const mean: MeanOrbit = fromW
|
||||
? {
|
||||
...corrected,
|
||||
orbit: { ...corrected.orbit, meanAnomalyAtEpochDeg: corrected.orbit.meanAnomalyAtEpochDeg + fromW.meanAnomalyDeg },
|
||||
rates: { ...corrected.rates, meanMotionDegPerDay: corrected.rates.meanMotionDegPerDay + fromW.meanMotionDegPerDay, meanAnomalyTerms: fromW.meanAnomalyTerms }
|
||||
}
|
||||
: corrected;
|
||||
|
||||
// Standish's fit states its own span, 3000 BC to AD 3000. The moons' table and the SBDB state
|
||||
// none, and hold for far less: each card says how far its orbit stays from Horizons over the
|
||||
// span it was measured, where the clock reaches AD 1 to AD 3000. An orbit that took terms from
|
||||
// its IAU W says so first: they move Mimas by up to 44.85 degrees, and are none of JPL's table.
|
||||
let orbitSource = fromW ? `${mean.orbitSource}, with the orbital terms of its IAU W (NAIF pck00011)` : mean.orbitSource;
|
||||
if (parentName || smallBody) {
|
||||
const stepDays = spec.trackStepDays ?? 2;
|
||||
const track = await fetchHorizonsTrack(spec.horizonsCommand, spec.center, stepDays, `horizons-track-${spec.id}-${stepDays}d.txt`);
|
||||
horizonsTracks.set(spec.id, track);
|
||||
const worst = Math.max(...track.map((point) => offsetFromTrackDeg(mean, point)));
|
||||
orbitSource += `, within ${(Math.ceil(worst * 10) / 10).toFixed(1)} degrees of Horizons from ${TRACK_START_YEAR} to ${TRACK_STOP_YEAR}`;
|
||||
}
|
||||
const radiusKm = smallBody?.radiusKm ?? spec.radiusKm ?? result.radiusKm;
|
||||
if (radiusKm === undefined) {
|
||||
if (result.radiusKm === undefined) {
|
||||
console.warn(` no physical radius found for ${spec.name}; defaulting to 0.`);
|
||||
}
|
||||
|
||||
// A moon listed here is tidally locked unless its spec says otherwise, so its day is its
|
||||
// orbit: the sidereal period from the same mean motion that carries it round. Not every page
|
||||
// says so — the Moon's gives a rate, Titan's and Proteus's nothing. Every locked moon here is
|
||||
// turned by its IAU W, at this same rate (see `lockedToOrbit`), and `build.ts` checks that W and
|
||||
// the orbit keep its face to its planet from AD 1 to 3000; this day is what the renderer would
|
||||
// turn a moon without W by.
|
||||
const locked = spec.kind === 'moon' && !spec.spinsFreely;
|
||||
const rotationPeriodHours = result.tidallyLocked || locked
|
||||
? (360 / mean.rates.meanMotionDegPerDay) * HOURS_PER_DAY
|
||||
: (spec.rotationPeriodHours ?? (smallBody ? smallBody.rotationPeriodHours : result.rotationPeriodHours));
|
||||
const parentGm = spec.barycentric && spec.parentBodyId ? gmById.get(spec.parentBodyId) : undefined;
|
||||
if (spec.barycentric && (result.gmKm3PerS2 === undefined || parentGm === undefined)) {
|
||||
throw new Error(`${spec.name} and its planet need a GM each to place their barycentre.`);
|
||||
}
|
||||
if (rotationPeriodHours === undefined) {
|
||||
console.warn(` no rotation period found for ${spec.name}; it will not turn.`);
|
||||
}
|
||||
|
||||
bodies.push({
|
||||
id: spec.id,
|
||||
systemStarId: SUN_STAR_ID,
|
||||
name: spec.name,
|
||||
kind: spec.kind,
|
||||
radiusKm: radiusKm ?? 0,
|
||||
...(spec.semiAxesKm ? { semiAxesKm: spec.semiAxesKm } : {}),
|
||||
orbit: mean.orbit,
|
||||
rates: mean.rates,
|
||||
...(mean.laplacePole ? { laplacePole: mean.laplacePole } : {}),
|
||||
orbitSource,
|
||||
...(spec.measuredEccentricity !== undefined ? { measuredEccentricity: spec.measuredEccentricity } : {}),
|
||||
...(spec.parentBodyId ? { parentBodyId: spec.parentBodyId } : {}),
|
||||
...(parentGm !== undefined ? { massRatio: result.gmKm3PerS2! / parentGm } : {}),
|
||||
...(rotationPeriodHours !== undefined ? { rotationPeriodHours } : {}),
|
||||
...((result.obliquityDeg ?? spec.obliquityDeg) !== undefined ? { obliquityDeg: result.obliquityDeg ?? spec.obliquityDeg } : {}),
|
||||
...(rotation ? { rotationalElements: locked ? lockedToOrbit(rotation.elements, mean, spec.name, spec.poleFollowsOrbit) : rotation.elements } : {})
|
||||
radiusKm: result.radiusKm ?? 0,
|
||||
orbit: result.orbit,
|
||||
...(spec.parentBodyId ? { parentBodyId: spec.parentBodyId } : {})
|
||||
});
|
||||
}
|
||||
|
||||
ensureDataDir();
|
||||
writeFileSync(dataPath('bodies.json'), JSON.stringify(bodies, null, 2));
|
||||
console.log(` wrote ${bodies.length} bodies.`);
|
||||
return { bodies, horizonsOrbits, horizonsTracks };
|
||||
}
|
||||
|
||||
/** Degrees between where a moon's or dwarf planet's mean elements put it and where Horizons has it. */
|
||||
export function offsetFromTrackDeg(mean: Pick<MeanOrbit, 'orbit' | 'rates' | 'laplacePole'>, point: TrackPoint): number {
|
||||
const own = positionAtEpoch(meanElementsAt(mean.orbit, mean.rates, point.jd));
|
||||
const place = mean.laplacePole ? laplacePlaneToEquatorial(own, mean.laplacePole) : eclipticToEquatorial(own);
|
||||
const cosine = (place.x * point.x + place.y * point.y + place.z * point.z) / (Math.hypot(place.x, place.y, place.z) * Math.hypot(point.x, point.y, point.z));
|
||||
return (Math.acos(Math.min(1, Math.max(-1, cosine))) * 180) / Math.PI;
|
||||
return bodies;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { OrbitalElements } from '../../../src/app/shared/models/body.model';
|
||||
import { extractGmKm3PerS2, extractObliquityDeg, extractRadiusKm, extractRotationPeriodHours, isTidallyLocked } from '../../../src/app/shared/astro/horizons-page';
|
||||
import { fetchTextCached } from './http';
|
||||
|
||||
const HORIZONS_URL = 'https://ssd.jpl.nasa.gov/api/horizons.api';
|
||||
@@ -11,7 +10,7 @@ const REFERENCE_START = '2025-01-01';
|
||||
const REFERENCE_STOP = '2025-01-02';
|
||||
|
||||
export interface HorizonsQuery {
|
||||
/** Horizons body id, e.g. `'499'` for Mars, or a small body's number and a semicolon, `'1;'` for Ceres. */
|
||||
/** Horizons body id, e.g. `'499'` for Mars. */
|
||||
command: string;
|
||||
/** Horizons coordinate center, e.g. `'500@10'` (Sun) or `'500@399'` (Earth). */
|
||||
center: string;
|
||||
@@ -21,42 +20,44 @@ export interface HorizonsQuery {
|
||||
export interface HorizonsResult {
|
||||
radiusKm?: number;
|
||||
orbit: OrbitalElements;
|
||||
/**
|
||||
* Sidereal rotation period in hours, negative where the page gives a negative rate —
|
||||
* Venus and Uranus. Absent where the page publishes none. The same pages also give an obliquity
|
||||
* past 90 degrees for those two, which says the same thing again; see the renderer's spinFor.
|
||||
*/
|
||||
rotationPeriodHours?: number;
|
||||
/** Tilt of the rotation axis from the body's own orbital plane, in degrees. */
|
||||
obliquityDeg?: number;
|
||||
/** The page says "Synchronous" instead of a period: its day is its orbit. */
|
||||
tidallyLocked: boolean;
|
||||
/** The body's own GM, km³/s², where the page states one: what sets where a pair's barycentre lies. */
|
||||
gmKm3PerS2?: number;
|
||||
}
|
||||
|
||||
const RADIUS_PATTERNS = [
|
||||
/Vol\.?\s*mean\s*radius[^=]*=\s*([\d.]+)/i,
|
||||
/Mean\s*radius[^=]*=\s*([\d.]+)/i,
|
||||
/Radius\s*\(IAU\)[^=]*=\s*([\d.]+)/i,
|
||||
/Radius,?\s*\(km\)\s*=\s*([\d.]+)/i,
|
||||
/Radius\s*\(gravity\),?\s*km\s*=\s*([\d.]+)/i
|
||||
];
|
||||
|
||||
/**
|
||||
* Queries JPL Horizons for a body's heliocentric (or planetocentric, for moons) osculating
|
||||
* orbital elements plus, when available, its mean physical radius and how it turns — all in a
|
||||
* single request (`OBJ_DATA=YES` + `EPHEM_TYPE=ELEMENTS`).
|
||||
* orbital elements plus, when available, its mean physical radius — both in a single
|
||||
* request (`OBJ_DATA=YES` + `EPHEM_TYPE=ELEMENTS`).
|
||||
*/
|
||||
export async function fetchHorizonsBody(query: HorizonsQuery): Promise<HorizonsResult> {
|
||||
const url =
|
||||
`${HORIZONS_URL}?format=text&COMMAND='${encodeURIComponent(query.command)}'&OBJ_DATA='YES'` +
|
||||
`${HORIZONS_URL}?format=text&COMMAND='${query.command}'&OBJ_DATA='YES'` +
|
||||
`&MAKE_EPHEM='YES'&EPHEM_TYPE='ELEMENTS'&CENTER='${query.center}'` +
|
||||
`&START_TIME='${REFERENCE_START}'&STOP_TIME='${REFERENCE_STOP}'&STEP_SIZE='1d'`;
|
||||
|
||||
const text = await fetchTextCached(url, query.cacheKey);
|
||||
return {
|
||||
radiusKm: extractRadiusKm(text),
|
||||
orbit: extractOrbitalElements(text),
|
||||
rotationPeriodHours: extractRotationPeriodHours(text),
|
||||
obliquityDeg: extractObliquityDeg(text),
|
||||
tidallyLocked: isTidallyLocked(text),
|
||||
gmKm3PerS2: extractGmKm3PerS2(text)
|
||||
orbit: extractOrbitalElements(text)
|
||||
};
|
||||
}
|
||||
|
||||
function extractRadiusKm(text: string): number | undefined {
|
||||
for (const pattern of RADIUS_PATTERNS) {
|
||||
const match = text.match(pattern);
|
||||
if (match) {
|
||||
return Number(match[1]);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function extractOrbitalElements(text: string): OrbitalElements {
|
||||
const startIndex = text.indexOf('$$SOE');
|
||||
const endIndex = text.indexOf('$$EOE');
|
||||
@@ -93,40 +94,3 @@ function extractNumber(text: string, pattern: RegExp): number {
|
||||
}
|
||||
return Number(match[1]);
|
||||
}
|
||||
|
||||
/** The span a moon's or dwarf planet's mean elements are checked against Horizons over, and the card names. */
|
||||
export const TRACK_START_YEAR = 1950;
|
||||
export const TRACK_STOP_YEAR = 2100;
|
||||
|
||||
/** One Horizons position: TDB Julian date, and ICRF equatorial coordinates in AU from the centre. */
|
||||
export interface TrackPoint {
|
||||
jd: number;
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where Horizons has a body, from its centre, every `stepDays` from 1950 to 2100: the ephemeris the
|
||||
* mean elements are checked against over the whole span, where one date saw a moon at its best.
|
||||
*/
|
||||
export async function fetchHorizonsTrack(command: string, center: string, stepDays: number, cacheKey: string): Promise<TrackPoint[]> {
|
||||
const url =
|
||||
`${HORIZONS_URL}?format=text&COMMAND='${encodeURIComponent(command)}'&OBJ_DATA='NO'&MAKE_EPHEM='YES'` +
|
||||
`&EPHEM_TYPE='VECTORS'&CENTER='${center}'&START_TIME='${TRACK_START_YEAR}-01-01'&STOP_TIME='${TRACK_STOP_YEAR}-01-01'` +
|
||||
`&STEP_SIZE='${stepDays}%20d'&REF_PLANE='FRAME'&REF_SYSTEM='ICRF'&VEC_TABLE='1'&OUT_UNITS='AU-D'&CSV_FORMAT='YES'&VEC_CORR='NONE'`;
|
||||
const text = await fetchTextCached(url, cacheKey);
|
||||
const startIndex = text.indexOf('$$SOE');
|
||||
const endIndex = text.indexOf('$$EOE');
|
||||
if (startIndex === -1 || endIndex === -1) {
|
||||
throw new Error(`Horizons gave no vectors for ${command} from ${center}: ${text.slice(0, 300)}`);
|
||||
}
|
||||
return text
|
||||
.slice(startIndex + '$$SOE'.length, endIndex)
|
||||
.trim()
|
||||
.split(/\r?\n/)
|
||||
.map((row) => {
|
||||
const [jd, , x, y, z] = row.split(',').map((field) => field.trim());
|
||||
return { jd: Number(jd), x: Number(x), y: Number(y), z: Number(z) };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
import { eclipticToEquatorial, laplacePlaneToEquatorial } from '../../../src/app/shared/astro/coordinates';
|
||||
import { meanElementsAt, positionAtEpoch } from '../../../src/app/shared/astro/kepler';
|
||||
import { MeanOrbit } from '../../../src/app/shared/astro/mean-elements';
|
||||
import { orientationAt } from '../../../src/app/shared/astro/rotational-elements';
|
||||
import { BodyRecord, RotationalElements } from '../../../src/app/shared/models/body.model';
|
||||
|
||||
const J2000_JD = 2451545;
|
||||
const DAYS_PER_JULIAN_CENTURY = 36525;
|
||||
const DEG_TO_RAD = Math.PI / 180;
|
||||
|
||||
/** 2025-01-01, the date the ETL asks Horizons about: where a locked moon's W is left as the IAU has it. */
|
||||
export const PRESENT_JD = 2460676.5;
|
||||
|
||||
/**
|
||||
* How far the IAU's W rate for a locked moon may be from the mean motion its orbit is drawn at, as
|
||||
* a fraction of it, before it is taken for the orbit's. Measured: at most 3.4e-6 (Iapetus; Proteus
|
||||
* 6.3e-7). What this catches is a rate read for the wrong body: Oberon's for Titania's is 55 per cent out.
|
||||
*/
|
||||
const MAX_LOCKED_RATE_OFFSET = 1e-5;
|
||||
|
||||
/** Harmonics of the node's angle that carry a pole round its orbit's; see {@link lockedToOrbit}. */
|
||||
const POLE_HARMONICS = 5;
|
||||
|
||||
/**
|
||||
* How far a periodic term's angle may turn from a multiple of the node's rate, as a fraction of it,
|
||||
* and still be taken for the node's angle as the IAU's source had it. Measured: at most 3.1e-2
|
||||
* (Callisto's J6), then Rhea's R4 1.2e-2 and Ganymede's J5 3.3e-3; the nearest that is not a node is
|
||||
* a term of Miranda's W alone, 6.0e-2 from three times it. Multiples go up to the ninth, the most the
|
||||
* report takes (Triton's N7); past that, Umbriel's W has a term 1.0e-2 from ten times its node's.
|
||||
*/
|
||||
const MAX_NODE_RATE_OFFSET = 0.05;
|
||||
const MAX_NODE_HARMONIC = 9;
|
||||
|
||||
/** How far, in degrees, re-rating may move a locked moon's pole or W at {@link PRESENT_JD}; see {@link lockedToOrbit}. */
|
||||
const MAX_PRESENT_OFFSET_DEG = 1e-6;
|
||||
|
||||
/** The planet's east longitude on a moon's IAU body-fixed frame, from the moon's mean place, at a TDB date. */
|
||||
export function subPlanetLongitudeDeg(body: Pick<BodyRecord, 'orbit' | 'rates' | 'laplacePole'>, elements: RotationalElements, jd: number): number {
|
||||
const own = positionAtEpoch(meanElementsAt(body.orbit, body.rates, jd));
|
||||
const place = body.laplacePole ? laplacePlaneToEquatorial(own, body.laplacePole) : eclipticToEquatorial(own);
|
||||
const { poleRaDeg, poleDecDeg, primeMeridianDeg } = orientationAt(elements, jd);
|
||||
const pole = { raDeg: poleRaDeg, decDeg: poleDecDeg };
|
||||
const w = primeMeridianDeg * DEG_TO_RAD;
|
||||
const meridian = laplacePlaneToEquatorial({ x: Math.cos(w), y: Math.sin(w), z: 0 }, pole);
|
||||
const east = laplacePlaneToEquatorial({ x: -Math.sin(w), y: Math.cos(w), z: 0 }, pole);
|
||||
const along = (axis: { x: number; y: number; z: number }) => -(place.x * axis.x + place.y * axis.y + place.z * axis.z);
|
||||
return Math.atan2(along(east), along(meridian)) / DEG_TO_RAD;
|
||||
}
|
||||
|
||||
/**
|
||||
* A locked moon's IAU elements, turned at the rate its orbit is drawn at, so it keeps its face to
|
||||
* its planet over the clock's AD 1 to 3000 and not only near the present its W was fitted to.
|
||||
*
|
||||
* The report gives a locked moon's W the mean motion of whichever orbit its authors had, and JPL's
|
||||
* table has another: Proteus's W turns 6.3e-7 of its rate slower than its row, which turned its far
|
||||
* side to Neptune at AD 1 (146 degrees), Mimas's 1.6e-7 faster (52 at AD 1) and Miranda's (23).
|
||||
* W's rate is set to the orbit's here, its constant moved so W is unchanged at {@link PRESENT_JD}.
|
||||
* Measured over AD 1-3000: Proteus 2.7 degrees, Mimas 8.9, Miranda 2.4, Ariel 1.0. A W with a
|
||||
* quadratic is left: Phobos's orbit already takes the quadratic from W (see
|
||||
* `orbitalTermsOfPrimeMeridian`), and the Moon's, its tidal slowing, is 0.75 degrees at AD 1.
|
||||
*
|
||||
* The node's angle goes the same way. A moon in a Cassini state keeps its axis on its orbit normal,
|
||||
* which goes round the Laplace pole with the node, and the IAU's pole goes round with it on a term
|
||||
* of the node's angle, at the node's rate as its source had it, not quite JPL's current one the
|
||||
* orbit is drawn at (see `nodePeriodYears` in `fetchSolarSystem.ts`): Rhea's R4 turns 1.2 per cent
|
||||
* faster than its node, Callisto's J6 3.1 per cent, and Miranda's U11 0.013 per cent, which on a
|
||||
* 4.4-degree circle over twenty centuries still adds up. On the IAU's rates the axes part from the
|
||||
* drawn orbits by AD 1 or 3000: Rhea's by 0.77 degrees, Miranda's 0.59, Triton's 0.51, Europa's and
|
||||
* Callisto's 0.33. Every term whose angle turns within {@link MAX_NODE_RATE_OFFSET} of a multiple of
|
||||
* the node's rate is set to that multiple, its constant moved so the angle is unchanged at the
|
||||
* present, and the pole with it: over AD 1-3000 the axes of Io, Europa, Ganymede, Callisto, Rhea,
|
||||
* Miranda and Triton stay within 0.23 degrees of their orbit normals, and Mimas's, whose drawn node
|
||||
* takes the IAU's S3 itself, within 0.44. The rest of the pole and its terms are the IAU's, and so
|
||||
* are all of the Moon's and Phobos's, left whole with their W: Ariel's, Umbriel's, Titania's and
|
||||
* Oberon's poles go round on angles of their own at none of their nodes' multiples (Oberon's, the
|
||||
* nearest, 8.7 per cent from three times its node's rate), and their axes stay within 0.50 degrees
|
||||
* of their orbit normals without.
|
||||
*
|
||||
* `poleFollowsOrbit` is for Iapetus, whose IAU pole moves 3.9 degrees a century in right ascension
|
||||
* and 1.1 in declination: a straight line through its orbit normal's 3 439-year circle round the
|
||||
* Laplace pole, 8.3 degrees in radius (16.6 across), which by AD 1 has run past the celestial pole (Dec 97.9) and 11
|
||||
* degrees off the orbit, and turned its face 87 degrees from Saturn. Its axis sits on its orbit normal
|
||||
* (0.04 degrees apart today), as a moon in a Cassini state keeps it, so its pole is given the circle: the
|
||||
* normal's right ascension as sines and declination as cosines of the node's angle and its first
|
||||
* {@link POLE_HARMONICS} harmonics, the IAU's own form for a precessing pole, with its constants
|
||||
* set so the pole is the IAU's at the present. W counts from where the equator crosses the ICRF
|
||||
* equator, which swings as the pole goes round, so W takes sines of the same angles, fitted to hold
|
||||
* the face where it is today. Measured over AD 1-3000: the axis within 0.74 degrees of the orbit
|
||||
* normal (the IAU's line, 11.06), and the face within 16 of Saturn (87), which is what the row's own
|
||||
* 9.4-degree lag and its eccentricity make it from 1950 to 2100 as well (15.9).
|
||||
*/
|
||||
export function lockedToOrbit(elements: RotationalElements, mean: Pick<MeanOrbit, 'orbit' | 'rates' | 'laplacePole'>, name: string, poleFollowsOrbit = false): RotationalElements {
|
||||
const [w0, w1, w2 = 0] = elements.primeMeridianDeg;
|
||||
if (w2 !== 0) {
|
||||
return elements;
|
||||
}
|
||||
const n = Math.sign(w1) * mean.rates.meanMotionDegPerDay;
|
||||
if (Math.abs(w1 / n - 1) > MAX_LOCKED_RATE_OFFSET) {
|
||||
throw new Error(`${name}'s IAU W turns at ${w1} degrees a day, ${Math.abs(w1 / n - 1).toExponential(2)} of its orbit's ${n}: not the rate of the orbit it keeps its face to.`);
|
||||
}
|
||||
const nodeRate = mean.rates.longitudeOfAscendingNodeDegPerDay * DAYS_PER_JULIAN_CENTURY;
|
||||
const present = (PRESENT_JD - J2000_JD) / DAYS_PER_JULIAN_CENTURY;
|
||||
const terms = elements.terms?.map((term) => {
|
||||
const [constant, rate, quadratic = 0] = term.angleDeg;
|
||||
const k = Math.round(rate / nodeRate);
|
||||
if (quadratic !== 0 || k === 0 || Math.abs(k) > MAX_NODE_HARMONIC || Math.abs(rate / (k * nodeRate) - 1) > MAX_NODE_RATE_OFFSET) {
|
||||
return term;
|
||||
}
|
||||
return { ...term, angleDeg: [constant + (rate - k * nodeRate) * present, k * nodeRate] };
|
||||
});
|
||||
const locked: RotationalElements = { ...elements, primeMeridianDeg: [w0 + (w1 - n) * (PRESENT_JD - J2000_JD), n, 0], ...(terms ? { terms } : {}) };
|
||||
const turned = poleFollowsOrbit ? poleRoundOrbit(locked, mean) : locked;
|
||||
// Whatever is re-rated, the pole and W at the present are the kernel's, which is what they were
|
||||
// fitted to. Measured: at most 4.7e-10 degrees (Deimos's W, some 2.6 million degrees round).
|
||||
const [iau, own] = [elements, turned].map((each) => orientationAt(each, PRESENT_JD));
|
||||
const moved = Math.max(...(['poleRaDeg', 'poleDecDeg', 'primeMeridianDeg'] as const).map((key) => Math.abs(own[key] - iau[key])));
|
||||
if (moved > MAX_PRESENT_OFFSET_DEG) {
|
||||
throw new Error(`${name}'s pole or W on ${PRESENT_JD} is ${moved.toExponential(2)} degrees from the IAU's: re-rated, it should be where the kernel has it today.`);
|
||||
}
|
||||
return turned;
|
||||
}
|
||||
|
||||
function poleRoundOrbit(elements: RotationalElements, mean: Pick<MeanOrbit, 'orbit' | 'rates' | 'laplacePole'>): RotationalElements {
|
||||
if (!mean.laplacePole) {
|
||||
throw new Error('A pole that follows its orbit is carried round the orbit\'s Laplace pole, and this orbit has none.');
|
||||
}
|
||||
const laplacePole = mean.laplacePole;
|
||||
const normalAt = (jd: number) => {
|
||||
const { inclinationDeg, longitudeOfAscendingNodeDeg } = meanElementsAt(mean.orbit, mean.rates, jd);
|
||||
const tilt = inclinationDeg * DEG_TO_RAD;
|
||||
const node = longitudeOfAscendingNodeDeg * DEG_TO_RAD;
|
||||
const normal = laplacePlaneToEquatorial({ x: Math.sin(tilt) * Math.sin(node), y: -Math.sin(tilt) * Math.cos(node), z: Math.cos(tilt) }, laplacePole);
|
||||
return { raDeg: Math.atan2(normal.y, normal.x) / DEG_TO_RAD, decDeg: Math.asin(normal.z) / DEG_TO_RAD };
|
||||
};
|
||||
// The node's angle, T in centuries, turned so that 0 is where the normal is furthest north: the
|
||||
// circle is then even in declination and odd in right ascension about it, as the form requires.
|
||||
const nodeRate = mean.rates.longitudeOfAscendingNodeDegPerDay * DAYS_PER_JULIAN_CENTURY;
|
||||
const nodeAtJ2000 = meanElementsAt(mean.orbit, mean.rates, J2000_JD).longitudeOfAscendingNodeDeg;
|
||||
const jdAtAngle = (angleDeg: number, phaseDeg: number) => J2000_JD + ((angleDeg - phaseDeg - nodeAtJ2000) / nodeRate) * DAYS_PER_JULIAN_CENTURY;
|
||||
let phase = 0;
|
||||
let northmost = -Infinity;
|
||||
for (let candidate = 0; candidate < 360; candidate += 0.01) {
|
||||
const dec = normalAt(jdAtAngle(0, candidate)).decDeg;
|
||||
if (dec > northmost) {
|
||||
northmost = dec;
|
||||
phase = candidate;
|
||||
}
|
||||
}
|
||||
const centre = laplacePole;
|
||||
const samples = 3600;
|
||||
const ra = new Array<number>(POLE_HARMONICS + 1).fill(0);
|
||||
const dec = new Array<number>(POLE_HARMONICS + 1).fill(0);
|
||||
for (let sample = 0; sample < samples; sample++) {
|
||||
const angle = (sample / samples) * 360;
|
||||
const normal = normalAt(jdAtAngle(angle, phase));
|
||||
const raOffset = ((((normal.raDeg - centre.raDeg) % 360) + 540) % 360) - 180;
|
||||
for (let k = 0; k <= POLE_HARMONICS; k++) {
|
||||
ra[k] += (2 / samples) * raOffset * Math.sin(k * angle * DEG_TO_RAD);
|
||||
dec[k] += ((k === 0 ? 1 : 2) / samples) * (normal.decDeg - centre.decDeg) * Math.cos(k * angle * DEG_TO_RAD);
|
||||
}
|
||||
}
|
||||
const terms = Array.from({ length: POLE_HARMONICS }, (_, index) => {
|
||||
const k = index + 1;
|
||||
return { angleDeg: [k * (nodeAtJ2000 + phase), k * nodeRate], ra: ra[k], dec: dec[k], pm: 0 };
|
||||
});
|
||||
const round: RotationalElements = { ...elements, poleRaDeg: [centre.raDeg, 0, 0], poleDecDeg: [centre.decDeg + dec[0], 0, 0], terms: [...(elements.terms ?? []), ...terms] };
|
||||
// The IAU's pole at the present, exactly: the fitted circle's constants moved onto it.
|
||||
const iau = orientationAt(elements, PRESENT_JD);
|
||||
const fitted = orientationAt(round, PRESENT_JD);
|
||||
round.poleRaDeg = [round.poleRaDeg[0] + iau.poleRaDeg - fitted.poleRaDeg, 0, 0];
|
||||
round.poleDecDeg = [round.poleDecDeg[0] + iau.poleDecDeg - fitted.poleDecDeg, 0, 0];
|
||||
// W's sines on the same angles, fitted over a turn of the node to what the face drifts by.
|
||||
const pm = new Array<number>(POLE_HARMONICS + 1).fill(0);
|
||||
const wSamples = 36000;
|
||||
for (let sample = 0; sample < wSamples; sample++) {
|
||||
const angle = (sample / wSamples) * 360;
|
||||
const drift = subPlanetLongitudeDeg(mean, round, jdAtAngle(angle, phase));
|
||||
for (let k = 1; k <= POLE_HARMONICS; k++) {
|
||||
pm[k] += (2 / wSamples) * drift * Math.sin(k * angle * DEG_TO_RAD);
|
||||
}
|
||||
}
|
||||
const ownTerms = elements.terms?.length ?? 0;
|
||||
const turned: RotationalElements = { ...round, terms: round.terms!.map((term, index) => (index < ownTerms ? term : { ...term, pm: pm[index - ownTerms + 1] })) };
|
||||
// And W the IAU's at the present.
|
||||
const shift = orientationAt(turned, PRESENT_JD).primeMeridianDeg - orientationAt(elements, PRESENT_JD).primeMeridianDeg;
|
||||
turned.primeMeridianDeg = [turned.primeMeridianDeg[0] - shift, turned.primeMeridianDeg[1], 0];
|
||||
return turned;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { SbdbAnswer } from '../../../src/app/shared/astro/mean-elements';
|
||||
import { fetchJsonCached, fetchTextCached } from './http';
|
||||
|
||||
/**
|
||||
* Standish's "Keplerian Elements for Approximate Positions of the Major Planets", Table 2a/2b:
|
||||
* elements against the J2000 ecliptic and their rates per century, fit to the JPL ephemeris for
|
||||
* 3000 BC to AD 3000. Table 1 is closer near the present — Saturn within 0.23 degrees of Horizons
|
||||
* from 1950 to 2100 against this table's 0.32 — but it is only fit for 1800-2050, which the clock
|
||||
* leaves in minutes, and by AD 3000 it has Saturn 4.3 degrees out where this one is within 0.3
|
||||
* of every planet. The page at ssd.jpl.nasa.gov/planets/approx_pos.html carries the same numbers but has
|
||||
* dropped Pluto, so this reads the plain-text file as JPL last published it, from the Internet
|
||||
* Archive's copy — pinned to one capture, so the numbers cannot move under the cache.
|
||||
*/
|
||||
const PLANET_ELEMENTS_URL = 'https://web.archive.org/web/20210420020242id_/https://ssd.jpl.nasa.gov/txt/p_elem_t2.txt';
|
||||
|
||||
/**
|
||||
* JPL SSD's planetary satellite mean elements, as the page stood until 2021: each moon's elements,
|
||||
* its sidereal mean motion to ten figures, and how fast its node and periapsis turn, against its
|
||||
* local Laplace plane (the Moon against the ecliptic). The current page, ssd.jpl.nasa.gov/sats/elem,
|
||||
* has dropped the mean motion and rounds the period to four or five figures — 0.3187 days for
|
||||
* Phobos, which is a revolution out within a decade — so a period from it would not hold. Pinned
|
||||
* to one Internet Archive capture for the same reason as the planets.
|
||||
*/
|
||||
const SATELLITE_ELEMENTS_URL = 'https://web.archive.org/web/20210203000649id_/https://ssd.jpl.nasa.gov/?sat_elem';
|
||||
|
||||
export async function fetchPlanetMeanElementsText(): Promise<string> {
|
||||
return fetchTextCached(PLANET_ELEMENTS_URL, 'jpl-planet-mean-elements-t2.txt');
|
||||
}
|
||||
|
||||
export async function fetchSatelliteMeanElementsHtml(): Promise<string> {
|
||||
return fetchTextCached(SATELLITE_ELEMENTS_URL, 'jpl-satellite-mean-elements.html');
|
||||
}
|
||||
|
||||
/**
|
||||
* A small body's answer from JPL's Small-Body Database: osculating elements to full precision
|
||||
* (without `full-prec` they come rounded to three figures: Ceres's n as 0.214 degrees a day for
|
||||
* 0.2143045, which is 1.1 degrees out within a decade) and its physical parameters.
|
||||
*/
|
||||
export async function fetchSmallBodyAnswer(designation: string, cacheKey: string): Promise<SbdbAnswer> {
|
||||
return fetchJsonCached<SbdbAnswer>(`https://ssd-api.jpl.nasa.gov/sbdb.api?sstr=${encodeURIComponent(designation)}&phys-par=1&full-prec=1`, cacheKey);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { fetchTextCached } from './http';
|
||||
|
||||
/**
|
||||
* NAIF's generic text PCK, which carries the IAU WGCCRE 2015 report's rotational elements
|
||||
* (Archinal et al. 2018, Celest Mech Dyn Astr 130:22) for every body here that has them, periodic
|
||||
* terms included, in a form a program can read rather than a table typeset in a paper. A released
|
||||
* kernel is never edited, only superseded under a new name, so the URL pins the numbers.
|
||||
*/
|
||||
const PCK_URL = 'https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/pck00011.tpc';
|
||||
|
||||
export async function fetchPckText(): Promise<string> {
|
||||
return fetchTextCached(PCK_URL, 'naif-pck00011.tpc');
|
||||
}
|
||||
@@ -1,24 +1,9 @@
|
||||
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||
/* Compiler and Angular options come from @avalon-vanguard/config (tsconfig/angular.json). */
|
||||
{
|
||||
"extends": "@avalon-vanguard/config/tsconfig/angular.json",
|
||||
"compileOnSave": false,
|
||||
"compilerOptions": {
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"experimentalDecorators": true,
|
||||
"importHelpers": true,
|
||||
"target": "ES2022",
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true
|
||||
},
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
|
||||