@johnmorrisdotca/chikyu-earth 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
+ import { DEFAULT_LEVELS, tileKeyParts, tilePlace } from "../door/map.js";
1
2
  import { TILE_FRAG, TILE_VERT } from "./shaders.js";
2
3
  import { MAX_TEXTURE, TIERS } from "./tiers.js";
3
- import { coveringTile, parseManifest, tileColumns, tileLevel, tileRect, tileRows, tilesInView } from "./tiles.js";
4
+ import { coveringTile, tileColumns, tileLevel, tileRect, tileRows, tilesInView } from "./tiles.js";
4
5
  /**
5
6
  * The most tiles held at once, day and night together, about a megabyte and a third of graphics memory each (a 512 pixel square with its mipmaps).
6
7
  *
@@ -23,13 +24,51 @@ export const TILE_LIMIT = 48;
23
24
  * ```
24
25
  */
25
26
  export const TILE_KEEP_MS = 4000;
27
+ /**
28
+ * The bytes of decoded tiles the view holds, all sources together: 72 MB, which is the 48 tiles it has always held (`TILE_LIMIT`, a 512 pixel square with its mipmaps is 1.4 MB). A tile that arrives when the view needs every tile it holds,
29
+ * and does not fit, is refused and counted (`stats.refused`): the view draws what it holds.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { TILE_BUDGET } from "@johnmorrisdotca/chikyu-earth/realistic";
34
+ *
35
+ * console.log(TILE_BUDGET / 1024 / 1024);
36
+ * ```
37
+ */
38
+ export const TILE_BUDGET = 72 * 1024 * 1024;
26
39
  const IN_FLIGHT = 6;
27
40
  const NEW_PER_DRAW = 8;
28
- const RETRY_MS = 30_000;
29
41
  // the day mix reaches full light at 0.22: a tile whose darkest point is brighter than that never shows the night picture
30
42
  const NIGHT_BELOW = 0.25;
31
43
  const GRID = 16;
32
44
  const keyOf = (layer, id) => `${layer}/${id.level}/${id.col}/${id.row}`;
45
+ const tags = new WeakMap();
46
+ let tagged = 0;
47
+ /** A name for a source object, so that two sources with the same id never share a tile in the page's cache. */
48
+ const tagOf = (source) => {
49
+ let tag = tags.get(source);
50
+ if (tag === undefined)
51
+ tags.set(source, (tag = tagged += 1));
52
+ return tag;
53
+ };
54
+ /** The levels a source says it has, kept to those the pyramid's rule allows: a tile's place on the sphere would be wrong otherwise. */
55
+ function cleanLayer(given) {
56
+ if (typeof given !== "object" || given === null)
57
+ return undefined;
58
+ const levels = [];
59
+ for (const entry of given.levels instanceof Array ? given.levels : []) {
60
+ if (typeof entry?.level !== "number" || !Number.isInteger(entry.level) || entry.level < 0 || entry.level > 8 || entry.width !== 1024 * 2 ** entry.level)
61
+ continue;
62
+ levels.push({ level: entry.level, width: entry.width });
63
+ }
64
+ return levels.length > 0 ? { tileSize: 512, levels: levels.sort((a, b) => a.level - b.level) } : undefined;
65
+ }
66
+ const isTile = (tile) => {
67
+ if (typeof tile !== "object" || tile === null)
68
+ return false;
69
+ const one = tile;
70
+ return typeof one.width === "number" && one.width > 0 && Number.isFinite(one.width) && typeof one.height === "number" && one.height > 0 && Number.isFinite(one.height) && typeof one.image === "object" && one.image !== null;
71
+ };
33
72
  /** A 0 to 1 grid, the same for every tile: the vertex shader puts it on the sphere. */
34
73
  function patch(three) {
35
74
  const positions = new Float32Array((GRID + 1) * (GRID + 1) * 3);
@@ -62,25 +101,33 @@ function patch(three) {
62
101
  /** Make the set that puts tiles on `parent`, a group that turns with the Earth. */
63
102
  export function createTileSet(three, parent, shared, deps) {
64
103
  const limit = deps.limit ?? TILE_LIMIT;
104
+ const budget = deps.budgetBytes ?? TILE_BUDGET;
65
105
  const clock = deps.now ?? (() => performance.now());
66
106
  const geometry = patch(three);
67
107
  const entries = new Map();
68
108
  const failed = new Map();
69
109
  let queue = [];
70
110
  let wantedKeys = new Set();
71
- let current;
111
+ /** The sources the levels were read for. */
112
+ let current = {};
113
+ /** Counts the times the sources changed: an answer for an earlier set of them is let go. */
114
+ let generation = 0;
115
+ let refused = 0;
72
116
  let manifest;
73
117
  let manifestFetch;
74
118
  let inFlight = 0;
75
119
  let requested = 0;
76
120
  let wantedLevel = null;
77
121
  let shown = 0;
122
+ /** The tiles in view from each source, by the source's id, as of the last placing. */
123
+ let used = new Map();
78
124
  let timer;
79
125
  let last;
80
126
  let disposed = false;
81
127
  const baseDay = TIERS.day[TIERS.day.length - 1];
82
128
  const baseNight = TIERS.night[TIERS.night.length - 1];
83
- const take = (layer, id, base) => deps.assets.acquire(`chikyu-earth:tile:${base}${keyOf(layer, id)}`, () => {
129
+ const accountOf = (source, key) => `chikyu-earth:tile:${tagOf(source)}:${key}`;
130
+ const take = (layer, id, source) => deps.assets.acquire(accountOf(source, keyOf(layer, id)), () => {
84
131
  const texture = new three.Texture();
85
132
  texture.wrapS = three.ClampToEdgeWrapping;
86
133
  texture.wrapT = three.ClampToEdgeWrapping;
@@ -88,19 +135,33 @@ export function createTileSet(three, parent, shared, deps) {
88
135
  texture.magFilter = three.LinearFilter;
89
136
  texture.anisotropy = 8;
90
137
  const controller = new AbortController();
91
- const made = { texture, closed: false, ready: Promise.resolve(), release: () => undefined };
92
- made.ready = fetch(`${base}${keyOf(layer, id)}.webp`, { signal: controller.signal })
93
- .then((response) => {
94
- if (!response.ok)
95
- throw new Error(`${keyOf(layer, id)}: ${response.status}`);
96
- return response.blob();
138
+ const made = { texture, bytes: 0, closed: false, ready: Promise.resolve(), release: () => undefined };
139
+ made.ready = Promise.resolve()
140
+ .then(() => {
141
+ // the source names its tiles: the one for this place is the key of the pyramid's tile that matches
142
+ const key = source.need({ ...tilePlace(id), layer }, 1024 * 2 ** id.level).find((one) => {
143
+ const parts = tileKeyParts(one);
144
+ return parts !== undefined && parts.level === id.level && parts.col === id.col && parts.row === id.row;
145
+ });
146
+ if (key === undefined)
147
+ throw new Error(`${keyOf(layer, id)}: the source "${source.info.id}" names no tile for this place`);
148
+ return source.load(key, controller.signal);
97
149
  })
98
- .then((blob) => createImageBitmap(blob, { premultiplyAlpha: "none", colorSpaceConversion: "none" }))
99
- .then((bitmap) => {
150
+ .then((tile) => {
151
+ if (!isTile(tile)) {
152
+ tile?.image?.close?.();
153
+ throw new TypeError(`${keyOf(layer, id)}: the source "${source.info.id}" gave something that is not a picture`);
154
+ }
155
+ const bytes = source.bytes(tile);
156
+ if (typeof bytes !== "number" || !Number.isFinite(bytes) || bytes < 0) {
157
+ tile.image.close?.();
158
+ throw new TypeError(`${keyOf(layer, id)}: the source "${source.info.id}" gave a tile with a size that is not a number`);
159
+ }
100
160
  if (made.closed)
101
- bitmap.close();
161
+ tile.image.close?.();
102
162
  else {
103
- texture.image = bitmap;
163
+ made.bytes = bytes;
164
+ texture.image = tile.image;
104
165
  texture.needsUpdate = true;
105
166
  }
106
167
  });
@@ -119,8 +180,15 @@ export function createTileSet(three, parent, shared, deps) {
119
180
  parent.remove(entry.mesh);
120
181
  entry.mesh.material.dispose();
121
182
  }
122
- if (current !== undefined)
123
- deps.assets.release(`chikyu-earth:tile:${current}${entry.key}`);
183
+ deps.assets.release(accountOf(entry.source, entry.key));
184
+ };
185
+ /** The bytes of the tiles that have arrived and are held. */
186
+ const heldBytes = () => {
187
+ let sum = 0;
188
+ for (const entry of entries.values())
189
+ if (entry.ready)
190
+ sum += entry.asset.bytes;
191
+ return sum;
124
192
  };
125
193
  const reset = () => {
126
194
  for (const entry of [...entries.values()])
@@ -133,37 +201,49 @@ export function createTileSet(three, parent, shared, deps) {
133
201
  manifest = undefined;
134
202
  wantedLevel = null;
135
203
  shown = 0;
204
+ used = new Map();
205
+ generation += 1;
136
206
  };
137
- const readManifest = (base) => {
207
+ /** Asks each layer's source for its levels, once, when the sources change: a source that has no `levels` has `DEFAULT_LEVELS`, and one that cannot say leaves the layer without tiles. */
208
+ const readManifest = (set) => {
138
209
  manifest = undefined;
139
210
  const controller = new AbortController();
140
211
  manifestFetch = controller;
141
- fetch(`${base}manifest.json`, { signal: controller.signal })
142
- .then((response) => (response.ok ? response.json() : undefined))
143
- .then((json) => {
144
- if (disposed || current !== base || manifestFetch !== controller)
145
- return;
146
- const read = parseManifest(json);
147
- manifest = read ?? null;
148
- if (read) {
149
- deps.onManifest?.(Object.fromEntries(Object.entries(read.layers).map(([name, layer]) => [name, layer.levels[layer.levels.length - 1].width])));
150
- deps.invalidate();
212
+ const turn = generation;
213
+ const ask = async (layer) => {
214
+ const source = set[layer];
215
+ if (source === undefined)
216
+ return undefined;
217
+ try {
218
+ return cleanLayer(source.levels === undefined ? DEFAULT_LEVELS : await source.levels(layer, controller.signal));
151
219
  }
152
- }, () => {
153
- if (!disposed && current === base && manifestFetch === controller)
220
+ catch {
221
+ return undefined;
222
+ }
223
+ };
224
+ void Promise.all([ask("day"), ask("night")]).then(([day, night]) => {
225
+ if (disposed || generation !== turn || manifestFetch !== controller)
226
+ return;
227
+ if (day === undefined) {
154
228
  manifest = null;
229
+ return;
230
+ }
231
+ const layers = night === undefined ? { day } : { day, night };
232
+ manifest = { layers };
233
+ deps.onManifest?.(Object.fromEntries(Object.entries(layers).map(([name, layer]) => [name, layer.levels[layer.levels.length - 1].width])));
234
+ deps.invalidate();
155
235
  });
156
236
  };
157
237
  const pump = () => {
158
- const base = current;
159
- if (base === undefined)
160
- return;
161
238
  while (inFlight < IN_FLIGHT && queue.length > 0) {
162
239
  const next = queue.shift();
163
240
  const key = keyOf(next.layer, next.id);
164
241
  if (entries.has(key))
165
242
  continue;
166
- const entry = { key, layer: next.layer, id: next.id, asset: take(next.layer, next.id, base), ready: false, integrated: false, lastWanted: clock() };
243
+ const source = current[next.layer];
244
+ if (source === undefined)
245
+ continue;
246
+ const entry = { key, layer: next.layer, id: next.id, source, asset: take(next.layer, next.id, source), ready: false, integrated: false, lastWanted: clock() };
167
247
  entries.set(key, entry);
168
248
  inFlight += 1;
169
249
  requested += 1;
@@ -174,7 +254,16 @@ export function createTileSet(three, parent, shared, deps) {
174
254
  entry.asset.ready.then(() => {
175
255
  if (entries.get(key) === entry) {
176
256
  entry.ready = true;
177
- deps.invalidate();
257
+ // a tile that does not fit under the budget even when everything not needed is let go is refused, and counted: the view draws what it holds
258
+ if (heldBytes() > budget)
259
+ sweep(true);
260
+ if (heldBytes() > budget) {
261
+ refused += 1;
262
+ failed.set(key, clock());
263
+ drop(entry);
264
+ }
265
+ else
266
+ deps.invalidate();
178
267
  }
179
268
  settled();
180
269
  }, () => {
@@ -283,6 +372,11 @@ export function createTileSet(three, parent, shared, deps) {
283
372
  };
284
373
  const place = (camera, visible) => {
285
374
  shown = 0;
375
+ used = new Map();
376
+ const nightBy = new Map();
377
+ for (const entry of entries.values())
378
+ if (entry.layer === "night" && entry.integrated && entry.ready)
379
+ nightBy.set(entry.asset.texture, entry);
286
380
  for (const entry of entries.values()) {
287
381
  if (!entry.mesh)
288
382
  continue;
@@ -292,18 +386,26 @@ export function createTileSet(three, parent, shared, deps) {
292
386
  visible.set(entry.id.level, set);
293
387
  }
294
388
  entry.mesh.visible = set.has(entry.id.row * tileColumns(entry.id.level) + entry.id.col);
295
- if (entry.mesh.visible)
389
+ if (entry.mesh.visible) {
296
390
  shown += 1;
391
+ used.set(entry.source.info.id, (used.get(entry.source.info.id) ?? 0) + 1);
392
+ // a night tile is in view when a day tile in view reads it
393
+ const dark = entry.nightMap?.value ? nightBy.get(entry.nightMap.value) : undefined;
394
+ if (dark)
395
+ used.set(dark.source.info.id, (used.get(dark.source.info.id) ?? 0) + 1);
396
+ }
297
397
  }
298
398
  };
299
- /** Free what is no longer wanted: past its time, or the oldest first when over the limit. True when something on the sphere went. */
300
- const sweep = () => {
399
+ /** Free what is no longer wanted: past its time, or the oldest first when over the limit or the budget (`all`: everything not wanted, for room). True when something on the sphere went. */
400
+ const sweep = (all = false) => {
301
401
  const now = clock();
302
402
  let changed = false;
303
403
  const unwanted = [...entries.values()].filter((entry) => !wantedKeys.has(entry.key)).sort((a, b) => a.lastWanted - b.lastWanted);
304
404
  for (const entry of unwanted) {
305
- if (now - entry.lastWanted < TILE_KEEP_MS && entries.size <= limit)
405
+ if (!all && now - entry.lastWanted < TILE_KEEP_MS && entries.size <= limit && heldBytes() <= budget)
306
406
  continue;
407
+ if (all && heldBytes() <= budget)
408
+ break;
307
409
  if (entry.mesh?.visible || entry.integrated)
308
410
  changed = true;
309
411
  drop(entry);
@@ -339,32 +441,36 @@ export function createTileSet(three, parent, shared, deps) {
339
441
  loading: [...entries.values()].filter((entry) => !entry.ready).length,
340
442
  failed: failed.size,
341
443
  requested,
444
+ heldBytes: heldBytes(),
445
+ refused,
446
+ used: Object.fromEntries(used),
342
447
  };
343
448
  },
344
449
  sync(camera, sun, night, ratio) {
345
450
  if (disposed)
346
451
  return;
347
- const base = deps.base();
348
- if (base !== current) {
452
+ const now = deps.sources();
453
+ if (now.day !== current.day || now.night !== current.night) {
349
454
  reset();
350
- current = base;
351
- if (base !== undefined)
352
- readManifest(base);
455
+ current = { ...(now.day ? { day: now.day } : {}), ...(now.night ? { night: now.night } : {}) };
456
+ if (current.day !== undefined)
457
+ readManifest(current);
353
458
  }
354
459
  last = { camera };
355
- if (current === undefined || !manifest)
460
+ if (current.day === undefined || !manifest)
356
461
  return;
357
- const now = clock();
462
+ const at = clock();
358
463
  const wanted = choose(camera, sun, night, ratio);
359
464
  wantedLevel = wanted.level;
360
465
  wantedKeys = new Set([...wanted.day.map((tile) => keyOf("day", tile)), ...wanted.night.map((id) => keyOf("night", id))]);
361
- for (const [key, when] of failed)
362
- if (now - when >= RETRY_MS)
466
+ // a tile that failed is asked for again only after it has left the view and come back (the view changed), never on a timer and never while it stays in view: at rest the door sends nothing
467
+ for (const key of [...failed.keys()])
468
+ if (!wantedKeys.has(key))
363
469
  failed.delete(key);
364
470
  for (const key of wantedKeys) {
365
471
  const entry = entries.get(key);
366
472
  if (entry)
367
- entry.lastWanted = now;
473
+ entry.lastWanted = at;
368
474
  }
369
475
  queue = [...wanted.day.map((tile) => ({ layer: "day", id: { level: tile.level, col: tile.col, row: tile.row } })), ...wanted.night.map((id) => ({ layer: "night", id }))].filter((item) => !failed.has(keyOf(item.layer, item.id)) && !entries.has(keyOf(item.layer, item.id)));
370
476
  pump();
@@ -397,7 +503,7 @@ export function createTileSet(three, parent, shared, deps) {
397
503
  clearTimeout(timer);
398
504
  timer = undefined;
399
505
  reset();
400
- current = undefined;
506
+ current = {};
401
507
  geometry.dispose();
402
508
  },
403
509
  };
@@ -1,5 +1,6 @@
1
1
  import { type ViewController } from "@johnmorrisdotca/kazoku-ui/view-controls";
2
2
  import type { GeoPoint } from "../types.ts";
3
+ import { type BodyLabelSettings } from "../realistic/body-label.ts";
3
4
  import { setThreeLoader } from "../realistic/shared.ts";
4
5
  import type { LightMode } from "../realistic/earth.ts";
5
6
  import type { SatelliteInfo, SatelliteRef, Satellites } from "../satellites/types.ts";
@@ -162,6 +163,15 @@ export declare class ChikyuSpace extends HTMLElement {
162
163
  */
163
164
  get meteorsStrength(): number;
164
165
  set meteorsStrength(value: number);
166
+ /**
167
+ * 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:
168
+ * `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),
169
+ * `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.
170
+ * 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`
171
+ * and `AdditiveBlending`; without them `chikyu-body-label-unavailable` is sent and the name is not drawn.
172
+ */
173
+ get bodyLabel(): BodyLabelSettings | null;
174
+ set bodyLabel(value: Partial<BodyLabelSettings> | null);
165
175
  /**
166
176
  * 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
167
177
  * under the picture (`air-label="off"` takes the line away, for a page that says it itself).
@@ -315,6 +325,13 @@ export declare class ChikyuSpace extends HTMLElement {
315
325
  shower: string | null;
316
326
  zhr: number;
317
327
  };
328
+ /** The name written on the Earth: whether `body-label` is set, its text, the label is made, and it is showing (it is hidden while the Earth is small). */
329
+ bodyLabel: {
330
+ on: boolean;
331
+ text: string;
332
+ made: boolean;
333
+ showing: boolean;
334
+ };
318
335
  };
319
336
  }
320
337
  declare global {
@@ -1,6 +1,7 @@
1
1
  import { carryControls } from "@johnmorrisdotca/kazoku-ui/view-controls";
2
2
  import { adoptStyles } from "../adopt.js";
3
3
  import { airFor, readAirThickness } from "../realistic/air.js";
4
+ import { BODY_LABEL_ATTRIBUTES, bodyLabelText, readBodyLabel } from "../realistic/body-label.js";
4
5
  import { createGate, frameCap } from "../realistic/gate.js";
5
6
  import { setThreeLoader, takeRenderer } from "../realistic/shared.js";
6
7
  import { NOTES_STYLE, setAirNote } from "../realistic/air-note.js";
@@ -100,7 +101,7 @@ const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:h
100
101
  * ```
101
102
  */
102
103
  export class ChikyuSpace extends HTMLElement {
103
- static observedAttributes = ["cloud-drift", "camera", "earth-size", "earth-x", "earth-y", "center", "time", "speed", "scale", "labels", "orbits", "bodies", "light", "meteors", "meteors-label", "meteors-strength", "air-thickness", "air-label", "lang"];
104
+ 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, "air-thickness", "air-label", "lang"];
104
105
  #model = newSpaceModel();
105
106
  #mode = "now";
106
107
  #speed = 1;
@@ -158,6 +159,7 @@ export class ChikyuSpace extends HTMLElement {
158
159
  this.#note = root.getElementById("meteor-note");
159
160
  this.#airNote = root.getElementById("air-note");
160
161
  this.#model.airThickness = readAirThickness(this.getAttribute("air-thickness"));
162
+ this.#applyBodyLabel();
161
163
  setAirNote(this.#airNote, this, this.#model.airThickness);
162
164
  this.#played = false;
163
165
  this.#model.meteors.on = this.#meteorsAsked();
@@ -186,6 +188,7 @@ export class ChikyuSpace extends HTMLElement {
186
188
  this.#tiers[layer] = width;
187
189
  },
188
190
  onLabels: (places) => this.#placeLabels(places),
191
+ onLabelError: (error) => this.dispatchEvent(new CustomEvent("chikyu-body-label-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
189
192
  onSelected: (place) => this.#placeChosen(place),
190
193
  onMoving: () => this.#gate?.request(),
191
194
  onRideLost: () => this.#rideLost(),
@@ -263,8 +266,13 @@ export class ChikyuSpace extends HTMLElement {
263
266
  this.#model.airThickness = readAirThickness(value);
264
267
  this.#gate?.request();
265
268
  }
266
- else if (name === "meteors-label" || name === "lang")
269
+ else if (name === "meteors-label" || name === "lang") {
267
270
  setMeteorNote(this.#note, this, this.#model.meteors.on);
271
+ if (name === "lang")
272
+ this.#applyBodyLabel();
273
+ }
274
+ else if (BODY_LABEL_ATTRIBUTES.includes(name))
275
+ this.#applyBodyLabel();
268
276
  if (name === "air-thickness" || name === "air-label" || name === "lang")
269
277
  setAirNote(this.#airNote, this, this.#model.airThickness);
270
278
  }
@@ -303,6 +311,41 @@ export class ChikyuSpace extends HTMLElement {
303
311
  set meteorsStrength(value) {
304
312
  this.setAttribute("meteors-strength", String(value));
305
313
  }
314
+ /**
315
+ * 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:
316
+ * `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),
317
+ * `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.
318
+ * 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`
319
+ * and `AdditiveBlending`; without them `chikyu-body-label-unavailable` is sent and the name is not drawn.
320
+ */
321
+ get bodyLabel() {
322
+ return readBodyLabel((name) => this.getAttribute(name));
323
+ }
324
+ set bodyLabel(value) {
325
+ for (const name of BODY_LABEL_ATTRIBUTES)
326
+ this.removeAttribute(name);
327
+ if (value === null)
328
+ return;
329
+ this.setAttribute("body-label", value.look ?? "painted");
330
+ if (value.strength !== undefined)
331
+ this.setAttribute("body-label-strength", String(value.strength));
332
+ if (value.repeat !== undefined)
333
+ this.setAttribute("body-label-repeat", value.repeat);
334
+ if (value.latitude !== undefined)
335
+ this.setAttribute("body-label-latitude", String(value.latitude));
336
+ if (value.facing)
337
+ this.setAttribute("body-label-facing", "");
338
+ if (value.font)
339
+ this.setAttribute("body-label-font", value.font);
340
+ if (value.fallbackFont)
341
+ this.setAttribute("body-label-fallback-font", value.fallbackFont);
342
+ }
343
+ /** Puts the name's settings and text right from the attributes (`body-label` and its family, `lang`). */
344
+ #applyBodyLabel() {
345
+ this.#model.bodyLabel.settings = readBodyLabel((name) => this.getAttribute(name));
346
+ this.#model.bodyLabel.text = bodyLabelText((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en");
347
+ this.#gate?.request();
348
+ }
306
349
  /**
307
350
  * 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
308
351
  * under the picture (`air-label="off"` takes the line away, for a page that says it itself).
@@ -661,6 +704,7 @@ export class ChikyuSpace extends HTMLElement {
661
704
  camera: { position: [this.#model.pose.p[0], this.#model.pose.p[1], this.#model.pose.p[2]], fov: this.#model.pose.fov },
662
705
  bodies: { look: this.#model.bodies || painter?.looks?.[0] || "plain", painted: this.#model.painted.bodies, moons: this.#model.painted.moons },
663
706
  meteors: { on: this.#model.meteors.on, strength: this.#model.meteors.strength, ...this.#model.meteors.drawn },
707
+ bodyLabel: { on: this.#model.bodyLabel.settings !== null, text: this.#model.bodyLabel.text, ...this.#model.bodyLabel.drawn },
664
708
  };
665
709
  }
666
710
  #satelliteStats() {
@@ -8,6 +8,7 @@ import { type ScaleMode } from "./scale.ts";
8
8
  import type { SatelliteRef } from "../satellites/types.ts";
9
9
  import { type RideLook } from "./ride.ts";
10
10
  import { type SatelliteState } from "./satellite-layer.ts";
11
+ import { type BodyLabelState } from "../realistic/body-label.ts";
11
12
  import { type MeteorState } from "../meteors/layer.ts";
12
13
  type Three = ThreeParts;
13
14
  /** How much of the view's shorter side the Earth's disc fills at zoom 1 when the page does not say: 0.9, so the atmosphere's glow (8% beyond the disc) is inside the view and never cut. */
@@ -152,6 +153,8 @@ export interface SpaceModel {
152
153
  satellites: SatelliteState;
153
154
  /** Meteors seen from space, on the Earth (src/meteors/layer.ts): off unless the element switches them on. */
154
155
  meteors: MeteorState;
156
+ /** The name written on the Earth (src/realistic/body-label.ts): off unless the element sets it. */
157
+ bodyLabel: BodyLabelState;
155
158
  /** The body or satellite the camera rides along with, or null. */
156
159
  ride: RideState | null;
157
160
  /** Set at each draw: the target of the ride could not be placed (a satellite whose elements are too old, or that is gone), so the ordinary camera was used. */
@@ -280,6 +283,8 @@ export interface SpaceDeps {
280
283
  air?: () => "full" | "light";
281
284
  /** Where each body is on the screen, in CSS pixels in the box, or null when it is behind the camera. Called at each draw. */
282
285
  onLabels?: (places: Record<BodyName, BodyPlace | null>) => void;
286
+ /** The name written on the Earth could not be made. */
287
+ onLabelError?: (error: unknown) => void;
283
288
  /** Where the chosen satellite is on the screen, or null. Called at each draw while a satellite is chosen (and once when it is let go). */
284
289
  onSelected?: (place: {
285
290
  x: number;
@@ -6,6 +6,7 @@ import { createTrack, orbitPath, PLANETS } from "./ephemeris.js";
6
6
  import { placeAround, placeMoon, placeSun, RADIUS } from "./scale.js";
7
7
  import { ridePose } from "./ride.js";
8
8
  import { createSatelliteLayer, newSatelliteState } from "./satellite-layer.js";
9
+ import { createBodyLabelLayer, newBodyLabelState } from "../realistic/body-label.js";
9
10
  import { createMeteorLayer, newMeteorState } from "../meteors/layer.js";
10
11
  import { subsolarPoint, unitVector } from "../realistic/sun.js";
11
12
  const RAD = Math.PI / 180;
@@ -81,6 +82,7 @@ export const newSpaceModel = () => ({
81
82
  rideMotion: 0,
82
83
  satellites: newSatelliteState(),
83
84
  meteors: newMeteorState(),
85
+ bodyLabel: newBodyLabelState(),
84
86
  pick: null,
85
87
  ratio: () => Math.min(globalThis.devicePixelRatio || 1, 2),
86
88
  });
@@ -263,6 +265,7 @@ export function createSpaceItem(model, deps) {
263
265
  let releaseTimer;
264
266
  let meteors = null;
265
267
  let meteorTimer;
268
+ let nameOn = null;
266
269
  let layer;
267
270
  const rideState = new Float64Array(6);
268
271
  let selectedShown = false;
@@ -587,6 +590,10 @@ export function createSpaceItem(model, deps) {
587
590
  }
588
591
  deps.onLabels(places);
589
592
  }
593
+ // the name written on the Earth: made the first time the settings ask for it; none while a ride along a body hides the Earth
594
+ if (model.bodyLabel.settings && !nameOn)
595
+ nameOn = createBodyLabelLayer(three, earth, model.bodyLabel, { invalidate: () => deps.invalidate(), ...(deps.onLabelError ? { onError: deps.onLabelError } : {}) });
596
+ nameOn?.sync(camera, rideFrom ? 0 : Math.min(px.Earth, 1e5));
590
597
  if (layer && deps.onSelected) {
591
598
  const at = model.satellites.selected ? layer.place(camera, size) : null;
592
599
  if (at || selectedShown)
@@ -622,6 +629,7 @@ export function createSpaceItem(model, deps) {
622
629
  if (meteorTimer !== undefined)
623
630
  clearTimeout(meteorTimer);
624
631
  meteors?.dispose();
632
+ nameOn?.dispose();
625
633
  layer?.dispose();
626
634
  model.pick = null;
627
635
  textures.dispose();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnmorrisdotca/chikyu-earth",
3
- "version": "0.30.0",
3
+ "version": "0.32.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",
@@ -119,6 +119,11 @@
119
119
  "import": "./dist/space/element.js",
120
120
  "default": "./dist/space/element.js"
121
121
  },
122
+ "./door": {
123
+ "types": "./dist/door/index.d.ts",
124
+ "import": "./dist/door/index.js",
125
+ "default": "./dist/door/index.js"
126
+ },
122
127
  "./meteors": {
123
128
  "types": "./dist/meteors/index.d.ts",
124
129
  "import": "./dist/meteors/index.js",
@@ -185,7 +190,7 @@
185
190
  },
186
191
  "dependencies": {
187
192
  "@johnmorrisdotca/chizu": "^1.6.0",
188
- "@johnmorrisdotca/kazoku-ui": "^0.27.0",
193
+ "@johnmorrisdotca/kazoku-ui": "^0.36.0",
189
194
  "d3-geo": "^3.1.1"
190
195
  },
191
196
  "peerDependencies": {