astraeus 0.6.0 → 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 (60) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +31 -8
  3. package/package.json +1 -1
  4. package/src/api/AstraeusScene.d.ts +4 -2
  5. package/src/api/AstraeusScene.js +13 -10
  6. package/src/api/AstraeusScene.node.js +13 -10
  7. package/src/api/errors.d.ts +1 -1
  8. package/src/api/index.d.ts +1 -0
  9. package/src/api/mount.d.ts +5 -1
  10. package/src/api/mount.js +2 -0
  11. package/src/api/mount.node.js +2 -0
  12. package/src/api/pathProvenance.d.ts +15 -6
  13. package/src/api/pathProvenance.js +23 -11
  14. package/src/api/scene.d.ts +18 -1
  15. package/src/api/scene.js +88 -10
  16. package/src/api/sphereOfInfluence.d.ts +20 -0
  17. package/src/api/sphereOfInfluence.js +48 -0
  18. package/src/api/viewerLink.d.ts +7 -1
  19. package/src/api/viewerLink.js +13 -2
  20. package/src/api/views.d.ts +42 -0
  21. package/src/api/views.js +80 -0
  22. package/src/app/App.js +32 -5
  23. package/src/app/App.node.js +32 -5
  24. package/src/app/AstraeusScene.d.ts +3 -0
  25. package/src/app/CameraController.d.ts +6 -0
  26. package/src/app/CameraController.js +3 -1
  27. package/src/app/StoryMarkers.d.ts +4 -1
  28. package/src/app/StoryMarkers.js +3 -2
  29. package/src/app/TrackedBodyView.d.ts +1 -1
  30. package/src/app/TrackedBodyView.js +20 -11
  31. package/src/app/experienceDefinition.d.ts +3 -0
  32. package/src/app/mission.d.ts +15 -2
  33. package/src/app/mission.js +15 -0
  34. package/src/app/sceneCamera.d.ts +2 -0
  35. package/src/app/sceneCamera.js +14 -0
  36. package/src/app/sceneFrame.d.ts +2 -0
  37. package/src/app/sceneFrame.js +42 -6
  38. package/src/app/viewHiding.d.ts +13 -0
  39. package/src/app/viewHiding.js +37 -0
  40. package/src/app/viewerPort.d.ts +6 -0
  41. package/src/app/views.d.ts +31 -0
  42. package/src/app/views.js +2 -0
  43. package/src/shell/AstraeusShell.d.ts +12 -2
  44. package/src/shell/AstraeusShell.js +42 -4
  45. package/src/shell/AstraeusShell.node.js +42 -4
  46. package/src/shell/DisplaySwitches.d.ts +18 -1
  47. package/src/shell/DisplaySwitches.js +18 -5
  48. package/src/shell/TimelineBar.css +18 -0
  49. package/src/shell/TimelineBar.js +29 -4
  50. package/src/shell/TimelineBar.node.js +29 -4
  51. package/src/shell/TopBar.d.ts +4 -2
  52. package/src/shell/TopBar.js +3 -3
  53. package/src/shell/TopBar.node.js +3 -3
  54. package/src/shell/timelineModel.d.ts +13 -0
  55. package/src/shell/timelineModel.js +25 -0
  56. package/src/shell/viewCamera.d.ts +4 -0
  57. package/src/shell/viewCamera.js +13 -0
  58. package/src/synthetic/syntheticJourneyScene.js +11 -1
  59. package/src/synthetic/syntheticViewsDefinition.d.ts +6 -0
  60. package/src/synthetic/syntheticViewsDefinition.js +44 -0
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";
@@ -12,6 +13,7 @@ import { buildElementsBody, ElementsBodyError, parseElementsBodyRecord } from ".
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";
@@ -23,6 +25,7 @@ import { buildGroupLayer, planGroup } from "./group.js";
23
25
  import { SceneError } from "./errors.js";
24
26
  import { toUtcMs } from "./time.js";
25
27
  import { switchesOf } from "./switches.js";
28
+ import { resolveViews, viewsOf } from "./views.js";
26
29
  import { TimeScaleOutOfRangeError } from "../core/timeScale.js";
27
30
  import { checkEventObjects, eventProvenanceOf, eventsOf, pacingFor, panelsOf, timelineOf } from "./story.js";
28
31
  export { toUtcMs } from "./time.js";
@@ -151,6 +154,7 @@ export class Scene {
151
154
  #panels;
152
155
  #timeline;
153
156
  #switches;
157
+ #views;
154
158
  constructor() {
155
159
  this.camera = new SceneCamera((id) => this.#taken(id), (id) => this.#bodies.has(id) && circlesTheSun(this.#catalogue, id));
156
160
  }
@@ -185,6 +189,8 @@ export class Scene {
185
189
  * scene.addBody(sun).addBodyFromElements(record, { orbit: true, showLabel: false });
186
190
  */
187
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`);
188
194
  const parsed = parseRecord(record);
189
195
  if (this.#taken(parsed.id) || this.#catalogue.has(parsed.id))
190
196
  throw new SceneError("duplicate-id", `addBodyFromElements("${parsed.id}"): that id is already in the scene or the catalogue`);
@@ -247,7 +253,7 @@ export class Scene {
247
253
  if (!builtInCatalogue.has(center))
248
254
  throw new SceneError("unknown-body", `addTrajectory("${id}"): centre "${center}" is not a catalogued body`);
249
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." });
250
- 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 };
251
257
  const readouts = readoutsOf(id, input.readouts);
252
258
  if (input.labelReach !== undefined) {
253
259
  checkLabelReach(input.labelReach, new SceneError("bad-trajectory", `addTrajectory("${id}"): labelReach ${String(input.labelReach)} must be a positive finite number`));
@@ -257,8 +263,12 @@ export class Scene {
257
263
  throw new SceneError("bad-trajectory", `addTrajectory("${id}"): plane "${String(input.plane)}" must be "EQJ" or "ecliptic-j2000"`);
258
264
  const toEqj = input.plane === "ecliptic-j2000" ? createOrbTwoBodyAdapter().eclipticJ2000ToEqjMatrix() : null;
259
265
  const body = "samples" in input ? sampledBody(common, input, center, toEqj) : providerBody(common, input, toEqj);
260
- const provenanceSpans = input.provenanceSpans === undefined ? undefined : planPathProvenance(id, input.provenanceSpans, { startUtcMs: body.trajectory.bounds.startUtcMs, endUtcMs: body.trajectory.bounds.endUtcMs });
261
- 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 }) });
262
272
  }
263
273
  /** Whether a body, path or group already has this id. */
264
274
  #taken(id) {
@@ -340,6 +350,19 @@ export class Scene {
340
350
  this.#switches = switchesOf(switches, this.#switches);
341
351
  return this;
342
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
+ }
343
366
  /**
344
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;
345
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
@@ -400,6 +423,12 @@ export class Scene {
400
423
  anchors.set(label, body.anchorTimesUtcMs[index]); });
401
424
  return panelsOf(this.#panels, { events: this.#events, anchors, objectIds: [...this.#bodies.keys(), ...this.#tracked.keys(), ...this.#groups.keys()], window });
402
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
+ }
403
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. */
404
433
  #checkGroups(ids) {
405
434
  for (const plan of this.#groups.values()) {
@@ -585,11 +614,48 @@ export class Scene {
585
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`);
586
615
  return layer;
587
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
+ }
588
653
  /** A readout, or the body the line is fixed to, names a body the scene must hold. */
589
654
  #checkReadouts(entry, ids) {
590
- const fixed = entry.body.lineFixedTo;
591
- if (fixed !== undefined && !ids.includes(fixed))
592
- 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
+ }
593
659
  for (const spec of entry.readouts) {
594
660
  const named = readoutBody(spec);
595
661
  if (named !== undefined && !ids.includes(named))
@@ -614,12 +680,16 @@ export class Scene {
614
680
  this.#checkSolarSystemScale(sunCentred);
615
681
  for (const entry of this.#tracked.values())
616
682
  this.#checkReadouts(entry, ids);
617
- const tracked = [...this.#tracked.values()].map((entry) => entry.body);
683
+ const entries = [...this.#tracked.values()];
684
+ const tracked = entries.map((entry) => entry.body);
618
685
  const timeline = this.#timeline;
619
686
  const { window, startUtcMs } = spanOf(timeline, this.#timeUtcMs, [...tracked.map((body) => body.trajectory.bounds), ...[...this.#activities.values()].map((activity) => activity.window)]);
620
687
  const sunOrbitIds = this.#sunOrbitIds(ids);
621
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.
622
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));
623
693
  const fit = this.#deferredRead(ids, window, fault, undefined, () => this.#fitFarthestKm(startUtcMs));
624
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.
625
695
  const sunPaths = this.#deferredRead(ids, window, fault, [], () => this.#earlySunPaths(sunOrbitIds, startUtcMs));
@@ -659,6 +729,7 @@ export class Scene {
659
729
  composition: createComposition(this.#catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
660
730
  scaleChoices: scaleChoicesOf(this.#scale, this.#scaleOnly, this.#enlargedInSun(sunCentred)),
661
731
  ...(this.#switches === undefined ? {} : { displaySwitches: this.#switches }),
732
+ ...this.#viewsEntry(ids, storyPanels),
662
733
  ...viewEntries(timeline, this.camera, fit?.read, this.#pathCover(sunCentred, ids[0])),
663
734
  ...(target === undefined ? {} : { startView: { focus: target, azimuthDeg: view.azimuthDeg ?? 0, elevationDeg: view.elevationDeg ?? 30, distance: view.distance ?? 40 } }),
664
735
  trackedBodies: tracked,
@@ -670,9 +741,10 @@ export class Scene {
670
741
  prepare: async () => {
671
742
  if (fault.error !== undefined)
672
743
  throw fault.error;
673
- 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)
674
745
  await loadPlanetSeries();
675
746
  this.#checkPlanetSpan(ids, window);
747
+ auto.settle((read) => this.#planetRead(ids, window, read));
676
748
  if (this.#groups.size > layers.length)
677
749
  layers.push(...this.#planetRead(ids, window, () => this.#groupLayers(ids, window, startUtcMs, late)));
678
750
  if (sunPaths.length < sunOrbitIds.length)
@@ -780,6 +852,11 @@ function sampledBody(common, input, center, toEqj) {
780
852
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): ${error instanceof Error ? error.message : String(error)}`);
781
853
  }
782
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
+ }
783
860
  function providerBody(common, input, toEqj) {
784
861
  if (typeof input.provider?.stateAt !== "function")
785
862
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): provider needs a stateAt(time) function`);
@@ -787,8 +864,9 @@ function providerBody(common, input, toEqj) {
787
864
  if (bounds.endUtcMs <= bounds.startUtcMs)
788
865
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): bounds must end after they start`);
789
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).
790
868
  const step = (bounds.endUtcMs - bounds.startUtcMs) / (PROVIDER_PATH_SAMPLES - 1);
791
- 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)) };
792
870
  }
793
871
  /** A provider's State with its position and velocity rotated into EQJ; unchanged for EQJ input. */
794
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
+ }
@@ -7,7 +7,9 @@ export interface ViewerChange {
7
7
  /** Simulated seconds per real second. */
8
8
  readonly rate: number;
9
9
  readonly playing: boolean;
10
- /** `playback`: the clock ran on; `visitor`: someone used the timeline; `host`: the host page called `setTime` or `setRate`. */
10
+ /** Only in a scene with views: the id of the view showing. */
11
+ readonly view?: string;
12
+ /** `playback`: the clock ran on; `visitor`: someone used the timeline or the view choice; `host`: the host page called `setTime`, `setRate` or `setView`. */
11
13
  readonly cause: ViewerChangeCause;
12
14
  }
13
15
  /** Where the playback rate comes from. `scene` is the rate the scene opened at; `chosen` is one a visitor or the host picked, which stays until it is released. */
@@ -27,6 +29,10 @@ export declare class ViewerLink implements ViewerPort {
27
29
  get time(): number | undefined;
28
30
  get rate(): number | undefined;
29
31
  get playing(): boolean | undefined;
32
+ /** The id of the view showing; undefined before the viewer is drawn, after it is gone, and in a scene without views. */
33
+ get view(): string | undefined;
34
+ /** Switches to the view with this id. An id the scene does not name, or a scene without views, throws `bad-view`; before the viewer is drawn or after it is gone, `missing-data`. */
35
+ setView(id: string): void;
30
36
  setTime(time: TimeInput): void;
31
37
  /**
32
38
  * Only a speed the timeline offers is taken, so the speed picker always shows what is running; any other number throws `bad-timeline`.
@@ -29,6 +29,17 @@ export class ViewerLink {
29
29
  get time() { return this.#control?.read().timeUtcMs; }
30
30
  get rate() { return this.#control?.read().rate; }
31
31
  get playing() { return this.#control?.read().playing; }
32
+ /** The id of the view showing; undefined before the viewer is drawn, after it is gone, and in a scene without views. */
33
+ get view() { return this.#control?.read().view; }
34
+ /** Switches to the view with this id. An id the scene does not name, or a scene without views, throws `bad-view`; before the viewer is drawn or after it is gone, `missing-data`. */
35
+ setView(id) {
36
+ const control = this.#open("setView");
37
+ if (!control.views.includes(id)) {
38
+ throw new SceneError("bad-view", control.views.length === 0 ? "setView: the scene has no views; name them with setViews" : `setView: "${String(id)}" is not one of the scene's views (${control.views.join(", ")})`);
39
+ }
40
+ control.setView(id);
41
+ this.publish(control.read(), "host");
42
+ }
32
43
  setTime(time) {
33
44
  const control = this.#open("setTime");
34
45
  const timeUtcMs = toUtcMs(time, "setTime");
@@ -67,14 +78,14 @@ export class ViewerLink {
67
78
  }
68
79
  publish(state, cause) {
69
80
  const last = this.#last;
70
- if (last !== undefined && last.timeUtcMs === state.timeUtcMs && last.rate === state.rate && last.playing === state.playing && last.auto === state.auto)
81
+ if (last !== undefined && last.timeUtcMs === state.timeUtcMs && last.rate === state.rate && last.playing === state.playing && last.auto === state.auto && last.view === state.view)
71
82
  return;
72
83
  if (state.auto !== undefined)
73
84
  this.#rateSource = state.auto ? "scene" : "chosen";
74
85
  else if (cause === "visitor" && last !== undefined && last.rate !== state.rate)
75
86
  this.#rateSource = "chosen";
76
87
  this.#last = state;
77
- const change = { time: state.timeUtcMs, rate: state.rate, playing: state.playing, cause };
88
+ const change = { time: state.timeUtcMs, rate: state.rate, playing: state.playing, ...(state.view === undefined ? {} : { view: state.view }), cause };
78
89
  for (const listener of [...this.#listeners])
79
90
  listener(change);
80
91
  }
@@ -0,0 +1,42 @@
1
+ import { type ViewPlace, type ViewSettings } from "../app/views.js";
2
+ /** What a view's camera does when what it follows or focuses on is not in the view: `"stay"` (default) keeps the pose and stops following, `"start"` takes the scene's start, `{ follow: id }` / `{ focus: id }` takes that framing (the object must be in the view). */
3
+ export type ViewCameraInput = "stay" | "start" | {
4
+ readonly follow: string;
5
+ } | {
6
+ readonly focus: string;
7
+ };
8
+ /** One named view. `paths` are `addTrajectory` ids, `bodies` are `addBody` or `addGroup` ids, `events` are `addEvents` ids and `panels` are `addStoryPanels` ids. */
9
+ export interface ViewInput {
10
+ readonly id: string;
11
+ readonly label: string;
12
+ readonly paths?: readonly string[];
13
+ readonly bodies?: readonly string[];
14
+ readonly events?: readonly string[];
15
+ readonly panels?: readonly string[];
16
+ readonly camera?: ViewCameraInput;
17
+ }
18
+ /** Options of `setViews`: where the choice shows (`"top-bar"` or `"panel"`) and the opening view (default the first). */
19
+ export interface ViewsOptions {
20
+ readonly place: ViewPlace;
21
+ readonly start?: string;
22
+ }
23
+ /** A `setViews` call, checked for shape; its ids are checked against the scene by `resolveViews`. */
24
+ export interface ViewsPlan {
25
+ readonly place: ViewPlace;
26
+ readonly start: string;
27
+ readonly views: readonly ViewInput[];
28
+ }
29
+ /** What the finished scene holds, for `resolveViews`. */
30
+ export interface ViewScope {
31
+ readonly paths: readonly string[];
32
+ readonly bodies: readonly string[];
33
+ readonly events: readonly string[];
34
+ readonly panels: readonly string[];
35
+ }
36
+ /** Checks the shape of a `setViews` call (list, ids, labels, place, start, camera form, id lists); the ids are checked when the scene is built. */
37
+ export declare function viewsOf(input: readonly ViewInput[], options: ViewsOptions): ViewsPlan;
38
+ /**
39
+ * Resolves the membership once: for each kind, an id no view names shows in every view, and an id some views name shows only in those. Throws `bad-view` for an id the scene does not hold
40
+ * and for a camera target the view does not show.
41
+ */
42
+ export declare function resolveViews(plan: ViewsPlan, scope: ViewScope): ViewSettings;
@@ -0,0 +1,80 @@
1
+ import { VIEW_PLACES } from "../app/views.js";
2
+ import { SceneError } from "./errors.js";
3
+ const KINDS = ["paths", "bodies", "events", "panels"];
4
+ const bad = (message) => new SceneError("bad-view", `setViews: ${message}`);
5
+ /** Checks the shape of a `setViews` call (list, ids, labels, place, start, camera form, id lists); the ids are checked when the scene is built. */
6
+ export function viewsOf(input, options) {
7
+ // A deep copy first, so a later edit to the caller's objects cannot slip past the checks below.
8
+ const views = Array.isArray(input) ? structuredClone(input) : input;
9
+ if (!Array.isArray(views) || views.length === 0)
10
+ throw bad(`give a non-empty list such as [{ id: "all", label: "All" }]`);
11
+ if (typeof options !== "object" || options === null || !VIEW_PLACES.includes(options.place))
12
+ throw bad(`place must be one of ${VIEW_PLACES.join(", ")}, got ${JSON.stringify(options?.place)}`);
13
+ const seen = new Set();
14
+ views.forEach((view, index) => {
15
+ const where = `view ${index}`;
16
+ if (typeof view !== "object" || view === null)
17
+ throw bad(`${where} must be an object { id, label, ... }`);
18
+ if (typeof view.id !== "string" || view.id === "")
19
+ throw bad(`${where} needs a non-empty id`);
20
+ if (typeof view.label !== "string" || view.label === "")
21
+ throw bad(`view "${view.id}" needs a non-empty label`);
22
+ if (seen.has(view.id))
23
+ throw bad(`view "${view.id}" appears twice`);
24
+ seen.add(view.id);
25
+ for (const kind of KINDS) {
26
+ const ids = view[kind];
27
+ if (ids !== undefined && (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id !== "")))
28
+ throw bad(`view "${view.id}" ${kind} must be a list of non-empty ids`);
29
+ }
30
+ cameraOf(view);
31
+ });
32
+ const start = options.start ?? views[0].id;
33
+ if (!seen.has(start))
34
+ throw bad(`start "${String(start)}" is not a view (views: ${[...seen].join(", ")})`);
35
+ return { place: options.place, start, views: views.map((view) => ({ ...view })) };
36
+ }
37
+ /** The camera rule a view asks for; a malformed one throws `bad-view`. */
38
+ function cameraOf(view) {
39
+ const camera = view.camera;
40
+ if (camera === undefined || camera === "stay")
41
+ return { rule: "stay" };
42
+ if (camera === "start")
43
+ return { rule: "start" };
44
+ const follow = camera?.follow;
45
+ const focus = camera?.focus;
46
+ const target = follow ?? focus;
47
+ if (typeof camera !== "object" || camera === null || typeof target !== "string" || target === "" || (follow !== undefined) === (focus !== undefined))
48
+ throw bad(`view "${view.id}" camera must be "stay", "start", { follow: id } or { focus: id }, got ${JSON.stringify(camera)}`);
49
+ return { rule: "start", framing: follow === undefined ? { focus: target } : { follow: target } };
50
+ }
51
+ /**
52
+ * Resolves the membership once: for each kind, an id no view names shows in every view, and an id some views name shows only in those. Throws `bad-view` for an id the scene does not hold
53
+ * and for a camera target the view does not show.
54
+ */
55
+ export function resolveViews(plan, scope) {
56
+ const known = { paths: new Set(scope.paths), bodies: new Set(scope.bodies), events: new Set(scope.events), panels: new Set(scope.panels) };
57
+ const what = { paths: "a path (addTrajectory)", bodies: "a body or group", events: "an event (addEvents)", panels: "a story panel (addStoryPanels)" };
58
+ const named = { paths: new Set(), bodies: new Set(), events: new Set(), panels: new Set() };
59
+ for (const view of plan.views) {
60
+ for (const kind of KINDS) {
61
+ for (const id of view[kind] ?? []) {
62
+ if (!known[kind].has(id))
63
+ throw bad(`view "${view.id}" ${kind}: "${id}" is not ${what[kind]} in the scene`);
64
+ named[kind].add(id);
65
+ }
66
+ }
67
+ }
68
+ const shows = (view, kind, id) => !named[kind].has(id) || (view[kind] ?? []).includes(id);
69
+ const views = plan.views.map((view) => {
70
+ const objects = new Set([...scope.paths.filter((id) => shows(view, "paths", id)), ...scope.bodies.filter((id) => shows(view, "bodies", id))]);
71
+ const camera = cameraOf(view);
72
+ if (camera.rule === "start" && camera.framing !== undefined) {
73
+ const target = "follow" in camera.framing ? camera.framing.follow : camera.framing.focus;
74
+ if (!objects.has(target))
75
+ throw bad(`view "${view.id}" camera: "${target}" is not shown in that view (a body or path of the scene it names, or one no view hides from it)`);
76
+ }
77
+ return { id: view.id, label: view.label, camera, objects, events: new Set(scope.events.filter((id) => shows(view, "events", id))), panels: new Set(scope.panels.filter((id) => shows(view, "panels", id))) };
78
+ });
79
+ return { place: plan.place, start: plan.start, views };
80
+ }
package/src/app/App.js CHANGED
@@ -27,6 +27,7 @@ import { resolveSkySettings, withSkyObject } from "./skyModel.js";
27
27
  import { ORBIT_LOOK_LIMITS, resolveOrbitLook } from "../assets/orbitLook.js";
28
28
  import { DEFAULT_BODY_SET_LOOK } from "./bodySet.js";
29
29
  import { displaySwitchItems, orbitStart } from "./displaySwitches.js";
30
+ import { experienceInView, hiddenByView, viewById } from "./viewHiding.js";
30
31
  import { baseGlowOf, glowLookFromSearch, markerSettingsFromSearch } from "./bodyDraw.js";
31
32
  import { brightnessFromSearch, milkyWayFromSearch, skyHiddenBySearch } from "./SkyView.js";
32
33
  /** Frames-per-second readings kept for the graph: one per 250 ms poll, so about 15 seconds. */
@@ -137,6 +138,7 @@ function initialSceneControls(definition, runtime, experience, startScale, glowB
137
138
  hiddenLabels: hiddenLabelsFrom(search, labelStart(definition) === undefined ? experience.objects : experience.objects.map(({ id }) => ({ id, showLabel: labelStart(definition) }))),
138
139
  ...startOrbitControls(definition),
139
140
  labelObjects: experience.objects,
141
+ viewHidden: hiddenByView(definition.views, viewById(definition.views, definition.views?.start ?? ""), experience),
140
142
  storyMarkers,
141
143
  featureMarkers: featureMarkerSpecs(definition.experience.bodyFeatures),
142
144
  featureMinBodyPx: featureMinBodyPxFromSearch(search),
@@ -182,7 +184,11 @@ export function App({ definition, onOpenAddress, writeTitle = true, host }) {
182
184
  });
183
185
  return () => { cancelled = true; };
184
186
  }, []);
185
- const shellExperience = useMemo(() => withSkyObject(experience, runtime.sky.visible, starStatus), [experience, runtime.sky.visible, starStatus]);
187
+ // The current view (App state, like the display switches). The shell's lists read one experience, filtered here once; the scene hides the same ids from `controls.viewHidden`.
188
+ const [viewId, setViewId] = useState(() => definition.views?.start ?? "");
189
+ const currentView = useMemo(() => viewById(definition.views, viewId), [definition.views, viewId]);
190
+ const viewExperience = useMemo(() => experienceInView(experience, definition.views, currentView), [experience, definition.views, currentView]);
191
+ const shellExperience = useMemo(() => withSkyObject(viewExperience, runtime.sky.visible, starStatus), [viewExperience, runtime.sky.visible, starStatus]);
186
192
  const metricsFor = useMemo(() => definition.createMetrics(experienceRuntime), [definition, experienceRuntime]);
187
193
  const glowBase = useMemo(() => baseGlowOf(runtime.bodies.map((id) => runtime.catalogue.get(id))), [runtime]);
188
194
  const storySet = definition.experience.storyPanels;
@@ -244,6 +250,7 @@ export function App({ definition, onOpenAddress, writeTitle = true, host }) {
244
250
  const updateCameraRequest = useCallback((request) => {
245
251
  controls.current.cameraRequest = request;
246
252
  }, []);
253
+ const holdCamera = useCallback(() => { controls.current.cameraRequest = { kind: "hold" }; }, []);
247
254
  const requestPanel = useCallback((id) => setPanelRequest((previous) => ({ id, serial: (previous?.serial ?? 0) + 1 })), []);
248
255
  const requestPick = useCallback((id) => setPickRequest((previous) => ({ id, serial: (previous?.serial ?? 0) + 1 })), []);
249
256
  const requestFeature = useCallback((key) => setFeatureRequest((previous) => ({ key, serial: (previous?.serial ?? 0) + 1 })), []);
@@ -266,7 +273,19 @@ export function App({ definition, onOpenAddress, writeTitle = true, host }) {
266
273
  controls.current.policy = scalePolicyFor(id, suppliedPolicies);
267
274
  setScale(id);
268
275
  }, [suppliedPolicies]);
269
- const stateNow = useCallback(() => ({ ...runtime.clock.snapshot(), ...(runtime.pacing === undefined ? {} : { auto: controls.current.paceAuto === true }) }), [runtime]);
276
+ // The view showing is read from a ref set at the switch, so a publish right after a switch already names the new view.
277
+ const viewRef = useRef(viewId);
278
+ const chooseView = useCallback((id) => {
279
+ viewRef.current = id;
280
+ controls.current.viewHidden = hiddenByView(definition.views, viewById(definition.views, id), experience);
281
+ setViewId(id);
282
+ }, [definition, experience]);
283
+ const viewIds = useMemo(() => definition.views?.views.map((view) => view.id) ?? [], [definition]);
284
+ const stateNow = useCallback(() => ({
285
+ ...runtime.clock.snapshot(),
286
+ ...(runtime.pacing === undefined ? {} : { auto: controls.current.paceAuto === true }),
287
+ ...(definition.views === undefined ? {} : { view: viewRef.current }),
288
+ }), [runtime, definition]);
270
289
  useEffect(() => {
271
290
  const id = window.setInterval(() => {
272
291
  // The readout wraps with the scene, so the shown time never rests past the end while looping.
@@ -302,9 +321,9 @@ export function App({ definition, onOpenAddress, writeTitle = true, host }) {
302
321
  useEffect(() => {
303
322
  if (host === undefined)
304
323
  return undefined;
305
- host.attach({ window: runtime.loopWindow, rates: definition.experience.rates, paced: runtime.pacing !== undefined, read: stateNow, seek: seekTo, setRate: changeRate });
324
+ host.attach({ window: runtime.loopWindow, rates: definition.experience.rates, paced: runtime.pacing !== undefined, read: stateNow, seek: seekTo, setRate: changeRate, views: viewIds, setView: chooseView });
306
325
  return () => host.detach();
307
- }, [host, runtime, definition, seekTo, changeRate]);
326
+ }, [host, runtime, definition, seekTo, changeRate, viewIds, chooseView]);
308
327
  useEffect(() => {
309
328
  if (!developerMode)
310
329
  return undefined;
@@ -333,6 +352,14 @@ export function App({ definition, onOpenAddress, writeTitle = true, host }) {
333
352
  return;
334
353
  setViewLink(await shareViewLink({ view, scaleId: scale, up: upChoice, timeUtcMs: runtime.clock.snapshot().timeUtcMs }));
335
354
  };
355
+ const viewChoice = definition.views === undefined ? undefined : {
356
+ place: definition.views.place,
357
+ options: definition.views.views.map((view) => ({ id: view.id, label: view.label, active: view.id === currentView?.id })),
358
+ onSelect: (id) => {
359
+ chooseView(id);
360
+ host?.publish(stateNow(), "visitor");
361
+ },
362
+ };
336
363
  const displaySwitches = displaySwitchItems({
337
364
  settings: definition.displaySwitches,
338
365
  orbit: { present: orbitPaths.length > 0, look: orbitShown, set: setOrbit },
@@ -433,5 +460,5 @@ export function App({ definition, onOpenAddress, writeTitle = true, host }) {
433
460
  }, onSeek: (timeUtcMs) => {
434
461
  seekTo(timeUtcMs);
435
462
  host?.publish(stateNow(), "visitor");
436
- }, onCameraRequest: updateCameraRequest, onSelectionChange: updateSelectedObject, scaleId: scale, onScaleChange: updateScale, scaleChoices: scaleChoices, switcher: switcherOf(definition, runtime, onOpenAddress), displaySwitches: displaySwitches, metricsFor: metricsFor, developerTools: developerTools, storyPanelSettings: { autoOpen: storyAutoOpen, pauseSeconds: storyPauseSeconds }, timelineGlow: timelineGlow, phoneLayout: phoneLayout, highlightedFamily: setLook.highlightFamily, onHighlightFamily: highlightFamily, onSetPlaying: setPlaying, panelRequest: panelRequest, onOpenPanelChange: markOpenPanel, featureRequest: featureRequest, pickRequest: pickRequest, onOpenFeatureChange: markOpenFeature, children: _jsx("div", { className: "canvas-host", children: _jsx(AstraeusScene, { runtime: runtime, controls: controls.current, readout: readout, scaleId: scale }) }) }));
463
+ }, onCameraRequest: updateCameraRequest, onCameraHold: holdCamera, onSelectionChange: updateSelectedObject, scaleId: scale, onScaleChange: updateScale, scaleChoices: scaleChoices, switcher: switcherOf(definition, runtime, onOpenAddress), displaySwitches: displaySwitches, viewChoice: viewChoice, viewCamera: currentView === undefined ? undefined : { id: currentView.id, rule: currentView.camera }, metricsFor: metricsFor, developerTools: developerTools, storyPanelSettings: { autoOpen: storyAutoOpen, pauseSeconds: storyPauseSeconds }, timelineGlow: timelineGlow, phoneLayout: phoneLayout, highlightedFamily: setLook.highlightFamily, onHighlightFamily: highlightFamily, onSetPlaying: setPlaying, panelRequest: panelRequest, onOpenPanelChange: markOpenPanel, featureRequest: featureRequest, pickRequest: pickRequest, onOpenFeatureChange: markOpenFeature, children: _jsx("div", { className: "canvas-host", children: _jsx(AstraeusScene, { runtime: runtime, controls: controls.current, readout: readout, scaleId: scale }) }) }));
437
464
  }