@johnmorrisdotca/chikyu-earth 0.65.1 → 0.67.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.
@@ -3,4 +3,6 @@ export { FLATTENED, MAX_ZOOM, clampView, groundPoint, pixelsPerDegree, projectFl
3
3
  export { COMPASS_POINTS, SHADOW_RADIUS_KM, compassPoint, inEarthShadow, shadowFlags, sunDirection, sunDirectionScene, trackStateOf, trackStateOfScene, type CompassPoint, type GroundTrackState } from "./track-state.ts";
4
4
  export { GROUP_COLOURS, PLANE_COLOURS, SPARE_COLOUR, TRACK_SHADOW, TRACK_SUNLIT } from "./colours.ts";
5
5
  export { FLAT_WORDS, type FlatLang } from "./words.ts";
6
+ export { placeOver, pointText } from "./marks.ts";
7
+ export { MASK_COLS, MASK_ROWS, nightWeights, photoPieces, photoWidth, readLook, type FlatLook, type PhotoPiece } from "./photo.ts";
6
8
  export type { ChikyuFlat, FlatPick, FlatPlane, GroupStyle } from "./element.ts";
@@ -5,3 +5,5 @@ export { FLATTENED, MAX_ZOOM, clampView, groundPoint, pixelsPerDegree, projectFl
5
5
  export { COMPASS_POINTS, SHADOW_RADIUS_KM, compassPoint, inEarthShadow, shadowFlags, sunDirection, sunDirectionScene, trackStateOf, trackStateOfScene } from "./track-state.js";
6
6
  export { GROUP_COLOURS, PLANE_COLOURS, SPARE_COLOUR, TRACK_SHADOW, TRACK_SUNLIT } from "./colours.js";
7
7
  export { FLAT_WORDS } from "./words.js";
8
+ export { placeOver, pointText } from "./marks.js";
9
+ export { MASK_COLS, MASK_ROWS, nightWeights, photoPieces, photoWidth, readLook } from "./photo.js";
@@ -0,0 +1,33 @@
1
+ import type { FlatLang } from "./words.ts";
2
+ /**
3
+ * A place on the Earth in words that a reader can find on the map: `23°S 15°W`, in Japanese `南緯23° 西経15°`. Whole degrees; the equator and the Greenwich meridian are `0°`.
4
+ *
5
+ * @param lon - Degrees east.
6
+ * @param lat - Degrees north.
7
+ * @param lang - `en` or `ja`.
8
+ * @returns The text.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { pointText } from "@johnmorrisdotca/chikyu-earth/flat";
13
+ *
14
+ * console.log(pointText(-15, -23, "en"), pointText(139.7, 35.7, "ja"));
15
+ * ```
16
+ */
17
+ export declare function pointText(lon: number, lat: number, lang: FlatLang): string;
18
+ /**
19
+ * What a point is over, as a name: the country it is in (Natural Earth's outlines, as the map draws them), else the ocean, sea, gulf or bay whose label point is nearest in proportion to how far that kind of name reaches. Null when there is none within reach (the polar caps).
20
+ *
21
+ * @param lon - Degrees east.
22
+ * @param lat - Degrees north.
23
+ * @param lang - `en` or `ja`.
24
+ * @returns The name, or null.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import { placeOver } from "@johnmorrisdotca/chikyu-earth/flat";
29
+ *
30
+ * console.log(placeOver(139.7, 35.7, "en"), placeOver(-15, -23, "en"), placeOver(-15, -23, "ja"));
31
+ * ```
32
+ */
33
+ export declare function placeOver(lon: number, lat: number, lang: FlatLang): string | null;
@@ -0,0 +1,70 @@
1
+ // What the flat map's own marks (the Sun overhead, the reader's place) say about themselves: where a point is, in words. Pure: numbers in, text out.
2
+ import { geoContains } from "d3-geo";
3
+ import { COUNTRIES } from "../countries.js";
4
+ import { SEA_FEATURES } from "../sea-names/features.js";
5
+ const RAD = Math.PI / 180;
6
+ /**
7
+ * A place on the Earth in words that a reader can find on the map: `23°S 15°W`, in Japanese `南緯23° 西経15°`. Whole degrees; the equator and the Greenwich meridian are `0°`.
8
+ *
9
+ * @param lon - Degrees east.
10
+ * @param lat - Degrees north.
11
+ * @param lang - `en` or `ja`.
12
+ * @returns The text.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { pointText } from "@johnmorrisdotca/chikyu-earth/flat";
17
+ *
18
+ * console.log(pointText(-15, -23, "en"), pointText(139.7, 35.7, "ja"));
19
+ * ```
20
+ */
21
+ export function pointText(lon, lat, lang) {
22
+ const wrapped = ((((lon + 180) % 360) + 360) % 360) - 180;
23
+ const la = Math.round(Math.abs(lat));
24
+ const lo = Math.round(Math.abs(wrapped));
25
+ const south = la !== 0 && lat < 0;
26
+ const north = la !== 0 && lat >= 0;
27
+ const east = lo !== 0 && lo !== 180 && wrapped > 0;
28
+ const west = lo !== 0 && lo !== 180 && wrapped <= 0;
29
+ if (lang === "ja")
30
+ return `${south ? "南緯" : north ? "北緯" : ""}${la}° ${east ? "東経" : west ? "西経" : ""}${lo}°`;
31
+ return `${la}°${south ? "S" : north ? "N" : ""} ${lo}°${east ? "E" : west ? "W" : ""}`;
32
+ }
33
+ /** How far (degrees) from its label point a name is taken to reach, by what it names: an ocean reaches further than a gulf. */
34
+ const REACH = { ocean: 40, sea: 14, gulf: 9, bay: 9 };
35
+ /** The great-circle distance between two points, degrees. */
36
+ const apart = (lon1, lat1, lon2, lat2) => {
37
+ const a = Math.sin(((lat2 - lat1) * RAD) / 2) ** 2 + Math.cos(lat1 * RAD) * Math.cos(lat2 * RAD) * Math.sin(((lon2 - lon1) * RAD) / 2) ** 2;
38
+ return (2 * Math.asin(Math.min(1, Math.sqrt(a)))) / RAD;
39
+ };
40
+ /**
41
+ * What a point is over, as a name: the country it is in (Natural Earth's outlines, as the map draws them), else the ocean, sea, gulf or bay whose label point is nearest in proportion to how far that kind of name reaches. Null when there is none within reach (the polar caps).
42
+ *
43
+ * @param lon - Degrees east.
44
+ * @param lat - Degrees north.
45
+ * @param lang - `en` or `ja`.
46
+ * @returns The name, or null.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * import { placeOver } from "@johnmorrisdotca/chikyu-earth/flat";
51
+ *
52
+ * console.log(placeOver(139.7, 35.7, "en"), placeOver(-15, -23, "en"), placeOver(-15, -23, "ja"));
53
+ * ```
54
+ */
55
+ export function placeOver(lon, lat, lang) {
56
+ for (const feature of COUNTRIES.features) {
57
+ if (geoContains(feature, [lon, lat]))
58
+ return (lang === "ja" ? feature.properties.ja : null) ?? feature.properties.name;
59
+ }
60
+ let best = null;
61
+ for (const one of SEA_FEATURES) {
62
+ const reach = REACH[one.kind];
63
+ if (reach === undefined)
64
+ continue;
65
+ const score = apart(lon, lat, one.lon, one.lat) / reach;
66
+ if (score <= 1 && (best === null || score < best.score))
67
+ best = { name: one.name[lang] || one.name.en, score };
68
+ }
69
+ return best?.name ?? null;
70
+ }
@@ -0,0 +1,167 @@
1
+ import { type FlatView } from "./geometry.ts";
2
+ /**
3
+ * The two looks of the flat map: `map`, the drawn map of countries (the default), and `photo`, NASA's picture of the Earth.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { FlatLook } from "@johnmorrisdotca/chikyu-earth/flat";
8
+ *
9
+ * const look: FlatLook = "photo";
10
+ * console.log(look);
11
+ * ```
12
+ */
13
+ export type FlatLook = "map" | "photo";
14
+ /**
15
+ * Which look an attribute value asks for: `photo`, in any case, else the drawn map.
16
+ *
17
+ * @param value - The `look` attribute, or null.
18
+ * @returns `photo` or `map`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { readLook } from "@johnmorrisdotca/chikyu-earth/flat";
23
+ *
24
+ * console.log(readLook("Photo"), readLook(null), readLook("satellite"));
25
+ * ```
26
+ */
27
+ export declare const readLook: (value: string | null) => FlatLook;
28
+ /**
29
+ * Which width of a picture to hold: the smallest shipped width (`TIERS`) with a texel for each pixel the whole world is across, else the largest, never more than `cap` (4096 at most), never less than the smallest.
30
+ *
31
+ * @param layer - `day` or `night`.
32
+ * @param worldPx - Device pixels across the whole world (360 degrees) at this zoom.
33
+ * @param cap - The most pixels across to ask for.
34
+ * @returns One of the widths of `TIERS[layer]`.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import { photoWidth } from "@johnmorrisdotca/chikyu-earth/flat";
39
+ *
40
+ * console.log(photoWidth("day", 900), photoWidth("day", 3000), photoWidth("day", 3000, 2048), photoWidth("night", 9000));
41
+ * ```
42
+ */
43
+ export declare function photoWidth(layer: "day" | "night", worldPx: number, cap?: number): number;
44
+ /**
45
+ * One piece of a picture and where it lands in the map's box: `s*` is the rectangle of the picture's own pixels, `d*` the rectangle of the box, in CSS pixels from its top left.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * import type { PhotoPiece } from "@johnmorrisdotca/chikyu-earth/flat";
50
+ *
51
+ * const area = (piece: PhotoPiece): number => piece.dw * piece.dh;
52
+ * console.log(typeof area);
53
+ * ```
54
+ */
55
+ export interface PhotoPiece {
56
+ sx: number;
57
+ sy: number;
58
+ sw: number;
59
+ sh: number;
60
+ dx: number;
61
+ dy: number;
62
+ dw: number;
63
+ dh: number;
64
+ }
65
+ /**
66
+ * The pieces that draw a whole-world picture (longitude -180 at its left edge, 90 degrees north at its top, 2 to 1) on the map: one for each turn of the world that shows in the box, cut to what shows, so that a point of the picture lands where `projectFlat` puts that longitude and latitude.
67
+ *
68
+ * @param view - The view.
69
+ * @param width - The picture's width in pixels.
70
+ * @param height - The picture's height in pixels.
71
+ * @returns The pieces, left to right.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { photoPieces } from "@johnmorrisdotca/chikyu-earth/flat";
76
+ *
77
+ * console.log(photoPieces({ width: 720, height: 360, centerLon: 0, centerLat: 0, zoom: 1 }, 2048, 1024));
78
+ * ```
79
+ */
80
+ export declare function photoPieces(view: FlatView, width: number, height: number): PhotoPiece[];
81
+ /**
82
+ * The width of the night weights' grid (`nightWeights`): one cell a degree of longitude.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * import { MASK_COLS } from "@johnmorrisdotca/chikyu-earth/flat";
87
+ *
88
+ * console.log(MASK_COLS);
89
+ * ```
90
+ */
91
+ export declare const MASK_COLS = 360;
92
+ /**
93
+ * The height of the night weights' grid (`nightWeights`): one cell a degree of latitude.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * import { MASK_ROWS } from "@johnmorrisdotca/chikyu-earth/flat";
98
+ *
99
+ * console.log(MASK_ROWS);
100
+ * ```
101
+ */
102
+ export declare const MASK_ROWS = 180;
103
+ /**
104
+ * How dark and how lit with city lights each degree of the world is, for a Sun over a place: two grids of 360 by 180 (a cell a degree, longitude -180 at the left, 90 north at the top), each 0 to 255. `veil` is how far the day picture is darkened (0 in the day, 219 at most, in the middle of the night, so the land can still be made out),
105
+ * `lights` is how much of the night picture shows. The change runs from the Sun 15 degrees up the sky to 7 degrees below the horizon, soft like the light itself.
106
+ *
107
+ * @param sunLon - Degrees east of the point under the Sun.
108
+ * @param sunLat - Degrees north of the point under the Sun.
109
+ * @returns The two grids.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * import { nightWeights } from "@johnmorrisdotca/chikyu-earth/flat";
114
+ *
115
+ * const { veil, lights } = nightWeights(0, 0);
116
+ * console.log(veil[90 * 360 + 180], lights[90 * 360 + 180], veil[90 * 360], lights[90 * 360]);
117
+ * ```
118
+ */
119
+ export declare function nightWeights(sunLon: number, sunLat: number): {
120
+ veil: Uint8ClampedArray;
121
+ lights: Uint8ClampedArray;
122
+ };
123
+ interface Held {
124
+ width: number;
125
+ bitmap: ImageBitmap;
126
+ }
127
+ export interface PhotoDeps {
128
+ /** Where the pictures are served from; ends with a slash. */
129
+ base: () => string;
130
+ /** The widest picture to hold, 4096 at most. */
131
+ cap: () => number;
132
+ /** A picture arrived or was let go: draw the map again. */
133
+ changed: () => void;
134
+ failed: (error: unknown) => void;
135
+ }
136
+ /** The pictures the photo look holds: the day picture and the night picture, each one size at a time, fetched when `want` first asks and freed by `dispose`. */
137
+ export declare class PhotoPictures {
138
+ #private;
139
+ /** A canvas of the box's size for the night picture, which is masked before it is added; made when first needed. */
140
+ scratch: HTMLCanvasElement | null;
141
+ /** The mask's canvas, 360 by 180. */
142
+ mask: HTMLCanvasElement | null;
143
+ constructor(deps: PhotoDeps);
144
+ get day(): Held | null;
145
+ get night(): Held | null;
146
+ /** True while a picture is on its way. */
147
+ get loading(): boolean;
148
+ /** Ask for the sizes that `worldPx` device pixels across the world need: a larger one is fetched at once, a smaller one only once the zoom has stayed out for a few seconds. */
149
+ want(worldPx: number): void;
150
+ /** Free everything: the pictures, the canvases and the requests on their way. */
151
+ dispose(): void;
152
+ }
153
+ /**
154
+ * Lay the photo on a canvas already scaled to CSS pixels: the day picture, then `lines` (the borders), then the night darkening and the city lights for a Sun over `sun` (nothing of the night when `sun` is null). Returns false when there is no day picture yet and nothing was drawn.
155
+ *
156
+ * @param ctx - The map canvas's context, its transform set to the device pixel ratio.
157
+ * @param view - The view.
158
+ * @param pictures - The pictures held.
159
+ * @param sun - The point under the Sun, or null for all day.
160
+ * @param lines - Draws the borders on `ctx`, or null.
161
+ * @returns Whether the photo was drawn.
162
+ */
163
+ export declare function paintPhoto(ctx: CanvasRenderingContext2D, view: FlatView, pictures: PhotoPictures, sun: {
164
+ lon: number;
165
+ lat: number;
166
+ } | null, lines: (() => void) | null): boolean;
167
+ export {};
@@ -0,0 +1,309 @@
1
+ // The flat map's photo look: NASA's day picture of the Earth laid on the map, the night picture (city lights) blended in across the terminator. The pictures are the ones the realistic Earth uses
2
+ // (`textures/`), loaded only when the look is asked for, one size of each at a time, and let go when the look goes. The pure parts (which size, where each piece of the picture lands, how dark each place is) have no DOM.
3
+ import { TIERS, MAX_TEXTURE } from "../realistic/tiers.js";
4
+ import { pixelsPerDegree } from "./geometry.js";
5
+ const RAD = Math.PI / 180;
6
+ /**
7
+ * Which look an attribute value asks for: `photo`, in any case, else the drawn map.
8
+ *
9
+ * @param value - The `look` attribute, or null.
10
+ * @returns `photo` or `map`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { readLook } from "@johnmorrisdotca/chikyu-earth/flat";
15
+ *
16
+ * console.log(readLook("Photo"), readLook(null), readLook("satellite"));
17
+ * ```
18
+ */
19
+ export const readLook = (value) => (value !== null && value.trim().toLowerCase() === "photo" ? "photo" : "map");
20
+ /**
21
+ * Which width of a picture to hold: the smallest shipped width (`TIERS`) with a texel for each pixel the whole world is across, else the largest, never more than `cap` (4096 at most), never less than the smallest.
22
+ *
23
+ * @param layer - `day` or `night`.
24
+ * @param worldPx - Device pixels across the whole world (360 degrees) at this zoom.
25
+ * @param cap - The most pixels across to ask for.
26
+ * @returns One of the widths of `TIERS[layer]`.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { photoWidth } from "@johnmorrisdotca/chikyu-earth/flat";
31
+ *
32
+ * console.log(photoWidth("day", 900), photoWidth("day", 3000), photoWidth("day", 3000, 2048), photoWidth("night", 9000));
33
+ * ```
34
+ */
35
+ export function photoWidth(layer, worldPx, cap = MAX_TEXTURE) {
36
+ const widths = TIERS[layer].filter((width) => width <= Math.max(Math.min(cap, MAX_TEXTURE), TIERS[layer][0]));
37
+ return widths.find((width) => width >= worldPx) ?? widths[widths.length - 1];
38
+ }
39
+ /**
40
+ * The pieces that draw a whole-world picture (longitude -180 at its left edge, 90 degrees north at its top, 2 to 1) on the map: one for each turn of the world that shows in the box, cut to what shows, so that a point of the picture lands where `projectFlat` puts that longitude and latitude.
41
+ *
42
+ * @param view - The view.
43
+ * @param width - The picture's width in pixels.
44
+ * @param height - The picture's height in pixels.
45
+ * @returns The pieces, left to right.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * import { photoPieces } from "@johnmorrisdotca/chikyu-earth/flat";
50
+ *
51
+ * console.log(photoPieces({ width: 720, height: 360, centerLon: 0, centerLat: 0, zoom: 1 }, 2048, 1024));
52
+ * ```
53
+ */
54
+ export function photoPieces(view, width, height) {
55
+ const k = pixelsPerDegree(view);
56
+ const w = 360 * k;
57
+ const h = 180 * k;
58
+ const x0 = view.width / 2 - (view.centerLon + 180) * k;
59
+ const y0 = view.height / 2 - (90 - view.centerLat) * k;
60
+ const top = Math.max(0, y0);
61
+ const bottom = Math.min(view.height, y0 + h);
62
+ const out = [];
63
+ if (!(bottom > top) || !(w > 0))
64
+ return out;
65
+ for (let turn = Math.floor(-x0 / w); x0 + turn * w < view.width; turn += 1) {
66
+ const left = x0 + turn * w;
67
+ const from = Math.max(0, left);
68
+ const to = Math.min(view.width, left + w);
69
+ if (!(to > from))
70
+ continue;
71
+ out.push({ sx: ((from - left) / w) * width, sy: ((top - y0) / h) * height, sw: ((to - from) / w) * width, sh: ((bottom - top) / h) * height, dx: from, dy: top, dw: to - from, dh: bottom - top });
72
+ }
73
+ return out;
74
+ }
75
+ /**
76
+ * The width of the night weights' grid (`nightWeights`): one cell a degree of longitude.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * import { MASK_COLS } from "@johnmorrisdotca/chikyu-earth/flat";
81
+ *
82
+ * console.log(MASK_COLS);
83
+ * ```
84
+ */
85
+ export const MASK_COLS = 360;
86
+ /**
87
+ * The height of the night weights' grid (`nightWeights`): one cell a degree of latitude.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { MASK_ROWS } from "@johnmorrisdotca/chikyu-earth/flat";
92
+ *
93
+ * console.log(MASK_ROWS);
94
+ * ```
95
+ */
96
+ export const MASK_ROWS = 180;
97
+ const smooth = (low, high, x) => {
98
+ const t = Math.min(1, Math.max(0, (x - low) / (high - low)));
99
+ return t * t * (3 - 2 * t);
100
+ };
101
+ /**
102
+ * How dark and how lit with city lights each degree of the world is, for a Sun over a place: two grids of 360 by 180 (a cell a degree, longitude -180 at the left, 90 north at the top), each 0 to 255. `veil` is how far the day picture is darkened (0 in the day, 219 at most, in the middle of the night, so the land can still be made out),
103
+ * `lights` is how much of the night picture shows. The change runs from the Sun 15 degrees up the sky to 7 degrees below the horizon, soft like the light itself.
104
+ *
105
+ * @param sunLon - Degrees east of the point under the Sun.
106
+ * @param sunLat - Degrees north of the point under the Sun.
107
+ * @returns The two grids.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * import { nightWeights } from "@johnmorrisdotca/chikyu-earth/flat";
112
+ *
113
+ * const { veil, lights } = nightWeights(0, 0);
114
+ * console.log(veil[90 * 360 + 180], lights[90 * 360 + 180], veil[90 * 360], lights[90 * 360]);
115
+ * ```
116
+ */
117
+ export function nightWeights(sunLon, sunLat) {
118
+ const veil = new Uint8ClampedArray(MASK_COLS * MASK_ROWS);
119
+ const lights = new Uint8ClampedArray(MASK_COLS * MASK_ROWS);
120
+ const sinS = Math.sin(sunLat * RAD);
121
+ const cosS = Math.cos(sunLat * RAD);
122
+ for (let row = 0; row < MASK_ROWS; row += 1) {
123
+ const lat = (90 - (row + 0.5)) * RAD;
124
+ const a = Math.sin(lat) * sinS;
125
+ const b = Math.cos(lat) * cosS;
126
+ for (let col = 0; col < MASK_COLS; col += 1) {
127
+ // the sine of the Sun's height above the horizon there
128
+ const height = a + b * Math.cos((-180 + col + 0.5 - sunLon) * RAD);
129
+ veil[row * MASK_COLS + col] = Math.round(0.86 * 255 * (1 - smooth(-0.12, 0.26, height)));
130
+ lights[row * MASK_COLS + col] = Math.round(255 * (1 - smooth(-0.12, 0.0, height)));
131
+ }
132
+ }
133
+ return { veil, lights };
134
+ }
135
+ /** Milliseconds a smaller size must be enough before the larger one is let go. */
136
+ const DOWNGRADE_MS = 4000;
137
+ /** The pictures the photo look holds: the day picture and the night picture, each one size at a time, fetched when `want` first asks and freed by `dispose`. */
138
+ export class PhotoPictures {
139
+ #slots = [
140
+ { layer: "day", held: null, loading: 0, abort: null, lower: undefined },
141
+ { layer: "night", held: null, loading: 0, abort: null, lower: undefined },
142
+ ];
143
+ #deps;
144
+ #dead = false;
145
+ /** A canvas of the box's size for the night picture, which is masked before it is added; made when first needed. */
146
+ scratch = null;
147
+ /** The mask's canvas, 360 by 180. */
148
+ mask = null;
149
+ constructor(deps) {
150
+ this.#deps = deps;
151
+ }
152
+ get day() {
153
+ return this.#slots[0].held;
154
+ }
155
+ get night() {
156
+ return this.#slots[1].held;
157
+ }
158
+ /** True while a picture is on its way. */
159
+ get loading() {
160
+ return this.#slots.some((slot) => slot.loading > 0);
161
+ }
162
+ /** Ask for the sizes that `worldPx` device pixels across the world need: a larger one is fetched at once, a smaller one only once the zoom has stayed out for a few seconds. */
163
+ want(worldPx) {
164
+ if (this.#dead)
165
+ return;
166
+ for (const slot of this.#slots) {
167
+ const wanted = photoWidth(slot.layer, worldPx, this.#deps.cap());
168
+ const have = slot.held?.width ?? 0;
169
+ if (wanted === have || slot.loading === wanted) {
170
+ clearTimeout(slot.lower);
171
+ slot.lower = undefined;
172
+ continue;
173
+ }
174
+ if (wanted > have) {
175
+ clearTimeout(slot.lower);
176
+ slot.lower = undefined;
177
+ this.#load(slot, wanted);
178
+ }
179
+ else if (slot.lower === undefined) {
180
+ slot.lower = setTimeout(() => {
181
+ slot.lower = undefined;
182
+ this.#load(slot, photoWidth(slot.layer, worldPx, this.#deps.cap()));
183
+ }, DOWNGRADE_MS);
184
+ }
185
+ }
186
+ }
187
+ #load(slot, width) {
188
+ slot.abort?.abort();
189
+ const abort = new AbortController();
190
+ slot.abort = abort;
191
+ slot.loading = width;
192
+ fetch(`${this.#deps.base()}${slot.layer}-${width}.webp`, { signal: abort.signal })
193
+ .then((response) => {
194
+ if (!response.ok)
195
+ throw new Error(`${slot.layer}-${width}.webp: ${response.status}`);
196
+ return response.blob();
197
+ })
198
+ .then((blob) => createImageBitmap(blob))
199
+ .then((bitmap) => {
200
+ if (this.#dead || abort.signal.aborted) {
201
+ bitmap.close();
202
+ return;
203
+ }
204
+ const old = slot.held;
205
+ slot.held = { width, bitmap };
206
+ slot.loading = 0;
207
+ slot.abort = null;
208
+ old?.bitmap.close();
209
+ this.#deps.changed();
210
+ })
211
+ .catch((error) => {
212
+ if (abort.signal.aborted || this.#dead)
213
+ return;
214
+ slot.loading = 0;
215
+ slot.abort = null;
216
+ // the night picture is a finishing touch: the map is shown without it. Without the day picture there is no photo
217
+ if (slot.layer === "day")
218
+ this.#deps.failed(error);
219
+ });
220
+ }
221
+ /** Free everything: the pictures, the canvases and the requests on their way. */
222
+ dispose() {
223
+ this.#dead = true;
224
+ for (const slot of this.#slots) {
225
+ clearTimeout(slot.lower);
226
+ slot.abort?.abort();
227
+ slot.held?.bitmap.close();
228
+ slot.held = null;
229
+ }
230
+ for (const canvas of [this.scratch, this.mask])
231
+ if (canvas)
232
+ canvas.width = canvas.height = 0;
233
+ this.scratch = this.mask = null;
234
+ }
235
+ }
236
+ /**
237
+ * Lay the photo on a canvas already scaled to CSS pixels: the day picture, then `lines` (the borders), then the night darkening and the city lights for a Sun over `sun` (nothing of the night when `sun` is null). Returns false when there is no day picture yet and nothing was drawn.
238
+ *
239
+ * @param ctx - The map canvas's context, its transform set to the device pixel ratio.
240
+ * @param view - The view.
241
+ * @param pictures - The pictures held.
242
+ * @param sun - The point under the Sun, or null for all day.
243
+ * @param lines - Draws the borders on `ctx`, or null.
244
+ * @returns Whether the photo was drawn.
245
+ */
246
+ export function paintPhoto(ctx, view, pictures, sun, lines) {
247
+ const day = pictures.day;
248
+ if (!day)
249
+ return false;
250
+ ctx.imageSmoothingEnabled = true;
251
+ ctx.imageSmoothingQuality = "high";
252
+ for (const p of photoPieces(view, day.width, day.width / 2))
253
+ ctx.drawImage(day.bitmap, p.sx, p.sy, p.sw, p.sh, p.dx, p.dy, p.dw, p.dh);
254
+ lines?.();
255
+ if (!sun)
256
+ return true;
257
+ const weights = nightWeights(sun.lon, sun.lat);
258
+ const mask = (pictures.mask ??= Object.assign(document.createElement("canvas"), { width: MASK_COLS, height: MASK_ROWS }));
259
+ const maskCtx = mask.getContext("2d");
260
+ const image = maskCtx.createImageData(MASK_COLS, MASK_ROWS);
261
+ const fill = (alpha, rgb) => {
262
+ for (let i = 0; i < alpha.length; i += 1) {
263
+ image.data[i * 4] = rgb[0];
264
+ image.data[i * 4 + 1] = rgb[1];
265
+ image.data[i * 4 + 2] = rgb[2];
266
+ image.data[i * 4 + 3] = alpha[i];
267
+ }
268
+ return image;
269
+ };
270
+ const lay = (target) => {
271
+ target.imageSmoothingEnabled = true;
272
+ target.imageSmoothingQuality = "high";
273
+ for (const p of photoPieces(view, MASK_COLS, MASK_ROWS))
274
+ target.drawImage(mask, p.sx, p.sy, p.sw, p.sh, p.dx, p.dy, p.dw, p.dh);
275
+ };
276
+ maskCtx.putImageData(fill(weights.veil, [3, 9, 24]), 0, 0);
277
+ lay(ctx);
278
+ const night = pictures.night;
279
+ if (!night)
280
+ return true;
281
+ const scratch = (pictures.scratch ??= document.createElement("canvas"));
282
+ const target = ctx.canvas;
283
+ if (scratch.width !== target.width || scratch.height !== target.height) {
284
+ scratch.width = target.width;
285
+ scratch.height = target.height;
286
+ }
287
+ const s = scratch.getContext("2d");
288
+ s.setTransform(1, 0, 0, 1, 0, 0);
289
+ s.clearRect(0, 0, scratch.width, scratch.height);
290
+ s.setTransform(target.width / view.width, 0, 0, target.height / view.height, 0, 0);
291
+ s.globalCompositeOperation = "source-over";
292
+ s.imageSmoothingEnabled = true;
293
+ s.imageSmoothingQuality = "high";
294
+ for (const p of photoPieces(view, night.width, night.width / 2))
295
+ s.drawImage(night.bitmap, p.sx, p.sy, p.sw, p.sh, p.dx, p.dy, p.dw, p.dh);
296
+ s.globalCompositeOperation = "destination-in";
297
+ maskCtx.putImageData(fill(weights.lights, [255, 255, 255]), 0, 0);
298
+ lay(s);
299
+ // the picture times itself: the dim glow of the land under the lights drops away and the lights stay
300
+ s.globalCompositeOperation = "multiply";
301
+ s.drawImage(scratch, 0, 0, view.width, view.height);
302
+ s.globalCompositeOperation = "source-over";
303
+ ctx.save();
304
+ ctx.globalCompositeOperation = "lighter";
305
+ for (let pass = 0; pass < 3; pass += 1)
306
+ ctx.drawImage(scratch, 0, 0, view.width, view.height);
307
+ ctx.restore();
308
+ return true;
309
+ }
@@ -40,6 +40,29 @@ export const FLAT_WORDS = {
40
40
  trackKey: "Ground track colours",
41
41
  sunlitNow: ", in sunlight",
42
42
  shadowNow: ", in the Earth's shadow",
43
+ lookGroup: "Look of the map",
44
+ lookMap: "Map",
45
+ lookPhoto: "Photo",
46
+ creditShort: "Earth: NASA",
47
+ key: "Key",
48
+ keyShow: "Show the key to the map",
49
+ keyHide: "Hide the key to the map",
50
+ keyMarks: "What the marks on the map are",
51
+ sunMark: "The Sun is overhead here",
52
+ sunOver: "{what}: over {place}, {point}",
53
+ sunAt: "{what}: {point}",
54
+ homeMark: "My place",
55
+ homeOver: "{what}: {place}, {point}",
56
+ homeAt: "{what}: {point}",
57
+ keySun: "The Sun is overhead",
58
+ keyHome: "My place",
59
+ keySatGroup: "A satellite: its colour is its group",
60
+ keySatPlane: "A satellite: its colour is its orbital plane",
61
+ keyFaint: "A faint satellite: its orbit data is old, so the place is an estimate",
62
+ keyRing: "The satellite you chose",
63
+ keyFootprint: "Footprint: the area that can see the satellite",
64
+ keyNight: "The night side",
65
+ keyNightPhoto: "The night side: darker, with city lights",
43
66
  },
44
67
  ja: {
45
68
  map: "世界の平面地図の上の衛星",
@@ -72,6 +95,29 @@ export const FLAT_WORDS = {
72
95
  trackKey: "地上軌跡の色",
73
96
  sunlitNow: "、日なた",
74
97
  shadowNow: "、地球の影の中",
98
+ lookGroup: "地図の見た目",
99
+ lookMap: "地図",
100
+ lookPhoto: "写真",
101
+ creditShort: "地球:NASA",
102
+ key: "凡例",
103
+ keyShow: "地図の凡例を表示する",
104
+ keyHide: "地図の凡例を閉じる",
105
+ keyMarks: "地図の印が表すもの",
106
+ sunMark: "ここは太陽が真上にある場所です",
107
+ sunOver: "{what}:{place}の上、{point}",
108
+ sunAt: "{what}:{point}",
109
+ homeMark: "自分の場所",
110
+ homeOver: "{what}:{place}、{point}",
111
+ homeAt: "{what}:{point}",
112
+ keySun: "太陽が真上にある場所",
113
+ keyHome: "自分の場所",
114
+ keySatGroup: "衛星:色はグループを表します",
115
+ keySatPlane: "衛星:色は軌道面を表します",
116
+ keyFaint: "うすい衛星:軌道データが古いため、場所は推定です",
117
+ keyRing: "選んだ衛星",
118
+ keyFootprint: "可視範囲:その衛星が見える範囲",
119
+ keyNight: "夜の側",
120
+ keyNightPhoto: "夜の側:暗くなり、街の明かりが見えます",
75
121
  },
76
122
  };
77
123
  /** The words with their `{name}` places filled in. */