@johnmorrisdotca/wakusei-planets 0.26.1 → 0.28.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,8 +1,9 @@
1
1
  import { BODIES } from "../facts.js";
2
2
  import { silhouette } from "../pose.js";
3
3
  import { cross } from "../vec.js";
4
- import { BALL_FRAGMENT, bodyFragment, GLOW_FRAGMENT, GLOW_VERTEX, PAINTED_SURFACE, RING_FRAGMENT, RING_VERTEX, STAR_GLOW_FRAGMENT, VERTEX } from "./glsl.js";
5
- import { lookOf } from "./look.js";
4
+ import { BALL_FRAGMENT, bodyFragment, GLOW_FRAGMENT, GLOW_VERTEX, PAINTED_SURFACE, PAINTED_SURFACE_WINDOWED, RING_FRAGMENT_DETAIL, RING_VERTEX, STAR_GLOW_FRAGMENT, VERTEX } from "./glsl.js";
5
+ import { detailOf, lookOf } from "./look.js";
6
+ import { createDetail } from "./detail.js";
6
7
  import { fallbackLook } from "./fallback.js";
7
8
  import { writeBasis } from "./basis.js";
8
9
  import { loadImage } from "./textures.js";
@@ -10,10 +11,21 @@ import { ringStrip } from "./rings.js";
10
11
  export { fallbackLook } from "./fallback.js";
11
12
  function makeBodyMaterial(T, look, painted) {
12
13
  const a = look.atmosphere;
14
+ // a glowing body (the Sun, a star) is drawn as it always was: no window of finer map and no generic detail
15
+ const generic = look.emissive !== true;
16
+ const fine = detailOf(look);
13
17
  return new T.ShaderMaterial({
14
18
  vertexShader: VERTEX,
15
- fragmentShader: bodyFragment(painted ? PAINTED_SURFACE : look.surface, painted, false, look.limbTint),
19
+ fragmentShader: bodyFragment(painted ? (generic ? PAINTED_SURFACE_WINDOWED : PAINTED_SURFACE) : look.surface, painted, false, look.limbTint, generic),
16
20
  uniforms: {
21
+ ...(generic
22
+ ? {
23
+ uTexel: { value: painted ? (2 * Math.PI) / (look.painted?.widths[0] ?? 2048) : 0.005 },
24
+ uDetailAmp: { value: fine.amount },
25
+ uDetailStretch: { value: fine.stretch },
26
+ ...(painted ? { uDetail: { value: null }, uDetailRect: { value: [0, 1, 1, 1] }, uDetailFade: { value: new T.Vector2(0, 0) }, uDetailOn: { value: 0 }, uDetailTexel: { value: 0.003 } } : {}),
27
+ }
28
+ : {}),
17
29
  uLight: { value: new T.Vector3(-0.6, 0.2, 0.77) },
18
30
  uRelief: { value: (painted ? (look.painted?.relief ?? 0) : (look.relief ?? 0.6)) },
19
31
  uAmbient: { value: look.ambient ?? 0.04 },
@@ -54,7 +66,7 @@ export function createBodyItem(options) {
54
66
  async build({ three: T, assets, width, height }) {
55
67
  const look = options.shaded ?? lookOf(options.id) ?? fallbackLook(facts);
56
68
  const wantPainted = (options.look === "painted" || look.mapped === true) && look.painted !== undefined;
57
- const geometry = assets.acquire("wk:sphere", () => new T.SphereGeometry(1, 128, 64), (g) => g.dispose());
69
+ const geometry = assets.acquire("wk:sphere", () => new T.SphereGeometry(1, 192, 96), (g) => g.dispose());
58
70
  const shader = assets.acquire(`wk:body:${held}:r`, () => makeBodyMaterial(T, look, false), (m) => m.dispose());
59
71
  const paintedMaterial = wantPainted ? assets.acquire(`wk:body:${held}:p`, () => makeBodyMaterial(T, look, true), (m) => m.dispose()) : undefined;
60
72
  const materials = paintedMaterial === undefined ? [shader] : [shader, paintedMaterial];
@@ -105,13 +117,13 @@ export function createBodyItem(options) {
105
117
  photoTexture.dispose();
106
118
  const ringMaterial = (key, depthTest) => assets.acquire(`wk:ringmat:${ringKey}:${key}`, () => new T.ShaderMaterial({
107
119
  vertexShader: RING_VERTEX,
108
- fragmentShader: RING_FRAGMENT,
120
+ fragmentShader: RING_FRAGMENT_DETAIL,
109
121
  side: T.DoubleSide,
110
122
  transparent: true,
111
123
  premultipliedAlpha: photoTexture === undefined,
112
124
  depthWrite: false,
113
125
  depthTest,
114
- uniforms: { uRingTex: { value: ringTexture }, uRingR: { value: new T.Vector2(ringInner, ringOuter) }, uLight: { value: new T.Vector3(0, 0, 1) }, uRingN: { value: new T.Vector3(0, 1, 0) } },
126
+ uniforms: { uRingTex: { value: ringTexture }, uRingR: { value: new T.Vector2(ringInner, ringOuter) }, uLight: { value: new T.Vector3(0, 0, 1) }, uRingN: { value: new T.Vector3(0, 1, 0) }, uRingTexel: { value: 1 / (photoTexture !== undefined ? photo.width : table.width) } },
115
127
  }), (m) => m.dispose());
116
128
  // 0..pi is the +Y half. The basis maps local +Y onto +east.
117
129
  const half = (key, depthTest) => {
@@ -176,6 +188,8 @@ export function createBodyItem(options) {
176
188
  drop(t);
177
189
  textureWidth = w;
178
190
  paintedMaterial.uniforms.uMap.value = shared;
191
+ if (paintedMaterial.uniforms.uTexel !== undefined)
192
+ paintedMaterial.uniforms.uTexel.value = (2 * Math.PI) / w;
179
193
  mesh.material = paintedMaterial;
180
194
  options.report?.({ painted: true, width: w });
181
195
  };
@@ -185,6 +199,30 @@ export function createBodyItem(options) {
185
199
  textureWidth = 0;
186
200
  options.report?.({ painted: false, width: 0, failed: true });
187
201
  };
202
+ // the window of finer map for a close zoom, laid over the painted map by the painted material
203
+ const windowUniforms = wantPainted && paintedMaterial !== undefined && look.emissive !== true && options.tiles !== undefined && look.painted !== undefined ? paintedMaterial.uniforms : undefined;
204
+ const detail = windowUniforms === undefined || options.tiles === undefined
205
+ ? undefined
206
+ : createDetail(T, {
207
+ base: () => options.tiles.base(),
208
+ body: look.painted.map,
209
+ ratio: () => options.tiles.ratio(),
210
+ allowed: () => options.tiles.allowed(),
211
+ redraw: () => options.redraw(),
212
+ ...(options.tiles.onLevels === undefined ? {} : { onLevels: (levels) => options.tiles.onLevels(levels) }),
213
+ apply: (shown) => {
214
+ if (shown === null) {
215
+ windowUniforms.uDetailOn.value = 0;
216
+ windowUniforms.uDetail.value = null;
217
+ return;
218
+ }
219
+ windowUniforms.uDetail.value = shown.texture;
220
+ windowUniforms.uDetailRect.value = [shown.rect.u0, shown.rect.vTop, shown.rect.du, shown.rect.dv];
221
+ windowUniforms.uDetailFade.value.set(shown.fade.u, shown.fade.v);
222
+ windowUniforms.uDetailTexel.value = shown.texel;
223
+ windowUniforms.uDetailOn.value = 1;
224
+ },
225
+ });
188
226
  if (wantPainted && paintedMaterial !== undefined) {
189
227
  const widths = look.painted.widths;
190
228
  try {
@@ -360,6 +398,12 @@ export function createBodyItem(options) {
360
398
  glow.scale.setScalar(1);
361
399
  }
362
400
  requestSharperTexture(state);
401
+ if (detail !== undefined && textureWidth > 0) {
402
+ const east = cross(state.pose.pole, state.pose.meridian);
403
+ const ax = facts.axesKm;
404
+ const mean = facts.radiusKm;
405
+ detail.sync({ left: camera.left, right: camera.right, bottom: camera.bottom, top: camera.top }, { east, pole: state.pose.pole, meridian: state.pose.meridian, scale: [ax ? ax[1] / mean : 1, ax ? ax[2] / mean : 1 - facts.flattening, ax ? ax[0] / mean : 1] }, viewWidth);
406
+ }
363
407
  };
364
408
  apply(latest);
365
409
  return {
@@ -372,6 +416,9 @@ export function createBodyItem(options) {
372
416
  get painted() {
373
417
  return textureWidth > 0;
374
418
  },
419
+ get detail() {
420
+ return detail?.stats;
421
+ },
375
422
  resize(w, h) {
376
423
  viewWidth = w;
377
424
  viewHeight = h;
@@ -384,6 +431,11 @@ export function createBodyItem(options) {
384
431
  },
385
432
  dispose() {
386
433
  gone = true;
434
+ if (windowUniforms !== undefined) {
435
+ windowUniforms.uDetailOn.value = 0;
436
+ windowUniforms.uDetail.value = null;
437
+ }
438
+ detail?.dispose();
387
439
  for (const o of orbitLines.values())
388
440
  o.line.geometry.dispose();
389
441
  orbitMaterial.dispose();
@@ -0,0 +1,73 @@
1
+ import type * as THREE from "three";
2
+ import { type Axes, type TileLevel, type ViewBox } from "./tiles.ts";
3
+ type Three = Pick<typeof THREE, "ClampToEdgeWrapping" | "DataTexture" | "LinearFilter" | "NoColorSpace">;
4
+ /** Milliseconds a window that the view no longer needs is kept (the view may come straight back) before its texture is freed. */
5
+ export declare const DETAIL_KEEP_MS = 4000;
6
+ /** Milliseconds a changed view must stay changed before a new window is fetched, so a drag or a pinch does not fetch what it passes. */
7
+ export declare const DETAIL_SETTLE_MS = 140;
8
+ /** Decoded tiles kept (about a megabyte each), those of the window first. */
9
+ export declare const DETAIL_TILES_KEPT = 48;
10
+ /** What a window is doing, for a page or a test. */
11
+ export interface DetailStats {
12
+ /** A readable tile set was found (a body with levels in it, or not). */
13
+ ready: boolean;
14
+ /** The level the view wants now, or `null` when the body's own picture is sharp enough. */
15
+ level: number | null;
16
+ /** The level on the body now, or `null`. */
17
+ shown: number | null;
18
+ /** Tiles held decoded, and tiles being fetched. */
19
+ held: number;
20
+ loading: number;
21
+ /** Tiles or windows that could not be made and are not tried again for a while. */
22
+ failed: number;
23
+ /** Tile fetches made. */
24
+ requested: number;
25
+ /** The width and height in pixels of the window's picture now, or 0. */
26
+ pixels: number;
27
+ }
28
+ /** What a window gives the body when one is ready or let go: the picture and where it lies, or `null` for none. */
29
+ export interface DetailWindow {
30
+ texture: THREE.Texture;
31
+ /** `u0` the map coordinate of the west edge, `vTop` of the north edge, `du` and `dv` the size, all fractions of the map. */
32
+ rect: {
33
+ u0: number;
34
+ du: number;
35
+ vTop: number;
36
+ dv: number;
37
+ };
38
+ /** The softening at the window's edges as fractions of its size; 0 where the window meets a pole or goes right round. */
39
+ fade: {
40
+ u: number;
41
+ v: number;
42
+ };
43
+ /** The angle a texel of the window covers, in radians. */
44
+ texel: number;
45
+ }
46
+ export interface DetailDeps {
47
+ /** Where the tile set is, ending with a slash, or `undefined` for none. Read at every draw. */
48
+ base: () => string | undefined;
49
+ /** The body's name in the tile set. */
50
+ body: string;
51
+ /** Device pixels to a CSS pixel. */
52
+ ratio: () => number;
53
+ /** False on a device that should keep to the package's own pictures (little memory). */
54
+ allowed: () => boolean;
55
+ /** Ask for one draw. */
56
+ redraw: () => void;
57
+ /** Told when the tile set's levels for this body are known (`undefined` when it has none), so the zoom range can follow. */
58
+ onLevels?: (levels: readonly TileLevel[] | undefined) => void;
59
+ /** Put the window on the body, or take it off (`null`). */
60
+ apply: (window: DetailWindow | null) => void;
61
+ now?: () => number;
62
+ }
63
+ export interface Detail {
64
+ /** Called at each draw with where the camera is and the body's axes. */
65
+ sync(box: ViewBox, axes: Axes, viewWidth: number): void;
66
+ readonly stats: DetailStats;
67
+ dispose(): void;
68
+ }
69
+ /** Forget what was read of the tile sets (for a test that serves different ones). */
70
+ export declare function forgetManifests(): void;
71
+ /** Make the window of finer map for one body. */
72
+ export declare function createDetail(T: Three, deps: DetailDeps): Detail;
73
+ export {};
@@ -0,0 +1,289 @@
1
+ import { chooseWindow, covers, parseManifest, tilePath, visibleRegion, windowRect, windowTiles, TILE_SIZE, texelAngle } from "./tiles.js";
2
+ /** Milliseconds a window that the view no longer needs is kept (the view may come straight back) before its texture is freed. */
3
+ export const DETAIL_KEEP_MS = 4000;
4
+ /** Milliseconds a changed view must stay changed before a new window is fetched, so a drag or a pinch does not fetch what it passes. */
5
+ export const DETAIL_SETTLE_MS = 140;
6
+ /** Decoded tiles kept (about a megabyte each), those of the window first. */
7
+ export const DETAIL_TILES_KEPT = 48;
8
+ const RETRY_MS = 30_000;
9
+ const IN_FLIGHT = 6;
10
+ // One manifest read for each tile set of the page, shared by every element.
11
+ const manifests = new Map();
12
+ function readManifest(base, now) {
13
+ const held = manifests.get(base);
14
+ if (held !== undefined && now - held.at < RETRY_MS)
15
+ return held.value;
16
+ const value = fetch(`${base}manifest.json`, { mode: "cors" }).then(async (response) => (response.ok ? parseManifest(await response.json().catch(() => undefined)) : undefined), () => undefined);
17
+ manifests.set(base, { at: now, value });
18
+ return value;
19
+ }
20
+ /** Forget what was read of the tile sets (for a test that serves different ones). */
21
+ export function forgetManifests() {
22
+ manifests.clear();
23
+ }
24
+ const keyOf = (w) => `${w.level}:${w.col0}:${w.cols}:${w.row0}:${w.rows}`;
25
+ /** Make the window of finer map for one body. */
26
+ export function createDetail(T, deps) {
27
+ const clock = deps.now ?? (() => performance.now());
28
+ const cache = new Map();
29
+ const inFlight = new Map();
30
+ const failed = new Map();
31
+ let manifest;
32
+ let manifestFor = "";
33
+ let manifestAsked = false;
34
+ let askedAt = 0;
35
+ let levels;
36
+ let held;
37
+ let loading;
38
+ let pending;
39
+ let freeTimer;
40
+ let wantLevel = null;
41
+ let requested = 0;
42
+ let gone = false;
43
+ // The Texture class of the three.js module the page handed over: `DataTexture` extends it, and a page's subset of three need not name it.
44
+ const TextureClass = Object.getPrototypeOf(T.DataTexture);
45
+ const forgetTiles = (keep) => {
46
+ if (cache.size <= DETAIL_TILES_KEPT)
47
+ return;
48
+ const order = [...cache.entries()].filter(([k]) => !keep.has(k)).sort((a, b) => a[1].used - b[1].used);
49
+ for (const [k, entry] of order) {
50
+ if (cache.size <= DETAIL_TILES_KEPT)
51
+ break;
52
+ entry.bitmap.close();
53
+ cache.delete(k);
54
+ }
55
+ };
56
+ const release = () => {
57
+ if (held === undefined)
58
+ return;
59
+ held.texture.dispose();
60
+ held.canvas.width = 0;
61
+ held.canvas.height = 0;
62
+ held = undefined;
63
+ };
64
+ const cancelPending = () => {
65
+ if (pending !== undefined)
66
+ clearTimeout(pending.timer);
67
+ pending = undefined;
68
+ };
69
+ const cancelLoading = () => {
70
+ for (const controller of inFlight.values())
71
+ controller.abort();
72
+ inFlight.clear();
73
+ loading = undefined;
74
+ };
75
+ const install = (window) => {
76
+ const tiles = windowTiles(window);
77
+ const canvas = document.createElement("canvas");
78
+ canvas.width = window.cols * TILE_SIZE;
79
+ canvas.height = window.rows * TILE_SIZE;
80
+ const context = canvas.getContext("2d");
81
+ if (context === null)
82
+ return;
83
+ for (const tile of tiles) {
84
+ const entry = cache.get(tilePath(deps.body, tile));
85
+ if (entry === undefined)
86
+ return;
87
+ context.drawImage(entry.bitmap, tile.x, tile.y);
88
+ }
89
+ const texture = new TextureClass(canvas);
90
+ texture.flipY = false;
91
+ texture.wrapS = T.ClampToEdgeWrapping;
92
+ texture.wrapT = T.ClampToEdgeWrapping;
93
+ texture.magFilter = T.LinearFilter;
94
+ texture.colorSpace = T.NoColorSpace;
95
+ texture.anisotropy = 4;
96
+ texture.needsUpdate = true;
97
+ const old = held;
98
+ held = { key: keyOf(window), window, texture, canvas };
99
+ const rect = windowRect(window);
100
+ const full = window.cols >= window.columns;
101
+ // a window that reaches a pole has no edge there: its rectangle goes a little past the pole and the picture is clamped
102
+ const northPole = window.row0 === 0;
103
+ const southPole = window.row0 + window.rows >= window.rowsTotal;
104
+ const grow = 0.06 * rect.dv;
105
+ const vTop = northPole ? rect.vTop + grow : rect.vTop;
106
+ const dv = rect.dv + (northPole ? grow : 0) + (southPole ? grow : 0);
107
+ deps.apply({
108
+ texture,
109
+ rect: { u0: rect.u0, du: rect.du, vTop, dv },
110
+ fade: { u: full ? 0 : 0.03, v: northPole && southPole ? 0 : 0.03 },
111
+ texel: texelAngle(window.columns * TILE_SIZE),
112
+ });
113
+ if (old !== undefined) {
114
+ old.texture.dispose();
115
+ old.canvas.width = 0;
116
+ old.canvas.height = 0;
117
+ }
118
+ forgetTiles(new Set(tiles.map((t) => tilePath(deps.body, t))));
119
+ deps.redraw();
120
+ };
121
+ const load = (window) => {
122
+ const key = keyOf(window);
123
+ if (loading?.key === key)
124
+ return;
125
+ cancelLoading();
126
+ loading = { key, window };
127
+ const base = deps.base();
128
+ if (base === undefined)
129
+ return;
130
+ const tiles = windowTiles(window).map((t) => ({ t, path: tilePath(deps.body, t) }));
131
+ const todo = tiles.filter(({ path }) => !cache.has(path));
132
+ for (const { path } of tiles) {
133
+ const entry = cache.get(path);
134
+ if (entry !== undefined)
135
+ entry.used = clock();
136
+ }
137
+ const done = () => {
138
+ if (gone || loading?.key !== key)
139
+ return;
140
+ if (tiles.every(({ path }) => cache.has(path))) {
141
+ loading = undefined;
142
+ install(window);
143
+ }
144
+ };
145
+ if (todo.length === 0) {
146
+ done();
147
+ return;
148
+ }
149
+ let next = 0;
150
+ const start = () => {
151
+ while (inFlight.size < IN_FLIGHT && next < todo.length) {
152
+ const { path } = todo[next];
153
+ next += 1;
154
+ const controller = new AbortController();
155
+ inFlight.set(path, controller);
156
+ requested += 1;
157
+ void fetch(`${base}${path}.webp`, { mode: "cors", signal: controller.signal })
158
+ .then((response) => (response.ok ? response.blob() : Promise.reject(new Error(String(response.status)))))
159
+ .then((blob) => createImageBitmap(blob))
160
+ .then((bitmap) => {
161
+ inFlight.delete(path);
162
+ if (gone || loading?.key !== key) {
163
+ bitmap.close();
164
+ return;
165
+ }
166
+ cache.set(path, { bitmap, used: clock() });
167
+ start();
168
+ done();
169
+ }, (error) => {
170
+ inFlight.delete(path);
171
+ if (gone || (error instanceof DOMException && error.name === "AbortError"))
172
+ return;
173
+ // a tile that cannot be had spoils the window: leave the picture as it is and try again after a while
174
+ failed.set(key, clock());
175
+ cancelLoading();
176
+ });
177
+ }
178
+ };
179
+ start();
180
+ };
181
+ const dropTiles = () => {
182
+ for (const entry of cache.values())
183
+ entry.bitmap.close();
184
+ cache.clear();
185
+ };
186
+ // not wanted any more (zoomed out, or out of sight): after a few seconds the picture and every decoded tile are let go
187
+ const scheduleFree = () => {
188
+ if ((held === undefined && cache.size === 0) || freeTimer !== undefined)
189
+ return;
190
+ freeTimer = setTimeout(() => {
191
+ freeTimer = undefined;
192
+ if (gone)
193
+ return;
194
+ cancelLoading();
195
+ dropTiles();
196
+ if (held === undefined)
197
+ return;
198
+ release();
199
+ deps.apply(null);
200
+ deps.redraw();
201
+ }, DETAIL_KEEP_MS);
202
+ };
203
+ const cancelFree = () => {
204
+ if (freeTimer !== undefined)
205
+ clearTimeout(freeTimer);
206
+ freeTimer = undefined;
207
+ };
208
+ const ask = (base) => {
209
+ if (manifestAsked && manifestFor === base && (manifest !== undefined || clock() - askedAt < RETRY_MS))
210
+ return;
211
+ manifestAsked = true;
212
+ manifestFor = base;
213
+ askedAt = clock();
214
+ void readManifest(base, clock()).then((read) => {
215
+ if (gone || manifestFor !== base)
216
+ return;
217
+ manifest = read;
218
+ levels = read?.bodies[deps.body];
219
+ deps.onLevels?.(levels);
220
+ if (levels !== undefined)
221
+ deps.redraw();
222
+ });
223
+ };
224
+ return {
225
+ sync(box, axes, viewWidth) {
226
+ if (gone)
227
+ return;
228
+ const base = deps.base();
229
+ if (base === undefined || !deps.allowed()) {
230
+ wantLevel = null;
231
+ scheduleFree();
232
+ return;
233
+ }
234
+ ask(base);
235
+ if (levels === undefined)
236
+ return;
237
+ const region = visibleRegion(box, axes);
238
+ const radiansPixels = (deps.ratio() * viewWidth) / Math.max(1e-9, box.right - box.left);
239
+ const want = region === undefined ? undefined : chooseWindow(region, levels, radiansPixels);
240
+ wantLevel = want?.level ?? null;
241
+ if (want === undefined) {
242
+ cancelPending();
243
+ scheduleFree();
244
+ return;
245
+ }
246
+ cancelFree();
247
+ const inside = visibleRegion(box, axes, 0);
248
+ if (held !== undefined && held.window.level >= want.level && inside !== undefined && covers(held.window, inside)) {
249
+ cancelPending();
250
+ return;
251
+ }
252
+ const key = keyOf(want);
253
+ if (held?.key === key || loading?.key === key || pending?.key === key)
254
+ return;
255
+ const lastFailed = failed.get(key);
256
+ if (lastFailed !== undefined && clock() - lastFailed < RETRY_MS)
257
+ return;
258
+ cancelPending();
259
+ pending = {
260
+ key,
261
+ timer: setTimeout(() => {
262
+ pending = undefined;
263
+ if (!gone)
264
+ load(want);
265
+ }, DETAIL_SETTLE_MS),
266
+ };
267
+ },
268
+ get stats() {
269
+ return {
270
+ ready: manifest !== undefined,
271
+ level: wantLevel,
272
+ shown: held?.window.level ?? null,
273
+ held: cache.size,
274
+ loading: inFlight.size,
275
+ failed: failed.size,
276
+ requested,
277
+ pixels: held === undefined ? 0 : held.window.cols * TILE_SIZE * held.window.rows * TILE_SIZE,
278
+ };
279
+ },
280
+ dispose() {
281
+ gone = true;
282
+ cancelPending();
283
+ cancelLoading();
284
+ cancelFree();
285
+ release();
286
+ dropTiles();
287
+ },
288
+ };
289
+ }
@@ -0,0 +1,10 @@
1
+ import { type BodyFacts, type BodyId } from "../facts.ts";
2
+ /** The half-width of a body's picture, in its radii, when it has no scale of its own: the globe takes a little under half the height, so its rings, glow and haze have room round it. */
3
+ export declare const ROOM = 2.2;
4
+ export declare function extentOf(f: BodyFacts, options: {
5
+ scaleTo?: BodyId;
6
+ spanKm?: number;
7
+ moons?: boolean;
8
+ range?: number;
9
+ tight?: boolean;
10
+ }): number;
@@ -0,0 +1,21 @@
1
+ // How far from a body's middle to the edge of its picture at zoom 1, in body radii: the size of the picture, which the zoom and the zoom limit are measured against. Pure.
2
+ import { nearMoons } from "../ephemeris.js";
3
+ import { BODIES, ringReach } from "../facts.js";
4
+ /** The half-width of a body's picture, in its radii, when it has no scale of its own: the globe takes a little under half the height, so its rings, glow and haze have room round it. */
5
+ export const ROOM = 2.2;
6
+ export function extentOf(f, options) {
7
+ if (options.moons === true && f.parent === undefined && f.id !== "sun") {
8
+ const near = nearMoons(f.id);
9
+ const far = Math.max(1.8, ringReach(f) * 1.15, ...near.map((m) => m.reach * 1.1));
10
+ return options.range ?? far;
11
+ }
12
+ if (options.spanKm !== undefined)
13
+ return options.spanKm / f.radiusKm;
14
+ if (options.scaleTo !== undefined)
15
+ return (BODIES[options.scaleTo].radiusKm * 1.06) / f.radiusKm;
16
+ if (options.tight !== true)
17
+ return ROOM;
18
+ // tight (a thumbnail): the picture holds the body and its rings, and an irregular body (Deimos, Phobos, Nix, Hydra) whole along its longest axis
19
+ const longest = f.axesKm === undefined ? 1 : Math.max(...f.axesKm) / f.radiusKm;
20
+ return Math.max(1.06, ringReach(f) * 1.04, longest * 1.06);
21
+ }
@@ -1,11 +1,32 @@
1
1
  export declare const VERTEX = "\nvarying vec3 vObj;\nvarying vec3 vN;\nvarying vec3 vW;\nvoid main() {\n vObj = vec3(position.z, position.x, position.y);\n vN = normalize(normalMatrix * normal);\n vec4 w = modelMatrix * vec4(position, 1.0);\n vW = w.xyz;\n gl_Position = projectionMatrix * viewMatrix * w;\n}";
2
2
  /** Noise, craters and the band palette, for the surface code of a body to call. */
3
3
  export declare const PRELUDE = "\nfloat hash13(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }\nvec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); }\nfloat vnoise(vec3 p) {\n vec3 i = floor(p); vec3 f = fract(p); f = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix(hash13(i), hash13(i + vec3(1,0,0)), f.x), mix(hash13(i + vec3(0,1,0)), hash13(i + vec3(1,1,0)), f.x), f.y),\n mix(mix(hash13(i + vec3(0,0,1)), hash13(i + vec3(1,0,1)), f.x), mix(hash13(i + vec3(0,1,1)), hash13(i + vec3(1,1,1)), f.x), f.y), f.z);\n}\n// Noise that knows how big a pixel is: an octave finer than the pixel can show is replaced by its average (0.5) instead of being sampled, so a small body is smooth and not a spray of pixel-sized specks.\nfloat fbm(vec3 p) { float fw = length(fwidth(p)); float a = 0.5; float s = 0.0; for (int i = 0; i < 5; i++) { s += a * mix(0.5, vnoise(p), 1.0 - smoothstep(0.3, 0.7, fw)); p = p * 2.03 + vec3(1.7, 9.2, 3.1); fw *= 2.03; a *= 0.5; } return s; }\n// Craters: a bowl and a raised rim in each cell that has one. Returns a height, negative in a bowl. A crater smaller than about two pixels fades out (it would only be noise).\nfloat craters(vec3 p, float freq, float amp, float seed) {\n vec3 q = p * freq + seed; vec3 ip = floor(q); float h = 0.0;\n float fw = length(fwidth(q));\n for (int x = -1; x <= 1; x++) for (int y = -1; y <= 1; y++) for (int z = -1; z <= 1; z++) {\n vec3 c = ip + vec3(float(x), float(y), float(z));\n float on = step(0.52, hash13(c + 3.7));\n vec3 ctr = c + hash33(c);\n float rad = mix(0.12, 0.36, hash13(c + 17.3));\n float d = length(q - ctr) / rad;\n float bowl = d < 1.0 ? (d * d - 1.0) : 0.0;\n float rim = d >= 1.0 ? exp(-pow((d - 1.0) * 5.0, 2.0)) * 0.3 * smoothstep(1.0, 1.08, d) : 0.0;\n h += on * amp * rad * (bowl + rim) * (1.0 - smoothstep(0.35, 0.9, fw / rad));\n }\n return h;\n}\nfloat lon(vec3 p) { return atan(p.y, p.x); }\nfloat lat(vec3 p) { return asin(clamp(p.z, -1.0, 1.0)); }\nfloat wrapPi(float a) { return a - 6.2831853 * floor((a + 3.1415927) / 6.2831853); }\nvec3 dirOf(float lonDeg, float latDeg) { float lo = radians(lonDeg); float la = radians(latDeg); return vec3(cos(la) * cos(lo), cos(la) * sin(lo), sin(la)); }\n// One big round bowl with a rim, by longitude, latitude and angular radius in degrees. Negative inside.\nfloat bowl(vec3 p, float lonDeg, float latDeg, float radDeg, float depth) {\n float d = acos(clamp(dot(p, dirOf(lonDeg, latDeg)), -1.0, 1.0)) / radians(radDeg);\n return d < 1.0 ? depth * (d * d - 1.0) : depth * exp(-pow((d - 1.0) * 5.0, 2.0)) * 0.3 * smoothstep(1.0, 1.08, d);\n}\n// A soft oval on the body, 1 inside and 0 outside, by longitude and latitude in degrees.\nfloat oval(vec3 p, float lon0, float lat0, float rx, float ry, float soft) {\n float dx = wrapPi(lon(p) - radians(lon0)) * cos(radians(lat0)) / radians(rx);\n float dy = (lat(p) - radians(lat0)) / radians(ry);\n return 1.0 - smoothstep(1.0 - soft, 1.0, sqrt(dx * dx + dy * dy));\n}";
4
- /** The fragment shader of a body: the surface code goes between the prelude and `main`. `limbTint` is the colour the edge of a glowing body shifts to (default the Sun's orange). */
5
- export declare function bodyFragment(surface: string, painted: boolean, world?: boolean, limbTint?: readonly [number, number, number]): string;
4
+ /**
5
+ * The generic fine detail of a close view, for the fragment shader of a body (`bodyFragment` with `detail`). It is not a measured feature of the body: it is noise, put on so that a body never goes smooth when the
6
+ * zoom takes it past the sharpness of its map. `gTexel` is the angle one texel of the picture being read covers (radians); where a pixel is smaller than a texel (the map is enlarged more than about one and a
7
+ * quarter times) octaves of noise are added, each half the size of the one before, each only while its cells are still wider than about two pixels, so nothing is finer than the screen can show and nothing
8
+ * shimmers. `uDetailAmp` is how strong it is (0 turns it off) and `uDetailStretch` stretches it along the lines of latitude (a gas giant's streaks).
9
+ */
10
+ export declare const MICRO_DETAIL = "\nuniform float uTexel;\nuniform float uDetailAmp;\nuniform float uDetailStretch;\nfloat gTexel = 0.003;\nfloat microDetail(vec3 p) {\n if (uDetailAmp <= 0.0) return 1.0;\n float fw = max(length(fwidth(p)), 1e-9);\n float mag = gTexel / fw;\n float fade = smoothstep(1.2, 3.0, mag);\n if (fade <= 0.0) return 1.0;\n float sum = 0.0;\n float amp = 1.0;\n for (int i = 0; i < 6; i++) {\n float cell = gTexel * 0.7 / exp2(float(i));\n float w = smoothstep(1.4, 3.0, cell / fw);\n if (w <= 0.0) break;\n vec3 q = vec3(p.xy, p.z * uDetailStretch) / cell;\n sum += w * amp * (vnoise(q + float(i) * 19.19) - 0.5);\n amp *= 0.58;\n }\n return max(0.0, 1.0 + uDetailAmp * 2.0 * fade * sum);\n}\n";
11
+ /**
12
+ * The fragment shader of a body: the surface code goes between the prelude and `main`. `limbTint` is the colour the edge of a glowing body shifts to (default the Sun's orange). `detail` adds the generic fine
13
+ * detail (`MICRO_DETAIL`) that carries a body past the sharpness of its map; a body that glows never takes it, and without it the shader is the same program as before it existed.
14
+ */
15
+ export declare function bodyFragment(surface: string, painted: boolean, world?: boolean, limbTint?: readonly [number, number, number], detail?: boolean): string;
6
16
  /** A painted body's surface code: the map by longitude and latitude, with the seam at 180 degrees left alone. */
7
17
  export declare const PAINTED_SURFACE = "\nvec4 surface(vec3 p) {\n float u1 = atan(p.y, p.x) / 6.2831853 + 0.5;\n float u2 = fract(u1 + 0.5) - 0.5;\n float v = asin(clamp(p.z, -1.0, 1.0)) / 3.1415927 + 0.5;\n vec2 a = vec2(u1, v); vec2 b = vec2(u2, v);\n vec2 ax = dFdx(a); vec2 ay = dFdy(a); vec2 bx = dFdx(b); vec2 by = dFdy(b);\n bool useA = dot(ax, ax) + dot(ay, ay) <= dot(bx, bx) + dot(by, by);\n vec3 c = textureGrad(uMap, useA ? a : b, useA ? ax : bx, useA ? ay : by).rgb;\n // A map of plain bands is the same at every longitude, so the body turns and the picture does not. The wave, the spot and the polar hexagon move with the surface.\n if (uMark > 0.5) {\n float lon = atan(p.y, p.x);\n float lat = asin(clamp(p.z, -1.0, 1.0));\n float wave = sin(lon * 4.0 + lat * 6.0);\n float belt = 1.0 - smoothstep(1.15, 1.45, abs(lat));\n c *= 0.86 + 0.22 * (0.5 + 0.5 * wave) * belt;\n if (uMark > 1.5) {\n float ang = atan(p.y, p.x);\n float radius = length(p.xy);\n float hexR = 0.26 + 0.045 * cos(ang * 6.0);\n float hex = (1.0 - smoothstep(0.0, 0.028, abs(radius - hexR))) * smoothstep(0.42, 0.68, p.z);\n c = mix(c, vec3(0.45, 0.55, 0.68), hex);\n } else {\n float spot = exp(-pow((lat - 0.32) / 0.2, 2.0) - pow(lon / 0.5, 2.0));\n c = mix(c, c * vec3(0.28, 0.34, 0.5), clamp(spot, 0.0, 1.0));\n }\n }\n return vec4(c, dot(c, vec3(0.3, 0.59, 0.11)));\n}";
18
+ /**
19
+ * A painted body's surface code with a window of finer picture (`uDetail`, placed by `uDetailRect` and softened at its edges by `uDetailFade`, `uDetailOn` is 1 while there is one), and the texel angles `micro` detail
20
+ * (`MICRO_DETAIL`) needs. Use it with `bodyFragment(..., true)`; a glowing body takes `PAINTED_SURFACE`.
21
+ */
22
+ export declare const PAINTED_SURFACE_WINDOWED = "\nuniform sampler2D uDetail;\nuniform vec4 uDetailRect;\nuniform vec2 uDetailFade;\nuniform float uDetailOn;\nuniform float uDetailTexel;\nvec4 surface(vec3 p) {\n float u1 = atan(p.y, p.x) / 6.2831853 + 0.5;\n float u2 = fract(u1 + 0.5) - 0.5;\n float v = asin(clamp(p.z, -1.0, 1.0)) / 3.1415927 + 0.5;\n vec2 a = vec2(u1, v); vec2 b = vec2(u2, v);\n vec2 ax = dFdx(a); vec2 ay = dFdy(a); vec2 bx = dFdx(b); vec2 by = dFdy(b);\n bool useA = dot(ax, ax) + dot(ay, ay) <= dot(bx, bx) + dot(by, by);\n vec3 c = textureGrad(uMap, useA ? a : b, useA ? ax : bx, useA ? ay : by).rgb;\n // The window of finer picture laid over the map: tiles of a sharper level, where they are loaded (see scene/detail.ts). Longitude is measured east of the window's west edge, so a window may cross the seam;\n // the gradients are those of the continuous variant, so the picture is filtered the same on both sides of it.\n gTexel = uTexel;\n if (uDetailOn > 0.5) {\n vec2 q = useA ? a : b;\n vec2 gx = useA ? ax : bx;\n vec2 gy = useA ? ay : by;\n float rx = fract(q.x - uDetailRect.x) / uDetailRect.z;\n float ry = (uDetailRect.y - q.y) / uDetailRect.w;\n if (rx < 1.0 && ry > 0.0 && ry < 1.0) {\n float fx = uDetailFade.x > 0.0 ? min(smoothstep(0.0, uDetailFade.x, rx), smoothstep(0.0, uDetailFade.x, 1.0 - rx)) : 1.0;\n float fy = uDetailFade.y > 0.0 ? min(smoothstep(0.0, uDetailFade.y, ry), smoothstep(0.0, uDetailFade.y, 1.0 - ry)) : 1.0;\n vec3 d = textureGrad(uDetail, vec2(rx, ry), vec2(gx.x / uDetailRect.z, -gx.y / uDetailRect.w), vec2(gy.x / uDetailRect.z, -gy.y / uDetailRect.w)).rgb;\n c = mix(c, d, fx * fy);\n gTexel = mix(uTexel, uDetailTexel, fx * fy);\n }\n }\n // A map of plain bands is the same at every longitude, so the body turns and the picture does not. The wave, the spot and the polar hexagon move with the surface.\n if (uMark > 0.5) {\n float lon = atan(p.y, p.x);\n float lat = asin(clamp(p.z, -1.0, 1.0));\n float wave = sin(lon * 4.0 + lat * 6.0);\n float belt = 1.0 - smoothstep(1.15, 1.45, abs(lat));\n c *= 0.86 + 0.22 * (0.5 + 0.5 * wave) * belt;\n if (uMark > 1.5) {\n float ang = atan(p.y, p.x);\n float radius = length(p.xy);\n float hexR = 0.26 + 0.045 * cos(ang * 6.0);\n float hex = (1.0 - smoothstep(0.0, 0.028, abs(radius - hexR))) * smoothstep(0.42, 0.68, p.z);\n c = mix(c, vec3(0.45, 0.55, 0.68), hex);\n } else {\n float spot = exp(-pow((lat - 0.32) / 0.2, 2.0) - pow(lon / 0.5, 2.0));\n c = mix(c, c * vec3(0.28, 0.34, 0.5), clamp(spot, 0.0, 1.0));\n }\n }\n return vec4(c, dot(c, vec3(0.3, 0.59, 0.11)));\n}";
8
23
  export declare const RING_FRAGMENT = "\nprecision highp float;\nuniform sampler2D uRingTex;\nuniform vec2 uRingR;\nuniform vec3 uLight;\nuniform vec3 uRingN;\nvarying vec3 vL;\nvarying vec3 vW;\nvoid main() {\n float u = (length(vL.xy) - uRingR.x) / (uRingR.y - uRingR.x);\n if (u < 0.0 || u > 1.0) discard;\n vec4 t = texture2D(uRingTex, vec2(u, 0.5));\n float nl = dot(uRingN, uLight);\n float side = nl * uRingN.z;\n float bright = 0.16 + 0.84 * clamp(abs(nl) * 2.0, 0.0, 1.0);\n if (side < 0.0) bright *= 0.38;\n float b = dot(vW, uLight);\n float closest = sqrt(max(dot(vW, vW) - b * b, 0.0));\n float shadow = b < 0.0 ? smoothstep(1.02, 0.97, closest) : 0.0;\n vec3 c = pow(t.rgb, vec3(2.2)) * bright * (1.0 - 0.93 * shadow);\n gl_FragColor = vec4(pow(c, vec3(1.0 / 2.2)), t.a);\n}";
24
+ /**
25
+ * The ring's fragment shader with generic ringlets for a close view: where a texel of the ring's strip (`uRingTexel`, its width as a fraction of the ring's span) is more than about a pixel and a quarter wide, noise
26
+ * along the radius, octave by octave, finer than the strip, only while its cells are still two or more pixels wide. It is not a measured feature of the rings: the strip's own opacity and colour, its gaps and the planet's
27
+ * shadow stay as they were, and the detail only makes the strip's blur ringlets. Where a texel is smaller than a pixel it changes nothing.
28
+ */
29
+ export declare const RING_FRAGMENT_DETAIL: string;
9
30
  export declare const RING_VERTEX = "\nvarying vec3 vL;\nvarying vec3 vW;\nvoid main() {\n vL = position;\n vec4 w = modelMatrix * vec4(position, 1.0);\n vW = w.xyz;\n gl_Position = projectionMatrix * viewMatrix * w;\n}";
10
31
  /**
11
32
  * The body's vertex shader for a perspective camera and a body anywhere in the scene: the normal and the position are in the scene's axes, the position in body radii from the body's centre