@johnmorrisdotca/chikyu-earth 0.9.0 → 0.10.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ Three fixes for a page that puts the Earth behind something else.
6
+
7
+ - **A time and a view changed together are one draw** (MODULES-177). `time` and `setView` in one task each asked the rate gate; the first drew at once and the second 33 ms later, so a page moving the Sun and the camera on every tick drew twice. `Gate.soon()` makes every ask of one task a single ask, made when the task ends, and the realistic element uses it. Measured before: 2 draws for the two changes, now 1 (`e2e/realistic.gl.ts`).
8
+ - **`max-ratio`** on `<chikyu-earth-realistic>`: the most device pixels to a CSS pixel the canvas is drawn at (2 at most; `0.5` draws at half the size and scales it up). It is read when the element connects and is the shared renderer's cap for the page; the textures are chosen for it too. Test: at a device ratio of 2, `max-ratio="1"` draws a canvas under a third of the pixels.
9
+ - **A strict Content-Security-Policy no longer refuses the elements' styles** (MODULES-180). `<chikyu-earth>`, `<chikyu-earth-realistic>` and `<chikyu-space>` wrote a `<style>` into their shadow roots, which `style-src 'self'` blocks. They now adopt a constructable stylesheet (shared by every element with the same text), and where a browser has none, a `<style>` carrying the element's `nonce`. Test (`e2e/csp.gl.ts`): each element in a page served with `style-src 'self'` reports no violation, its styles apply, and no `<style>` is written.
10
+ - **`setSharedRenderer(renderer)`** (`@johnmorrisdotca/chikyu-earth/realistic/element`; MODULES-171): the page hands the Earth and the space view a renderer made with kazoku-ui's `createSharedRenderer`, so a page that draws other things with it keeps one WebGL context. The page owns it: its `maxRatio` and `onContext` apply and the elements never dispose it. Call it before the first element connects (it throws while one is in the page). Unit-tested (`test/shared.test.ts`).
11
+
12
+ ## 0.9.1
13
+
14
+ The ground now follows the pointer, in every look and when riding.
15
+
16
+ - **The Earth turned the wrong way up and down** (MODULES-200). A drag up made the ground go down in the line, thick, realistic and space looks, and the up arrow did the same: the controls' tilt was added to the latitude of the view, and it should be subtracted (the top of the globe tips away as the tilt grows, as the controls say). It is now one sign in `lookAt` and `projectionView` (`src/view.ts`) and one in the space view, so the flat globe, the realistic Earth and the space view agree. **A tilt in an address or a call now tips the other way.**
17
+ Left and right were right already. Auto-turn turns the real way: the Earth goes round west to east, so with north up the ground moves from left to right, the same way as a drag right and the right arrow.
18
+ - **A ride could not be dragged** (MODULES-199). Riding at a body, a drag turned the camera's head round the straight-down line, which from the ISS only spun the picture, and tilt could not go the other way past the straight-down look, so a drag seemed to do nothing. `ridePose` now looks about from the base look as a head on a pivot does: yaw turns the camera to its left and tilt tips it towards the bottom of its picture, so a drag right moves the ground right and a drag up moves it up, about one and a half pixels a pixel, the pace of the line globe and the Earth from space. The angle for a pixel follows the field of view, so zooming in does not make the ground race. Behind a satellite (`view: "follow"`) the drag is mirrored, because the Earth is behind what the camera looks at, and the Earth follows the pointer.
19
+ - **The demo keeps the address's yaw and tilt when it opens on a ride** (it set both to 0 as the ride began), and **an address with `ride` and no `look` opens the space look**, so the reported address rides the ISS.
20
+ - **Tests**: `e2e/drag.gl.ts` drags with a real pointer, presses the arrow keys and runs Auto-turn in the line, thick, realistic and space looks, riding the ISS (down and at the horizon) and the Moon, and behind the ISS and the Moon, and checks which way the ground moved by sliding the first picture over the second; and that a ride opens with the address's turn, a drag writes it back and the address brings the same picture back; and the reported address. All fail on 0.9.0. Unit tests for `ridePose` and the view's signs.
21
+
3
22
  ## 0.9.0
4
23
 
5
24
  Ride along: the camera on the ISS, a Starlink satellite, the Moon or a planet, looking at the Earth.
package/README.md CHANGED
@@ -193,7 +193,7 @@ document.getElementById("controls")!.addEventListener("kazoku-viewchange", (even
193
193
  });
194
194
  ```
195
195
 
196
- The mapping is `rotate([lambda0 + yaw, phi0 - tilt])`, `scale(baseScale * zoom)` and
196
+ The mapping is `rotate([lambda0 + yaw, phi0 + tilt])`, `scale(baseScale * zoom)` and
197
197
  `translate([cx + panX, cy + panY])`, where `lambda0` and `phi0` are the home centre. Front returns to that home
198
198
  view. Auto-turn's `0.004178` degrees a second is 360° per sidereal day; kazoku-ui leaves it still for a reader who
199
199
  prefers reduced motion, and a drag or zoom never stops or resets it.
@@ -0,0 +1 @@
1
+ export declare function adoptStyles(root: ShadowRoot, css: string, nonce?: string): void;
package/dist/adopt.js ADDED
@@ -0,0 +1,26 @@
1
+ // Puts an element's styles into its shadow root so a strict Content-Security-Policy (`style-src 'self'`) allows them: a constructable stylesheet is not inline
2
+ // markup. A browser without that gets a <style> carrying the element's `nonce` attribute, which a page can allow by nonce.
3
+ const sheets = new Map();
4
+ export function adoptStyles(root, css, nonce = "") {
5
+ if (typeof CSSStyleSheet === "function" && "replaceSync" in CSSStyleSheet.prototype && "adoptedStyleSheets" in root) {
6
+ try {
7
+ let sheet = sheets.get(css);
8
+ if (!sheet) {
9
+ sheet = new CSSStyleSheet();
10
+ sheet.replaceSync(css);
11
+ sheets.set(css, sheet);
12
+ }
13
+ if (!root.adoptedStyleSheets.includes(sheet))
14
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
15
+ return;
16
+ }
17
+ catch {
18
+ // a browser that has the API and refuses it: the <style> below
19
+ }
20
+ }
21
+ const style = root.ownerDocument.createElement("style");
22
+ if (nonce)
23
+ style.setAttribute("nonce", nonce);
24
+ style.textContent = css;
25
+ root.prepend(style);
26
+ }
package/dist/element.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // <chikyu-earth>: the globe as a web component. A shared view controller supplies its yaw, tilt, zoom and pan;
2
2
  // it opens centred on where you are (the `center` attribute wins over geolocation). Importing registers it once.
3
+ import { adoptStyles } from "./adopt.js";
3
4
  import { globe } from "./globe.js";
4
5
  import { cleanStyle } from "./styles.js";
5
6
  import { globeBaseScale, HOME_VIEW, lookAt } from "./view.js";
@@ -13,6 +14,7 @@ const readCentre = (value) => {
13
14
  return null;
14
15
  return { lon, lat };
15
16
  };
17
+ const STYLE = ":host{display:block;position:relative}.holder svg{display:block;width:100%;height:auto}.overlay{position:absolute;inset:0;pointer-events:none;transform-origin:50% 50%}";
16
18
  /**
17
19
  * The `<chikyu-earth>` custom element: the line globe, drawn as SVG in its shadow root. Importing this entry point registers the tag once. It takes the attributes `size` (pixels, 320 by default), `center` (`"lon,lat"`; wins over the browser's location), `look` (`line` or `thick`; `style` is the older name for it, and a framework that reads `style` as CSS cannot use it) and `graticule`, and a shared view controller's camera through `setView`.
18
20
  *
@@ -97,7 +99,8 @@ export class ChikyuEarth extends HTMLElement {
97
99
  #ensureShell() {
98
100
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
99
101
  if (!this.#overlay || !root.contains(this.#overlay)) {
100
- root.innerHTML = `<style>:host{display:block;position:relative}.holder svg{display:block;width:100%;height:auto}.overlay{position:absolute;inset:0;pointer-events:none;transform-origin:50% 50%}</style><div class="holder"></div><div class="overlay"></div>`;
102
+ root.innerHTML = `<div class="holder"></div><div class="overlay"></div>`;
103
+ adoptStyles(root, STYLE, this.nonce);
101
104
  this.#overlay = root.querySelector(".overlay");
102
105
  }
103
106
  return root;
@@ -1,6 +1,6 @@
1
1
  import type { GeoPoint, GlobeView } from "../types.ts";
2
- import { setThreeLoader } from "./shared.ts";
3
- export { setThreeLoader };
2
+ import { setSharedRenderer, setThreeLoader } from "./shared.ts";
3
+ export { setSharedRenderer, setThreeLoader };
4
4
  import type { OverlayHost } from "../markers/layer.ts";
5
5
  import { type Layer } from "./tiers.ts";
6
6
  type EarthLayer = Extract<Layer, "day" | "night" | "clouds" | "water">;
@@ -31,7 +31,7 @@ export type EarthState = "loading" | "live" | "unavailable" | "lost" | "idle";
31
31
  */
32
32
  export declare const readTime: (value: string | null) => number | "now";
33
33
  /**
34
- * The `<chikyu-earth-realistic>` custom element: the Earth from space, drawn with three.js through kazoku-ui's shared renderer (one WebGL context for the page). It takes `center` (`"lon,lat"`), `time` (`now` or an ISO date; the real Sun at that moment), `clouds="off"`, `lights="off"`, `live-seconds` and `texture-base` (where the pictures are served from), and a shared view controller's camera through `setView`. It draws only when something changes, at most 30 times a second, and nothing while it is out of sight or the tab is hidden.
34
+ * The `<chikyu-earth-realistic>` custom element: the Earth from space, drawn with three.js through kazoku-ui's shared renderer (one WebGL context for the page). It takes `center` (`"lon,lat"`), `time` (`now` or an ISO date; the real Sun at that moment), `clouds="off"`, `lights="off"`, `live-seconds`, `texture-base` (where the pictures are served from) and `max-ratio` (the most device pixels to a CSS pixel the canvas is drawn at, 2 at most, and `0.5` draws at half the size and scales it up: for a background; read when the element connects, and it is the shared renderer's cap for the whole page), and a shared view controller's camera through `setView`. It draws only when something changes, at most 30 times a second, and nothing while it is out of sight or the tab is hidden.
35
35
  *
36
36
  * @example
37
37
  * ```ts no-run
@@ -1,8 +1,13 @@
1
+ // <chikyu-earth-realistic>: the Earth from space as a web component, drawn by kazoku-ui's shared 3D renderer (one WebGL context for the
2
+ // page) with three.js, which is the page's own. Optional entry point: the flat `<chikyu-earth>` needs neither. It draws only when something
3
+ // changes, at most 30 times a second, and nothing at all while it is out of sight or the tab is hidden.
4
+ import { adoptStyles } from "../adopt.js";
1
5
  import { createEarthItem, lookAt, newModel } from "./earth.js";
2
6
  import { createGate, frameCap } from "./gate.js";
3
- import { setThreeLoader, takeRenderer } from "./shared.js";
4
- export { setThreeLoader };
7
+ import { setSharedRenderer, setThreeLoader, takeRenderer } from "./shared.js";
8
+ export { setSharedRenderer, setThreeLoader };
5
9
  import { MAX_TEXTURE, TIERS } from "./tiers.js";
10
+ const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}";
6
11
  const RAD = Math.PI / 180;
7
12
  /** The Sun and the clouds are re-placed this often while the time is "now": 15 degrees an hour is 0.25 degree a minute. */
8
13
  const LIVE_TICK_MS = 60_000;
@@ -15,6 +20,10 @@ const readCentre = (value) => {
15
20
  return null;
16
21
  return { lon: lon, lat: lat };
17
22
  };
23
+ const readRatio = (value) => {
24
+ const ratio = Number(value);
25
+ return value !== null && Number.isFinite(ratio) && ratio > 0 ? Math.min(ratio, 2) : undefined;
26
+ };
18
27
  /**
19
28
  * A `time` attribute: "now" (or none) follows the clock, else an ISO date such as 2026-06-21T12:00:00Z.
20
29
  *
@@ -35,7 +44,7 @@ export const readTime = (value) => {
35
44
  return Number.isFinite(ms) ? ms : "now";
36
45
  };
37
46
  /**
38
- * The `<chikyu-earth-realistic>` custom element: the Earth from space, drawn with three.js through kazoku-ui's shared renderer (one WebGL context for the page). It takes `center` (`"lon,lat"`), `time` (`now` or an ISO date; the real Sun at that moment), `clouds="off"`, `lights="off"`, `live-seconds` and `texture-base` (where the pictures are served from), and a shared view controller's camera through `setView`. It draws only when something changes, at most 30 times a second, and nothing while it is out of sight or the tab is hidden.
47
+ * The `<chikyu-earth-realistic>` custom element: the Earth from space, drawn with three.js through kazoku-ui's shared renderer (one WebGL context for the page). It takes `center` (`"lon,lat"`), `time` (`now` or an ISO date; the real Sun at that moment), `clouds="off"`, `lights="off"`, `live-seconds`, `texture-base` (where the pictures are served from) and `max-ratio` (the most device pixels to a CSS pixel the canvas is drawn at, 2 at most, and `0.5` draws at half the size and scales it up: for a background; read when the element connects, and it is the shared renderer's cap for the whole page), and a shared view controller's camera through `setView`. It draws only when something changes, at most 30 times a second, and nothing while it is out of sight or the tab is hidden.
39
48
  *
40
49
  * @example
41
50
  * ```ts no-run
@@ -80,7 +89,8 @@ export class ChikyuEarthRealistic extends HTMLElement {
80
89
  if (!this.hasAttribute("aria-label"))
81
90
  this.setAttribute("aria-label", "The Earth from space, with its sunlit and dark sides");
82
91
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
83
- root.innerHTML = `<style>:host{display:block;aspect-ratio:1/1;position:relative}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}</style><div id="stage"></div><div id="overlay"></div>`;
92
+ root.innerHTML = `<div id="stage"></div><div id="overlay"></div>`;
93
+ adoptStyles(root, STYLE, this.nonce);
84
94
  this.#stage = root.getElementById("stage");
85
95
  this.#overlay = root.getElementById("overlay");
86
96
  this.#stage.addEventListener("webglcontextlost", this.#lost, true);
@@ -92,14 +102,17 @@ export class ChikyuEarthRealistic extends HTMLElement {
92
102
  if (!battery.charging && battery.level <= 0.2)
93
103
  this.#gate?.setMinMs(1000 / Math.min(cap, 15));
94
104
  }, () => undefined);
95
- const taken = takeRenderer(this.#onContext);
105
+ const maxRatio = readRatio(this.getAttribute("max-ratio"));
106
+ if (maxRatio)
107
+ this.#model.ratio = () => Math.min(globalThis.devicePixelRatio || 1, 2, maxRatio);
108
+ const taken = takeRenderer(this.#onContext, maxRatio);
96
109
  this.#taken = taken;
97
110
  const item = createEarthItem(this.#model, {
98
111
  assets: taken.renderer.assets,
99
112
  textureBase: () => this.#textureBase(),
100
113
  cap: () => this.#textureCap(),
101
114
  drift: 1.5,
102
- invalidate: () => this.#gate?.request(),
115
+ invalidate: () => this.#gate?.soon(),
103
116
  onPose: (pose) => {
104
117
  this.#pose = { ...pose, transform: "" };
105
118
  for (const listener of this.#listeners)
@@ -169,7 +182,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
169
182
  }
170
183
  set centre(value) {
171
184
  this.#model.centre = { ...value };
172
- this.#gate?.request();
185
+ this.#gate?.soon();
173
186
  }
174
187
  /** The moment shown: milliseconds since the epoch, or "now" to follow the clock. */
175
188
  get time() {
@@ -182,21 +195,21 @@ export class ChikyuEarthRealistic extends HTMLElement {
182
195
  else
183
196
  this.#model.time = this.#mode;
184
197
  this.#startTick();
185
- this.#gate?.request();
198
+ this.#gate?.soon();
186
199
  }
187
200
  get clouds() {
188
201
  return this.#model.clouds;
189
202
  }
190
203
  set clouds(value) {
191
204
  this.#model.clouds = value;
192
- this.#gate?.request();
205
+ this.#gate?.soon();
193
206
  }
194
207
  get lights() {
195
208
  return this.#model.lights;
196
209
  }
197
210
  set lights(value) {
198
211
  this.#model.lights = value;
199
- this.#gate?.request();
212
+ this.#gate?.soon();
200
213
  }
201
214
  /** What the element is doing, for a page or a test: its state, the texture widths held, the draws made. */
202
215
  get stats() {
@@ -218,7 +231,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
218
231
  this.#model.view = { ...view };
219
232
  const drawn = this.#model.drawn;
220
233
  if (!drawn) {
221
- this.#gate?.request();
234
+ this.#gate?.soon();
222
235
  return;
223
236
  }
224
237
  const shifted = view.zoom !== drawn.view.zoom || view.panX !== drawn.view.panX || view.panY !== drawn.view.panY;
@@ -226,7 +239,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
226
239
  const b = lookAt(this.#model.centre, view);
227
240
  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;
228
241
  if (shifted || px >= 0.5 || (final && px > 0.01))
229
- this.#gate?.request();
242
+ this.#gate?.soon();
230
243
  }
231
244
  /** The view as it is (for a page that wants to read it back). */
232
245
  get view() {
@@ -244,7 +257,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
244
257
  }
245
258
  #onTick = () => {
246
259
  this.#model.time = Date.now();
247
- this.#gate?.request();
260
+ this.#gate?.soon();
248
261
  };
249
262
  #take = () => {
250
263
  if (this.#view && !this.#view.live)
@@ -19,6 +19,8 @@ export declare const browserTimers: Timers;
19
19
  export interface Gate {
20
20
  /** Ask for `fire` to run: now if the last run was `minMs` ago or more, else once, when that time has passed. */
21
21
  request(): void;
22
+ /** Like `request`, but every ask made in one task is one ask, made when the task ends: a time and a view set together are one draw. */
23
+ soon(): void;
22
24
  /** Forget a run that is waiting. */
23
25
  cancel(): void;
24
26
  /** Change the least time between runs (a lower frame rate on a battery). */
@@ -27,20 +27,31 @@ export function createGate(minMs, fire, timers = browserTimers) {
27
27
  let least = minMs;
28
28
  let last = -Infinity;
29
29
  let waiting;
30
+ let soon = false;
30
31
  const run = () => {
31
32
  waiting = undefined;
32
33
  last = timers.now();
33
34
  fire();
34
35
  };
36
+ const request = () => {
37
+ if (waiting !== undefined)
38
+ return;
39
+ const wait = last + least - timers.now();
40
+ if (wait <= 0)
41
+ run();
42
+ else
43
+ waiting = timers.set(run, wait);
44
+ };
35
45
  return {
36
- request() {
37
- if (waiting !== undefined)
46
+ request,
47
+ soon() {
48
+ if (soon)
38
49
  return;
39
- const wait = last + least - timers.now();
40
- if (wait <= 0)
41
- run();
42
- else
43
- waiting = timers.set(run, wait);
50
+ soon = true;
51
+ queueMicrotask(() => {
52
+ soon = false;
53
+ request();
54
+ });
44
55
  },
45
56
  cancel() {
46
57
  if (waiting !== undefined)
@@ -15,8 +15,22 @@ export type ContextState = "lost" | "restored" | "unavailable";
15
15
  * ```
16
16
  */
17
17
  export declare function setThreeLoader(load: () => Promise<Three>): void;
18
- /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. */
19
- export declare function takeRenderer(onContext: (state: ContextState) => void): {
18
+ /**
19
+ * Hands the elements a renderer the page made, so a page that draws other things with kazoku-ui's shared renderer keeps one WebGL context for all of them. Call it before the first element connects, or while none is in the page. The page owns the renderer: the elements never dispose it, and its own `maxRatio` and `onContext` apply. Pass `undefined` to go back to the package's own.
20
+ *
21
+ * @param renderer - A renderer made with `createSharedRenderer` from `@johnmorrisdotca/kazoku-ui/renderer`, whose `load` gives the same three.js, or `undefined`.
22
+ *
23
+ * @example
24
+ * ```ts no-run
25
+ * import { createSharedRenderer } from "@johnmorrisdotca/kazoku-ui/renderer";
26
+ * import { setSharedRenderer } from "@johnmorrisdotca/chikyu-earth/realistic/element";
27
+ *
28
+ * setSharedRenderer(createSharedRenderer({ load: () => import("three"), maxRatio: 1.5 }));
29
+ * ```
30
+ */
31
+ export declare function setSharedRenderer(renderer: SharedRenderer<Three> | undefined): void;
32
+ /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. A `maxRatio` lower than the one it was made with makes a new one if no element holds it. */
33
+ export declare function takeRenderer(onContext: (state: ContextState) => void, maxRatio?: number): {
20
34
  renderer: SharedRenderer<Three>;
21
35
  release(): void;
22
36
  };
@@ -2,6 +2,9 @@
2
2
  // WebGL context between them. The last element to leave lets it go (after a second, in case it is only moving).
3
3
  import { createSharedRenderer } from "@johnmorrisdotca/kazoku-ui/renderer";
4
4
  let shared;
5
+ // A renderer the page made and handed over: used as it is, and never disposed here.
6
+ let given;
7
+ let sharedRatio;
5
8
  let loader = () => import("three");
6
9
  const contextListeners = new Set();
7
10
  let elements = 0;
@@ -21,24 +24,55 @@ let releaseTimer;
21
24
  export function setThreeLoader(load) {
22
25
  loader = load;
23
26
  }
24
- /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. */
25
- export function takeRenderer(onContext) {
27
+ /**
28
+ * Hands the elements a renderer the page made, so a page that draws other things with kazoku-ui's shared renderer keeps one WebGL context for all of them. Call it before the first element connects, or while none is in the page. The page owns the renderer: the elements never dispose it, and its own `maxRatio` and `onContext` apply. Pass `undefined` to go back to the package's own.
29
+ *
30
+ * @param renderer - A renderer made with `createSharedRenderer` from `@johnmorrisdotca/kazoku-ui/renderer`, whose `load` gives the same three.js, or `undefined`.
31
+ *
32
+ * @example
33
+ * ```ts no-run
34
+ * import { createSharedRenderer } from "@johnmorrisdotca/kazoku-ui/renderer";
35
+ * import { setSharedRenderer } from "@johnmorrisdotca/chikyu-earth/realistic/element";
36
+ *
37
+ * setSharedRenderer(createSharedRenderer({ load: () => import("three"), maxRatio: 1.5 }));
38
+ * ```
39
+ */
40
+ export function setSharedRenderer(renderer) {
41
+ if (renderer !== given && elements > 0)
42
+ throw new Error("chikyu-earth: setSharedRenderer must be called before an element connects");
43
+ if (renderer !== given) {
44
+ clearTimeout(releaseTimer);
45
+ shared?.dispose();
46
+ shared = undefined;
47
+ }
48
+ given = renderer;
49
+ }
50
+ /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. A `maxRatio` lower than the one it was made with makes a new one if no element holds it. */
51
+ export function takeRenderer(onContext, maxRatio) {
26
52
  clearTimeout(releaseTimer);
53
+ if (!given && shared && elements <= 0 && sharedRatio !== maxRatio) {
54
+ shared.dispose();
55
+ shared = undefined;
56
+ }
27
57
  elements += 1;
28
58
  contextListeners.add(onContext);
29
- shared ??= createSharedRenderer({
30
- load: () => loader(),
31
- onContext: (state) => {
32
- for (const listener of contextListeners)
33
- listener(state);
34
- },
35
- });
59
+ if (!given && !shared) {
60
+ sharedRatio = maxRatio;
61
+ shared = createSharedRenderer({
62
+ load: () => loader(),
63
+ ...(maxRatio === undefined ? {} : { maxRatio }),
64
+ onContext: (state) => {
65
+ for (const listener of contextListeners)
66
+ listener(state);
67
+ },
68
+ });
69
+ }
36
70
  return {
37
- renderer: shared,
71
+ renderer: (given ?? shared),
38
72
  release() {
39
73
  contextListeners.delete(onContext);
40
74
  elements -= 1;
41
- if (elements <= 0) {
75
+ if (elements <= 0 && !given) {
42
76
  releaseTimer = setTimeout(() => {
43
77
  if (elements <= 0) {
44
78
  shared?.dispose();
@@ -146,7 +146,7 @@ export declare class ChikyuSpace extends HTMLElement {
146
146
  get orbits(): boolean;
147
147
  set orbits(value: boolean);
148
148
  /**
149
- * The shared controls' camera: yaw and tilt turn the view, zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. A turn that moves nothing on the screen by half a pixel is kept
149
+ * The shared controls' camera: yaw and tilt turn the view (the Earth's surface moves right for a drag right and up for a drag up), zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. A turn that moves nothing on the screen by half a pixel is kept
150
150
  * for the next draw but does not cause one unless `final` is true (the default), so an Auto-turn at the Earth's own rate costs a draw every half minute, not thirty a second.
151
151
  *
152
152
  * @param view - The controls' yaw and tilt in degrees and zoom.
@@ -162,7 +162,7 @@ export declare class ChikyuSpace extends HTMLElement {
162
162
  set body(name: BodyName);
163
163
  /**
164
164
  * Ride along with a body or a satellite. By default the camera sits at it and looks at the Earth, with the way it is going at the top of the picture, at its real place for the moment shown, so the
165
- * Earth turns and slides beneath as it moves along its orbit (an ISS view goes round about every 90 minutes). The shared controls' yaw and tilt turn the view and tip it towards the horizon, their zoom narrows it.
165
+ * Earth turns and slides beneath as it moves along its orbit (an ISS view goes round about every 90 minutes). A drag looks about from there (a drag right turns the camera to its left and a drag up tips it towards the bottom of its picture, so the ground follows the pointer), the shared controls' zoom narrows the view.
166
166
  * A satellite is `{ group, index }` of a group set with `setSatellites`; it is placed exactly, one SGP4 call a frame, at any speed. Another call switches smoothly; `null` stops. The draw rate follows how
167
167
  * fast the picture moves, never more than 30 a second (one a second for a reader who asked for reduced motion), and nothing is drawn out of sight.
168
168
  *
@@ -1,3 +1,4 @@
1
+ import { adoptStyles } from "../adopt.js";
1
2
  import { createGate, frameCap } from "../realistic/gate.js";
2
3
  import { setThreeLoader, takeRenderer } from "../realistic/shared.js";
3
4
  import { MAX_TEXTURE } from "../realistic/tiers.js";
@@ -49,6 +50,7 @@ const readTime = (value) => {
49
50
  const ms = Date.parse(value);
50
51
  return Number.isFinite(ms) ? ms : "now";
51
52
  };
53
+ 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}`;
52
54
  /**
53
55
  * 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.
54
56
  *
@@ -98,7 +100,8 @@ export class ChikyuSpace extends HTMLElement {
98
100
  if (!this.hasAttribute("aria-label"))
99
101
  this.setAttribute("aria-label", "The Earth, the Moon, the Sun and the planets in their places for the date shown");
100
102
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
101
- root.innerHTML = `<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}</style><div id="stage"></div><div id="labels" aria-hidden="true"></div>`;
103
+ root.innerHTML = `<div id="stage"></div><div id="labels" aria-hidden="true"></div>`;
104
+ adoptStyles(root, STYLE, this.nonce);
102
105
  this.#stage = root.getElementById("stage");
103
106
  this.#labelBox = root.getElementById("labels");
104
107
  this.#pool.clear();
@@ -224,7 +227,7 @@ export class ChikyuSpace extends HTMLElement {
224
227
  this.#gate?.request();
225
228
  }
226
229
  /**
227
- * The shared controls' camera: yaw and tilt turn the view, zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. A turn that moves nothing on the screen by half a pixel is kept
230
+ * The shared controls' camera: yaw and tilt turn the view (the Earth's surface moves right for a drag right and up for a drag up), zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. A turn that moves nothing on the screen by half a pixel is kept
228
231
  * for the next draw but does not cause one unless `final` is true (the default), so an Auto-turn at the Earth's own rate costs a draw every half minute, not thirty a second.
229
232
  *
230
233
  * @param view - The controls' yaw and tilt in degrees and zoom.
@@ -256,7 +259,7 @@ export class ChikyuSpace extends HTMLElement {
256
259
  // --- riding along -------------------------------------------------------------------------------------------------------------------------------
257
260
  /**
258
261
  * Ride along with a body or a satellite. By default the camera sits at it and looks at the Earth, with the way it is going at the top of the picture, at its real place for the moment shown, so the
259
- * Earth turns and slides beneath as it moves along its orbit (an ISS view goes round about every 90 minutes). The shared controls' yaw and tilt turn the view and tip it towards the horizon, their zoom narrows it.
262
+ * Earth turns and slides beneath as it moves along its orbit (an ISS view goes round about every 90 minutes). A drag looks about from there (a drag right turns the camera to its left and a drag up tips it towards the bottom of its picture, so the ground follows the pointer), the shared controls' zoom narrows the view.
260
263
  * A satellite is `{ group, index }` of a group set with `setSatellites`; it is placed exactly, one SGP4 call a frame, at any speed. Another call switches smoothly; `null` stops. The draw rate follows how
261
264
  * fast the picture moves, never more than 30 a second (one a second for a reader who asked for reduced motion), and nothing is drawn out of sight.
262
265
  *
@@ -40,9 +40,9 @@ export interface RideInput {
40
40
  /** Its direction of travel, in any unit: only the direction is used. */
41
41
  velocity: Vec3;
42
42
  look: RideLook;
43
- /** Degrees: turns the view round the straight-down line (0 has the way it is going at the top of the picture). */
43
+ /** The shared controls' yaw in degrees (a drag across the view is 180): turns the camera to look along its picture's left, so the ground moves right. 0 has the way it is going at the top of the picture. */
44
44
  yaw: number;
45
- /** Degrees: tips the view forward from where `look` puts it, towards the horizon and beyond. */
45
+ /** The shared controls' tilt in degrees (a drag down the view is 60): tips the camera to look towards the bottom of its picture, so the ground moves up. */
46
46
  tilt: number;
47
47
  /** 1 is the natural view; more narrows the field of view. */
48
48
  zoom: number;
@@ -67,7 +67,8 @@ export interface RidePose {
67
67
  }
68
68
  /**
69
69
  * The camera of a body-borne view: at `position`, looking at the Earth, with the way the body is going at the top of the picture. `look: "horizon"` tips it forward until the
70
- * horizon is a little above the middle; `tilt` tips it further, `yaw` turns it round the straight-down line, and `zoom` narrows the field of view.
70
+ * horizon is a little above the middle. A drag looks about from there, as a head on a pivot does: `yaw` turns the camera to its left and `tilt` tips it towards the bottom of its picture, so the
71
+ * ground follows the pointer (right for a drag right, up for a drag up); the angle for each pixel of the drag is the field of view's, so the pace is the same at any zoom. `zoom` narrows the field of view.
71
72
  *
72
73
  * @param input - The camera's place, its way of travel, the look, and the shared controls' yaw, tilt and zoom.
73
74
  * @returns The camera's place, forward and up directions (unit vectors), its field of view, and the Earth's angular radius from there.
@@ -1,4 +1,6 @@
1
1
  const RAD = Math.PI / 180;
2
+ /** How far the ground moves in the picture for each pixel of a drag at the middle of it: the same pace as the line globe and the Earth from space (about one and a half). */
3
+ const GRAB = 1.5;
2
4
  /**
3
5
  * The field of view, in degrees, of a camera riding along at zoom 1 (the Earth's view from outside is 35).
4
6
  *
@@ -21,7 +23,8 @@ const unit = (a) => {
21
23
  };
22
24
  /**
23
25
  * The camera of a body-borne view: at `position`, looking at the Earth, with the way the body is going at the top of the picture. `look: "horizon"` tips it forward until the
24
- * horizon is a little above the middle; `tilt` tips it further, `yaw` turns it round the straight-down line, and `zoom` narrows the field of view.
26
+ * horizon is a little above the middle. A drag looks about from there, as a head on a pivot does: `yaw` turns the camera to its left and `tilt` tips it towards the bottom of its picture, so the
27
+ * ground follows the pointer (right for a drag right, up for a drag up); the angle for each pixel of the drag is the field of view's, so the pace is the same at any zoom. `zoom` narrows the field of view.
25
28
  *
26
29
  * @param input - The camera's place, its way of travel, the look, and the shared controls' yaw, tilt and zoom.
27
30
  * @returns The camera's place, forward and up directions (unit vectors), its field of view, and the Earth's angular radius from there.
@@ -46,12 +49,15 @@ export function ridePose(input) {
46
49
  ahead = cross([1, 0, 0], nadir);
47
50
  }
48
51
  ahead = unit(ahead);
49
- const turn = input.yaw * RAD;
50
- ahead = add(scale(ahead, Math.cos(turn)), scale(cross(nadir, ahead), Math.sin(turn)));
51
52
  const earthRadiusDegrees = distance <= 1 ? 90 : Math.asin(1 / distance) / RAD;
52
- const base = input.look === "horizon" ? Math.max(0, earthRadiusDegrees - 12) : 0;
53
- const pitch = Math.min(150, Math.max(0, base + input.tilt)) * RAD;
54
- const forward = add(scale(nadir, Math.cos(pitch)), scale(ahead, Math.sin(pitch)));
55
- const up = add(scale(ahead, Math.cos(pitch)), scale(nadir, -Math.sin(pitch)));
56
- return { position: [input.position[0], input.position[1], input.position[2]], forward, up, fov: Math.min(100, Math.max(5, RIDE_FOV / Math.max(0.05, input.zoom))), earthRadiusDegrees };
53
+ const base = input.look === "horizon" ? Math.max(0, earthRadiusDegrees - 12) * RAD : 0;
54
+ const forward0 = add(scale(nadir, Math.cos(base)), scale(ahead, Math.sin(base)));
55
+ const up0 = add(scale(ahead, Math.cos(base)), scale(nadir, -Math.sin(base)));
56
+ const fov = Math.min(100, Math.max(5, RIDE_FOV / Math.max(0.05, input.zoom)));
57
+ const turn = input.yaw * (GRAB * fov / 180) * RAD;
58
+ const lift = input.tilt * (GRAB * fov / 60) * RAD;
59
+ const turned = add(scale(forward0, Math.cos(turn)), scale(cross(up0, forward0), Math.sin(turn)));
60
+ const forward = add(scale(turned, Math.cos(lift)), scale(up0, -Math.sin(lift)));
61
+ const up = add(scale(up0, Math.cos(lift)), scale(turned, Math.sin(lift)));
62
+ return { position: [input.position[0], input.position[1], input.position[2]], forward, up, fov, earthRadiusDegrees };
57
63
  }
@@ -323,8 +323,10 @@ export function createSpaceItem(model, deps) {
323
323
  }
324
324
  else {
325
325
  const spin = model.cameraSpin ?? frame.spin;
326
- const lon = model.centre.lon - model.view.yaw;
327
- const lat = Math.max(-90, Math.min(90, model.centre.lat + model.view.tilt));
326
+ // 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
327
+ const way = ride && ride.view === "follow" && typeof ride.target !== "string" ? -1 : 1;
328
+ const lon = model.centre.lon - way * model.view.yaw;
329
+ const lat = Math.max(-90, Math.min(90, model.centre.lat - way * model.view.tilt));
328
330
  const aim = direction(spin + lon, lat);
329
331
  distance = Math.max(1.05 * focusRadius, (FIT_DISTANCE * focusRadius) / Math.max(1e-9, model.view.zoom));
330
332
  target.set(focusPos[0], focusPos[1], focusPos[2]);
package/dist/view.d.ts CHANGED
@@ -41,7 +41,7 @@ export interface ProjectionView {
41
41
  */
42
42
  export declare const globeBaseScale: (size: number) => number;
43
43
  /**
44
- * Where the view is centred on the globe: the home centre, turned by yaw (west) and tipped by tilt (north), held to the poles.
44
+ * Where the view is centred on the globe: the home centre, turned by yaw (west) and tipped by tilt (south), held to the poles; a drag right is yaw and a drag up is tilt, and the ground follows the pointer.
45
45
  *
46
46
  * @param centre - The home centre.
47
47
  * @param view - The turn, tip, zoom and pan from the view controls.
package/dist/view.js CHANGED
@@ -24,7 +24,7 @@ export const HOME_VIEW = Object.freeze({ yaw: 0, tilt: 0, zoom: 1, panX: 0, panY
24
24
  */
25
25
  export const globeBaseScale = (size) => size / 2 - 1;
26
26
  /**
27
- * Where the view is centred on the globe: the home centre, turned by yaw (west) and tipped by tilt (north), held to the poles.
27
+ * Where the view is centred on the globe: the home centre, turned by yaw (west) and tipped by tilt (south), held to the poles; a drag right is yaw and a drag up is tilt, and the ground follows the pointer.
28
28
  *
29
29
  * @param centre - The home centre.
30
30
  * @param view - The turn, tip, zoom and pan from the view controls.
@@ -39,7 +39,7 @@ export const globeBaseScale = (size) => size / 2 - 1;
39
39
  */
40
40
  export const lookAt = (centre, view) => ({
41
41
  lon: centre.lon - view.yaw,
42
- lat: Math.max(-90, Math.min(90, centre.lat + view.tilt)),
42
+ lat: Math.max(-90, Math.min(90, centre.lat - view.tilt)),
43
43
  });
44
44
  /**
45
45
  * What the projection is given for a view: yaw turns longitude, tilt tips latitude, zoom scales and pan moves the disc in CSS pixels.
@@ -58,7 +58,7 @@ export const lookAt = (centre, view) => ({
58
58
  */
59
59
  export function projectionView(centre, size, view = HOME_VIEW) {
60
60
  return {
61
- rotation: [-centre.lon + view.yaw, -centre.lat - view.tilt],
61
+ rotation: [-centre.lon + view.yaw, -centre.lat + view.tilt],
62
62
  scale: globeBaseScale(size) * view.zoom,
63
63
  translate: [size / 2 + view.panX, size / 2 + view.panY],
64
64
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnmorrisdotca/chikyu-earth",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Chikyu Earth 地球 — A line-drawn globe for the web: country outlines that turn at the Earth's own rate, centred on where you are, with an optional realistic Earth from space (three.js), the Sun, Moon and planets, satellites on their orbits, and markers for any place. A web component and an SVG string.",
5
5
  "keywords": [
6
6
  "earth",