@johnmorrisdotca/wakusei-planets 0.48.0 → 0.49.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,6 +1,7 @@
1
1
  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
+ import { type DriveState } from "./drive.ts";
4
5
  import { type HeightLevel, type TerrainManifest } from "./height.ts";
5
6
  import { type TerrainProgress } from "./load.ts";
6
7
  import { type SurfaceScene } from "./scene.ts";
@@ -77,6 +78,7 @@ export declare class WakuseiSurface extends HTMLElement {
77
78
  quality: string;
78
79
  scale: number;
79
80
  scaled: number;
81
+ vehicle: DriveState | undefined;
80
82
  drawMs: number | undefined;
81
83
  rocks: number;
82
84
  };
@@ -90,6 +92,23 @@ export declare class WakuseiSurface extends HTMLElement {
90
92
  * @param aside - Metres to the right.
91
93
  */
92
94
  walk(ahead: number, aside?: number): void;
95
+ /** Which view of the rover: `chase` (from behind and above, the default) or `seat` (the commander's). The key C turns from one to the other. */
96
+ get driveCamera(): "chase" | "seat";
97
+ set driveCamera(value: "chase" | "seat");
98
+ /** The rover being driven, or `undefined` when it is not. */
99
+ get vehicle(): DriveState | undefined;
100
+ /**
101
+ * 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
102
+ * stick do the same by the real time between frames.
103
+ *
104
+ * @param seconds - How long to drive.
105
+ * @param input - The throttle and the steering.
106
+ * @returns Whether the element is driving.
107
+ */
108
+ driveFor(seconds: number, input?: {
109
+ throttle: number;
110
+ steer: number;
111
+ }): boolean;
93
112
  /** The things at the site, at their published places (none where the site has none or `objects="off"`). */
94
113
  get objects(): readonly SiteObject[];
95
114
  /**
@@ -1,7 +1,9 @@
1
1
  import { createGate, frameCap } from "../gate.js";
2
2
  import { setThreeLoader, takeRenderer } from "../scene/shared.js";
3
3
  import { TILES_BASE } from "../scene/textures.js";
4
- import { madeGround, setKeepOut, standingPlace } from "./detail.js";
4
+ import { madeGround, rocksAround, setKeepOut, standingPlace } from "./detail.js";
5
+ import { driveStep, driveView, ROVER, startDrive, toWorld } from "./drive.js";
6
+ import { DustField } from "./dust.js";
5
7
  import { drop, groundAt } from "./height.js";
6
8
  import { loadTerrain } from "./load.js";
7
9
  import { createSurfaceItem } from "./scene.js";
@@ -53,7 +55,7 @@ const num = (value, fallback) => {
53
55
  * ```
54
56
  */
55
57
  export class WakuseiSurface extends HTMLElement {
56
- static observedAttributes = ["quality", "shadows", "detail", "exposure", "site", "time", "heading", "pitch", "fov", "tiles", "lang", "body", "standby", "scale", "stick", "objects"];
58
+ static observedAttributes = ["quality", "shadows", "detail", "exposure", "site", "time", "heading", "pitch", "fov", "tiles", "lang", "body", "standby", "scale", "stick", "objects", "drive", "drive-camera"];
57
59
  #root;
58
60
  #stage;
59
61
  #noteEl;
@@ -99,6 +101,15 @@ export class WakuseiSurface extends HTMLElement {
99
101
  #objects = [];
100
102
  #labelEls = new Map();
101
103
  #chosen;
104
+ /** 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. */
105
+ #vehicle;
106
+ #driveCamera = "chase";
107
+ #camOffset = { azimuth: 0, pitch: 0 };
108
+ #driveEyeUp = 0;
109
+ #trail = [];
110
+ #dust = new DustField(900, 17);
111
+ #blockers = [];
112
+ #blockersAt;
102
113
  #stickPointer = -1;
103
114
  #pointers = new Map();
104
115
  #pinch = 0;
@@ -150,7 +161,7 @@ export class WakuseiSurface extends HTMLElement {
150
161
  /** Numbers for a test or a status line: the draws, the tiles, the renderer's own counts, the mesh, the quality of the last draw and the milliseconds of the last measured one. */
151
162
  get stats() {
152
163
  const scene = this.#view?.scene;
153
- return { state: this.#state, draws: this.#draws, tiles: this.#progress, renderer: this.#renderer?.stats, mesh: scene?.mesh, quality: this.#quality(), scale: this.#drawScale, scaled: this.#scaled, drawMs: scene?.drawMs ?? this.#drawMs, rocks: scene?.rocks ?? 0 };
164
+ return { state: this.#state, draws: this.#draws, tiles: this.#progress, renderer: this.#renderer?.stats, mesh: scene?.mesh, quality: this.#quality(), scale: this.#drawScale, scaled: this.#scaled, vehicle: this.#vehicle === undefined ? undefined : { ...this.#vehicle, spin: [...this.#vehicle.spin] }, drawMs: scene?.drawMs ?? this.#drawMs, rocks: scene?.rocks ?? 0 };
154
165
  }
155
166
  /** The quality of the next draw: the `quality` attribute, or in `auto` the quality of motion while the view moves and the machine's own quality of rest otherwise. */
156
167
  #quality() {
@@ -219,6 +230,14 @@ export class WakuseiSurface extends HTMLElement {
219
230
  attributeChangedCallback(name) {
220
231
  if (!this.isConnected)
221
232
  return;
233
+ if (name === "drive") {
234
+ this.#syncDrive();
235
+ return;
236
+ }
237
+ if (name === "drive-camera") {
238
+ this.driveCamera = this.getAttribute("drive-camera") === "seat" ? "seat" : "chase";
239
+ return;
240
+ }
222
241
  if (name === "stick") {
223
242
  this.#showStick();
224
243
  return;
@@ -305,6 +324,7 @@ export class WakuseiSurface extends HTMLElement {
305
324
  const stand = this.getAttribute("detail") === "off" ? { x: 0, y: 0 } : standingPlace(0, 0);
306
325
  this.#at = { east: stand.x, north: stand.y };
307
326
  this.#placed = true;
327
+ this.#syncDrive();
308
328
  }
309
329
  if (this.#view === undefined) {
310
330
  if (this.#renderer === undefined) {
@@ -392,6 +412,8 @@ export class WakuseiSurface extends HTMLElement {
392
412
  }
393
413
  /** The eyes' height over the site's origin: the ground under them (the made craters too: the feet follow them) and a person's height. */
394
414
  #eyeUp() {
415
+ if (this.#vehicle !== undefined)
416
+ return this.#driveEyeUp;
395
417
  return this.#groundAt(this.#at.east, this.#at.north) + EYE_HEIGHT;
396
418
  }
397
419
  /** Ask for a draw. A change of the view (`moving`, the default) is drawn at the quality of motion and followed, a moment after the last, by one at the quality of rest. */
@@ -446,11 +468,147 @@ export class WakuseiSurface extends HTMLElement {
446
468
  this.#measured += 1;
447
469
  if (this.#drawScale < 1)
448
470
  this.#scaled += 1;
449
- 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, measure: measure || this.getAttribute("measure") !== null });
471
+ 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 }), measure: measure || this.getAttribute("measure") !== null });
450
472
  this.#view.invalidate();
451
473
  this.#draws += 1;
452
474
  this.#placeLabels();
453
475
  }
476
+ // --- driving the rover (`drive="on"`) ---------------------------------------------------------------------------------------------------------------
477
+ /** Which view of the rover: `chase` (from behind and above, the default) or `seat` (the commander's). The key C turns from one to the other. */
478
+ get driveCamera() {
479
+ return this.#driveCamera;
480
+ }
481
+ set driveCamera(value) {
482
+ this.#driveCamera = value === "seat" ? "seat" : "chase";
483
+ this.#syncDriveCamera();
484
+ this.#changed();
485
+ }
486
+ /** The rover being driven, or `undefined` when it is not. */
487
+ get vehicle() {
488
+ return this.#vehicle === undefined ? undefined : { ...this.#vehicle, spin: [...this.#vehicle.spin] };
489
+ }
490
+ /** Start or stop driving as the `drive` attribute says: the rover starts at its published place (where its last traverse ends), looking along its heading from behind; stopping puts the eyes back on the ground there. */
491
+ #syncDrive() {
492
+ const on = this.getAttribute("drive") === "on" && this.#terrain !== undefined && this.#placed;
493
+ if (!on) {
494
+ if (this.#vehicle === undefined)
495
+ return;
496
+ const v = this.#vehicle;
497
+ this.#vehicle = undefined;
498
+ this.#trail = [];
499
+ this.#at = { east: v.east, north: v.north };
500
+ this.#changed();
501
+ return;
502
+ }
503
+ if (this.#vehicle !== undefined)
504
+ return;
505
+ const rover = this.#objects.find((o) => o.kind === "rover");
506
+ const [east, north, heading] = rover === undefined ? [this.#at.east, this.#at.north, this.#look.azimuth] : [rover.east, rover.north, rover.heading ?? 0];
507
+ this.#driveCamera = this.getAttribute("drive-camera") === "seat" ? "seat" : "chase";
508
+ this.#vehicle = startDrive(east, north, heading, this.#groundAt(east, north));
509
+ this.#trail = [east, north];
510
+ this.#dust = new DustField(900, 17);
511
+ this.#camOffset = { azimuth: 0, pitch: 0 };
512
+ this.#blockersAt = undefined;
513
+ for (const el of this.#labelEls.values())
514
+ el.hidden = true;
515
+ this.choose(undefined);
516
+ this.#syncDriveCamera();
517
+ this.#changed();
518
+ }
519
+ /** The eyes where the view of the rover puts them. */
520
+ #syncDriveCamera() {
521
+ const v = this.#vehicle;
522
+ if (v === undefined)
523
+ return;
524
+ const view = driveView(v, this.#driveCamera, this.#camOffset, (e, n) => this.#groundAt(e, n));
525
+ this.#at = { east: view.eye.east, north: view.eye.north };
526
+ this.#driveEyeUp = view.eye.up;
527
+ this.#look = clampLook({ azimuth: view.azimuth, pitch: view.pitch, fov: this.#look.fov });
528
+ }
529
+ /** The big rocks and the things near the rover, as circles it cannot enter (found again when it has gone 8 m from where they were found). */
530
+ #obstacles() {
531
+ const v = this.#vehicle;
532
+ if (this.#blockersAt === undefined || Math.hypot(v.east - this.#blockersAt.east, v.north - this.#blockersAt.north) > 8) {
533
+ this.#blockersAt = { east: v.east, north: v.north };
534
+ const list = [];
535
+ if (this.getAttribute("detail") !== "off")
536
+ for (const rock of rocksAround(v.east, v.north, 28, 0.0024))
537
+ if (rock.size >= 0.6)
538
+ list.push({ x: rock.x, y: rock.y, r: rock.size * 0.5 + 1.1 });
539
+ const near = { lander: 6, flag: 1.6, station: 2.8, instrument: 1.8, rover: 0 };
540
+ for (const o of this.#objects)
541
+ if (near[o.kind] > 0)
542
+ list.push({ x: o.east, y: o.north, r: near[o.kind] });
543
+ this.#blockers = list;
544
+ }
545
+ return this.#blockers;
546
+ }
547
+ /** Advance the rover by `seconds` (in steps of at most a sixtieth), throwing dust from the wheels that are down and leaving tracks. */
548
+ #advance(seconds, input) {
549
+ let v = this.#vehicle;
550
+ const ground = (e, n) => this.#groundAt(e, n);
551
+ const blockers = this.#obstacles();
552
+ const blocked = (e, n) => blockers.some((b) => (e - b.x) ** 2 + (n - b.y) ** 2 < b.r * b.r);
553
+ const steps = Math.max(1, Math.ceil(seconds * 60));
554
+ const dt = seconds / steps;
555
+ for (let i = 0; i < steps; i += 1) {
556
+ v = driveStep(v, input, dt, ground, blocked);
557
+ // each wheel on the ground throws grains up and back: the faster, the more
558
+ if (!v.airborne && Math.abs(v.speed) > 0.6) {
559
+ const h = (v.heading * Math.PI) / 180;
560
+ const [fx, fz] = [Math.sin(h), Math.cos(h)];
561
+ const grains = Math.abs(v.speed) * dt * 26;
562
+ const [rx, rz] = [Math.cos(h), -Math.sin(h)];
563
+ for (const [wx, , wz] of ROVER.wheels) {
564
+ const w = toWorld(v, [wx, 0, wz]);
565
+ for (let k = 0; k < grains + Math.random() * 0.999; k += 1) {
566
+ // thrown up and back from the tyre in a fan: the faster the rover, the wider and farther
567
+ const back = -Math.sign(v.speed) * Math.abs(v.speed) * (0.3 + 0.3 * Math.random());
568
+ const side = (Math.random() - 0.5) * 1.6 * Math.min(1, Math.abs(v.speed));
569
+ this.#dust.emit([w[0], w[1] + 0.05, w[2]], [fx * back + rx * side, 0.5 + 0.18 * Math.abs(v.speed), fz * back + rz * side], 2);
570
+ }
571
+ }
572
+ }
573
+ this.#dust.step(dt, ground);
574
+ }
575
+ this.#vehicle = v;
576
+ // the tracks: a point every 1.2 m
577
+ const last = this.#trail.length >= 2 ? [this.#trail[this.#trail.length - 2], this.#trail[this.#trail.length - 1]] : [Infinity, Infinity];
578
+ if (Math.hypot(v.east - last[0], v.north - last[1]) >= 1.2 && this.#trail.length < 12_000)
579
+ this.#trail.push(v.east, v.north);
580
+ this.#syncDriveCamera();
581
+ }
582
+ /** While a key or the stick is asked for, and while the rover is still rolling, settling on its springs or throwing dust: a step at most thirty times a second, and nothing once it is at rest. */
583
+ #driveTick() {
584
+ const k = this.#keys;
585
+ const now = performance.now();
586
+ const dt = Math.min(0.1, (now - this.#walkAt) / 1000);
587
+ this.#walkAt = now;
588
+ const throttle = Math.max(-1, Math.min(1, (k.has("w") || k.has("ArrowUp") ? 1 : 0) - (k.has("s") || k.has("ArrowDown") ? 1 : 0) + this.#push.y));
589
+ const steer = Math.max(-1, Math.min(1, (k.has("d") || k.has("ArrowRight") ? 1 : 0) - (k.has("a") || k.has("ArrowLeft") ? 1 : 0) + this.#push.x));
590
+ this.#advance(dt, { throttle, steer });
591
+ this.#changed();
592
+ const v = this.#vehicle;
593
+ const rolling = Math.abs(v.speed) > 0.01 || v.airborne || Math.abs(v.vy) > 0.02 || Math.abs(v.steer) > 0.005 || this.#dust.live > 0;
594
+ if (throttle !== 0 || steer !== 0 || rolling)
595
+ this.#walkTimer = setTimeout(this.#walkTick, 33);
596
+ }
597
+ /**
598
+ * 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
599
+ * stick do the same by the real time between frames.
600
+ *
601
+ * @param seconds - How long to drive.
602
+ * @param input - The throttle and the steering.
603
+ * @returns Whether the element is driving.
604
+ */
605
+ driveFor(seconds, input = { throttle: 0, steer: 0 }) {
606
+ if (this.#vehicle === undefined)
607
+ return false;
608
+ this.#advance(seconds, input);
609
+ this.#changed();
610
+ return true;
611
+ }
454
612
  // --- the things at the site: a small button on each, which goes to it and says what it is ----------------------------------------------------------------------------------------------------
455
613
  /** The things at the site, at their published places (none where the site has none or `objects="off"`). */
456
614
  get objects() {
@@ -489,7 +647,7 @@ export class WakuseiSurface extends HTMLElement {
489
647
  }
490
648
  /** Put each button on its thing in the picture, or hide it behind the viewer, off the picture or too far to tell. Done at each draw: nothing moves by itself. */
491
649
  #placeLabels() {
492
- if (this.#labelEls.size === 0)
650
+ if (this.#labelEls.size === 0 || this.#vehicle !== undefined)
493
651
  return;
494
652
  const box = this.getBoundingClientRect();
495
653
  const [w, h] = [box.width, box.height];
@@ -516,6 +674,8 @@ export class WakuseiSurface extends HTMLElement {
516
674
  * @returns Whether there is such a thing here.
517
675
  */
518
676
  choose(id) {
677
+ if (this.#vehicle !== undefined)
678
+ return false; // the rover is being driven: the eyes are its
519
679
  const about = this.#root.getElementById("about");
520
680
  const o = id === undefined ? undefined : this.#objects.find((x) => x.id === id);
521
681
  if (id !== undefined && o === undefined)
@@ -616,6 +776,12 @@ export class WakuseiSurface extends HTMLElement {
616
776
  }
617
777
  const box = this.getBoundingClientRect();
618
778
  const perPixel = this.#look.fov / Math.max(1, box.height);
779
+ if (this.#vehicle !== undefined) {
780
+ this.#camOffset = { azimuth: this.#camOffset.azimuth - (event.clientX - was.x) * perPixel, pitch: Math.max(-60, Math.min(60, this.#camOffset.pitch + (event.clientY - was.y) * perPixel)) };
781
+ this.#syncDriveCamera();
782
+ this.#changed();
783
+ return;
784
+ }
619
785
  this.#look = clampLook({ ...this.#look, azimuth: this.#look.azimuth - (event.clientX - was.x) * perPixel, pitch: this.#look.pitch + (event.clientY - was.y) * perPixel });
620
786
  this.#changed();
621
787
  };
@@ -641,6 +807,10 @@ export class WakuseiSurface extends HTMLElement {
641
807
  };
642
808
  #onKeyDown = (event) => {
643
809
  const key = event.key.length === 1 ? event.key.toLowerCase() : event.key;
810
+ if (key === "c" && this.#vehicle !== undefined) {
811
+ this.driveCamera = this.#driveCamera === "chase" ? "seat" : "chase";
812
+ return;
813
+ }
644
814
  if (key === "+" || key === "=")
645
815
  return this.#zoom(0.85);
646
816
  if (key === "-" || key === "_")
@@ -663,6 +833,8 @@ export class WakuseiSurface extends HTMLElement {
663
833
  /** While a key is held: a step every frame at a walking pace (and a turn at a quarter turn a second), at most thirty a second; nothing when no key is held. */
664
834
  #walkTick = () => {
665
835
  clearTimeout(this.#walkTimer);
836
+ if (this.#vehicle !== undefined)
837
+ return this.#driveTick();
666
838
  if (this.#keys.size === 0 && this.#push.x === 0 && this.#push.y === 0)
667
839
  return;
668
840
  const now = performance.now();
@@ -24,3 +24,6 @@ export declare const TRACK_FRAGMENT = "\nprecision highp float;\nvarying vec2 vU
24
24
  /** The things at a site: the rocks' light, with a flat colour for each corner (the gold of the lunar module's foil, the grey of the rover's frame). */
25
25
  export declare const OBJECT_VERTEX: string;
26
26
  export declare const OBJECT_FRAGMENT: string;
27
+ /** A grain of dust in flight: a small square that always faces the viewer, at a place in the site's plane, its size in metres. */
28
+ export declare const DUST_VERTEX = "\nprecision highp float;\n// position (declared by three.js) is the grain's place; the corner of its square is in uv, -1 to 1\nuniform mat4 uVP;\nuniform vec3 uRight;\nuniform vec3 uUp;\nuniform float uSize;\nvarying vec2 vUv;\nvoid main() {\n vUv = uv * 2.0 - 1.0;\n vec3 w = vec3(position.x, position.y, -position.z) + (uRight * vUv.x + uUp * vUv.y) * uSize;\n gl_Position = uVP * vec4(w, 1.0);\n}\n";
29
+ export declare const DUST_FRAGMENT = "\nprecision highp float;\nvarying vec2 vUv;\nvoid main() {\n float r = length(vUv);\n if (r > 1.0) discard;\n gl_FragColor = vec4(vec3(0.6), 0.55 * (1.0 - r * r));\n}\n";
@@ -454,4 +454,28 @@ void main() {
454
454
  `;
455
455
  /** The things at a site: the rocks' light, with a flat colour for each corner (the gold of the lunar module's foil, the grey of the rover's frame). */
456
456
  export const OBJECT_VERTEX = ROCK_VERTEX.replace("attribute float tone;", "attribute float tone;\nattribute vec3 tint;").replace("varying float vTone;", "varying float vTone;\nvarying vec3 vTint;").replace("vTone = tone;", "vTone = tone;\n vTint = tint;");
457
- export const OBJECT_FRAGMENT = ROCK_FRAGMENT.replace("varying float vTone;", "varying float vTone;\nvarying vec3 vTint;").replace("gl_FragColor = vec4(vec3(pow(clamp(light, 0.0, 1.0), 1.0 / 2.2)), 1.0);", "gl_FragColor = vec4(pow(clamp(vec3(light) * vTint, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0);");
457
+ export const OBJECT_FRAGMENT = ROCK_FRAGMENT.replace("varying float vTone;", "varying float vTone;\nvarying vec3 vTint;").replace("uAlbedo * 1.1 * vTone * (shine + 0.12 * (n.y * 0.5 + 0.5))", "uAlbedo * 2.4 * vTone * (shine + 0.3 * (n.y * 0.5 + 0.5))").replace("gl_FragColor = vec4(vec3(pow(clamp(light, 0.0, 1.0), 1.0 / 2.2)), 1.0);", "gl_FragColor = vec4(pow(clamp(vec3(light) * vTint, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0);");
458
+ /** A grain of dust in flight: a small square that always faces the viewer, at a place in the site's plane, its size in metres. */
459
+ export const DUST_VERTEX = /* glsl */ `
460
+ precision highp float;
461
+ // position (declared by three.js) is the grain's place; the corner of its square is in uv, -1 to 1
462
+ uniform mat4 uVP;
463
+ uniform vec3 uRight;
464
+ uniform vec3 uUp;
465
+ uniform float uSize;
466
+ varying vec2 vUv;
467
+ void main() {
468
+ vUv = uv * 2.0 - 1.0;
469
+ vec3 w = vec3(position.x, position.y, -position.z) + (uRight * vUv.x + uUp * vUv.y) * uSize;
470
+ gl_Position = uVP * vec4(w, 1.0);
471
+ }
472
+ `;
473
+ export const DUST_FRAGMENT = /* glsl */ `
474
+ precision highp float;
475
+ varying vec2 vUv;
476
+ void main() {
477
+ float r = length(vUv);
478
+ if (r > 1.0) discard;
479
+ gl_FragColor = vec4(vec3(0.6), 0.55 * (1.0 - r * r));
480
+ }
481
+ `;
@@ -5,6 +5,8 @@ export { decodeHeight, drop, emptyLevel, fillFromCoarser, groundAt, sampleLevel,
5
5
  export { loadPlan, loadTerrain, type LoadJob, type LoadOptions, type Terrain, type TerrainProgress } from "./load.ts";
6
6
  export type { SurfaceState } from "./element.ts";
7
7
  export { landerParts, roverParts } from "./shapes.ts";
8
+ export { DustField } from "./dust.ts";
9
+ export { driveParts, driveStep, driveView, startDrive, ROVER, type DriveInput, type DriveState, type DriveView } from "./drive.ts";
8
10
  export { keepAway, objectParts, objectsOf, partShadows, traverseOf, KEEP_OUT, type Part, type SiteObject } from "./objects.ts";
9
11
  export { craterIn, craterProfile, madeGround, setKeepOut, rimBoost, rocksAround, standingPlace, type Crater, type Rock } from "./detail.ts";
10
12
  export { rockMesh, type RockMesh } from "./rocks.ts";
@@ -5,6 +5,8 @@ export { EYE_HEIGHT, FOV_LIMITS, WALK_SPEED, clampLook, forward, stepOver, viewP
5
5
  export { decodeHeight, drop, emptyLevel, fillFromCoarser, groundAt, sampleLevel, tileAddress } from "./height.js";
6
6
  export { loadPlan, loadTerrain } from "./load.js";
7
7
  export { landerParts, roverParts } from "./shapes.js";
8
+ export { DustField } from "./dust.js";
9
+ export { driveParts, driveStep, driveView, startDrive, ROVER } from "./drive.js";
8
10
  export { keepAway, objectParts, objectsOf, partShadows, traverseOf, KEEP_OUT } from "./objects.js";
9
11
  export { craterIn, craterProfile, madeGround, setKeepOut, rimBoost, rocksAround, standingPlace } from "./detail.js";
10
12
  export { rockMesh } from "./rocks.js";
@@ -1,5 +1,6 @@
1
1
  import type { Item3D, Scene3D } from "@johnmorrisdotca/kazoku-ui/renderer";
2
2
  import type { ThreeParts } from "../scene/body.ts";
3
+ import { type DriveState } from "./drive.ts";
3
4
  import { type SiteObject } from "./objects.ts";
4
5
  import type { HeightLevel, TerrainManifest } from "./height.ts";
5
6
  import type { MoonSky } from "./sky.ts";
@@ -26,6 +27,12 @@ export interface SurfaceState {
26
27
  quality?: "full" | "medium" | "fast";
27
28
  /** The share of the canvas's width and height the ground is drawn at, 1 (the default) to 0.25: below 1 it is drawn to a smaller target and stretched, which is what a draw while the view moves does on a machine that is slow. It needs `WebGLRenderTarget` in the three.js module (a page's own cut-down module may not have it; the draw is then at full size). */
28
29
  scale?: number;
30
+ /** The rover being driven, as `driveStep` leaves it: drawn in place of the one standing at its published place. */
31
+ vehicle?: DriveState;
32
+ /** The path the driven rover has left, east, north, east, north, ... in metres: drawn as tracks. */
33
+ trail?: readonly number[];
34
+ /** The grains of dust in flight, east, up, north for each (`DustField.position`), drawn as small squares. */
35
+ dust?: Float32Array;
29
36
  /** Whether the things at the site (the lander, the rover, the flag, the station) and the rover's tracks are drawn (default true; the made ground keeps away from them while they are). */
30
37
  objects?: boolean;
31
38
  /** Time the next draw to the end of the graphics queue (it waits for the card, so it is for a few draws, not every one). */
@@ -1,5 +1,6 @@
1
1
  import { rocksAround } from "./detail.js";
2
- import { DISC_FRAGMENT, DISC_VERTEX, GROUND_FRAGMENT, GROUND_VERTEX, OBJECT_FRAGMENT, OBJECT_VERTEX, ROCK_FRAGMENT, ROCK_VERTEX, SHADOW_FRAGMENT, SHADOW_VERTEX, TRACK_FRAGMENT, TRACK_VERTEX } from "./glsl.js";
2
+ import { DISC_FRAGMENT, DISC_VERTEX, GROUND_FRAGMENT, GROUND_VERTEX, OBJECT_FRAGMENT, OBJECT_VERTEX, ROCK_FRAGMENT, ROCK_VERTEX, SHADOW_FRAGMENT, SHADOW_VERTEX, TRACK_FRAGMENT, TRACK_VERTEX, DUST_FRAGMENT, DUST_VERTEX } from "./glsl.js";
3
+ import { driveParts } from "./drive.js";
3
4
  import { KEEP_OUT, objectParts, partShadows } from "./objects.js";
4
5
  import { rockMesh } from "./rocks.js";
5
6
  import { cameraAxes, viewProjection } from "./view.js";
@@ -226,6 +227,7 @@ export function createSurfaceItem(options) {
226
227
  const list = options.objects ?? [];
227
228
  const ground = options.groundY;
228
229
  const on = state.objects !== false && list.length > 0 && ground !== undefined;
230
+ const driving = state.vehicle !== undefined;
229
231
  if (objectMesh !== undefined)
230
232
  objectMesh.visible = on;
231
233
  if (objectShadowMesh !== undefined)
@@ -234,7 +236,7 @@ export function createSurfaceItem(options) {
234
236
  trackMesh.visible = on;
235
237
  if (!on || ground === undefined)
236
238
  return;
237
- const key = `${state.sky.sun.azimuth.toFixed(1)}|${state.sky.sun.altitude.toFixed(1)}|${objectVersion}`;
239
+ const key = `${state.sky.sun.azimuth.toFixed(1)}|${state.sky.sun.altitude.toFixed(1)}|${objectVersion}|${driving}|${state.shadows !== false}`;
238
240
  if (key === objectKey)
239
241
  return;
240
242
  objectKey = key;
@@ -244,6 +246,8 @@ export function createSurfaceItem(options) {
244
246
  const tint = [];
245
247
  const shadow = [];
246
248
  for (const object of list) {
249
+ if (driving && object.kind === "rover")
250
+ continue;
247
251
  const base = ground(object.east, object.north);
248
252
  const parts = objectParts(object, base);
249
253
  for (const part of parts) {
@@ -254,7 +258,8 @@ export function createSurfaceItem(options) {
254
258
  tint.push(...(part.colour ?? [1, 1, 1]));
255
259
  }
256
260
  }
257
- shadow.push(...partShadows(parts, base, state.sky.sun.azimuth, state.sky.sun.altitude));
261
+ if (state.shadows !== false)
262
+ shadow.push(...partShadows(parts, base, state.sky.sun.azimuth, state.sky.sun.altitude));
258
263
  }
259
264
  const geometry = new T.BufferGeometry();
260
265
  geometry.setAttribute("position", new T.BufferAttribute(new Float32Array(position), 3));
@@ -333,6 +338,176 @@ export function createSurfaceItem(options) {
333
338
  trackMesh.renderOrder = 0.5;
334
339
  scene.add(trackMesh);
335
340
  }
341
+ // the rover being driven: its parts as one mesh turned and placed at each draw (a few thousand corners: cheap), its shadow, the path it has left as tracks and the grains it throws as small squares
342
+ let vehicleMesh;
343
+ let vehicleShadow;
344
+ let vehicleCount = 0;
345
+ const makeVehicle = (state) => {
346
+ const v = state.vehicle;
347
+ if (v === undefined || state.objects === false) {
348
+ if (vehicleMesh !== undefined)
349
+ vehicleMesh.visible = false;
350
+ if (vehicleShadow !== undefined)
351
+ vehicleShadow.visible = false;
352
+ return;
353
+ }
354
+ const parts = driveParts(v);
355
+ const count = parts.reduce((n, part) => n + part.position.length / 3, 0);
356
+ if (vehicleMesh === undefined || count !== vehicleCount) {
357
+ vehicleMesh?.geometry.dispose();
358
+ const geometry = new T.BufferGeometry();
359
+ geometry.setAttribute("position", new T.BufferAttribute(new Float32Array(count * 3), 3));
360
+ geometry.setAttribute("normal", new T.BufferAttribute(new Float32Array(count * 3), 3));
361
+ const tone = new Float32Array(count);
362
+ const tint = new Float32Array(count * 3);
363
+ let at = 0;
364
+ for (const part of parts) {
365
+ for (let i = 0; i < part.position.length / 3; i += 1) {
366
+ tone[at] = part.tone;
367
+ tint.set(part.colour ?? [1, 1, 1], at * 3);
368
+ at += 1;
369
+ }
370
+ }
371
+ geometry.setAttribute("tone", new T.BufferAttribute(tone, 1));
372
+ geometry.setAttribute("tint", new T.BufferAttribute(tint, 3));
373
+ vehicleCount = count;
374
+ if (vehicleMesh === undefined) {
375
+ vehicleMesh = new T.Mesh(geometry, objectMaterial);
376
+ vehicleMesh.frustumCulled = false;
377
+ vehicleMesh.renderOrder = 1;
378
+ scene.add(vehicleMesh);
379
+ }
380
+ else
381
+ vehicleMesh.geometry = geometry;
382
+ }
383
+ const position = vehicleMesh.geometry.getAttribute("position");
384
+ const normal = vehicleMesh.geometry.getAttribute("normal");
385
+ let at = 0;
386
+ for (const part of parts) {
387
+ position.array.set(part.position, at * 3);
388
+ normal.array.set(part.normal, at * 3);
389
+ at += part.position.length / 3;
390
+ }
391
+ position.needsUpdate = true;
392
+ normal.needsUpdate = true;
393
+ vehicleMesh.visible = true;
394
+ const shadow = state.shadows === false ? [] : partShadows(parts, v.y, state.sky.sun.azimuth, state.sky.sun.altitude);
395
+ const geometry = new T.BufferGeometry();
396
+ geometry.setAttribute("position", new T.BufferAttribute(new Float32Array(shadow), 3));
397
+ geometry.setAttribute("uv", new T.BufferAttribute(new Float32Array((shadow.length / 3) * 2).map((_, i) => (i % 2 === 1 ? 0 : 0.5)), 2));
398
+ if (vehicleShadow === undefined) {
399
+ vehicleShadow = new T.Mesh(geometry, shadowMaterial);
400
+ vehicleShadow.frustumCulled = false;
401
+ vehicleShadow.renderOrder = 2;
402
+ scene.add(vehicleShadow);
403
+ }
404
+ else {
405
+ vehicleShadow.geometry.dispose();
406
+ vehicleShadow.geometry = geometry;
407
+ }
408
+ vehicleShadow.visible = true;
409
+ };
410
+ // the driven path: a strip like the published traverse's, grown as the rover goes (room for 6,000 points)
411
+ const TRAIL_MAX = 6000;
412
+ let trailMesh;
413
+ let trailMaterialDriven;
414
+ let trailBuilt = 0;
415
+ const makeTrail = (state) => {
416
+ const points = state.trail;
417
+ if (points === undefined || points.length < 4) {
418
+ if (trailMesh !== undefined)
419
+ trailMesh.visible = false;
420
+ trailBuilt = 0;
421
+ return;
422
+ }
423
+ if (trailMesh === undefined) {
424
+ const geometry = new T.BufferGeometry();
425
+ geometry.setAttribute("position", new T.BufferAttribute(new Float32Array(TRAIL_MAX * 2 * 3), 3));
426
+ geometry.setAttribute("uv", new T.BufferAttribute(new Float32Array(TRAIL_MAX * 2 * 2), 2));
427
+ const indices = new Uint32Array((TRAIL_MAX - 1) * 6);
428
+ for (let i = 1; i < TRAIL_MAX; i += 1)
429
+ indices.set([2 * i - 2, 2 * i - 1, 2 * i, 2 * i - 1, 2 * i + 1, 2 * i], (i - 1) * 6);
430
+ geometry.setIndex(new T.BufferAttribute(indices, 1));
431
+ const material = new T.ShaderMaterial({ vertexShader: TRACK_VERTEX, fragmentShader: TRACK_FRAGMENT, uniforms, transparent: true, depthWrite: false, side: 2 });
432
+ material.polygonOffset = true;
433
+ material.polygonOffsetFactor = -3;
434
+ material.polygonOffsetUnits = -3;
435
+ trailMaterialDriven = material;
436
+ trailMesh = new T.Mesh(geometry, material);
437
+ trailMesh.frustumCulled = false;
438
+ trailMesh.renderOrder = 0.6;
439
+ scene.add(trailMesh);
440
+ }
441
+ const count = Math.min(TRAIL_MAX, points.length / 2);
442
+ if (count < trailBuilt)
443
+ trailBuilt = 0;
444
+ const position = trailMesh.geometry.getAttribute("position").array;
445
+ const uv = trailMesh.geometry.getAttribute("uv").array;
446
+ let along = trailBuilt > 0 ? uv[(trailBuilt - 1) * 4] : 0;
447
+ for (let i = Math.max(0, trailBuilt - 1); i < count; i += 1) {
448
+ const a = Math.max(0, i - 1);
449
+ const b = Math.min(count - 1, i + 1);
450
+ const [dx, dy] = [points[2 * b] - points[2 * a], points[2 * b + 1] - points[2 * a + 1]];
451
+ const len = Math.hypot(dx, dy) || 1;
452
+ const [nx, ny] = [-dy / len, dx / len];
453
+ if (i > 0)
454
+ along += Math.hypot(points[2 * i] - points[2 * i - 2], points[2 * i + 1] - points[2 * i - 1]);
455
+ for (const side of [-1, 1]) {
456
+ const k = i * 2 + (side === 1 ? 1 : 0);
457
+ position[k * 3] = points[2 * i] + nx * 1.4 * side;
458
+ position[k * 3 + 1] = points[2 * i + 1] + ny * 1.4 * side;
459
+ position[k * 3 + 2] = 0;
460
+ uv[k * 2] = along;
461
+ uv[k * 2 + 1] = side;
462
+ }
463
+ }
464
+ trailBuilt = count;
465
+ trailMesh.geometry.getAttribute("position").needsUpdate = true;
466
+ trailMesh.geometry.getAttribute("uv").needsUpdate = true;
467
+ trailMesh.geometry.setDrawRange(0, Math.max(0, (count - 1) * 6));
468
+ trailMesh.visible = true;
469
+ };
470
+ // the dust: one small square for each grain in the pool, in the corners of a fixed set of triangles
471
+ let dustMesh;
472
+ let dustMaterial;
473
+ const dustUniforms = { uVP: uniforms.uVP, uRight: { value: new T.Vector3(1, 0, 0) }, uUp: { value: new T.Vector3(0, 1, 0) }, uSize: { value: 0.022 } };
474
+ const makeDust = (state) => {
475
+ const grains = state.dust;
476
+ if (grains === undefined) {
477
+ if (dustMesh !== undefined)
478
+ dustMesh.visible = false;
479
+ return;
480
+ }
481
+ const n = grains.length / 3;
482
+ if (dustMesh === undefined) {
483
+ const geometry = new T.BufferGeometry();
484
+ geometry.setAttribute("position", new T.BufferAttribute(new Float32Array(n * 4 * 3), 3));
485
+ const uv = new Float32Array(n * 4 * 2);
486
+ const index = new Uint32Array(n * 6);
487
+ for (let i = 0; i < n; i += 1) {
488
+ uv.set([0, 0, 1, 0, 1, 1, 0, 1], i * 8);
489
+ index.set([i * 4, i * 4 + 1, i * 4 + 2, i * 4, i * 4 + 2, i * 4 + 3], i * 6);
490
+ }
491
+ geometry.setAttribute("uv", new T.BufferAttribute(uv, 2));
492
+ geometry.setIndex(new T.BufferAttribute(index, 1));
493
+ const material = new T.ShaderMaterial({ vertexShader: DUST_VERTEX, fragmentShader: DUST_FRAGMENT, uniforms: dustUniforms, transparent: true, depthWrite: false });
494
+ dustMaterial = material;
495
+ dustMesh = new T.Mesh(geometry, material);
496
+ dustMesh.frustumCulled = false;
497
+ dustMesh.renderOrder = 3;
498
+ scene.add(dustMesh);
499
+ }
500
+ const position = dustMesh.geometry.getAttribute("position");
501
+ const array = position.array;
502
+ for (let i = 0; i < n; i += 1)
503
+ for (let c = 0; c < 4; c += 1)
504
+ array.set([grains[i * 3], grains[i * 3 + 1], grains[i * 3 + 2]], (i * 4 + c) * 3);
505
+ position.needsUpdate = true;
506
+ const axes = cameraAxes(state.look);
507
+ dustUniforms.uRight.value.set(axes.right[0], axes.right[1], axes.right[2]);
508
+ dustUniforms.uUp.value.set(axes.up[0], axes.up[1], axes.up[2]);
509
+ dustMesh.visible = true;
510
+ };
336
511
  let measuring = false;
337
512
  let drawMs;
338
513
  let aspect = context.width / Math.max(1, context.height);
@@ -346,6 +521,9 @@ export function createSurfaceItem(options) {
346
521
  fullPixel = (2 * Math.tan((look.fov * Math.PI) / 360)) / pixelHeight;
347
522
  makeRocks(state);
348
523
  makeObjects(state);
524
+ makeVehicle(state);
525
+ makeTrail(state);
526
+ makeDust(state);
349
527
  measuring = state.measure === true;
350
528
  const world = new T.Vector3(eye.east, eye.up, -eye.north);
351
529
  const vp = viewProjection([world.x, world.y, world.z], look, aspect);
@@ -479,6 +657,12 @@ export function createSurfaceItem(options) {
479
657
  objectShadowMesh?.geometry.dispose();
480
658
  trackGeometry?.dispose();
481
659
  trackMaterial?.dispose();
660
+ vehicleMesh?.geometry.dispose();
661
+ vehicleShadow?.geometry.dispose();
662
+ trailMesh?.geometry.dispose();
663
+ dustMesh?.geometry.dispose();
664
+ trailMaterialDriven?.dispose();
665
+ dustMaterial?.dispose();
482
666
  objectMaterial.dispose();
483
667
  blitMaterial.dispose();
484
668
  },
@@ -47,8 +47,8 @@ export declare function placePart(part: Part, east: number, base: number, north:
47
47
  export declare function landerParts(): Part[];
48
48
  /**
49
49
  * The lunar rover in its own frame (x right, z forward, the middle of its wheelbase on the ground at the origin): a frame and floor, four wheels (parts 0 to 3: front left, front right, rear left, rear right) with a
50
- * fender over each, two seats, the console with its handle, the dish on its mast, the television camera on its own mast, a whip antenna and the boxes at both ends. Sizes from the published ones (3.1 m long, 2.3 m
51
- * wide, wheels 0.82 m across, the wheelbase 2.3 m).
50
+ * fender over each, two seats, the console with its handle, the dish on its mast, the television camera on its own mast, a whip antenna and the boxes at both ends. Sizes from the published ones (about 3.05 m long, 2.13 m
51
+ * wide, wheels 0.81 m across, the wheelbase 2.29 m).
52
52
  *
53
53
  * @returns The parts.
54
54
  *