@johnmorrisdotca/chikyu-earth 0.24.0 → 0.26.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.
@@ -7,8 +7,8 @@ import { type PlanetName } from "./ephemeris.ts";
7
7
  import { type SatelliteStyle } from "./satellite-layer.ts";
8
8
  import type { RideLook } from "./ride.ts";
9
9
  import { type ScaleMode } from "./scale.ts";
10
- import { BODY_NAMES, type BodyName, type BodyPainter, type RideTarget } from "./scene.ts";
11
- export { BODY_NAMES, type BodyName, type RideTarget };
10
+ import { BODY_NAMES, type CameraMode, type BodyName, type BodyPainter, type RideTarget } from "./scene.ts";
11
+ export { BODY_NAMES, type BodyName, type CameraMode, type RideTarget };
12
12
  /**
13
13
  * Change how the Sun and the planets are drawn (before the first element connects): the space view keeps their places, sizes, light, names and orbits and asks
14
14
  * the painter only for what to draw at each place (see `BodyPainter`). Left alone, they are plain spheres in the right colours.
@@ -147,8 +147,32 @@ export declare class ChikyuSpace extends HTMLElement {
147
147
  connectedCallback(): void;
148
148
  disconnectedCallback(): void;
149
149
  attributeChangedCallback(name: string, _old: string | null, value: string | null): void;
150
+ /**
151
+ * Meteors seen from space, on or off (the attribute `meteors`): short streaks where meteors burn, on the dark side of the Earth and in its twilight, more of them under an active shower, only while the
152
+ * clock runs, and for a reader who prefers reduced motion only once the page has set a `speed` (a Play). Each streak's place and moment are drawn at random, and a line under the picture says so
153
+ * (`meteors-label="off"` takes it away); how often they appear, where, how high and when follow real data (`@johnmorrisdotca/chikyu-earth/meteors`). None are drawn while the Earth is under 40 pixels in radius.
154
+ * `chikyu-meteors` is sent when the strongest active shower changes, with `detail: { shower, zhr }`. Off by default, and nothing of theirs is made until they are first switched on.
155
+ */
156
+ get meteors(): boolean;
157
+ set meteors(value: boolean);
150
158
  get centre(): GeoPoint;
151
159
  set centre(value: GeoPoint);
160
+ /**
161
+ * How the camera is held (the `camera` attribute). `space` (the default): held in the stars, looking at the place `center` names as it is at the moment the camera is set (when the element opens, and again when `time` or `center` is set), so the Earth
162
+ * turns beneath it as the clock runs, with the day and night line where the Sun really is. `ground`: held over `center` on the ground, so the Earth keeps still and the clock moves the light across it. `sun`: held on the Sun's side, `center` being the
163
+ * longitude and latitude from the sub-solar point (`0,0` looks straight at the noon place), so the day and night line keeps its place on the screen while the Earth turns beneath.
164
+ */
165
+ get camera(): CameraMode;
166
+ set camera(value: CameraMode);
167
+ /** The share of the view's shorter side the Earth's disc fills at zoom 1 (the `earth-size` attribute): 0.9 by default, so the atmosphere's glow is never cut at any shape of box. Above 1 the Earth is larger than the view. */
168
+ get earthSize(): number;
169
+ set earthSize(value: number);
170
+ /** Where the Earth's centre is across the view (the `earth-x` attribute): 0 at the left edge, 0.5 in the middle (the default), 1 at the right edge. */
171
+ get earthX(): number;
172
+ set earthX(value: number);
173
+ /** Where the Earth's centre is down the view (the `earth-y` attribute): 0 at the top, 0.5 in the middle (the default), 1 at the bottom. */
174
+ get earthY(): number;
175
+ set earthY(value: number);
152
176
  /** The moment shown: milliseconds since the epoch, or "now" to follow the clock. Setting it points the camera at the same place on the ground again. */
153
177
  get time(): number;
154
178
  set time(value: number | Date | "now");
@@ -268,6 +292,15 @@ export declare class ChikyuSpace extends HTMLElement {
268
292
  painted: number;
269
293
  moons: number;
270
294
  };
295
+ /** The meteors: whether they are on, the streaks alive now and started so far, the streaks a second being drawn, and the strongest active shower's code and rate. */
296
+ meteors: {
297
+ on: boolean;
298
+ alive: number;
299
+ spawned: number;
300
+ perSecond: number;
301
+ shower: string | null;
302
+ zhr: number;
303
+ };
271
304
  };
272
305
  }
273
306
  declare global {
@@ -2,12 +2,13 @@ import { carryControls } from "@johnmorrisdotca/kazoku-ui/view-controls";
2
2
  import { adoptStyles } from "../adopt.js";
3
3
  import { createGate, frameCap } from "../realistic/gate.js";
4
4
  import { setThreeLoader, takeRenderer } from "../realistic/shared.js";
5
+ import { METEOR_NOTE_STYLE, prefersLessMotion, setMeteorNote } from "../meteors/note.js";
5
6
  import { MAX_TEXTURE } from "../realistic/tiers.js";
6
7
  import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
7
8
  import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt } from "./ephemeris.js";
8
9
  import { MAX_ORBIT_GROUP } from "./satellite-layer.js";
9
10
  import { placeAround, placeMoon, placeSun, RADIUS } from "./scale.js";
10
- import { BODY_NAMES, createSpaceItem, FIT_DISTANCE, newSpaceModel } from "./scene.js";
11
+ import { BODY_NAMES, createSpaceItem, DEFAULT_EARTH_SIZE, newSpaceModel } from "./scene.js";
11
12
  export { BODY_NAMES };
12
13
  let painter;
13
14
  /**
@@ -33,6 +34,15 @@ export { setThreeLoader };
33
34
  /** A `light` attribute: `lit` or `boost`, else the true sun. */
34
35
  const readLight = (value) => (value === "lit" || value === "boost" ? value : "sun");
35
36
  const RAD = Math.PI / 180;
37
+ /** A `camera` attribute: `ground` or `sun`, else the camera held in the stars (the default: the Earth turns beneath it). */
38
+ const readCamera = (value) => (value === "ground" || value === "sun" ? value : "space");
39
+ /** A number attribute within a range, or the fallback. */
40
+ const readNumber = (value, fallback, min, max) => {
41
+ if (value === null || value.trim() === "")
42
+ return fallback;
43
+ const n = Number(value);
44
+ return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback;
45
+ };
36
46
  /** The Earth's own turn, degrees a second. */
37
47
  const EARTH_RATE = 360 / 86_164.0905;
38
48
  /** The quickest a satellite goes round, degrees a second (a low orbit: 88 minutes). */
@@ -61,7 +71,7 @@ const readTime = (value) => {
61
71
  const ms = Date.parse(value);
62
72
  return Number.isFinite(ms) ? ms : "now";
63
73
  };
64
- const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#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-sat{position:absolute;left:0;top:0;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-sat[hidden]{display:none}`;
74
+ const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#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-sat{position:absolute;left:0;top:0;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-sat[hidden]{display:none}${METEOR_NOTE_STYLE}`;
65
75
  /**
66
76
  * The `<chikyu-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`, `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`), `labels` and `orbits` (`off` hides them); positions are computed in the browser by astronomy-engine, an optional peer dependency. It draws only when something changes, and nothing while it is out of sight.
67
77
  *
@@ -87,11 +97,14 @@ const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:h
87
97
  * ```
88
98
  */
89
99
  export class ChikyuSpace extends HTMLElement {
90
- static observedAttributes = ["center", "time", "speed", "scale", "labels", "orbits", "bodies", "light"];
100
+ static observedAttributes = ["cloud-drift", "camera", "earth-size", "earth-x", "earth-y", "center", "time", "speed", "scale", "labels", "orbits", "bodies", "light", "meteors", "meteors-label", "lang"];
91
101
  #model = newSpaceModel();
92
102
  #mode = "now";
93
103
  #speed = 1;
94
104
  #view;
105
+ /** The page has set a `speed` since the element came into the page: for a reader who prefers reduced motion, that is the Play that lets meteors start. */
106
+ #played = false;
107
+ #note;
95
108
  #gate;
96
109
  #taken;
97
110
  #stage;
@@ -124,6 +137,9 @@ export class ChikyuSpace extends HTMLElement {
124
137
  this.#model.orbits = this.getAttribute("orbits") !== "off";
125
138
  this.#model.bodies = this.getAttribute("bodies") ?? "";
126
139
  this.#model.light = readLight(this.getAttribute("light"));
140
+ this.#model.camera = readCamera(this.getAttribute("camera"));
141
+ this.#model.cloudDrift = Number.isFinite(Number(this.getAttribute("cloud-drift") ?? "0")) ? Number(this.getAttribute("cloud-drift") ?? "0") : 0;
142
+ this.#model.earth = { size: readNumber(this.getAttribute("earth-size"), DEFAULT_EARTH_SIZE, 0.02, 50), x: readNumber(this.getAttribute("earth-x"), 0.5, -2, 3), y: readNumber(this.getAttribute("earth-y"), 0.5, -2, 3) };
127
143
  this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
128
144
  this.#model.speed = this.#speed;
129
145
  if (!this.hasAttribute("role"))
@@ -131,10 +147,16 @@ export class ChikyuSpace extends HTMLElement {
131
147
  if (!this.hasAttribute("aria-label"))
132
148
  this.setAttribute("aria-label", "The Earth, the Moon, the Sun and the planets in their places for the date shown");
133
149
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
134
- root.innerHTML = `<div id="stage"></div><div id="labels" aria-hidden="true"></div>`;
150
+ root.innerHTML = `<div id="stage"></div><div id="labels" aria-hidden="true"></div><p id="meteor-note" hidden></p>`;
135
151
  adoptStyles(root, STYLE, this.nonce);
136
152
  this.#stage = root.getElementById("stage");
137
153
  this.#labelBox = root.getElementById("labels");
154
+ this.#note = root.getElementById("meteor-note");
155
+ this.#played = false;
156
+ this.#model.meteors.on = this.#meteorsAsked();
157
+ this.#model.meteors.running = () => this.#speed !== 0 && document.visibilityState !== "hidden" && (this.#played || !prefersLessMotion());
158
+ this.#model.meteors.onShower = (shower, zhr) => this.dispatchEvent(new CustomEvent("chikyu-meteors", { detail: { shower, zhr } }));
159
+ setMeteorNote(this.#note, this, this.#model.meteors.on);
138
160
  this.#pool.clear();
139
161
  const nav = navigator;
140
162
  this.#gate = createGate(1000 / frameCap(30, { deviceMemory: nav.deviceMemory, hardwareConcurrency: nav.hardwareConcurrency }), () => this.#view?.invalidate());
@@ -210,12 +232,90 @@ export class ChikyuSpace extends HTMLElement {
210
232
  this.bodies = value ?? "";
211
233
  else if (name === "light")
212
234
  this.light = readLight(value);
235
+ else if (name === "camera")
236
+ this.camera = readCamera(value);
237
+ else if (name === "cloud-drift") {
238
+ this.#model.cloudDrift = Number.isFinite(Number(value ?? "0")) ? Number(value ?? "0") : 0;
239
+ this.#gate?.request();
240
+ }
241
+ else if (name === "earth-size")
242
+ this.earthSize = readNumber(value, DEFAULT_EARTH_SIZE, 0.02, 50);
243
+ else if (name === "earth-x")
244
+ this.earthX = readNumber(value, 0.5, -2, 3);
245
+ else if (name === "earth-y")
246
+ this.earthY = readNumber(value, 0.5, -2, 3);
247
+ else if (name === "meteors")
248
+ this.meteors = this.#meteorsAsked();
249
+ else if (name === "meteors-label" || name === "lang")
250
+ setMeteorNote(this.#note, this, this.#model.meteors.on);
251
+ }
252
+ #meteorsAsked() {
253
+ return this.hasAttribute("meteors") && this.getAttribute("meteors") !== "off";
254
+ }
255
+ /**
256
+ * Meteors seen from space, on or off (the attribute `meteors`): short streaks where meteors burn, on the dark side of the Earth and in its twilight, more of them under an active shower, only while the
257
+ * clock runs, and for a reader who prefers reduced motion only once the page has set a `speed` (a Play). Each streak's place and moment are drawn at random, and a line under the picture says so
258
+ * (`meteors-label="off"` takes it away); how often they appear, where, how high and when follow real data (`@johnmorrisdotca/chikyu-earth/meteors`). None are drawn while the Earth is under 40 pixels in radius.
259
+ * `chikyu-meteors` is sent when the strongest active shower changes, with `detail: { shower, zhr }`. Off by default, and nothing of theirs is made until they are first switched on.
260
+ */
261
+ get meteors() {
262
+ return this.#model.meteors.on;
263
+ }
264
+ set meteors(value) {
265
+ if (value !== this.#meteorsAsked()) {
266
+ if (value)
267
+ this.setAttribute("meteors", "");
268
+ else
269
+ this.removeAttribute("meteors");
270
+ return;
271
+ }
272
+ this.#model.meteors.on = value;
273
+ setMeteorNote(this.#note, this, value);
274
+ this.#gate?.request();
213
275
  }
214
276
  get centre() {
215
277
  return { ...this.#model.centre };
216
278
  }
217
279
  set centre(value) {
218
280
  this.#model.centre = { ...value };
281
+ this.#model.cameraSpin = null;
282
+ this.#gate?.request();
283
+ }
284
+ /**
285
+ * How the camera is held (the `camera` attribute). `space` (the default): held in the stars, looking at the place `center` names as it is at the moment the camera is set (when the element opens, and again when `time` or `center` is set), so the Earth
286
+ * turns beneath it as the clock runs, with the day and night line where the Sun really is. `ground`: held over `center` on the ground, so the Earth keeps still and the clock moves the light across it. `sun`: held on the Sun's side, `center` being the
287
+ * longitude and latitude from the sub-solar point (`0,0` looks straight at the noon place), so the day and night line keeps its place on the screen while the Earth turns beneath.
288
+ */
289
+ get camera() {
290
+ return this.#model.camera;
291
+ }
292
+ set camera(value) {
293
+ this.#model.camera = value;
294
+ this.#model.cameraSpin = null;
295
+ this.#gate?.request();
296
+ }
297
+ /** The share of the view's shorter side the Earth's disc fills at zoom 1 (the `earth-size` attribute): 0.9 by default, so the atmosphere's glow is never cut at any shape of box. Above 1 the Earth is larger than the view. */
298
+ get earthSize() {
299
+ return this.#model.earth.size;
300
+ }
301
+ set earthSize(value) {
302
+ this.#model.earth.size = Number.isFinite(value) ? Math.min(50, Math.max(0.02, value)) : DEFAULT_EARTH_SIZE;
303
+ this.#gate?.request();
304
+ }
305
+ /** Where the Earth's centre is across the view (the `earth-x` attribute): 0 at the left edge, 0.5 in the middle (the default), 1 at the right edge. */
306
+ get earthX() {
307
+ return this.#model.earth.x;
308
+ }
309
+ set earthX(value) {
310
+ this.#model.earth.x = Number.isFinite(value) ? value : 0.5;
311
+ this.#gate?.request();
312
+ }
313
+ /** Where the Earth's centre is down the view (the `earth-y` attribute): 0 at the top, 0.5 in the middle (the default), 1 at the bottom. */
314
+ get earthY() {
315
+ return this.#model.earth.y;
316
+ }
317
+ set earthY(value) {
318
+ this.#model.earth.y = Number.isFinite(value) ? value : 0.5;
219
319
  this.#gate?.request();
220
320
  }
221
321
  /** The moment shown: milliseconds since the epoch, or "now" to follow the clock. Setting it points the camera at the same place on the ground again. */
@@ -239,6 +339,8 @@ export class ChikyuSpace extends HTMLElement {
239
339
  if (this.#speed !== 0 && this.isConnected)
240
340
  this.#advance(performance.now());
241
341
  const was = this.#speed;
342
+ if (this.isConnected && this.#view)
343
+ this.#played = true;
242
344
  this.#speed = Number.isFinite(value) ? value : 1;
243
345
  this.#model.speed = this.#speed;
244
346
  this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
@@ -486,7 +588,7 @@ export class ChikyuSpace extends HTMLElement {
486
588
  const sites = painter?.moons?.(name, this.#model.time) ?? [];
487
589
  const reach = Math.max(1, ...sites.map((site) => Math.hypot(...site.offset)).filter((r) => r <= 22));
488
590
  const radius = RADIUS[name][this.#model.mode];
489
- return Math.min(1, (FIT_DISTANCE * radius) / ((reach * radius * 1.15) / Math.tan(17.5 * RAD)));
591
+ return Math.min(1, (this.#model.fit * radius) / ((reach * radius * 1.15) / Math.tan(17.5 * RAD)));
490
592
  }
491
593
  const frame = this.#model.drawn?.frame ?? frameAt(this.#model.time);
492
594
  const mode = this.#model.mode;
@@ -499,7 +601,7 @@ export class ChikyuSpace extends HTMLElement {
499
601
  inner: Math.max(around("Mercury"), around("Venus"), around("Mars"), Math.hypot(...sun)),
500
602
  "solar-system": Math.max(...Object.keys(frame.planets).map(around), Math.hypot(...sun)),
501
603
  }[preset];
502
- return preset === "earth" ? 1 : FIT_DISTANCE / Math.max(FIT_DISTANCE, reach * 3.4);
604
+ return preset === "earth" ? 1 : this.#model.fit / Math.max(this.#model.fit, reach * 3.4);
503
605
  }
504
606
  /** What the element is doing, for a page or a test. */
505
607
  get stats() {
@@ -518,6 +620,7 @@ export class ChikyuSpace extends HTMLElement {
518
620
  ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null },
519
621
  camera: { position: [this.#model.pose.p[0], this.#model.pose.p[1], this.#model.pose.p[2]], fov: this.#model.pose.fov },
520
622
  bodies: { look: this.#model.bodies || painter?.looks?.[0] || "plain", painted: this.#model.painted.bodies, moons: this.#model.painted.moons },
623
+ meteors: { on: this.#model.meteors.on, ...this.#model.meteors.drawn },
521
624
  };
522
625
  }
523
626
  #satelliteStats() {
@@ -1,4 +1,4 @@
1
1
  export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, orbitPath, PLANETS, type Frame, type PlanetName, type Vec3 } from "./ephemeris.ts";
2
2
  export { compress, MOON_COMPRESSED, placeAround, placeMoon, placeSun, RADIUS, SUN_COMPRESSED, truePosition, type ScaleMode } from "./scale.ts";
3
- export { plainPainter, type BodyDrawing, type BodyMoon, type BodyPainter, type PaintContext } from "./scene.ts";
3
+ export { fitDistance, plainPainter, type BodyDrawing, type BodyMoon, type BodyPainter, type PaintContext } from "./scene.ts";
4
4
  export { RIDE_FOV, ridePose, type RideInput, type RideLook, type RidePose } from "./ride.ts";
@@ -2,5 +2,5 @@
2
2
  // `@johnmorrisdotca/chikyu-earth/space/element`.
3
3
  export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, orbitPath, PLANETS } from "./ephemeris.js";
4
4
  export { compress, MOON_COMPRESSED, placeAround, placeMoon, placeSun, RADIUS, SUN_COMPRESSED, truePosition } from "./scale.js";
5
- export { plainPainter } from "./scene.js";
5
+ export { fitDistance, plainPainter } from "./scene.js";
6
6
  export { RIDE_FOV, ridePose } from "./ride.js";
@@ -33,12 +33,12 @@ export interface SatelliteLayer {
33
33
  /** Place every shown group for `model.time` and the chosen satellite exactly. */
34
34
  update(time: number, speed: number): void;
35
35
  /** The satellite nearest to a point of the view (CSS pixels) within `radius`, if one is in front of the Earth. */
36
- pick(x: number, y: number, camera: THREE.PerspectiveCamera, size: {
36
+ pick(x: number, y: number, camera: THREE.Camera, size: {
37
37
  width: number;
38
38
  height: number;
39
39
  }, radius: number): SatelliteRef | null;
40
40
  /** Where the chosen satellite is in the view, if it is. */
41
- place(camera: THREE.PerspectiveCamera, size: {
41
+ place(camera: THREE.Camera, size: {
42
42
  width: number;
43
43
  height: number;
44
44
  }): {
@@ -49,5 +49,5 @@ export interface SatelliteLayer {
49
49
  exact(ref: SatelliteRef, time: number, out: Float64Array): boolean;
50
50
  dispose(): void;
51
51
  }
52
- export declare function createSatelliteLayer(three: Three, scene: THREE.Scene, state: SatelliteState, ratio: () => number): SatelliteLayer;
52
+ export declare function createSatelliteLayer(three: Three, scene: THREE.Object3D, state: SatelliteState, ratio: () => number): SatelliteLayer;
53
53
  export {};
@@ -31,6 +31,8 @@ export function createSatelliteLayer(three, scene, state, ratio) {
31
31
  const drawn = new Map();
32
32
  const tmp = new Float64Array(6);
33
33
  const projected = new three.Vector3();
34
+ const world = new three.Vector3();
35
+ const view = new three.Vector3();
34
36
  const selectedMaterial = new three.ShaderMaterial({ vertexShader: POINT_VERT, fragmentShader: POINT_FRAG, uniforms: { size: { value: 14 }, tint: { value: new three.Color("#ffffff") }, ring: { value: 1 } }, transparent: true, depthWrite: false });
35
37
  const selectedPosition = new Float32Array(3);
36
38
  const selectedGeometry = new three.BufferGeometry();
@@ -183,6 +185,9 @@ export function createSatelliteLayer(three, scene, state, ratio) {
183
185
  let best = null;
184
186
  let bestD = radius * radius;
185
187
  const c = camera.position;
188
+ const ortho = camera.isOrthographicCamera === true;
189
+ // an orthographic view looks along one direction: what is behind the Earth is further than its centre and inside its disc
190
+ const centreDepth = ortho ? view.set(0, 0, 0).applyMatrix4(camera.matrixWorldInverse).z : 0;
186
191
  for (const [name, entry] of drawn) {
187
192
  const group = state.groups.get(name);
188
193
  if (!group || !entry.points.visible)
@@ -191,7 +196,8 @@ export function createSatelliteLayer(three, scene, state, ratio) {
191
196
  for (let i = 0; i < group.satellites.count; i += 1) {
192
197
  if (!group.satellites.visible(i))
193
198
  continue;
194
- projected.set(p[i * 3], p[i * 3 + 1], p[i * 3 + 2]).project(camera);
199
+ world.set(p[i * 3], p[i * 3 + 1], p[i * 3 + 2]).applyMatrix4(scene.matrixWorld);
200
+ projected.copy(world).project(camera);
195
201
  if (projected.z > 1 || projected.z < -1)
196
202
  continue;
197
203
  const dx = ((projected.x + 1) / 2) * size.width - x;
@@ -199,17 +205,24 @@ export function createSatelliteLayer(three, scene, state, ratio) {
199
205
  const d = dx * dx + dy * dy;
200
206
  if (d > bestD)
201
207
  continue;
202
- // behind the Earth: the line from the camera to the satellite passes through the unit sphere before it gets there
203
- const px = p[i * 3] - c.x;
204
- const py = p[i * 3 + 1] - c.y;
205
- const pz = p[i * 3 + 2] - c.z;
206
- const len2 = px * px + py * py + pz * pz;
207
- const t = Math.max(0, Math.min(1, -(c.x * px + c.y * py + c.z * pz) / len2));
208
- const nx = c.x + px * t;
209
- const ny = c.y + py * t;
210
- const nz = c.z + pz * t;
211
- if (nx * nx + ny * ny + nz * nz < 0.998)
212
- continue;
208
+ if (ortho) {
209
+ view.copy(world).applyMatrix4(camera.matrixWorldInverse);
210
+ if (view.z < centreDepth && view.x * view.x + view.y * view.y < 0.996)
211
+ continue;
212
+ }
213
+ else {
214
+ // behind the Earth: the line from the camera to the satellite passes through the unit sphere before it gets there
215
+ const px = world.x - c.x;
216
+ const py = world.y - c.y;
217
+ const pz = world.z - c.z;
218
+ const len2 = px * px + py * py + pz * pz;
219
+ const t = Math.max(0, Math.min(1, -(c.x * px + c.y * py + c.z * pz) / len2));
220
+ const nx = c.x + px * t;
221
+ const ny = c.y + py * t;
222
+ const nz = c.z + pz * t;
223
+ if (nx * nx + ny * ny + nz * nz < 0.998)
224
+ continue;
225
+ }
213
226
  best = { group: name, index: i };
214
227
  bestD = d;
215
228
  }
@@ -219,7 +232,7 @@ export function createSatelliteLayer(three, scene, state, ratio) {
219
232
  place(camera, size) {
220
233
  if (!selectedPoints.visible)
221
234
  return null;
222
- projected.set(selectedPosition[0], selectedPosition[1], selectedPosition[2]).project(camera);
235
+ projected.set(selectedPosition[0], selectedPosition[1], selectedPosition[2]).applyMatrix4(scene.matrixWorld).project(camera);
223
236
  if (projected.z > 1 || projected.z < -1)
224
237
  return null;
225
238
  return { x: ((projected.x + 1) / 2) * size.width, y: ((1 - projected.y) / 2) * size.height };
@@ -8,9 +8,40 @@ import { type ScaleMode } from "./scale.ts";
8
8
  import type { SatelliteRef } from "../satellites/types.ts";
9
9
  import { type RideLook } from "./ride.ts";
10
10
  import { type SatelliteState } from "./satellite-layer.ts";
11
+ import { type MeteorState } from "../meteors/layer.ts";
11
12
  type Three = ThreeParts;
12
- /** The camera's distance, in Earth radii, at which the Earth fills the view at zoom 1. */
13
- export declare const FIT_DISTANCE = 3.4;
13
+ /** How much of the view's shorter side the Earth's disc fills at zoom 1 when the page does not say: 0.9, so the atmosphere's glow (8% beyond the disc) is inside the view and never cut. */
14
+ export declare const DEFAULT_EARTH_SIZE = 0.9;
15
+ /**
16
+ * The camera's distance, in radii of the body it looks at, at which the body's disc fills `size` of the view's shorter side (`aspect` is the view's width over its height; the field of view is vertical).
17
+ * Pure; `size` may be above 1 for a body drawn larger than the view.
18
+ *
19
+ * @param size - Share of the shorter side the disc's diameter fills.
20
+ * @param aspect - Width over height of the view.
21
+ * @returns The distance, in the body's radii.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { fitDistance } from "@johnmorrisdotca/chikyu-earth/space";
26
+ *
27
+ * console.log(fitDistance(0.9, 16 / 9).toFixed(2));
28
+ * ```
29
+ */
30
+ export declare function fitDistance(size: number, aspect: number): number;
31
+ /**
32
+ * The camera at the centre of the Earth's view: `ground` is held over a place on the ground (the Earth keeps still, the clock moves the light), `space` is held in the stars at the direction the place was in when it was set (the Earth turns beneath it), `sun` is held on the Sun's side (the day and night line keeps its place while the Earth turns).
33
+ *
34
+ * @example
35
+ * ```ts no-run
36
+ * import type { CameraMode, ChikyuSpace } from "@johnmorrisdotca/chikyu-earth/space/element";
37
+ *
38
+ * const hold = (space: ChikyuSpace, mode: CameraMode): void => {
39
+ * space.camera = mode;
40
+ * };
41
+ * console.log(typeof hold);
42
+ * ```
43
+ */
44
+ export type CameraMode = "ground" | "space" | "sun";
14
45
  /**
15
46
  * The eleven bodies the space view places, names and lets a reader choose: the Earth, the Sun, the Moon, the seven other planets and Pluto.
16
47
  *
@@ -76,8 +107,20 @@ export interface SpaceModel {
76
107
  lon: number;
77
108
  lat: number;
78
109
  };
79
- /** Earth's turn against the stars (degrees) at the moment the camera was last moved: the camera is fixed to the stars, not to the ground. */
110
+ /** Which way the camera is held (see `CameraMode`). */
111
+ camera: CameraMode;
112
+ /** Degrees an hour the cloud picture is made to move eastward against the ground: 0, the default (it is one snapshot, not a forecast). */
113
+ cloudDrift: number;
114
+ /** For the `space` camera: the Earth's turn against the stars (degrees) at the moment the camera was set, so it stays in the stars while the Earth turns beneath; null until the next draw sets it. */
80
115
  cameraSpin: number | null;
116
+ /** The share of the view's shorter side the Earth's disc fills at zoom 1, and where its centre is in the view (0 to 1 across and down; 0.5, 0.5 is the middle). */
117
+ earth: {
118
+ size: number;
119
+ x: number;
120
+ y: number;
121
+ };
122
+ /** The camera's distance at zoom 1 in radii of the body it looks at, as the last draw worked it out from the view's shape and `earth.size`. */
123
+ fit: number;
81
124
  orbits: boolean;
82
125
  labels: boolean;
83
126
  /** Milliseconds of game time one second of wall time covers (the ephemeris is looked up once per such span). */
@@ -105,6 +148,8 @@ export interface SpaceModel {
105
148
  speed: number;
106
149
  /** The satellites shown, the one chosen, and what the last draw did with them. */
107
150
  satellites: SatelliteState;
151
+ /** Meteors seen from space, on the Earth (src/meteors/layer.ts): off unless the element switches them on. */
152
+ meteors: MeteorState;
108
153
  /** The body or satellite the camera rides along with, or null. */
109
154
  ride: RideState | null;
110
155
  /** Set at each draw: the target of the ride could not be placed (a satellite whose elements are too old, or that is gone), so the ordinary camera was used. */
@@ -5,10 +5,31 @@ import { createTrack, orbitPath, PLANETS } from "./ephemeris.js";
5
5
  import { placeAround, placeMoon, placeSun, RADIUS } from "./scale.js";
6
6
  import { ridePose } from "./ride.js";
7
7
  import { createSatelliteLayer, newSatelliteState } from "./satellite-layer.js";
8
+ import { createMeteorLayer, newMeteorState } from "../meteors/layer.js";
9
+ import { subsolarPoint, unitVector } from "../realistic/sun.js";
8
10
  const RAD = Math.PI / 180;
9
- /** The camera's distance, in Earth radii, at which the Earth fills the view at zoom 1. */
10
- export const FIT_DISTANCE = 3.4;
11
11
  const FOV = 35;
12
+ /** How much of the view's shorter side the Earth's disc fills at zoom 1 when the page does not say: 0.9, so the atmosphere's glow (8% beyond the disc) is inside the view and never cut. */
13
+ export const DEFAULT_EARTH_SIZE = 0.9;
14
+ /**
15
+ * The camera's distance, in radii of the body it looks at, at which the body's disc fills `size` of the view's shorter side (`aspect` is the view's width over its height; the field of view is vertical).
16
+ * Pure; `size` may be above 1 for a body drawn larger than the view.
17
+ *
18
+ * @param size - Share of the shorter side the disc's diameter fills.
19
+ * @param aspect - Width over height of the view.
20
+ * @returns The distance, in the body's radii.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { fitDistance } from "@johnmorrisdotca/chikyu-earth/space";
25
+ *
26
+ * console.log(fitDistance(0.9, 16 / 9).toFixed(2));
27
+ * ```
28
+ */
29
+ export function fitDistance(size, aspect) {
30
+ const across = Math.max(0.02, Math.min(50, size)) * Math.min(1, Math.max(0.05, aspect));
31
+ return Math.sqrt(1 + 1 / (across * Math.tan((FOV / 2) * RAD)) ** 2);
32
+ }
12
33
  const LAYERS = ["day", "night", "clouds", "water", "moon"];
13
34
  /** The moons of a planet are shown once the planet is this many CSS pixels across its radius, and each is drawn at least this many pixels across its radius. */
14
35
  const MOON_MIN_PLANET_PX = 4;
@@ -34,7 +55,11 @@ export const newSpaceModel = () => ({
34
55
  mode: "compressed",
35
56
  view: { yaw: 0, tilt: 0, zoom: 1 },
36
57
  centre: { lon: 0, lat: 0 },
58
+ camera: "space",
59
+ cloudDrift: 0,
37
60
  cameraSpin: null,
61
+ earth: { size: DEFAULT_EARTH_SIZE, x: 0.5, y: 0.5 },
62
+ fit: fitDistance(DEFAULT_EARTH_SIZE, 1),
38
63
  orbits: true,
39
64
  labels: true,
40
65
  stepMs: 1000,
@@ -53,6 +78,7 @@ export const newSpaceModel = () => ({
53
78
  pose: { p: [0, 0, 0], q: [0, 0, 0, 1], fov: FOV, valid: false },
54
79
  rideMotion: 0,
55
80
  satellites: newSatelliteState(),
81
+ meteors: newMeteorState(),
56
82
  pick: null,
57
83
  ratio: () => Math.min(globalThis.devicePixelRatio || 1, 2),
58
84
  });
@@ -132,15 +158,17 @@ export function createSpaceItem(model, deps) {
132
158
  const track = createTrack(model.stepMs);
133
159
  let trackStep = model.stepMs;
134
160
  const sunEarth = { value: new three.Vector3(1, 0, 0) };
161
+ /** The Sun in the Earth's own axes (the surface program finds where a cloud's shadow falls from it). */
162
+ const sunLocal = { value: new three.Vector3(1, 0, 0) };
163
+ const cloudShift = { value: 0 };
135
164
  const sunView = { value: new three.Vector3(1, 0, 0) };
136
165
  const grid = sphere(three, 96, 48);
137
166
  const solid = sphere(three, 48, 24);
138
167
  const earthMaterial = new three.ShaderMaterial({
139
168
  vertexShader: SURFACE_VERT,
140
169
  fragmentShader: SURFACE_FRAG,
141
- uniforms: { dayMap: uniform.day, nightMap: uniform.night, waterMap: uniform.water, sunDir: sunEarth, lights: { value: 1 }, boost: { value: 0 }, ortho: { value: 0 } },
170
+ uniforms: { dayMap: uniform.day, nightMap: uniform.night, waterMap: uniform.water, cloudMap: uniform.clouds, sunDir: sunEarth, sunLocal, cloudShift, lights: { value: 1 }, boost: { value: 0 }, ortho: { value: 0 } },
142
171
  });
143
- const cloudShift = { value: 0 };
144
172
  const cloudMaterial = new three.ShaderMaterial({
145
173
  vertexShader: SURFACE_VERT,
146
174
  fragmentShader: CLOUD_FRAG,
@@ -231,6 +259,8 @@ export function createSpaceItem(model, deps) {
231
259
  }
232
260
  const moonSlots = new Map();
233
261
  let releaseTimer;
262
+ let meteors = null;
263
+ let meteorTimer;
234
264
  let layer;
235
265
  const rideState = new Float64Array(6);
236
266
  let selectedShown = false;
@@ -256,6 +286,8 @@ export function createSpaceItem(model, deps) {
256
286
  scene,
257
287
  camera,
258
288
  update() {
289
+ const fit = fitDistance(model.earth.size, size.width / Math.max(1, size.height));
290
+ model.fit = fit;
259
291
  const frame = track.at(model.time);
260
292
  model.lookups = track.lookups;
261
293
  if (model.stepMs !== trackStep) {
@@ -271,7 +303,12 @@ export function createSpaceItem(model, deps) {
271
303
  clouds.rotation.copy(earth.rotation);
272
304
  const toSun = unit(frame.sun);
273
305
  sunEarth.value.set(toSun[0], toSun[1], toSun[2]);
274
- cloudShift.value = -(((model.time / 3_600_000) * 1.5) % 360) / 360;
306
+ {
307
+ // the Earth is turned about the y axis by spin + 90 degrees: the Sun in its own axes is turned back by as much
308
+ const back = -(frame.spin + 90) * RAD;
309
+ sunLocal.value.set(toSun[0] * Math.cos(back) + toSun[2] * Math.sin(back), toSun[1], -toSun[0] * Math.sin(back) + toSun[2] * Math.cos(back));
310
+ }
311
+ cloudShift.value = -(((model.time / 3_600_000) * model.cloudDrift) % 360) / 360;
275
312
  earthMaterial.uniforms["lights"].value = model.light === "lit" ? 0 : 1;
276
313
  earthMaterial.uniforms["boost"].value = model.light === "boost" ? 1 : 0;
277
314
  // the Moon, with its near side to the Earth
@@ -358,7 +395,7 @@ export function createSpaceItem(model, deps) {
358
395
  const place = [rideState[0], rideState[1], rideState[2]];
359
396
  if (ride.view === "follow") {
360
397
  focusPos = place;
361
- focusRadius = Math.max(1e-4, ride.distanceKm / 6371 / FIT_DISTANCE);
398
+ focusRadius = Math.max(1e-4, ride.distanceKm / 6371 / fit);
362
399
  }
363
400
  else
364
401
  rideFrom = { position: place, velocity: [rideState[3], rideState[4], rideState[5]], hidden: null, gameSeconds: 0 };
@@ -390,13 +427,24 @@ export function createSpaceItem(model, deps) {
390
427
  model.rideMotion = typeof ride.target === "string" ? ((speed / Math.max(1e-9, away)) / rideFrom.gameSeconds) * focal : (speed / Math.max(50, (away - 1) * 6371)) * focal;
391
428
  }
392
429
  else {
393
- const spin = model.cameraSpin ?? frame.spin;
430
+ // where the camera is held: over a place on the ground (the Earth's own turn is added to it), in the stars (the turn at the moment it was set), or on the Sun's side (the Sun's right ascension and, for the latitude, its declination)
431
+ let spin = frame.spin;
432
+ let baseLat = model.centre.lat;
433
+ if (model.camera === "space") {
434
+ if (model.cameraSpin === null)
435
+ model.cameraSpin = frame.spin;
436
+ spin = model.cameraSpin;
437
+ }
438
+ else if (model.camera === "sun") {
439
+ spin = Math.atan2(-frame.sun[2], frame.sun[0]) / RAD;
440
+ baseLat += Math.asin(Math.max(-1, Math.min(1, frame.sun[1] / (Math.hypot(...frame.sun) || 1)))) / RAD;
441
+ }
394
442
  // behind a satellite the Earth is the far side of what the camera looks at, so it moves with the camera's side-step; the view is mirrored for the ground to follow the pointer
395
443
  const way = ride && ride.view === "follow" && typeof ride.target !== "string" ? -1 : 1;
396
444
  const lon = model.centre.lon - way * model.view.yaw;
397
- const lat = Math.max(-90, Math.min(90, model.centre.lat - way * model.view.tilt));
445
+ const lat = Math.max(-90, Math.min(90, baseLat - way * model.view.tilt));
398
446
  const aim = direction(spin + lon, lat);
399
- distance = Math.max(1.05 * focusRadius, (FIT_DISTANCE * focusRadius) / Math.max(1e-9, model.view.zoom));
447
+ distance = Math.max(1.05 * focusRadius, (fit * focusRadius) / Math.max(1e-9, model.view.zoom));
400
448
  target.set(focusPos[0], focusPos[1], focusPos[2]);
401
449
  camera.position.set(target.x + aim[0] * distance, target.y + aim[1] * distance, target.z + aim[2] * distance);
402
450
  camera.up.set(0, 1, 0);
@@ -423,6 +471,13 @@ export function createSpaceItem(model, deps) {
423
471
  }
424
472
  camera.fov = fovNow;
425
473
  camera.aspect = size.width / Math.max(1, size.height);
474
+ // the Earth's place in the view: the picture is moved, not the camera (a camera riding from a body keeps the middle)
475
+ const shiftX = rideFrom ? 0 : (model.earth.x - 0.5) * size.width;
476
+ const shiftY = rideFrom ? 0 : (model.earth.y - 0.5) * size.height;
477
+ if (shiftX !== 0 || shiftY !== 0)
478
+ camera.setViewOffset(size.width, size.height, -shiftX, -shiftY, size.width, size.height);
479
+ else if (camera.view)
480
+ camera.clearViewOffset();
426
481
  camera.updateProjectionMatrix();
427
482
  camera.updateMatrixWorld();
428
483
  // always lit: the light comes from the camera's side of the Earth (the Sun, Moon and planets stay where they are)
@@ -535,6 +590,20 @@ export function createSpaceItem(model, deps) {
535
590
  deps.onSelected(at);
536
591
  selectedShown = at !== null;
537
592
  }
593
+ // the meteors, on the Earth: made the first time they are switched on, and asking for their own next draw while a streak is alive or one is due
594
+ if (model.meteors.on && !meteors)
595
+ meteors = createMeteorLayer(three, earth, model.meteors);
596
+ if (meteors) {
597
+ // the camera's place, turned into the Earth's own axes (the Earth is at the middle of the scene and turns about its pole)
598
+ const turn = earth.rotation.y;
599
+ const fx = camera.position.x * Math.cos(turn) - camera.position.z * Math.sin(turn);
600
+ const fz = camera.position.x * Math.sin(turn) + camera.position.z * Math.cos(turn);
601
+ const far = Math.hypot(fx, camera.position.y, fz) || 1;
602
+ const wait = meteors.step({ now: performance.now(), time: model.time, facing: [fx / far, camera.position.y / far, fz / far], sun: unitVector(subsolarPoint(model.time)), radius: Math.min(px.Earth, 1e5), width: size.width, height: size.height });
603
+ if (meteorTimer !== undefined)
604
+ clearTimeout(meteorTimer);
605
+ meteorTimer = Number.isFinite(wait) ? setTimeout(() => deps.invalidate(), wait) : undefined;
606
+ }
538
607
  if (model.rideLost)
539
608
  deps.onRideLost?.();
540
609
  if (model.transition)
@@ -547,6 +616,9 @@ export function createSpaceItem(model, deps) {
547
616
  dispose() {
548
617
  if (releaseTimer !== undefined)
549
618
  clearTimeout(releaseTimer);
619
+ if (meteorTimer !== undefined)
620
+ clearTimeout(meteorTimer);
621
+ meteors?.dispose();
550
622
  layer?.dispose();
551
623
  model.pick = null;
552
624
  textures.dispose();