astraeus 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +31 -8
  3. package/data/moons/jupiter.json +351 -115
  4. package/data/moons/neptune.json +54 -16
  5. package/data/moons/pluto.json +21 -5
  6. package/data/moons/saturn.json +882 -292
  7. package/data/moons/uranus.json +90 -28
  8. package/package.json +1 -1
  9. package/src/api/AstraeusScene.d.ts +4 -2
  10. package/src/api/AstraeusScene.js +13 -10
  11. package/src/api/AstraeusScene.node.js +13 -10
  12. package/src/api/bodies.d.ts +6 -1
  13. package/src/api/bodies.js +15 -2
  14. package/src/api/data.d.ts +2 -1
  15. package/src/api/data.js +4 -13
  16. package/src/api/errors.d.ts +1 -1
  17. package/src/api/index.d.ts +2 -1
  18. package/src/api/index.js +1 -1
  19. package/src/api/index.node.js +1 -1
  20. package/src/api/mount.d.ts +5 -1
  21. package/src/api/mount.js +2 -0
  22. package/src/api/mount.node.js +2 -0
  23. package/src/api/pathProvenance.d.ts +15 -6
  24. package/src/api/pathProvenance.js +23 -11
  25. package/src/api/scene.d.ts +18 -1
  26. package/src/api/scene.js +110 -15
  27. package/src/api/sphereOfInfluence.d.ts +20 -0
  28. package/src/api/sphereOfInfluence.js +48 -0
  29. package/src/api/viewerLink.d.ts +7 -1
  30. package/src/api/viewerLink.js +13 -2
  31. package/src/api/views.d.ts +42 -0
  32. package/src/api/views.js +80 -0
  33. package/src/app/App.js +32 -5
  34. package/src/app/App.node.js +32 -5
  35. package/src/app/AstraeusScene.d.ts +3 -0
  36. package/src/app/CameraController.d.ts +6 -0
  37. package/src/app/CameraController.js +3 -1
  38. package/src/app/PathView.d.ts +3 -2
  39. package/src/app/PathView.js +5 -5
  40. package/src/app/StoryMarkers.d.ts +4 -1
  41. package/src/app/StoryMarkers.js +3 -2
  42. package/src/app/TrackedBodyView.d.ts +1 -1
  43. package/src/app/TrackedBodyView.js +20 -11
  44. package/src/app/experienceDefinition.d.ts +3 -0
  45. package/src/app/mission.d.ts +15 -2
  46. package/src/app/mission.js +15 -0
  47. package/src/app/sceneCamera.d.ts +2 -0
  48. package/src/app/sceneCamera.js +14 -0
  49. package/src/app/sceneFrame.d.ts +2 -0
  50. package/src/app/sceneFrame.js +42 -6
  51. package/src/app/sceneHooks.js +1 -1
  52. package/src/app/viewHiding.d.ts +13 -0
  53. package/src/app/viewHiding.js +37 -0
  54. package/src/app/viewerPort.d.ts +6 -0
  55. package/src/app/views.d.ts +31 -0
  56. package/src/app/views.js +2 -0
  57. package/src/assets/bodies/listedMoons.d.ts +4 -0
  58. package/src/assets/bodies/listedMoons.js +7 -0
  59. package/src/assets/catalogue.d.ts +3 -0
  60. package/src/assets/catalogue.js +8 -0
  61. package/src/assets/moonCatalogue.d.ts +3 -1
  62. package/src/assets/moonCatalogue.js +1 -0
  63. package/src/core/bodies/jupiterMoons.d.ts +1 -1
  64. package/src/core/bodies/listedMoonBodies.d.ts +18 -0
  65. package/src/core/bodies/listedMoonBodies.js +36 -0
  66. package/src/core/bodies/listedMoons.d.ts +18 -0
  67. package/src/core/bodies/listedMoons.js +483 -0
  68. package/src/core/bodies/moonSystem.d.ts +3 -2
  69. package/src/core/bodies/moonSystem.js +1 -1
  70. package/src/shell/AstraeusShell.d.ts +12 -2
  71. package/src/shell/AstraeusShell.js +42 -4
  72. package/src/shell/AstraeusShell.node.js +42 -4
  73. package/src/shell/DisplaySwitches.d.ts +18 -1
  74. package/src/shell/DisplaySwitches.js +18 -5
  75. package/src/shell/TimelineBar.css +18 -0
  76. package/src/shell/TimelineBar.js +29 -4
  77. package/src/shell/TimelineBar.node.js +29 -4
  78. package/src/shell/TopBar.d.ts +4 -2
  79. package/src/shell/TopBar.js +3 -3
  80. package/src/shell/TopBar.node.js +3 -3
  81. package/src/shell/timelineModel.d.ts +13 -0
  82. package/src/shell/timelineModel.js +25 -0
  83. package/src/shell/viewCamera.d.ts +4 -0
  84. package/src/shell/viewCamera.js +13 -0
  85. package/src/synthetic/syntheticJourneyScene.d.ts +2 -1
  86. package/src/synthetic/syntheticJourneyScene.js +29 -14
  87. package/src/synthetic/syntheticViewsDefinition.d.ts +6 -0
  88. package/src/synthetic/syntheticViewsDefinition.js +44 -0
package/src/api/data.js CHANGED
@@ -1,29 +1,20 @@
1
- import { JUPITER_MOON_SYSTEM } from "../core/bodies/jupiterMoons.js";
2
- import { MARS_MOON_SYSTEM, NEPTUNE_MOON_SYSTEM, PLUTO_MOON_SYSTEM, SATURN_MOON_SYSTEM, URANUS_MOON_SYSTEM } from "../core/bodies/planetMoons.js";
1
+ import { MOON_SYSTEMS } from "../core/bodies/listedMoonBodies.js";
3
2
  import { MoonOutOfSpanError } from "../core/bodies/moonSystem.js";
4
- import { catalogue } from "../assets/catalogue.js";
3
+ import { catalogue as builtInCatalogue } from "../assets/catalogue.js";
5
4
  import { SceneError } from "./errors.js";
6
5
  import { registerPictures } from "../assets/pictures.js";
7
- const SYSTEMS = {
8
- jupiter: JUPITER_MOON_SYSTEM,
9
- saturn: SATURN_MOON_SYSTEM,
10
- uranus: URANUS_MOON_SYSTEM,
11
- neptune: NEPTUNE_MOON_SYSTEM,
12
- mars: MARS_MOON_SYSTEM,
13
- pluto: PLUTO_MOON_SYSTEM,
14
- };
15
6
  /**
16
7
  * Hands the packages' pictures and moon positions to the engine and loads the chunks the scene's window needs for the moons it holds.
17
8
  * Nothing is looked up behind the caller's back: a package that was not passed in contributes nothing.
18
9
  */
19
- export async function installData(data, sceneBodies, window) {
10
+ export async function installData(data, sceneBodies, window, catalogue = builtInCatalogue) {
20
11
  for (const source of data) {
21
12
  if (source.pictures !== undefined)
22
13
  registerPictures(source.pictures);
23
14
  const positions = source.moonPositions;
24
15
  if (positions === undefined)
25
16
  continue;
26
- const system = SYSTEMS[positions.centre];
17
+ const system = MOON_SYSTEMS[positions.centre];
27
18
  if (system === undefined)
28
19
  throw new RangeError(`${source.name}: no moon system for "${positions.centre}"`);
29
20
  system.provideIndex(positions.loadIndex);
@@ -1,5 +1,5 @@
1
1
  /** Why a scene call was refused; `code` is stable so a caller can branch on it. */
2
- export type SceneErrorCode = "unknown-body" | "duplicate-id" | "bad-time" | "bad-trajectory" | "bad-scale" | "missing-data" | "out-of-span" | "empty-scene" | "bad-element" | "no-orbit" | "bad-anchor" | "bad-readout" | "bad-event" | "bad-panels" | "bad-timeline" | "bad-switch" | "bad-body" | "bad-group" | "bad-activity" | "bad-camera";
2
+ export type SceneErrorCode = "unknown-body" | "duplicate-id" | "bad-time" | "bad-trajectory" | "bad-scale" | "missing-data" | "out-of-span" | "empty-scene" | "bad-element" | "no-orbit" | "bad-anchor" | "bad-readout" | "bad-event" | "bad-panels" | "bad-timeline" | "bad-switch" | "bad-body" | "bad-group" | "bad-activity" | "bad-camera" | "bad-view";
3
3
  /** The one error the public API throws for bad input; the message names the offending value. */
4
4
  export declare class SceneError extends RangeError {
5
5
  readonly code: SceneErrorCode;
@@ -1,11 +1,12 @@
1
1
  export { Scene, SceneCamera, type AddBodyOptions, type AnchorInput, type ReadoutInput, type DataSource, type MoonPositions, type FollowView, type GroupInput, type GroupOrbitInput, type GroupClumpInput, type GroupReadoutInput, type ActivityInput, type ActivitySampleInput, type ActivitySourceInput, type ElementsBodyRecord, type TimeInput, type TrajectoryInput, type TrajectorySampleInput } from "./scene.js";
2
2
  export { type EventInput, type AddEventsOptions, type TimelineInput, type PacingInput, type StoryPanelsInput } from "./story.js";
3
3
  export { type SwitchesInput } from "./switches.js";
4
+ export { type ViewsOptions, type ViewInput, type ViewCameraInput } from "./views.js";
4
5
  export { mount, type MountOptions, type MountedScene } from "./mount.js";
5
6
  export { AstraeusScene, type AstraeusSceneProps } from "./AstraeusScene.js";
6
7
  export { type ViewerChange, type RateSource } from "./viewerLink.js";
7
8
  export { SceneError, type SceneErrorCode } from "./errors.js";
8
- export { sun, mercury, venus, earth, moon, mars, jupiter, saturn, uranus, neptune, pluto, io, europa, ganymede, callisto, mimas, enceladus, tethys, dione, rhea, titan, iapetus, triton, charon, phobos, deimos, type BodyRef } from "./bodies.js";
9
+ export { sun, mercury, venus, earth, moon, mars, jupiter, saturn, uranus, neptune, pluto, io, europa, ganymede, callisto, mimas, enceladus, tethys, dione, rhea, titan, iapetus, triton, charon, phobos, deimos, listedMoons, type BodyRef } from "./bodies.js";
9
10
  export { trueScale, readableScale, solarSystemScale, type ScalePolicy } from "../core/scalePolicy.js";
10
11
  export type { State } from "../core/state.js";
11
12
  export type { Provenance, ProvenanceSourceType } from "../core/provenance.js";
package/src/api/index.js CHANGED
@@ -3,6 +3,6 @@ export { Scene, SceneCamera } from "./scene.js";
3
3
  export { mount } from "./mount.js";
4
4
  export { AstraeusScene } from "./AstraeusScene.js";
5
5
  export { SceneError } from "./errors.js";
6
- export { sun, mercury, venus, earth, moon, mars, jupiter, saturn, uranus, neptune, pluto, io, europa, ganymede, callisto, mimas, enceladus, tethys, dione, rhea, titan, iapetus, triton, charon, phobos, deimos } from "./bodies.js";
6
+ export { sun, mercury, venus, earth, moon, mars, jupiter, saturn, uranus, neptune, pluto, io, europa, ganymede, callisto, mimas, enceladus, tethys, dione, rhea, titan, iapetus, triton, charon, phobos, deimos, listedMoons } from "./bodies.js";
7
7
  export { trueScale, readableScale, solarSystemScale } from "../core/scalePolicy.js";
8
8
  export { APPROXIMATE_LIMIT_FRACTION, INDICATIVE_LIMIT_FRACTION, classifyPositionError, parseElementsBodyRecord } from "../core/elementsBody.js";
@@ -3,6 +3,6 @@ export { Scene, SceneCamera } from "./scene.js";
3
3
  export { mount } from "./mount.node.js";
4
4
  export { AstraeusScene } from "./AstraeusScene.node.js";
5
5
  export { SceneError } from "./errors.js";
6
- export { sun, mercury, venus, earth, moon, mars, jupiter, saturn, uranus, neptune, pluto, io, europa, ganymede, callisto, mimas, enceladus, tethys, dione, rhea, titan, iapetus, triton, charon, phobos, deimos } from "./bodies.js";
6
+ export { sun, mercury, venus, earth, moon, mars, jupiter, saturn, uranus, neptune, pluto, io, europa, ganymede, callisto, mimas, enceladus, tethys, dione, rhea, titan, iapetus, triton, charon, phobos, deimos, listedMoons } from "./bodies.js";
7
7
  export { trueScale, readableScale, solarSystemScale } from "../core/scalePolicy.js";
8
8
  export { APPROXIMATE_LIMIT_FRACTION, INDICATIVE_LIMIT_FRACTION, classifyPositionError, parseElementsBodyRecord } from "../core/elementsBody.js";
@@ -6,7 +6,7 @@ import { type ViewerChange } from "./viewerLink.js";
6
6
  export interface MountOptions {
7
7
  /** Data packages the scene's bodies need, such as moon pictures or positions; nothing is looked up behind the caller's back. */
8
8
  readonly data?: readonly DataSource[];
9
- /** Called whenever the viewer's time, speed or playing state changes: playback running, a visitor using the timeline, or the host's own `setTime` / `setRate`. About ten times a second while playing. */
9
+ /** Called whenever the viewer's time, speed or playing state changes: playback running, a visitor using the timeline, or the host's own `setTime` / `setRate` / `setView`. About ten times a second while playing. */
10
10
  readonly onChange?: (change: ViewerChange) => void;
11
11
  }
12
12
  /** What `mount` returns. */
@@ -19,10 +19,14 @@ export interface MountedScene {
19
19
  readonly time: number | undefined;
20
20
  /** The playback speed (simulated seconds per real second); undefined like `time`. */
21
21
  readonly rate: number | undefined;
22
+ /** The id of the view showing; undefined until `ready` has resolved, after `unmount`, and in a scene without views. */
23
+ readonly view: string | undefined;
22
24
  /** Moves the viewer to `time` (ISO text, a `Date` or Unix milliseconds). Outside the timeline throws `bad-time`; before `ready` or after `unmount` throws `missing-data`. */
23
25
  setTime(time: TimeInput): void;
24
26
  /** Sets the playback speed to one of the speeds the timeline offers (`setTimeline({ rates })`); any other number throws `bad-timeline`. `"auto"` gives the speed back to the scene's `setTimeline({ pacing })` (throws `bad-timeline` when it has none). Before `ready` or after `unmount` throws `missing-data`. */
25
27
  setRate(rate: number | "auto"): void;
28
+ /** Switches to the view with this id (`setViews`). An unknown id, or a scene without views, throws `bad-view`; before `ready` or after `unmount` throws `missing-data`. `onChange` hears it with `cause: "host"`. */
29
+ setView(id: string): void;
26
30
  /** Calls `listener` on every change (see `MountOptions.onChange`); returns the function that stops it. No callbacks arrive after `unmount`. */
27
31
  onChange(listener: (change: ViewerChange) => void): () => void;
28
32
  }
package/src/api/mount.js CHANGED
@@ -35,6 +35,8 @@ export function mount(element, scene, options = {}) {
35
35
  ready,
36
36
  get time() { return link.time; },
37
37
  get rate() { return link.rate; },
38
+ get view() { return link.view; },
39
+ setView: (id) => link.setView(id),
38
40
  setTime: (time) => link.setTime(time),
39
41
  setRate: (rate) => link.setRate(rate),
40
42
  onChange: (listener) => link.onChange(listener),
@@ -34,6 +34,8 @@ export function mount(element, scene, options = {}) {
34
34
  ready,
35
35
  get time() { return link.time; },
36
36
  get rate() { return link.rate; },
37
+ get view() { return link.view; },
38
+ setView: (id) => link.setView(id),
37
39
  setTime: (time) => link.setTime(time),
38
40
  setRate: (rate) => link.setRate(rate),
39
41
  onChange: (listener) => link.onChange(listener),
@@ -1,10 +1,19 @@
1
1
  import type { WindowProvenanceSpan } from "../core/timeWindow.js";
2
2
  import type { ActivitySourceInput } from "./activity.js";
3
- /**
4
- * Checks a path's provenance by time span (the same `{ start, end, provenance }` shape as an activity's) and returns it in milliseconds.
5
- * Spans are sorted, do not overlap and lie inside the path's bounds; any fault is a `bad-trajectory` naming the path and the span's index.
6
- */
7
- export declare function planPathProvenance(id: string, spans: readonly ActivitySourceInput[], boundsUtcMs: {
3
+ import { type TimeInput } from "./time.js";
4
+ import type { LineStretch } from "../app/mission.js";
5
+ interface Bounds {
8
6
  readonly startUtcMs: number;
9
7
  readonly endUtcMs: number;
10
- }): readonly WindowProvenanceSpan[];
8
+ }
9
+ /** Checks a path's provenance by time span (the same `{ start, end, provenance }` shape as an activity's) and returns it in milliseconds. */
10
+ export declare function planPathProvenance(id: string, spans: readonly ActivitySourceInput[], boundsUtcMs: Bounds): readonly WindowProvenanceSpan[];
11
+ /** One stretch of a path's line and the body it is drawn against, as the caller gives it. */
12
+ export interface LineStretchInput {
13
+ readonly start: TimeInput;
14
+ readonly end: TimeInput;
15
+ readonly body: string;
16
+ }
17
+ /** Checks a path's `lineFixedTo` list (same span rules as `provenanceSpans`) and returns it in milliseconds. */
18
+ export declare function planLineStretches(id: string, stretches: readonly LineStretchInput[], boundsUtcMs: Bounds): readonly LineStretch[];
19
+ export {};
@@ -2,33 +2,45 @@ import { createProvenance } from "../core/provenance.js";
2
2
  import { SceneError } from "./errors.js";
3
3
  import { toUtcMs } from "./time.js";
4
4
  /**
5
- * Checks a path's provenance by time span (the same `{ start, end, provenance }` shape as an activity's) and returns it in milliseconds.
6
- * Spans are sorted, do not overlap and lie inside the path's bounds; any fault is a `bad-trajectory` naming the path and the span's index.
5
+ * The shared plan for a path's time-span lists (`provenanceSpans`, `lineFixedTo`): each span's `start` and `end` are read to milliseconds, `read` builds the item from the span,
6
+ * and the list must be sorted, not overlap and lie inside `bounds`. Any fault is a `bad-trajectory` naming the path, the field and the index.
7
7
  */
8
- export function planPathProvenance(id, spans, boundsUtcMs) {
9
- const bad = (index, message) => new SceneError("bad-trajectory", `addTrajectory("${id}"): provenanceSpans[${index}] ${message}`);
8
+ function planSpans(id, field, spans, bounds, read) {
9
+ const bad = (index, message) => new SceneError("bad-trajectory", `addTrajectory("${id}"): ${field}[${index}] ${message}`);
10
10
  if (!Array.isArray(spans))
11
- throw new SceneError("bad-trajectory", `addTrajectory("${id}"): provenanceSpans must be a list`);
11
+ throw new SceneError("bad-trajectory", `addTrajectory("${id}"): ${field} must be a list`);
12
12
  let previousEnd = -Infinity;
13
13
  return spans.map((span, index) => {
14
14
  let startUtcMs;
15
15
  let endUtcMs;
16
- let provenance;
16
+ let item;
17
17
  try {
18
- startUtcMs = toUtcMs(span?.start, `addTrajectory("${id}") provenanceSpans[${index}] start`);
19
- endUtcMs = toUtcMs(span?.end, `addTrajectory("${id}") provenanceSpans[${index}] end`);
20
- provenance = createProvenance(span?.provenance);
18
+ startUtcMs = toUtcMs(span?.start, `addTrajectory("${id}") ${field}[${index}] start`);
19
+ endUtcMs = toUtcMs(span?.end, `addTrajectory("${id}") ${field}[${index}] end`);
20
+ item = read(span);
21
21
  }
22
22
  catch (error) {
23
23
  throw bad(index, error instanceof Error ? error.message : String(error));
24
24
  }
25
25
  if (endUtcMs <= startUtcMs)
26
26
  throw bad(index, "must end after it starts");
27
- if (startUtcMs < boundsUtcMs.startUtcMs || endUtcMs > boundsUtcMs.endUtcMs)
27
+ if (startUtcMs < bounds.startUtcMs || endUtcMs > bounds.endUtcMs)
28
28
  throw bad(index, "lies outside the path");
29
29
  if (startUtcMs < previousEnd)
30
30
  throw bad(index, "overlaps or is out of order; spans must be sorted and not overlap");
31
31
  previousEnd = endUtcMs;
32
- return { startUtcMs, endUtcMs, provenance };
32
+ return { ...item, startUtcMs, endUtcMs };
33
+ });
34
+ }
35
+ /** Checks a path's provenance by time span (the same `{ start, end, provenance }` shape as an activity's) and returns it in milliseconds. */
36
+ export function planPathProvenance(id, spans, boundsUtcMs) {
37
+ return planSpans(id, "provenanceSpans", spans, boundsUtcMs, (span) => ({ provenance: createProvenance(span?.provenance) }));
38
+ }
39
+ /** Checks a path's `lineFixedTo` list (same span rules as `provenanceSpans`) and returns it in milliseconds. */
40
+ export function planLineStretches(id, stretches, boundsUtcMs) {
41
+ return planSpans(id, "lineFixedTo", stretches, boundsUtcMs, (stretch) => {
42
+ if (typeof stretch.body !== "string" || stretch.body === "")
43
+ throw new Error("body must be a body id");
44
+ return { body: stretch.body };
33
45
  });
34
46
  }
@@ -1,6 +1,7 @@
1
1
  import type { BodyId } from "../core/body.js";
2
2
  import { type Provenance } from "../core/provenance.js";
3
3
  import type { ActivitySourceInput } from "./activity.js";
4
+ import { type LineStretchInput } from "./pathProvenance.js";
4
5
  import { type ScalePolicy } from "../core/scalePolicy.js";
5
6
  import { type State } from "../core/state.js";
6
7
  import { type ElementsBodyRecord } from "../core/elementsBody.js";
@@ -14,6 +15,7 @@ export type { ActivityInput, ActivitySampleInput, ActivitySourceInput } from "./
14
15
  export type { DataSource, MoonPositions } from "./data.js";
15
16
  import { type TimeInput } from "./time.js";
16
17
  import { type SwitchesInput } from "./switches.js";
18
+ import { type ViewInput, type ViewsOptions } from "./views.js";
17
19
  import { type AddEventsOptions, type EventInput, type StoryPanelsInput, type TimelineInput } from "./story.js";
18
20
  export { toUtcMs, type TimeInput } from "./time.js";
19
21
  export type { ElementsBodyRecord } from "../core/elementsBody.js";
@@ -74,9 +76,14 @@ interface TrajectoryBase {
74
76
  /**
75
77
  * The body the path's line is drawn against: each sample is placed from this body at the sample's own time, then the line is carried to
76
78
  * this body's place from the scene centre at the clock time. Defaults to the scene centre; name the Sun for a probe crossing a Sun-centred scene.
79
+ * A list of `{ start, end, body }` (times as `provenanceSpans`) draws each stretch against its own body, so a flyby is one path: Sun-fixed cruise, planet-fixed encounter, Sun-fixed cruise.
80
+ * Sorted, not overlapping, inside the path's span; time outside every stretch is drawn against the scene centre. A fault throws `bad-trajectory` naming the index.
81
+ * `"auto"` builds that list from the path's own samples: each sample is fixed to the innermost body in the scene whose sphere of influence (`a (m / M)^(2/5)`, `a` the body's distance from its parent,
82
+ * GMs from the catalogue) holds the probe (a root body such as the Sun holds everything), else the scene centre; consecutive samples on one body merge. Resolved once when the planet series are in
83
+ * (at mount, or in `prepare`), never per frame. A body with no catalogue GM (most moons) is skipped. "auto" is reserved, so no body may carry that id.
77
84
  * Throws `bad-trajectory` at build if the scene does not hold the body.
78
85
  */
79
- readonly lineFixedTo?: BodyId;
86
+ readonly lineFixedTo?: BodyId | "auto" | readonly LineStretchInput[];
80
87
  /**
81
88
  * The frame the positions and velocities are given in, about `center`: "EQJ" (equatorial J2000, the default) or "ecliptic-j2000" (the vectors JPL Horizons
82
89
  * publishes by default). Ecliptic input is rotated to EQJ once, as it is read, so drawing, `stateOf` and readouts all see EQJ. Any other value throws `bad-trajectory`.
@@ -218,6 +225,16 @@ export declare class Scene {
218
225
  * scene.setSwitches({ orbitLines: { place: "top-bar" }, labels: { place: "panel", on: false }, milkyWay: { place: "developer", on: false } });
219
226
  */
220
227
  setSwitches(switches: SwitchesInput): this;
228
+ /**
229
+ * Names views of this one scene, each listing what it shows: `paths` (ids of `addTrajectory`), `bodies` (ids of `addBody` or `addGroup`), `events` (ids of `addEvents`) and `panels` (ids of `addStoryPanels`).
230
+ * Anything no view names shows in every view (shared bodies such as the planets); anything a view names shows only in the views that name it. `place` is `"top-bar"` or `"panel"` (as for `setSwitches`);
231
+ * `start` is the opening view (default the first). `camera` says what happens when the followed or focused object is not in the view switched to: `"stay"` (default), `"start"` (the scene's start) or
232
+ * `{ follow: id }` / `{ focus: id }` (that framing; the object must be in the view). Presentation only: State is unchanged and a hidden object keeps its state. May be called again; the later call replaces the views.
233
+ * An empty list, a repeated view id, a bad place or camera, or a `start` that is not a view throws `bad-view` here; an id the scene does not hold, or a camera target the view does not show, throws `bad-view` when the scene is built (`mount`), so the call may come before or after the objects.
234
+ * @example
235
+ * scene.setViews([{ id: "a", label: "Probe A", paths: ["probe-a"] }, { id: "b", label: "Probe B", paths: ["probe-b"] }, { id: "both", label: "Both" }], { place: "top-bar" });
236
+ */
237
+ setViews(views: readonly ViewInput[], options: ViewsOptions): this;
221
238
  /**
222
239
  * The state of a body in the scene at a moment (position in km always; velocity in km/s only where the body's source provides it), the same State the viewer draws: for a path added with `addTrajectory`, about its centre body;
223
240
  * for a ready-made body or one from `addBodyFromElements`, about its parent (a planet about the Sun, a moon about its planet). Figures a story quotes, such as a distance from the Sun, come from here. `velocityKmS` is set only for a path whose
package/src/api/scene.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createProvenance } from "../core/provenance.js";
2
- import { planPathProvenance } from "./pathProvenance.js";
2
+ import { planLineStretches, planPathProvenance } from "./pathProvenance.js";
3
+ import { influenceStretches, sphereOfInfluenceKm } from "./sphereOfInfluence.js";
3
4
  import { SampledTrajectory } from "../core/sampledTrajectory.js";
4
5
  import { readableScale, solarSystemScale, trueScale } from "../core/scalePolicy.js";
5
6
  import { createState } from "../core/state.js";
@@ -7,14 +8,16 @@ import { createOrbTwoBodyAdapter } from "../core/twoBodyAdapter.js";
7
8
  import { createStateResolver } from "../core/stateResolver.js";
8
9
  import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
9
10
  import { isPlanetId, loadPlanetSeries, planetSeriesLoaded, planetSeriesSpan } from "../core/planetSeries.js";
10
- import { catalogue as builtInCatalogue, extendCatalogue, rootBodyId } from "../assets/catalogue.js";
11
+ import { catalogue as builtInCatalogue, extendCatalogue, extendCatalogueWithMoons, rootBodyId } from "../assets/catalogue.js";
11
12
  import { buildElementsBody, ElementsBodyError, parseElementsBodyRecord } from "../core/elementsBody.js";
12
13
  import { createComposition } from "../assets/compositions.js";
13
14
  import { bodyMetrics } from "../app/bodyMetrics.js";
14
15
  import { needsPlanetSeries } from "../app/planetNeeds.js";
16
+ import { lineBodies } from "../app/mission.js";
15
17
  import { catalogueItem } from "../app/catalogueItem.js";
16
18
  import { createReadoutMetrics } from "../app/trackedMetrics.js";
17
19
  import { circlesTheSun, farthestSunDistanceKm, sunOrbitIdOf, sunOrbitLayer } from "./sunOrbit.js";
20
+ import { listedMoonBodyOf } from "../core/bodies/listedMoonBodies.js";
18
21
  import { FALLBACK_SCENE_CENTRE, readyMade } from "./bodies.js";
19
22
  import { installData } from "./data.js";
20
23
  import { planActivity, rateMetricOf } from "./activity.js";
@@ -22,6 +25,7 @@ import { buildGroupLayer, planGroup } from "./group.js";
22
25
  import { SceneError } from "./errors.js";
23
26
  import { toUtcMs } from "./time.js";
24
27
  import { switchesOf } from "./switches.js";
28
+ import { resolveViews, viewsOf } from "./views.js";
25
29
  import { TimeScaleOutOfRangeError } from "../core/timeScale.js";
26
30
  import { checkEventObjects, eventProvenanceOf, eventsOf, pacingFor, panelsOf, timelineOf } from "./story.js";
27
31
  export { toUtcMs } from "./time.js";
@@ -150,15 +154,32 @@ export class Scene {
150
154
  #panels;
151
155
  #timeline;
152
156
  #switches;
157
+ #views;
153
158
  constructor() {
154
159
  this.camera = new SceneCamera((id) => this.#taken(id), (id) => this.#bodies.has(id) && circlesTheSun(this.#catalogue, id));
155
160
  }
156
161
  /** Adds a catalogued body: a ready-made one (`earth`, `moon`, ...) or its id. The first body added is the scene's centre. `{ orbit: true }` also draws its orbit line. */
157
162
  addBody(body, options = {}) {
158
163
  const id = typeof body === "string" ? body : body.id;
159
- this.#register("addBody", id, typeof body === "string" ? readyMade(id) ?? { id, label: this.#catalogue.has(id) ? this.#catalogue.get(id).definition.label : id } : body, options);
164
+ const before = this.#catalogue;
165
+ this.#addListedMoon(id);
166
+ try {
167
+ this.#register("addBody", id, typeof body === "string" ? readyMade(id) ?? { id, label: this.#catalogue.has(id) ? this.#catalogue.get(id).definition.label : id } : body, options);
168
+ }
169
+ catch (error) {
170
+ this.#catalogue = before;
171
+ throw error;
172
+ }
160
173
  return this;
161
174
  }
175
+ /** A moon in the listed-moon table that the built-in catalogue does not define by hand is defined now, by the one rule, and joins this scene's catalogue only (an unused moon costs nothing). */
176
+ #addListedMoon(id) {
177
+ if (this.#catalogue.has(id))
178
+ return;
179
+ const moon = listedMoonBodyOf(id);
180
+ if (moon !== undefined && this.#catalogue.has(moon.definition.parentId))
181
+ this.#catalogue = extendCatalogueWithMoons(this.#catalogue, [moon]);
182
+ }
162
183
  /**
163
184
  * Adds your own body that circles the Sun, from its published orbit elements and where they came from: a record with the id, label, elements at an epoch, the source
164
185
  * (name, URL, solution, access date), a stated accuracy and optionally a radius and marker. Drawn as a marker on unperturbed two-body motion about the Sun; the provenance
@@ -168,6 +189,8 @@ export class Scene {
168
189
  * scene.addBody(sun).addBodyFromElements(record, { orbit: true, showLabel: false });
169
190
  */
170
191
  addBodyFromElements(record, options = {}) {
192
+ if (record?.id === "auto")
193
+ throw new SceneError("bad-element", `addBodyFromElements("auto"): "auto" is reserved (it is lineFixedTo's automatic choice) and cannot be a body id`);
171
194
  const parsed = parseRecord(record);
172
195
  if (this.#taken(parsed.id) || this.#catalogue.has(parsed.id))
173
196
  throw new SceneError("duplicate-id", `addBodyFromElements("${parsed.id}"): that id is already in the scene or the catalogue`);
@@ -188,7 +211,7 @@ export class Scene {
188
211
  if (options.orbit === true && moonOrbitPath(this.#catalogue, id) === undefined && !(circlesTheSun(this.#catalogue, id)))
189
212
  throw new SceneError("no-orbit", `${call}("${id}", { orbit: true }): the engine draws the orbit line of any catalogued moon whose data give a period about its planet and of any body that circles the Sun (every planet: its own source over a full turn where the source covers one, else the two-body ellipse osculating at the opening time)`);
190
213
  if (!this.#catalogue.has(id))
191
- throw new SceneError("unknown-body", `${call}("${id}"): not a catalogued body (known: ${this.#catalogue.ids().join(", ")})`);
214
+ throw new SceneError("unknown-body", `${call}("${id}"): not a catalogued body (known: ${builtInCatalogue.ids().join(", ")}; any moon in the moon lists is added by its id, and \`listedMoons(planet)\` names them with the data package each needs)`);
192
215
  if (this.#taken(id))
193
216
  throw new SceneError("duplicate-id", `${call}("${id}"): already in the scene`);
194
217
  checkBodyLook(id, options);
@@ -230,7 +253,7 @@ export class Scene {
230
253
  if (!builtInCatalogue.has(center))
231
254
  throw new SceneError("unknown-body", `addTrajectory("${id}"): centre "${center}" is not a catalogued body`);
232
255
  const provenance = input.provenance ?? createProvenance({ sourceType: "illustrative", sources: ["Supplied by the caller"], accuracy: "As supplied; the engine makes no claim.", notes: "Positions were passed to addTrajectory." });
233
- const common = { id, label: input.label ?? id, color: input.color ?? DEFAULT_COLOR, anchorTimesUtcMs: [], provenance, ...(input.lineFixedTo === undefined ? {} : { lineFixedTo: input.lineFixedTo }) };
256
+ const common = { id, label: input.label ?? id, color: input.color ?? DEFAULT_COLOR, anchorTimesUtcMs: [], provenance };
234
257
  const readouts = readoutsOf(id, input.readouts);
235
258
  if (input.labelReach !== undefined) {
236
259
  checkLabelReach(input.labelReach, new SceneError("bad-trajectory", `addTrajectory("${id}"): labelReach ${String(input.labelReach)} must be a positive finite number`));
@@ -240,8 +263,12 @@ export class Scene {
240
263
  throw new SceneError("bad-trajectory", `addTrajectory("${id}"): plane "${String(input.plane)}" must be "EQJ" or "ecliptic-j2000"`);
241
264
  const toEqj = input.plane === "ecliptic-j2000" ? createOrbTwoBodyAdapter().eclipticJ2000ToEqjMatrix() : null;
242
265
  const body = "samples" in input ? sampledBody(common, input, center, toEqj) : providerBody(common, input, toEqj);
243
- const provenanceSpans = input.provenanceSpans === undefined ? undefined : planPathProvenance(id, input.provenanceSpans, { startUtcMs: body.trajectory.bounds.startUtcMs, endUtcMs: body.trajectory.bounds.endUtcMs });
244
- this.#tracked.set(id, { center, body: withAnchors(body, input.anchors), readouts, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) });
266
+ const span = { startUtcMs: body.trajectory.bounds.startUtcMs, endUtcMs: body.trajectory.bounds.endUtcMs };
267
+ const provenanceSpans = input.provenanceSpans === undefined ? undefined : planPathProvenance(id, input.provenanceSpans, span);
268
+ checkLineFixedToType(id, input.lineFixedTo);
269
+ const auto = input.lineFixedTo === "auto";
270
+ const lineFixedTo = typeof input.lineFixedTo === "object" ? planLineStretches(id, input.lineFixedTo, span) : auto ? undefined : input.lineFixedTo;
271
+ this.#tracked.set(id, { center, ...(auto ? { auto: true } : {}), body: withAnchors(lineFixedTo === undefined ? body : { ...body, lineFixedTo }, input.anchors), readouts, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) });
245
272
  }
246
273
  /** Whether a body, path or group already has this id. */
247
274
  #taken(id) {
@@ -323,6 +350,19 @@ export class Scene {
323
350
  this.#switches = switchesOf(switches, this.#switches);
324
351
  return this;
325
352
  }
353
+ /**
354
+ * Names views of this one scene, each listing what it shows: `paths` (ids of `addTrajectory`), `bodies` (ids of `addBody` or `addGroup`), `events` (ids of `addEvents`) and `panels` (ids of `addStoryPanels`).
355
+ * Anything no view names shows in every view (shared bodies such as the planets); anything a view names shows only in the views that name it. `place` is `"top-bar"` or `"panel"` (as for `setSwitches`);
356
+ * `start` is the opening view (default the first). `camera` says what happens when the followed or focused object is not in the view switched to: `"stay"` (default), `"start"` (the scene's start) or
357
+ * `{ follow: id }` / `{ focus: id }` (that framing; the object must be in the view). Presentation only: State is unchanged and a hidden object keeps its state. May be called again; the later call replaces the views.
358
+ * An empty list, a repeated view id, a bad place or camera, or a `start` that is not a view throws `bad-view` here; an id the scene does not hold, or a camera target the view does not show, throws `bad-view` when the scene is built (`mount`), so the call may come before or after the objects.
359
+ * @example
360
+ * scene.setViews([{ id: "a", label: "Probe A", paths: ["probe-a"] }, { id: "b", label: "Probe B", paths: ["probe-b"] }, { id: "both", label: "Both" }], { place: "top-bar" });
361
+ */
362
+ setViews(views, options) {
363
+ this.#views = viewsOf(views, options);
364
+ return this;
365
+ }
326
366
  /**
327
367
  * The state of a body in the scene at a moment (position in km always; velocity in km/s only where the body's source provides it), the same State the viewer draws: for a path added with `addTrajectory`, about its centre body;
328
368
  * for a ready-made body or one from `addBodyFromElements`, about its parent (a planet about the Sun, a moon about its planet). Figures a story quotes, such as a distance from the Sun, come from here. `velocityKmS` is set only for a path whose
@@ -383,6 +423,12 @@ export class Scene {
383
423
  anchors.set(label, body.anchorTimesUtcMs[index]); });
384
424
  return panelsOf(this.#panels, { events: this.#events, anchors, objectIds: [...this.#bodies.keys(), ...this.#tracked.keys(), ...this.#groups.keys()], window });
385
425
  }
426
+ /** The `views` entry of the definition: the views resolved against the finished scene once (absent when none was named). */
427
+ #viewsEntry(ids, storyPanels) {
428
+ if (this.#views === undefined)
429
+ return {};
430
+ return { views: resolveViews(this.#views, { paths: [...this.#tracked.keys()], bodies: [...ids, ...this.#groups.keys()], events: this.#events.map(({ id }) => id), panels: storyPanels?.panels.map(({ id }) => id) ?? [] }) };
431
+ }
386
432
  /** Checks the groups against the finished scene: each circles its centre (default the scene's first body), which and whose clump body the scene must hold. */
387
433
  #checkGroups(ids) {
388
434
  for (const plan of this.#groups.values()) {
@@ -568,11 +614,48 @@ export class Scene {
568
614
  throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): "${id}" completes no turn within thirty years and its position and the Sun's gravity do not give a bound ellipse; add it with addBodyFromElements to draw its whole orbit`);
569
615
  return layer;
570
616
  }
617
+ /** The stretches of a `lineFixedTo: "auto"` path: the innermost scene body whose sphere of influence holds each sample (`sphereOfInfluence.ts`). Reads body states, so the planet series must be loaded. */
618
+ #autoStretches(entry, ids) {
619
+ const resolver = createStateResolver(this.#catalogue.definitions(), this.#catalogue.sources(), createOrbAstronomyAdapter());
620
+ const norm = (v) => Math.hypot(v[0], v[1], v[2]);
621
+ const candidates = [];
622
+ for (const id of ids) {
623
+ const { parentId, gmKm3S2 } = this.#catalogue.get(id).definition;
624
+ if (parentId === undefined) {
625
+ candidates.push({ id, radiusKm: () => Infinity, probeDistanceKm: () => 0 });
626
+ continue;
627
+ }
628
+ const parentGm = this.#catalogue.get(parentId).definition.gmKm3S2;
629
+ if (!(gmKm3S2 > 0 && parentGm > 0))
630
+ continue; // no published GM: this body cannot hold a probe
631
+ candidates.push({
632
+ id,
633
+ radiusKm: (t) => sphereOfInfluenceKm(gmKm3S2, parentGm, norm(resolver.stateOf(id, t, parentId).positionKm)),
634
+ probeDistanceKm: (t) => {
635
+ const probe = entry.body.trajectory.stateAt(t, entry.center).positionKm;
636
+ const body = resolver.stateOf(id, t, entry.center).positionKm;
637
+ return norm([probe[0] - body[0], probe[1] - body[1], probe[2] - body[2]]);
638
+ },
639
+ });
640
+ }
641
+ return influenceStretches(entry.body.pathTimesUtcMs, candidates);
642
+ }
643
+ /** The `"auto"` paths' one resolution into `tracked`: `now` runs it (through the caller's guarded read) when the planet series are in; else `later` is true and `settle` runs it in `prepare`. */
644
+ #autoPaths(entries, tracked, ids) {
645
+ const pending = entries.some((entry) => entry.auto === true);
646
+ const later = pending && !planetSeriesLoaded();
647
+ const resolve = () => entries.forEach((entry, index) => { if (entry.auto === true)
648
+ tracked[index] = { ...entry.body, lineFixedTo: this.#autoStretches(entry, ids) }; });
649
+ return { later, now: (guard) => { if (pending && !later)
650
+ guard(resolve); }, settle: (guard) => { if (later)
651
+ guard(resolve); } };
652
+ }
571
653
  /** A readout, or the body the line is fixed to, names a body the scene must hold. */
572
654
  #checkReadouts(entry, ids) {
573
- const fixed = entry.body.lineFixedTo;
574
- if (fixed !== undefined && !ids.includes(fixed))
575
- throw new SceneError("bad-trajectory", `addTrajectory("${entry.body.id}"): lineFixedTo names "${fixed}", which has not been added to the scene`);
655
+ for (const { index, body } of lineBodies(entry.body.lineFixedTo)) {
656
+ if (!ids.includes(body))
657
+ throw new SceneError("bad-trajectory", `addTrajectory("${entry.body.id}"): lineFixedTo${index === null ? "" : `[${index}]`} names "${body}", which has not been added to the scene`);
658
+ }
576
659
  for (const spec of entry.readouts) {
577
660
  const named = readoutBody(spec);
578
661
  if (named !== undefined && !ids.includes(named))
@@ -597,12 +680,16 @@ export class Scene {
597
680
  this.#checkSolarSystemScale(sunCentred);
598
681
  for (const entry of this.#tracked.values())
599
682
  this.#checkReadouts(entry, ids);
600
- const tracked = [...this.#tracked.values()].map((entry) => entry.body);
683
+ const entries = [...this.#tracked.values()];
684
+ const tracked = entries.map((entry) => entry.body);
601
685
  const timeline = this.#timeline;
602
686
  const { window, startUtcMs } = spanOf(timeline, this.#timeUtcMs, [...tracked.map((body) => body.trajectory.bounds), ...[...this.#activities.values()].map((activity) => activity.window)]);
603
687
  const sunOrbitIds = this.#sunOrbitIds(ids);
604
688
  // The farthest distance is worked out in setup, once: now when the planet series are in, else in `prepare` once they are; never in the frame loop.
605
689
  const fault = {};
690
+ // `lineFixedTo: "auto"` paths read body states: now when the planet series are in, else in `prepare` once they are (the viewer draws only after it resolves); never per frame.
691
+ const auto = this.#autoPaths(entries, tracked, ids);
692
+ auto.now((read) => this.#deferredRead(ids, window, fault, undefined, read));
606
693
  const fit = this.#deferredRead(ids, window, fault, undefined, () => this.#fitFarthestKm(startUtcMs));
607
694
  // The lines read planet positions; when the planet series are not loaded yet (a consumer's mount), they are drawn in `prepare`, once the series are in. The viewer draws only after `prepare` resolves.
608
695
  const sunPaths = this.#deferredRead(ids, window, fault, [], () => this.#earlySunPaths(sunOrbitIds, startUtcMs));
@@ -637,11 +724,12 @@ export class Scene {
637
724
  ...pacingEntry(timeline, this.#events),
638
725
  ...groupLayersEntry(layers, this.#groups.size > 0, sunOrbitIds.length > 0),
639
726
  ...(sunOrbitIds.length === 0 ? {} : { paths: sunPaths }),
640
- ...(this.#own.size === 0 ? {} : { catalogue: this.#catalogue }),
727
+ ...(this.#catalogue === builtInCatalogue ? {} : { catalogue: this.#catalogue }),
641
728
  ...visualOverridesEntry(this.#shape),
642
729
  composition: createComposition(this.#catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
643
730
  scaleChoices: scaleChoicesOf(this.#scale, this.#scaleOnly, this.#enlargedInSun(sunCentred)),
644
731
  ...(this.#switches === undefined ? {} : { displaySwitches: this.#switches }),
732
+ ...this.#viewsEntry(ids, storyPanels),
645
733
  ...viewEntries(timeline, this.camera, fit?.read, this.#pathCover(sunCentred, ids[0])),
646
734
  ...(target === undefined ? {} : { startView: { focus: target, azimuthDeg: view.azimuthDeg ?? 0, elevationDeg: view.elevationDeg ?? 30, distance: view.distance ?? 40 } }),
647
735
  trackedBodies: tracked,
@@ -653,16 +741,17 @@ export class Scene {
653
741
  prepare: async () => {
654
742
  if (fault.error !== undefined)
655
743
  throw fault.error;
656
- if (needsPlanetSeries(definition) || sunPaths.length < sunOrbitIds.length || this.#groups.size > layers.length)
744
+ if (needsPlanetSeries(definition) || auto.later || sunPaths.length < sunOrbitIds.length || this.#groups.size > layers.length)
657
745
  await loadPlanetSeries();
658
746
  this.#checkPlanetSpan(ids, window);
747
+ auto.settle((read) => this.#planetRead(ids, window, read));
659
748
  if (this.#groups.size > layers.length)
660
749
  layers.push(...this.#planetRead(ids, window, () => this.#groupLayers(ids, window, startUtcMs, late)));
661
750
  if (sunPaths.length < sunOrbitIds.length)
662
751
  sunPaths.push(...this.#planetRead(ids, window, () => sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs))));
663
752
  if (fit !== undefined)
664
753
  this.#planetRead(ids, window, () => fit.settle());
665
- await installData(data, ids, window);
754
+ await installData(data, ids, window, catalogue);
666
755
  },
667
756
  };
668
757
  return definition;
@@ -763,6 +852,11 @@ function sampledBody(common, input, center, toEqj) {
763
852
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): ${error instanceof Error ? error.message : String(error)}`);
764
853
  }
765
854
  }
855
+ /** `lineFixedTo` is a body id, `"auto"` or a list; anything else is `bad-trajectory` (the list's own faults are named by `planLineStretches`). */
856
+ function checkLineFixedToType(id, value) {
857
+ if (value !== undefined && typeof value !== "string" && typeof value !== "object")
858
+ throw new SceneError("bad-trajectory", `addTrajectory("${id}"): lineFixedTo ${String(value)} must be a body id, "auto" or a list of stretches`);
859
+ }
766
860
  function providerBody(common, input, toEqj) {
767
861
  if (typeof input.provider?.stateAt !== "function")
768
862
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): provider needs a stateAt(time) function`);
@@ -770,8 +864,9 @@ function providerBody(common, input, toEqj) {
770
864
  if (bounds.endUtcMs <= bounds.startUtcMs)
771
865
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): bounds must end after they start`);
772
866
  const trajectory = { body: common.id, bounds, stateAt: (timeUtcMs, center) => rotatedState(toEqj, input.provider.stateAt(timeUtcMs, center)) };
867
+ // Whole milliseconds, because the state resolver refuses a fractional time (the line is placed against another body at these times).
773
868
  const step = (bounds.endUtcMs - bounds.startUtcMs) / (PROVIDER_PATH_SAMPLES - 1);
774
- return { ...common, trajectory, pathTimesUtcMs: Array.from({ length: PROVIDER_PATH_SAMPLES }, (_, index) => bounds.startUtcMs + index * step) };
869
+ return { ...common, trajectory, pathTimesUtcMs: Array.from({ length: PROVIDER_PATH_SAMPLES }, (_, index) => Math.round(bounds.startUtcMs + index * step)) };
775
870
  }
776
871
  /** A provider's State with its position and velocity rotated into EQJ; unchanged for EQJ input. */
777
872
  function rotatedState(matrix, state) {
@@ -0,0 +1,20 @@
1
+ import type { LineStretch } from "../app/mission.js";
2
+ /**
3
+ * Laplace's sphere of influence of a body about its parent: `r = a (m / M)^(2/5)`, `a` the body's distance from the parent, `m` and `M` their GMs (km^3/s^2).
4
+ * Where either GM is missing or not above zero it returns NaN, so a body without a GM can never hold a probe.
5
+ */
6
+ export declare function sphereOfInfluenceKm(gmKm3S2: number | undefined, parentGmKm3S2: number | undefined, distanceFromParentKm: number): number;
7
+ /** A body that can hold a probe: its sphere of influence and the probe's distance from it, at a time. A root body (no parent) holds everything (infinite radius). */
8
+ export interface InfluenceCandidate {
9
+ readonly id: string;
10
+ readonly radiusKm: (timeUtcMs: number) => number;
11
+ readonly probeDistanceKm: (timeUtcMs: number) => number;
12
+ }
13
+ /** The candidate whose sphere holds the probe at `timeUtcMs`; the smallest sphere wins (a moon inside its planet's). */
14
+ export declare function innermostHolding(candidates: readonly InfluenceCandidate[], timeUtcMs: number): string | undefined;
15
+ /**
16
+ * The stretch list for a path sampled at `timesUtcMs`: each sample belongs to the innermost holding body, consecutive samples on one body merge, and a stretch starts at its first
17
+ * sample (so a boundary is within one sample of the true crossing) and ends where the next run starts, or at the path's last sample. Samples no body holds are left uncovered
18
+ * (drawn against the scene centre). A run that would start at the last sample is dropped (it has no length).
19
+ */
20
+ export declare function influenceStretches(timesUtcMs: readonly number[], candidates: readonly InfluenceCandidate[]): readonly LineStretch[];
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Laplace's sphere of influence of a body about its parent: `r = a (m / M)^(2/5)`, `a` the body's distance from the parent, `m` and `M` their GMs (km^3/s^2).
3
+ * Where either GM is missing or not above zero it returns NaN, so a body without a GM can never hold a probe.
4
+ */
5
+ export function sphereOfInfluenceKm(gmKm3S2, parentGmKm3S2, distanceFromParentKm) {
6
+ if (!(typeof gmKm3S2 === "number" && gmKm3S2 > 0 && typeof parentGmKm3S2 === "number" && parentGmKm3S2 > 0))
7
+ return Number.NaN;
8
+ return distanceFromParentKm * (gmKm3S2 / parentGmKm3S2) ** 0.4;
9
+ }
10
+ /** The candidate whose sphere holds the probe at `timeUtcMs`; the smallest sphere wins (a moon inside its planet's). */
11
+ export function innermostHolding(candidates, timeUtcMs) {
12
+ let best;
13
+ let bestRadius = Infinity;
14
+ for (const candidate of candidates) {
15
+ const radius = candidate.radiusKm(timeUtcMs);
16
+ if (!(radius >= candidate.probeDistanceKm(timeUtcMs)) || (best !== undefined && !(radius < bestRadius)))
17
+ continue;
18
+ best = candidate.id;
19
+ bestRadius = radius;
20
+ }
21
+ return best;
22
+ }
23
+ /**
24
+ * The stretch list for a path sampled at `timesUtcMs`: each sample belongs to the innermost holding body, consecutive samples on one body merge, and a stretch starts at its first
25
+ * sample (so a boundary is within one sample of the true crossing) and ends where the next run starts, or at the path's last sample. Samples no body holds are left uncovered
26
+ * (drawn against the scene centre). A run that would start at the last sample is dropped (it has no length).
27
+ */
28
+ export function influenceStretches(timesUtcMs, candidates) {
29
+ const stretches = [];
30
+ const end = timesUtcMs[timesUtcMs.length - 1];
31
+ let open;
32
+ const close = (until) => {
33
+ if (open !== undefined && until > open.start)
34
+ stretches.push({ startUtcMs: open.start, endUtcMs: until, body: open.body });
35
+ open = undefined;
36
+ };
37
+ for (const time of timesUtcMs) {
38
+ const body = innermostHolding(candidates, time);
39
+ if (open !== undefined && open.body === body)
40
+ continue;
41
+ close(time);
42
+ if (body !== undefined)
43
+ open = { start: time, body };
44
+ }
45
+ if (end !== undefined)
46
+ close(end);
47
+ return stretches;
48
+ }