@johnmorrisdotca/wakusei-planets 0.45.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/NOTICE.md +11 -0
- package/README.md +4 -3
- package/dist/scene/textures.d.ts +2 -2
- package/dist/space/element.d.ts +7 -0
- package/dist/space/element.js +12 -0
- package/dist/surface/detail.d.ts +169 -0
- package/dist/surface/detail.js +292 -0
- package/dist/surface/element.d.ts +90 -0
- package/dist/surface/element.js +482 -0
- package/dist/surface/glsl.d.ts +20 -0
- package/dist/surface/glsl.js +403 -0
- package/dist/surface/height.d.ts +257 -0
- package/dist/surface/height.js +232 -0
- package/dist/surface/index.d.ts +8 -0
- package/dist/surface/index.js +8 -0
- package/dist/surface/land.d.ts +111 -0
- package/dist/surface/land.js +261 -0
- package/dist/surface/load.d.ts +133 -0
- package/dist/surface/load.js +183 -0
- package/dist/surface/rocks.d.ts +45 -0
- package/dist/surface/rocks.js +166 -0
- package/dist/surface/scene.d.ts +64 -0
- package/dist/surface/scene.js +323 -0
- package/dist/surface/site.d.ts +58 -0
- package/dist/surface/site.js +38 -0
- package/dist/surface/sky.d.ts +81 -0
- package/dist/surface/sky.js +60 -0
- package/dist/surface/view.d.ts +129 -0
- package/dist/surface/view.js +139 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +23 -1
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { siteById } from "./site.js";
|
|
2
|
+
const landings = new WeakMap();
|
|
3
|
+
const FADE_MS = 700;
|
|
4
|
+
const GLIDE_MS = 950;
|
|
5
|
+
const reduced = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
6
|
+
const frame = () => new Promise((resolve) => (typeof requestAnimationFrame === "function" ? requestAnimationFrame(() => resolve()) : setTimeout(resolve, 16)));
|
|
7
|
+
const sleep = (ms, landing) => new Promise((resolve) => {
|
|
8
|
+
const timer = setTimeout(resolve, ms);
|
|
9
|
+
landing.wake = () => {
|
|
10
|
+
clearTimeout(timer);
|
|
11
|
+
resolve();
|
|
12
|
+
};
|
|
13
|
+
});
|
|
14
|
+
/** Wait while a test is true, a frame at a time, until it is false, the landing is cancelled or the time is up. */
|
|
15
|
+
async function waitWhile(landing, still, ms) {
|
|
16
|
+
const end = performance.now() + ms;
|
|
17
|
+
while (still() && !landing.cancelled) {
|
|
18
|
+
if (performance.now() > end)
|
|
19
|
+
return false;
|
|
20
|
+
await frame();
|
|
21
|
+
}
|
|
22
|
+
return !landing.cancelled;
|
|
23
|
+
}
|
|
24
|
+
const note = (space, type, site) => {
|
|
25
|
+
space.dispatchEvent(new CustomEvent(type, { detail: { site: site.id, name: site.name }, bubbles: true, composed: true }));
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The site the person is standing at over this orbit view, or `null` while in orbit (and while still coming down).
|
|
29
|
+
*
|
|
30
|
+
* @param space - The orbit view.
|
|
31
|
+
* @returns The site's name, as in `SURFACE_SITES`; `null` while in orbit or still coming down.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* import { landedAt } from "@johnmorrisdotca/wakusei-planets/surface/land";
|
|
36
|
+
*
|
|
37
|
+
* console.log(landedAt({} as never));
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export function landedAt(space) {
|
|
41
|
+
const landing = landings.get(space);
|
|
42
|
+
return landing?.down === true ? landing.site.id : null;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The standing view put over the orbit view, while coming down or standing, or `null`: for a page that sets its attributes (the Sun's moment, where to look) or listens to it.
|
|
46
|
+
*
|
|
47
|
+
* @param space - The orbit view.
|
|
48
|
+
* @returns The `<wakusei-surface>` element; `null` when no landing is under way or done.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* import { surfaceOf } from "@johnmorrisdotca/wakusei-planets/surface/land";
|
|
53
|
+
*
|
|
54
|
+
* console.log(surfaceOf({} as never));
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export function surfaceOf(space) {
|
|
58
|
+
return landings.get(space)?.surface ?? null;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Come down to a site from the orbit view in one move: the camera goes to the Moon if it is not there, turns over the site and comes in to the Moon's closest zoom, the standing view is made and its ground
|
|
62
|
+
* loaded meanwhile, and it fades in over the picture. `wakusei-landing` is sent when it starts and `wakusei-landed` (with the site) when the person is standing. Resolves the standing view; rejects when there is
|
|
63
|
+
* no such site, the view cannot be drawn, the ground does not come in time, or `leave` is called first.
|
|
64
|
+
*
|
|
65
|
+
* @param space - The orbit view, with the Moon in it.
|
|
66
|
+
* @param siteId - A site's name from `SURFACE_SITES`.
|
|
67
|
+
* @param options - Where the tiles are, the moment, where to look first, and whether to move smoothly.
|
|
68
|
+
* @returns The `<wakusei-surface>` element, standing.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts no-run
|
|
72
|
+
* import "@johnmorrisdotca/wakusei-planets/space/element";
|
|
73
|
+
* import { land, leave } from "@johnmorrisdotca/wakusei-planets/surface/land";
|
|
74
|
+
*
|
|
75
|
+
* const space = document.querySelector("wakusei-space")!;
|
|
76
|
+
* space.addEventListener("wakusei-landed", (event) => console.log("down at", (event as CustomEvent).detail.site));
|
|
77
|
+
* await land(space, "apollo-17");
|
|
78
|
+
* await leave(space);
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export async function land(space, siteId, options = {}) {
|
|
82
|
+
const site = siteById(siteId);
|
|
83
|
+
if (site === undefined)
|
|
84
|
+
throw new Error(`no site called ${siteId}`);
|
|
85
|
+
const before = landings.get(space);
|
|
86
|
+
if (before !== undefined) {
|
|
87
|
+
if (before.site.id === site.id && before.down)
|
|
88
|
+
return before.surface;
|
|
89
|
+
// another site, or one still coming down: that landing is called off first
|
|
90
|
+
await leave(space);
|
|
91
|
+
}
|
|
92
|
+
const root = space.shadowRoot;
|
|
93
|
+
if (root === null)
|
|
94
|
+
throw new Error("the orbit view is not connected");
|
|
95
|
+
const smooth = options.smooth !== false && !reduced();
|
|
96
|
+
// the standing view goes in at once (it is made when its element is known, a moment after), so that `leave` can call the landing off from the first moment
|
|
97
|
+
const surface = document.createElement("wakusei-surface");
|
|
98
|
+
surface.setAttribute("site", site.id);
|
|
99
|
+
surface.setAttribute("lang", space.getAttribute("lang") === "ja" ? "ja" : "en");
|
|
100
|
+
if (options.tiles !== undefined)
|
|
101
|
+
surface.setAttribute("tiles", options.tiles);
|
|
102
|
+
surface.setAttribute("time", String(options.time === "landing" ? site.time : (options.time ?? space.time)));
|
|
103
|
+
const look = options.look ?? {};
|
|
104
|
+
if (look.heading !== undefined)
|
|
105
|
+
surface.setAttribute("heading", String(look.heading));
|
|
106
|
+
if (look.pitch !== undefined)
|
|
107
|
+
surface.setAttribute("pitch", String(look.pitch));
|
|
108
|
+
if (look.fov !== undefined)
|
|
109
|
+
surface.setAttribute("fov", String(look.fov));
|
|
110
|
+
surface.setAttribute("data-landing", "");
|
|
111
|
+
// on standby: the ground is fetched while the camera comes in, and the renderer stays the orbit view's until the veil is down
|
|
112
|
+
surface.setAttribute("standby", "");
|
|
113
|
+
surface.style.cssText = "position:absolute;inset:0;width:100%;height:100%;z-index:5;touch-action:none;visibility:hidden";
|
|
114
|
+
const veil = document.createElement("div");
|
|
115
|
+
veil.setAttribute("data-landing-veil", "");
|
|
116
|
+
veil.style.cssText = `position:absolute;inset:0;background:#000;opacity:0;pointer-events:none;z-index:6;transition:opacity ${smooth ? FADE_MS : 0}ms ease`;
|
|
117
|
+
const landing = { site, surface, veil, down: false, cancelled: false };
|
|
118
|
+
landings.set(space, landing);
|
|
119
|
+
root.append(surface, veil);
|
|
120
|
+
note(space, "wakusei-landing", site);
|
|
121
|
+
const fail = (message) => {
|
|
122
|
+
if (landings.get(space) === landing)
|
|
123
|
+
landings.delete(space);
|
|
124
|
+
surface.remove();
|
|
125
|
+
veil.remove();
|
|
126
|
+
throw new Error(message);
|
|
127
|
+
};
|
|
128
|
+
try {
|
|
129
|
+
await import("./element.js");
|
|
130
|
+
// the orbit view turns to a site by its place in the Moon's list: where the page has given the views no lists, the package's own are given
|
|
131
|
+
const { placesLoader, setPlacesLoader } = await import("../scene/place-layer.js");
|
|
132
|
+
if (placesLoader() === undefined)
|
|
133
|
+
setPlacesLoader((await import("../places.js")).loadPlaces);
|
|
134
|
+
if (landing.cancelled)
|
|
135
|
+
throw new Error("the landing was called off");
|
|
136
|
+
// the camera: to the Moon, then over the site and in to the closest zoom, while the standing view loads behind
|
|
137
|
+
if (space.body !== "moon") {
|
|
138
|
+
space.goTo("moon", { smooth });
|
|
139
|
+
if (smooth) {
|
|
140
|
+
await frame();
|
|
141
|
+
await waitWhile(landing, () => space.stats.ride.gliding || space.stats.travelling !== null, 60_000);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (landing.cancelled)
|
|
145
|
+
throw new Error("the landing was called off");
|
|
146
|
+
const place = await space.goToPlace(site.place, { body: "moon", smooth, zoom: 3.6 });
|
|
147
|
+
if (place === undefined)
|
|
148
|
+
fail(`the orbit view has no place ${site.place}`);
|
|
149
|
+
if (smooth)
|
|
150
|
+
await sleep(GLIDE_MS, landing);
|
|
151
|
+
if (smooth)
|
|
152
|
+
await waitWhile(landing, () => space.stats.pictures.pending > 0, 3000);
|
|
153
|
+
// the ground is in (on standby), or why it cannot be
|
|
154
|
+
const loaded = await waitWhile(landing, () => !surface.loaded && surface.getAttribute("data-state") !== "unavailable", options.timeout ?? 20_000);
|
|
155
|
+
if (landing.cancelled)
|
|
156
|
+
throw new Error("the landing was called off");
|
|
157
|
+
if (!loaded)
|
|
158
|
+
fail("the ground did not come in time");
|
|
159
|
+
if (surface.getAttribute("data-state") === "unavailable")
|
|
160
|
+
fail("this device cannot draw the ground");
|
|
161
|
+
// the veil comes down over the orbit view, the standing view takes the renderer behind it, and the veil goes up on the ground
|
|
162
|
+
veil.style.opacity = "1";
|
|
163
|
+
if (smooth)
|
|
164
|
+
await sleep(FADE_MS, landing);
|
|
165
|
+
if (landing.cancelled)
|
|
166
|
+
throw new Error("the landing was called off");
|
|
167
|
+
surface.style.visibility = "visible";
|
|
168
|
+
surface.removeAttribute("standby");
|
|
169
|
+
const live = await waitWhile(landing, () => surface.getAttribute("data-state") !== "live" && surface.getAttribute("data-state") !== "unavailable", options.timeout ?? 20_000);
|
|
170
|
+
if (landing.cancelled)
|
|
171
|
+
throw new Error("the landing was called off");
|
|
172
|
+
if (!live || surface.getAttribute("data-state") === "unavailable") {
|
|
173
|
+
// the orbit view gets the renderer back before the error
|
|
174
|
+
surface.remove();
|
|
175
|
+
await space.resume();
|
|
176
|
+
veil.style.opacity = "0";
|
|
177
|
+
fail(live ? "this device cannot draw the ground" : "the ground did not come in time");
|
|
178
|
+
}
|
|
179
|
+
veil.style.opacity = "0";
|
|
180
|
+
if (smooth)
|
|
181
|
+
await sleep(FADE_MS, landing);
|
|
182
|
+
if (landing.cancelled)
|
|
183
|
+
throw new Error("the landing was called off");
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (landings.get(space) === landing && !landing.cancelled) {
|
|
187
|
+
landings.delete(space);
|
|
188
|
+
surface.remove();
|
|
189
|
+
veil.remove();
|
|
190
|
+
}
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
landing.down = true;
|
|
194
|
+
surface.setAttribute("tabindex", "0");
|
|
195
|
+
surface.addEventListener("keydown", (event) => {
|
|
196
|
+
if (event.key === "Escape")
|
|
197
|
+
void leave(space);
|
|
198
|
+
});
|
|
199
|
+
surface.focus({ preventScroll: true });
|
|
200
|
+
note(space, "wakusei-landed", site);
|
|
201
|
+
return surface;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Go back up: the standing view fades out and the orbit view's camera rises to the whole Moon. Sends `wakusei-left`. Does nothing when nobody has landed; a landing that is still coming down is called off (its
|
|
205
|
+
* `land` rejects).
|
|
206
|
+
*
|
|
207
|
+
* @param space - The orbit view.
|
|
208
|
+
* @param options - `smooth`: false to cut.
|
|
209
|
+
* @returns Resolves when the orbit view is showing again.
|
|
210
|
+
*
|
|
211
|
+
* @example
|
|
212
|
+
* ```ts no-run
|
|
213
|
+
* import { leave } from "@johnmorrisdotca/wakusei-planets/surface/land";
|
|
214
|
+
*
|
|
215
|
+
* const space = document.querySelector("wakusei-space")!;
|
|
216
|
+
* await leave(space);
|
|
217
|
+
* ```
|
|
218
|
+
*/
|
|
219
|
+
export async function leave(space, options = {}) {
|
|
220
|
+
const landing = landings.get(space);
|
|
221
|
+
if (landing === undefined)
|
|
222
|
+
return;
|
|
223
|
+
const wasDown = landing.down;
|
|
224
|
+
landing.cancelled = true;
|
|
225
|
+
landing.wake?.();
|
|
226
|
+
landings.delete(space);
|
|
227
|
+
const smooth = options.smooth !== false && !reduced();
|
|
228
|
+
const { surface, veil, site } = landing;
|
|
229
|
+
// the ground goes dark, the orbit view takes the renderer back behind the veil and rises to the whole Moon, and the veil goes up on it
|
|
230
|
+
veil.style.transition = `opacity ${smooth ? FADE_MS : 0}ms ease`;
|
|
231
|
+
veil.style.opacity = "1";
|
|
232
|
+
if (smooth && wasDown)
|
|
233
|
+
await new Promise((resolve) => setTimeout(resolve, FADE_MS));
|
|
234
|
+
surface.remove();
|
|
235
|
+
if (wasDown) {
|
|
236
|
+
await space.resume();
|
|
237
|
+
await space.goToPlace(site.place, { body: "moon", smooth: false, zoom: 1 });
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
await space.resume();
|
|
241
|
+
}
|
|
242
|
+
veil.style.opacity = "0";
|
|
243
|
+
if (smooth)
|
|
244
|
+
await new Promise((resolve) => setTimeout(resolve, FADE_MS));
|
|
245
|
+
veil.remove();
|
|
246
|
+
if (wasDown)
|
|
247
|
+
note(space, "wakusei-left", site);
|
|
248
|
+
}
|
|
249
|
+
const proto = globalThis.customElements?.get("wakusei-space")?.prototype;
|
|
250
|
+
const install = (target) => {
|
|
251
|
+
Object.defineProperties(target, {
|
|
252
|
+
land: { value: function (siteId, options) { return land(this, siteId, options); }, configurable: true, writable: true },
|
|
253
|
+
leave: { value: function (options) { return leave(this, options); }, configurable: true, writable: true },
|
|
254
|
+
landed: { get() { return landedAt(this); }, configurable: true },
|
|
255
|
+
standing: { get() { return surfaceOf(this); }, configurable: true },
|
|
256
|
+
});
|
|
257
|
+
};
|
|
258
|
+
if (proto !== undefined)
|
|
259
|
+
install(proto);
|
|
260
|
+
else if (typeof customElements !== "undefined")
|
|
261
|
+
void customElements.whenDefined("wakusei-space").then(() => install(customElements.get("wakusei-space").prototype));
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { type HeightLevel, type TerrainManifest } from "./height.ts";
|
|
2
|
+
/**
|
|
3
|
+
* What a site's tiles cost to load and where the load has got to.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { type TerrainProgress } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
8
|
+
*
|
|
9
|
+
* const progress: TerrainProgress = { done: 30, total: 120, bytes: 1_500_000, first: 40 };
|
|
10
|
+
* console.log(`${Math.round((progress.done / progress.total) * 100)}% of the tiles, ${(progress.bytes / 1e6).toFixed(1)} MB`);
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export interface TerrainProgress {
|
|
14
|
+
/** Files placed so far. */
|
|
15
|
+
done: number;
|
|
16
|
+
/** Files in all. */
|
|
17
|
+
total: number;
|
|
18
|
+
/** Bytes fetched so far. */
|
|
19
|
+
bytes: number;
|
|
20
|
+
/** Files in the first view, which `loadTerrain` waits for. */
|
|
21
|
+
first: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The terrain of a site, as loaded.
|
|
25
|
+
*
|
|
26
|
+
* The levels are whole from the first view on, and get finer in place as the rest of the tiles arrive: a tile not yet fetched holds what the coarser level makes of it. `complete` settles when the last
|
|
27
|
+
* tile is in.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```ts
|
|
31
|
+
* import { type Terrain } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
32
|
+
*
|
|
33
|
+
* const describe = (terrain: Terrain): string => `${terrain.manifest.site}: ${terrain.levels.length} levels, ${terrain.firstBytes} bytes for the first view`;
|
|
34
|
+
* console.log(describe({ manifest: { site: "apollo-17" }, levels: [], pictures: [], horizons: [], bytes: 0, firstBytes: 0, complete: Promise.resolve() } as unknown as Terrain));
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export interface Terrain {
|
|
38
|
+
manifest: TerrainManifest;
|
|
39
|
+
/** The levels, finest first. */
|
|
40
|
+
levels: HeightLevel[];
|
|
41
|
+
/** The ground picture's levels (grey in red, green and blue), where the site has a picture. */
|
|
42
|
+
pictures: HeightLevel[];
|
|
43
|
+
/** The baked horizons of the first three levels (`cells * sectors / 3` wide, `cells` tall, RGBA), where the site has them. */
|
|
44
|
+
horizons: {
|
|
45
|
+
id: string;
|
|
46
|
+
width: number;
|
|
47
|
+
height: number;
|
|
48
|
+
data: Uint8Array;
|
|
49
|
+
}[];
|
|
50
|
+
/** Bytes fetched so far. */
|
|
51
|
+
bytes: number;
|
|
52
|
+
/** Bytes the first view took. */
|
|
53
|
+
firstBytes: number;
|
|
54
|
+
/** Settles when every tile is in (rejects if one cannot be had, with the first view still good). */
|
|
55
|
+
complete: Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* What loading needs beyond the address: a `fetch` of your own (a test's), how many tiles to ask for at once (6), a way to stop, a line for progress and a line for each change of the terrain.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```ts
|
|
62
|
+
* import { type LoadOptions } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
63
|
+
*
|
|
64
|
+
* const options: LoadOptions = { concurrency: 4, onProgress: (progress) => console.log(`${progress.done} of ${progress.total}`), onChange: (id) => console.log(`${id} grew finer`) };
|
|
65
|
+
* console.log(options.concurrency);
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
export interface LoadOptions {
|
|
69
|
+
fetch?: typeof fetch;
|
|
70
|
+
concurrency?: number;
|
|
71
|
+
signal?: AbortSignal;
|
|
72
|
+
onProgress?(progress: TerrainProgress): void;
|
|
73
|
+
/** Called after a file is placed, with the name of what changed: a level (`h5`), a picture level (`a5`) or a horizon map (`horizon:h5`), so a texture can be sent again. */
|
|
74
|
+
onChange?(id: string): void;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* One file to fetch: a height tile, a picture tile or a horizon map, of the level at `index` in its list.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* import { type LoadJob } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
82
|
+
*
|
|
83
|
+
* const job: LoadJob = { kind: "height", index: 0, column: 3, row: 4, first: true };
|
|
84
|
+
* console.log(`${job.kind} tile ${job.column}/${job.row} of level ${job.index}${job.first ? " in the first view" : ""}`);
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
export interface LoadJob {
|
|
88
|
+
kind: "height" | "picture" | "horizon";
|
|
89
|
+
index: number;
|
|
90
|
+
column: number;
|
|
91
|
+
row: number;
|
|
92
|
+
/** Part of the first view. */
|
|
93
|
+
first: boolean;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The order a site's files are fetched in: the first view first (the coarse level whole, the finest level's 4 x 4 tiles round the site, the pictures of the same two and the finest horizon map), then every
|
|
97
|
+
* other height and picture tile nearest the site first, then the other horizon maps, then the levels beyond the coarse one (the far terrain, which only the farthest mountains need).
|
|
98
|
+
*
|
|
99
|
+
* @param manifest - The site's manifest.
|
|
100
|
+
* @returns The files, in the order to fetch them.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```ts
|
|
104
|
+
* import { loadPlan, type TerrainManifest } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
105
|
+
*
|
|
106
|
+
* const level = (id: string, res: number) => ({ id, res, tiles: 8, half: (256 * 8 * res) / 2 });
|
|
107
|
+
* const manifest = { tile: 256, levels: [level("h5", 5), level("h20", 20), level("h80", 80)] } as unknown as TerrainManifest;
|
|
108
|
+
* const plan = loadPlan(manifest);
|
|
109
|
+
* console.log(`${plan.filter((job) => job.first).length} files in the first view of ${plan.length}`);
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
export declare function loadPlan(manifest: TerrainManifest): LoadJob[];
|
|
113
|
+
/**
|
|
114
|
+
* Load a site's terrain in rings: the manifest, then the first view, then the rest in the background. The promise settles when the first view is in and the levels are whole (the tiles still to come hold what
|
|
115
|
+
* the coarser level makes of them); the rest arrives in place, `onChange` says what, and `complete` settles at the end.
|
|
116
|
+
*
|
|
117
|
+
* @param base - The folder the tiles are served from, with the body and the site under it (`<base>moon/apollo-17/manifest.json`).
|
|
118
|
+
* @param body - The body, `moon`.
|
|
119
|
+
* @param site - The site's name, `apollo-17`.
|
|
120
|
+
* @param options - A fetch, a concurrency, a signal, a progress line and a line for changes.
|
|
121
|
+
* @returns The manifest and the levels, finest first.
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts no-run
|
|
125
|
+
* import { loadTerrain } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
126
|
+
*
|
|
127
|
+
* const terrain = await loadTerrain("https://johnmorrisdotca.github.io/wakusei-planets/tiles/", "moon", "apollo-17");
|
|
128
|
+
* console.log(`${terrain.firstBytes} bytes to the first view`);
|
|
129
|
+
* await terrain.complete;
|
|
130
|
+
* console.log(`${terrain.bytes} bytes in all`);
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
export declare function loadTerrain(base: string, body: string, site: string, options?: LoadOptions): Promise<Terrain>;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Fetching a site's heights in rings: its manifest, then the first view (the coarse level whole, the finest level round the standing place, their pictures and the nearest horizon map), then everything else,
|
|
2
|
+
// nearest first, a few tiles at a time, each decoded by the browser into bytes and placed in its level. Browser only (it decodes pictures).
|
|
3
|
+
import { emptyLevel, fillFromCoarser, placeTile, tileAddress } from "./height.js";
|
|
4
|
+
/** One picture's bytes as RGBA, decoded by the browser with no colour conversion (two of the colours of a height tile are two halves of a number). */
|
|
5
|
+
async function decodePicture(blob, width, height) {
|
|
6
|
+
const bitmap = await createImageBitmap(blob, { colorSpaceConversion: "none", premultiplyAlpha: "none" });
|
|
7
|
+
const canvas = typeof OffscreenCanvas === "function" ? new OffscreenCanvas(width, height) : Object.assign(document.createElement("canvas"), { width, height });
|
|
8
|
+
const g = canvas.getContext("2d", { willReadFrequently: true });
|
|
9
|
+
if (g === null)
|
|
10
|
+
throw new Error("no 2d canvas to decode a tile with");
|
|
11
|
+
g.drawImage(bitmap, 0, 0);
|
|
12
|
+
bitmap.close();
|
|
13
|
+
return g.getImageData(0, 0, width, height).data;
|
|
14
|
+
}
|
|
15
|
+
const decodeTile = (blob, size) => decodePicture(blob, size, size);
|
|
16
|
+
/**
|
|
17
|
+
* The order a site's files are fetched in: the first view first (the coarse level whole, the finest level's 4 x 4 tiles round the site, the pictures of the same two and the finest horizon map), then every
|
|
18
|
+
* other height and picture tile nearest the site first, then the other horizon maps, then the levels beyond the coarse one (the far terrain, which only the farthest mountains need).
|
|
19
|
+
*
|
|
20
|
+
* @param manifest - The site's manifest.
|
|
21
|
+
* @returns The files, in the order to fetch them.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* import { loadPlan, type TerrainManifest } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
26
|
+
*
|
|
27
|
+
* const level = (id: string, res: number) => ({ id, res, tiles: 8, half: (256 * 8 * res) / 2 });
|
|
28
|
+
* const manifest = { tile: 256, levels: [level("h5", 5), level("h20", 20), level("h80", 80)] } as unknown as TerrainManifest;
|
|
29
|
+
* const plan = loadPlan(manifest);
|
|
30
|
+
* console.log(`${plan.filter((job) => job.first).length} files in the first view of ${plan.length}`);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export function loadPlan(manifest) {
|
|
34
|
+
const tiles = (count, near) => {
|
|
35
|
+
const out = [];
|
|
36
|
+
const from = near && count > 4 ? Math.floor(count / 2) - 2 : 0;
|
|
37
|
+
const to = near && count > 4 ? from + 4 : count;
|
|
38
|
+
for (let row = from; row < to; row += 1)
|
|
39
|
+
for (let column = from; column < to; column += 1)
|
|
40
|
+
out.push([column, row]);
|
|
41
|
+
return out;
|
|
42
|
+
};
|
|
43
|
+
const heightLevels = manifest.levels;
|
|
44
|
+
const pictureLevels = manifest.picture?.levels ?? [];
|
|
45
|
+
const horizons = manifest.horizon?.levels ?? [];
|
|
46
|
+
const coarse = Math.min(heightLevels.length - 1, Math.max(0, (horizons.length > 0 ? horizons.length : heightLevels.length - 1) - 1));
|
|
47
|
+
const pictureCoarse = pictureLevels.length - 1;
|
|
48
|
+
const first = [];
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
const add = (list, kind, index, column, row, isFirst) => {
|
|
51
|
+
const key = `${kind}:${index}:${column}:${row}`;
|
|
52
|
+
if (seen.has(key))
|
|
53
|
+
return;
|
|
54
|
+
seen.add(key);
|
|
55
|
+
list.push({ kind, index, column, row, first: isFirst });
|
|
56
|
+
};
|
|
57
|
+
const level = (kind, index, near, list, isFirst) => {
|
|
58
|
+
const info = (kind === "height" ? heightLevels : pictureLevels)[index];
|
|
59
|
+
if (info === undefined)
|
|
60
|
+
return;
|
|
61
|
+
for (const [column, row] of tiles(info.tiles, near))
|
|
62
|
+
add(list, kind, index, column, row, isFirst);
|
|
63
|
+
};
|
|
64
|
+
level("height", coarse, false, first, true);
|
|
65
|
+
level("height", 0, true, first, true);
|
|
66
|
+
if (pictureLevels.length > 0) {
|
|
67
|
+
level("picture", pictureCoarse, false, first, true);
|
|
68
|
+
level("picture", 0, true, first, true);
|
|
69
|
+
}
|
|
70
|
+
if (horizons.length > 0)
|
|
71
|
+
add(first, "horizon", 0, 0, 0, true);
|
|
72
|
+
const rest = [];
|
|
73
|
+
for (let index = 0; index <= coarse; index += 1)
|
|
74
|
+
level("height", index, false, rest, false);
|
|
75
|
+
for (let index = 0; index < pictureLevels.length; index += 1)
|
|
76
|
+
level("picture", index, false, rest, false);
|
|
77
|
+
const distance = (job) => {
|
|
78
|
+
const info = (job.kind === "height" ? heightLevels : pictureLevels)[job.index];
|
|
79
|
+
const side = manifest.tile * info.res;
|
|
80
|
+
return Math.hypot((job.column + 0.5) * side - info.half, (job.row + 0.5) * side - info.half);
|
|
81
|
+
};
|
|
82
|
+
rest.sort((a, b) => distance(a) - distance(b) || a.index - b.index);
|
|
83
|
+
for (let index = 1; index < horizons.length; index += 1)
|
|
84
|
+
add(rest, "horizon", index, 0, 0, false);
|
|
85
|
+
const far = [];
|
|
86
|
+
for (let index = coarse + 1; index < heightLevels.length; index += 1)
|
|
87
|
+
level("height", index, false, far, false);
|
|
88
|
+
return [...first.filter((job) => job.first), ...rest.filter((job) => !job.first), ...far];
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Load a site's terrain in rings: the manifest, then the first view, then the rest in the background. The promise settles when the first view is in and the levels are whole (the tiles still to come hold what
|
|
92
|
+
* the coarser level makes of them); the rest arrives in place, `onChange` says what, and `complete` settles at the end.
|
|
93
|
+
*
|
|
94
|
+
* @param base - The folder the tiles are served from, with the body and the site under it (`<base>moon/apollo-17/manifest.json`).
|
|
95
|
+
* @param body - The body, `moon`.
|
|
96
|
+
* @param site - The site's name, `apollo-17`.
|
|
97
|
+
* @param options - A fetch, a concurrency, a signal, a progress line and a line for changes.
|
|
98
|
+
* @returns The manifest and the levels, finest first.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts no-run
|
|
102
|
+
* import { loadTerrain } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
103
|
+
*
|
|
104
|
+
* const terrain = await loadTerrain("https://johnmorrisdotca.github.io/wakusei-planets/tiles/", "moon", "apollo-17");
|
|
105
|
+
* console.log(`${terrain.firstBytes} bytes to the first view`);
|
|
106
|
+
* await terrain.complete;
|
|
107
|
+
* console.log(`${terrain.bytes} bytes in all`);
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export async function loadTerrain(base, body, site, options = {}) {
|
|
111
|
+
const get = options.fetch ?? fetch;
|
|
112
|
+
const folder = base.endsWith("/") ? base : `${base}/`;
|
|
113
|
+
const manifestResponse = await get(`${folder}${body}/${site}/manifest.json`, { signal: options.signal });
|
|
114
|
+
if (!manifestResponse.ok)
|
|
115
|
+
throw new Error(`no terrain for ${body}/${site} at ${folder} (${manifestResponse.status})`);
|
|
116
|
+
const manifest = (await manifestResponse.json());
|
|
117
|
+
const levels = manifest.levels.map((info) => emptyLevel(info, manifest.tile));
|
|
118
|
+
const pictures = (manifest.picture?.levels ?? []).map((info) => emptyLevel(info, manifest.tile));
|
|
119
|
+
const hz = manifest.horizon;
|
|
120
|
+
const horizonWidth = hz === null || hz === undefined ? 0 : hz.cells * (hz.sectors / 3);
|
|
121
|
+
const horizons = (hz?.levels ?? []).map((entry) => ({ id: entry.id, width: horizonWidth, height: hz.cells, data: new Uint8Array(horizonWidth * hz.cells * 4) }));
|
|
122
|
+
const plan = loadPlan(manifest);
|
|
123
|
+
const firstJobs = plan.filter((job) => job.first);
|
|
124
|
+
const restJobs = plan.filter((job) => !job.first);
|
|
125
|
+
const terrain = { manifest, levels, pictures, horizons, bytes: 0, firstBytes: 0, complete: Promise.resolve() };
|
|
126
|
+
const placed = new Set();
|
|
127
|
+
let done = 0;
|
|
128
|
+
const report = () => options.onProgress?.({ done, total: plan.length, bytes: terrain.bytes, first: firstJobs.length });
|
|
129
|
+
const fetchJob = async (job) => {
|
|
130
|
+
if (job.kind === "horizon") {
|
|
131
|
+
const entry = hz.levels[job.index];
|
|
132
|
+
const response = await get(`${folder}${manifest.body}/${manifest.site}/${entry.file}`, { signal: options.signal });
|
|
133
|
+
if (!response.ok)
|
|
134
|
+
throw new Error(`horizon ${entry.id}: ${response.status}`);
|
|
135
|
+
const blob = await response.blob();
|
|
136
|
+
terrain.bytes += blob.size;
|
|
137
|
+
horizons[job.index].data.set(await decodePicture(blob, horizonWidth, hz.cells));
|
|
138
|
+
options.onChange?.(`horizon:${entry.id}`);
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
const picture = job.kind === "picture";
|
|
142
|
+
const target = (picture ? pictures : levels)[job.index];
|
|
143
|
+
const address = picture ? `${folder}${manifest.body}/${manifest.site}/ground/${target.id}/${job.column}/${job.row}.webp` : tileAddress(folder, manifest, target.id, job.column, job.row);
|
|
144
|
+
const response = await get(address, { signal: options.signal });
|
|
145
|
+
if (!response.ok)
|
|
146
|
+
throw new Error(`tile ${target.id}/${job.column}/${job.row}: ${response.status}`);
|
|
147
|
+
const blob = await response.blob();
|
|
148
|
+
terrain.bytes += blob.size;
|
|
149
|
+
placeTile(target, manifest.tile, job.column, job.row, await decodeTile(blob, manifest.tile));
|
|
150
|
+
placed.add(`${job.kind}:${job.index}:${job.column}:${job.row}`);
|
|
151
|
+
options.onChange?.(target.id);
|
|
152
|
+
}
|
|
153
|
+
done += 1;
|
|
154
|
+
report();
|
|
155
|
+
};
|
|
156
|
+
const run = async (jobs) => {
|
|
157
|
+
let next = 0;
|
|
158
|
+
const worker = async () => {
|
|
159
|
+
for (;;) {
|
|
160
|
+
const job = jobs[next++];
|
|
161
|
+
if (job === undefined)
|
|
162
|
+
return;
|
|
163
|
+
await fetchJob(job);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
await Promise.all(Array.from({ length: Math.max(1, options.concurrency ?? 6) }, worker));
|
|
167
|
+
};
|
|
168
|
+
await run(firstJobs);
|
|
169
|
+
// the tiles still to come hold what the coarser level makes of them, from the coarse level down
|
|
170
|
+
const coarse = Math.min(levels.length - 1, Math.max(0, (hz?.levels.length ?? levels.length - 1) - 1));
|
|
171
|
+
for (let index = coarse - 1; index >= 0; index -= 1) {
|
|
172
|
+
const to = levels[index];
|
|
173
|
+
const from = levels[index + 1];
|
|
174
|
+
fillFromCoarser(to, from, manifest.tile, (column, row) => placed.has(`height:${index}:${column}:${row}`), { from: from.height ?? manifest.height, to: to.height ?? manifest.height });
|
|
175
|
+
}
|
|
176
|
+
for (let index = pictures.length - 2; index >= 0; index -= 1) {
|
|
177
|
+
fillFromCoarser(pictures[index], pictures[index + 1], manifest.tile, (column, row) => placed.has(`picture:${index}:${column}:${row}`), "grey");
|
|
178
|
+
}
|
|
179
|
+
terrain.firstBytes = terrain.bytes;
|
|
180
|
+
terrain.complete = run(restJobs);
|
|
181
|
+
terrain.complete.catch(() => undefined);
|
|
182
|
+
return terrain;
|
|
183
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type Rock } from "./detail.ts";
|
|
2
|
+
/**
|
|
3
|
+
* The arrays of the rocks' mesh, in the site's plane (east, up, north): `ROCK_VERTICES` (240) a rock, and 10 for its shadow.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { rockMesh, type RockMesh } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
8
|
+
*
|
|
9
|
+
* const mesh: RockMesh = rockMesh([{ x: 2, y: 3, size: 0.5, shape: 0, turn: 0, tone: 1, flat: 0.6 }], () => 0, { azimuth: 95, altitude: 13 });
|
|
10
|
+
* console.log(mesh.count, mesh.position.length / 3, mesh.shadowIndex.length);
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export interface RockMesh {
|
|
14
|
+
position: Float32Array;
|
|
15
|
+
normal: Float32Array;
|
|
16
|
+
tone: Float32Array;
|
|
17
|
+
count: number;
|
|
18
|
+
shadowPosition: Float32Array;
|
|
19
|
+
shadowUv: Float32Array;
|
|
20
|
+
shadowIndex: Uint32Array;
|
|
21
|
+
}
|
|
22
|
+
/** Vertices a rock's mesh has: 80 faces of 3. */
|
|
23
|
+
export declare const ROCK_VERTICES: number;
|
|
24
|
+
/** The three shapes: the cut icosahedron with each corner pulled in or out by a seeded share, in lumps (a corner takes the share of its neighbours too), so each shape is its own and none is a ball. */
|
|
25
|
+
export declare const SHAPES: readonly (readonly (readonly [number, number, number])[])[];
|
|
26
|
+
/**
|
|
27
|
+
* The mesh of a list of rocks standing on the ground, and a shadow for each.
|
|
28
|
+
*
|
|
29
|
+
* @param rocks - The rocks, from `rocksAround`.
|
|
30
|
+
* @param ground - The ground's height at a point (metres east and north of the site), the made craters on it and the Moon's curve taken off.
|
|
31
|
+
* @param sun - The Sun's azimuth (degrees clockwise from north) and altitude (degrees).
|
|
32
|
+
* @returns The arrays.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { rockMesh, rocksAround } from "@johnmorrisdotca/wakusei-planets/surface";
|
|
37
|
+
*
|
|
38
|
+
* const mesh = rockMesh(rocksAround(0, 0, 20, 0.0024), () => 0, { azimuth: 95, altitude: 13 });
|
|
39
|
+
* console.log(mesh.count, "rocks");
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function rockMesh(rocks: readonly Rock[], ground: (x: number, y: number) => number, sun: {
|
|
43
|
+
azimuth: number;
|
|
44
|
+
altitude: number;
|
|
45
|
+
}): RockMesh;
|