@johnmorrisdotca/chikyu-earth 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1597 +1,3 @@
1
- import { carryControls, wrapYaw } from "@johnmorrisdotca/kazoku-ui/view-controls";
2
- import { adoptStyles } from "../adopt.js";
3
- import { airFor, readAirThickness } from "../realistic/air.js";
4
- import { BODY_LABEL_ATTRIBUTES, bodyLabelText, loadMichroma, readBodyLabel } from "../realistic/body-label.js";
5
- import { createSkyHost, SKY_ATTRIBUTES, SKY_STYLE } from "../sky/host.js";
6
- import { cleanPlaces, readPlaceGroups, readPlaces } from "../markers/places.js";
7
- import { createPlaceLayer, PLACE_STYLE, placesLostNotice, readPlaceLook } from "../markers/place-layer.js";
8
- import { aimAt, findPlace, glideView } from "../markers/go-to-place.js";
9
- import { subsolarPoint } from "../realistic/sun.js";
10
- import { SHORT_NAMES } from "../satellites/names.js";
11
- import { CITY_NAMES_ATTRIBUTES, CITY_NAMES_STYLE, createCityHost } from "../cities/host.js";
12
- import { BORDER_ATTRIBUTES, readBorders } from "../borders/lines.js";
13
- import { GRID_ATTRIBUTES, readGrid } from "../grid/lines.js";
14
- import { COUNTRY_NAMES_ATTRIBUTES } from "../country-names/geometry.js";
15
- import { COUNTRY_NAMES_STYLE, createCountryHost } from "../country-names/host.js";
16
- import { createGate, frameCap } from "../realistic/gate.js";
17
- import { setThreeLoader, takeRenderer } from "../realistic/shared.js";
18
- import { NOTES_STYLE, setAirNote } from "../realistic/air-note.js";
19
- import { IMMERSIVE_STYLE, immersiveWheel } from "../realistic/immersive.js";
20
- import { readMeteorStrength } from "../meteors/strength.js";
21
- import { METEOR_NOTE_STYLE, prefersLessMotion, setMeteorNote } from "../meteors/note.js";
22
- import { MAX_TEXTURE } from "../realistic/tiers.js";
23
- import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt } from "./ephemeris.js";
24
- import { MAX_ORBIT_GROUP } from "./satellite-layer.js";
25
- import { RIDE_FACES, rideTiltLimits, rideTurnDegrees } from "./ride.js";
26
- import { placeAround, placeMoon, placeSun, RADIUS } from "./scale.js";
27
- import { BODY_NAMES, createSpaceItem, DEFAULT_EARTH_SIZE, newSpaceModel } from "./scene.js";
28
- import { createPaintState, paintedGround } from "../paint/buffer.js";
29
- export { BODY_NAMES };
30
- let painter;
31
- let satellitePainter;
32
- /**
33
- * 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
34
- * the painter only for what to draw at each place (see `BodyPainter`). Left alone, they are plain spheres in the right colours.
35
- *
36
- * @param next - The painter to use, or `undefined` for the plain one.
37
- *
38
- * @example
39
- * ```ts no-run
40
- * import { plainPainter } from "@johnmorrisdotca/chikyu-earth/space";
41
- * import { setBodyPainter } from "@johnmorrisdotca/chikyu-earth/space/element";
42
- *
43
- * setBodyPainter({ make: (three, name) => plainPainter.make(three, name) });
44
- * ```
45
- */
46
- export function setBodyPainter(next) {
47
- painter = next;
48
- }
49
- /**
50
- * Where the 3D models of large satellites come from if the page has any: the package ships none. With a painter set, a satellite followed (`ride(ref, { view: "follow" })`) that the painter has a model for is drawn as that model, in the middle
51
- * of the picture at a size that reads, pointed the way it flies, lit by the Sun; a satellite it has none for stays a dot. See `SatellitePainter`.
52
- *
53
- * @param next - The painter, or `undefined` for none.
54
- *
55
- * @example
56
- * ```ts no-run
57
- * import { setSatellitePainter } from "@johnmorrisdotca/chikyu-earth/space/element";
58
- *
59
- * setSatellitePainter({ has: (norad) => norad === 25544, make: async () => null });
60
- * ```
61
- */
62
- export function setSatellitePainter(next) {
63
- satellitePainter = next;
64
- }
65
- /** Mean radii in kilometres (IAU), for what a click tells. */
66
- const RADIUS_KM = { Sun: 695_700, Mercury: 2439.7, Venus: 6051.8, Earth: 6371, Moon: 1737.4, Mars: 3389.5, Jupiter: 69_911, Saturn: 58_232, Uranus: 25_362, Neptune: 24_622, Pluto: 1188.3 };
67
- export { setThreeLoader };
68
- const FACE_KEYS = { w: "ahead", s: "behind", a: "left", d: "right", r: "up", f: "down" };
69
- /** A `light` attribute: `lit` or `boost`, else the true sun. */
70
- const readLight = (value) => (value === "lit" || value === "boost" ? value : "sun");
71
- const RAD = Math.PI / 180;
72
- /** A `camera` attribute: `ground` or `sun`, else the camera held in the stars (the default: the Earth turns beneath it). */
73
- const readCamera = (value) => (value === "ground" || value === "sun" ? value : "space");
74
- /** A number attribute within a range, or the fallback. */
75
- const readNumber = (value, fallback, min, max) => {
76
- if (value === null || value.trim() === "")
77
- return fallback;
78
- const n = Number(value);
79
- return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback;
80
- };
81
- /** The Earth's own turn, degrees a second. */
82
- const EARTH_RATE = 360 / 86_164.0905;
83
- /** The quickest a satellite goes round, degrees a second (a low orbit: 88 minutes). */
84
- const SATELLITE_RATE = 360 / (88 * 60);
85
- const SATELLITE_COLORS = ["#ffd54f", "#7fd4ff", "#ff8fa3", "#9ef0a8"];
86
- const REAL_TIME_TICK_MS = 60_000;
87
- /** The least time between two `chikyu-timechange` events while time runs: a few a second at most, however fast the picture is drawn. */
88
- const TIME_EVENT_MS = 250;
89
- /**
90
- * Tilt to the poles. The zoom is the camera's distance: a millionth of Fit takes in the whole solar system (the views of the planets and their distances need that much), and 2.5 times is as close as the Earth's 4096 pixel picture and the body textures stay sharp.
91
- * Riding at a body looking at the Earth, the zoom only narrows the camera's field a little either way: 0.5 to 6.
92
- */
93
- const LIMITS = { tiltMax: 90, zoomMin: 0.000001, zoomMax: 2.5 };
94
- const RIDE_ZOOM = { "zoom-min": "0.5", "zoom-max": "6" };
95
- const readCentre = (value) => {
96
- if (!value)
97
- return null;
98
- const [lon, lat] = value.split(",").map((part) => Number(part.trim()));
99
- if (!Number.isFinite(lon) || !Number.isFinite(lat) || Math.abs(lon) > 180 || Math.abs(lat) > 90)
100
- return null;
101
- return { lon: lon, lat: lat };
102
- };
103
- const readTime = (value) => {
104
- if (value === null || value === "" || value === "now")
105
- return "now";
106
- const ms = Date.parse(value);
107
- return Number.isFinite(ms) ? ms : "now";
108
- };
109
- const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden;isolation:isolate}${IMMERSIVE_STYLE}#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}${PLACE_STYLE}${SKY_STYLE}${COUNTRY_NAMES_STYLE}${CITY_NAMES_STYLE}${METEOR_NOTE_STYLE}${NOTES_STYLE}`;
110
- /**
111
- * 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.
112
- *
113
- * It carries kazoku-ui's controls itself: a drag turns the view, two fingers pinch, Ctrl and the wheel zoom (a plain wheel at Fit scrolls the page) and the arrow keys, + and - work once it is focused. The zoom runs from a millionth of Fit (the whole solar system) to 2.5 times, and from 0.5 to 6 times while riding from a body. `controls="none"` turns the hands off; `zoom-min` and `zoom-max` change the range. A `<kazoku-view-controls for="...">` on the element takes the hands over, and the page applies its events with `setView`. `immersive` is the full-screen mode: any shape of box, a plain wheel zooms and a drag anywhere turns.
114
- *
115
- * With a body painter that carries a `credit` (`setBodyPainter`), the credit of its pictures is written under the picture while it draws the bodies; `bodies-credit="off"` takes the line away.
116
- *
117
- * While time runs (`speed` is not 0) it sends `chikyu-timechange` with `detail: { time, running: true }`, `time` being the moment shown in milliseconds since 1970, at most four times a second however fast the picture is
118
- * drawn (and, with the clock at real time, as often as it steps: once a minute, or once a second with satellites or a ride on show), only while the tab is shown, and once with `running: false` when the clock holds
119
- * (`speed` set to 0): a page writes the date into its date box from it. It is not sent for a `time` the page sets itself. `chikyu-time` is the older event of every step the clock takes (up to thirty a second):
120
- * it is kept for pages that use it, but a page that shows the date wants `chikyu-timechange`.
121
- *
122
- * `borders` draws the borders on the Earth's land as thin lines that turn with it, as on `<chikyu-earth-realistic>`: `countries`, `regions` (from the page's `borderData.regions`, once the Earth is
123
- * large enough), or both with a bare attribute; `chikyu-borders-unavailable` is sent when the shapes cannot be loaded.
124
- *
125
- * `grid` draws the meridians and parallels on the Earth, and `country-names` names its countries, as on `<chikyu-earth-realistic>`: the names keep clear of the bodies', the places' and the
126
- * cities' names and stay on the Earth's disc; `chikyu-country-names-unavailable` is sent when the outlines cannot be loaded.
127
- *
128
- * @example
129
- * ```ts no-run
130
- * import type { ChikyuSpace } from "@johnmorrisdotca/chikyu-earth/space/element";
131
- *
132
- * const space = document.createElement("chikyu-space") as ChikyuSpace;
133
- * space.setAttribute("time", "2026-11-02T12:00Z");
134
- * space.setAttribute("speed", "86400");
135
- * space.placeGroups = false; // place-groups="off": every place keeps its own ring
136
- * space.paint = { id: "25544", length: "1w", swath: "coverage" };
137
- * space.clearPaint();
138
- * space.addEventListener("chikyu-timechange", (event) => {
139
- * const { time, running } = (event as CustomEvent<{ time: number; running: boolean }>).detail;
140
- * console.log(new Date(time).toISOString(), running ? "running" : "held");
141
- * });
142
- * document.body.append(space);
143
- * ```
144
- */
145
- export class ChikyuSpace extends HTMLElement {
146
- static observedAttributes = ["cloud-drift", "camera", "earth-size", "earth-x", "earth-y", "center", "time", "speed", "scale", "labels", "orbits", "bodies", "light", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, ...CITY_NAMES_ATTRIBUTES, ...BORDER_ATTRIBUTES, ...GRID_ATTRIBUTES, ...COUNTRY_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look", "place-groups", "bodies-credit", "satellite-tint"];
147
- #model = newSpaceModel();
148
- #paint = createPaintState();
149
- #mode = "now";
150
- #speed = 1;
151
- #view;
152
- /** 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. */
153
- #played = false;
154
- #note;
155
- /** The names of the stars and the constellation lines (`star-names`, `constellation-lines`), and the look of the names. */
156
- #sky;
157
- #skyStyle = {};
158
- #keepClear = [];
159
- /** The names of cities on the Earth (`city-names`), and the look of the names. */
160
- #cities;
161
- #citiesStyle = {};
162
- /** The names of the countries on the Earth (`country-names`), and the look of the names. */
163
- #countries;
164
- #countriesStyle = {};
165
- #satNames = {};
166
- /** A ringed satellite's name, by `group:index`, for `#satLabelLang`. The name does not depend on the moment, so a frame reads it and does not propagate the orbit again. */
167
- #satLabelCache = new Map();
168
- /** `en` or `ja` once that language has been read for the cached names; empty until the first read. */
169
- #satLabelLang = "";
170
- /** The ringed satellites of the last draw (`labelSatellites`), laid out with the places. */
171
- #marks = [];
172
- #airNote;
173
- #bodiesNote;
174
- #gate;
175
- #taken;
176
- #stage;
177
- #labelBox;
178
- #state = "loading";
179
- #timer;
180
- #last = 0;
181
- #announced = -Infinity;
182
- #pool = new Map();
183
- #places;
184
- #chosenLabel;
185
- #focusBeforeRide = "Earth";
186
- #lostTold = false;
187
- #names = {};
188
- #hint = "choose to look at it";
189
- #tiers = {};
190
- #hands;
191
- #ridden = {};
192
- #toldFacing = null;
193
- #placeLayer;
194
- /** Whether the page has been told that places in sight were left undrawn. */
195
- #placesLost = { told: false };
196
- #placeList = [];
197
- /** Counts the turns to a place, so a new one stops the one before. */
198
- #placeGlide = 0;
199
- #nameBoxes = new Map();
200
- /** A font that arrives after the names were measured: the boxes are read again on the next layout. The satellites' marks are not touched, or the page would be told again about each one already in view. */
201
- #onFonts = () => {
202
- this.#nameBoxes.clear();
203
- };
204
- /** The controller behind the element's own hands (`set`, `fit`, `state`), while it is in a page. */
205
- get controller() {
206
- return this.#hands?.controller;
207
- }
208
- connectedCallback() {
209
- document.fonts?.addEventListener?.("loadingdone", this.#onFonts);
210
- this.#model.centre = readCentre(this.getAttribute("center")) ?? this.#model.centre;
211
- this.#mode = readTime(this.getAttribute("time"));
212
- this.#model.time = this.#mode === "now" ? Date.now() : this.#mode;
213
- this.#speed = this.#readSpeed();
214
- this.#model.mode = this.getAttribute("scale") === "true" ? "true" : "compressed";
215
- this.#model.labels = this.getAttribute("labels") !== "off";
216
- this.#model.orbits = this.getAttribute("orbits") !== "off";
217
- this.#model.bodies = this.getAttribute("bodies") ?? "";
218
- this.#model.light = readLight(this.getAttribute("light"));
219
- this.#model.camera = readCamera(this.getAttribute("camera"));
220
- this.#model.cloudDrift = Number.isFinite(Number(this.getAttribute("cloud-drift") ?? "0")) ? Number(this.getAttribute("cloud-drift") ?? "0") : 0;
221
- 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) };
222
- this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
223
- this.#model.speed = this.#speed;
224
- if (!this.hasAttribute("role"))
225
- this.setAttribute("role", "img");
226
- if (!this.hasAttribute("aria-label"))
227
- this.setAttribute("aria-label", "The Earth, the Moon, the Sun and the planets in their places for the date shown");
228
- const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
229
- root.innerHTML = `<div id="stage"></div><div id="places"></div><div id="labels" aria-hidden="true"></div><div id="notes"><p id="air-note" hidden></p><p id="meteor-note" hidden></p><p id="bodies-note" hidden></p></div>`;
230
- adoptStyles(root, STYLE, this.nonce);
231
- this.#stage = root.getElementById("stage");
232
- this.#labelBox = root.getElementById("labels");
233
- this.#note = root.getElementById("meteor-note");
234
- this.#airNote = root.getElementById("air-note");
235
- this.#bodiesNote = root.getElementById("bodies-note");
236
- this.#sky = createSkyHost({
237
- root,
238
- attribute: (name) => this.getAttribute(name),
239
- language: () => ((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en"),
240
- onError: (error) => this.dispatchEvent(new CustomEvent("chikyu-sky-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
241
- loadFont: loadMichroma,
242
- });
243
- this.#sky.setStyle(this.#skyStyle);
244
- this.#sky.setKeepClear(this.#keepClear);
245
- this.#placeLayer = createPlaceLayer(root.getElementById("places"));
246
- this.#placeList = readPlaces(this.getAttribute("places"));
247
- this.#placeLayer.set(this.#placeList);
248
- this.#placeLayer.look = readPlaceLook(this.getAttribute("places-look"));
249
- this.#placeLayer.grouping = readPlaceGroups(this.getAttribute("place-groups"));
250
- this.#cities = createCityHost({
251
- root,
252
- attribute: (name) => this.getAttribute(name),
253
- language: () => ((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en"),
254
- onError: (error) => this.dispatchEvent(new CustomEvent("chikyu-city-names-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
255
- onLayout: () => this.#countryFrame(),
256
- });
257
- this.#cities.setStyle(this.#citiesStyle);
258
- Object.assign(this.#model.borders, readBorders(this.getAttribute("borders")));
259
- this.#model.borders.onError = (error) => this.dispatchEvent(new CustomEvent("chikyu-borders-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } }));
260
- this.#model.grid.on = readGrid(this.getAttribute("grid"));
261
- this.#model.grid.onError = (error) => this.dispatchEvent(new CustomEvent("chikyu-grid-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } }));
262
- this.#countries = createCountryHost({
263
- root,
264
- attribute: (name) => this.getAttribute(name),
265
- language: () => ((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en"),
266
- onError: (error) => this.dispatchEvent(new CustomEvent("chikyu-country-names-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
267
- });
268
- this.#countries.setStyle(this.#countriesStyle);
269
- this.#model.airThickness = readAirThickness(this.getAttribute("air-thickness"));
270
- this.#applyBodyLabel();
271
- setAirNote(this.#airNote, this, this.#model.airThickness);
272
- this.#showBodiesCredit();
273
- this.#played = false;
274
- this.#model.meteors.on = this.#meteorsAsked();
275
- this.#model.meteors.strength = readMeteorStrength(this.getAttribute("meteors-strength"));
276
- this.#model.meteors.running = () => this.#speed !== 0 && document.visibilityState !== "hidden" && (this.#played || !prefersLessMotion());
277
- this.#model.meteors.onShower = (shower, zhr) => this.dispatchEvent(new CustomEvent("chikyu-meteors", { detail: { shower, zhr } }));
278
- setMeteorNote(this.#note, this, this.#model.meteors.on);
279
- this.#pool.clear();
280
- const nav = navigator;
281
- this.#gate = createGate(1000 / frameCap(30, { deviceMemory: nav.deviceMemory, hardwareConcurrency: nav.hardwareConcurrency }), () => this.#view?.invalidate());
282
- this.#stage.addEventListener("webglcontextlost", this.#lost, true);
283
- this.#stage.addEventListener("webglcontextrestored", this.#restored, true);
284
- const taken = takeRenderer((state) => {
285
- if (state === "unavailable")
286
- this.#fail("WebGL is not available");
287
- });
288
- this.#taken = taken;
289
- const item = createSpaceItem(this.#model, {
290
- assets: taken.renderer.assets,
291
- textureBase: () => this.#textureBase(),
292
- cap: () => this.#textureCap(),
293
- air: () => airFor(this.getAttribute("air")),
294
- invalidate: () => this.#gate?.request(),
295
- onError: (error) => this.#fail(error instanceof Error ? error.message : String(error)),
296
- onTier: (layer, width) => {
297
- this.#tiers[layer] = width;
298
- },
299
- onLabels: (places) => this.#placeLabels(places),
300
- onSky: (sky) => this.#sky?.frame(sky),
301
- onPlaces: (view) => this.#drawPlaces(view),
302
- placeSprites: () => this.#placeLayer?.sprites ?? null,
303
- onCities: (frame) => this.#nameFrame(frame),
304
- onLabelError: (error) => this.dispatchEvent(new CustomEvent("chikyu-body-label-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
305
- onSatelliteMarks: (marks) => this.#showMarks(marks),
306
- onSelected: (place) => this.#placeChosen(place),
307
- onMoving: () => this.#gate?.request(),
308
- onRideLost: () => this.#rideLost(),
309
- onPlaceRings: (drawn) => this.#ringsDrawn(drawn),
310
- onSatellitesError: (error) => this.dispatchEvent(new CustomEvent("chikyu-satellites-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
311
- paint: {
312
- data: this.#paint.data,
313
- width: this.#paint.width,
314
- height: this.#paint.height,
315
- step: (ms) => this.#paint.step(ms, (at) => paintedGround(this.#model.satellites.groups, this.#paint.id, at)),
316
- span: () => this.#paint.spanMinutes,
317
- on: () => this.#paint.on,
318
- },
319
- ...(painter ? { painter } : {}),
320
- satellitePainter: () => satellitePainter,
321
- onPainterError: (error) => this.dispatchEvent(new CustomEvent("chikyu-bodies-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
322
- });
323
- this.#view = taken.renderer.view(this.#stage, item, { still: null });
324
- this.#set("loading");
325
- void this.#view.focus().then((live) => {
326
- if (live) {
327
- this.#set("live");
328
- this.dispatchEvent(new CustomEvent("chikyu-ready"));
329
- }
330
- else if (this.#state === "loading")
331
- this.#set("unavailable");
332
- });
333
- this.#last = performance.now();
334
- this.#schedule();
335
- this.addEventListener("pointerdown", this.#down);
336
- // before the shared hands (which hear it after this): a plain wheel in an immersive view zooms
337
- this.addEventListener("wheel", this.#wheel, { capture: true, passive: false });
338
- this.addEventListener("keydown", this.#faceKey);
339
- if (!this.hasAttribute("tabindex"))
340
- this.tabIndex = 0;
341
- this.#hands = carryControls(this, { initial: this.#model.view, limits: LIMITS, onChange: (state, info) => this.setView(state, info.final) });
342
- this.#labelBox.addEventListener("click", this.#labelClick);
343
- this.#labelBox.addEventListener("focusin", this.#labelFocus);
344
- }
345
- disconnectedCallback() {
346
- document.fonts?.removeEventListener?.("loadingdone", this.#onFonts);
347
- this.#marks = [];
348
- this.#markSeen.clear();
349
- this.#nameBoxes.clear();
350
- this.#hands?.unbind();
351
- this.#hands = undefined;
352
- this.#zoomRange(false);
353
- this.removeEventListener("pointerdown", this.#down);
354
- this.removeEventListener("wheel", this.#wheel, { capture: true });
355
- this.removeEventListener("keydown", this.#faceKey);
356
- window.removeEventListener("pointerup", this.#up, true);
357
- clearTimeout(this.#timer);
358
- this.#timer = undefined;
359
- this.#gate?.cancel();
360
- this.#view?.dispose();
361
- this.#view = undefined;
362
- this.#taken?.release();
363
- this.#taken = undefined;
364
- this.#sky?.dispose();
365
- this.#sky = undefined;
366
- this.#placeLayer?.dispose();
367
- this.#placeLayer = undefined;
368
- this.#cities?.dispose();
369
- this.#countries?.dispose();
370
- this.#countries = undefined;
371
- this.#cities = undefined;
372
- }
373
- attributeChangedCallback(name, _old, value) {
374
- if (name === "center")
375
- this.centre = readCentre(value) ?? { lon: 0, lat: 0 };
376
- else if (name === "time")
377
- this.time = readTime(value);
378
- else if (name === "speed")
379
- this.speed = this.#readSpeed();
380
- else if (name === "scale")
381
- this.scale = value === "true" ? "true" : "compressed";
382
- else if (name === "labels")
383
- this.labels = value !== "off";
384
- else if (name === "orbits")
385
- this.orbits = value !== "off";
386
- else if (name === "bodies")
387
- this.bodies = value ?? "";
388
- else if (name === "light")
389
- this.light = readLight(value);
390
- else if (name === "camera")
391
- this.camera = readCamera(value);
392
- else if (name === "cloud-drift") {
393
- this.#model.cloudDrift = Number.isFinite(Number(value ?? "0")) ? Number(value ?? "0") : 0;
394
- this.#gate?.request();
395
- }
396
- else if (name === "earth-size")
397
- this.earthSize = readNumber(value, DEFAULT_EARTH_SIZE, 0.02, 50);
398
- else if (name === "earth-x")
399
- this.earthX = readNumber(value, 0.5, -2, 3);
400
- else if (name === "earth-y")
401
- this.earthY = readNumber(value, 0.5, -2, 3);
402
- else if (name === "meteors")
403
- this.meteors = this.#meteorsAsked();
404
- else if (name === "meteors-strength") {
405
- this.#model.meteors.strength = readMeteorStrength(value);
406
- this.#gate?.request();
407
- }
408
- else if (name === "air-thickness") {
409
- this.#model.airThickness = readAirThickness(value);
410
- this.#gate?.request();
411
- }
412
- else if (name === "meteors-label" || name === "lang") {
413
- setMeteorNote(this.#note, this, this.#model.meteors.on);
414
- if (name === "lang") {
415
- this.#applyBodyLabel();
416
- this.#sky?.refresh();
417
- this.#cities?.refresh();
418
- this.#countries?.refresh();
419
- }
420
- }
421
- else if (BODY_LABEL_ATTRIBUTES.includes(name))
422
- this.#applyBodyLabel();
423
- else if (SKY_ATTRIBUTES.includes(name))
424
- this.#sky?.refresh();
425
- else if (name === "places") {
426
- this.#placeList = readPlaces(value);
427
- this.#placeLayer?.set(this.#placeList);
428
- this.#gate?.request();
429
- }
430
- else if (name === "places-look" && this.#placeLayer) {
431
- this.#placeLayer.look = readPlaceLook(value);
432
- this.#gate?.request();
433
- }
434
- else if (name === "place-groups" && this.#placeLayer) {
435
- this.#placeLayer.grouping = readPlaceGroups(value);
436
- this.#gate?.request();
437
- }
438
- else if (CITY_NAMES_ATTRIBUTES.includes(name))
439
- this.#cities?.refresh();
440
- else if (name === "borders") {
441
- Object.assign(this.#model.borders, readBorders(value));
442
- this.#gate?.request();
443
- }
444
- else if (name === "grid") {
445
- this.#model.grid.on = readGrid(value);
446
- this.#gate?.request();
447
- }
448
- else if (COUNTRY_NAMES_ATTRIBUTES.includes(name))
449
- this.#countries?.refresh();
450
- else if (name === "satellite-tint") {
451
- this.#model.satellites.orbitTint = value === "orbit";
452
- this.#gate?.request();
453
- }
454
- if (name === "air-thickness" || name === "air-label" || name === "lang")
455
- setAirNote(this.#airNote, this, this.#model.airThickness);
456
- if (name === "bodies-credit" || name === "lang")
457
- this.#showBodiesCredit();
458
- }
459
- #wheel = (event) => immersiveWheel(this, event);
460
- /** The body painter's credit under the picture, in the element's or the page's language: shown while the painter draws the bodies (not `plain`), unless `bodies-credit` is `off`. */
461
- #showBodiesCredit() {
462
- const note = this.#bodiesNote;
463
- if (!note)
464
- return;
465
- const lang = (this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en";
466
- const credit = painter?.credit?.[lang] ?? "";
467
- note.textContent = credit;
468
- note.lang = lang;
469
- note.hidden = credit === "" || this.bodies === "plain" || this.getAttribute("bodies-credit") === "off";
470
- }
471
- /**
472
- * True for the full-screen mode (the `immersive` attribute): the element fills its box in any shape (the Earth fits the shorter side with its glow inside it, `earth-size`), a plain wheel zooms instead of scrolling
473
- * the page, a drag anywhere on it turns the view, and a touch drag turns it instead of scrolling. A notch of the wheel is about 1.2 times; out far enough the Moon, the Sun and the planets come into view.
474
- */
475
- get immersive() {
476
- return this.hasAttribute("immersive");
477
- }
478
- set immersive(value) {
479
- this.toggleAttribute("immersive", value);
480
- }
481
- #meteorsAsked() {
482
- return this.hasAttribute("meteors") && this.getAttribute("meteors") !== "off";
483
- }
484
- /**
485
- * 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
486
- * 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
487
- * (`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.
488
- * `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.
489
- */
490
- get meteors() {
491
- return this.#model.meteors.on;
492
- }
493
- set meteors(value) {
494
- if (value !== this.#meteorsAsked()) {
495
- if (value)
496
- this.setAttribute("meteors", "");
497
- else
498
- this.removeAttribute("meteors");
499
- return;
500
- }
501
- this.#model.meteors.on = value;
502
- setMeteorNote(this.#note, this, value);
503
- this.#gate?.request();
504
- }
505
- /**
506
- * How strongly the meteors are drawn, from 0 to 1 (the attribute `meteors-strength`; 1, the full look, when the page says nothing): it scales how bright each streak is and how many are drawn, so 0.3 is
507
- * fewer and fainter and 0 draws none. It changes nothing that is real: the rates, the showers and `chikyu-meteors` are the same at every strength, and the line under the picture still says the streaks are an illustration.
508
- * A number outside the range is brought to its nearest end; setting the property writes the attribute.
509
- */
510
- get meteorsStrength() {
511
- return this.#model.meteors.strength;
512
- }
513
- set meteorsStrength(value) {
514
- this.setAttribute("meteors-strength", String(value));
515
- }
516
- /**
517
- * The name written on the Earth, as the family's body label: `EARTH` (`地球` on a Japanese page) laid on the globe so it turns with it, the surface showing through the letters. Off (`null`) unless the page sets it. The plain attributes are the family's:
518
- * `body-label` (`painted`, `etched`, `outline` or `burned`; absent, no label), `body-label-strength` (0 to 1, 0.5), `body-label-repeat` (`once`, `both` or `around`), `body-label-latitude` (degrees), `body-label-facing` (present: always facing the reader),
519
- * `body-label-font` (a CSS font family the page has loaded; Michroma, fetched once, when left out) and `body-label-fallback-font` (for letters the font has none of, such as Japanese). The property is the same options as an object, or `null`; setting it writes the attributes.
520
- * Nothing of it is fetched or made until it is first set, it is not drawn while the Earth is under 24 pixels in radius, and nothing is drawn at rest. A three.js handed over with `setThreeLoader` must include `CanvasTexture`, `SphereGeometry`, `MeshLambertMaterial`, `SRGBColorSpace`, `NormalBlending`
521
- * and `AdditiveBlending`; without them `chikyu-body-label-unavailable` is sent and the name is not drawn.
522
- */
523
- get bodyLabel() {
524
- return readBodyLabel((name) => this.getAttribute(name));
525
- }
526
- set bodyLabel(value) {
527
- for (const name of BODY_LABEL_ATTRIBUTES)
528
- this.removeAttribute(name);
529
- if (value === null)
530
- return;
531
- this.setAttribute("body-label", value.look ?? "painted");
532
- if (value.strength !== undefined)
533
- this.setAttribute("body-label-strength", String(value.strength));
534
- if (value.repeat !== undefined)
535
- this.setAttribute("body-label-repeat", value.repeat);
536
- if (value.latitude !== undefined)
537
- this.setAttribute("body-label-latitude", String(value.latitude));
538
- if (value.facing)
539
- this.setAttribute("body-label-facing", "");
540
- if (value.font)
541
- this.setAttribute("body-label-font", value.font);
542
- if (value.fallbackFont)
543
- this.setAttribute("body-label-fallback-font", value.fallbackFont);
544
- }
545
- /**
546
- * The names of the brightest stars and the constellations as faint lines, laid over the sky the page draws (hoshi-stars' `sky-labels`, an optional peer loaded only when one of these is set). The plain attributes are hoshi's: `star-names` (a count of the brightest stars in view and not covered by the
547
- * Earth, the Moon or the Sun; bare is 10), `star-names-magnitude` (only stars at least that bright) and `constellation-lines` (the 88 figures as lines at this strength, 0 to 1; bare is 0.16): none of them, and nothing is loaded. The figure under the pointer or touched is at full strength and shows its name. Names are in the
548
- * page's language and never overlap. Nothing is redrawn at rest. `chikyu-sky-unavailable` is sent when hoshi-stars is not there. The property is the look of the names, a partial `SkyLabelStyle` (font, size, case, ring, leader and the rest).
549
- */
550
- get skyStyle() {
551
- return { ...this.#skyStyle };
552
- }
553
- set skyStyle(value) {
554
- this.#skyStyle = { ...value };
555
- this.#sky?.setStyle(this.#skyStyle);
556
- }
557
- /**
558
- * The constellation that is picked, by its IAU abbreviation (`Ori`), or `null`. A reader picks one by a click or a tap on its lines or inside its figure (and with the key `C`, or `Shift`+`C` for the previous, while the element has the focus); a click on empty sky, or `Escape`, lets it go. The picked figure's lines are lit and its name is
559
- * shown at the middle of the part of it in view, until another is picked or it is let go. A page sets the property to pick one itself, which sends no event. `chikyu-constellation-pick` is sent at each pick of the reader's, with `detail` `{ abbreviation, id, name, english, japanese, kind, culture }` (`culture` is `iau` unless `constellation-culture` names another), and `null` when it is let go; `chikyu-constellation-hover` is sent the same way as a mouse rests on a figure and leaves it.
560
- * Needs `constellation-lines` set. `constellation-culture` (`iau` by default, `western`, `japanese` or `chinese`; each is fetched only when asked for, and the value is exactly what the page sets) makes the figures, the pick and the names those of that sky culture. The attribute `constellation-names` (off by default) writes the name of every figure in view at the middle of the part of it that is on the picture, quieter than the star names and clear of them, of the Earth, the Moon, the Sun, the places and satellites named, and of the places kept clear (`keepClear`).
561
- */
562
- get constellation() {
563
- return this.#sky?.picked ?? null;
564
- }
565
- set constellation(value) {
566
- this.#sky?.pick(value);
567
- }
568
- /**
569
- * Places on the picture where the sky's names must not go: a page's own text laid over the element, say. Each is a rectangle in the element's own CSS pixels from its top left (`{ x, y, width, height }`), or an element of the page whose box is read. A star name whose box touches
570
- * one is left out, and so is a star whose point is in one (the next star is named instead); the picked constellation's name is moved clear of it. The lines are still drawn. The boxes are read when the list changes, when the page or an element is resized or scrolled, and not at each frame: a
571
- * page that moves its text without resizing it sets the property again. The attribute `keep-clear` takes a CSS selector for the same (`keep-clear=".hero h1, .hero .lead"`). Nothing is redrawn at rest.
572
- */
573
- get keepClear() {
574
- return [...this.#keepClear];
575
- }
576
- set keepClear(value) {
577
- this.#keepClear = value ? [...value] : [];
578
- this.#sky?.setKeepClear(this.#keepClear);
579
- }
580
- /**
581
- * Places marked on the Earth (the attribute `places`, a JSON array): each `{ id, lon, lat, label, kind, color }`, `kind` being `here` (where the reader is: drawn bright and taller, with a quiet pulse) or `favourite`
582
- * (the default: quieter), and `color` an optional CSS colour of its own. The first `PLACE_MARKS` in sight (`here` first, then in the order given) stand up out of the ground with their names; every other place
583
- * is a ring on the ground, all of them one draw call, and places that crowd are gathered into one ring with their count. They turn with the Earth, are hidden on its far side, are dimmer on its night side
584
- * and keep their size in pixels at any zoom. Names never overlap one another or the bodies' names; one with no room is left out. The element stores nothing and sends nothing: the page hands the places
585
- * over and keeps them where it likes. Setting the property writes the attribute; at most `MAX_PLACES` are drawn. Nothing is drawn again at rest: the pulse is the page's own animation, stopped out of sight
586
- * and for a reader who asked for less motion.
587
- */
588
- get places() {
589
- return this.#placeList.map((place) => ({ ...place }));
590
- }
591
- set places(value) {
592
- const clean = cleanPlaces(value);
593
- if (clean.length === 0)
594
- this.removeAttribute("places");
595
- else
596
- this.setAttribute("places", JSON.stringify(clean));
597
- }
598
- /**
599
- * Turn the view so a place of `places` is in the middle, at a pace a reader can follow (at once with `smooth: false`, for a reader who asked for less motion, or before the picture is live); the zoom stays.
600
- * The place is named by its `id`, or by its label in any case. The camera must be looking at the Earth: while it rides along or looks at another body nothing moves. The tilt is held to 90 degrees either
601
- * way, so a place more than 90 degrees of latitude from `center` comes as near the middle as that allows.
602
- *
603
- * @param text - The place's id or label.
604
- * @param options - `smooth` (true by default).
605
- * @returns The place, once the turn has started; `undefined` when there is no such place or the camera is not looking at the Earth.
606
- */
607
- async goToPlace(text, options = {}) {
608
- const place = findPlace(this.#placeList, text);
609
- const base = this.#model.lookBase;
610
- if (!place || !base || this.#model.ride)
611
- return undefined;
612
- const controls = this.#controls();
613
- const from = { yaw: this.#model.view.yaw, tilt: this.#model.view.tilt };
614
- const to = aimAt(base, place, from);
615
- const glide = (this.#placeGlide += 1);
616
- const set = (yaw, tilt, final) => {
617
- if (controls)
618
- controls.set({ yaw, tilt, zoom: this.#model.view.zoom }, final, "place");
619
- else
620
- this.setView({ yaw, tilt, zoom: this.#model.view.zoom }, final);
621
- };
622
- glideView(set, from, to, options.smooth !== false && !prefersLessMotion() && this.#view?.live === true, () => glide === this.#placeGlide && this.isConnected);
623
- return { ...place };
624
- }
625
- /**
626
- * Whether places that crowd are gathered into one ring with their count (the attribute `place-groups`): on by default, `off` leaves every place its own ring. Setting the property writes the attribute.
627
- *
628
- * @example
629
- * ```ts no-run
630
- * import type { ChikyuSpace } from "@johnmorrisdotca/chikyu-earth/space/element";
631
- *
632
- * const space = document.querySelector("chikyu-space") as ChikyuSpace;
633
- * space.placeGroups = false;
634
- * space.getAttribute("place-groups"); // "off"
635
- * space.placeGroups = true;
636
- * space.hasAttribute("place-groups"); // false
637
- * ```
638
- */
639
- get placeGroups() {
640
- return this.#placeLayer?.grouping ?? readPlaceGroups(this.getAttribute("place-groups"));
641
- }
642
- set placeGroups(value) {
643
- if (value)
644
- this.removeAttribute("place-groups");
645
- else
646
- this.setAttribute("place-groups", "off");
647
- }
648
- /** The picture said whether it can draw the rings of the places that are not markers of their own. Without `Points` the places' layer draws them itself. */
649
- #ringsDrawn(drawn) {
650
- if (!this.#placeLayer || this.#placeLayer.ringsInPicture === drawn)
651
- return;
652
- this.#placeLayer.ringsInPicture = drawn;
653
- this.#gate?.request();
654
- }
655
- /** Tell the page once when places in sight had no room among the fallback circles. Missing `Points` alone leaves them drawn, so it says nothing. */
656
- #notePlacesLost() {
657
- const notice = placesLostNotice(this.#placesLost, this.#placeLayer?.stats.omitted ?? 0);
658
- if (!notice)
659
- return;
660
- this.dispatchEvent(new CustomEvent("chikyu-places-unavailable", { detail: notice }));
661
- }
662
- /** How the places are drawn (the attribute `places-look`): `beam` (a light rising out of the ground with a ring at its foot, the default), `pin` (a thin stick with a round head) or `ring` (only the ring on the ground). */
663
- get placesLook() {
664
- return this.#placeLayer?.look ?? readPlaceLook(this.getAttribute("places-look"));
665
- }
666
- set placesLook(value) {
667
- this.setAttribute("places-look", value);
668
- }
669
- /** Lays the places on the picture just drawn, clear of the bodies' names shown beside it. */
670
- #drawPlaces(view) {
671
- const layer = this.#placeLayer;
672
- if (!layer || (this.#placeList.length === 0 && this.#marks.length === 0 && layer.stats.shown === 0 && layer.stats.rings === 0))
673
- return;
674
- layer.frame(view, this.#bodyNameBoxes(), this.#marks, this.#model.light === "lit" ? null : subsolarPoint(this.#model.time));
675
- this.#notePlacesLost();
676
- }
677
- /** Tells the names of cities, then of countries, where the Earth is in the picture just drawn; the countries' names keep clear of the bodies', the places' and the cities'. */
678
- #nameFrame(frame) {
679
- this.#cities?.frame(frame);
680
- this.#lastNameFrame = frame;
681
- this.#countryFrame();
682
- }
683
- /** The frame the names were last laid out on. */
684
- #lastNameFrame = null;
685
- /** Lays the countries' names out on the last frame, clear of the bodies', the places' and the cities' names as they are now. */
686
- #countryFrame() {
687
- const countries = this.#countries;
688
- if (!countries)
689
- return;
690
- const frame = this.#lastNameFrame;
691
- countries.frame(frame, countries.stats.on && frame ? [...this.#bodyNameBoxes(), ...(this.#placeLayer?.boxes ?? []), ...(this.#cities?.boxes ?? [])] : []);
692
- }
693
- /** The boxes the bodies' names take beside them in the picture just drawn. */
694
- #bodyNameBoxes() {
695
- const taken = [];
696
- if (this.#model.labels && this.#places) {
697
- for (const name of BODY_NAMES) {
698
- const at = this.#places[name];
699
- const label = this.#pool.get(name);
700
- if (!at || !label || label.hidden)
701
- continue;
702
- const text = label.textContent ?? "";
703
- let box = this.#nameBoxes.get(text);
704
- if (!box) {
705
- const rect = label.getBoundingClientRect();
706
- box = { width: Math.ceil(rect.width), height: Math.ceil(rect.height) };
707
- if (box.width > 0)
708
- this.#nameBoxes.set(text, box);
709
- }
710
- taken.push({ left: at.x + Math.max(4, Math.min(at.r, 40)), top: at.y - 8, ...box });
711
- }
712
- }
713
- return taken;
714
- }
715
- /**
716
- * The look of the names of cities (`city-names`): font, size, weight, colour, the outline round the text, and the dot's colour and size. Any of them may be left out; the Earth's size, the language and the data are not set here.
717
- */
718
- get cityNamesStyle() {
719
- return { ...this.#citiesStyle };
720
- }
721
- set cityNamesStyle(value) {
722
- this.#citiesStyle = { ...value };
723
- this.#cities?.setStyle(this.#citiesStyle);
724
- }
725
- /** Whether the meridians and parallels are drawn on the Earth (the attribute `grid`). Setting it writes the attribute, or takes it away. */
726
- get grid() {
727
- return readGrid(this.getAttribute("grid"));
728
- }
729
- set grid(value) {
730
- if (value)
731
- this.setAttribute("grid", "");
732
- else
733
- this.removeAttribute("grid");
734
- }
735
- /**
736
- * The look of the names of countries (`country-names`): font, weight, colour, the outline round the text, and the smallest and largest text size. Any of them may be left out; the Earth's size, the
737
- * language and the data are not set here.
738
- */
739
- get countryNamesStyle() {
740
- return { ...this.#countriesStyle };
741
- }
742
- set countryNamesStyle(value) {
743
- this.#countriesStyle = { ...value };
744
- this.#countries?.setStyle(this.#countriesStyle);
745
- }
746
- /**
747
- * Which borders are drawn on the Earth (the attribute `borders`): the countries' at any size, and the regions' (provinces, states, prefectures) once the Earth is large enough on the screen to tell them apart.
748
- * Setting it writes the attribute: both sets as `borders="countries regions"`, one as its own word, none takes the attribute away.
749
- */
750
- get borders() {
751
- return readBorders(this.getAttribute("borders"));
752
- }
753
- set borders(value) {
754
- const words = [value.countries ? "countries" : "", value.regions ? "regions" : ""].filter(Boolean);
755
- if (words.length === 0)
756
- this.removeAttribute("borders");
757
- else
758
- this.setAttribute("borders", words.join(" "));
759
- }
760
- /**
761
- * Where the borders' shapes come from (see `BorderData`): `countries` in place of chizu's `world-geo`, and `regions`, a country's regions by its code, which draws the regions; without it none are drawn.
762
- * Set it before `borders` is switched on: shapes already loaded are kept.
763
- */
764
- get borderData() {
765
- return { ...this.#model.borders.data };
766
- }
767
- set borderData(value) {
768
- this.#model.borders.data = { ...value };
769
- this.#gate?.request();
770
- }
771
- /** Puts the name's settings and text right from the attributes (`body-label` and its family, `lang`). */
772
- #applyBodyLabel() {
773
- this.#model.bodyLabel.settings = readBodyLabel((name) => this.getAttribute(name));
774
- this.#model.bodyLabel.text = bodyLabelText((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en");
775
- this.#gate?.request();
776
- }
777
- /**
778
- * How many times its real thickness the air is drawn, from 1 (the true thickness) to 5 (the attribute `air-thickness`; 3 when the page says nothing): see `<chikyu-earth-realistic>`. While it is above 1 the element says so in a line
779
- * under the picture (`air-label="off"` takes the line away, for a page that says it itself).
780
- */
781
- get airThickness() {
782
- return this.#model.airThickness;
783
- }
784
- set airThickness(value) {
785
- this.setAttribute("air-thickness", String(value));
786
- }
787
- get centre() {
788
- return { ...this.#model.centre };
789
- }
790
- set centre(value) {
791
- this.#model.centre = { ...value };
792
- this.#model.cameraSpin = null;
793
- this.#gate?.request();
794
- }
795
- /**
796
- * 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
797
- * 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
798
- * 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.
799
- */
800
- get camera() {
801
- return this.#model.camera;
802
- }
803
- set camera(value) {
804
- this.#model.camera = value;
805
- this.#model.cameraSpin = null;
806
- this.#gate?.request();
807
- }
808
- /** 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. */
809
- get earthSize() {
810
- return this.#model.earth.size;
811
- }
812
- set earthSize(value) {
813
- this.#model.earth.size = Number.isFinite(value) ? Math.min(50, Math.max(0.02, value)) : DEFAULT_EARTH_SIZE;
814
- this.#gate?.request();
815
- }
816
- /** 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. */
817
- get earthX() {
818
- return this.#model.earth.x;
819
- }
820
- set earthX(value) {
821
- this.#model.earth.x = Number.isFinite(value) ? value : 0.5;
822
- this.#gate?.request();
823
- }
824
- /** 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. */
825
- get earthY() {
826
- return this.#model.earth.y;
827
- }
828
- set earthY(value) {
829
- this.#model.earth.y = Number.isFinite(value) ? value : 0.5;
830
- this.#gate?.request();
831
- }
832
- /** 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. */
833
- get time() {
834
- return this.#model.time;
835
- }
836
- set time(value) {
837
- this.#mode = value instanceof Date ? value.getTime() : value;
838
- this.#model.time = this.#mode === "now" ? Date.now() : this.#mode;
839
- this.#model.cameraSpin = null;
840
- this.#last = performance.now();
841
- this.#schedule();
842
- this.#gate?.request();
843
- }
844
- /** Seconds of game time per second: 1 is real time, 0 holds still, negative runs backwards. */
845
- get speed() {
846
- return this.#speed;
847
- }
848
- set speed(value) {
849
- // time up to this moment is worked out at the old speed, so a hold keeps the moment the reader saw last
850
- if (this.#speed !== 0 && this.isConnected)
851
- this.#advance(performance.now());
852
- const was = this.#speed;
853
- if (this.isConnected && this.#view)
854
- this.#played = true;
855
- this.#speed = Number.isFinite(value) ? value : 1;
856
- this.#model.speed = this.#speed;
857
- this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
858
- this.#last = performance.now();
859
- this.#schedule();
860
- this.#gate?.request();
861
- if (this.#speed === 0 && was !== 0)
862
- this.#announce(false);
863
- }
864
- get scale() {
865
- return this.#model.mode;
866
- }
867
- set scale(value) {
868
- this.#model.mode = value;
869
- this.#gate?.request();
870
- }
871
- get labels() {
872
- return this.#model.labels;
873
- }
874
- set labels(value) {
875
- this.#model.labels = value;
876
- if (!value)
877
- for (const label of this.#pool.values())
878
- label.hidden = true;
879
- this.#gate?.request();
880
- }
881
- /**
882
- * How the Sun, the planets, Pluto and their moons are drawn: one of the `looks` of the body painter set with `setBodyPainter` (wakusei-planets has `realistic` and `painted`), or `plain` (the sphere in the right colour, no moons); empty for the painter's first.
883
- * With no painter they are plain spheres and this does nothing. Changing it draws the bodies again with the new look.
884
- */
885
- get bodies() {
886
- return this.#model.bodies;
887
- }
888
- set bodies(value) {
889
- this.#model.bodies = value;
890
- this.#showBodiesCredit();
891
- this.#gate?.request();
892
- }
893
- /** How the Earth is lit: `sun` (true, the default), `lit` (always lit, as if by daylight from the camera's side, so a ride on the night side is never a black frame) or `boost` (the true terminator, with the night side raised). The Sun, the Moon and the planets keep their true places. */
894
- get light() {
895
- return this.#model.light;
896
- }
897
- set light(value) {
898
- this.#model.light = value;
899
- this.#gate?.request();
900
- }
901
- /** The looks the body painter offers (empty with no painter), for a page to build its choice from. */
902
- get bodyLooks() {
903
- return painter?.looks ?? [];
904
- }
905
- get orbits() {
906
- return this.#model.orbits;
907
- }
908
- set orbits(value) {
909
- this.#model.orbits = value;
910
- this.#gate?.request();
911
- }
912
- /**
913
- * 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
914
- * 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.
915
- *
916
- * @param view - The controls' yaw and tilt in degrees and zoom.
917
- * @param final - False for the frames of a turn that is still going on (Auto-turn, a drag); true when it has settled.
918
- */
919
- setView(view, final = true) {
920
- const now = this.#model.view;
921
- if (view.yaw === now.yaw && view.tilt === now.tilt && view.zoom === now.zoom)
922
- return;
923
- const model = this.#model;
924
- // a riding camera that looks round adds up its turn change by change: the controls wrap their yaw into -180..180, so the yaw alone cannot say how far round the camera has gone, and a change of zoom must not swing it
925
- if (view.yaw !== now.yaw)
926
- model.rideTurn += rideTurnDegrees(wrapYaw(view.yaw - now.yaw), view.zoom);
927
- // and the tilt is held to what does something in the look: past it a drag would have to come back before anything moved (the controls driving the view are handed the held tilt, the bar's own when one is bound)
928
- let tilt = view.tilt;
929
- const limits = model.ride && model.ride.view === "from" && model.rideDistance !== null ? rideTiltLimits(model.rideDistance, model.ride.look, view.zoom) : null;
930
- if (limits)
931
- tilt = Math.max(limits.min, Math.min(limits.max, tilt));
932
- this.#model.view = { yaw: view.yaw, tilt, zoom: view.zoom };
933
- // the whole view is handed back, the yaw as it is, so the controls keep what they held and the element hears nothing it did not already have
934
- if (tilt !== view.tilt)
935
- this.#controls()?.set({ yaw: view.yaw, tilt, zoom: view.zoom }, final, "ride");
936
- const drawn = this.#model.drawnView;
937
- if (drawn && !final && view.zoom === drawn.zoom) {
938
- const turned = Math.max(Math.abs(view.yaw - drawn.yaw), Math.abs(view.tilt - drawn.tilt)) * RAD;
939
- if (turned * (this.#model.heightPx / 2) < 0.5)
940
- return;
941
- }
942
- this.#gate?.request();
943
- this.#tellFacing();
944
- }
945
- /**
946
- * The controls that are driving this view: a `<kazoku-view-controls for="...">` bound to it (its hands are then the only ones and its controller holds the yaw and tilt), else the element's own hands.
947
- */
948
- #controls() {
949
- if (this.hasAttribute("data-kazoku-bar") && this.id) {
950
- const root = this.getRootNode();
951
- const bar = root.querySelector?.(`kazoku-view-controls[for="${CSS.escape(this.id)}"]`);
952
- const held = bar ? Reflect.get(bar, "controller") : undefined;
953
- if (held)
954
- return held;
955
- }
956
- return this.#hands?.controller;
957
- }
958
- /** The body the camera looks at: at zoom 1 it fills the view; the yaw and tilt turn the camera round it. */
959
- get body() {
960
- return this.#model.focus;
961
- }
962
- set body(name) {
963
- if (!BODY_NAMES.includes(name))
964
- return;
965
- this.#model.focus = name;
966
- this.#gate?.request();
967
- }
968
- // --- riding along -------------------------------------------------------------------------------------------------------------------------------
969
- /**
970
- * 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
971
- * 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.
972
- * 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
973
- * 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.
974
- *
975
- * @param target - A body name (`"Moon"`, `"Mars"`, ...) or a satellite `{ group, index }`, or `null` to stop.
976
- * @param options - `view`, `look`, `distanceKm`, `smooth` (see `RideOptions`).
977
- */
978
- ride(target, options = {}) {
979
- const model = this.#model;
980
- const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
981
- const wasRiding = model.ride !== null;
982
- if (target === null) {
983
- model.ride = null;
984
- model.rideTurn = 0;
985
- model.focus = this.#focusBeforeRide;
986
- }
987
- else {
988
- if (typeof target === "string" && !BODY_NAMES.includes(target))
989
- return;
990
- if (typeof target !== "string" && !model.satellites.groups.get(target.group))
991
- return;
992
- if (!wasRiding)
993
- this.#focusBeforeRide = model.focus;
994
- // the heading starts from the yaw the controls already hold (an address that carries `yaw` is read before the ride begins), so a ride opened from the address looks where the one that was dragged there looked
995
- model.rideTurn = rideTurnDegrees(model.view.yaw, model.view.zoom);
996
- const asked = options.view ?? "from";
997
- // above a body is meant for a satellite: a body is followed
998
- const view = typeof target === "string" && (target === "Earth" || asked === "above") ? "follow" : asked;
999
- // a body followed (a planet, the Moon, the Earth) is looked at from round it as the view turns: it has no ways to face
1000
- const faceable = !(view === "follow" && typeof target === "string");
1001
- const face = faceable && options.face && RIDE_FACES.includes(options.face) ? options.face : null;
1002
- model.ride = { target: typeof target === "string" ? target : { group: target.group, index: target.index }, view, look: face && view === "from" ? "horizon" : (options.look ?? "down"), face, distanceKm: Math.max(100, options.distanceKm ?? 3000) };
1003
- if (face) {
1004
- model.view = { yaw: 0, tilt: 0, zoom: model.view.zoom };
1005
- model.rideTurn = 0;
1006
- this.#controls()?.set({ yaw: 0, tilt: 0, zoom: model.view.zoom }, true, "ride");
1007
- }
1008
- if (typeof target === "string" && view === "follow")
1009
- model.focus = target;
1010
- else if (wasRiding)
1011
- model.focus = this.#focusBeforeRide;
1012
- }
1013
- this.#zoomRange(model.ride?.view === "from");
1014
- this.#lostTold = false;
1015
- const pose = model.pose;
1016
- model.transition = (options.smooth ?? true) && !reduced && pose.valid ? { start: performance.now(), duration: 1200, from: { p: [pose.p[0], pose.p[1], pose.p[2]], q: [pose.q[0], pose.q[1], pose.q[2], pose.q[3]], fov: pose.fov } } : null;
1017
- this.#last = performance.now();
1018
- this.#schedule();
1019
- this.#gate?.request();
1020
- this.dispatchEvent(new CustomEvent("chikyu-ride", { detail: this.riding }));
1021
- this.#tellFacing();
1022
- }
1023
- /**
1024
- * Face one way while riding: `ahead` along the way it goes, `behind`, `left` or `right` (as seen facing ahead), `down` straight at the Earth, `up` straight away from it.
1025
- * In the `above` view, `down` looks straight down at the satellite and the Earth below it. The camera glides there in half a second (at once for a reader who asked for reduced motion) and keeps the zoom.
1026
- * The facing stays pressed until the view is turned or tipped. `chikyu-ride-face` is sent with `{ face }` (`null` when it is let go). Keys, while the element is focused: W ahead, S behind, A left, D right, R up, F down. The arrow keys stay with the view controls.
1027
- *
1028
- * @param face - The way to face.
1029
- * Following a body (a planet, the Moon) there is no way to face: it returns `false`. Held keys do not repeat, and keys typed in a field or in editable text are left to it.
1030
- *
1031
- * @returns Whether the camera faces that way now (`true` too when it already did, and nothing moves).
1032
- */
1033
- face(face) {
1034
- const model = this.#model;
1035
- const ride = model.ride;
1036
- if (!ride || !RIDE_FACES.includes(face))
1037
- return false;
1038
- // following a body there is no way to face: only from a body or a satellite, following a satellite, or above it
1039
- if (ride.view === "follow" && typeof ride.target === "string")
1040
- return false;
1041
- // already facing that way: nothing to turn, and no glide started again
1042
- if (this.facing === face)
1043
- return true;
1044
- const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
1045
- const pose = model.pose;
1046
- const zoom = model.view.zoom;
1047
- model.ride = { ...ride, look: ride.view === "from" ? "horizon" : ride.look, face };
1048
- model.view = { yaw: 0, tilt: 0, zoom };
1049
- model.rideTurn = 0;
1050
- this.#controls()?.set({ yaw: 0, tilt: 0, zoom }, true, "ride");
1051
- model.rideTurn = 0;
1052
- model.view = { yaw: 0, tilt: 0, zoom };
1053
- model.transition = !reduced && pose.valid ? { start: performance.now(), duration: 500, from: { p: [pose.p[0], pose.p[1], pose.p[2]], q: [pose.q[0], pose.q[1], pose.q[2], pose.q[3]], fov: pose.fov } } : null;
1054
- this.#last = performance.now();
1055
- this.#schedule();
1056
- this.#gate?.request();
1057
- this.#tellFacing();
1058
- return true;
1059
- }
1060
- /** The facing (`face`), while the view has not been turned or tipped from it; `null` otherwise. */
1061
- get facing() {
1062
- const ride = this.#model.ride;
1063
- const view = this.#model.view;
1064
- return ride?.face && view.yaw === 0 && view.tilt === 0 ? ride.face : null;
1065
- }
1066
- #tellFacing() {
1067
- const now = this.facing;
1068
- if (now === this.#toldFacing)
1069
- return;
1070
- this.#toldFacing = now;
1071
- this.dispatchEvent(new CustomEvent("chikyu-ride-face", { detail: { face: now } }));
1072
- }
1073
- /** W ahead, S behind, A left, D right, R up, F down, while this element is focused and a ride is on. */
1074
- #faceKey = (event) => {
1075
- // a held key repeats: the first press turns, the repeats would only start the glide again and again
1076
- if (event.ctrlKey || event.metaKey || event.altKey || event.defaultPrevented || event.repeat)
1077
- return;
1078
- // typing in a field anywhere on the way to this element (its own shadow root and slots included), or in editable text, is typing, not facing
1079
- const typing = event.composedPath().some((node) => node instanceof HTMLElement && (node.matches("input, textarea, select") || node.isContentEditable));
1080
- if (typing)
1081
- return;
1082
- const face = FACE_KEYS[event.key.toLowerCase()];
1083
- if (face && this.face(face))
1084
- event.preventDefault();
1085
- };
1086
- /** From a body the zoom only narrows the field a little, so the range is 0.5 to 6: the `zoom-min` and `zoom-max` attributes, unless the page set them itself. */
1087
- #zoomRange(from) {
1088
- for (const name of ["zoom-min", "zoom-max"]) {
1089
- const mine = this.#ridden[name];
1090
- if (this.hasAttribute(name) && this.getAttribute(name) !== mine)
1091
- continue;
1092
- if (from) {
1093
- this.#ridden[name] = RIDE_ZOOM[name];
1094
- this.setAttribute(name, RIDE_ZOOM[name]);
1095
- }
1096
- else {
1097
- if (mine !== undefined)
1098
- this.removeAttribute(name);
1099
- delete this.#ridden[name];
1100
- }
1101
- }
1102
- }
1103
- /**
1104
- * The satellites the page has a model for (`setSatellitePainter`) in the groups now set, each with its name in the page's language: the large satellites that can be followed as a model. Empty with no painter.
1105
- */
1106
- largeSatellites() {
1107
- const out = [];
1108
- if (!satellitePainter)
1109
- return out;
1110
- this.#prepareSatLabelLang();
1111
- for (const [group, state] of this.#model.satellites.groups) {
1112
- state.satellites.sets.forEach((set, index) => {
1113
- if (satellitePainter.has(set.NORAD_CAT_ID))
1114
- out.push({ ref: { group, index }, noradId: set.NORAD_CAT_ID, name: this.#satelliteName({ group, index }) });
1115
- });
1116
- }
1117
- return out;
1118
- }
1119
- /**
1120
- * Follow the next (or, with a negative `step`, the previous) of the large satellites in `largeSatellites()`, going round: the first when none is followed yet. The followed satellite stays in the middle of the picture, as a model where the page has one,
1121
- * with the Earth turning and sliding beneath. Returns the satellite now followed, or `null` when there is none to follow.
1122
- *
1123
- * @param step - How many places to hop: 1 (the default) is the next.
1124
- */
1125
- followNext(step = 1) {
1126
- const list = this.largeSatellites();
1127
- if (list.length === 0)
1128
- return null;
1129
- const ride = this.#model.ride;
1130
- const current = ride && typeof ride.target !== "string" ? list.findIndex((one) => one.ref.group === ride.target.group && one.ref.index === ride.target.index) : -1;
1131
- const next = list[(((current < 0 ? (step > 0 ? -1 : 0) : current) + step) % list.length + list.length) % list.length];
1132
- this.ride(next.ref, { view: "follow" });
1133
- return next;
1134
- }
1135
- /** What the camera is riding along with now, or null. */
1136
- get riding() {
1137
- const ride = this.#model.ride;
1138
- return ride ? { ...ride, target: typeof ride.target === "string" ? ride.target : { ...ride.target } } : null;
1139
- }
1140
- #rideLost() {
1141
- if (this.#lostTold)
1142
- return;
1143
- this.#lostTold = true;
1144
- this.dispatchEvent(new CustomEvent("chikyu-ride-lost", { detail: this.riding }));
1145
- }
1146
- // --- satellites ---------------------------------------------------------------------------------------------------------------------------------
1147
- /**
1148
- * Colour each satellite by its orbit class (low, medium, geostationary, highly elliptical, other). Off by default, so a group keeps the colour it was given. The attribute is `satellite-tint="orbit"`.
1149
- */
1150
- get satelliteTint() {
1151
- return this.#model.satellites.orbitTint ? "orbit" : "off";
1152
- }
1153
- set satelliteTint(value) {
1154
- if (value === "orbit")
1155
- this.setAttribute("satellite-tint", "orbit");
1156
- else
1157
- this.removeAttribute("satellite-tint");
1158
- }
1159
- /**
1160
- * 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. Giving the name of a group
1161
- * 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).
1162
- * The groups are placed by SGP4 about once a second and interpolated between. Above `MAX_SATELLITE_SPEED` each satellite is a short streak along its orbit instead of being hidden.
1163
- *
1164
- * @param group - The group's name, for `showSatellites`, `selectSatellite` and the events.
1165
- * @param satellites - The group, or `null` to remove it.
1166
- * @param style - How to draw it.
1167
- */
1168
- /**
1169
- * Paint one satellite's path on the Earth. `id` is a NORAD catalogue number or `group:index`. `length` is how long the trail is kept, in simulated time (`1d` when left out, or `1w`, `1m`). `swath` is `track` (the point under the satellite, the default) or `coverage` (where it is at least 10° above the horizon). Setting another satellite clears the trail. `null` clears it.
1170
- */
1171
- get paint() {
1172
- return this.#paint.on ? { id: this.#paint.id, length: this.#paint.length, swath: this.#paint.swath } : null;
1173
- }
1174
- set paint(value) {
1175
- this.#paint.set(value);
1176
- this.#gate?.request();
1177
- }
1178
- /** Take the painted trail off the Earth. */
1179
- clearPaint() {
1180
- this.#paint.clear();
1181
- this.#gate?.request();
1182
- }
1183
- /** Texels the trail has painted. 0 after `clearPaint`, and again when the painted satellite changes. */
1184
- get paintPixels() {
1185
- return this.#paint.pixels;
1186
- }
1187
- setSatellites(group, satellites, style = {}) {
1188
- const groups = this.#model.satellites.groups;
1189
- if (satellites === null) {
1190
- groups.delete(group);
1191
- if (this.#model.satellites.selected?.group === group)
1192
- this.#model.satellites.selected = null;
1193
- }
1194
- else {
1195
- const was = groups.get(group);
1196
- groups.set(group, {
1197
- satellites,
1198
- color: style.color ?? was?.color ?? SATELLITE_COLORS[groups.size % SATELLITE_COLORS.length],
1199
- size: style.size ?? was?.size ?? 3,
1200
- orbits: (style.orbits ?? was?.orbits ?? false) && satellites.count <= MAX_ORBIT_GROUP,
1201
- visible: was?.visible ?? true,
1202
- });
1203
- }
1204
- // a group's index may now be a different satellite, so a cached name for that ref is no longer its name
1205
- this.#satLabelCache.clear();
1206
- this.#last = performance.now();
1207
- this.#schedule();
1208
- this.#gate?.request();
1209
- }
1210
- /** Show or hide a group without losing it. */
1211
- showSatellites(group, on) {
1212
- const found = this.#model.satellites.groups.get(group);
1213
- if (!found || found.visible === on)
1214
- return;
1215
- found.visible = on;
1216
- this.#schedule();
1217
- this.#gate?.request();
1218
- }
1219
- /** The groups now set, with how many satellites each holds and whether it is shown. */
1220
- get satelliteGroups() {
1221
- return [...this.#model.satellites.groups].map(([name, group]) => ({ name, count: group.satellites.count, visible: group.visible }));
1222
- }
1223
- /** Mark one satellite: a larger ring round it, its orbit drawn, and its name beside it. `null` lets it go. */
1224
- selectSatellite(ref) {
1225
- const found = ref ? this.#model.satellites.groups.get(ref.group) : undefined;
1226
- this.#model.satellites.selected = ref && found && ref.index >= 0 && ref.index < found.satellites.count ? { group: ref.group, index: ref.index } : null;
1227
- if (this.#chosenLabel)
1228
- this.#chosenLabel.hidden = true;
1229
- this.#gate?.request();
1230
- }
1231
- /** The satellite marked by `selectSatellite` or by a press on it, if any. */
1232
- get selectedSatellite() {
1233
- const chosen = this.#model.satellites.selected;
1234
- return chosen ? { ...chosen } : null;
1235
- }
1236
- /**
1237
- * Ring and name every satellite of a group (or stop): a ring round each and its name beside it, in the page's language (the ISS, Tiangong and Hubble by their short names, the rest as their elements name them, or as `satelliteNames` says), never over another name, a place's or a ring's.
1238
- * Names and rings are drawn with the places, only for satellites that are in the picture and not behind the Earth, and nothing is drawn at rest. `chikyu-satellite-visibility` is sent with `detail: { ref, visible }` when a labelled satellite comes into view or goes out of it (not at every frame).
1239
- * At most 80 satellites are ringed, over all the groups. A group that is not set, or is not shown, has none.
1240
- *
1241
- * @param group - The group's name, as given to `setSatellites`.
1242
- * @param on - `true` to ring and name its members (the default), `false` to stop.
1243
- */
1244
- labelSatellites(group, on = true) {
1245
- if (on)
1246
- this.#model.satellites.marked.add(group);
1247
- else
1248
- this.#model.satellites.marked.delete(group);
1249
- this.#gate?.request();
1250
- }
1251
- /** The groups whose satellites are ringed and named now (`labelSatellites`). */
1252
- get labelledSatellites() {
1253
- return [...this.#model.satellites.marked];
1254
- }
1255
- /**
1256
- * The names written beside the ringed satellites, by NORAD number, for a page in another language or with names of its own (`{ 25544: "Space Station" }`). One left out keeps its short name (the ISS, Tiangong and Hubble) or the name in its elements.
1257
- */
1258
- get satelliteNames() {
1259
- return { ...this.#satNames };
1260
- }
1261
- set satelliteNames(value) {
1262
- this.#satNames = { ...value };
1263
- this.#satLabelCache.clear();
1264
- this.#gate?.request();
1265
- }
1266
- /**
1267
- * Where a satellite is on the screen as of the last draw: `{ x, y, visible, heightKm }` in CSS pixels from the view's top left, `visible` meaning it is inside the box and not behind the Earth. `null` when its group is not set or not shown, it cannot be
1268
- * placed (its elements are too old), or it is behind the camera. It is the picture's own camera maths and its own test for the Earth in the way, so a page that draws its own rings need not repeat either.
1269
- */
1270
- placeSatellite(ref) {
1271
- return this.#model.placeSatellite?.(ref) ?? null;
1272
- }
1273
- /** The page's language for a satellite name: Japanese when the nearest `lang` starts with `ja`, otherwise English. Read once per pass, not once per satellite. */
1274
- #readSatLabelLang() {
1275
- return (this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en";
1276
- }
1277
- /** Remember the page's language and drop cached names when it changes. One `closest("[lang]")` for the pass. */
1278
- #prepareSatLabelLang() {
1279
- const lang = this.#readSatLabelLang();
1280
- if (lang !== this.#satLabelLang) {
1281
- this.#satLabelCache.clear();
1282
- this.#satLabelLang = lang;
1283
- }
1284
- }
1285
- /** The name beside a ringed satellite: the page's own (`satelliteNames`), else the short one in the page's language, else the name in its elements. Cached per ref and language: the name is constant, and reading it does not propagate the orbit again. */
1286
- #satelliteName(ref) {
1287
- const key = `${ref.group}:${ref.index}`;
1288
- const cached = this.#satLabelCache.get(key);
1289
- if (cached !== undefined)
1290
- return cached;
1291
- const info = this.satelliteInfo(ref);
1292
- if (!info)
1293
- return "";
1294
- const lang = this.#satLabelLang === "ja" ? "ja" : "en";
1295
- const name = this.#satNames[info.noradId] ?? SHORT_NAMES[info.noradId]?.[lang] ?? info.name;
1296
- this.#satLabelCache.set(key, name);
1297
- return name;
1298
- }
1299
- #markSeen = new Map();
1300
- /** Hands the places layer the ringed satellites of this draw, and tells the page when one comes into view or goes out of it. */
1301
- #showMarks(marks) {
1302
- if (marks.length > 0)
1303
- this.#prepareSatLabelLang();
1304
- this.#marks = marks.map((m) => ({ id: `${m.ref.group}:${m.ref.index}`, label: this.#satelliteName(m.ref), x: m.x, y: m.y, visible: m.visible }));
1305
- const now = new Map();
1306
- for (const m of marks) {
1307
- const key = `${m.ref.group}:${m.ref.index}`;
1308
- now.set(key, m.visible);
1309
- if (this.#markSeen.get(key) !== m.visible && (this.#markSeen.has(key) || m.visible))
1310
- this.dispatchEvent(new CustomEvent("chikyu-satellite-visibility", { detail: { ref: m.ref, visible: m.visible }, bubbles: true, composed: true }));
1311
- }
1312
- for (const [key, was] of this.#markSeen) {
1313
- if (!now.has(key) && was) {
1314
- const [group, index] = key.split(":");
1315
- this.dispatchEvent(new CustomEvent("chikyu-satellite-visibility", { detail: { ref: { group: group, index: Number(index) }, visible: false }, bubbles: true, composed: true }));
1316
- }
1317
- }
1318
- this.#markSeen = now;
1319
- }
1320
- /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period, and `ownerCountry` when the owner is one country); undefined if it cannot be placed then. */
1321
- satelliteInfo(ref) {
1322
- return this.#model.satellites.groups.get(ref.group)?.satellites.info(ref.index, this.#model.time);
1323
- }
1324
- /** The words shown beside each body, for a page in another language (`{ Mars: "火星" }`). A body left out keeps its English name. */
1325
- get bodyNames() {
1326
- return { ...this.#names };
1327
- }
1328
- set bodyNames(value) {
1329
- this.#names = { ...value };
1330
- for (const [name, button] of this.#pool)
1331
- this.#nameLabel(button, name);
1332
- }
1333
- /** What a screen reader hears after a body's name: "choose to look at it" by default, or the page's own words. */
1334
- get bodyHint() {
1335
- return this.#hint;
1336
- }
1337
- set bodyHint(value) {
1338
- this.#hint = value;
1339
- for (const [name, button] of this.#pool)
1340
- this.#nameLabel(button, name);
1341
- }
1342
- /** The radius and the distance from the Earth of a body now, for a page's own caption. */
1343
- bodyInfo(name) {
1344
- const frame = this.#model.drawn?.frame ?? frameAt(this.#model.time);
1345
- const geo = name === "Earth" ? [0, 0, 0] : name === "Sun" ? frame.sun : name === "Moon" ? frame.moon : frame.planets[name];
1346
- return { name, radiusKm: RADIUS_KM[name], distanceKm: Math.hypot(geo[0], geo[1], geo[2]) * (AU_IN_EARTH_RADII * EARTH_RADIUS_KM) };
1347
- }
1348
- /** The zoom that shows a part of the sky: the Earth alone, the Moon's orbit, the Sun, the planets out to Mars, or all of them, at this scale and moment. */
1349
- zoomFor(preset) {
1350
- if (preset.endsWith("-moons")) {
1351
- const name = preset.slice(0, -6);
1352
- const sites = painter?.moons?.(name, this.#model.time) ?? [];
1353
- const reach = Math.max(1, ...sites.map((site) => Math.hypot(...site.offset)).filter((r) => r <= 22));
1354
- const radius = RADIUS[name][this.#model.mode];
1355
- return Math.min(1, (this.#model.fit * radius) / ((reach * radius * 1.15) / Math.tan(17.5 * RAD)));
1356
- }
1357
- const frame = this.#model.drawn?.frame ?? frameAt(this.#model.time);
1358
- const mode = this.#model.mode;
1359
- const sun = placeSun(mode, frame.sun);
1360
- const around = (name) => Math.hypot(...placeAround(mode, sun, [frame.planets[name][0] - frame.sun[0], frame.planets[name][1] - frame.sun[1], frame.planets[name][2] - frame.sun[2]]));
1361
- const reach = {
1362
- earth: 0,
1363
- moon: Math.hypot(...placeMoon(mode, frame.moon)),
1364
- sun: Math.hypot(...sun),
1365
- inner: Math.max(around("Mercury"), around("Venus"), around("Mars"), Math.hypot(...sun)),
1366
- "solar-system": Math.max(...Object.keys(frame.planets).map(around), Math.hypot(...sun)),
1367
- }[preset];
1368
- return preset === "earth" ? 1 : this.#model.fit / Math.max(this.#model.fit, reach * 3.4);
1369
- }
1370
- /** What the element is doing, for a page or a test. */
1371
- get stats() {
1372
- const stats = this.#taken?.renderer.stats;
1373
- return {
1374
- state: this.#state,
1375
- draws: stats?.draws ?? 0,
1376
- contexts: stats?.contexts ?? 0,
1377
- canvas: stats?.canvas ?? { width: 0, height: 0, pixels: 0 },
1378
- tiers: { ...this.#tiers },
1379
- distance: this.#model.drawn?.distance ?? 0,
1380
- assets: { entries: stats?.assets.entries ?? 0, refs: stats?.assets.refs ?? 0 },
1381
- time: this.#model.time,
1382
- lookups: this.#model.lookups,
1383
- satellites: this.#satelliteStats(),
1384
- ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null, facing: this.facing },
1385
- camera: { position: [this.#model.pose.p[0], this.#model.pose.p[1], this.#model.pose.p[2]], quaternion: [this.#model.pose.q[0], this.#model.pose.q[1], this.#model.pose.q[2], this.#model.pose.q[3]], fov: this.#model.pose.fov },
1386
- bodies: { look: this.#model.bodies || painter?.looks?.[0] || "plain", painted: this.#model.painted.bodies, moons: this.#model.painted.moons, held: this.#model.painted.held, moon: this.#model.painted.moon, tiles: this.#model.painted.tiles },
1387
- meteors: { on: this.#model.meteors.on, strength: this.#model.meteors.strength, ...this.#model.meteors.drawn },
1388
- bodyLabel: { on: this.#model.bodyLabel.settings !== null, text: this.#model.bodyLabel.text, ...this.#model.bodyLabel.drawn },
1389
- sky: this.#sky?.stats ?? { on: false, loaded: false, names: 0, figures: 0, picked: null, pick: null, hover: null, constellations: 0, culture: "iau", renders: 0, lang: "", stars: [] },
1390
- followModel: this.#model.followModel,
1391
- places: { ...(this.#placeLayer?.stats ?? { places: 0, shown: 0, labels: 0, renders: 0, rings: 0, satelliteNames: 0, marks: 0, groups: 0, sprites: 0, dots: 0, omitted: 0 }) },
1392
- cityNames: this.#cities?.stats ?? { on: false, max: 0, radius: 0, tiers: [], cities: 0, names: 0, renders: 0 },
1393
- borders: { ...this.#model.borders.stats, shown: { ...this.#model.borders.stats.shown }, loaded: [...this.#model.borders.stats.loaded] },
1394
- grid: { ...this.#model.grid.stats },
1395
- countryNames: this.#countries?.stats ?? { on: false, max: 0, countries: 0, names: 0, renders: 0, failed: false },
1396
- };
1397
- }
1398
- #satelliteStats() {
1399
- const drawn = this.#model.satellites.drawn;
1400
- let propagations = 0;
1401
- let lastBatchMs = 0;
1402
- let maxBatchMs = 0;
1403
- for (const group of this.#model.satellites.groups.values()) {
1404
- propagations += group.satellites.propagations;
1405
- lastBatchMs = Math.max(lastBatchMs, group.satellites.timing.lastBatchMs);
1406
- maxBatchMs = Math.max(maxBatchMs, group.satellites.timing.maxBatchMs);
1407
- }
1408
- let epochMs = 0;
1409
- for (const group of this.#model.satellites.groups.values())
1410
- epochMs = Math.max(epochMs, group.satellites.newestEpochMs);
1411
- return { groups: this.#model.satellites.groups.size, placed: drawn.placed, segments: drawn.segments, tooFast: drawn.tooFast, dotScale: drawn.dotScale, epochMs, propagations, lastBatchMs, maxBatchMs, updateMs: drawn.updateMs, maxUpdateMs: drawn.maxUpdateMs, averageUpdateMs: drawn.updates ? drawn.totalMs / drawn.updates : 0, updates: drawn.updates };
1412
- }
1413
- // --- the game clock ----------------------------------------------------------------------------------------------------------------------------
1414
- #readSpeed() {
1415
- const raw = this.getAttribute("speed");
1416
- const value = raw === null || raw === "" ? 1 : Number(raw);
1417
- return Number.isFinite(value) ? value : 1;
1418
- }
1419
- /** Is anything on show that moves faster than the Earth turns: a group of satellites, including above the interpolation limit where they are drawn as streaks? */
1420
- #satellitesMoving() {
1421
- for (const group of this.#model.satellites.groups.values())
1422
- if (group.visible && group.satellites.count > 0)
1423
- return true;
1424
- return false;
1425
- }
1426
- /** While time runs, draw as often as it shows: real time once a minute; faster time as often as the Earth's turn moves a pixel (1 to 30 times a second). Satellites go round in 90 minutes and a ride along moves the whole picture, so with either on show real time draws about as often as a pixel moves (once a second at least), and a reader who asked for reduced motion gets one step a second. */
1427
- #schedule() {
1428
- clearTimeout(this.#timer);
1429
- this.#timer = undefined;
1430
- if (!this.isConnected || this.#speed === 0)
1431
- return;
1432
- const satellites = this.#satellitesMoving();
1433
- const riding = this.#model.ride !== null;
1434
- const radius = this.#model.drawn?.radiusPx ?? 200;
1435
- const pixelsPerSecond = Math.max((satellites ? SATELLITE_RATE : EARTH_RATE) * RAD * Math.abs(this.#speed) * radius, this.#model.rideMotion * Math.abs(this.#speed));
1436
- let perSecond = Math.min(30, Math.max(1, pixelsPerSecond));
1437
- if ((satellites || riding) && matchMedia("(prefers-reduced-motion: reduce)").matches)
1438
- perSecond = 1;
1439
- const wait = !satellites && !riding && this.#speed === 1 ? REAL_TIME_TICK_MS : 1000 / perSecond;
1440
- this.#timer = setTimeout(this.#tick, wait);
1441
- }
1442
- /** Bring the moment shown up to `now` (the page's own clock, in milliseconds) at the speed it has run at. */
1443
- #advance(now) {
1444
- if (this.#speed === 1 && this.#mode === "now")
1445
- this.#model.time = Date.now();
1446
- else
1447
- this.#model.time += (now - this.#last) * this.#speed;
1448
- this.#last = now;
1449
- }
1450
- /** 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. */
1451
- #announce(running) {
1452
- const now = performance.now();
1453
- if (running && (now - this.#announced < TIME_EVENT_MS || document.visibilityState === "hidden"))
1454
- return;
1455
- this.#announced = running ? now : -Infinity;
1456
- this.dispatchEvent(new CustomEvent("chikyu-timechange", { detail: { time: this.#model.time, running } }));
1457
- }
1458
- #tick = () => {
1459
- this.#advance(performance.now());
1460
- this.#gate?.request();
1461
- this.#schedule();
1462
- this.dispatchEvent(new CustomEvent("chikyu-time", { detail: { time: this.#model.time } }));
1463
- this.#announce(this.#speed !== 0);
1464
- };
1465
- // --- labels --------------------------------------------------------------------------------------------------------------------------------------
1466
- #placeLabels(places) {
1467
- this.#places = places;
1468
- const box = this.#labelBox;
1469
- if (!box)
1470
- return;
1471
- for (const name of BODY_NAMES) {
1472
- let label = this.#pool.get(name);
1473
- const at = places[name];
1474
- if (!label) {
1475
- if (!at)
1476
- continue;
1477
- const button = box.ownerDocument.createElement("button");
1478
- button.type = "button";
1479
- button.className = "sp-label";
1480
- button.dataset["body"] = name;
1481
- this.#nameLabel(button, name);
1482
- box.append(button);
1483
- this.#pool.set(name, button);
1484
- label = button;
1485
- }
1486
- if (!at) {
1487
- if (!label.hidden)
1488
- label.hidden = true;
1489
- continue;
1490
- }
1491
- if (label.hidden)
1492
- label.hidden = false;
1493
- label.style.transform = `translate(${Math.round(at.x + Math.max(4, Math.min(at.r, 40)))}px,${Math.round(at.y - 8)}px)`;
1494
- }
1495
- }
1496
- #placeChosen(place) {
1497
- const box = this.#labelBox;
1498
- if (!box)
1499
- return;
1500
- if (!place) {
1501
- if (this.#chosenLabel)
1502
- this.#chosenLabel.hidden = true;
1503
- return;
1504
- }
1505
- const chosen = this.#model.satellites.selected;
1506
- const name = chosen ? this.satelliteInfo(chosen)?.name : undefined;
1507
- if (!this.#chosenLabel) {
1508
- this.#chosenLabel = box.ownerDocument.createElement("div");
1509
- this.#chosenLabel.className = "sp-sat";
1510
- box.append(this.#chosenLabel);
1511
- }
1512
- if (this.#chosenLabel.textContent !== (name ?? ""))
1513
- this.#chosenLabel.textContent = name ?? "";
1514
- this.#chosenLabel.hidden = !name;
1515
- this.#chosenLabel.style.transform = `translate(${Math.round(place.x + 10)}px,${Math.round(place.y - 8)}px)`;
1516
- }
1517
- #nameLabel(button, name) {
1518
- const text = this.#names[name] ?? name;
1519
- button.textContent = text;
1520
- button.setAttribute("aria-label", `${text}: ${this.#hint}`);
1521
- }
1522
- // A body is chosen by pressing on it or on its name (and by Tab and Enter on the name); a drag that turns the view is not a choice.
1523
- #downX = 0;
1524
- #downY = 0;
1525
- #down = (event) => {
1526
- if (event.button !== 0)
1527
- return;
1528
- this.#downX = event.clientX;
1529
- this.#downY = event.clientY;
1530
- window.addEventListener("pointerup", this.#up, { capture: true, once: true });
1531
- };
1532
- #up = (event) => {
1533
- if (Math.hypot(event.clientX - this.#downX, event.clientY - this.#downY) > 6)
1534
- return;
1535
- const rect = this.getBoundingClientRect();
1536
- const x = event.clientX - rect.left;
1537
- const y = event.clientY - rect.top;
1538
- const satellite = this.#model.pick?.(x, y, 12);
1539
- if (satellite) {
1540
- this.dispatchEvent(new CustomEvent("chikyu-satellite-click", { detail: { ...satellite, info: this.satelliteInfo(satellite) }, bubbles: true, composed: true }));
1541
- return;
1542
- }
1543
- if (!this.#places)
1544
- return;
1545
- let best;
1546
- let bestD = Infinity;
1547
- for (const name of BODY_NAMES) {
1548
- const at = this.#places[name];
1549
- if (!at)
1550
- continue;
1551
- const d = Math.hypot(x - at.x, y - at.y);
1552
- if (d <= Math.max(at.r, 14) && d < bestD) {
1553
- best = name;
1554
- bestD = d;
1555
- }
1556
- }
1557
- if (best)
1558
- this.dispatchEvent(new CustomEvent("chikyu-body-click", { detail: this.bodyInfo(best), bubbles: true, composed: true }));
1559
- };
1560
- #labelClick = (event) => {
1561
- const name = event.target?.dataset?.["body"];
1562
- if (name)
1563
- this.dispatchEvent(new CustomEvent("chikyu-body-click", { detail: this.bodyInfo(name), bubbles: true, composed: true }));
1564
- };
1565
- #labelFocus = (event) => {
1566
- const name = event.target?.dataset?.["body"];
1567
- if (name)
1568
- this.dispatchEvent(new CustomEvent("chikyu-body-focus", { detail: this.bodyInfo(name), bubbles: true, composed: true }));
1569
- };
1570
- // --- the rest --------------------------------------------------------------------------------------------------------------------------------------
1571
- #textureBase() {
1572
- const given = this.getAttribute("texture-base");
1573
- const base = given ?? new URL("../textures/", import.meta.url).href;
1574
- return base.endsWith("/") ? base : `${base}/`;
1575
- }
1576
- #textureCap() {
1577
- const given = Number(this.getAttribute("max-texture"));
1578
- const memory = navigator.deviceMemory;
1579
- const cap = Number.isFinite(given) && given > 0 ? Math.min(given, MAX_TEXTURE) : MAX_TEXTURE;
1580
- return memory !== undefined && memory <= 2 ? Math.min(cap, 2048) : cap;
1581
- }
1582
- #lost = () => this.#set("lost");
1583
- #restored = () => this.#set("live");
1584
- #set(state) {
1585
- if (this.#state === state)
1586
- return;
1587
- this.#state = state;
1588
- this.dataset["state"] = state;
1589
- }
1590
- #fail(reason) {
1591
- this.#set("unavailable");
1592
- this.dispatchEvent(new CustomEvent("chikyu-unavailable", { detail: { reason } }));
1593
- }
1594
- }
1595
- if (typeof customElements !== "undefined" && !customElements.get("chikyu-space")) {
1596
- customElements.define("chikyu-space", ChikyuSpace);
1597
- }
1
+ // `<chikyu-space>` with every sky culture a page can ask for (`constellation-culture`). Each is a file of its own, loaded only when it is asked for. For a build without them use `space/no-cultures`.
2
+ import "../sky/cultures.js";
3
+ export * from "./element-base.js";