astraeus 0.3.0 → 0.5.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 (94) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +92 -11
  3. package/data/ephemerides/planets/planets.json +1 -1
  4. package/package.json +1 -1
  5. package/src/api/AstraeusScene.d.ts +9 -1
  6. package/src/api/AstraeusScene.js +26 -4
  7. package/src/api/AstraeusScene.node.js +26 -4
  8. package/src/api/activity.d.ts +1 -1
  9. package/src/api/activity.js +1 -1
  10. package/src/api/bodies.d.ts +2 -0
  11. package/src/api/bodies.js +2 -0
  12. package/src/api/data.js +11 -1
  13. package/src/api/errors.d.ts +1 -1
  14. package/src/api/index.d.ts +3 -2
  15. package/src/api/index.js +1 -1
  16. package/src/api/index.node.js +1 -1
  17. package/src/api/mount.d.ts +16 -0
  18. package/src/api/mount.js +13 -1
  19. package/src/api/mount.node.js +13 -1
  20. package/src/api/pathProvenance.d.ts +10 -0
  21. package/src/api/pathProvenance.js +34 -0
  22. package/src/api/scene.d.ts +26 -5
  23. package/src/api/scene.js +197 -44
  24. package/src/api/story.d.ts +41 -1
  25. package/src/api/story.js +63 -1
  26. package/src/api/sunOrbit.d.ts +3 -3
  27. package/src/api/sunOrbit.js +92 -24
  28. package/src/api/viewerLink.d.ts +40 -0
  29. package/src/api/viewerLink.js +86 -0
  30. package/src/app/App.d.ts +4 -1
  31. package/src/app/App.js +42 -6
  32. package/src/app/App.node.js +42 -6
  33. package/src/app/AstraeusScene.d.ts +7 -0
  34. package/src/app/BodySetView.js +3 -2
  35. package/src/app/KeplerPoints.d.ts +1 -1
  36. package/src/app/KeplerPoints.js +3 -2
  37. package/src/app/PointsView.js +3 -2
  38. package/src/app/SceneLabels.d.ts +2 -0
  39. package/src/app/SceneLabels.js +5 -1
  40. package/src/app/TrackedBodyView.d.ts +9 -3
  41. package/src/app/TrackedBodyView.js +54 -14
  42. package/src/app/bodyDraw.js +3 -2
  43. package/src/app/dotMaterial.d.ts +11 -0
  44. package/src/app/dotMaterial.js +38 -0
  45. package/src/app/experienceDefinition.d.ts +12 -0
  46. package/src/app/mission.d.ts +3 -1
  47. package/src/app/mission.js +1 -1
  48. package/src/app/openClock.d.ts +1 -1
  49. package/src/app/openClock.js +3 -0
  50. package/src/app/pathRules.d.ts +7 -3
  51. package/src/app/pathRules.js +9 -5
  52. package/src/app/sceneContentsHooks.js +2 -1
  53. package/src/app/sceneDebug.d.ts +4 -2
  54. package/src/app/sceneFrame.d.ts +2 -2
  55. package/src/app/sceneFrame.js +7 -2
  56. package/src/app/sceneFraming.d.ts +1 -1
  57. package/src/app/sceneFraming.js +9 -3
  58. package/src/app/viewerPort.d.ts +33 -0
  59. package/src/app/viewerPort.js +1 -0
  60. package/src/core/bodies/io.js +1 -1
  61. package/src/core/bodies/jupiterMoons.d.ts +1 -1
  62. package/src/core/bodies/jupiterMoons.js +6 -6
  63. package/src/core/bodies/moonSystem.d.ts +15 -1
  64. package/src/core/bodies/moonSystem.js +58 -7
  65. package/src/core/bodies/outerPlanets.js +1 -1
  66. package/src/core/bodies/planetMoons.js +10 -10
  67. package/src/core/chebyshevEphemeris.d.ts +7 -1
  68. package/src/core/chebyshevEphemeris.js +24 -7
  69. package/src/core/clock.d.ts +8 -0
  70. package/src/core/clock.js +14 -0
  71. package/src/core/pacing.d.ts +24 -0
  72. package/src/core/pacing.js +35 -0
  73. package/src/core/planetModels.d.ts +4 -1
  74. package/src/core/planetModels.js +6 -1
  75. package/src/core/planetSeries.d.ts +3 -0
  76. package/src/core/planetSeries.js +8 -1
  77. package/src/core/scalePolicy.d.ts +2 -0
  78. package/src/core/scalePolicy.js +2 -0
  79. package/src/core/timeWindow.d.ts +2 -0
  80. package/src/core/timeWindow.js +4 -3
  81. package/src/shell/AstraeusShell.d.ts +6 -2
  82. package/src/shell/AstraeusShell.js +3 -3
  83. package/src/shell/AstraeusShell.node.js +3 -3
  84. package/src/shell/TimelineBar.d.ts +4 -2
  85. package/src/shell/TimelineBar.js +15 -6
  86. package/src/shell/TimelineBar.node.js +15 -6
  87. package/src/shell/experience.d.ts +3 -1
  88. package/src/shell/infoModel.js +5 -4
  89. package/src/shell/timelineModel.d.ts +2 -3
  90. package/src/shell/timelineModel.js +3 -11
  91. package/src/synthetic/syntheticJourneyScene.d.ts +9 -0
  92. package/src/synthetic/syntheticJourneyScene.js +75 -0
  93. package/src/synthetic/syntheticProbeDefinition.d.ts +5 -0
  94. package/src/synthetic/syntheticProbeDefinition.js +38 -0
package/src/api/scene.js CHANGED
@@ -1,9 +1,12 @@
1
1
  import { createProvenance } from "../core/provenance.js";
2
+ import { planPathProvenance } from "./pathProvenance.js";
2
3
  import { SampledTrajectory } from "../core/sampledTrajectory.js";
3
- import { readableScale, trueScale } from "../core/scalePolicy.js";
4
+ import { readableScale, solarSystemScale, trueScale } from "../core/scalePolicy.js";
5
+ import { createState } from "../core/state.js";
6
+ import { createOrbTwoBodyAdapter } from "../core/twoBodyAdapter.js";
4
7
  import { createStateResolver } from "../core/stateResolver.js";
5
8
  import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
6
- import { loadPlanetSeries, planetSeriesLoaded } from "../core/planetSeries.js";
9
+ import { isPlanetId, loadPlanetSeries, planetSeriesLoaded, planetSeriesSpan } from "../core/planetSeries.js";
7
10
  import { catalogue as builtInCatalogue, extendCatalogue, rootBodyId } from "../assets/catalogue.js";
8
11
  import { buildElementsBody, ElementsBodyError, parseElementsBodyRecord } from "../core/elementsBody.js";
9
12
  import { createComposition, SIDEREAL_MONTH_MS } from "../assets/compositions.js";
@@ -13,24 +16,27 @@ import { needsPlanetSeries } from "../app/planetNeeds.js";
13
16
  import { catalogueItem } from "../app/catalogueItem.js";
14
17
  import { createReadoutMetrics } from "../app/trackedMetrics.js";
15
18
  import { circlesTheSun, farthestSunDistanceKm, sunOrbitIdOf, sunOrbitLayer } from "./sunOrbit.js";
16
- import { readyMade } from "./bodies.js";
19
+ import { FALLBACK_SCENE_CENTRE, readyMade } from "./bodies.js";
17
20
  import { installData } from "./data.js";
18
21
  import { planActivity, rateMetricOf } from "./activity.js";
19
22
  import { buildGroupLayer, planGroup } from "./group.js";
20
23
  import { SceneError } from "./errors.js";
21
24
  import { toUtcMs } from "./time.js";
22
25
  import { switchesOf } from "./switches.js";
23
- import { eventProvenanceOf, eventsOf, panelsOf, timelineOf } from "./story.js";
26
+ import { TimeScaleOutOfRangeError } from "../core/timeScale.js";
27
+ import { eventProvenanceOf, eventsOf, pacingFor, panelsOf, timelineOf } from "./story.js";
24
28
  export { toUtcMs } from "./time.js";
25
- /** The orbits the engine can draw: the parent the line is measured from, and the span one lap covers. */
29
+ /** The orbits the engine can draw: the span one lap covers (the parent the line is measured from is the body's catalogue parent). */
26
30
  const ORBITS = {
27
- moon: { parent: "earth", path: { spanMs: SIDEREAL_MONTH_MS } },
28
- io: { parent: "jupiter", path: { spanMs: IO_PERIOD_DAYS * 86_400_000, look: { endFadeOn: false } } },
31
+ moon: { path: { spanMs: SIDEREAL_MONTH_MS } },
32
+ io: { path: { spanMs: IO_PERIOD_DAYS * 86_400_000, look: { endFadeOn: false } } },
29
33
  };
30
34
  const DEFAULT_COLOR = "#ffd27a";
31
35
  const DAY_MS = 86_400_000;
32
36
  const PROVIDER_PATH_SAMPLES = 128;
33
- const SCALES = [trueScale, readableScale];
37
+ const SCALES = [trueScale, readableScale, solarSystemScale];
38
+ /** Samples along a path when its farthest distance is read for the default zoom-out. */
39
+ const PATH_COVER_SAMPLES = 400;
34
40
  /** The scene's camera: what it opens on. */
35
41
  export class SceneCamera {
36
42
  #target;
@@ -117,10 +123,13 @@ export class Scene {
117
123
  camera;
118
124
  #bodies = new Map();
119
125
  #tracked = new Map();
126
+ /** Paths added without a `center`: they follow the scene's first body, so one added before any body is rebuilt when the first body arrives. */
127
+ #defaulted = new Map();
120
128
  #groups = new Map();
121
129
  #activities = new Map();
122
130
  #orbits = new Set();
123
131
  #own = new Map();
132
+ #labelReaches = new Map();
124
133
  #shape = new Map();
125
134
  #catalogue = builtInCatalogue;
126
135
  #notes = new Map();
@@ -171,12 +180,14 @@ export class Scene {
171
180
  }
172
181
  #register(call, id, ref, options) {
173
182
  if (options.orbit === true && ORBITS[id] === undefined && !(circlesTheSun(this.#catalogue, id)))
174
- throw new SceneError("no-orbit", `${call}("${id}", { orbit: true }): the engine draws the orbit line of ${Object.keys(ORBITS).join(" and ")} and of any body that circles the Sun`);
183
+ throw new SceneError("no-orbit", `${call}("${id}", { orbit: true }): the engine draws the orbit line of ${Object.keys(ORBITS).join(" and ")} 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)`);
175
184
  if (!this.#catalogue.has(id))
176
185
  throw new SceneError("unknown-body", `${call}("${id}"): not a catalogued body (known: ${this.#catalogue.ids().join(", ")})`);
177
186
  if (this.#taken(id))
178
187
  throw new SceneError("duplicate-id", `${call}("${id}"): already in the scene`);
179
188
  checkBodyLook(id, options);
189
+ if (options.labelReach !== undefined)
190
+ this.#labelReaches.set(id, options.labelReach);
180
191
  if (options.orbit === true)
181
192
  this.#orbits.add(id);
182
193
  if (options.color !== undefined || options.knownLimitations !== undefined)
@@ -186,6 +197,9 @@ export class Scene {
186
197
  if (options.description !== undefined)
187
198
  this.#notes.set(id, options.description);
188
199
  this.#bodies.set(id, ref);
200
+ if (this.#bodies.size === 1 && builtInCatalogue.has(id))
201
+ for (const input of this.#defaulted.values())
202
+ this.#buildTracked(input, id);
189
203
  }
190
204
  /** Adds a path to follow and draw, from sampled states or a provider with `stateAt(time)`. */
191
205
  addTrajectory(input) {
@@ -194,15 +208,34 @@ export class Scene {
194
208
  throw new SceneError("bad-trajectory", "addTrajectory: the trajectory needs a non-empty id");
195
209
  if (this.#taken(id))
196
210
  throw new SceneError("duplicate-id", `addTrajectory("${id}"): that id is already in the scene`);
197
- const center = input.center ?? "earth";
211
+ this.#buildTracked(input, input.center ?? this.#sceneCentre());
212
+ if (input.center === undefined)
213
+ this.#defaulted.set(id, input);
214
+ return this;
215
+ }
216
+ /** The scene's centre: its first body when that is a built-in one, else Earth (the default of a path added before any body; `#register` re-reads it when the first body arrives). */
217
+ #sceneCentre() {
218
+ const first = this.#bodies.keys().next();
219
+ return first.done === true || !builtInCatalogue.has(first.value) ? FALLBACK_SCENE_CENTRE : first.value;
220
+ }
221
+ /** Validates and stores one path about `center`. */
222
+ #buildTracked(input, center) {
223
+ const id = input.id;
198
224
  if (!builtInCatalogue.has(center))
199
225
  throw new SceneError("unknown-body", `addTrajectory("${id}"): centre "${center}" is not a catalogued body`);
200
226
  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." });
201
- const common = { id, label: input.label ?? id, color: input.color ?? DEFAULT_COLOR, anchorTimesUtcMs: [], provenance };
227
+ const common = { id, label: input.label ?? id, color: input.color ?? DEFAULT_COLOR, anchorTimesUtcMs: [], provenance, ...(input.lineFixedTo === undefined ? {} : { lineFixedTo: input.lineFixedTo }) };
202
228
  const readouts = readoutsOf(id, input.readouts);
203
- const body = "samples" in input ? sampledBody(common, input, center) : providerBody(common, input);
204
- this.#tracked.set(id, { center, body: withAnchors(body, input.anchors), readouts, ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) });
205
- return this;
229
+ if (input.labelReach !== undefined) {
230
+ checkLabelReach(input.labelReach, new SceneError("bad-trajectory", `addTrajectory("${id}"): labelReach ${String(input.labelReach)} must be a positive finite number`));
231
+ this.#labelReaches.set(id, input.labelReach);
232
+ }
233
+ if (input.plane !== undefined && input.plane !== "EQJ" && input.plane !== "ecliptic-j2000")
234
+ throw new SceneError("bad-trajectory", `addTrajectory("${id}"): plane "${String(input.plane)}" must be "EQJ" or "ecliptic-j2000"`);
235
+ const toEqj = input.plane === "ecliptic-j2000" ? createOrbTwoBodyAdapter().eclipticJ2000ToEqjMatrix() : null;
236
+ const body = "samples" in input ? sampledBody(common, input, center, toEqj) : providerBody(common, input, toEqj);
237
+ const provenanceSpans = input.provenanceSpans === undefined ? undefined : planPathProvenance(id, input.provenanceSpans, { startUtcMs: body.trajectory.bounds.startUtcMs, endUtcMs: body.trajectory.bounds.endUtcMs });
238
+ 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 }) });
206
239
  }
207
240
  /** Whether a body, path or group already has this id. */
208
241
  #taken(id) {
@@ -239,10 +272,10 @@ export class Scene {
239
272
  this.#timeUtcMs = toUtcMs(time, "setTime");
240
273
  return this;
241
274
  }
242
- /** Chooses the opening scale: `trueScale` or `readableScale`; the viewer can switch to the other (in a Sun-centred scene with an enlarged body, to the \"solar-system\" scale instead of the readable one), unless `{ only: true }` offers this scale alone. */
275
+ /** Chooses the opening scale: `trueScale`, `readableScale` or `solarSystemScale` (true distances, the enlarged bodies drawn larger; it needs a Sun-centred scene with an enlarged body, else the scene throws `bad-scale`); the viewer can switch to the other (in a Sun-centred scene with an enlarged body, the second choice is the Solar system scale instead of the readable one), unless `{ only: true }` offers this scale alone. */
243
276
  setScale(scale, options = {}) {
244
277
  if (!SCALES.some((known) => known.id === scale?.id))
245
- throw new SceneError("bad-scale", `setScale: "${String(scale?.id)}" is not a scale; use trueScale or readableScale`);
278
+ throw new SceneError("bad-scale", `setScale: "${String(scale?.id)}" is not a scale; use trueScale, readableScale or solarSystemScale`);
246
279
  this.#scale = scale;
247
280
  this.#scaleOnly = options.only === true;
248
281
  return this;
@@ -267,7 +300,7 @@ export class Scene {
267
300
  this.#panels = panels;
268
301
  return this;
269
302
  }
270
- /** Sets the timeline: its span (`start`, `end`), the speeds offered (`rates`), the speed it opens at (`rate`) and whether playback wraps from the end to the start (`loop`; ignored with `{ none: true }`, which has no span to wrap, and when `setTimeline` is not called), or `{ none: true }` for no timeline bar, with time frozen at `at` or running at `rate`. Without this call the span follows the paths and the speeds are 1 minute, 1 hour and 1 day per second. */
303
+ /** Sets the timeline: its span (`start`, `end`), the speeds offered (`rates`), the speed it opens at (`rate`), `pacing` (playback that slows for encounters and speeds up for cruise: spans `{ from, to, rate }` and event rules `{ near: { type, within }, rate }`, easing between speeds; a speed the visitor or host picks wins until `setRate("auto")`; see `PacingInput`) and whether playback wraps from the end to the start (`loop`; ignored with `{ none: true }`, which has no span to wrap, and when `setTimeline` is not called), or `{ none: true }` for no timeline bar, with time frozen at `at` or running at `rate`. Without this call the span follows the paths and the speeds are 1 minute, 1 hour and 1 day per second. */
271
304
  setTimeline(timeline) {
272
305
  this.#timeline = timelineOf(timeline);
273
306
  return this;
@@ -365,6 +398,10 @@ export class Scene {
365
398
  #earlySunPaths(orbitIds, openUtcMs) {
366
399
  return planetSeriesLoaded() ? orbitIds.map((id) => this.#sunPath(id, openUtcMs)) : [];
367
400
  }
401
+ #checkSolarSystemScale(sunCentred) {
402
+ if (this.#scale.id === solarSystemScale.id && !this.#enlargedInSun(sunCentred))
403
+ throw new SceneError("bad-scale", "setScale: the Solar system scale needs a Sun-centred scene with an enlarged body (addBody(x, { enlarge }))");
404
+ }
368
405
  /** Whether a Sun-centred scene enlarges a body, which the viewer's solar-system scale draws. */
369
406
  #enlargedInSun(sunCentred) {
370
407
  return sunCentred && [...this.#shape.values()].some((shape) => shape.enlarge !== undefined);
@@ -390,6 +427,54 @@ export class Scene {
390
427
  }
391
428
  }
392
429
  }
430
+ /** The `out-of-span` error naming the planets when the scene's window reaches outside the years the planet series cover (the series are loaded); undefined otherwise. */
431
+ #planetSpanError(ids, window) {
432
+ const planets = ids.filter(isPlanetId);
433
+ if (planets.length === 0 || !planetSeriesLoaded())
434
+ return undefined;
435
+ const span = planetSeriesSpan();
436
+ if (window.startUtcMs >= span.startUtcMs && window.endUtcMs <= span.endUtcMs)
437
+ return undefined;
438
+ const iso = (ms) => new Date(ms).toISOString().slice(0, 10);
439
+ return new SceneError("out-of-span", `${planets.join(", ")} is outside the years the built-in planet series covers: it covers ${iso(span.startUtcMs)} to ${iso(span.endUtcMs)}, but the scene runs ${iso(window.startUtcMs)} to ${iso(window.endUtcMs)}; set the timeline inside that span`);
440
+ }
441
+ /** Throws `out-of-span` naming the planets when the scene's window reaches outside the years the planet series cover (the series are loaded). */
442
+ #checkPlanetSpan(ids, window) {
443
+ const error = this.#planetSpanError(ids, window);
444
+ if (error !== undefined)
445
+ throw error;
446
+ }
447
+ /**
448
+ * The one choke point for planet-series reads during setup (orbit lines, the fit distance, clump groups): checks the span first, and turns a
449
+ * `TimeScaleOutOfRangeError` from the read into the named `out-of-span` error when the window is outside the series, so no setup read can leak the raw one.
450
+ */
451
+ #planetRead(ids, window, read) {
452
+ this.#checkPlanetSpan(ids, window);
453
+ try {
454
+ return read();
455
+ }
456
+ catch (error) {
457
+ if (error instanceof TimeScaleOutOfRangeError)
458
+ throw this.#planetSpanError(ids, window) ?? error;
459
+ throw error;
460
+ }
461
+ }
462
+ /**
463
+ * A setup read in `toDefinition`: an `out-of-span` failure is recorded in `fault` and the read gives `fallback`, so `toDefinition` (and so `mount`) never throws it;
464
+ * `prepare` rejects with the recorded error, which is how it always arrives (once, as `ready` rejecting).
465
+ */
466
+ #deferredRead(ids, window, fault, fallback, read) {
467
+ try {
468
+ return this.#planetRead(ids, window, read);
469
+ }
470
+ catch (error) {
471
+ if (error instanceof SceneError && error.code === "out-of-span") {
472
+ fault.error ??= error;
473
+ return fallback;
474
+ }
475
+ throw error;
476
+ }
477
+ }
393
478
  /** Throws `missing-data` naming the bodies whose data package was not passed. */
394
479
  #checkData(data) {
395
480
  const missing = this.missingData(data);
@@ -402,21 +487,26 @@ export class Scene {
402
487
  #moonPaths() {
403
488
  return [...this.#orbits].filter((id) => ORBITS[id] !== undefined).map((id) => {
404
489
  const orbit = ORBITS[id];
405
- if (!this.#bodies.has(orbit.parent))
406
- throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about ${orbit.parent}, which has not been added to the scene`);
490
+ const parent = this.#catalogue.get(id).definition.parentId;
491
+ if (parent === undefined || !this.#bodies.has(parent))
492
+ throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about ${parent}, which has not been added to the scene`);
407
493
  return { body: id, ...orbit.path };
408
494
  });
409
495
  }
410
- /** Whether the scene is centred on the Sun; such a scene cannot hold a tracked path. */
496
+ /** Whether the scene is centred on the Sun. */
411
497
  #checkSunCentred(ids) {
412
- const sunCentred = ids[0] === rootBodyId(this.#catalogue);
413
- if (sunCentred && this.#tracked.size > 0)
414
- throw new SceneError("bad-trajectory", `addTrajectory("${[...this.#tracked.keys()][0]}"): a scene centred on the Sun cannot hold a tracked path yet; centre the scene on Earth or another body`);
415
- return sunCentred;
498
+ return ids[0] === rootBodyId(this.#catalogue);
499
+ }
500
+ /** How far a label shows, for bodies and paths alike: the item's own `labelReach` if given, else the shared rule: a Sun-centred scene, or one that fits the zoom-out to an orbit (`fitOrbit`, whose limit changes with the canvas), sets no limit; otherwise the camera reach, at least 500. */
501
+ #labelReach(id, sunCentred) {
502
+ const own = this.#labelReaches.get(id);
503
+ if (own !== undefined)
504
+ return { labelMaxDistance: own };
505
+ return sunCentred || this.camera.fitted !== undefined ? {} : { labelMaxDistance: Math.max(500, this.camera.reach ?? 0) };
416
506
  }
417
- /** The shell item of a body: from the catalogue, with the scene's own words, look and label setting. A Sun-centred scene, or one that fits the zoom-out to an orbit (`fitOrbit`, whose limit changes with the canvas), sets no label limit, so labels stay shown at any distance. */
507
+ /** The shell item of a body: from the catalogue, with the scene's own words, look and label setting. Label reach is `#labelReach`. */
418
508
  #bodyObject(body, ids, sunCentred) {
419
- const own = { labelPriority: 100 - ids.indexOf(body.id), ...(sunCentred || this.camera.fitted !== undefined ? {} : { labelMaxDistance: Math.max(500, this.camera.reach ?? 0) }), ...(this.#shape.get(body.id)?.showLabel === undefined ? {} : { showLabel: this.#shape.get(body.id).showLabel }), ...(this.#notes.has(body.id) ? { description: this.#notes.get(body.id) } : {}), ...this.#looks.get(body.id) };
509
+ const own = { labelPriority: 100 - ids.indexOf(body.id), ...this.#labelReach(body.id, sunCentred), ...(this.#shape.get(body.id)?.showLabel === undefined ? {} : { showLabel: this.#shape.get(body.id).showLabel }), ...(this.#notes.has(body.id) ? { description: this.#notes.get(body.id) } : {}), ...this.#looks.get(body.id) };
420
510
  return { ...catalogueItem(body.id, own, this.#catalogue), label: body.label };
421
511
  }
422
512
  /** The event provenance entries of the experience: the batch's, and each event's own. */
@@ -436,23 +526,47 @@ export class Scene {
436
526
  return id;
437
527
  });
438
528
  }
529
+ /**
530
+ * The distance the default zoom-out must cover for the scene's paths about the scene centre (I-114): a path reaching past the planets must fit whole whichever point of it the camera looks at,
531
+ * so twice its farthest distance from the centre (no two points of a path are farther apart than that). Sampled over each path's span; undefined when no path is about the centre.
532
+ */
533
+ #pathCover(sunCentred, centre) {
534
+ if (!sunCentred)
535
+ return undefined;
536
+ const about = [...this.#tracked.values()].filter((entry) => entry.center === centre);
537
+ if (about.length === 0)
538
+ return undefined;
539
+ return () => 2 * Math.max(...about.map(({ body }) => {
540
+ const { startUtcMs, endUtcMs } = body.trajectory.bounds;
541
+ let farthest = 0;
542
+ for (let k = 0; k < PATH_COVER_SAMPLES; k += 1)
543
+ farthest = Math.max(farthest, Math.hypot(...body.trajectory.stateAt(Math.round(startUtcMs + ((endUtcMs - startUtcMs) * k) / (PATH_COVER_SAMPLES - 1)), centre).positionKm));
544
+ return farthest;
545
+ }));
546
+ }
439
547
  /** The fitted body's farthest Sun distance, read once when the viewer first needs it (a planet's reads the planet series, loaded by then); undefined when no orbit is fitted. */
440
548
  #fitFarthestKm(openUtcMs) {
441
549
  const id = this.camera.fitted;
442
550
  if (id === undefined)
443
551
  return undefined;
444
552
  let km;
445
- return () => (km ??= farthestSunDistanceKm(this.#catalogue, id, openUtcMs, this.#own.get(id)));
553
+ const read = () => (km ??= farthestSunDistanceKm(this.#catalogue, id, openUtcMs, this.#own.get(id)));
554
+ if (planetSeriesLoaded())
555
+ read();
556
+ return { read, settle: () => void read() };
446
557
  }
447
558
  /** One Sun-orbit line: one full turn from the opening time (an own body from its periapsis). Reads planet positions, so the planet series must be loaded. */
448
559
  #sunPath(id, openUtcMs) {
449
560
  const layer = sunOrbitLayer(this.#catalogue, id, openUtcMs, this.#looks.get(id)?.color ?? "", this.#own.get(id));
450
561
  if (layer === undefined)
451
- throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): "${id}" completes no turn within a dozen years and the catalogue does not know its period; add it with addBodyFromElements to draw its whole orbit`);
562
+ 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`);
452
563
  return layer;
453
564
  }
454
- /** A readout names a body the scene must hold, so it can be measured against. */
565
+ /** A readout, or the body the line is fixed to, names a body the scene must hold. */
455
566
  #checkReadouts(entry, ids) {
567
+ const fixed = entry.body.lineFixedTo;
568
+ if (fixed !== undefined && !ids.includes(fixed))
569
+ throw new SceneError("bad-trajectory", `addTrajectory("${entry.body.id}"): lineFixedTo names "${fixed}", which has not been added to the scene`);
456
570
  for (const spec of entry.readouts) {
457
571
  const named = readoutBody(spec);
458
572
  if (named !== undefined && !ids.includes(named))
@@ -474,14 +588,18 @@ export class Scene {
474
588
  const ids = [...this.#bodies.keys()];
475
589
  const paths = this.#moonPaths();
476
590
  const sunCentred = this.#checkSunCentred(ids);
591
+ this.#checkSolarSystemScale(sunCentred);
477
592
  for (const entry of this.#tracked.values())
478
593
  this.#checkReadouts(entry, ids);
479
594
  const tracked = [...this.#tracked.values()].map((entry) => entry.body);
480
595
  const timeline = this.#timeline;
481
596
  const { window, startUtcMs } = spanOf(timeline, this.#timeUtcMs, [...tracked.map((body) => body.trajectory.bounds), ...[...this.#activities.values()].map((activity) => activity.window)]);
482
597
  const sunOrbitIds = this.#sunOrbitIds(ids);
598
+ // 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.
599
+ const fault = {};
600
+ const fit = this.#deferredRead(ids, window, fault, undefined, () => this.#fitFarthestKm(startUtcMs));
483
601
  // 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.
484
- const sunPaths = this.#earlySunPaths(sunOrbitIds, startUtcMs);
602
+ const sunPaths = this.#deferredRead(ids, window, fault, [], () => this.#earlySunPaths(sunOrbitIds, startUtcMs));
485
603
  const target = this.camera.target;
486
604
  const view = this.camera.view;
487
605
  const storyPanels = this.#storyPanels(window);
@@ -489,14 +607,14 @@ export class Scene {
489
607
  // A clump near a body reads its position; with the planet series not loaded yet, those groups are built in `prepare` (the viewer draws only after it resolves).
490
608
  const seriesIn = planetSeriesLoaded();
491
609
  const late = (plan) => !seriesIn && plan.input.clump !== undefined;
492
- const layers = [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))];
610
+ const layers = this.#deferredRead(ids, window, fault, [], () => [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))]);
493
611
  const labelled = [...this.#bodies.values(), ...tracked, ...[...this.#groups.values()]].map(({ id, label }) => ({ id, label }));
494
612
  const catalogue = this.#catalogue;
495
613
  const definition = {
496
614
  experience: {
497
615
  objects: [
498
616
  ...[...this.#bodies.values()].map((body) => this.#bodyObject(body, ids, sunCentred)),
499
- ...[...this.#tracked.values()].map(({ body, description, knownLimitations }) => ({ id: body.id, label: body.label, color: body.color, availability: body.trajectory.bounds, labelPriority: 80, labelMaxDistance: 4, provenance: body.provenance, ...(description === undefined ? {} : { description }), ...(knownLimitations === undefined ? {} : { knownLimitations }) })),
617
+ ...[...this.#tracked.values()].map(({ body, description, knownLimitations, provenanceSpans }) => ({ id: body.id, label: body.label, color: body.color, availability: body.trajectory.bounds, labelPriority: 80, ...this.#labelReach(body.id, sunCentred), provenance: body.provenance, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(description === undefined ? {} : { description }), ...(knownLimitations === undefined ? {} : { knownLimitations }) })),
500
618
  ],
501
619
  cameraPresets: cameraPresetsOf(labelled),
502
620
  ...(target === undefined ? {} : { startCameraPresetId: `${this.camera.following ? "follow" : "focus"}-${target}` }),
@@ -509,6 +627,7 @@ export class Scene {
509
627
  rates: timeline?.rates ?? [60, 3_600, DAY_MS / 1000],
510
628
  },
511
629
  clock: clockOf(timeline, startUtcMs),
630
+ ...pacingEntry(timeline, this.#events),
512
631
  ...groupLayersEntry(layers, this.#groups.size > 0, sunOrbitIds.length > 0),
513
632
  ...(sunOrbitIds.length === 0 ? {} : { paths: sunPaths }),
514
633
  ...(this.#own.size === 0 ? {} : { catalogue: this.#catalogue }),
@@ -516,7 +635,7 @@ export class Scene {
516
635
  composition: createComposition(this.#catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
517
636
  scaleChoices: scaleChoicesOf(this.#scale, this.#scaleOnly, this.#enlargedInSun(sunCentred)),
518
637
  ...(this.#switches === undefined ? {} : { displaySwitches: this.#switches }),
519
- ...viewEntries(timeline, this.camera, this.#fitFarthestKm(startUtcMs)),
638
+ ...viewEntries(timeline, this.camera, fit?.read, this.#pathCover(sunCentred, ids[0])),
520
639
  ...(target === undefined ? {} : { startView: { focus: target, azimuthDeg: view.azimuthDeg ?? 0, elevationDeg: view.elevationDeg ?? 30, distance: view.distance ?? 40 } }),
521
640
  trackedBodies: tracked,
522
641
  createMetrics: ({ resolver }) => {
@@ -525,12 +644,17 @@ export class Scene {
525
644
  return (objectId, timeUtcMs) => (this.#groups.has(objectId) ? this.#groupMetrics(objectId, timeUtcMs) : this.#tracked.has(objectId) ? readouts(objectId, timeUtcMs) : catalogued(objectId, timeUtcMs));
526
645
  },
527
646
  prepare: async () => {
647
+ if (fault.error !== undefined)
648
+ throw fault.error;
528
649
  if (needsPlanetSeries(definition) || sunPaths.length < sunOrbitIds.length || this.#groups.size > layers.length)
529
650
  await loadPlanetSeries();
651
+ this.#checkPlanetSpan(ids, window);
530
652
  if (this.#groups.size > layers.length)
531
- layers.push(...this.#groupLayers(ids, window, startUtcMs, late));
653
+ layers.push(...this.#planetRead(ids, window, () => this.#groupLayers(ids, window, startUtcMs, late)));
532
654
  if (sunPaths.length < sunOrbitIds.length)
533
- sunPaths.push(...sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs)));
655
+ sunPaths.push(...this.#planetRead(ids, window, () => sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs))));
656
+ if (fit !== undefined)
657
+ this.#planetRead(ids, window, () => fit.settle());
534
658
  await installData(data, ids, window);
535
659
  },
536
660
  };
@@ -538,12 +662,13 @@ export class Scene {
538
662
  }
539
663
  }
540
664
  /** The playback and camera settings the scene asked for: looping, the farthest zoom-out and the ecliptic up. */
541
- function viewEntries(timeline, camera, farthestKm) {
665
+ function viewEntries(timeline, camera, farthestKm, cover) {
542
666
  const { reach, view, target } = camera;
543
667
  return {
544
668
  ...(timeline?.loop === true ? { loop: true } : {}),
545
669
  ...(reach === undefined ? {} : { camera: { maxFocusDistance: reach, far: reach * 2.5 } }),
546
670
  ...(farthestKm === undefined ? {} : { camera: { fitOrbit: { farthestKm } } }),
671
+ ...(reach !== undefined || farthestKm !== undefined || cover === undefined ? {} : { camera: { cover: { farthestKm: cover } } }),
547
672
  ...(view.up === undefined || target === undefined ? {} : { viewUp: view.up }),
548
673
  };
549
674
  }
@@ -592,20 +717,35 @@ function spanOf(timeline, timeUtcMs, tracked) {
592
717
  }
593
718
  return { window, startUtcMs: setTime ?? now ?? window.startUtcMs };
594
719
  }
720
+ /** The pacing the timeline asked for, laid over the scene's events; a rule naming an event type with no events throws `bad-timeline`. */
721
+ function pacingEntry(timeline, events) {
722
+ const pacing = timeline === undefined ? undefined : pacingFor(timeline, events, timeline.rate ?? 60);
723
+ return pacing === undefined ? {} : { pacing };
724
+ }
595
725
  /** The clock's opening: 60 times real time unless set; with no timeline and no rate, frozen. */
596
726
  function clockOf(timeline, startUtcMs) {
597
727
  return { startUtcMs, rate: timeline?.rate ?? 60, ...(timeline?.none === true && timeline.rate === undefined ? { playing: false } : {}) };
598
728
  }
599
729
  /**
600
730
  * The scale choices offered: the opening one first, then the other unless the caller offered one alone. A Sun-centred scene with an enlarged body (`addBody(x, { enlarge })`)
601
- * offers the viewer's "solar-system" scale (true distances, the named bodies enlarged) in place of the readable scale it would offer second, since the readable scale does not enlarge.
731
+ * offers `solarSystemScale` (true distances, the named bodies enlarged) in place of the readable scale it would offer second, since the readable scale does not enlarge.
602
732
  */
603
733
  function scaleChoicesOf(scale, only, enlarged) {
604
- const second = SCALES.filter((other) => other.id !== scale.id).map((other) => (enlarged && other.id === readableScale.id ? "solar-system" : other.id));
605
- return only ? [scale.id] : [scale.id, ...second];
734
+ const offered = [trueScale, enlarged ? solarSystemScale : readableScale];
735
+ const second = scale.id === readableScale.id ? [trueScale] : offered.filter((other) => other.id !== scale.id);
736
+ return only ? [scale.id] : [scale.id, ...second.map((other) => other.id)];
737
+ }
738
+ /** Rotates a vector by a row-major 3x3 matrix; a missing matrix leaves it as it is. Input that is not three numbers passes through for the State checks to refuse. */
739
+ function rotated(matrix, v) {
740
+ if (matrix === null || v === undefined || v.length !== 3)
741
+ return v;
742
+ return [0, 1, 2].map((row) => matrix[3 * row] * v[0] + matrix[3 * row + 1] * v[1] + matrix[3 * row + 2] * v[2]);
606
743
  }
607
- function sampledBody(common, input, center) {
608
- const samples = input.samples.map((sample, index) => ({ ...sample, timeUtcMs: toUtcMs(sample.time, `addTrajectory("${common.id}") sample ${index} time`) }));
744
+ function sampledBody(common, input, center, toEqj) {
745
+ const samples = input.samples.map((sample, index) => {
746
+ const velocityKmS = rotated(toEqj, sample.velocityKmS);
747
+ return { positionKm: rotated(toEqj, sample.positionKm), ...(velocityKmS === undefined ? {} : { velocityKmS }), timeUtcMs: toUtcMs(sample.time, `addTrajectory("${common.id}") sample ${index} time`) };
748
+ });
609
749
  try {
610
750
  const trajectory = new SampledTrajectory({ body: common.id, center, samples });
611
751
  return { ...common, trajectory, pathTimesUtcMs: samples.map((sample) => sample.timeUtcMs) };
@@ -616,16 +756,22 @@ function sampledBody(common, input, center) {
616
756
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): ${error instanceof Error ? error.message : String(error)}`);
617
757
  }
618
758
  }
619
- function providerBody(common, input) {
759
+ function providerBody(common, input, toEqj) {
620
760
  if (typeof input.provider?.stateAt !== "function")
621
761
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): provider needs a stateAt(time) function`);
622
762
  const bounds = { startUtcMs: toUtcMs(input.bounds?.start, `addTrajectory("${common.id}") bounds.start`), endUtcMs: toUtcMs(input.bounds?.end, `addTrajectory("${common.id}") bounds.end`) };
623
763
  if (bounds.endUtcMs <= bounds.startUtcMs)
624
764
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): bounds must end after they start`);
625
- const trajectory = { body: common.id, bounds, stateAt: (timeUtcMs, center) => input.provider.stateAt(timeUtcMs, center) };
765
+ const trajectory = { body: common.id, bounds, stateAt: (timeUtcMs, center) => rotatedState(toEqj, input.provider.stateAt(timeUtcMs, center)) };
626
766
  const step = (bounds.endUtcMs - bounds.startUtcMs) / (PROVIDER_PATH_SAMPLES - 1);
627
767
  return { ...common, trajectory, pathTimesUtcMs: Array.from({ length: PROVIDER_PATH_SAMPLES }, (_, index) => bounds.startUtcMs + index * step) };
628
768
  }
769
+ /** A provider's State with its position and velocity rotated into EQJ; unchanged for EQJ input. */
770
+ function rotatedState(matrix, state) {
771
+ if (matrix === null)
772
+ return state;
773
+ return createState({ body: state.body, center: state.center, timeUtcMs: state.timeUtcMs, positionKm: rotated(matrix, state.positionKm), ...(state.velocityKmS === undefined ? {} : { velocityKmS: rotated(matrix, state.velocityKmS) }), orientation: state.orientation });
774
+ }
629
775
  /** The timeline span: the union of the trajectories' and activities' spans, else a month about the chosen time (or about now). */
630
776
  function windowOf(tracked, timeUtcMs) {
631
777
  if (tracked.length > 0) {
@@ -637,8 +783,15 @@ function windowOf(tracked, timeUtcMs) {
637
783
  const centre = timeUtcMs ?? Date.now();
638
784
  return { startUtcMs: centre - 15 * DAY_MS, endUtcMs: centre + 15 * DAY_MS };
639
785
  }
640
- /** Checks the colour and known limits given to `addBody`. */
786
+ /** Throws `error` unless `reach` is a positive finite number. */
787
+ function checkLabelReach(reach, error) {
788
+ if (!(typeof reach === "number" && Number.isFinite(reach) && reach > 0))
789
+ throw error;
790
+ }
791
+ /** Checks the colour, known limits and label reach given to `addBody`. */
641
792
  function checkBodyLook(id, options) {
793
+ if (options.labelReach !== undefined)
794
+ checkLabelReach(options.labelReach, new SceneError("bad-body", `addBody("${id}"): labelReach ${String(options.labelReach)} must be a positive finite number`));
642
795
  if (options.enlarge !== undefined && !(typeof options.enlarge === "number" && Number.isFinite(options.enlarge) && options.enlarge >= 1))
643
796
  throw new SceneError("bad-body", `addBody("${id}"): enlarge ${String(options.enlarge)} must be a number of at least 1`);
644
797
  if (options.showLabel !== undefined && typeof options.showLabel !== "boolean")
@@ -1,4 +1,5 @@
1
1
  import { type TimelineEvent } from "../core/events.js";
2
+ import type { Pacing } from "../core/pacing.js";
2
3
  import { type Provenance } from "../core/provenance.js";
3
4
  import type { TimeBounds } from "../core/trajectory.js";
4
5
  import { type PanelLookup, type StoryPanelSet } from "../shell/storyPanels.js";
@@ -27,7 +28,8 @@ export type TimelineInput = {
27
28
  readonly start: TimeInput;
28
29
  readonly end: TimeInput;
29
30
  readonly rates?: readonly number[];
30
- readonly rate?: number; /** True: while playing, reaching the end wraps to the start and plays on. The viewer can still seek and pause. Default false. Not available with `none: true`, where it is ignored. */
31
+ readonly rate?: number; /** Playback that slows for encounters and speeds up for cruise: see `PacingInput`. */
32
+ readonly pacing?: readonly PacingInput[]; /** True: while playing, reaching the end wraps to the start and plays on. The viewer can still seek and pause. Default false. Not available with `none: true`, where it is ignored. */
31
33
  readonly loop?: boolean;
32
34
  readonly none?: undefined;
33
35
  } | {
@@ -35,6 +37,37 @@ export type TimelineInput = {
35
37
  readonly at?: TimeInput;
36
38
  readonly rate?: number;
37
39
  };
40
+ /**
41
+ * One piece of a timeline's pacing. A span `{ from, to, rate }` plays at `rate` between two moments; an event rule `{ near: { type, within }, rate }` plays at `rate`
42
+ * within `within` seconds (simulated) of every event of that `type` (see `addEvents`). Outside every piece playback runs at the timeline's `rate`. Between a piece and
43
+ * what surrounds it the speed eases over `ramp` simulated seconds (default: `within` for an event rule, a tenth of the span for a span). `rate` here is any positive number;
44
+ * it need not be one of the offered `rates`. Spans may not overlap (touching is fine); where an event rule meets a span or another rule, the slowest speed wins, whichever contains the other and in whatever order they are listed.
45
+ */
46
+ export type PacingInput = {
47
+ readonly from: TimeInput;
48
+ readonly to: TimeInput;
49
+ readonly rate: number;
50
+ readonly ramp?: number;
51
+ } | {
52
+ readonly near: {
53
+ readonly type: string;
54
+ readonly within: number;
55
+ };
56
+ readonly rate: number;
57
+ readonly ramp?: number;
58
+ };
59
+ /** A checked pacing piece: moments as Unix milliseconds, seconds as milliseconds. */
60
+ export type PacingPiece = {
61
+ readonly fromUtcMs: number;
62
+ readonly toUtcMs: number;
63
+ readonly rate: number;
64
+ readonly rampMs: number;
65
+ } | {
66
+ readonly type: string;
67
+ readonly withinMs: number;
68
+ readonly rate: number;
69
+ readonly rampMs: number;
70
+ };
38
71
  /** What `setTimeline` was given, checked and converted. */
39
72
  export interface TimelineSetting {
40
73
  readonly window?: TimeBounds;
@@ -42,6 +75,8 @@ export interface TimelineSetting {
42
75
  readonly rate?: number;
43
76
  /** Playback wraps from the end of the span to its start. */
44
77
  readonly loop?: boolean;
78
+ /** The checked pacing pieces (absent: none). */
79
+ readonly pacing?: readonly PacingPiece[];
45
80
  /** No timeline bar. */
46
81
  readonly none: boolean;
47
82
  /** For no timeline: the moment time is frozen at, or runs on from. */
@@ -67,3 +102,8 @@ export declare function eventsOf(inputs: readonly EventInput[], known: readonly
67
102
  export declare function timelineOf(input: TimelineInput): TimelineSetting;
68
103
  /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
69
104
  export declare function panelsOf(raw: StoryPanelsInput, lookup: PanelLookup): StoryPanelSet;
105
+ /**
106
+ * The pacing the viewer runs, laid over the events: spans, then one zone per event of each rule's type. `pacedRate` lays the zones fastest first, so the slowest applicable piece wins wherever they meet, whatever contains what.
107
+ * A rule whose type has no event throws `bad-timeline` naming the piece (a mistyped type would otherwise slow nothing, silently).
108
+ */
109
+ export declare function pacingFor(setting: TimelineSetting, events: readonly TimelineEvent[], baseRate: number): Pacing | undefined;
package/src/api/story.js CHANGED
@@ -48,7 +48,8 @@ export function timelineOf(input) {
48
48
  const rates = input.rates;
49
49
  if (rates !== undefined && (!Array.isArray(rates) || rates.length === 0 || !rates.every((rate) => Number.isFinite(rate) && rate > 0)))
50
50
  throw bad("rates must be a non-empty list of positive numbers");
51
- return { none: false, window, ...(rates === undefined ? {} : { rates }), ...(input.rate === undefined ? {} : { rate: input.rate }), ...(input.loop === true ? { loop: true } : {}) };
51
+ const pacing = pacingOf(input.pacing, bad);
52
+ return { none: false, window, ...(rates === undefined ? {} : { rates }), ...(pacing === undefined ? {} : { pacing }), ...(input.rate === undefined ? {} : { rate: input.rate }), ...(input.loop === true ? { loop: true } : {}) };
52
53
  }
53
54
  /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
54
55
  export function panelsOf(raw, lookup) {
@@ -61,3 +62,64 @@ export function panelsOf(raw, lookup) {
61
62
  throw error;
62
63
  }
63
64
  }
65
+ /** Checks `pacing`: each piece names the field that is wrong (`pacing[2].rate`); spans must not overlap. */
66
+ function pacingOf(input, bad) {
67
+ if (input === undefined)
68
+ return undefined;
69
+ if (!Array.isArray(input))
70
+ throw bad("pacing must be a list of { from, to, rate } and { near: { type, within }, rate }");
71
+ const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
72
+ const pieces = input.map((raw, index) => {
73
+ const at = `pacing[${index}]`;
74
+ if (typeof raw !== "object" || raw === null)
75
+ throw bad(`${at} must be an object`);
76
+ const piece = raw;
77
+ if (!positive(piece.rate))
78
+ throw bad(`${at}.rate must be a positive number, got ${String(piece.rate)}`);
79
+ if (piece.ramp !== undefined && !(typeof piece.ramp === "number" && Number.isFinite(piece.ramp) && piece.ramp >= 0))
80
+ throw bad(`${at}.ramp must be zero or more seconds, got ${String(piece.ramp)}`);
81
+ if (piece.near !== undefined) {
82
+ const { type, within } = piece.near;
83
+ if (typeof type !== "string" || type === "")
84
+ throw bad(`${at}.near.type must be a non-empty event type`);
85
+ if (!positive(within))
86
+ throw bad(`${at}.near.within must be a positive number of seconds, got ${String(within)}`);
87
+ return { type, withinMs: within * 1000, rate: piece.rate, rampMs: (piece.ramp ?? within) * 1000 };
88
+ }
89
+ if (piece.from === undefined || piece.to === undefined)
90
+ throw bad(`${at} needs { from, to, rate } or { near: { type, within }, rate }`);
91
+ const fromUtcMs = toUtcMs(piece.from, `setTimeline ${at}.from`);
92
+ const toUtcMsValue = toUtcMs(piece.to, `setTimeline ${at}.to`);
93
+ if (toUtcMsValue <= fromUtcMs)
94
+ throw bad(`${at}.to must be after ${at}.from`);
95
+ return { fromUtcMs, toUtcMs: toUtcMsValue, rate: piece.rate, rampMs: piece.ramp === undefined ? (toUtcMsValue - fromUtcMs) / 10 : piece.ramp * 1000 };
96
+ });
97
+ const spans = pieces.flatMap((piece, index) => ("fromUtcMs" in piece ? [{ piece, index }] : [])).sort((a, b) => a.piece.fromUtcMs - b.piece.fromUtcMs);
98
+ for (let i = 1; i < spans.length; i += 1) {
99
+ if (spans[i].piece.fromUtcMs < spans[i - 1].piece.toUtcMs)
100
+ throw bad(`pacing[${spans[i].index}] overlaps pacing[${spans[i - 1].index}]; spans may touch but not overlap`);
101
+ }
102
+ return pieces.length === 0 ? undefined : pieces;
103
+ }
104
+ /**
105
+ * The pacing the viewer runs, laid over the events: spans, then one zone per event of each rule's type. `pacedRate` lays the zones fastest first, so the slowest applicable piece wins wherever they meet, whatever contains what.
106
+ * A rule whose type has no event throws `bad-timeline` naming the piece (a mistyped type would otherwise slow nothing, silently).
107
+ */
108
+ export function pacingFor(setting, events, baseRate) {
109
+ if (setting.pacing === undefined)
110
+ return undefined;
111
+ const spans = [];
112
+ const near = [];
113
+ setting.pacing.forEach((piece, index) => {
114
+ if ("fromUtcMs" in piece) {
115
+ spans.push({ fromUtcMs: piece.fromUtcMs, toUtcMs: piece.toUtcMs, rate: piece.rate, rampMs: piece.rampMs });
116
+ return;
117
+ }
118
+ const matching = events.filter((event) => event.type === piece.type);
119
+ if (matching.length === 0)
120
+ throw new SceneError("bad-timeline", `setTimeline: pacing[${index}].near.type "${piece.type}" matches no event; give the events that type with addEvents`);
121
+ for (const event of matching)
122
+ near.push({ fromUtcMs: event.timeUtcMs - piece.withinMs, toUtcMs: event.timeUtcMs + piece.withinMs, rate: piece.rate, rampMs: piece.rampMs });
123
+ });
124
+ return { baseRate, zones: [...spans, ...near] };
125
+ }