@johnmorrisdotca/chikyu-earth 0.25.0 → 0.27.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.
@@ -3,13 +3,15 @@
3
3
  // changes, at most 30 times a second, and nothing at all while it is out of sight or the tab is hidden.
4
4
  import { carryControls } from "@johnmorrisdotca/kazoku-ui/view-controls";
5
5
  import { adoptStyles } from "../adopt.js";
6
+ import { cameraCentre, createEarthItem, discRadius, lookAt, newModel } from "./earth.js";
7
+ import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
8
+ import { MAX_ORBIT_GROUP } from "../space/satellite-layer.js";
6
9
  import { METEOR_NOTE_STYLE, prefersLessMotion, setMeteorNote } from "../meteors/note.js";
7
- import { createEarthItem, discRadius, lookAt, newModel } from "./earth.js";
8
10
  import { createGate, frameCap } from "./gate.js";
9
11
  import { setSharedRenderer, setThreeLoader, takeRenderer } from "./shared.js";
10
12
  export { setSharedRenderer, setThreeLoader };
11
13
  import { MAX_TEXTURE, TIERS } from "./tiers.js";
12
- const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}" + METEOR_NOTE_STYLE;
14
+ const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative}:host([immersive]){aspect-ratio:auto;width:100%;height:100%;touch-action:none!important;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}" + METEOR_NOTE_STYLE;
13
15
  const RAD = Math.PI / 180;
14
16
  /** The Sun and the clouds are re-placed this often at real time: 15 degrees an hour is 0.25 degree a minute. */
15
17
  const LIVE_TICK_MS = 60_000;
@@ -30,6 +32,15 @@ const readCentre = (value) => {
30
32
  return null;
31
33
  return { lon: lon, lat: lat };
32
34
  };
35
+ /** A `camera` attribute: `ground` or `sun`, else the camera held in the stars (the default: the Earth turns beneath it). */
36
+ const readCamera = (value) => (value === "ground" || value === "sun" ? value : "space");
37
+ /** A `cloud-drift` attribute: degrees an hour the clouds are made to move eastward against the ground (0, the default: where the picture has them). */
38
+ const readDrift = (value) => (value !== null && Number.isFinite(Number(value)) ? Number(value) : 0);
39
+ /** The plain wheel in an immersive view is a pinch of this share: a notch (100) zooms about 1.2 times, as the family's mouse wheel does with Alt. */
40
+ const WHEEL_AS_PINCH = 0.2;
41
+ /** The quickest a satellite goes round, degrees a second (a low orbit: 88 minutes). */
42
+ const SATELLITE_RATE = 360 / (88 * 60);
43
+ const SATELLITE_COLORS = ["#ffd54f", "#7fd4ff", "#ff8fa3", "#9ef0a8"];
33
44
  /** A `light` attribute: `lit` or `boost`, else the true sun. */
34
45
  const readLight = (value) => (value === "lit" || value === "boost" ? value : "sun");
35
46
  const readRatio = (value) => {
@@ -110,7 +121,7 @@ export const readTime = (value) => {
110
121
  * ```
111
122
  */
112
123
  export class ChikyuEarthRealistic extends HTMLElement {
113
- static observedAttributes = ["center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "meteors", "meteors-label", "lang"];
124
+ static observedAttributes = ["cloud-drift", "center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "camera", "immersive", "meteors", "meteors-label", "lang"];
114
125
  #model = newModel();
115
126
  #mode = "now";
116
127
  #view;
@@ -151,6 +162,9 @@ export class ChikyuEarthRealistic extends HTMLElement {
151
162
  this.#model.clouds = this.getAttribute("clouds") !== "off";
152
163
  this.#model.lights = this.getAttribute("lights") !== "off";
153
164
  this.#model.light = readLight(this.getAttribute("light"));
165
+ this.#model.camera = readCamera(this.getAttribute("camera"));
166
+ this.#model.cloudDrift = readDrift(this.getAttribute("cloud-drift"));
167
+ this.#model.speed = this.speed;
154
168
  if (!this.hasAttribute("role"))
155
169
  this.setAttribute("role", "img");
156
170
  if (!this.hasAttribute("aria-label"))
@@ -192,7 +206,6 @@ export class ChikyuEarthRealistic extends HTMLElement {
192
206
  }
193
207
  this.dispatchEvent(new CustomEvent("chikyu-tiles", { detail: { layers } }));
194
208
  },
195
- drift: 1.5,
196
209
  invalidate: () => this.#gate?.soon(),
197
210
  onDraw: () => this.#gate?.drawn(),
198
211
  onPose: (pose) => {
@@ -202,6 +215,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
202
215
  for (const listener of this.#listeners)
203
216
  listener(this.#pose);
204
217
  },
218
+ onSatellitesError: (error) => this.dispatchEvent(new CustomEvent("chikyu-satellites-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
205
219
  onError: (error) => this.#fail(error instanceof Error ? error.message : String(error)),
206
220
  onTier: (layer, width) => {
207
221
  if (layer in this.#tiers)
@@ -220,7 +234,10 @@ export class ChikyuEarthRealistic extends HTMLElement {
220
234
  this.#set(this.#view?.live === false && taken.renderer.focused !== undefined ? "idle" : "unavailable");
221
235
  });
222
236
  this.addEventListener("pointerdown", this.#take);
237
+ this.addEventListener("pointerdown", this.#down);
223
238
  this.addEventListener("focusin", this.#take);
239
+ // before the shared hands (which hear it after this): a plain wheel in an immersive view zooms
240
+ this.addEventListener("wheel", this.#wheel, { capture: true, passive: false });
224
241
  this.#hands = carryControls(this, { initial: this.#model.view, limits: LIMITS, onChange: (state, info) => this.setView(state, info.final) });
225
242
  this.#startTick();
226
243
  document.addEventListener("visibilitychange", this.#onVisible);
@@ -228,6 +245,9 @@ export class ChikyuEarthRealistic extends HTMLElement {
228
245
  }
229
246
  disconnectedCallback() {
230
247
  this.removeEventListener("pointerdown", this.#take);
248
+ this.removeEventListener("pointerdown", this.#down);
249
+ this.removeEventListener("wheel", this.#wheel, { capture: true });
250
+ window.removeEventListener("pointerup", this.#up, true);
231
251
  this.removeEventListener("focusin", this.#take);
232
252
  this.#hands?.unbind();
233
253
  this.#hands = undefined;
@@ -261,6 +281,12 @@ export class ChikyuEarthRealistic extends HTMLElement {
261
281
  this.#startTick();
262
282
  else if (name === "tiles")
263
283
  this.#gate?.soon();
284
+ else if (name === "camera")
285
+ this.camera = readCamera(value);
286
+ else if (name === "cloud-drift") {
287
+ this.#model.cloudDrift = readDrift(value);
288
+ this.#gate?.soon();
289
+ }
264
290
  else if (name === "meteors")
265
291
  this.meteors = this.#meteorsAsked();
266
292
  else if (name === "meteors-label" || name === "lang")
@@ -327,8 +353,29 @@ export class ChikyuEarthRealistic extends HTMLElement {
327
353
  }
328
354
  set centre(value) {
329
355
  this.#model.centre = { ...value };
356
+ this.#model.cameraSpin = null;
357
+ this.#gate?.soon();
358
+ }
359
+ /**
360
+ * 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
361
+ * moment the camera is set (when the element opens, and again when `time` or `center` is set), so the Earth turns beneath it as the clock runs, with the day and night line where the Sun really is. `ground`: over the place `center` names 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 longitude and
362
+ * latitude from the sub-solar point (`0,0` looks straight at the noon place and shows no night), so the day and night line keeps its place on the screen while the Earth turns beneath. A drag turns the view about the same body in any of them.
363
+ */
364
+ get camera() {
365
+ return this.#model.camera;
366
+ }
367
+ set camera(value) {
368
+ this.#model.camera = value;
369
+ this.#model.cameraSpin = null;
330
370
  this.#gate?.soon();
331
371
  }
372
+ /** True for the full-screen mode (the `immersive` attribute): the element fills its box in any shape, a plain wheel zooms instead of scrolling the page, and a touch drag turns the view instead of scrolling. */
373
+ get immersive() {
374
+ return this.hasAttribute("immersive");
375
+ }
376
+ set immersive(value) {
377
+ this.toggleAttribute("immersive", value);
378
+ }
332
379
  /** The moment shown: milliseconds since the epoch, or "now" while it follows the real clock. The clock runs from it at `speed`, so a number read while time runs is the moment it has reached. */
333
380
  get time() {
334
381
  return this.#mode === "now" && this.speed === 1 ? "now" : this.#model.time;
@@ -339,6 +386,8 @@ export class ChikyuEarthRealistic extends HTMLElement {
339
386
  this.#model.time = Date.now();
340
387
  else
341
388
  this.#model.time = this.#mode;
389
+ this.#model.cameraSpin = null;
390
+ this.#model.speed = this.speed;
342
391
  this.#last = performance.now();
343
392
  this.#startTick();
344
393
  this.#gate?.soon();
@@ -362,6 +411,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
362
411
  if (this.isConnected && this.#view)
363
412
  this.#played = true;
364
413
  this.#speed = next;
414
+ this.#model.speed = this.speed;
365
415
  this.#last = performance.now();
366
416
  this.#startTick();
367
417
  this.#gate?.soon();
@@ -394,6 +444,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
394
444
  return {
395
445
  state: this.#state,
396
446
  tiers: { ...this.#tiers },
447
+ satellites: this.#satelliteStats(),
397
448
  tiles: this.#model.tiles?.stats ?? { ready: false, level: null, held: 0, shown: 0, loading: 0, failed: 0, requested: 0 },
398
449
  draws: stats?.draws ?? 0,
399
450
  contexts: stats?.contexts ?? 0,
@@ -415,11 +466,110 @@ export class ChikyuEarthRealistic extends HTMLElement {
415
466
  }
416
467
  const shifted = view.zoom !== drawn.view.zoom || view.panX !== drawn.view.panX || view.panY !== drawn.view.panY;
417
468
  const a = lookAt(drawn.centre, drawn.view);
418
- const b = lookAt(this.#model.centre, view);
469
+ const b = lookAt(cameraCentre(this.#model), view);
419
470
  const px = (Math.abs(b.lon - a.lon) * Math.cos(((a.lat + b.lat) / 2) * RAD) + Math.abs(b.lat - a.lat)) * RAD * drawn.radius;
420
471
  if (shifted || px >= 0.5 || (final && px > 0.01))
421
472
  this.#gate?.soon();
422
473
  }
474
+ // --- satellites ---------------------------------------------------------------------------------------------------------------------------------
475
+ /**
476
+ * Show a group of satellites (made by `createSatellites`) under a name, or take the group away with `null`. A group is one draw call however many satellites it holds, so every group of the catalogue can be shown at once. Giving the name of a group
477
+ * that is already shown replaces it. `style`: `color` and `size` (CSS pixels) of the dots, and `orbits` to draw every orbit (only for a group of 40 or fewer, such as the stations). The groups are placed by SGP4 about once a second and interpolated
478
+ * between, are hidden while the clock runs faster than `MAX_SATELLITE_SPEED`, are hidden by the Earth when they are behind it, and draw at most 30 times a second and not at all while the clock holds.
479
+ *
480
+ * @param group - The group's name, for `showSatellites`, `selectSatellite` and the events.
481
+ * @param satellites - The group, or `null` to remove it.
482
+ * @param style - How to draw it.
483
+ */
484
+ setSatellites(group, satellites, style = {}) {
485
+ const groups = this.#model.satellites.groups;
486
+ if (satellites === null) {
487
+ groups.delete(group);
488
+ if (this.#model.satellites.selected?.group === group)
489
+ this.#model.satellites.selected = null;
490
+ }
491
+ else {
492
+ const was = groups.get(group);
493
+ groups.set(group, {
494
+ satellites,
495
+ color: style.color ?? was?.color ?? SATELLITE_COLORS[groups.size % SATELLITE_COLORS.length],
496
+ size: style.size ?? was?.size ?? 3,
497
+ orbits: (style.orbits ?? was?.orbits ?? false) && satellites.count <= MAX_ORBIT_GROUP,
498
+ visible: was?.visible ?? true,
499
+ });
500
+ }
501
+ this.#last = performance.now();
502
+ this.#startTick();
503
+ this.#gate?.soon();
504
+ }
505
+ /** Show or hide a group without losing it. */
506
+ showSatellites(group, on) {
507
+ const found = this.#model.satellites.groups.get(group);
508
+ if (!found || found.visible === on)
509
+ return;
510
+ found.visible = on;
511
+ this.#startTick();
512
+ this.#gate?.soon();
513
+ }
514
+ /** The groups now set, with how many satellites each holds and whether it is shown. */
515
+ get satelliteGroups() {
516
+ return [...this.#model.satellites.groups].map(([name, group]) => ({ name, count: group.satellites.count, visible: group.visible }));
517
+ }
518
+ /** Mark one satellite: a larger ring round it and its orbit drawn. `null` lets it go. */
519
+ selectSatellite(ref) {
520
+ const found = ref ? this.#model.satellites.groups.get(ref.group) : undefined;
521
+ this.#model.satellites.selected = ref && found && ref.index >= 0 && ref.index < found.satellites.count ? { group: ref.group, index: ref.index } : null;
522
+ this.#gate?.soon();
523
+ }
524
+ /** The satellite marked by `selectSatellite` or by a press on it, if any. */
525
+ get selectedSatellite() {
526
+ const chosen = this.#model.satellites.selected;
527
+ return chosen ? { ...chosen } : null;
528
+ }
529
+ /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period); undefined if it cannot be placed then. */
530
+ satelliteInfo(ref) {
531
+ return this.#model.satellites.groups.get(ref.group)?.satellites.info(ref.index, this.#model.time);
532
+ }
533
+ #satelliteStats() {
534
+ const drawn = this.#model.satellites.drawn;
535
+ let propagations = 0;
536
+ let lastBatchMs = 0;
537
+ let maxBatchMs = 0;
538
+ for (const group of this.#model.satellites.groups.values()) {
539
+ propagations += group.satellites.propagations;
540
+ lastBatchMs = Math.max(lastBatchMs, group.satellites.timing.lastBatchMs);
541
+ maxBatchMs = Math.max(maxBatchMs, group.satellites.timing.maxBatchMs);
542
+ }
543
+ return { groups: this.#model.satellites.groups.size, placed: drawn.placed, tooFast: drawn.tooFast, propagations, lastBatchMs, maxBatchMs, updateMs: drawn.updateMs, maxUpdateMs: drawn.maxUpdateMs, averageUpdateMs: drawn.updates ? drawn.totalMs / drawn.updates : 0, updates: drawn.updates };
544
+ }
545
+ // A press that does not turn the view (under 6 pixels) on a satellite tells the page, which chooses it with `selectSatellite` if it likes.
546
+ #downX = 0;
547
+ #downY = 0;
548
+ #down = (event) => {
549
+ if (event.button !== 0 || this.#model.satellites.groups.size === 0)
550
+ return;
551
+ this.#downX = event.clientX;
552
+ this.#downY = event.clientY;
553
+ window.addEventListener("pointerup", this.#up, { capture: true, once: true });
554
+ };
555
+ #up = (event) => {
556
+ if (Math.hypot(event.clientX - this.#downX, event.clientY - this.#downY) > 6)
557
+ return;
558
+ const rect = this.getBoundingClientRect();
559
+ const satellite = this.#model.pick?.(event.clientX - rect.left, event.clientY - rect.top, 12);
560
+ if (satellite)
561
+ this.dispatchEvent(new CustomEvent("chikyu-satellite-click", { detail: { ...satellite, info: this.satelliteInfo(satellite) }, bubbles: true, composed: true }));
562
+ };
563
+ // In an immersive view a plain wheel zooms. It is passed on to the shared hands as the wheel's own pinch (Ctrl and a small step), so whichever hands hold the view (the element's, or a bar bound to it) apply it with their limits;
564
+ // Ctrl, Command, Alt and Shift with the wheel are the family's own and are left alone.
565
+ #wheel = (event) => {
566
+ if (!this.hasAttribute("immersive") || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey)
567
+ return;
568
+ event.preventDefault();
569
+ event.stopImmediatePropagation();
570
+ const pixels = event.deltaMode === 1 ? event.deltaY * 33 : event.deltaMode === 2 ? event.deltaY * 800 : event.deltaY;
571
+ this.dispatchEvent(new WheelEvent("wheel", { deltaY: Math.max(-250, Math.min(250, pixels)) * WHEEL_AS_PINCH, deltaMode: 0, clientX: event.clientX, clientY: event.clientY, ctrlKey: true, bubbles: true, cancelable: true, composed: true }));
572
+ };
423
573
  /** The view as it is (for a page that wants to read it back). */
424
574
  get view() {
425
575
  return { ...this.#model.view };
@@ -437,12 +587,23 @@ export class ChikyuEarthRealistic extends HTMLElement {
437
587
  const seconds = Number(this.getAttribute("live-seconds"));
438
588
  const live = Number.isFinite(seconds) && seconds > 0 ? Math.max(MIN_TICK_MS, seconds * 1000) : LIVE_TICK_MS;
439
589
  const speed = Math.abs(this.speed);
440
- if (speed <= 1)
590
+ const satellites = this.#satellitesMoving();
591
+ // satellites go round in 90 minutes, so with any on show even real time is drawn about once a second
592
+ if (speed <= 1 && !satellites)
441
593
  return live;
442
594
  if (typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches)
443
595
  return Math.min(live, 1000);
444
596
  const radius = this.#model.drawn?.radius ?? 200;
445
- return Math.min(live, 1000 / Math.min(30, Math.max(1, SUN_RATE * RAD * speed * radius)));
597
+ return Math.min(live, 1000 / Math.min(30, Math.max(1, (satellites ? SATELLITE_RATE : SUN_RATE) * RAD * speed * radius)));
598
+ }
599
+ /** Is anything on show that moves faster than the Earth turns: a group of satellites the clock is slow enough to place? */
600
+ #satellitesMoving() {
601
+ if (Math.abs(this.speed) > MAX_SATELLITE_SPEED)
602
+ return false;
603
+ for (const group of this.#model.satellites.groups.values())
604
+ if (group.visible && group.satellites.count > 0)
605
+ return true;
606
+ return false;
446
607
  }
447
608
  /** Tell the page the moment shown: at most four times a second while time runs (`running`, and not from a hidden tab), and once, at once, when it holds. */
448
609
  #announce(running) {
@@ -1,7 +1,7 @@
1
- export { subsolarPoint, unitVector, julianDay } from "./sun.ts";
1
+ export { greenwichSidereal, subsolarPoint, unitVector, julianDay } from "./sun.ts";
2
2
  export { chooseTier, textureBytes, textureCap, MAX_TEXTURE, TIERS, TEXELS_PER_RADIUS_PIXEL, type Layer } from "./tiers.ts";
3
3
  export { createGate, frameCap, type Gate } from "./gate.ts";
4
- export { lookAt, discRadius, ATMOSPHERE_OUTER, type LightMode } from "./earth.ts";
4
+ export { lookAt, discRadius, ATMOSPHERE_OUTER, cameraCentre, type CameraMode, type LightMode } from "./earth.ts";
5
5
  export type { ThreeParts } from "./earth.ts";
6
6
  export { TEXEL_SLACK, coveringTile, parseManifest, pointOnEarth, tileColumns, tileLevel, tileRect, tileRows, tilesInView, type TileCamera, type TileId, type TileLayer, type VisibleTile } from "./tiles.ts";
7
7
  export { TILE_KEEP_MS, TILE_LIMIT } from "./tile-set.ts";
@@ -1,8 +1,8 @@
1
1
  // The realistic Earth's pure parts, which import on a server and need neither three.js nor a browser. The element is
2
2
  // `@johnmorrisdotca/chikyu-earth/realistic/element`.
3
- export { subsolarPoint, unitVector, julianDay } from "./sun.js";
3
+ export { greenwichSidereal, subsolarPoint, unitVector, julianDay } from "./sun.js";
4
4
  export { chooseTier, textureBytes, textureCap, MAX_TEXTURE, TIERS, TEXELS_PER_RADIUS_PIXEL } from "./tiers.js";
5
5
  export { createGate, frameCap } from "./gate.js";
6
- export { lookAt, discRadius, ATMOSPHERE_OUTER } from "./earth.js";
6
+ export { lookAt, discRadius, ATMOSPHERE_OUTER, cameraCentre } from "./earth.js";
7
7
  export { TEXEL_SLACK, coveringTile, parseManifest, pointOnEarth, tileColumns, tileLevel, tileRect, tileRows, tilesInView } from "./tiles.js";
8
8
  export { TILE_KEEP_MS, TILE_LIMIT } from "./tile-set.js";
@@ -9,7 +9,7 @@ export declare const TILE_FRAG: string;
9
9
  export declare const TILE_VERT = "\nuniform vec4 rect;\nuniform float radius;\nvarying vec2 vUv;\nvarying vec2 vUvG;\nvarying vec3 vNormal;\nvarying vec3 vWorld;\nvoid main() {\n vUv = uv;\n float lon = mix(rect.x, rect.z, uv.x);\n float lat = mix(rect.y, rect.w, uv.y);\n vec3 unit = vec3(cos(lat) * sin(lon), sin(lat), cos(lat) * cos(lon));\n vUvG = vec2((lon + 3.14159265358979) / 6.28318530717959, 0.5 - lat / 3.14159265358979);\n vNormal = normalize(mat3(modelMatrix) * unit);\n vec4 world = modelMatrix * vec4(unit * radius, 1.0);\n vWorld = world.xyz;\n gl_Position = projectionMatrix * viewMatrix * world;\n}";
10
10
  export declare const CLOUD_FRAG = "\nuniform sampler2D cloudMap;\nuniform vec3 sunDir;\nuniform float shift;\nuniform float opacity;\nvarying vec2 vUv;\nvarying vec3 vNormal;\nvoid main() {\n vec3 n = normalize(vNormal);\n float ndl = dot(n, sunDir);\n float c = texture2D(cloudMap, vec2(vUv.x + shift, vUv.y)).r;\n float a = smoothstep(0.28, 0.88, c) * opacity;\n float day = smoothstep(-0.10, 0.25, ndl);\n vec3 col = mix(vec3(0.015, 0.02, 0.04), vec3(1.0), day * (0.18 + 0.82 * pow(max(ndl, 0.0), 0.45)));\n col += vec3(0.55, 0.28, 0.14) * smoothstep(-0.14, 0.0, ndl) * (1.0 - smoothstep(0.0, 0.25, ndl)) * 0.35;\n gl_FragColor = vec4(col, a);\n}";
11
11
  export declare const ATMOSPHERE_VERT = "\nvarying vec3 vPosView;\nvarying vec3 vNormalView;\nvoid main() {\n vec4 view = modelViewMatrix * vec4(position, 1.0);\n vPosView = view.xyz;\n vNormalView = normalize(normalMatrix * position);\n gl_Position = projectionMatrix * view;\n}";
12
- export declare const ATMOSPHERE_FRAG = "\nuniform vec3 sunView;\nuniform float outer;\nuniform float ortho;\nvarying vec3 vPosView;\nvarying vec3 vNormalView;\nvoid main() {\n vec3 n = normalize(vNormalView);\n vec3 v = ortho > 0.5 ? vec3(0.0, 0.0, 1.0) : normalize(-vPosView);\n float nz = clamp(dot(n, v), -1.0, 1.0);\n float rho = outer * sqrt(max(0.0, 1.0 - nz * nz));\n float t = clamp((rho - 1.0) / (outer - 1.0), 0.0, 1.0);\n vec2 dir = normalize(n.xy + vec2(1e-5, 0.0));\n float side = smoothstep(-0.40, 0.55, dot(vec3(dir, 0.0), sunView));\n float glow = pow(1.0 - t, 3.0) * (0.10 + 0.90 * side);\n vec3 col = mix(vec3(0.10, 0.22, 0.60), vec3(0.42, 0.68, 1.0), side);\n gl_FragColor = vec4(col, glow * 0.9);\n}";
12
+ export declare const ATMOSPHERE_FRAG = "\nuniform vec3 sunView;\nuniform float outer;\nuniform float ortho;\nvarying vec3 vPosView;\nvarying vec3 vNormalView;\nvoid main() {\n vec3 n = normalize(vNormalView);\n vec3 v = ortho > 0.5 ? vec3(0.0, 0.0, 1.0) : normalize(-vPosView);\n float nz = clamp(dot(n, v), -1.0, 1.0);\n float rho = outer * sqrt(max(0.0, 1.0 - nz * nz));\n float t = clamp((rho - 1.0) / (outer - 1.0), 0.0, 1.0);\n vec2 dir = normalize(n.xy + vec2(1e-5, 0.0));\n // the Sun's light at this point of the limb: 1 where the Sun stands behind it, 0 at the terminator, -1 on the night side\n float toward = dot(vec3(dir, 0.0), sunView);\n float side = smoothstep(-0.45, 0.45, toward);\n // a thin bright layer on the limb and a wide faint halo, both fading to nothing at the outer edge\n float limb = pow(1.0 - t, 5.0);\n float halo = pow(1.0 - t, 2.2);\n float glow = (limb * 0.85 + halo * 0.35) * (0.06 + 0.94 * side);\n vec3 day = mix(vec3(0.30, 0.52, 0.95), vec3(0.50, 0.74, 1.0), limb);\n vec3 dusk = mix(vec3(1.0, 0.42, 0.16), vec3(1.0, 0.62, 0.30), limb);\n float band = exp(-pow(toward / 0.32, 2.0));\n vec3 col = mix(mix(vec3(0.06, 0.12, 0.35), day, side), dusk, band * 0.85);\n gl_FragColor = vec4(col, clamp(glow, 0.0, 1.0) * (1.0 - t));\n}";
13
13
  /** The Moon and other plain bodies: a picture (or a flat colour) lit by the Sun, with a trace of light on the dark side. */
14
14
  export declare const BODY_FRAG = "\nuniform sampler2D map;\nuniform vec3 tint;\nuniform float textured;\nuniform float ambient;\nuniform vec3 sunDir;\nvarying vec2 vUv;\nvarying vec3 vNormal;\nvoid main() {\n vec3 n = normalize(vNormal);\n float ndl = dot(n, sunDir);\n vec3 albedo = textured > 0.5 ? texture2D(map, vUv).rgb : tint;\n float lit = smoothstep(-0.04, 0.12, ndl) * (0.10 + 0.95 * pow(max(ndl, 0.0), 0.6));\n gl_FragColor = vec4(albedo * (ambient + lit), 1.0);\n}";
15
15
  /** A flat quad facing the camera: the Sun's disc and its glow. */
@@ -10,12 +10,24 @@ void main() {
10
10
  vWorld = (modelMatrix * vec4(position, 1.0)).xyz;
11
11
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
12
12
  }`;
13
- /** The surface program. `tile` is the program of a map tile laid over the whole-Earth pictures: the day picture is read at the tile's own coordinates, the rest at the whole Earth's. */
13
+ /**
14
+ * The surface program. `tile` is the program of a map tile laid over the whole-Earth pictures: the day picture is read at the tile's own coordinates, the rest at the whole Earth's.
15
+ *
16
+ * What it shades, in the textures' own (sRGB) space (a look, not a radiometric model):
17
+ * - the Sun's light reddens towards the terminator and the twilight has a warm band on the lit side and a blue hour beyond it;
18
+ * - the ocean is a clearer blue, with a hard glint under the Sun, a broad sheen round it, and the sky reflected at grazing angles; clouds hide the glint;
19
+ * - the clouds throw a shadow on the ground, displaced away from the Sun and longer as it gets low;
20
+ * - the night side has the city lights warm and softly spread, dimmed where cloud covers them;
21
+ * - the air shows as a rim on the limb, blue by day and orange along the terminator.
22
+ */
14
23
  const surfaceFrag = (tile) => /* glsl */ `
15
24
  uniform sampler2D dayMap;
16
25
  uniform sampler2D nightMap;
17
26
  uniform sampler2D waterMap;
27
+ uniform sampler2D cloudMap;
18
28
  uniform vec3 sunDir;
29
+ uniform vec3 sunLocal;
30
+ uniform float cloudShift;
19
31
  uniform float lights;
20
32
  uniform float boost;
21
33
  uniform float ortho;
@@ -23,30 +35,58 @@ ${tile ? "uniform vec4 nightRect;\nvarying vec2 vUvG;" : ""}
23
35
  varying vec2 vUv;
24
36
  varying vec3 vNormal;
25
37
  varying vec3 vWorld;
38
+ const float PI = 3.14159265358979;
26
39
  void main() {
27
40
  vec3 n = normalize(vNormal);
28
41
  vec3 toEye = ortho > 0.5 ? vec3(0.0, 0.0, 1.0) : normalize(cameraPosition - vWorld);
29
42
  float ndl = dot(n, sunDir);
43
+ float ndv = clamp(dot(n, toEye), 0.0, 1.0);
30
44
  float day = smoothstep(-0.10, 0.22, ndl);
45
+ vec2 g = ${tile ? "vUvG" : "vUv"};
31
46
  vec3 albedo = texture2D(dayMap, vUv).rgb;
32
- float water = texture2D(waterMap, ${tile ? "vUvG" : "vUv"}).r;
47
+ float water = texture2D(waterMap, g).r;
48
+ albedo = pow(albedo, vec3(0.86)) * 1.08;
49
+ albedo *= mix(vec3(1.0), vec3(1.05, 1.22, 1.55), water);
50
+
51
+ // the cloud over this point, and the cloud whose shadow falls on it (found by going back along the Sun's ground track)
52
+ float lat = (0.5 - g.y) * PI;
53
+ float lon = (g.x - 0.5) * 2.0 * PI;
54
+ vec3 east = vec3(cos(lon), 0.0, -sin(lon));
55
+ vec3 north = vec3(-sin(lat) * sin(lon), cos(lat), -sin(lat) * cos(lon));
56
+ vec2 away = -vec2(dot(sunLocal, east), dot(sunLocal, north)) / max(ndl, 0.2);
57
+ vec2 cu = vec2(g.x + cloudShift, g.y);
58
+ vec2 shadowAt = cu + vec2(away.x * 0.012 / (2.0 * PI * max(cos(lat), 0.15)), -away.y * 0.012 / PI);
59
+ float cover = smoothstep(0.28, 0.88, texture2D(cloudMap, cu).r);
60
+ float shadow = smoothstep(0.28, 0.88, texture2D(cloudMap, shadowAt).r);
33
61
 
34
- vec3 lit = albedo * (0.07 + 1.0 * pow(max(ndl, 0.0), 0.5));
62
+ vec3 sunColour = mix(vec3(1.0, 0.62, 0.38), vec3(1.0, 0.97, 0.91), smoothstep(0.0, 0.22, ndl));
63
+ vec3 lit = albedo * sunColour * (0.07 + 1.2 * pow(max(ndl, 0.0), 0.5));
64
+ lit *= 1.0 - 0.5 * shadow * smoothstep(0.02, 0.3, ndl);
35
65
  float dusk = smoothstep(-0.14, 0.0, ndl) * (1.0 - smoothstep(0.0, 0.30, ndl));
36
66
  lit += vec3(0.55, 0.28, 0.14) * dusk * 0.30 * (0.35 + 0.65 * albedo.g);
37
67
 
68
+ // the ocean: a hard glint, a broad sheen round it, the sky at grazing angles
38
69
  vec3 h = normalize(sunDir + toEye);
39
- float glint = pow(max(dot(n, h), 0.0), 220.0) * water * day;
40
- lit += vec3(1.0, 0.93, 0.80) * glint * 0.7;
70
+ float nh = max(dot(n, h), 0.0);
71
+ float open = water * (1.0 - 0.9 * cover) * day;
72
+ float spec = pow(nh, 400.0) * 0.45 + pow(nh, 50.0) * 0.12;
73
+ lit += vec3(1.0, 0.93, 0.80) * spec * open;
74
+ lit += vec3(0.28, 0.50, 0.95) * pow(1.0 - ndv, 4.0) * 0.5 * open;
41
75
 
42
- vec3 night = texture2D(nightMap, ${tile ? "(vUvG - nightRect.xy) / nightRect.zw" : "vUv"}).rgb;
43
- night = night * night * vec3(1.6, 1.5, 1.3) * lights + night * 0.25;
76
+ vec2 nuv = ${tile ? "(vUvG - nightRect.xy) / nightRect.zw" : "vUv"};
77
+ vec3 lamp = texture2D(nightMap, nuv).rgb;
78
+ ${tile ? "vec3 spread = lamp;" : "vec3 spread = (texture2D(nightMap, nuv + vec2(0.0007, 0.0)).rgb + texture2D(nightMap, nuv - vec2(0.0007, 0.0)).rgb + texture2D(nightMap, nuv + vec2(0.0, 0.0014)).rgb + texture2D(nightMap, nuv - vec2(0.0, 0.0014)).rgb) * 0.25;"}
79
+ vec3 lamps = (lamp * lamp * vec3(1.6, 1.4, 1.1) + spread * vec3(0.55, 0.40, 0.22)) * lights * (1.0 - 0.7 * cover);
80
+ vec3 night = lamps + lamp * 0.25;
81
+ // the blue hour just beyond the terminator
82
+ night += vec3(0.04, 0.08, 0.20) * smoothstep(-0.20, -0.06, ndl) * (1.0 - smoothstep(-0.06, 0.06, ndl)) * 0.28;
44
83
  vec3 col = mix(night, lit, day);
45
84
  col += pow(albedo, vec3(0.75)) * boost * 0.65 * (1.0 - day);
46
85
 
47
- float rim = pow(1.0 - clamp(dot(n, toEye), 0.0, 1.0), 3.0);
86
+ float rim = pow(1.0 - ndv, 3.0);
48
87
  float sunSide = 0.12 + 0.88 * smoothstep(-0.25, 0.5, ndl);
49
- col += vec3(0.20, 0.45, 1.0) * rim * sunSide * 0.55;
88
+ vec3 rimColour = mix(vec3(0.20, 0.45, 1.0), vec3(1.0, 0.45, 0.18), 0.8 * (1.0 - smoothstep(0.0, 0.30, abs(ndl))));
89
+ col += rimColour * rim * sunSide * 0.6;
50
90
  gl_FragColor = vec4(col, 1.0);
51
91
  }`;
52
92
  export const SURFACE_FRAG = surfaceFrag(false);
@@ -113,10 +153,18 @@ void main() {
113
153
  float rho = outer * sqrt(max(0.0, 1.0 - nz * nz));
114
154
  float t = clamp((rho - 1.0) / (outer - 1.0), 0.0, 1.0);
115
155
  vec2 dir = normalize(n.xy + vec2(1e-5, 0.0));
116
- float side = smoothstep(-0.40, 0.55, dot(vec3(dir, 0.0), sunView));
117
- float glow = pow(1.0 - t, 3.0) * (0.10 + 0.90 * side);
118
- vec3 col = mix(vec3(0.10, 0.22, 0.60), vec3(0.42, 0.68, 1.0), side);
119
- gl_FragColor = vec4(col, glow * 0.9);
156
+ // the Sun's light at this point of the limb: 1 where the Sun stands behind it, 0 at the terminator, -1 on the night side
157
+ float toward = dot(vec3(dir, 0.0), sunView);
158
+ float side = smoothstep(-0.45, 0.45, toward);
159
+ // a thin bright layer on the limb and a wide faint halo, both fading to nothing at the outer edge
160
+ float limb = pow(1.0 - t, 5.0);
161
+ float halo = pow(1.0 - t, 2.2);
162
+ float glow = (limb * 0.85 + halo * 0.35) * (0.06 + 0.94 * side);
163
+ vec3 day = mix(vec3(0.30, 0.52, 0.95), vec3(0.50, 0.74, 1.0), limb);
164
+ vec3 dusk = mix(vec3(1.0, 0.42, 0.16), vec3(1.0, 0.62, 0.30), limb);
165
+ float band = exp(-pow(toward / 0.32, 2.0));
166
+ vec3 col = mix(mix(vec3(0.06, 0.12, 0.35), day, side), dusk, band * 0.85);
167
+ gl_FragColor = vec4(col, clamp(glow, 0.0, 1.0) * (1.0 - t));
120
168
  }`;
121
169
  /** The Moon and other plain bodies: a picture (or a flat colour) lit by the Sun, with a trace of light on the dark side. */
122
170
  export const BODY_FRAG = /* glsl */ `
@@ -13,6 +13,20 @@ import type { GeoPoint } from "../types.ts";
13
13
  * ```
14
14
  */
15
15
  export declare const julianDay: (ms: number) => number;
16
+ /**
17
+ * How far the Earth has turned against the stars at `ms`: Greenwich mean sidereal time, in degrees from 0 to 360. The longitude that faces a direction fixed in space goes west at this rate (about 361 degrees a day).
18
+ *
19
+ * @param ms - A moment, in milliseconds since the Unix epoch.
20
+ * @returns The angle in degrees.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { greenwichSidereal } from "@johnmorrisdotca/chikyu-earth/realistic";
25
+ *
26
+ * console.log(greenwichSidereal(Date.UTC(2000, 0, 1, 12)).toFixed(2));
27
+ * ```
28
+ */
29
+ export declare function greenwichSidereal(ms: number): number;
16
30
  /**
17
31
  * The point where the Sun is at the zenith at `ms`: latitude is the Sun's declination, longitude runs west at 15 degrees an hour.
18
32
  *
@@ -14,6 +14,24 @@ const wrap360 = (degrees) => ((degrees % 360) + 360) % 360;
14
14
  * ```
15
15
  */
16
16
  export const julianDay = (ms) => ms / 86_400_000 + 2_440_587.5;
17
+ /**
18
+ * How far the Earth has turned against the stars at `ms`: Greenwich mean sidereal time, in degrees from 0 to 360. The longitude that faces a direction fixed in space goes west at this rate (about 361 degrees a day).
19
+ *
20
+ * @param ms - A moment, in milliseconds since the Unix epoch.
21
+ * @returns The angle in degrees.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { greenwichSidereal } from "@johnmorrisdotca/chikyu-earth/realistic";
26
+ *
27
+ * console.log(greenwichSidereal(Date.UTC(2000, 0, 1, 12)).toFixed(2));
28
+ * ```
29
+ */
30
+ export function greenwichSidereal(ms) {
31
+ const days = julianDay(ms) - 2_451_545;
32
+ const t = days / 36_525;
33
+ return wrap360(280.46061837 + 360.98564736629 * days + 0.000387933 * t * t);
34
+ }
17
35
  /**
18
36
  * The point where the Sun is at the zenith at `ms`: latitude is the Sun's declination, longitude runs west at 15 degrees an hour.
19
37
  *
@@ -41,7 +59,7 @@ export function subsolarPoint(ms) {
41
59
  const obliquity = (23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60) / 60 + 0.00256 * Math.cos(node)) * RAD;
42
60
  const declination = Math.asin(Math.sin(obliquity) * Math.sin(apparentLongitude));
43
61
  const rightAscension = Math.atan2(Math.cos(obliquity) * Math.sin(apparentLongitude), Math.cos(apparentLongitude)) / RAD;
44
- const siderealGreenwich = wrap360(280.46061837 + 360.98564736629 * (jd - 2_451_545) + 0.000387933 * t * t);
62
+ const siderealGreenwich = greenwichSidereal(ms);
45
63
  const lon = ((wrap360(rightAscension - siderealGreenwich) + 180) % 360) - 180;
46
64
  return { lon, lat: declination / RAD };
47
65
  }
@@ -37,6 +37,8 @@ export interface TileShared {
37
37
  /** The whole-Earth water and night pictures' uniforms: their value is the picture now held. */
38
38
  water: Uniform<THREE.Texture | null>;
39
39
  night: Uniform<THREE.Texture | null>;
40
+ /** More uniforms the surface program reads (the cloud picture and where the Sun is in the Earth's axes), shared with the sphere's own. */
41
+ extra?: Record<string, Uniform<unknown>>;
40
42
  }
41
43
  export interface TileSetDeps {
42
44
  assets: AssetCache;
@@ -239,6 +239,7 @@ export function createTileSet(three, parent, shared, deps) {
239
239
  lights: shared.lights,
240
240
  boost: shared.boost,
241
241
  ortho: shared.ortho,
242
+ ...shared.extra,
242
243
  nightRect,
243
244
  rect: { value: tileRect(entry.id) },
244
245
  // a finer level sits a little higher, so two levels at once never fight for the same depth; all sit above the whole-Earth sphere's flat faces
@@ -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.
@@ -157,6 +157,22 @@ export declare class ChikyuSpace extends HTMLElement {
157
157
  set meteors(value: boolean);
158
158
  get centre(): GeoPoint;
159
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);
160
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. */
161
177
  get time(): number;
162
178
  set time(value: number | Date | "now");