@johnmorrisdotca/wakusei-planets 0.28.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/NOTICE.md +20 -0
  3. package/README.md +61 -16
  4. package/dist/embed.d.ts +64 -0
  5. package/dist/embed.js +66 -0
  6. package/dist/index.d.ts +4 -1
  7. package/dist/index.js +4 -1
  8. package/dist/lineup/data.d.ts +160 -0
  9. package/dist/lineup/data.js +303 -0
  10. package/dist/lineup/element.d.ts +99 -0
  11. package/dist/lineup/element.js +782 -0
  12. package/dist/lineup/labels.d.ts +141 -0
  13. package/dist/lineup/labels.js +155 -0
  14. package/dist/lineup/layout.d.ts +174 -0
  15. package/dist/lineup/layout.js +162 -0
  16. package/dist/lineup/scene3d.d.ts +47 -0
  17. package/dist/lineup/scene3d.js +155 -0
  18. package/dist/portrait/element.d.ts +5 -2
  19. package/dist/portrait/element.js +57 -6
  20. package/dist/portrait/scene3d.d.ts +13 -0
  21. package/dist/portrait/scene3d.js +21 -2
  22. package/dist/scene/body.d.ts +3 -1
  23. package/dist/scene/body.js +2 -1
  24. package/dist/scene/detail.d.ts +8 -2
  25. package/dist/scene/detail.js +56 -28
  26. package/dist/scene/painter.d.ts +32 -0
  27. package/dist/scene/painter.js +94 -10
  28. package/dist/scene/textures.d.ts +4 -2
  29. package/dist/scene/textures.js +2 -0
  30. package/dist/scene/tiles.d.ts +46 -0
  31. package/dist/scene/tiles.js +165 -19
  32. package/dist/space/arrows.d.ts +87 -0
  33. package/dist/space/arrows.js +117 -0
  34. package/dist/space/beside.d.ts +74 -0
  35. package/dist/space/beside.js +76 -0
  36. package/dist/space/bodies.d.ts +83 -0
  37. package/dist/space/bodies.js +93 -0
  38. package/dist/space/clock.d.ts +31 -0
  39. package/dist/space/clock.js +45 -0
  40. package/dist/space/element.d.ts +98 -15
  41. package/dist/space/element.js +320 -63
  42. package/dist/space/frame.d.ts +45 -2
  43. package/dist/space/frame.js +56 -4
  44. package/dist/space/index.d.ts +6 -1
  45. package/dist/space/index.js +6 -1
  46. package/dist/space/labels.d.ts +52 -0
  47. package/dist/space/labels.js +40 -0
  48. package/dist/space/scale.d.ts +5 -5
  49. package/dist/space/scale.js +10 -4
  50. package/dist/space/scene.d.ts +50 -9
  51. package/dist/space/scene.js +313 -36
  52. package/dist/space/spin.d.ts +37 -0
  53. package/dist/space/spin.js +29 -0
  54. package/dist/version.d.ts +1 -1
  55. package/dist/version.js +1 -1
  56. package/package.json +8 -1
@@ -0,0 +1,155 @@
1
+ import { makeBodyMaterial } from "../scene/body.js";
2
+ import { STAR_GLOW_FRAGMENT, GLOW_VERTEX } from "../scene/glsl.js";
3
+ import { createPainter } from "../scene/painter.js";
4
+ import "../bodies/earth.js";
5
+ import "../bodies/jupiter.js";
6
+ /** A body smaller than this many pixels across its radius is not drawn at all: it would be nothing but noise. */
7
+ const MIN_RADIUS_PX = 0.2;
8
+ /** How fast a body turns on the page, in degrees a second: slow, so it is easy to see and easy to take hold of. A planet is the same for every planet. */
9
+ const PLANET_TURN = 8;
10
+ const turnOf = (star) => Math.min(10, Math.max(2, Math.abs(star.turn.degreesPerSecond) * 0.5)) * Math.sign(star.turn.degreesPerSecond || 1);
11
+ /**
12
+ * The item the shared renderer shows for a line-up: its `build` makes the scene, whose `apply` is handed each state.
13
+ */
14
+ export function createLineupItem(options) {
15
+ return {
16
+ key: options.key,
17
+ build({ three: T, assets, width, height }) {
18
+ const scene = new T.Scene();
19
+ const camera = new T.OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
20
+ const painter = createPainter({ textureBase: options.textureBase(), farBase: options.farBase() });
21
+ const sphere = assets.acquire("lu:sphere", () => new T.SphereGeometry(1, 128, 64), (g) => g.dispose());
22
+ const glowGeometry = assets.acquire("wk:glow", () => new T.PlaneGeometry(6, 6), (g) => g.dispose());
23
+ const items = new Map();
24
+ for (const body of options.bodies) {
25
+ const group = new T.Group();
26
+ group.name = body.name.en;
27
+ const item = { place: body, group, angle: 0, rate: PLANET_TURN };
28
+ if (body.kind === "star") {
29
+ const star = options.stars.get(body.id);
30
+ item.look = star;
31
+ item.rate = turnOf(star);
32
+ item.material = assets.acquire(`lu:star:${star.key}`, () => makeBodyMaterial(T, star.look, false), (m) => m.dispose());
33
+ item.mesh = new T.Mesh(sphere, item.material);
34
+ item.mesh.frustumCulled = false;
35
+ group.add(item.mesh);
36
+ const own = star.look.glow;
37
+ if (own !== undefined) {
38
+ item.glowMaterial = assets.acquire(`lu:glow:${star.key}`, () => new T.ShaderMaterial({ vertexShader: GLOW_VERTEX, fragmentShader: STAR_GLOW_FRAGMENT, transparent: true, depthWrite: false, blending: T.AdditiveBlending, uniforms: { uColour: { value: new T.Vector3(...own.colour) }, uStrength: { value: own.strength }, uSpread: { value: own.spread }, uRim: { value: own.rim ?? 0 }, uProm: { value: own.prominence ?? 0 }, uSeed: { value: own.seed ?? 0 }, uTime: { value: 0 } } }), (m) => m.dispose());
39
+ item.glow = new T.Mesh(glowGeometry, item.glowMaterial);
40
+ item.glow.position.z = -5;
41
+ item.glow.frustumCulled = false;
42
+ group.add(item.glow);
43
+ }
44
+ }
45
+ else {
46
+ item.painting = painter.make(T, body.body, { look: options.look, invalidate: () => options.redraw(), ratio: Math.min(2, globalThis.devicePixelRatio || 1), maxTexture: 2048 });
47
+ group.add(item.painting.object);
48
+ }
49
+ group.visible = false;
50
+ scene.add(group);
51
+ items.set(body.id, item);
52
+ }
53
+ let viewWidth = width;
54
+ let viewHeight = height;
55
+ let latest = options.state();
56
+ let after = [];
57
+ let shown = [];
58
+ let moving = false;
59
+ const light = [-0.6, 0.2, 0.77];
60
+ const norm = Math.hypot(...light);
61
+ const toSun = [light[0] / norm, light[1] / norm, light[2] / norm];
62
+ /** Put every body where it is, turn it, and fit the camera's depth to the biggest one in the picture. */
63
+ const apply = (state) => {
64
+ latest = state;
65
+ const aspect = viewWidth / Math.max(1, viewHeight);
66
+ const halfH = state.view.h;
67
+ const halfW = halfH * aspect;
68
+ const pxPerUnit = viewHeight / (2 * halfH);
69
+ shown = [];
70
+ let biggest = 0;
71
+ for (const place of state.places) {
72
+ const item = items.get(place.body.id);
73
+ if (item === undefined)
74
+ continue;
75
+ const r = place.r;
76
+ const inPicture = Math.abs(place.x - state.view.x) - r < halfW && Math.abs(place.y - state.view.y) - r < halfH && r * pxPerUnit >= MIN_RADIUS_PX;
77
+ item.group.visible = inPicture;
78
+ if (!inPicture)
79
+ continue;
80
+ shown.push(place.body.id);
81
+ biggest = Math.max(biggest, r);
82
+ const hand = state.hands.get(place.body.id) ?? { yaw: 0, pitch: 0 };
83
+ const yaw = ((item.angle + hand.yaw) * Math.PI) / 180;
84
+ const pitch = (hand.pitch * Math.PI) / 180;
85
+ item.group.position.set(place.x - state.view.x, place.y - state.view.y, 0);
86
+ item.group.scale.setScalar(r);
87
+ if (item.mesh !== undefined && item.look !== undefined) {
88
+ const squash = 1 - item.look.oblateness;
89
+ item.mesh.rotation.set(pitch, yaw, 0, "XYZ");
90
+ item.mesh.scale.set(1, squash, 1);
91
+ if (item.glow !== undefined && item.look.oblateness > 0)
92
+ item.glow.scale.set(1, Math.sqrt(squash * squash * Math.cos(pitch) ** 2 + Math.sin(pitch) ** 2), 1);
93
+ const seconds = (performance.now() / 1000) % 100_000;
94
+ item.material.uniforms.uTime.value = seconds;
95
+ if (item.glowMaterial !== undefined)
96
+ item.glowMaterial.uniforms.uTime.value = seconds;
97
+ }
98
+ else if (item.painting !== undefined) {
99
+ const pole = [0, Math.cos(pitch), Math.sin(pitch)];
100
+ // the prime meridian faces the viewer at yaw 0 and goes round the pole with the turn
101
+ const meridian = [Math.sin(yaw), -Math.sin(pitch) * Math.cos(yaw), Math.cos(pitch) * Math.cos(yaw)];
102
+ item.painting.update({ toSun, ms: 0, radiusPx: r * pxPerUnit, pose: { pole, meridian } });
103
+ }
104
+ }
105
+ // the camera sits at the middle of the picture; everything is drawn round it, and its depth holds the biggest body and its glow
106
+ const R = Math.max(1e-9, biggest);
107
+ camera.left = -halfW;
108
+ camera.right = halfW;
109
+ camera.top = halfH;
110
+ camera.bottom = -halfH;
111
+ camera.position.set(0, 0, 4 * R);
112
+ camera.near = 4 * R - 1.5 * R;
113
+ camera.far = 4 * R + 6 * R;
114
+ camera.updateProjectionMatrix();
115
+ moving = state.spin && shown.length > 0;
116
+ };
117
+ apply(latest);
118
+ return {
119
+ scene,
120
+ camera,
121
+ apply,
122
+ get drawn() {
123
+ return shown;
124
+ },
125
+ afterDraw(fn) {
126
+ after.push(fn);
127
+ },
128
+ resize(w, h) {
129
+ viewWidth = w;
130
+ viewHeight = h;
131
+ apply(latest);
132
+ },
133
+ update(dt) {
134
+ if (after.length > 0) {
135
+ const run = after;
136
+ after = [];
137
+ queueMicrotask(() => run.forEach((fn) => fn()));
138
+ }
139
+ if (!moving)
140
+ return false;
141
+ for (const [id, item] of items)
142
+ if (item.group.visible && id !== latest.holding)
143
+ item.angle = (item.angle + item.rate * dt) % 360;
144
+ apply(latest);
145
+ return true;
146
+ },
147
+ dispose() {
148
+ for (const item of items.values())
149
+ item.painting?.dispose();
150
+ scene.clear();
151
+ },
152
+ };
153
+ },
154
+ };
155
+ }
@@ -3,6 +3,7 @@ import type { ThreeParts } from "../scene/body.ts";
3
3
  import { setThreeLoader } from "../scene/shared.ts";
4
4
  import "../element.ts";
5
5
  import { type Guide, type Placed, type Portrait, type Resolved } from "./model.ts";
6
+ import { type PortraitScene } from "./scene3d.ts";
6
7
  export { setThreeLoader };
7
8
  /**
8
9
  * What the element is doing: `line` (an SVG), `loading`, `still`, `live`, `lost` or `unavailable` (no WebGL: the line drawing is shown).
@@ -20,10 +21,10 @@ export type PortraitState = "line" | "loading" | "still" | "live" | "lost" | "un
20
21
  * The `<wakusei-portrait>` custom element: a scene of bodies arranged on one picture.
21
22
  *
22
23
  * Attributes: `scene` (the scene as the portrait builder writes it in its address), `look` (`line`, `realistic` or `painted`: replaces the scene's), `size` (pixels across), `lang` (`en` or `ja`: the names),
23
- * `live` (`always`, `hover` or `off`: when it takes the page's one WebGL context), `texture-base` and `texture-far-base` (where the surface pictures are).
24
+ * `live` (`always`, `hover` or `off`: when it takes the page's one WebGL context), `texture-base` and `texture-far-base` (where the surface pictures are), and `tiles` (where the finer map tiles are, for a close zoom; `off` for none).
24
25
  *
25
26
  * It carries the shared view controls itself: a drag moves the picture, two fingers pinch, Ctrl, Command or Alt with the wheel zooms (the plain wheel scrolls the page at Fit), and the arrow keys, + and - and 0 work once it is focused.
26
- * `controls="none"` turns them off (the portrait builder does, for it edits the scene by dragging its bodies); `zoom-min` and `zoom-max` set the range (0.1 to 8 by default); a `<kazoku-view-controls for="...">` takes over and reads it.
27
+ * `controls="none"` turns them off (the portrait builder does, for it edits the scene by dragging its bodies); `zoom-min` and `zoom-max` set the range (0.1 to 8 by default, and further for a body with finer map tiles: see the close zoom guide); a `<kazoku-view-controls for="...">` takes over and reads it.
27
28
  *
28
29
  * @example
29
30
  * ```ts no-run
@@ -51,6 +52,8 @@ export declare class WakuseiPortrait extends HTMLElement {
51
52
  state: PortraitState;
52
53
  bodies: number;
53
54
  renderer: SharedRenderer<ThreeParts>["stats"] | undefined;
55
+ tiles: PortraitScene["tiles"] | undefined;
56
+ zoomMax: number | undefined;
54
57
  };
55
58
  /** Where everything is on the page now: the picture's size in pixels, pixels to a scene unit, and the bodies (back to front). */
56
59
  get metrics(): {
@@ -4,7 +4,9 @@ import { createGate, frameCap } from "../gate.js";
4
4
  import { setThreeLoader, takeRenderer } from "../scene/shared.js";
5
5
  // /portrait has always registered the body element as well.
6
6
  import "../element.js";
7
- import { texturePaths } from "../scene/textures.js";
7
+ import { texturePaths, tilesBase } from "../scene/textures.js";
8
+ import { detailOf, lookOf } from "../scene/look.js";
9
+ import { mapWidthOf, ringWidthOf, zoomLimit } from "../scene/reach.js";
8
10
  import { backgroundCss, drawShapes, lineScene, paintBackground, shapesOf, shapesSvg, starfield } from "./overlay.js";
9
11
  import { decodeScene, defaultPortrait, encodeScene, fromScreen, hitTest, resolve, toScreen } from "./model.js";
10
12
  import { REDUCED_TURN } from "../live.js";
@@ -12,8 +14,9 @@ import { poseOf } from "./pose.js";
12
14
  import { createPortraitItem } from "./scene3d.js";
13
15
  export { setThreeLoader };
14
16
  /**
15
- * The zoom range of a portrait that carries its own controls. The floor is arbitrary: a tenth of Fit leaves room to see the whole scene small. The ceiling is the painted maps: the sharpest is 2048 pixels round
16
- * a body, which stays sharp to a few times the size at Fit and softens after that; 8 times is as far as the bodies' own shader detail goes. A scene of a line look has detail at any scale.
17
+ * The zoom range of a portrait that carries its own controls, before it knows what its bodies have. The floor is arbitrary: a tenth of Fit leaves room to see the whole scene small. The ceiling is as far as the
18
+ * bodies' own pictures go: 8 times is where the 2048 pixel maps and the shader detail run out. A shaded scene goes further where a body has finer map tiles (`#limits`), as far as the farthest-reaching body in it;
19
+ * a scene of a line look stays here, so a scene can change look without the range changing under it.
17
20
  */
18
21
  const CARRIED_LIMITS = { zoomMin: 0.1, zoomMax: 8 };
19
22
  const TEMPLATE = `<style>
@@ -30,10 +33,10 @@ const num = (value, fallback) => {
30
33
  * The `<wakusei-portrait>` custom element: a scene of bodies arranged on one picture.
31
34
  *
32
35
  * Attributes: `scene` (the scene as the portrait builder writes it in its address), `look` (`line`, `realistic` or `painted`: replaces the scene's), `size` (pixels across), `lang` (`en` or `ja`: the names),
33
- * `live` (`always`, `hover` or `off`: when it takes the page's one WebGL context), `texture-base` and `texture-far-base` (where the surface pictures are).
36
+ * `live` (`always`, `hover` or `off`: when it takes the page's one WebGL context), `texture-base` and `texture-far-base` (where the surface pictures are), and `tiles` (where the finer map tiles are, for a close zoom; `off` for none).
34
37
  *
35
38
  * It carries the shared view controls itself: a drag moves the picture, two fingers pinch, Ctrl, Command or Alt with the wheel zooms (the plain wheel scrolls the page at Fit), and the arrow keys, + and - and 0 work once it is focused.
36
- * `controls="none"` turns them off (the portrait builder does, for it edits the scene by dragging its bodies); `zoom-min` and `zoom-max` set the range (0.1 to 8 by default); a `<kazoku-view-controls for="...">` takes over and reads it.
39
+ * `controls="none"` turns them off (the portrait builder does, for it edits the scene by dragging its bodies); `zoom-min` and `zoom-max` set the range (0.1 to 8 by default, and further for a body with finer map tiles: see the close zoom guide); a `<kazoku-view-controls for="...">` takes over and reads it.
37
40
  *
38
41
  * @example
39
42
  * ```ts no-run
@@ -71,6 +74,8 @@ export class WakuseiPortrait extends HTMLElement {
71
74
  #overKey = "";
72
75
  #lineKey = "";
73
76
  #zoom = 1;
77
+ #tileLevels = new Map();
78
+ #limitKey = "";
74
79
  #panX = 0;
75
80
  #panY = 0;
76
81
  #hands;
@@ -96,6 +101,7 @@ export class WakuseiPortrait extends HTMLElement {
96
101
  set portrait(value) {
97
102
  this.#portrait = value;
98
103
  this.#fromAttributes = false;
104
+ this.#refreshLimits();
99
105
  this.#changed();
100
106
  }
101
107
  /** The chosen body's index and the guides to draw over the picture (the builder's editing). */
@@ -108,7 +114,7 @@ export class WakuseiPortrait extends HTMLElement {
108
114
  }
109
115
  /** Numbers for a test or a status line. */
110
116
  get stats() {
111
- return { state: this.#state, bodies: this.#resolved.placed.length, renderer: this.#renderer?.stats };
117
+ return { state: this.#state, bodies: this.#resolved.placed.length, renderer: this.#renderer?.stats, tiles: this.#view?.scene?.tiles, zoomMax: this.#hands?.controller.limits.zoomMax };
112
118
  }
113
119
  /** Where everything is on the page now: the picture's size in pixels, pixels to a scene unit, and the bodies (back to front). */
114
120
  get metrics() {
@@ -161,6 +167,7 @@ export class WakuseiPortrait extends HTMLElement {
161
167
  this.#applyHover();
162
168
  this.#readAttributes();
163
169
  this.#hands = carryControls(this, { turnable: false, limits: CARRIED_LIMITS, onChange: (view) => this.setView(view) });
170
+ this.#refreshLimits();
164
171
  this.#queue();
165
172
  }
166
173
  disconnectedCallback() {
@@ -264,6 +271,43 @@ export class WakuseiPortrait extends HTMLElement {
264
271
  if (look === "line" || look === "realistic" || look === "painted" || look === "illustrated")
265
272
  p.look = look;
266
273
  this.#portrait = p;
274
+ this.#refreshLimits();
275
+ }
276
+ /**
277
+ * The zoom range now: a line scene, or one of bodies with no finer maps, `CARRIED_LIMITS`; a shaded scene as far as its farthest-reaching body goes by the table of `scene/reach.ts` (each body measured in the
278
+ * radii its picture reaches at zoom 1, from the middle of the short side of the view to its edge, on the widest map it has, the finest tile level once the tiles are found, and on whether its surface is soft).
279
+ */
280
+ #limits() {
281
+ const p = this.#portrait;
282
+ if (p.look === "line")
283
+ return CARRIED_LIMITS;
284
+ const { placed, camera } = resolve(p);
285
+ const { width, height } = this.#size();
286
+ const half = camera.h * Math.min(1, width / Math.max(1, height));
287
+ let zoomMax = CARRIED_LIMITS.zoomMax;
288
+ for (const one of placed) {
289
+ if (one.r <= 0)
290
+ continue;
291
+ const look = lookOf(one.body);
292
+ if (look === undefined)
293
+ continue;
294
+ const painted = p.look !== "illustrated" && look.painted !== undefined;
295
+ const smooth = detailOf(look).stretch > 1;
296
+ const extent = half / one.r;
297
+ zoomMax = Math.max(zoomMax, look.emissive === true ? zoomLimit(1, 0, false) : zoomLimit(extent, mapWidthOf(look, painted, this.#tileLevels.get(one.body)), smooth, painted ? ringWidthOf(look, BODIES[one.body].radiusKm) : 0));
298
+ }
299
+ return { zoomMin: CARRIED_LIMITS.zoomMin, zoomMax };
300
+ }
301
+ /** Tell the shared controls the zoom range, when it has changed (a new scene, the tiles of a body found). */
302
+ #refreshLimits() {
303
+ if (this.#hands === undefined)
304
+ return;
305
+ const limits = this.#limits();
306
+ const key = `${limits.zoomMax}`;
307
+ if (key === this.#limitKey)
308
+ return;
309
+ this.#limitKey = key;
310
+ this.#hands.setLimits(limits);
267
311
  }
268
312
  #lang() {
269
313
  return this.getAttribute("lang") === "ja" ? "ja" : "en";
@@ -438,6 +482,13 @@ export class WakuseiPortrait extends HTMLElement {
438
482
  key: this.#viewKey,
439
483
  state: () => this.#draw(),
440
484
  ...texturePaths(this),
485
+ tilesBase: () => tilesBase(this),
486
+ onLevels: (body, levels) => {
487
+ this.#tileLevels.set(body, levels);
488
+ this.#refreshLimits();
489
+ // the bodies are told of the camera when the scene is applied, not when it is drawn: once the tile set is read, apply it again so the window the view needs is asked for
490
+ this.#changed();
491
+ },
441
492
  redraw: () => this.#view?.invalidate(),
442
493
  });
443
494
  this.#view = this.#renderer.view(this.#stage, item);
@@ -1,5 +1,7 @@
1
1
  import type { Item3D, Scene3D } from "@johnmorrisdotca/kazoku-ui/renderer";
2
+ import type { BodyId } from "../facts.ts";
2
3
  import type { ThreeParts } from "../scene/body.ts";
4
+ import type { TileLevel } from "../scene/tiles.ts";
3
5
  import "../bodies/all.ts";
4
6
  import { type Placed, type Resolved } from "./model.ts";
5
7
  /** Everything that decides how the scene looks at one draw. */
@@ -23,6 +25,13 @@ export interface PortraitScene extends Scene3D {
23
25
  afterDraw(fn: () => void): void;
24
26
  /** The paintings the scene holds now. */
25
27
  readonly bodies: number;
28
+ /** What the windows of finer map tiles on the bodies are doing, summed: tile fetches made, tiles being fetched, windows and the finest level on a body now (`null` for none), and windows or tiles that failed. */
29
+ readonly tiles: {
30
+ requested: number;
31
+ loading: number;
32
+ failed: number;
33
+ shown: number | null;
34
+ };
26
35
  }
27
36
  export interface PortraitItemOptions {
28
37
  /** A key that changes whenever the picture would: the renderer keeps one still for each key. */
@@ -30,6 +39,10 @@ export interface PortraitItemOptions {
30
39
  state(): PortraitDraw;
31
40
  textureBase(): string;
32
41
  farBase(): string;
42
+ /** Where the finer map tiles are, or `undefined` for none. */
43
+ tilesBase(): string | undefined;
44
+ /** Told when a body's tile levels are known (`undefined` when it has none), so the zoom range can follow. */
45
+ onLevels(body: BodyId, levels: readonly TileLevel[] | undefined): void;
33
46
  redraw(): void;
34
47
  }
35
48
  /**
@@ -27,7 +27,7 @@ export function createPortraitItem(options) {
27
27
  return {
28
28
  key: options.key,
29
29
  build({ three: T, width, height }) {
30
- const painter = createPainter({ textureBase: options.textureBase(), farBase: options.farBase() });
30
+ const painter = createPainter({ textureBase: options.textureBase(), farBase: options.farBase(), tiles: options.tilesBase() ?? "off" });
31
31
  const scene = new T.Scene();
32
32
  const camera = new T.OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
33
33
  const held = new Map();
@@ -67,11 +67,12 @@ export function createPortraitItem(options) {
67
67
  camera.far = distance + slot;
68
68
  camera.position.set(cam.x, cam.y, distance);
69
69
  camera.updateProjectionMatrix();
70
+ camera.updateMatrixWorld();
70
71
  const toSun = lightVector(state.light);
71
72
  placed.forEach((p, i) => {
72
73
  let one = held.get(p.body);
73
74
  if (one === undefined) {
74
- const painting = painter.make(T, p.body, { look: state.look, invalidate: () => options.redraw(), ratio: ratio(), maxTexture: placed.length > 6 ? 1024 : 2048 });
75
+ const painting = painter.make(T, p.body, { look: state.look, invalidate: () => options.redraw(), ratio: ratio(), maxTexture: placed.length > 6 ? 1024 : 2048, onLevels: (levels) => options.onLevels(p.body, levels) });
75
76
  scene.add(painting.object);
76
77
  one = { painting, look: state.look };
77
78
  held.set(p.body, one);
@@ -86,6 +87,7 @@ export function createPortraitItem(options) {
86
87
  radiusPx: r * pxPerUnit,
87
88
  pose: { pole: pose.pole, meridian: pose.meridian },
88
89
  ...(state.shadows ? { occluders: occludersFor(placed, i) } : {}),
90
+ view: { camera, width: viewWidth, height: viewHeight },
89
91
  });
90
92
  });
91
93
  };
@@ -97,6 +99,23 @@ export function createPortraitItem(options) {
97
99
  get bodies() {
98
100
  return held.size;
99
101
  },
102
+ get tiles() {
103
+ let requested = 0;
104
+ let loading = 0;
105
+ let failed = 0;
106
+ let shown = null;
107
+ for (const one of held.values()) {
108
+ const stats = one.painting.tiles;
109
+ if (stats === undefined)
110
+ continue;
111
+ requested += stats.requested;
112
+ loading += stats.loading;
113
+ failed += stats.failed;
114
+ if (stats.shown !== null)
115
+ shown = Math.max(shown ?? 0, stats.shown);
116
+ }
117
+ return { requested, loading, failed, shown };
118
+ },
100
119
  afterDraw(fn) {
101
120
  after.push(fn);
102
121
  },
@@ -7,7 +7,7 @@ import { type DetailStats } from "./detail.ts";
7
7
  import type { TileLevel } from "./tiles.ts";
8
8
  export { fallbackLook } from "./fallback.ts";
9
9
  /** The parts of three.js the bodies use: a page may hand over a module with only these (see `setThreeLoader`). */
10
- export type ThreeParts = Pick<typeof THREE, "AdditiveBlending" | "BufferAttribute" | "BufferGeometry" | "ClampToEdgeWrapping" | "DataTexture" | "DoubleSide" | "Group" | "Line" | "LineBasicMaterial" | "LinearFilter" | "Mesh" | "NoColorSpace" | "OrthographicCamera" | "PlaneGeometry" | "RepeatWrapping" | "RGBAFormat" | "RingGeometry" | "Scene" | "ShaderMaterial" | "SphereGeometry" | "TextureLoader" | "Vector2" | "Vector3" | "WebGLRenderer">;
10
+ export type ThreeParts = Pick<typeof THREE, "AdditiveBlending" | "BufferAttribute" | "BufferGeometry" | "ClampToEdgeWrapping" | "DataTexture" | "DoubleSide" | "Group" | "Line" | "LineBasicMaterial" | "LineSegments" | "LinearFilter" | "Mesh" | "NoColorSpace" | "OrthographicCamera" | "PlaneGeometry" | "RepeatWrapping" | "RGBAFormat" | "RingGeometry" | "Scene" | "ShaderMaterial" | "SphereGeometry" | "TextureLoader" | "Vector2" | "Vector3" | "WebGLRenderer">;
11
11
  /** One moon in a system view: its place in planet radii (viewer's frame) and the points of its orbit, if they changed. */
12
12
  export interface MoonDraw {
13
13
  id: BodyId;
@@ -76,6 +76,8 @@ export interface BodyItemOptions {
76
76
  onLevels?(levels: readonly TileLevel[] | undefined): void;
77
77
  };
78
78
  }
79
+ /** The shader material of a body: its surface code with the look's lighting and glow uniforms. A star made from numbers is drawn with it too (the size line-up). */
80
+ export declare function makeBodyMaterial(T: ThreeParts, look: BodyLook, painted: boolean): THREE.ShaderMaterial;
79
81
  /**
80
82
  * The shared-renderer item for a body: what `renderer.view(host, item)` shows. `state()` is read when the scene is built and `apply` moves it afterwards.
81
83
  *
@@ -9,7 +9,8 @@ import { writeBasis } from "./basis.js";
9
9
  import { loadImage } from "./textures.js";
10
10
  import { ringStrip } from "./rings.js";
11
11
  export { fallbackLook } from "./fallback.js";
12
- function makeBodyMaterial(T, look, painted) {
12
+ /** The shader material of a body: its surface code with the look's lighting and glow uniforms. A star made from numbers is drawn with it too (the size line-up). */
13
+ export function makeBodyMaterial(T, look, painted) {
13
14
  const a = look.atmosphere;
14
15
  // a glowing body (the Sun, a star) is drawn as it always was: no window of finer map and no generic detail
15
16
  const generic = look.emissive !== true;
@@ -1,5 +1,5 @@
1
1
  import type * as THREE from "three";
2
- import { type Axes, type TileLevel, type ViewBox } from "./tiles.ts";
2
+ import { type Axes, type Seen, type TileLevel, type ViewBox } from "./tiles.ts";
3
3
  type Three = Pick<typeof THREE, "ClampToEdgeWrapping" | "DataTexture" | "LinearFilter" | "NoColorSpace">;
4
4
  /** Milliseconds a window that the view no longer needs is kept (the view may come straight back) before its texture is freed. */
5
5
  export declare const DETAIL_KEEP_MS = 4000;
@@ -61,8 +61,14 @@ export interface DetailDeps {
61
61
  now?: () => number;
62
62
  }
63
63
  export interface Detail {
64
- /** Called at each draw with where the camera is and the body's axes. */
64
+ /** Called at each draw with where the camera is and the body's axes (an orthographic camera looking straight at the body, as `<wakusei-body>` has). The tile set is read at the first call. */
65
65
  sync(box: ViewBox, axes: Axes, viewWidth: number): void;
66
+ /**
67
+ * Called at each draw of a body seen by any camera (`seenRegion`): what the camera sees of it, or `undefined` for none. The tile set is read only once the 2048 pixel map is not sharp enough for the view.
68
+ */
69
+ follow(seen: Seen | undefined): void;
70
+ /** Called at a draw when the body is too small in the view to want tiles at all: nothing is read, and what is held is let go after a few seconds. */
71
+ rest(): void;
66
72
  readonly stats: DetailStats;
67
73
  dispose(): void;
68
74
  }
@@ -1,4 +1,4 @@
1
- import { chooseWindow, covers, parseManifest, tilePath, visibleRegion, windowRect, windowTiles, TILE_SIZE, texelAngle } from "./tiles.js";
1
+ import { chooseWindow, covers, parseManifest, tilePath, visibleRegion, windowRect, windowTiles, BASE_WIDTH, TEXEL_SLACK, TILE_SIZE, texelAngle } from "./tiles.js";
2
2
  /** Milliseconds a window that the view no longer needs is kept (the view may come straight back) before its texture is freed. */
3
3
  export const DETAIL_KEEP_MS = 4000;
4
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. */
@@ -221,49 +221,77 @@ export function createDetail(T, deps) {
221
221
  deps.redraw();
222
222
  });
223
223
  };
224
+ const idle = () => {
225
+ wantLevel = null;
226
+ cancelPending();
227
+ scheduleFree();
228
+ };
229
+ // what the view needs, whoever works out the region: the window, loaded after the view has settled
230
+ const track = (region, inside, radiansPixels) => {
231
+ const want = region === undefined ? undefined : chooseWindow(region, levels, radiansPixels);
232
+ wantLevel = want?.level ?? null;
233
+ if (want === undefined) {
234
+ cancelPending();
235
+ scheduleFree();
236
+ return;
237
+ }
238
+ cancelFree();
239
+ if (held !== undefined && held.window.level >= want.level && inside !== undefined && covers(held.window, inside)) {
240
+ cancelPending();
241
+ return;
242
+ }
243
+ const key = keyOf(want);
244
+ if (held?.key === key || loading?.key === key || pending?.key === key)
245
+ return;
246
+ const lastFailed = failed.get(key);
247
+ if (lastFailed !== undefined && clock() - lastFailed < RETRY_MS)
248
+ return;
249
+ cancelPending();
250
+ pending = {
251
+ key,
252
+ timer: setTimeout(() => {
253
+ pending = undefined;
254
+ if (!gone)
255
+ load(want);
256
+ }, DETAIL_SETTLE_MS),
257
+ };
258
+ };
224
259
  return {
225
260
  sync(box, axes, viewWidth) {
226
261
  if (gone)
227
262
  return;
228
263
  const base = deps.base();
229
264
  if (base === undefined || !deps.allowed()) {
230
- wantLevel = null;
231
- scheduleFree();
265
+ idle();
232
266
  return;
233
267
  }
234
268
  ask(base);
235
269
  if (levels === undefined)
236
270
  return;
237
271
  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();
272
+ track(region, region === undefined ? undefined : visibleRegion(box, axes, 0), (deps.ratio() * viewWidth) / Math.max(1e-9, box.right - box.left));
273
+ },
274
+ follow(seen) {
275
+ if (gone)
244
276
  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();
277
+ const base = deps.base();
278
+ if (base === undefined || !deps.allowed()) {
279
+ idle();
250
280
  return;
251
281
  }
252
- const key = keyOf(want);
253
- if (held?.key === key || loading?.key === key || pending?.key === key)
282
+ // the tile set is read when the view wants more than the 2048 pixel map gives, not before: a page that never gets that close fetches nothing
283
+ const radiansPixels = seen === undefined ? 0 : seen.radiansPixels * deps.ratio();
284
+ if (seen !== undefined && radiansPixels / TEXEL_SLACK > BASE_WIDTH / (2 * Math.PI))
285
+ ask(base);
286
+ if (levels === undefined) {
287
+ idle();
254
288
  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
- };
289
+ }
290
+ track(seen?.region, seen?.inside, radiansPixels);
291
+ },
292
+ rest() {
293
+ if (!gone)
294
+ idle();
267
295
  },
268
296
  get stats() {
269
297
  return {
@@ -1,6 +1,8 @@
1
1
  import type * as THREE from "three";
2
2
  import "../bodies/all.ts";
3
3
  import { type Vec3 } from "../vec.ts";
4
+ import { type DetailStats } from "./detail.ts";
5
+ import { type TileLevel } from "./tiles.ts";
4
6
  import { moonOffset, orientation } from "./orient.ts";
5
7
  export { moonOffset, orientation };
6
8
  /**
@@ -41,12 +43,36 @@ export type PainterLook = (typeof LOOKS)[number];
41
43
  export interface PaintContext {
42
44
  /** `realistic` (the default) or `painted`. */
43
45
  look?: string;
46
+ /** True to draw every body that has a surface picture from it, in any look (the space view does: a planet or a moon with a real map never shows the shaded look instead). A body with no picture is still shaded. */
47
+ mapped?: boolean;
44
48
  /** Ask for a new draw: a sharper picture has arrived. */
45
49
  invalidate?(): void;
46
50
  /** Device pixels to a CSS pixel; default 1. */
47
51
  ratio?: number;
48
52
  /** The widest picture the GPU should be given, in pixels; default 2048. */
49
53
  maxTexture?: number;
54
+ /** Told when the finer map tiles' levels for this body are known (`undefined` when it has none), so a view can raise its zoom range. Only called for a painter that has a tile set and a view in `PaintInfo`. */
55
+ onLevels?(levels: readonly TileLevel[] | undefined): void;
56
+ }
57
+ /**
58
+ * The camera that draws a body and the size of its view, so the painter can tell which part of the body's surface is in view and lay finer map tiles over it. The camera's world and projection matrices must be
59
+ * current. Without it a body is drawn from its own pictures, as it always was.
60
+ *
61
+ * @example
62
+ * ```ts no-run
63
+ * import type { PaintView } from "@johnmorrisdotca/wakusei-planets/painter";
64
+ * import * as THREE from "three";
65
+ *
66
+ * const camera = new THREE.PerspectiveCamera(35, 1, 0.1, 1000);
67
+ * const view: PaintView = { camera, width: 420, height: 420 };
68
+ * console.log(view.width);
69
+ * ```
70
+ */
71
+ export interface PaintView {
72
+ camera: THREE.Camera;
73
+ /** The view's width and height in CSS pixels. */
74
+ width: number;
75
+ height: number;
50
76
  }
51
77
  /**
52
78
  * What the caller tells a painted body at each draw: the direction to the Sun (a unit vector in the scene's axes), the time, and how many CSS pixels across its radius the body is on the screen.
@@ -70,6 +96,8 @@ export interface PaintInfo {
70
96
  };
71
97
  /** Spheres that may shade this body from the Sun: x, y, z (from this body's centre) and radius, all in this body's radii, in the scene's axes. At most six are used. */
72
98
  occluders?: readonly (readonly [number, number, number, number])[];
99
+ /** The camera, so that a body big in the view gets finer map tiles for the part in view (see `PaintView`). Left out, none are used. */
100
+ view?: PaintView;
73
101
  }
74
102
  /**
75
103
  * One body made by the painter: an object of radius 1 at the origin for the caller to move and scale.
@@ -88,6 +116,8 @@ export interface Painting {
88
116
  billboard?: boolean;
89
117
  /** Call at each draw, after the object has been placed and scaled. */
90
118
  update(info: PaintInfo): void;
119
+ /** What the window of finer map tiles on this body is doing, or `undefined` for a body with none (a glowing one, one with no painted map, or a painter with no tile set). */
120
+ readonly tiles?: DetailStats;
91
121
  dispose(): void;
92
122
  }
93
123
  /**
@@ -121,6 +151,8 @@ export interface MoonSite {
121
151
  export interface PainterOptions {
122
152
  textureBase?: string;
123
153
  farBase?: string;
154
+ /** Where the finer map tiles are (a folder address that ends in a slash; `off` for none). Left out, the demo site's (`TILES_BASE`) unless `textureBase` is given, in which case there are none. They are laid over a body that is big in the view, when the caller gives `PaintInfo.view`. */
155
+ tiles?: string;
124
156
  }
125
157
  /**
126
158
  * A painter: makes the bodies as three.js objects (`make`) and tells where a planet's moons are (`moons`). Its shape is chikyu-earth's `BodyPainter`, so `setBodyPainter(painter)` is all the wiring.