@johnmorrisdotca/wakusei-planets 0.35.0 → 0.36.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.
@@ -14,8 +14,12 @@ import { ownCredit } from "../door/own.js";
14
14
  import { setThreeLoader, takeRenderer } from "../scene/shared.js";
15
15
  import { texturePaths, tilesBase } from "../scene/textures.js";
16
16
  import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt, SPACE_DWARFS, SPACE_MINORS, SPACE_PLANETS } from "./frame.js";
17
- import { moonOffset } from "../scene/orient.js";
17
+ import { moonOffset, orientation } from "../scene/orient.js";
18
18
  import { moonDistance, placeBodies, radiusIn } from "./scale.js";
19
+ import { groundDirection } from "./aim.js";
20
+ import { besideMoon } from "./beside.js";
21
+ import { SUN_REGIONS } from "./regions.js";
22
+ import { travelArrival } from "./travel.js";
19
23
  import { createSpaceItem, FIT_DISTANCE, newSpaceModel, SPACE_BODIES } from "./scene.js";
20
24
  export { setThreeLoader, SPACE_BODIES };
21
25
  /** The words the view says on itself for the scale in use. A page in another language gives its own with `scaleNames`. */
@@ -26,6 +30,20 @@ const SCALE_WORDS = {
26
30
  /** A body whose disc is smaller than this many CSS pixels across its radius is marked with a ring as well as its name. */
27
31
  const RING_BELOW_PX = 4;
28
32
  const readLight = (value) => (value === "lit" ? "lit" : "sun");
33
+ /** The kinds of move between two views, as `transition` names them. */
34
+ const TRAVEL_KINDS = ["turn-travel", "direct", "look-back", "auto", "cut"];
35
+ const readTravel = (value, fallback) => {
36
+ const name = typeof value === "string" ? value.trim().toLowerCase() : "";
37
+ return TRAVEL_KINDS.includes(name) ? name : fallback;
38
+ };
39
+ const readPace = (value, fallback) => {
40
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number.parseFloat(value) : Number.NaN;
41
+ return Number.isFinite(n) && n > 0 ? Math.min(20, Math.max(0.05, n)) : fallback;
42
+ };
43
+ /** A zoom event less than this many milliseconds after the one before is of the same gesture (the family's own window for a turn of the wheel). */
44
+ const GESTURE_GAP_MS = 300;
45
+ const REGION_IDS = SUN_REGIONS.map((region) => region.id);
46
+ const readRegion = (value) => (typeof value === "string" && REGION_IDS.includes(value.trim().toLowerCase()) ? value.trim().toLowerCase() : undefined);
29
47
  const RAD = Math.PI / 180;
30
48
  const REAL_TIME_TICK_MS = 60_000;
31
49
  /** The plain wheel in an immersive view is passed on as a pinch of this share, so a notch (100) zooms about 1.2 times, as the family's mouse wheel does with Alt. */
@@ -57,7 +75,7 @@ const readBody = (value) => {
57
75
  * 1.05 radii from the surface (`FIT_DISTANCE` over the zoom), so past a zoom of about 3.9 nothing moves; 3.6 is where the finest map tiles of the Earth, Mars and the Moon (16384 pixels round) run out of detail too, so it is the same ceiling for both.
58
76
  */
59
77
  const CARRIED_LIMITS = { zoomMin: 1e-6, zoomMax: 3.6, tiltMax: 90 };
60
- const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}:host([immersive]){aspect-ratio:auto;width:100%;height:100%;touch-action:none!important;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}.sp-arrow{position:absolute;left:0;top:0;margin:0;padding:0 4px 0 0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;opacity:.8;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:auto;cursor:pointer}.sp-arrow::before{content:"";display:inline-block;width:0;height:0;margin:0 5px 1px 0;border:5px solid transparent;border-left:7px solid #fff;transform:rotate(var(--turn,0deg));transform-origin:30% 50%}.sp-arrow[hidden]{display:none}.sp-arrow:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label,.sp-ring{transition:opacity .35s ease}.sp-label[data-carried],.sp-ring[data-carried]{opacity:0;pointer-events:none}@media (prefers-reduced-motion:reduce){.sp-label,.sp-ring{transition:none}}.sp-ring{position:absolute;left:0;top:0;width:16px;height:16px;margin:-8px 0 0 -8px;box-sizing:border-box;border:1.5px solid rgba(255,255,255,.85);border-radius:50%;box-shadow:0 0 3px #000;pointer-events:none;will-change:transform}.sp-ring[hidden]{display:none}.sp-scale{position:absolute;left:10px;top:8px;margin:0;padding:0;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;opacity:.9;text-shadow:0 0 3px #000,0 0 3px #000;pointer-events:none}</style><div id="stage"></div><div id="labels"></div><p class="sp-scale" part="scale" role="status"></p>`;
78
+ const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}:host([immersive]){aspect-ratio:auto;width:100%;height:100%;touch-action:none!important;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}.sp-arrow{position:absolute;left:0;top:0;margin:0;padding:0 4px 0 0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;opacity:.8;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:auto;cursor:pointer}.sp-arrow::before{content:"";display:inline-block;width:0;height:0;margin:0 5px 1px 0;border:5px solid transparent;border-left:7px solid #fff;transform:rotate(var(--turn,0deg));transform-origin:30% 50%}.sp-arrow[hidden]{display:none}.sp-arrow:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label,.sp-ring{transition:opacity .35s ease}.sp-label[data-carried],.sp-ring[data-carried]{opacity:0;pointer-events:none}@media (prefers-reduced-motion:reduce){.sp-label,.sp-ring{transition:none}}.sp-ring{position:absolute;left:0;top:0;width:16px;height:16px;margin:-8px 0 0 -8px;box-sizing:border-box;border:1.5px solid rgba(255,255,255,.85);border-radius:50%;box-shadow:0 0 3px #000;pointer-events:none;will-change:transform}.sp-ring[hidden]{display:none}.sp-scale{position:absolute;left:10px;top:8px;margin:0;padding:0;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;opacity:.9;text-shadow:0 0 3px #000,0 0 3px #000;pointer-events:none}.sp-region{position:absolute;left:10px;bottom:8px;margin:0;padding:0;font:600 15px/20px system-ui,-apple-system,sans-serif;color:#fff;opacity:.95;text-shadow:0 0 4px #000,0 0 4px #000;pointer-events:none;transition:opacity .35s}.sp-region[hidden]{display:block;opacity:0}@media (prefers-reduced-motion:reduce){.sp-region{transition:none}}</style><div id="stage"></div><div id="labels"></div><p class="sp-scale" part="scale" role="status"></p><p class="sp-region" id="region" part="region" role="status" hidden></p>`;
61
79
  /**
62
80
  * The `<wakusei-space>` custom element: the Earth, the Moon, the Sun and the planets where they are at a date and time, drawn with three.js through the shared renderer. It takes `center`
63
81
  * (`"lon,lat"`), `time` (`now` or an ISO date), `speed` (1 is real time, 0 holds, 86400 is a day a second, negative runs backwards), `scale` (`compressed` or `true`), `look` (`realistic` or `painted`),
@@ -87,7 +105,7 @@ const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;ove
87
105
  * ```
88
106
  */
89
107
  export class WakuseiSpace extends HTMLElement {
90
- static observedAttributes = ["center", "time", "speed", "scale", "labels", "labels-always", "covered", "orbits", "help", "look", "light", "lang", "data", "arrows", "help-through", ...NAME_LABEL_ATTRIBUTES];
108
+ static observedAttributes = ["center", "time", "speed", "scale", "labels", "labels-always", "covered", "roadster", "orbiters", "orbits", "help", "look", "light", "lang", "data", "arrows", "help-through", "transition", "pace", ...NAME_LABEL_ATTRIBUTES];
91
109
  #model = newSpaceModel();
92
110
  #clock = createGameClock("now", 1);
93
111
  #view;
@@ -136,15 +154,19 @@ export class WakuseiSpace extends HTMLElement {
136
154
  this.#model.labels = this.getAttribute("labels") !== "off";
137
155
  this.#labelsAlways = this.hasAttribute("labels-always") && this.getAttribute("labels-always") !== "off";
138
156
  this.#covered = this.getAttribute("covered") === "arrow" ? "arrow" : "name";
157
+ this.roadster = this.hasAttribute("roadster") && this.getAttribute("roadster") !== "off";
158
+ this.orbiters = this.hasAttribute("orbiters") && this.getAttribute("orbiters") !== "off";
139
159
  this.#model.orbits = this.getAttribute("orbits") !== "off";
140
160
  this.#model.arrowCount = arrowCount(this.getAttribute("arrows"));
141
161
  this.#model.help = this.hasAttribute("help") && this.getAttribute("help") !== "off";
142
162
  this.#model.helpThrough = this.hasAttribute("help-through") && this.getAttribute("help-through") !== "off";
163
+ this.#travel = { kind: readTravel(this.getAttribute("transition"), "turn-travel"), pace: readPace(this.getAttribute("pace"), 1) };
143
164
  this.#model.look = this.getAttribute("look") === "painted" ? "painted" : "realistic";
144
165
  this.#model.light = readLight(this.getAttribute("light"));
145
166
  this.#relabel();
146
167
  this.#door.book.ownOnly(this.getAttribute("data") === "own");
147
168
  this.#model.stepMs = Math.max(1000, Math.abs(this.#clock.speed) * 1000);
169
+ this.#model.speed = this.#clock.speed;
148
170
  if (!this.hasAttribute("role"))
149
171
  this.setAttribute("role", "img");
150
172
  if (!this.hasAttribute("tabindex"))
@@ -156,7 +178,9 @@ export class WakuseiSpace extends HTMLElement {
156
178
  this.#stage = root.getElementById("stage");
157
179
  this.#labelBox = root.getElementById("labels");
158
180
  this.#scaleLine = root.querySelector(".sp-scale");
181
+ this.#regionLine = root.getElementById("region");
159
182
  this.#nameScale();
183
+ this.#showRegion();
160
184
  this.#pool.clear();
161
185
  this.#rings.clear();
162
186
  this.#arrows.clear();
@@ -230,6 +254,10 @@ export class WakuseiSpace extends HTMLElement {
230
254
  this.labelsAlways = value !== null && value !== "off";
231
255
  else if (name === "covered")
232
256
  this.covered = value === "arrow" ? "arrow" : "name";
257
+ else if (name === "roadster")
258
+ this.roadster = value !== null && value !== "off";
259
+ else if (name === "orbiters")
260
+ this.orbiters = value !== null && value !== "off";
233
261
  else if (name === "orbits")
234
262
  this.orbits = value !== "off";
235
263
  else if (name === "arrows")
@@ -238,6 +266,10 @@ export class WakuseiSpace extends HTMLElement {
238
266
  this.help = value !== null && value !== "off";
239
267
  else if (name === "help-through")
240
268
  this.helpThrough = value !== null && value !== "off";
269
+ else if (name === "transition")
270
+ this.transition = readTravel(value, "turn-travel");
271
+ else if (name === "pace")
272
+ this.pace = readPace(value, 1);
241
273
  else if (name === "look")
242
274
  this.look = value === "painted" ? "painted" : "realistic";
243
275
  else if (name === "light")
@@ -248,6 +280,7 @@ export class WakuseiSpace extends HTMLElement {
248
280
  for (const [id, button] of this.#pool)
249
281
  this.#nameLabel(button, id);
250
282
  this.#nameScale();
283
+ this.#showRegion();
251
284
  this.#relabel();
252
285
  }
253
286
  else if (NAME_LABEL_ATTRIBUTES.includes(name))
@@ -303,6 +336,7 @@ export class WakuseiSpace extends HTMLElement {
303
336
  if (this.isConnected)
304
337
  this.#model.time = this.#clock.time;
305
338
  this.#model.stepMs = Math.max(1000, Math.abs(this.#clock.speed) * 1000);
339
+ this.#model.speed = this.#clock.speed;
306
340
  this.#schedule();
307
341
  this.#gate?.request();
308
342
  if (this.#clock.speed === 0 && was !== 0)
@@ -335,6 +369,83 @@ export class WakuseiSpace extends HTMLElement {
335
369
  label.hidden = true;
336
370
  this.#gate?.request();
337
371
  }
372
+ #travel = { kind: "turn-travel", pace: 1 };
373
+ #regionLine;
374
+ /** When the last zoom event was heard at a stage out from the Sun (ms of the page's clock). The events of one gesture (a pinch, a turn of the wheel) come less than `GESTURE_GAP_MS` apart: one gesture is one step. */
375
+ #regionZoomAt = Number.NEGATIVE_INFINITY;
376
+ /**
377
+ * How the camera moves from one view to the next: `turn-travel` (the default: turn beside the body being left until the next is in the picture, then travel to it, never an empty frame), `direct` (a straight
378
+ * eased glide), `look-back` (straight, watching the body left until the end), `auto` (`turn-travel`), `cut` (no move). The attribute `transition` says the same; `goTo` and `ride` take one for a single move. A
379
+ * reader who asked for reduced motion always gets `cut`.
380
+ */
381
+ get transition() {
382
+ return this.#travel.kind;
383
+ }
384
+ set transition(value) {
385
+ this.#travel = { ...this.#travel, kind: readTravel(value, this.#travel.kind) };
386
+ }
387
+ /** How slow the moves are: the plan's own length times this (1 by default; 2 is twice as slow). The attribute `pace` says the same; `goTo` and `ride` take `duration` in milliseconds for a single move instead. */
388
+ get pace() {
389
+ return this.#travel.pace;
390
+ }
391
+ set pace(value) {
392
+ this.#travel = { ...this.#travel, pace: readPace(value, this.#travel.pace) };
393
+ }
394
+ /** The stage out from the Sun the view is framed on (`inner-planets`, `asteroid-belt`, `outer-planets`, `kuiper-belt`, `whole-system`), or null for a view of a body. */
395
+ get region() {
396
+ return this.#model.region;
397
+ }
398
+ #orbitersLoading = false;
399
+ /**
400
+ * Show the spacecraft in orbit round the Moon and Mars (the attribute `orbiters`; off by default): each a small dot where `/orbiters` puts it on the date shown, scaled with its body, on its orbit line, with its
401
+ * name beside it in the page's language, once the body is at least 24 CSS pixels in radius on the screen. A modelled or predicted path is drawn dim; a craft with no path is not drawn. The paths (a 9 kB module)
402
+ * are loaded the first time they are shown. `stats.orbiters` says what was drawn and each one's status.
403
+ */
404
+ get orbiters() {
405
+ return this.#model.orbiters;
406
+ }
407
+ set orbiters(value) {
408
+ this.#model.orbiters = value;
409
+ if (value && this.#model.orbiterSet === null && !this.#orbitersLoading) {
410
+ this.#orbitersLoading = true;
411
+ void import("../orbiters.js").then((mod) => {
412
+ this.#model.orbiterSet = {
413
+ ids: mod.ORBITER_IDS,
414
+ centre: (id) => mod.orbiterCentre(id),
415
+ position: (id, ms) => (mod.orbiterElements(id) === undefined ? null : mod.orbiterPosition(id, ms)),
416
+ path: (id, ms, points) => mod.orbiterPath(id, ms, points),
417
+ status: (id, ms) => mod.orbiterStatus(id, ms),
418
+ name: (id) => ({ ...mod.orbiterFacts(id).name }),
419
+ };
420
+ this.#gate?.request();
421
+ }, () => {
422
+ this.#orbitersLoading = false;
423
+ });
424
+ }
425
+ this.#gate?.request();
426
+ }
427
+ #roadsterLoading = false;
428
+ /**
429
+ * Show Starman and the Tesla Roadster (the attribute `roadster`; off by default): a small marked body where `/roadster` puts the car on the date shown, on its orbit line (about one trip round the Sun), with its name
430
+ * (`Starman`, `スターマン`) beside it, from the launch in 2018 to the end of 2035. Its path (a 20 kB table) is loaded the first time it is shown, and never when it is not. `stats.roadster` says what was drawn.
431
+ */
432
+ get roadster() {
433
+ return this.#model.roadster;
434
+ }
435
+ set roadster(value) {
436
+ this.#model.roadster = value;
437
+ if (value && this.#model.roadsterPath === null && !this.#roadsterLoading) {
438
+ this.#roadsterLoading = true;
439
+ // the table comes with the module, so it is fetched only when the car is first shown
440
+ void import("../roadster.js").then((mod) => {
441
+ this.#model.roadsterPath = { positionAu: (ms) => mod.roadsterPositionAu(ms), record: { ...mod.ROADSTER.record }, name: { ...mod.ROADSTER.name } };
442
+ this.#gate?.request();
443
+ }, () => {
444
+ this.#roadsterLoading = false;
445
+ });
446
+ }
447
+ this.#gate?.request();
448
+ }
338
449
  #covered = "name";
339
450
  #arrows = new Map();
340
451
  /**
@@ -424,6 +535,23 @@ export class WakuseiSpace extends HTMLElement {
424
535
  */
425
536
  setView(view, final = true) {
426
537
  const now = this.#model.view;
538
+ if (this.#model.region !== null && view.zoom !== 1) {
539
+ // at a stage out from the Sun a zoom gesture is a step: out to the next stage, in to the one before (or the Sun); one gesture, one step, and the controls go back to holding zoom 1 (the element's own
540
+ // hands are set here; a bar bound to the element hears `wakusei-hop` with zoom 1, which a step or a refused gesture both announce)
541
+ const at = performance.now();
542
+ const fresh = at - this.#regionZoomAt > GESTURE_GAP_MS;
543
+ this.#regionZoomAt = at;
544
+ if (fresh && this.#model.transition === null) {
545
+ if (view.zoom < 1)
546
+ this.stepOut();
547
+ else
548
+ this.stepIn();
549
+ }
550
+ else
551
+ this.#announceHop(1);
552
+ this.#hands?.controller.set({ zoom: 1 }, true, "jump");
553
+ return;
554
+ }
427
555
  const [roll, panX, panY] = [view.roll ?? 0, view.panX ?? 0, view.panY ?? 0];
428
556
  if (view.yaw === now.yaw && view.tilt === now.tilt && view.zoom === now.zoom && roll === now.roll && panX === now.panX && panY === now.panY)
429
557
  return;
@@ -461,35 +589,188 @@ export class WakuseiSpace extends HTMLElement {
461
589
  return { current: this.bodyInfo(here), previous: this.bodyInfo(hopFrom(here, -1, canCentre)), next: this.bodyInfo(hopFrom(here, 1, canCentre)) };
462
590
  }
463
591
  /**
464
- * Go to a body: it becomes the middle of the view and the zoom brings it whole into view (`zoom`, 1 by default; a planet's `-moons` preset for its system), gliding there from where the camera is unless `smooth` is
465
- * false or the reader asked for reduced motion. `wakusei-hop` tells the page where it went and where the next and previous hops lead. A name in any case, in English or Japanese, works.
592
+ * Go to a body: it becomes the middle of the view and the zoom brings it whole into view (`zoom`, 1 by default; a planet's `-moons` preset for its system), travelling there from where the camera is (`transition`,
593
+ * the view's own by default; `duration` in milliseconds, the plan's own by default) unless `smooth` is false or the reader asked for reduced motion. The travel arrives from the side it comes from, moved round
594
+ * towards the Sun where that side would show the body mostly dark, so the way in is straight: the controls' yaw and tilt are set to that side. A stage out from the Sun (`inner-planets`, `asteroid-belt`,
595
+ * `outer-planets`, `kuiper-belt`, `whole-system`) is a target too: the Sun is looked at and the camera stands back until the stage's orbits are all in the picture, with the stage's name shown. `wakusei-hop`
596
+ * tells the page where it went and where the next and previous hops lead. A name in any case, in English or Japanese, works.
466
597
  *
467
- * @param target - A body's name (`"saturn"`, `"Saturn"`, `"土星"`).
468
- * @param options - `smooth` (true by default) and `zoom` (1 by default).
598
+ * @param target - A body's name (`"saturn"`, `"Saturn"`, `"土星"`) or a stage's id.
599
+ * @param options - `smooth` (true by default), `zoom` (1 by default), `transition` and `duration`.
469
600
  * @returns Whether the view can go there.
470
601
  */
471
602
  goTo(target, options = {}) {
603
+ const region = readRegion(target);
604
+ if (region !== undefined) {
605
+ this.#goToRegion(region, options);
606
+ return true;
607
+ }
472
608
  const id = readBody(target);
473
609
  if (!id)
474
610
  return false;
475
611
  const model = this.#model;
476
- const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
477
- const pose = model.pose;
478
- const glide = (options.smooth ?? true) && !reduced && pose.valid && model.ride === null;
612
+ const leaving = this.#leaving();
613
+ const kind = this.#moveKind(options, id);
479
614
  if (model.ride !== null)
480
615
  this.ride(null, { smooth: false });
481
- model.transition = glide ? { start: performance.now(), duration: 1200, from: { p: [pose.p[0], pose.p[1], pose.p[2]], q: [pose.q[0], pose.q[1], pose.q[2], pose.q[3]], fov: pose.fov } } : null;
616
+ model.transition = this.#startMove(kind, leaving, id, options.duration);
617
+ model.region = null;
618
+ this.#showRegion();
482
619
  this.#selected = id;
483
620
  this.#model.focus = id;
484
621
  const zoom = options.zoom ?? 1;
485
- // a bar bound to the element holds the view's state: it applies the zoom the page hears in the event; without one the element's own hands do
622
+ // the side the camera comes from, as the controls' yaw and tilt: the element's own hands are set to it here, and a bar bound to the element (which holds the view's state) hears it in the event with the zoom
623
+ const side = model.transition !== null ? this.#faceApproach(id) : null;
486
624
  if (!this.hasAttribute("data-kazoku-bar"))
487
- this.#hands?.controller.set({ zoom }, true, "jump");
625
+ this.#hands?.controller.set(side ? { ...side, zoom } : { zoom }, true, "jump");
488
626
  this.#schedule();
489
627
  this.#gate?.request();
490
- this.#announceHop(zoom);
628
+ this.#announceHop(zoom, side ?? undefined);
491
629
  return true;
492
630
  }
631
+ /** The body the camera is at now: the target of the ride, or the body looked at. */
632
+ #leaving() {
633
+ const ride = this.#model.ride;
634
+ if (ride !== null)
635
+ return typeof ride.target === "string" ? ride.target : ride.around;
636
+ return this.#model.focus;
637
+ }
638
+ /**
639
+ * The kind of move a call gets: `cut` for `smooth: false`, for a reader who asked for reduced motion, or before the first draw; else the call's `transition`, or the view's. `auto` is `direct` when the
640
+ * destination is on the screen as the move starts (it stays in view and grows), `turn-travel` when it is not.
641
+ */
642
+ #moveKind(options, destination = null) {
643
+ const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
644
+ if (!(options.smooth ?? true) || reduced || !this.#model.pose.valid)
645
+ return "cut";
646
+ const kind = readTravel(options.transition, this.#travel.kind);
647
+ if (kind !== "auto")
648
+ return kind;
649
+ const place = destination === null ? null : this.placeOf(destination);
650
+ const inView = place !== null && place.x >= 0 && place.y >= 0 && place.x <= this.clientWidth && place.y <= this.clientHeight;
651
+ return inView ? "direct" : "turn-travel";
652
+ }
653
+ /** A move from where the last draw left the camera, or null for a cut. The scene builds its path at the next draw. */
654
+ #startMove(kind, leaving, destination, duration) {
655
+ if (kind === "cut")
656
+ return null;
657
+ const pose = this.#model.pose;
658
+ const leavingReach = this.#model.region !== null && leaving === "sun" ? (this.#model.regionDrawn?.reach ?? 0) : 0;
659
+ return {
660
+ start: performance.now(),
661
+ duration: typeof duration === "number" && Number.isFinite(duration) && duration > 0 ? duration : 0,
662
+ pace: this.#travel.pace,
663
+ kind,
664
+ from: { p: [pose.p[0], pose.p[1], pose.p[2]], q: [pose.q[0], pose.q[1], pose.q[2], pose.q[3]], fov: pose.fov },
665
+ leaving,
666
+ destination,
667
+ leavingReach,
668
+ input: null,
669
+ plan: null,
670
+ origin: [0, 0, 0],
671
+ };
672
+ }
673
+ /** Where a body is drawn now, in Earth radii from the Earth's centre, and its drawn radius: the places the scene uses, worked out the same way. */
674
+ #site(id) {
675
+ const mode = this.#model.mode;
676
+ const pos = placeBodies(mode, frameAt(this.#model.time));
677
+ if (SPACE_BODIES.includes(id))
678
+ return { at: [...pos[id]], radius: radiusIn(id, mode) };
679
+ const host = (hostOf(id) ?? "earth");
680
+ const real = moonOffset(id, this.#model.time);
681
+ const d = Math.hypot(real[0], real[1], real[2]);
682
+ const k = (d === 0 ? 1 : moonDistance(mode, host, d) / d) * radiusIn(host, mode);
683
+ const centre = pos[host];
684
+ return { at: [centre[0] + real[0] * k, centre[1] + real[1] * k, centre[2] + real[2] * k], radius: Math.max(1e-6, (BODIES[id].radiusKm / BODIES[host].radiusKm) * radiusIn(host, mode)) };
685
+ }
686
+ /**
687
+ * The controls' yaw and tilt that look at a body from the side the camera comes from (moved round towards the Sun where that side would show it mostly dark), so the move in is straight and nothing is turned
688
+ * back on arrival; null when the camera has not drawn yet.
689
+ */
690
+ #faceApproach(id) {
691
+ const model = this.#model;
692
+ if (!model.pose.valid)
693
+ return null;
694
+ const body = this.#site(id);
695
+ const sun = id === "sun" ? undefined : this.#site("sun").at;
696
+ const wanted = travelArrival({ body: body.at, radius: body.radius, from: model.camera.position, sun, aspect: 16 / 9 });
697
+ const side = [wanted.position[0] - body.at[0], wanted.position[1] - body.at[1], wanted.position[2] - body.at[2]];
698
+ const anchor = model.anchor ?? model.time;
699
+ // the scene aims from the ground direction of (lon - yaw, lat - tilt) at the anchor moment: search the pair that lies along the wanted side, coarse then fine
700
+ const score = (yaw, tilt) => {
701
+ const aim = groundDirection(model.centre.lon - yaw, Math.max(-90, Math.min(90, model.centre.lat - tilt)), anchor);
702
+ return aim[0] * side[0] + aim[1] * side[1] + aim[2] * side[2];
703
+ };
704
+ let best = { yaw: model.view.yaw, tilt: model.view.tilt, score: -Infinity };
705
+ for (let yaw = -180; yaw < 180; yaw += 6)
706
+ for (let tilt = -85; tilt <= 85; tilt += 5) {
707
+ const n = score(yaw, tilt);
708
+ if (n > best.score)
709
+ best = { yaw, tilt, score: n };
710
+ }
711
+ for (let yaw = best.yaw - 6; yaw <= best.yaw + 6; yaw += 1)
712
+ for (let tilt = Math.max(-89, best.tilt - 5); tilt <= Math.min(89, best.tilt + 5); tilt += 1) {
713
+ const n = score(yaw, tilt);
714
+ if (n > best.score)
715
+ best = { yaw, tilt, score: n };
716
+ }
717
+ return { yaw: best.yaw, tilt: best.tilt };
718
+ }
719
+ /** Go to a stage out from the Sun: the Sun is looked at and the camera stands back until every orbit of the stage is in the picture; from another stage the move is a straight pull back or push in. */
720
+ #goToRegion(region, options) {
721
+ const model = this.#model;
722
+ const leaving = this.#leaving();
723
+ const kind = this.#moveKind(options, "sun");
724
+ if (model.ride !== null)
725
+ this.ride(null, { smooth: false });
726
+ model.transition = this.#startMove(kind, model.region !== null ? "sun" : leaving, "sun", options.duration);
727
+ model.region = region;
728
+ this.#selected = "sun";
729
+ model.focus = "sun";
730
+ // at a stage the controls hold zoom 1: a zoom gesture is taken as a step out or in, not as a zoom
731
+ if (!this.hasAttribute("data-kazoku-bar"))
732
+ this.#hands?.controller.set({ zoom: 1 }, true, "jump");
733
+ this.#showRegion();
734
+ this.#schedule();
735
+ this.#gate?.request();
736
+ this.#announceHop(1);
737
+ this.dispatchEvent(new CustomEvent("wakusei-region", { detail: { region, name: this.#regionName(region) }, bubbles: true, composed: true }));
738
+ }
739
+ /** The next stage out from the Sun from where the view is (the first stage from a body), with the same move as `goTo`; null, and nothing done, when the view is already at the widest stage. */
740
+ stepOut(options = {}) {
741
+ const here = this.#model.region;
742
+ const next = here === null ? REGION_IDS[0] : REGION_IDS[REGION_IDS.indexOf(here) + 1];
743
+ if (next === undefined)
744
+ return null;
745
+ this.#goToRegion(next, options);
746
+ return next;
747
+ }
748
+ /** The next stage in towards the Sun from the stage the view is at, or the Sun itself (`"sun"`, zoom 1) from the first stage; null, and nothing done, when the view is not at a stage. */
749
+ stepIn(options = {}) {
750
+ const here = this.#model.region;
751
+ if (here === null)
752
+ return null;
753
+ const i = REGION_IDS.indexOf(here);
754
+ if (i <= 0) {
755
+ this.goTo("sun", options);
756
+ return "sun";
757
+ }
758
+ this.#goToRegion(REGION_IDS[i - 1], options);
759
+ return REGION_IDS[i - 1];
760
+ }
761
+ #regionName(region) {
762
+ const name = SUN_REGIONS.find((entry) => entry.id === region).name;
763
+ return this.getAttribute("lang") === "ja" ? name.ja : name.en;
764
+ }
765
+ /** The stage's name in the corner of the view, in the element's language, or nothing at a body. */
766
+ #showRegion() {
767
+ const line = this.#regionLine;
768
+ if (!line)
769
+ return;
770
+ const region = this.#model.region;
771
+ line.textContent = region === null ? "" : this.#regionName(region);
772
+ line.hidden = region === null;
773
+ }
493
774
  /** Go to the next body in the order of `bodyList()` (the Sun, Mercury, Venus, the Earth, the Moon, Mars, Phobos, Deimos, Ceres, Jupiter, its moons, and on), round to the Sun after the last. */
494
775
  next(options = {}) {
495
776
  this.goTo(hopFrom(this.#model.focus, 1, canCentre), options);
@@ -511,9 +792,9 @@ export class WakuseiSpace extends HTMLElement {
511
792
  set selected(id) {
512
793
  this.#selected = id;
513
794
  }
514
- /** `zoom` is the zoom the page should bring the view to: given by `goTo`, left out when the body was only set (the zoom stays). */
515
- #announceHop(zoom) {
516
- this.dispatchEvent(new CustomEvent("wakusei-hop", { detail: { ...this.hopper, zoom }, bubbles: true, composed: true }));
795
+ /** `zoom` is the zoom the page should bring the view to: given by `goTo`, left out when the body was only set (the zoom stays). `side` is the controls' yaw and tilt that look from the side the camera comes from, given by a `goTo` that travels. */
796
+ #announceHop(zoom, side) {
797
+ this.dispatchEvent(new CustomEvent("wakusei-hop", { detail: { ...this.hopper, zoom, ...(side ? { yaw: side.yaw, tilt: side.tilt } : {}) }, bubbles: true, composed: true }));
517
798
  }
518
799
  /** The words shown beside each body, for a page in another language (`{ mars: "火星" }`). A body left out keeps its name in the element's `lang`. */
519
800
  get bodyNames() {
@@ -575,7 +856,7 @@ export class WakuseiSpace extends HTMLElement {
575
856
  */
576
857
  ride(target, options = {}) {
577
858
  const model = this.#model;
578
- const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
859
+ const leaving = this.#leaving();
579
860
  const wasRiding = model.ride !== null;
580
861
  if (target === null) {
581
862
  model.ride = null;
@@ -594,12 +875,42 @@ export class WakuseiSpace extends HTMLElement {
594
875
  model.focus = this.#focusBeforeRide;
595
876
  }
596
877
  this.#lostTold = false;
597
- const pose = model.pose;
598
- model.transition = (options.smooth ?? true) && !reduced && pose.valid ? { start: performance.now(), duration: 1200, from: { p: [pose.p[0], pose.p[1], pose.p[2]], q: [pose.q[0], pose.q[1], pose.q[2], pose.q[3]], fov: pose.fov } } : null;
878
+ const destination = target !== null && typeof target === "string" ? (readBody(target) ?? null) : target === null ? this.#model.focus : null;
879
+ model.transition = this.#startMove(this.#moveKind(options, destination), leaving, destination, options.duration);
880
+ if (model.transition !== null && model.ride?.view === "beside" && typeof model.ride.target === "string") {
881
+ // beside a moon the picture can be swung round the line from its planet by the controls' yaw: take the yaw that puts the camera nearest the side it comes from, so the way in is straight
882
+ const yaw = this.#besideYaw(model.ride.target);
883
+ if (yaw !== null && !this.hasAttribute("data-kazoku-bar"))
884
+ this.#hands?.controller.set({ yaw, tilt: 0 }, true, "jump");
885
+ }
886
+ model.region = null;
887
+ this.#showRegion();
599
888
  this.#schedule();
600
889
  this.#gate?.request();
601
890
  this.dispatchEvent(new CustomEvent("wakusei-ride", { detail: this.riding }));
602
891
  }
892
+ /** The controls' yaw for the view from beside a moon that puts the camera nearest the side it comes from, in whole degrees; null before the first draw. */
893
+ #besideYaw(moon) {
894
+ const model = this.#model;
895
+ if (!model.pose.valid)
896
+ return null;
897
+ const host = (moon === "moon" ? "earth" : (hostOf(moon) ?? "earth"));
898
+ const site = this.#site(moon);
899
+ const planet = this.#site(host);
900
+ const sun = this.#site("sun").at;
901
+ const north = orientation(host, model.time).pole;
902
+ const from = model.camera.position;
903
+ let best = { yaw: 0, near: -Infinity };
904
+ for (let yaw = 0; yaw < 360; yaw += 10) {
905
+ const camera = besideMoon({ moon: site.at, moonRadius: site.radius, host: planet.at, hostRadius: planet.radius, sun, north, aspect: 16 / 9, zoom: 1, yaw, tilt: 0 });
906
+ const a = [camera.position[0] - site.at[0], camera.position[1] - site.at[1], camera.position[2] - site.at[2]];
907
+ const b = [from[0] - site.at[0], from[1] - site.at[1], from[2] - site.at[2]];
908
+ const near = (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) / (Math.hypot(...a) * Math.hypot(...b) || 1);
909
+ if (near > best.near)
910
+ best = { yaw, near };
911
+ }
912
+ return best.yaw;
913
+ }
603
914
  #resolveRide(target, options) {
604
915
  const look = options.look ?? "down";
605
916
  const distanceKm = Math.max(100, options.distanceKm ?? 3000);
@@ -712,11 +1023,15 @@ export class WakuseiSpace extends HTMLElement {
712
1023
  tiles: { ...this.#model.tiles },
713
1024
  door: { points: this.#model.door.points, sources: this.#door.book.stats() },
714
1025
  ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null },
1026
+ travelling: this.#model.travelling === null ? null : { ...this.#model.travelling },
1027
+ region: this.#model.region === null ? null : { id: this.#model.region, name: this.#regionName(this.#model.region), reach: this.#model.regionDrawn?.reach ?? 0, distance: this.#model.regionDrawn?.distance ?? 0 },
715
1028
  orbits: { drawn: [...this.#model.rings.drawn], miss: { ...this.#model.rings.miss }, hidden: [...this.#model.rings.hidden] },
716
1029
  arrows: Object.fromEntries(Object.entries(this.#model.arrows).map(([id, list]) => [id, list.map((a) => ({ position: [...a.position], direction: [...a.direction] }))])),
717
1030
  arrowPx: this.#model.arrowPx,
718
1031
  help: this.#model.helpDrawn ? { body: this.#model.helpDrawn.body, axis: [...this.#model.helpDrawn.axis], pole: [...this.#model.helpDrawn.pole], retrograde: this.#model.helpDrawn.retrograde, arcTurn: [...this.#model.helpDrawn.arcTurn] } : null,
719
1032
  bodyLabels: { count: this.#model.labelsDrawn.count, focus: this.#model.labelsDrawn.focus === null ? null : { ...this.#model.labelsDrawn.focus } },
1033
+ orbiters: { count: this.#model.orbitersDrawn.count, status: { ...this.#model.orbitersDrawn.status } },
1034
+ roadster: { shown: this.#model.roadsterDrawn.shown, position: this.#model.roadsterDrawn.position === null ? null : [...this.#model.roadsterDrawn.position], radiusPx: this.#model.roadsterDrawn.radiusPx },
720
1035
  };
721
1036
  }
722
1037
  // --- the game clock ----------------------------------------------------------------------------------------------------------------------------
@@ -761,7 +1076,12 @@ export class WakuseiSpace extends HTMLElement {
761
1076
  };
762
1077
  // --- labels --------------------------------------------------------------------------------------------------------------------------------------
763
1078
  #nameOf(id) {
764
- return this.#names[id] ?? BODIES[id].name[this.getAttribute("lang") === "ja" ? "ja" : "en"];
1079
+ const lang = this.getAttribute("lang") === "ja" ? "ja" : "en";
1080
+ if (id === "roadster")
1081
+ return this.#names[id] ?? this.#model.roadsterPath?.name[lang] ?? "Starman";
1082
+ if (this.#model.orbiterSet !== null && this.#model.orbiterSet.ids.includes(id))
1083
+ return this.#names[id] ?? this.#model.orbiterSet.name(id)[lang];
1084
+ return this.#names[id] ?? BODIES[id].name[lang];
765
1085
  }
766
1086
  #placeLabels(places) {
767
1087
  this.#places = places;
@@ -889,6 +1209,10 @@ export class WakuseiSpace extends HTMLElement {
889
1209
  return 0;
890
1210
  if (id === "sun")
891
1211
  return 1;
1212
+ if (id === "roadster")
1213
+ return 3;
1214
+ if (this.#model.orbiterSet !== null && this.#model.orbiterSet.ids.includes(id))
1215
+ return 5;
892
1216
  const kind = bodyKindOf(id);
893
1217
  return kind === "moon" ? 4 : kind === "planet" || kind === "star" ? 2 : 3;
894
1218
  }
@@ -995,6 +1319,11 @@ export class WakuseiSpace extends HTMLElement {
995
1319
  * the middle of the view (`goTo`), unless it already is, so a press never sends the view anywhere else.
996
1320
  */
997
1321
  #press(id) {
1322
+ // the Roadster and the orbiters are no bodies of the package: a press on such a name says so and goes nowhere
1323
+ if (id === "roadster" || (this.#model.orbiterSet !== null && this.#model.orbiterSet.ids.includes(id))) {
1324
+ this.dispatchEvent(new CustomEvent("wakusei-body-click", { detail: { id, name: this.#nameOf(id), kind: "spacecraft" }, bubbles: true, composed: true }));
1325
+ return;
1326
+ }
998
1327
  this.dispatchEvent(new CustomEvent("wakusei-body-click", { detail: this.bodyInfo(id), bubbles: true, composed: true }));
999
1328
  if (this.#selected === id) {
1000
1329
  if (canCentre(id) && this.#model.focus !== id)
@@ -124,6 +124,20 @@ export interface SpaceFrame {
124
124
  /** The minor bodies: Vesta, Pallas, Chiron, Pholus and Halley's comet, from tables fitted to Horizons (outside their years, from osculating elements). */
125
125
  minors: Record<SpaceMinor, Vec3>;
126
126
  }
127
+ /**
128
+ * An ecliptic J2000 vector in the scene's axes (equatorial J2000, y north): what `frameAt` does to every heliocentric place, for a place of your own (the Roadster's, from `/roadster`).
129
+ *
130
+ * @param v - A vector in ecliptic J2000 axes.
131
+ * @returns The same vector in the scene's axes.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * import { eclipticToScene } from "@johnmorrisdotca/wakusei-planets/space";
136
+ *
137
+ * console.log(eclipticToScene([0, 1, 0]).map((n) => n.toFixed(3)).join(", "));
138
+ * ```
139
+ */
140
+ export declare function eclipticToScene(v: Vec3): Vec3;
127
141
  /**
128
142
  * The state of the sky at `ms`: the Sun, the Moon and eight planets as seen from the Earth's centre, worked out by this package's own models in a fraction of a millisecond.
129
143
  *
@@ -64,6 +64,22 @@ export const SPACE_DWARFS = DWARF_IDS;
64
64
  * ```
65
65
  */
66
66
  export const SPACE_MINORS = MINOR_IDS;
67
+ /**
68
+ * An ecliptic J2000 vector in the scene's axes (equatorial J2000, y north): what `frameAt` does to every heliocentric place, for a place of your own (the Roadster's, from `/roadster`).
69
+ *
70
+ * @param v - A vector in ecliptic J2000 axes.
71
+ * @returns The same vector in the scene's axes.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { eclipticToScene } from "@johnmorrisdotca/wakusei-planets/space";
76
+ *
77
+ * console.log(eclipticToScene([0, 1, 0]).map((n) => n.toFixed(3)).join(", "));
78
+ * ```
79
+ */
80
+ export function eclipticToScene(v) {
81
+ return scene(v);
82
+ }
67
83
  /** An ecliptic J2000 vector in the scene's axes (equatorial J2000, y north). */
68
84
  const scene = (v) => {
69
85
  const c = Math.cos(OBLIQUITY * RAD);
@@ -1,4 +1,4 @@
1
- export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, moonOrbit, planetOrbit, SPACE_DWARFS, SPACE_MINORS, SPACE_PLANETS, type SpaceDwarf, type SpaceFrame, type SpaceMinor, type SpacePlanet, type SpaceVec3 } from "./frame.ts";
1
+ export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, eclipticToScene, frameAt, moonOrbit, planetOrbit, SPACE_DWARFS, SPACE_MINORS, SPACE_PLANETS, type SpaceDwarf, type SpaceFrame, type SpaceMinor, type SpacePlanet, type SpaceVec3 } from "./frame.ts";
2
2
  export { compress, MOON_COMPRESSED, moonDistance, orbitLine, placeAround, placeBodies, placeMoon, placeSun, radiusIn, SUN_COMPRESSED, truePosition, type ScaleMode } from "./scale.ts";
3
3
  export { groundDirection } from "./aim.ts";
4
4
  export { RIDE_FOV, ridePose, type RideInput, type RideLook, type RidePose } from "./ride.ts";
@@ -8,3 +8,5 @@ export { besideMoon, BESIDE_RADII, type BesideCamera, type BesideInput } from ".
8
8
  export { ARROWS_PER_ORBIT, arrowCount, arrowSites, MAX_ARROWS_PER_ORBIT, chevron, spinArrow, type OrbitArrow } from "./arrows.ts";
9
9
  export { spinAxis, type SpinAxis } from "./spin.ts";
10
10
  export { COVER_ARROW_GAP, COVER_MIN_PX, coverArrows, coveredBy, type CoverArrow, type CoverEntry } from "./covered.ts";
11
+ export { TRAVEL_CLEARANCE, travelArrival, travelPlan, travelPose, type TravelBody, type TravelInput, type TravelKind, type TravelPlan, type TravelSample, type TravelSight, type TravelView } from "./travel.ts";
12
+ export { regionOrbits, regionView, SUN_REGIONS, type SunRegion } from "./regions.ts";
@@ -1,5 +1,5 @@
1
1
  // The space view's pure parts: where the bodies are (this package's own models), the two scales and, for riding along, where a camera looks. They import on a server. The element is `@johnmorrisdotca/wakusei-planets/space/element`.
2
- export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, moonOrbit, planetOrbit, SPACE_DWARFS, SPACE_MINORS, SPACE_PLANETS } from "./frame.js";
2
+ export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, eclipticToScene, frameAt, moonOrbit, planetOrbit, SPACE_DWARFS, SPACE_MINORS, SPACE_PLANETS } from "./frame.js";
3
3
  export { compress, MOON_COMPRESSED, moonDistance, orbitLine, placeAround, placeBodies, placeMoon, placeSun, radiusIn, SUN_COMPRESSED, truePosition } from "./scale.js";
4
4
  export { groundDirection } from "./aim.js";
5
5
  export { RIDE_FOV, ridePose } from "./ride.js";
@@ -9,3 +9,5 @@ export { besideMoon, BESIDE_RADII } from "./beside.js";
9
9
  export { ARROWS_PER_ORBIT, arrowCount, arrowSites, MAX_ARROWS_PER_ORBIT, chevron, spinArrow } from "./arrows.js";
10
10
  export { spinAxis } from "./spin.js";
11
11
  export { COVER_ARROW_GAP, COVER_MIN_PX, coverArrows, coveredBy } from "./covered.js";
12
+ export { TRAVEL_CLEARANCE, travelArrival, travelPlan, travelPose } from "./travel.js";
13
+ export { regionOrbits, regionView, SUN_REGIONS } from "./regions.js";