@johnmorrisdotca/wakusei-planets 0.60.0 → 0.61.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.
@@ -1,7 +1,3 @@
1
- // Driving the lunar rover: a vehicle on four wheels over the same ground the eyes walk on. The step is pure and small: throttle and steering in, the rover's place, heading, height, pitch and roll out, the chassis
2
- // settling on a spring over the four places its wheels touch, free in the air where the ground falls away (the Moon's gravity is a sixth of ours, so a crest throws it). The ground is whatever function the page gives:
3
- // the measured heights and the made craters, so the rover follows the craters exactly. What is real: the rover's size, the gravity and a top speed near the published one. What is made: the feel of the spring, the
4
- // steering, the limits on a slope. No DOM.
5
1
  import { roverParts } from "./shapes.js";
6
2
  /**
7
3
  * The rover's measures: those published (its length and width, the wheels' size and the wheelbase, the gravity of the Moon) and those chosen here (the speeds, the steering, the slope it will not climb, the spring).
@@ -76,10 +72,10 @@ export function toWorld(state, p) {
76
72
  return [state.east + x1 * c + z2 * s, state.y + y2, state.north - x1 * s + z2 * c];
77
73
  }
78
74
  /** The ground under each wheel, at the places the four wheels are. */
79
- function wheelGrounds(state, ground) {
75
+ function wheelGrounds(state, ground, rig) {
80
76
  const h = state.heading * RAD;
81
77
  const [c, s] = [Math.cos(h), Math.sin(h)];
82
- return ROVER.wheels.map(([x, , z]) => ground(state.east + x * c + z * s, state.north - x * s + z * c));
78
+ return rig.wheels.map(([x, , z]) => ground(state.east + x * c + z * s, state.north - x * s + z * c));
83
79
  }
84
80
  /**
85
81
  * One step of driving: the speed follows the throttle (slowed uphill by the Moon's gravity, stopped by a slope over 25 degrees and by anything in `blocked`), the heading follows the steering (the four wheels steer, the
@@ -90,6 +86,7 @@ function wheelGrounds(state, ground) {
90
86
  * @param dt - Seconds (at most 0.05 are used; call it more often for a longer time).
91
87
  * @param ground - The ground's height over the site's ground at a place.
92
88
  * @param blocked - True at a place the rover cannot go (a big rock, the lunar module).
89
+ * @param rig - The vehicle's measures (its wheels' places and size); the lunar rover's by default, a model's from `rigOf`.
93
90
  * @returns The rover a moment later.
94
91
  *
95
92
  * @example
@@ -101,7 +98,7 @@ function wheelGrounds(state, ground) {
101
98
  * console.log(`${rover.north.toFixed(1)} m north after two seconds, at ${rover.speed.toFixed(1)} m/s`);
102
99
  * ```
103
100
  */
104
- export function driveStep(state, input, dt, ground, blocked) {
101
+ export function driveStep(state, input, dt, ground, blocked, rig = ROVER) {
105
102
  const d = Math.min(Math.max(dt, 0), 0.05);
106
103
  const next = { ...state, spin: [...state.spin] };
107
104
  const throttle = Math.min(1, Math.max(-1, input.throttle));
@@ -122,11 +119,11 @@ export function driveStep(state, input, dt, ground, blocked) {
122
119
  if (Math.abs(throttle) < 0.02 && Math.abs(next.speed) < 0.08 && Math.abs(state.pitch) < ROVER.maxSlope)
123
120
  next.speed = 0;
124
121
  // the heading: four wheels steer, so the turn is tight; the move
125
- const yaw = (next.speed * 2 * Math.tan(next.steer)) / ROVER.wheelbase;
122
+ const yaw = (next.speed * 2 * Math.tan(next.steer)) / rig.wheelbase;
126
123
  next.heading = (((state.heading + yaw * d * (180 / Math.PI)) % 360) + 360) % 360;
127
124
  const h = next.heading * RAD;
128
125
  const [e, n] = [state.east + Math.sin(h) * next.speed * d, state.north + Math.cos(h) * next.speed * d];
129
- const front = [e + Math.sin(h) * ROVER.length * 0.5, n + Math.cos(h) * ROVER.length * 0.5];
126
+ const front = [e + Math.sin(h) * rig.length * 0.5, n + Math.cos(h) * rig.length * 0.5];
130
127
  if (next.speed !== 0 && blocked !== undefined && (blocked(e, n) || blocked(front[0], front[1]))) {
131
128
  next.speed = 0;
132
129
  }
@@ -136,11 +133,11 @@ export function driveStep(state, input, dt, ground, blocked) {
136
133
  next.distance += Math.abs(next.speed) * d;
137
134
  }
138
135
  // the ground under the four wheels: the plane they make, and where the rover sits over it
139
- const g = wheelGrounds(next, ground);
136
+ const g = wheelGrounds(next, ground, rig);
140
137
  const [fl, fr, rl, rr] = [g[0], g[1], g[2], g[3]];
141
138
  const rest = (fl + fr + rl + rr) / 4;
142
- const pitchTarget = Math.atan2((fl + fr) / 2 - (rl + rr) / 2, ROVER.wheelbase);
143
- const rollTarget = Math.atan2((fr + rr) / 2 - (fl + rl) / 2, ROVER.track);
139
+ const pitchTarget = Math.atan2((fl + fr) / 2 - (rl + rr) / 2, rig.wheelbase);
140
+ const rollTarget = Math.atan2((fr + rr) / 2 - (fl + rl) / 2, rig.track);
144
141
  const settle = 1 - Math.exp(-d * 10);
145
142
  next.pitch += (pitchTarget - next.pitch) * settle;
146
143
  next.roll += (rollTarget - next.roll) * settle;
@@ -156,7 +153,7 @@ export function driveStep(state, input, dt, ground, blocked) {
156
153
  if (next.vy < 0)
157
154
  next.vy *= -0.15; // the springs take most of a landing
158
155
  }
159
- const turn = (next.speed * d) / ROVER.wheelRadius;
156
+ const turn = (next.speed * d) / rig.wheelRadius;
160
157
  for (let i = 0; i < 4; i += 1)
161
158
  next.spin[i] = (next.spin[i] + turn) % (Math.PI * 2);
162
159
  return next;
@@ -227,6 +224,7 @@ export function driveParts(state) {
227
224
  * @param offset - The driver's turn of the view, degrees right and up.
228
225
  * @param ground - The ground's height over the site's ground at a place.
229
226
  * @param drag - What a drag does in the chase view: `head` or `orbit` (the default).
227
+ * @param rig - The vehicle's measures (where its eyes are); the lunar rover's by default, a model's from `rigOf`.
230
228
  * @returns The eyes.
231
229
  *
232
230
  * @example
@@ -239,9 +237,9 @@ export function driveParts(state) {
239
237
  * console.log(view.eye.north.toFixed(1), turned.eye.north.toFixed(1), turned.azimuth);
240
238
  * ```
241
239
  */
242
- export function driveView(state, view, offset, ground, drag = "orbit") {
240
+ export function driveView(state, view, offset, ground, drag = "orbit", rig = ROVER) {
243
241
  if (view === "seat") {
244
- const eye = toWorld(state, ROVER.seat);
242
+ const eye = toWorld(state, rig.seat);
245
243
  return { eye: { east: eye[0], north: eye[2], up: eye[1] }, azimuth: (((state.heading + offset.azimuth) % 360) + 360) % 360, pitch: state.pitch / RAD + offset.pitch };
246
244
  }
247
245
  // the eyes stand behind the rover along the heading turned by the drag (`orbit`: they go round it) or along the heading alone (`head`: they keep their place and only the look turns)
@@ -2,6 +2,7 @@ import type { SharedRenderer } from "@johnmorrisdotca/kazoku-ui/renderer";
2
2
  import type { ThreeParts } from "../scene/body.ts";
3
3
  import { setThreeLoader } from "../scene/shared.ts";
4
4
  import { type DriveDrag, type DriveState } from "./drive.ts";
5
+ import type { Rig } from "./rig.ts";
5
6
  import { type HeightLevel, type TerrainManifest } from "./height.ts";
6
7
  import { type TerrainProgress } from "./load.ts";
7
8
  import { type SurfaceScene } from "./scene.ts";
@@ -118,6 +119,23 @@ export declare class WakuseiSurface extends HTMLElement {
118
119
  set driveDrag(value: DriveDrag);
119
120
  /** The rover being driven, or `undefined` when it is not. */
120
121
  get vehicle(): DriveState | undefined;
122
+ /**
123
+ * The rover model being drawn in place of the shapes, with the node names it has and the angles its wheels and pivots were last set to; `undefined` while none is asked for (`drive-model`), while it loads or when it could not be loaded.
124
+ *
125
+ * @example
126
+ * ```ts no-run
127
+ * const surface = document.querySelector("wakusei-surface") as HTMLElement & { driveModel?: { url: string; nodes: readonly string[] } };
128
+ * surface.addEventListener("wakusei-model", () => console.log(surface.driveModel?.nodes.join(" ")));
129
+ * surface.setAttribute("drive-model", "/models/perseverance.glb");
130
+ * ```
131
+ */
132
+ get driveModel(): {
133
+ url: string;
134
+ nodes: readonly string[];
135
+ angles: Readonly<Record<string, number>>;
136
+ rig: Rig;
137
+ renders: number;
138
+ } | undefined;
121
139
  /**
122
140
  * Drive by a set time, whatever the clock says: advance the rover `seconds` with the throttle and steering given (each -1 to 1) and draw. For a test or a sequence of pictures taken one step at a time; the keys and the
123
141
  * stick do the same by the real time between frames.
@@ -130,7 +148,26 @@ export declare class WakuseiSurface extends HTMLElement {
130
148
  throttle: number;
131
149
  steer: number;
132
150
  }): boolean;
133
- /** The descent being watched: its clock in seconds from ignition, whether it runs, the camera and what the lunar module is doing at that moment; `undefined` when it is not watched. */
151
+ /**
152
+ * The descent being watched: its clock in seconds from ignition, whether it runs, the camera and what the lunar module is doing at that moment; `undefined` when it is not watched.
153
+ *
154
+ * Two events say what happens to it, both bubbling and composed. `wakusei-landing-state` is sent when it starts or stops running (`playLanding()`, `pauseLanding()`, and the clock reaching the touchdown),
155
+ * when `landingRate` changes and when `watch-camera` changes; its `detail` is `{ t, playing, rate, camera, ended }` (`t` in seconds from ignition, `ended` true at the touchdown), so a page can keep the pause
156
+ * state without reading `landing` every second. `wakusei-landing-ended` is sent once each time the clock arrives at the touchdown (T+12:05, 725 s), by running or by a seek; its `detail` is
157
+ * `{ t: 725, rate, camera }`, and it is sent again only after the clock has left the touchdown and come back.
158
+ *
159
+ * @example
160
+ * ```ts no-run
161
+ * import type { WakuseiSurface } from "@johnmorrisdotca/wakusei-planets/surface/element";
162
+ *
163
+ * const view = document.querySelector("wakusei-surface") as WakuseiSurface;
164
+ * view.addEventListener("wakusei-landing-state", (event) => {
165
+ * const { playing, rate, camera } = (event as CustomEvent).detail;
166
+ * location.hash = `${playing ? "play" : "pause"}-${rate}-${camera}`;
167
+ * });
168
+ * view.addEventListener("wakusei-landing-ended", () => console.log("the lunar module is down"));
169
+ * ```
170
+ */
134
171
  get landing(): {
135
172
  t: number;
136
173
  playing: boolean;
@@ -66,7 +66,7 @@ const num = (value, fallback) => {
66
66
  * ```
67
67
  */
68
68
  export class WakuseiSurface extends HTMLElement {
69
- static observedAttributes = ["quality", "shadows", "detail", "exposure", "site", "time", "heading", "pitch", "fov", "tiles", "lang", "body", "standby", "scale", "stick", "objects", "drive", "drive-camera", "drive-drag", "watch", "watch-from", "watch-camera"];
69
+ static observedAttributes = ["quality", "shadows", "detail", "exposure", "site", "time", "heading", "pitch", "fov", "tiles", "lang", "body", "standby", "scale", "stick", "objects", "drive", "drive-camera", "drive-drag", "drive-model", "watch", "watch-from", "watch-camera"];
70
70
  #root;
71
71
  #stage;
72
72
  #noteEl;
@@ -114,6 +114,10 @@ export class WakuseiSurface extends HTMLElement {
114
114
  #chosen;
115
115
  /** The rover being driven (`drive="on"`), the view of it, the driver's own turn of the view, the path left, the dust thrown, and the places it cannot go. */
116
116
  #vehicle;
117
+ /** The rover model asked for with `drive-model`, once it has loaded, and the address it was asked for at. */
118
+ #model;
119
+ #modelUrl = "";
120
+ #modelAbort;
117
121
  #driveCamera = "chase";
118
122
  #camOffset = { azimuth: 0, pitch: 0 };
119
123
  #driveEyeUp = 0;
@@ -236,6 +240,7 @@ export class WakuseiSurface extends HTMLElement {
236
240
  clearTimeout(this.#landingTimer);
237
241
  this.#gate?.cancel();
238
242
  clearTimeout(this.#walkTimer);
243
+ this.#dropModel();
239
244
  for (const [type, fn] of [["pointerdown", this.#onPointerDown], ["pointermove", this.#onPointerMove], ["pointerup", this.#onPointerUp], ["pointercancel", this.#onPointerUp], ["wheel", this.#onWheel], ["keydown", this.#onKeyDown], ["keyup", this.#onKeyUp], ["blur", this.#onBlur]])
240
245
  this.removeEventListener(type, fn);
241
246
  this.#view?.dispose();
@@ -255,6 +260,10 @@ export class WakuseiSurface extends HTMLElement {
255
260
  this.#syncLanding(name !== "watch");
256
261
  return;
257
262
  }
263
+ if (name === "drive-model") {
264
+ this.#syncModel();
265
+ return;
266
+ }
258
267
  if (name === "drive-camera") {
259
268
  this.driveCamera = this.getAttribute("drive-camera") === "seat" ? "seat" : "chase";
260
269
  return;
@@ -499,7 +508,7 @@ export class WakuseiSurface extends HTMLElement {
499
508
  this.#measured += 1;
500
509
  if (this.#drawScale < 1)
501
510
  this.#scaled += 1;
502
- scene.apply({ eye: { east: this.#at.east, north: this.#at.north, up: this.#eyeUp() }, look: this.#look, sky: this.#sky, shadows: this.getAttribute("shadows") !== "off", detail: this.getAttribute("detail") !== "off", exposure: num(this.getAttribute("exposure"), 1.6), quality: this.#quality(), scale: this.#drawScale, objects: this.#objects.length > 0, ...(this.#vehicle === undefined ? {} : { vehicle: this.#vehicle, trail: this.#trail, dust: this.#dust.position }), ...(this.#landing === undefined ? {} : { lander: this.#landerState(), dust: this.#dust.position }), measure: measure || this.getAttribute("measure") !== null });
511
+ scene.apply({ eye: { east: this.#at.east, north: this.#at.north, up: this.#eyeUp() }, look: this.#look, sky: this.#sky, shadows: this.getAttribute("shadows") !== "off", detail: this.getAttribute("detail") !== "off", exposure: num(this.getAttribute("exposure"), 1.6), quality: this.#quality(), scale: this.#drawScale, objects: this.#objects.length > 0, ...(this.#vehicle === undefined ? {} : { vehicle: this.#vehicle, ...(this.#model === undefined ? {} : { model: this.#model }), trail: this.#trail, dust: this.#dust.position }), ...(this.#landing === undefined ? {} : { lander: this.#landerState(), dust: this.#dust.position }), measure: measure || this.getAttribute("measure") !== null });
503
512
  this.#view.invalidate();
504
513
  this.#draws += 1;
505
514
  this.#placeLabels();
@@ -545,6 +554,7 @@ export class WakuseiSurface extends HTMLElement {
545
554
  const v = this.#vehicle;
546
555
  this.#vehicle = undefined;
547
556
  this.#trail = [];
557
+ this.#dropModel();
548
558
  this.#at = { east: v.east, north: v.north };
549
559
  this.#changed();
550
560
  return;
@@ -562,15 +572,78 @@ export class WakuseiSurface extends HTMLElement {
562
572
  for (const el of this.#labelEls.values())
563
573
  el.hidden = true;
564
574
  this.choose(undefined);
575
+ this.#syncModel();
565
576
  this.#syncDriveCamera();
566
577
  this.#changed();
567
578
  }
579
+ /** The vehicle's measures: a loaded model's, or the lunar rover's. */
580
+ #rig() {
581
+ return this.#model?.rig ?? ROVER;
582
+ }
583
+ /**
584
+ * The rover model being drawn in place of the shapes, with the node names it has and the angles its wheels and pivots were last set to; `undefined` while none is asked for (`drive-model`), while it loads or when it could not be loaded.
585
+ *
586
+ * @example
587
+ * ```ts no-run
588
+ * const surface = document.querySelector("wakusei-surface") as HTMLElement & { driveModel?: { url: string; nodes: readonly string[] } };
589
+ * surface.addEventListener("wakusei-model", () => console.log(surface.driveModel?.nodes.join(" ")));
590
+ * surface.setAttribute("drive-model", "/models/perseverance.glb");
591
+ * ```
592
+ */
593
+ get driveModel() {
594
+ const m = this.#model;
595
+ return m === undefined ? undefined : { url: this.#modelUrl, nodes: m.nodes, angles: { ...m.angles }, rig: m.rig, renders: m.renders };
596
+ }
597
+ #dropModel() {
598
+ this.#modelAbort?.abort();
599
+ this.#modelAbort = undefined;
600
+ this.#model?.dispose();
601
+ this.#model = undefined;
602
+ this.#modelUrl = "";
603
+ }
604
+ /**
605
+ * Load the model `drive-model` names, once the rover is being driven: its file is fetched and its loader imported only then. Until it is in (or if it cannot be loaded) the shapes are drawn; `wakusei-model` is sent when it is
606
+ * drawn, with `detail.url` and `detail.nodes`, and `wakusei-model-error` with `detail.url` and `detail.reason` when it cannot be.
607
+ */
608
+ #syncModel() {
609
+ const url = this.getAttribute("drive-model") ?? "";
610
+ if (this.#vehicle === undefined || url === "") {
611
+ this.#dropModel();
612
+ if (this.#vehicle !== undefined)
613
+ this.#changed();
614
+ return;
615
+ }
616
+ if (url === this.#modelUrl)
617
+ return;
618
+ this.#dropModel();
619
+ this.#modelUrl = url;
620
+ const abort = new AbortController();
621
+ this.#modelAbort = abort;
622
+ void import("./model.js")
623
+ .then((m) => m.loadVehicleModel(url, { signal: abort.signal }))
624
+ .then((model) => {
625
+ if (abort.signal.aborted) {
626
+ model.dispose();
627
+ return;
628
+ }
629
+ this.#model = model;
630
+ this.#syncDriveCamera();
631
+ this.#changed();
632
+ this.dispatchEvent(new CustomEvent("wakusei-model", { detail: { url, nodes: model.nodes }, bubbles: true, composed: true }));
633
+ })
634
+ .catch((error) => {
635
+ if (abort.signal.aborted)
636
+ return;
637
+ this.#modelUrl = "";
638
+ this.dispatchEvent(new CustomEvent("wakusei-model-error", { detail: { url, reason: error instanceof Error ? error.message : String(error) }, bubbles: true, composed: true }));
639
+ });
640
+ }
568
641
  /** The eyes where the view of the rover puts them. */
569
642
  #syncDriveCamera() {
570
643
  const v = this.#vehicle;
571
644
  if (v === undefined)
572
645
  return;
573
- const view = driveView(v, this.#driveCamera, this.#camOffset, (e, n) => this.#groundAt(e, n), this.driveDrag);
646
+ const view = driveView(v, this.#driveCamera, this.#camOffset, (e, n) => this.#groundAt(e, n), this.driveDrag, this.#rig());
574
647
  this.#at = { east: view.eye.east, north: view.eye.north };
575
648
  this.#driveEyeUp = view.eye.up;
576
649
  this.#look = clampLook({ azimuth: view.azimuth, pitch: view.pitch, fov: this.#look.fov });
@@ -599,17 +672,18 @@ export class WakuseiSurface extends HTMLElement {
599
672
  const ground = (e, n) => this.#groundAt(e, n);
600
673
  const blockers = this.#obstacles();
601
674
  const blocked = (e, n) => blockers.some((b) => (e - b.x) ** 2 + (n - b.y) ** 2 < b.r * b.r);
675
+ const rig = this.#rig();
602
676
  const steps = Math.max(1, Math.ceil(seconds * 60));
603
677
  const dt = seconds / steps;
604
678
  for (let i = 0; i < steps; i += 1) {
605
- v = driveStep(v, input, dt, ground, blocked);
679
+ v = driveStep(v, input, dt, ground, blocked, rig);
606
680
  // each wheel on the ground throws grains up and back: the faster, the more
607
681
  if (!v.airborne && Math.abs(v.speed) > 0.6) {
608
682
  const h = (v.heading * Math.PI) / 180;
609
683
  const [fx, fz] = [Math.sin(h), Math.cos(h)];
610
684
  const grains = Math.abs(v.speed) * dt * 26;
611
685
  const [rx, rz] = [Math.cos(h), -Math.sin(h)];
612
- for (const [wx, , wz] of ROVER.wheels) {
686
+ for (const [wx, , wz] of rig.wheels) {
613
687
  const w = toWorld(v, [wx, 0, wz]);
614
688
  for (let k = 0; k < grains + Math.random() * 0.999; k += 1) {
615
689
  // thrown up and back from the tyre in a fan: the faster the rover, the wider and farther
@@ -659,7 +733,26 @@ export class WakuseiSurface extends HTMLElement {
659
733
  return true;
660
734
  }
661
735
  // --- watching the landing (`watch="landing"`): Apollo 17's powered descent from the lunar module's window or from the ground ---------------------------------------------------------------------
662
- /** The descent being watched: its clock in seconds from ignition, whether it runs, the camera and what the lunar module is doing at that moment; `undefined` when it is not watched. */
736
+ /**
737
+ * The descent being watched: its clock in seconds from ignition, whether it runs, the camera and what the lunar module is doing at that moment; `undefined` when it is not watched.
738
+ *
739
+ * Two events say what happens to it, both bubbling and composed. `wakusei-landing-state` is sent when it starts or stops running (`playLanding()`, `pauseLanding()`, and the clock reaching the touchdown),
740
+ * when `landingRate` changes and when `watch-camera` changes; its `detail` is `{ t, playing, rate, camera, ended }` (`t` in seconds from ignition, `ended` true at the touchdown), so a page can keep the pause
741
+ * state without reading `landing` every second. `wakusei-landing-ended` is sent once each time the clock arrives at the touchdown (T+12:05, 725 s), by running or by a seek; its `detail` is
742
+ * `{ t: 725, rate, camera }`, and it is sent again only after the clock has left the touchdown and come back.
743
+ *
744
+ * @example
745
+ * ```ts no-run
746
+ * import type { WakuseiSurface } from "@johnmorrisdotca/wakusei-planets/surface/element";
747
+ *
748
+ * const view = document.querySelector("wakusei-surface") as WakuseiSurface;
749
+ * view.addEventListener("wakusei-landing-state", (event) => {
750
+ * const { playing, rate, camera } = (event as CustomEvent).detail;
751
+ * location.hash = `${playing ? "play" : "pause"}-${rate}-${camera}`;
752
+ * });
753
+ * view.addEventListener("wakusei-landing-ended", () => console.log("the lunar module is down"));
754
+ * ```
755
+ */
663
756
  get landing() {
664
757
  const l = this.#landing;
665
758
  if (l === undefined)
@@ -689,8 +782,14 @@ export class WakuseiSurface extends HTMLElement {
689
782
  return this.#landing?.rate ?? 1;
690
783
  }
691
784
  set landingRate(value) {
692
- if (this.#landing !== undefined)
693
- this.#landing.rate = Math.min(16, Math.max(0.25, value));
785
+ const l = this.#landing;
786
+ if (l === undefined)
787
+ return;
788
+ const rate = Math.min(16, Math.max(0.25, value));
789
+ if (rate === l.rate)
790
+ return;
791
+ l.rate = rate;
792
+ this.#landingAnnounce();
694
793
  }
695
794
  /** Run the descent from where the clock is (from the start again if it had ended). */
696
795
  playLanding() {
@@ -699,17 +798,31 @@ export class WakuseiSurface extends HTMLElement {
699
798
  return;
700
799
  if (l.t >= LANDING.duration)
701
800
  this.landingTime = l.camera === "ground" ? 540 : LANDING.viewStart;
801
+ const was = l.playing;
702
802
  l.playing = true;
703
803
  this.#landingAt = performance.now();
804
+ if (!was)
805
+ this.#landingAnnounce();
704
806
  this.#landingTick();
705
807
  }
706
808
  /** Hold the descent where it is. */
707
809
  pauseLanding() {
708
- if (this.#landing === undefined)
810
+ const l = this.#landing;
811
+ if (l === undefined)
709
812
  return;
710
- this.#landing.playing = false;
813
+ const was = l.playing;
814
+ l.playing = false;
711
815
  clearTimeout(this.#landingTimer);
712
816
  this.#landingFrame(0, true);
817
+ if (was)
818
+ this.#landingAnnounce();
819
+ }
820
+ /** Tell a page the descent's state changed: `wakusei-landing-state` with the clock, whether it runs, the rate, the camera and whether it has ended. */
821
+ #landingAnnounce() {
822
+ const l = this.#landing;
823
+ if (l === undefined)
824
+ return;
825
+ this.dispatchEvent(new CustomEvent("wakusei-landing-state", { detail: { t: l.t, playing: l.playing, rate: l.rate, camera: l.camera, ended: l.t >= LANDING.duration }, bubbles: true, composed: true }));
713
826
  }
714
827
  /** The touchdown point: where the lunar module stands at Apollo 17 (the published place), or the site point where it has none. */
715
828
  #touchdown() {
@@ -746,13 +859,16 @@ export class WakuseiSurface extends HTMLElement {
746
859
  return;
747
860
  if (this.#landing.camera !== camera)
748
861
  this.#look = clampLook({ ...this.#look, fov: camera === "ground" ? 27 : 74 });
862
+ const changed = this.#landing.camera !== camera;
749
863
  this.#landing.camera = camera;
750
864
  this.#landing.from = from;
751
865
  this.#camOffset = { azimuth: 0, pitch: 0 };
752
866
  this.#landingFrame(0, true);
867
+ if (changed)
868
+ this.#landingAnnounce();
753
869
  return;
754
870
  }
755
- this.#landing = { t: camera === "ground" ? 540 : LANDING.viewStart, playing: true, rate: 1, camera, from, passed: 0, second: -1 };
871
+ this.#landing = { t: camera === "ground" ? 540 : LANDING.viewStart, playing: true, rate: 1, camera, from, passed: 0, second: -1, ended: false };
756
872
  this.#landing.passed = calloutsBy(this.#landing.t).length;
757
873
  this.#dust = new DustField(20000, 17);
758
874
  this.#camOffset = { azimuth: 0, pitch: 0 };
@@ -772,6 +888,13 @@ export class WakuseiSurface extends HTMLElement {
772
888
  const l = this.#landing;
773
889
  if (l === undefined)
774
890
  return;
891
+ // arriving at the touchdown, by running or by a seek, stops the clock
892
+ const atEnd = l.t >= LANDING.duration;
893
+ const stopped = atEnd && l.playing;
894
+ if (stopped) {
895
+ l.playing = false;
896
+ clearTimeout(this.#landingTimer);
897
+ }
775
898
  const pose = landingAt(l.t);
776
899
  const td = this.#touchdown();
777
900
  const ground = (e, n) => this.#groundAt(e, n);
@@ -859,6 +982,15 @@ export class WakuseiSurface extends HTMLElement {
859
982
  l.second = second;
860
983
  this.dispatchEvent(new CustomEvent("wakusei-landing-clock", { detail: { t: l.t, clock, altitude: pose.altitude, speed: pose.speed, descent: pose.descent, playing: l.playing, callout: newest === undefined ? undefined : { id: newest.id, t: newest.t, en: newest.en, ja: newest.ja, reported: newest.reported } }, bubbles: true, composed: true }));
861
984
  }
985
+ if (stopped)
986
+ this.#landingAnnounce();
987
+ // the descent ends once each time the clock arrives at the touchdown; a seek back or a play from the start makes it ready to end again
988
+ if (atEnd && !l.ended) {
989
+ l.ended = true;
990
+ this.dispatchEvent(new CustomEvent("wakusei-landing-ended", { detail: { t: l.t, rate: l.rate, camera: l.camera }, bubbles: true, composed: true }));
991
+ }
992
+ else if (!atEnd)
993
+ l.ended = false;
862
994
  this.#changed(l.playing);
863
995
  }
864
996
  /** While the descent runs: the clock moves by the real time between frames (times the rate), at most thirty times a second; at the touchdown, or paused, nothing is drawn. */
@@ -872,10 +1004,8 @@ export class WakuseiSurface extends HTMLElement {
872
1004
  this.#landingAt = now;
873
1005
  const seconds = Math.min(dt * l.rate, LANDING.duration - l.t);
874
1006
  l.t += seconds;
875
- if (l.t >= LANDING.duration - 1e-6) {
1007
+ if (l.t >= LANDING.duration - 1e-6)
876
1008
  l.t = LANDING.duration;
877
- l.playing = false;
878
- }
879
1009
  this.#landingFrame(seconds, false);
880
1010
  if (l.playing)
881
1011
  this.#landingTimer = setTimeout(this.#landingTick, 33);
@@ -7,6 +7,7 @@ export type { SurfaceState } from "./element.ts";
7
7
  export { ascentParts, landerParts, roverParts } from "./shapes.ts";
8
8
  export { calloutsBy, CALLOUTS, clockText, LANDING, landingAt, type Callout, type LandingPose } from "./landing.ts";
9
9
  export { DustField } from "./dust.ts";
10
+ export { MODEL_NODES, fromModelFrame, modelPose, modelShadowParts, rigOf, type ModelNodes, type Rig } from "./rig.ts";
10
11
  export { driveParts, driveStep, driveView, startDrive, ROVER, type DriveDrag, type DriveInput, type DriveState, type DriveView } from "./drive.ts";
11
12
  export { keepAway, objectParts, objectsOf, partShadows, traverseOf, KEEP_OUT, type Part, type SiteObject } from "./objects.ts";
12
13
  export { craterIn, craterProfile, madeGround, setKeepOut, rimBoost, rocksAround, standingPlace, type Crater, type Rock } from "./detail.ts";
@@ -7,6 +7,7 @@ export { loadPlan, loadTerrain } from "./load.js";
7
7
  export { ascentParts, landerParts, roverParts } from "./shapes.js";
8
8
  export { calloutsBy, CALLOUTS, clockText, LANDING, landingAt } from "./landing.js";
9
9
  export { DustField } from "./dust.js";
10
+ export { MODEL_NODES, fromModelFrame, modelPose, modelShadowParts, rigOf } from "./rig.js";
10
11
  export { driveParts, driveStep, driveView, startDrive, ROVER } from "./drive.js";
11
12
  export { keepAway, objectParts, objectsOf, partShadows, traverseOf, KEEP_OUT } from "./objects.js";
12
13
  export { craterIn, craterProfile, madeGround, setKeepOut, rimBoost, rocksAround, standingPlace } from "./detail.js";
@@ -0,0 +1,54 @@
1
+ import { type DriveState } from "./drive.ts";
2
+ import { type Rig } from "./rig.ts";
3
+ /**
4
+ * A rover model that has been loaded: its rig for the drive step and the calls the scene makes. Made by `loadVehicleModel`.
5
+ *
6
+ * @example
7
+ * ```ts no-run
8
+ * import { loadVehicleModel, type VehicleModel } from "@johnmorrisdotca/wakusei-planets/surface/model";
9
+ *
10
+ * const model: VehicleModel = await loadVehicleModel("/models/perseverance.glb");
11
+ * console.log(model.rig.wheelbase, model.nodes.length);
12
+ * model.dispose();
13
+ * ```
14
+ */
15
+ export interface VehicleModel {
16
+ /** What a drive step and the seat view take from the model. */
17
+ readonly rig: Rig;
18
+ /** The names of the nodes the model has that this package uses (`wheel-fl`, `steer-fr`, `eye`, ...). */
19
+ readonly nodes: readonly string[];
20
+ /** The model's height over the ground, metres. */
21
+ readonly height: number;
22
+ /** Put the model where the drive state is, with the wheels rolled and steered, lit from `sun` (a direction in the scene's frame, east, up, minus north) at `strength` (0 to 1). */
23
+ place(state: DriveState, sun: readonly [number, number, number], strength: number): void;
24
+ /** Draw it with the page's renderer over what is drawn, with the ground's view-projection matrix. */
25
+ render(gl: {
26
+ render(scene: unknown, camera: unknown): void;
27
+ autoClear: boolean;
28
+ }, viewProjection: Float32Array): void;
29
+ /** The roll and steer angles each named node has been set to by the last `place`, for a test. */
30
+ readonly angles: Readonly<Record<string, number>>;
31
+ /** How many times it has been drawn, for a test. */
32
+ readonly renders: number;
33
+ /** Let go of the geometry, the materials and the textures. */
34
+ dispose(): void;
35
+ }
36
+ /**
37
+ * Load a rover model from a GLB and read its rig. The nodes it must give are in `MODEL_NODES`: `wheel-xx` (rolled about X), `steer-xx` (turned about Y) and `eye` or `seat-commander`; a model with no corner wheel is refused.
38
+ * The loader and the meshopt decoder are three.js's own add-ons, imported when this is first called. Each call makes its own copy (the loaded file is read again from the browser's cache), which `dispose()` frees.
39
+ *
40
+ * @param url - Where the GLB is served from.
41
+ * @param options - `signal` to cancel the request.
42
+ * @returns The model, or a rejection when the file cannot be read or has no corner wheel.
43
+ *
44
+ * @example
45
+ * ```ts no-run
46
+ * import { loadVehicleModel } from "@johnmorrisdotca/wakusei-planets/surface/model";
47
+ *
48
+ * const model = await loadVehicleModel("https://johnmorrisdotca.github.io/wakusei-planets/models/perseverance.glb");
49
+ * console.log(model.rig.track.toFixed(2), "m between the wheels");
50
+ * ```
51
+ */
52
+ export declare function loadVehicleModel(url: string, options?: {
53
+ signal?: AbortSignal;
54
+ }): Promise<VehicleModel>;