@johnmorrisdotca/chikyu-earth 0.30.0 → 0.31.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.
@@ -10,6 +10,9 @@ import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
10
10
  import { MAX_ORBIT_GROUP } from "../space/satellite-layer.js";
11
11
  import { readMeteorStrength } from "../meteors/strength.js";
12
12
  import { METEOR_NOTE_STYLE, prefersLessMotion, setMeteorNote } from "../meteors/note.js";
13
+ import { createDoorHost } from "../door/host.js";
14
+ import { folderSource } from "../door/map.js";
15
+ import { ownCredit } from "../door/own.js";
13
16
  import { createGate, frameCap } from "./gate.js";
14
17
  import { setSharedRenderer, setThreeLoader, takeRenderer } from "./shared.js";
15
18
  export { setSharedRenderer, setThreeLoader };
@@ -125,7 +128,7 @@ export const readTime = (value) => {
125
128
  * ```
126
129
  */
127
130
  export class ChikyuEarthRealistic extends HTMLElement {
128
- static observedAttributes = ["cloud-drift", "center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "camera", "immersive", "meteors", "meteors-label", "meteors-strength", "air-thickness", "air-label", "lang"];
131
+ static observedAttributes = ["cloud-drift", "center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "data", "camera", "immersive", "meteors", "meteors-label", "meteors-strength", "air-thickness", "air-label", "lang"];
129
132
  #model = newModel();
130
133
  #mode = "now";
131
134
  #view;
@@ -141,6 +144,11 @@ export class ChikyuEarthRealistic extends HTMLElement {
141
144
  #state = "loading";
142
145
  #tiers = { day: TIERS.day[0], night: TIERS.night[0], clouds: TIERS.clouds[0], water: TIERS.water[0] };
143
146
  #taken;
147
+ /** The data door: the outside sources of map this Earth draws from, and whose data is on the screen. */
148
+ #door = createDoorHost(this, {
149
+ own: () => this.#ownCredits(),
150
+ used: () => new Map(Object.entries(this.#model.tiles?.stats.used ?? {})),
151
+ }, { kinds: ["tiles"] }, () => this.#gate?.soon());
144
152
  #stage;
145
153
  #overlay;
146
154
  #pose = null;
@@ -170,6 +178,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
170
178
  this.#model.camera = readCamera(this.getAttribute("camera"));
171
179
  this.#model.cloudDrift = readDrift(this.getAttribute("cloud-drift"));
172
180
  this.#model.airThickness = readAirThickness(this.getAttribute("air-thickness"));
181
+ this.#door.book.ownOnly(this.getAttribute("data") === "own");
173
182
  this.#model.speed = this.speed;
174
183
  if (!this.hasAttribute("role"))
175
184
  this.setAttribute("role", "img");
@@ -207,17 +216,20 @@ export class ChikyuEarthRealistic extends HTMLElement {
207
216
  assets: taken.renderer.assets,
208
217
  textureBase: () => this.#textureBase(),
209
218
  cap: () => this.#textureCap(),
210
- tiles: () => this.tiles ?? undefined,
219
+ sources: () => this.#tileSources(),
211
220
  onTiles: (layers) => {
212
221
  if (!this.hasAttribute("zoom-max") || this.getAttribute("zoom-max") === this.#reach) {
213
222
  this.#reach = TILES_ZOOM_MAX;
214
- this.setAttribute("zoom-max", TILES_ZOOM_MAX);
223
+ // not written again when it is already there: the view controls take a written attribute as a new limit and bring the view back to fit, which a change of source must not do to a reader's zoom
224
+ if (this.getAttribute("zoom-max") !== TILES_ZOOM_MAX)
225
+ this.setAttribute("zoom-max", TILES_ZOOM_MAX);
215
226
  }
216
227
  this.dispatchEvent(new CustomEvent("chikyu-tiles", { detail: { layers } }));
217
228
  },
218
229
  air: () => airFor(this.getAttribute("air")),
219
230
  invalidate: () => this.#gate?.soon(),
220
231
  onDraw: () => this.#gate?.drawn(),
232
+ onTiled: () => this.#door.announce(),
221
233
  onPose: (pose) => {
222
234
  if (this.#hands)
223
235
  this.#hands.controller.grabRadius = discRadius(pose.width, pose.height, 1);
@@ -291,6 +303,8 @@ export class ChikyuEarthRealistic extends HTMLElement {
291
303
  this.#startTick();
292
304
  else if (name === "tiles")
293
305
  this.#gate?.soon();
306
+ else if (name === "data")
307
+ this.#door.book.ownOnly(value === "own");
294
308
  else if (name === "camera")
295
309
  this.camera = readCamera(value);
296
310
  else if (name === "cloud-drift") {
@@ -362,6 +376,50 @@ export class ChikyuEarthRealistic extends HTMLElement {
362
376
  get controller() {
363
377
  return this.#hands?.controller;
364
378
  }
379
+ /** The map source of each layer now: the last one a page added for it, else the folder of the `tiles` attribute. */
380
+ #tileSources() {
381
+ const folder = this.tiles === null ? undefined : folderSource(this.tiles);
382
+ const day = this.#door.book.mapSources("day")[0] ?? folder;
383
+ const night = this.#door.book.mapSources("night")[0] ?? folder;
384
+ return { ...(day ? { day } : {}), ...(night ? { night } : {}) };
385
+ }
386
+ /** The package's own credits for the last drawn frame: its pictures while it is drawn, and its finer tiles when a window of them is in view (unless a page added the folder itself, which the door counts). */
387
+ #ownCredits() {
388
+ const used = this.#model.tiles?.stats.used ?? {};
389
+ const own = [ownCredit("chikyu-pictures", this.#state === "live" ? 1 : 0)];
390
+ if (this.#door.book.get("chikyu-tiles") === undefined)
391
+ own.push(ownCredit("chikyu-tiles", used["chikyu-tiles"] ?? 0));
392
+ return own;
393
+ }
394
+ /**
395
+ * The outside sources of map this Earth draws from (the data door): each carries its own licence and credit, and a map source for the `day` or `night` layer takes the place of the folder of tiles for that layer. Assign a list to
396
+ * replace them; a source that is refused (an empty credit, no licence, a clashing id, a kind the Earth does not draw, a layer it does not know) throws a `TypeError` and nothing changes. A property, never an attribute: data is not text.
397
+ */
398
+ get sources() {
399
+ return this.#door.sources();
400
+ }
401
+ set sources(list) {
402
+ this.#door.setSources(list);
403
+ }
404
+ /** Adds an outside source of map: checked at once (a `TypeError` for one that is refused), and the Earth draws from it. Returns the function that takes it away. */
405
+ addSource(source) {
406
+ return this.#door.book.addSource(source);
407
+ }
408
+ /** Takes a source away by its id: its loads stop, its tiles are freed, its credit goes. Returns whether there was one. */
409
+ removeSource(id) {
410
+ return this.#door.book.removeSource(id);
411
+ }
412
+ /** Switches a source off (`false`) or on again, and keeps it in the Earth: a layers panel's switch. The attribute `data="own"` ignores every outside source at once. */
413
+ enableSource(id, on) {
414
+ this.#door.book.enableSource(id, on);
415
+ }
416
+ /**
417
+ * Whose data is in the last drawn frame: the package's own first (its pictures; its finer tiles while a window of them is in view) and then each outside source that gave a tile, with how many (`used`). `creditLine(credits, "en" | "ja")`
418
+ * from `@johnmorrisdotca/chikyu-earth/door` writes them as a line with the licences. `chikyu-creditschange` fires when this set changes (not at each frame), with `detail: { credits }`.
419
+ */
420
+ credits() {
421
+ return this.#door.credits();
422
+ }
365
423
  /** Where the finer map tiles are served from (a folder with `manifest.json`), or `null` for none; the attribute `tiles`. The Earth loads only the tiles in view, over its own pictures. */
366
424
  get tiles() {
367
425
  const given = this.getAttribute("tiles");
@@ -486,7 +544,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
486
544
  state: this.#state,
487
545
  tiers: { ...this.#tiers },
488
546
  satellites: this.#satelliteStats(),
489
- tiles: this.#model.tiles?.stats ?? { ready: false, level: null, held: 0, shown: 0, loading: 0, failed: 0, requested: 0 },
547
+ tiles: this.#model.tiles?.stats ?? { ready: false, level: null, held: 0, shown: 0, loading: 0, failed: 0, requested: 0, heldBytes: 0, refused: 0, used: {} },
490
548
  draws: stats?.draws ?? 0,
491
549
  contexts: stats?.contexts ?? 0,
492
550
  canvas: stats?.canvas ?? { width: 0, height: 0, pixels: 0 },
@@ -1,5 +1,6 @@
1
1
  import type * as THREE from "three";
2
2
  import type { AssetCache } from "@johnmorrisdotca/kazoku-ui/renderer";
3
+ import { type EarthMapSource } from "../door/map.ts";
3
4
  import type { ThreeParts } from "./textures.ts";
4
5
  import { type TileCamera } from "./tiles.ts";
5
6
  /**
@@ -24,6 +25,18 @@ export declare const TILE_LIMIT = 48;
24
25
  * ```
25
26
  */
26
27
  export declare const TILE_KEEP_MS = 4000;
28
+ /**
29
+ * 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,
30
+ * and does not fit, is refused and counted (`stats.refused`): the view draws what it holds.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { TILE_BUDGET } from "@johnmorrisdotca/chikyu-earth/realistic";
35
+ *
36
+ * console.log(TILE_BUDGET / 1024 / 1024);
37
+ * ```
38
+ */
39
+ export declare const TILE_BUDGET: number;
27
40
  type Three = ThreeParts;
28
41
  type Uniform<T> = {
29
42
  value: T;
@@ -40,10 +53,17 @@ export interface TileShared {
40
53
  /** More uniforms the surface program reads (the cloud picture and where the Sun is in the Earth's axes), shared with the sphere's own. */
41
54
  extra?: Record<string, Uniform<unknown>>;
42
55
  }
56
+ /** The map source each layer is drawn from now, or none: read at every draw. A layer's tiles come from its source alone, and the night tiles go with day tiles (no day source, no tiles). */
57
+ export type TileSources = {
58
+ day?: EarthMapSource;
59
+ night?: EarthMapSource;
60
+ };
43
61
  export interface TileSetDeps {
44
62
  assets: AssetCache;
45
- /** Where the tile set is, ending with a slash, or `undefined` for none. Read at every draw. */
46
- base: () => string | undefined;
63
+ /** The sources of the layers now (the data door's: a source a page added, else the `tiles` folder). Read at every draw; the objects are the same while nothing changed. */
64
+ sources: () => TileSources;
65
+ /** The bytes of decoded tiles held, all sources together: `TILE_BUDGET` where left out. */
66
+ budgetBytes?: number;
47
67
  /** The widest picture this device holds: tiles are only used where the day picture reaches 4096. */
48
68
  cap: () => number;
49
69
  /** Ask for one draw. */
@@ -67,6 +87,11 @@ export interface TileStats {
67
87
  failed: number;
68
88
  /** Tile fetches made. */
69
89
  requested: number;
90
+ /** The bytes of decoded tiles held, which never pass the budget except by tiles the view needs now, and tiles that arrived and did not fit, which are not held. */
91
+ heldBytes: number;
92
+ refused: number;
93
+ /** The tiles in view that came from each source, by the source's id: what a credit line counts. */
94
+ used: Record<string, number>;
70
95
  }
71
96
  export interface TileSet {
72
97
  sync(camera: TileCamera, sun: readonly [number, number, number], night: boolean, ratio: number): void;
@@ -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
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnmorrisdotca/chikyu-earth",
3
- "version": "0.30.0",
3
+ "version": "0.31.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",