@johnmorrisdotca/chikyu-earth 0.46.0 → 0.46.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.46.2 - 2026-11-13
4
+
5
+ - **Finer than the package's own tiles, from NASA's imagery service** (MODULES-1263, step 2). `tiles-finer="gibs"` on `<chikyu-earth-realistic>` and `<chikyu-space>` (off unless set) reads a daily true-colour picture in the browser, and only when the view is closer than the tiles already underneath. The layer is MODIS Terra (the VIIRS layer has no days after 2026-11-02), and the day is the most recent one with a picture: the page asks for one tile, the one under the middle of the view, for each day in turn from the UTC day before the one on show back at most 10 days, one at a time, and keeps the answer for the session; if no day answers it says nothing and keeps the package's own tiles, and it never fetches the capabilities file. A day before the layer's first day asks nothing. The clouds are left in, and a daily picture has black wedges between satellite passes: a wholly black tile is not shown, a partly black one is. A page can name the layer and the day rule (`latest`, the default, `previous-day`, `shown` or one day). A tile that is missing, black, or still out after two seconds stays out, the coarser picture remains, and that tile is not asked for again while it is in view. The 48 tile and 72 MB limits, and six requests at a time, are unchanged. A tile fades in over a third of a second, or at once for a reader who asked for less motion, and then nothing is drawn for it. The credit line shows NASA's acknowledgement while those tiles are on screen. `gibsTiles` is the same source from `@johnmorrisdotca/chikyu-earth/door`. A map source may now name its own grid; the package's own folder is unchanged.
6
+
7
+ ## 0.46.1 - 2026-11-13
8
+
9
+ - **Ride along keeps the satellite at the bottom, large, sharp and steady** (MODULES-1303). In an outside ride along (`view: "from"`, `look: "horizon"`) the satellite's middle is at 90 per cent of the picture's height and its model is drawn 17 per cent of the height in radius, so it sits at the bottom middle with part of it below the bottom edge; the page's model is told that real size (`update({ radiusPx })`) so it can be drawn sharp. Looking down (Ride above) it is at the centre. Its attitude is the track frame (long axis along the way it goes, top straight up) at every frame; a moment with no level speed keeps the last good frame instead of dropping the model. The ridden satellite's model does not depend on the satellite layers (`showSatellites`, a focus that hides the others), and its ring and name are left off, since they would cover it. `stats.followModel` gains `radiusPx`, `box` and `axes`. The page must call `setSatellitePainter` with its models before `ride`, and `ride(ref, { view: "from", look: "horizon" })` (outside is the default); the satellite must stay in a group set with `setSatellites` (removing the group ends the ride). `e2e/ride-model.gl.ts` holds the tests.
10
+
3
11
  ## 0.46.0 - 2026-11-13
4
12
 
5
13
  - **A satellite's streak keeps its short look at any clock speed and any Earth size** (MODULES-1282). Above 60 times real time each satellite is a streak along its orbit for the stretch one frame spans; at 10 minutes a second that is a few millimetres, but at an hour a second it was a long straight line across the globe, the stretch also grew when frames came slowly, and on a small Earth the streaks and the dark rim of the dots stayed as long and heavy as on a large one, so thousands of them blackened it. Now a streak is never longer than the smaller of 0.025 of the Earth's drawn radius (about 160 km of orbit, what a low satellite covers in a frame at 10 minutes a second, so it shrinks in proportion as the Earth is drawn smaller, down to a dot) and `satellite-streak-max`, new on `<chikyu-space>` and `<chikyu-earth-realistic>` (the property `satelliteStreakMax`), a ceiling in CSS pixels, 8 when the page says nothing; `off` or `0` draws the whole stretch, as before. It is a length on the screen and not seconds of travel, so a low and a high satellite are drawn equally long. A streak is also always one frame at 30 a second, whatever the frames really take, so its length does not depend on the frame rate; it ends at the satellite and points back along its orbit. The marks lose weight as the Earth is drawn smaller: from a drawn radius of 150 pixels down to 40 the streaks are fainter and the dark rim of the dots fades until it is gone, at normal speed too, and a crowd of satellites that would cover more of a small Earth's near side than a limit (6% for dots, 35% for streaks) is drawn fainter in proportion, so 16,000 satellites leave a small Earth no more washed than a whole one; a whole Earth is drawn as before. `stats.satellites` has `longestStreakPx`, `streakCapPx`, `weight`, `fade` and `earthPx`; `Satellites.arc` takes the cap, in Earth radii, as an optional last argument.
package/NOTICE.md CHANGED
@@ -68,6 +68,16 @@ text read on 2026-11-02, so check them if you need the exact wording for print.
68
68
 
69
69
  The bathymetry-free Blue Marble maps (base map, and base map with topography, on the same Blue Marble page) fall under the same NASA terms; the tiles use the one with bathymetry, as `day-*.webp` does. The clouds are not tiled: NASA's sharper cloud files (Visible Earth 57747, once at eoimages.gsfc.nasa.gov) are no longer served, and the Blue Marble 2002 page (https://science.nasa.gov/earth/earth-observatory/the-blue-marble-true-color-global-imagery-at-1km-resolution/) offers only the 2048 picture already in `clouds-2048.webp`.
70
70
 
71
+ ## Finer tiles read from NASA's imagery service
72
+
73
+ `tiles-finer="gibs"` (off unless a page sets it) reads tiles in the browser from NASA's Global Imagery Browse Services, `https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/`. Read on 2026-11-13.
74
+
75
+ The service's page "Data Use Guidance and Acknowledgements" (https://www.earthdata.nasa.gov/engage/open-data-services-software/earthdata-developer-portal/gibs-api, read 2026-11-13) says: "NASA supports full and open sharing of data. We ask that users who make use of GIBS in their clients or when referencing it in written or oral presentations to add the following acknowledgment: We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." That is the sentence the element's credit line shows, in those words, while such a tile is on screen. The Japanese line is this package's translation of that sentence; NASA published no Japanese wording. No other limit on use by a public website is stated on that page. This package is not endorsed by NASA and uses none of NASA's insignia or logotype.
76
+
77
+ The tile matrix was read the same day from `https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/1.0.0/WMTSCapabilities.xml`. Geographic tiles are 512 pixels, the corner of the matrix is longitude -180 and latitude 90, and a pixel is 0.5625/2^level degrees. Levels 0, 1 and 2 run past the Earth (2×1, 3×2 and 5×3 tiles); from level 3 the matrix covers the Earth in 10×5 tiles and doubles from there. A successful tile for the static shaded-relief layer answered `access-control-allow-origin: *` and `cache-control: public, max-age=259200`. A successful tile for a daily true-colour layer on the same day answered `access-control-allow-origin: *` and `cache-control: max-age=0, no-store`. No key is sent.
78
+
79
+ The default layer is `MODIS_Terra_CorrectedReflectance_TrueColor` (250 m, JPEG), whose days in that document run from 2000-02-24 to 2026-11-13 with gaps; the page looks for the most recent day that answers with a picture, from the day before the moment on show back at most 10 days, one tile a day (checked against the live service on 2026-11-13: 2026-11-13 answered 200 with an all-black picture, 2026-11-12 and 2026-11-11 with pictures; the daily tiles answer `cache-control: max-age=0, no-store, no-cache, must-revalidate` and `access-control-allow-origin: *`, and carry `layer-time-actual`). `VIIRS_SNPP_CorrectedReflectance_TrueColor` has days from 2015-11-24 to 2026-11-02 with gaps. `BlueMarble_ShadedRelief_Bathymetry` (500 m) has no day. A day before the first day, or in a gap of the list that was read, is not requested; a day after the last listed day is, because a daily layer goes on growing. The daily layers are true colour with the clouds left in, and a day's picture has black gaps between passes.
80
+
71
81
  The 500 m maps could fill one more level (65536 across for the day map); the pyramid stops at level 5 (day) and level 4 (night) for now. Where the pyramid is hosted: GitHub Pages of this public repository, which costs nothing (docs/guides/earth-tiles.md). It adds 3,412 files and 35.4 MB to the site (852 files and 10.3 MB before the 500 m levels; the levels above day 4 and night 3 go out only when the repository variable EARTH_TILES_ALL is yes, see docs/guides/earth-tiles.md). The source files are downloaded by the build (688 MB, once, kept by CI's cache) and are not part of the site.
72
82
 
73
83
  ## The Moon's picture
package/README.md CHANGED
@@ -176,7 +176,7 @@ atmosphere at the rim, drawn with three.js through kazoku-ui's shared renderer.
176
176
 
177
177
  Needs `three` and `@johnmorrisdotca/kazoku-ui` (both optional peers) and the pictures (1.6 MB, from NASA, in `dist/textures/`). It draws nothing while nothing changes,
178
178
  at most 30 times a second while it does, in one WebGL context, with textures that grow as you zoom and are freed after. With `tiles="/tiles/"` (a folder of NASA map
179
- tiles, [how](docs/guides/earth-tiles.md)) it loads only the finer tiles in view, so you can zoom in to 40 times and stay sharp. With `speed="86400"` (a day a second; the name `<chikyu-space>` uses) its clock runs on from the date shown and the Sun, the night side and the clouds follow it ([guide](docs/guides/time-and-play.md)). `immersive` fills the window, `camera="space"` holds the camera in the stars so the Earth turns beneath it, and it draws every satellite group at once ([guide](docs/guides/full-screen-and-camera.md)). All of it, the budget and the tests:
179
+ tiles, [how](docs/guides/earth-tiles.md)) it loads only the finer tiles in view, so you can zoom in to 40 times and stay sharp. `tiles-finer="gibs"` (off unless set) also asks NASA's imagery service for a daily picture, only closer than those tiles, and the credit line names it while it is on screen. With `speed="86400"` (a day a second; the name `<chikyu-space>` uses) its clock runs on from the date shown and the Sun, the night side and the clouds follow it ([guide](docs/guides/time-and-play.md)). `immersive` fills the window, `camera="space"` holds the camera in the stars so the Earth turns beneath it, and it draws every satellite group at once ([guide](docs/guides/full-screen-and-camera.md)). All of it, the budget and the tests:
180
180
  [docs/realistic.md](docs/realistic.md).
181
181
 
182
182
  ## The Sun, the Moon and the planets
@@ -611,7 +611,7 @@ console.log(countryList().filter((country) => country.alpha2 === null).map((coun
611
611
 
612
612
  ## How to cite
613
613
 
614
- > Morris, J. (2026). *Chikyu Earth* (version 0.46.0) [Computer software]. https://github.com/johnmorrisdotca/chikyu-earth
614
+ > Morris, J. (2026). *Chikyu Earth* (version 0.46.2) [Computer software]. https://github.com/johnmorrisdotca/chikyu-earth
615
615
 
616
616
  GitHub's "Cite this repository" button reads [CITATION.cff](CITATION.cff) and gives BibTeX and APA. Cite the version you used (`npm ls @johnmorrisdotca/chikyu-earth`), and credit the sources behind the numbers and pictures: [NOTICE.md](NOTICE.md) says who made each one and under what terms.
617
617
 
@@ -0,0 +1,171 @@
1
+ import { type EarthMapSource, type EarthTilesOptions } from "./map.ts";
2
+ /** The day this service's tile matrix, layers and terms were read. */
3
+ export declare const GIBS_READ = "2026-11-13";
4
+ /**
5
+ * The id of the source `gibsTiles` makes. A view credits it while its tiles are on the screen.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { GIBS_ID } from "@johnmorrisdotca/chikyu-earth/door";
10
+ *
11
+ * console.log(GIBS_ID);
12
+ * ```
13
+ */
14
+ export declare const GIBS_ID = "gibs";
15
+ /**
16
+ * How long a tile is given to arrive before the coarser picture is left as it is and the tile is not asked for again while it stays in view.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { GIBS_SLOW_MS } from "@johnmorrisdotca/chikyu-earth/door";
21
+ *
22
+ * console.log(GIBS_SLOW_MS);
23
+ * ```
24
+ */
25
+ export declare const GIBS_SLOW_MS = 2000;
26
+ /**
27
+ * The acknowledgement NASA asks a client to show, in their words (English, read 2026-11-13). The Japanese is this package's translation of that sentence: NASA published none.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { GIBS_CREDIT } from "@johnmorrisdotca/chikyu-earth/door";
32
+ *
33
+ * console.log(GIBS_CREDIT.en.startsWith("We acknowledge"));
34
+ * ```
35
+ */
36
+ export declare const GIBS_CREDIT: {
37
+ readonly en: "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS).";
38
+ readonly ja: "NASAの地球科学データ情報システム(ESDIS)の一部である Global Imagery Browse Services(GIBS)が提供する画像を使用していることを記します。";
39
+ };
40
+ /** A day the layer has imagery, inclusive, as the capabilities document listed it on 2026-11-13. Dates sort as text. */
41
+ interface DayRange {
42
+ start: string;
43
+ end: string;
44
+ }
45
+ interface GibsLayer {
46
+ id: string;
47
+ matrix: "250m" | "500m";
48
+ /** Empty for a picture that has no day (the shaded relief). */
49
+ ranges: readonly DayRange[];
50
+ /** True when the picture is one day of the satellite and clouds are left in. */
51
+ clouds: boolean;
52
+ }
53
+ /**
54
+ * The layers a page may ask for. The ranges are the days the capabilities document listed on 2026-11-13; a day outside them is not requested.
55
+ * The two daily layers are true colour with the clouds left in. The shaded relief is the same kind of picture as the package's own level 5, and is only a stand-in.
56
+ */
57
+ export declare const GIBS_LAYERS: Readonly<Record<string, GibsLayer>>;
58
+ /** The layer a page gets without naming one: MODIS Terra true colour, whose days run to the present (the VIIRS layer's lagged days behind by ten days or more when this was read). */
59
+ export declare const GIBS_DEFAULT_LAYER = "MODIS_Terra_CorrectedReflectance_TrueColor";
60
+ /** How many days, counting the first, the default rule looks back for a day with imagery. */
61
+ export declare const GIBS_LOOKBACK_DAYS = 10;
62
+ /**
63
+ * True when every sampled pixel is black, which is the picture the service returns for a day it has no swath for (a 200, not a 404).
64
+ *
65
+ * @param pixels - RGBA bytes.
66
+ * @returns Whether every pixel is black.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { samplesAreBlank } from "@johnmorrisdotca/chikyu-earth/door";
71
+ *
72
+ * console.log(samplesAreBlank(new Uint8ClampedArray([0, 0, 0, 255])));
73
+ * ```
74
+ */
75
+ export declare function samplesAreBlank(pixels: Uint8ClampedArray): boolean;
76
+ /**
77
+ * The UTC day `yyyy-mm-dd` of a moment.
78
+ *
79
+ * @param ms - Milliseconds since the epoch.
80
+ * @returns The day.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * import { utcDay } from "@johnmorrisdotca/chikyu-earth/door";
85
+ *
86
+ * console.log(utcDay(Date.UTC(2026, 5, 21, 12)));
87
+ * ```
88
+ */
89
+ export declare function utcDay(ms: number): string;
90
+ /**
91
+ * The UTC day before `ms`.
92
+ *
93
+ * @param ms - Milliseconds since the epoch.
94
+ * @returns The day before.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * import { previousUtcDay } from "@johnmorrisdotca/chikyu-earth/door";
99
+ *
100
+ * console.log(previousUtcDay(Date.UTC(2026, 5, 21, 12)));
101
+ * ```
102
+ */
103
+ export declare function previousUtcDay(ms: number): string;
104
+ /**
105
+ * Whether the layer may have imagery for a day: inside one of the ranges listed on 2026-11-13, or after the last of them (a daily layer goes on growing, and the list does not). A day before the layer's first day, or in a gap the list shows, has none, and is not asked for.
106
+ */
107
+ export declare function gibsHasDay(layer: GibsLayer, day: string): boolean;
108
+ /** A day the layer can serve for a fixed rule (`latest`, the default, starts at the day before `ms`), or `undefined` when it lands where the layer has no imagery (nothing is requested). */
109
+ export declare function gibsDay(layer: GibsLayer, rule: string, ms: number): string | undefined;
110
+ /** The days the default rule looks at, newest first: from `start`, back, skipping days the layer is known to lack, until the layer's first day or `GIBS_LOOKBACK_DAYS` days have been counted. */
111
+ export declare function gibsCandidates(layer: GibsLayer, start: string): string[];
112
+ /** Forget what the default rule has settled (for a page that wants to look again, and for the tests). */
113
+ export declare function forgetGibsDays(): void;
114
+ /**
115
+ * What `gibsTiles` takes. `time` is the moment the Earth is showing. The day requested is the day before that, unless `date` says otherwise.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * import type { GibsTilesOptions } from "@johnmorrisdotca/chikyu-earth/door";
120
+ *
121
+ * const options: GibsTilesOptions = { time: () => new Date("2026-06-21T12:00:00Z") };
122
+ * console.log(typeof options.time);
123
+ * ```
124
+ */
125
+ export interface GibsTilesOptions extends EarthTilesOptions {
126
+ /** The moment the view is showing. The default day is the UTC day before this. */
127
+ time: () => Date;
128
+ /** A layer id (see `GIBS_LAYERS`). Left out, the MODIS Terra daily true-colour layer. */
129
+ layer?: string;
130
+ /**
131
+ * `latest` (the default): the most recent day with imagery, looked for from the day before `time` back, one tile under the middle of the view a day. `previous-day` (that day alone), `shown` (the UTC day of `time`), or one day `yyyy-mm-dd`.
132
+ */
133
+ date?: string;
134
+ /** Called when the default rule has found its day, so the view draws again and asks for the tiles. */
135
+ changed?: () => void;
136
+ }
137
+ /**
138
+ * A map source that reads NASA's imagery service directly. It declares its own grid (512 pixel tiles, the Geographic matrix, which is not the package's pyramid). `need` names no tile for a day outside the layer's range.
139
+ * `load` gives a tile two seconds, and treats a 404 or an all-black tile as no imagery. The clouds are not taken out of the daily layers.
140
+ *
141
+ * @param options - The clock, the layer and the day rule, and the `fetch` to use.
142
+ * @returns The source. Its `layer` is `day`. It does not replace the package's own tiles: a view lays it over them, and only when the view is closer than those tiles serve.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * import { gibsTiles } from "@johnmorrisdotca/chikyu-earth/door";
147
+ *
148
+ * const source = gibsTiles({ time: () => new Date("2026-06-21T12:00:00Z") });
149
+ * console.log(source.need({ lonMin: -1, lonMax: 1, latMin: -1, latMax: 1, layer: "day" }, 50000)[0]);
150
+ * ```
151
+ */
152
+ export declare function gibsTiles(options: GibsTilesOptions): EarthMapSource;
153
+ /**
154
+ * The finer source an element makes from its attributes, the same object while the attributes are unchanged, or `undefined` when finer tiles are off or the view is limited to the package's own data.
155
+ *
156
+ * @param time - The moment the element is showing.
157
+ * @param changed - Called when the source has found the day it will read, so the element draws again.
158
+ * @returns A reader of the element's attributes.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * import { createFinerHolder } from "@johnmorrisdotca/chikyu-earth/door";
163
+ *
164
+ * const hold = createFinerHolder(() => new Date("2026-06-21T12:00:00Z"));
165
+ * console.log(hold.source(() => null, false));
166
+ * ```
167
+ */
168
+ export declare function createFinerHolder(time: () => Date, changed?: () => void): {
169
+ source(read: (name: string) => string | null, ownOnly: boolean): EarthMapSource | undefined;
170
+ };
171
+ export {};
@@ -0,0 +1,362 @@
1
+ import { tileKeyParts } from "./map.js";
2
+ import { gibsGrid, gridKeys, gridLevelFor, gridOnEarth } from "./grid.js";
3
+ /** The day this service's tile matrix, layers and terms were read. */
4
+ export const GIBS_READ = "2026-11-13";
5
+ /**
6
+ * The id of the source `gibsTiles` makes. A view credits it while its tiles are on the screen.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { GIBS_ID } from "@johnmorrisdotca/chikyu-earth/door";
11
+ *
12
+ * console.log(GIBS_ID);
13
+ * ```
14
+ */
15
+ export const GIBS_ID = "gibs";
16
+ /**
17
+ * How long a tile is given to arrive before the coarser picture is left as it is and the tile is not asked for again while it stays in view.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { GIBS_SLOW_MS } from "@johnmorrisdotca/chikyu-earth/door";
22
+ *
23
+ * console.log(GIBS_SLOW_MS);
24
+ * ```
25
+ */
26
+ export const GIBS_SLOW_MS = 2000;
27
+ /** The address of one tile. The matrix, the day and the layer are the source's; the path is `z/row/col`, which is not the package's `level/column/row`. */
28
+ const TILE_URL = "https://gibs.earthdata.nasa.gov/wmts/epsg4326/best";
29
+ /**
30
+ * The acknowledgement NASA asks a client to show, in their words (English, read 2026-11-13). The Japanese is this package's translation of that sentence: NASA published none.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { GIBS_CREDIT } from "@johnmorrisdotca/chikyu-earth/door";
35
+ *
36
+ * console.log(GIBS_CREDIT.en.startsWith("We acknowledge"));
37
+ * ```
38
+ */
39
+ export const GIBS_CREDIT = {
40
+ en: "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS).",
41
+ ja: "NASAの地球科学データ情報システム(ESDIS)の一部である Global Imagery Browse Services(GIBS)が提供する画像を使用していることを記します。",
42
+ };
43
+ const INFO = {
44
+ id: GIBS_ID,
45
+ name: { en: "NASA GIBS imagery", ja: "NASA GIBSの画像" },
46
+ credit: { en: GIBS_CREDIT.en, ja: GIBS_CREDIT.ja },
47
+ licence: { name: "Public domain", nameJa: "パブリックドメイン", url: "https://www.earthdata.nasa.gov/engage/open-data-services-software/earthdata-developer-portal/gibs-api" },
48
+ url: "https://www.earthdata.nasa.gov/engage/open-data-services-software/earthdata-developer-portal/gibs-api",
49
+ retrieved: GIBS_READ,
50
+ };
51
+ /**
52
+ * The layers a page may ask for. The ranges are the days the capabilities document listed on 2026-11-13; a day outside them is not requested.
53
+ * The two daily layers are true colour with the clouds left in. The shaded relief is the same kind of picture as the package's own level 5, and is only a stand-in.
54
+ */
55
+ export const GIBS_LAYERS = {
56
+ VIIRS_SNPP_CorrectedReflectance_TrueColor: {
57
+ id: "VIIRS_SNPP_CorrectedReflectance_TrueColor",
58
+ matrix: "250m",
59
+ clouds: true,
60
+ ranges: [
61
+ { start: "2015-11-24", end: "2022-07-27" },
62
+ { start: "2022-08-10", end: "2024-05-31" },
63
+ { start: "2024-06-04", end: "2024-07-11" },
64
+ { start: "2024-07-16", end: "2024-07-24" },
65
+ { start: "2024-07-29", end: "2024-11-03" },
66
+ { start: "2024-11-06", end: "2026-04-28" },
67
+ { start: "2026-04-30", end: "2026-07-10" },
68
+ { start: "2026-07-16", end: "2026-11-02" },
69
+ ],
70
+ },
71
+ MODIS_Terra_CorrectedReflectance_TrueColor: {
72
+ id: "MODIS_Terra_CorrectedReflectance_TrueColor",
73
+ matrix: "250m",
74
+ clouds: true,
75
+ ranges: [
76
+ { start: "2000-02-24", end: "2000-04-25" },
77
+ { start: "2000-04-28", end: "2000-08-06" },
78
+ { start: "2000-08-18", end: "2001-06-15" },
79
+ { start: "2001-07-03", end: "2002-03-19" },
80
+ { start: "2002-03-28", end: "2003-12-16" },
81
+ { start: "2003-12-24", end: "2008-12-20" },
82
+ { start: "2008-12-23", end: "2016-02-18" },
83
+ { start: "2016-02-27", end: "2022-10-10" },
84
+ { start: "2022-10-23", end: "2026-11-13" },
85
+ ],
86
+ },
87
+ BlueMarble_ShadedRelief_Bathymetry: { id: "BlueMarble_ShadedRelief_Bathymetry", matrix: "500m", clouds: false, ranges: [] },
88
+ };
89
+ /** The layer a page gets without naming one: MODIS Terra true colour, whose days run to the present (the VIIRS layer's lagged days behind by ten days or more when this was read). */
90
+ export const GIBS_DEFAULT_LAYER = "MODIS_Terra_CorrectedReflectance_TrueColor";
91
+ const DEFAULT_LAYER = GIBS_DEFAULT_LAYER;
92
+ /** How many days, counting the first, the default rule looks back for a day with imagery. */
93
+ export const GIBS_LOOKBACK_DAYS = 10;
94
+ /**
95
+ * True when every sampled pixel is black, which is the picture the service returns for a day it has no swath for (a 200, not a 404).
96
+ *
97
+ * @param pixels - RGBA bytes.
98
+ * @returns Whether every pixel is black.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * import { samplesAreBlank } from "@johnmorrisdotca/chikyu-earth/door";
103
+ *
104
+ * console.log(samplesAreBlank(new Uint8ClampedArray([0, 0, 0, 255])));
105
+ * ```
106
+ */
107
+ export function samplesAreBlank(pixels) {
108
+ if (pixels.length < 4)
109
+ return false;
110
+ for (let i = 0; i < pixels.length; i += 4)
111
+ if (pixels[i] > 1 || pixels[i + 1] > 1 || pixels[i + 2] > 1)
112
+ return false;
113
+ return true;
114
+ }
115
+ /**
116
+ * The UTC day `yyyy-mm-dd` of a moment.
117
+ *
118
+ * @param ms - Milliseconds since the epoch.
119
+ * @returns The day.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * import { utcDay } from "@johnmorrisdotca/chikyu-earth/door";
124
+ *
125
+ * console.log(utcDay(Date.UTC(2026, 5, 21, 12)));
126
+ * ```
127
+ */
128
+ export function utcDay(ms) {
129
+ return new Date(ms).toISOString().slice(0, 10);
130
+ }
131
+ /**
132
+ * The UTC day before `ms`.
133
+ *
134
+ * @param ms - Milliseconds since the epoch.
135
+ * @returns The day before.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * import { previousUtcDay } from "@johnmorrisdotca/chikyu-earth/door";
140
+ *
141
+ * console.log(previousUtcDay(Date.UTC(2026, 5, 21, 12)));
142
+ * ```
143
+ */
144
+ export function previousUtcDay(ms) {
145
+ const day = new Date(ms);
146
+ day.setUTCDate(day.getUTCDate() - 1);
147
+ return day.toISOString().slice(0, 10);
148
+ }
149
+ /**
150
+ * Whether the layer may have imagery for a day: inside one of the ranges listed on 2026-11-13, or after the last of them (a daily layer goes on growing, and the list does not). A day before the layer's first day, or in a gap the list shows, has none, and is not asked for.
151
+ */
152
+ export function gibsHasDay(layer, day) {
153
+ if (layer.ranges.length === 0)
154
+ return true;
155
+ const first = layer.ranges[0];
156
+ const last = layer.ranges[layer.ranges.length - 1];
157
+ if (day < first.start)
158
+ return false;
159
+ if (day > last.end)
160
+ return true;
161
+ return layer.ranges.some((range) => day >= range.start && day <= range.end);
162
+ }
163
+ /** The day a fixed rule names (`previous-day`, `shown`, or one `yyyy-mm-dd`), or `undefined` for `latest`, which has to be looked for. */
164
+ function fixedDay(rule, ms) {
165
+ if (/^\d{4}-\d{2}-\d{2}$/.test(rule))
166
+ return rule;
167
+ if (rule === "shown")
168
+ return utcDay(ms);
169
+ if (rule === "previous-day")
170
+ return previousUtcDay(ms);
171
+ return undefined;
172
+ }
173
+ /** A day the layer can serve for a fixed rule (`latest`, the default, starts at the day before `ms`), or `undefined` when it lands where the layer has no imagery (nothing is requested). */
174
+ export function gibsDay(layer, rule, ms) {
175
+ if (layer.ranges.length === 0)
176
+ return "default";
177
+ const named = fixedDay(rule, ms) ?? previousUtcDay(ms);
178
+ return gibsHasDay(layer, named) ? named : undefined;
179
+ }
180
+ /** The day before `day`. */
181
+ const dayBefore = (day) => previousUtcDay(Date.parse(`${day}T12:00:00Z`));
182
+ /** The days the default rule looks at, newest first: from `start`, back, skipping days the layer is known to lack, until the layer's first day or `GIBS_LOOKBACK_DAYS` days have been counted. */
183
+ export function gibsCandidates(layer, start) {
184
+ const found = [];
185
+ let day = start;
186
+ for (let count = 0; count < GIBS_LOOKBACK_DAYS; count += 1) {
187
+ if (layer.ranges.length > 0 && day < layer.ranges[0].start)
188
+ break;
189
+ if (gibsHasDay(layer, day))
190
+ found.push(day);
191
+ day = dayBefore(day);
192
+ }
193
+ return found;
194
+ }
195
+ /** The days the default rule has settled, by layer and starting day: a day with imagery, or `null` for none. Kept for the session, so a view that moves asks nothing again. */
196
+ const settled = new Map();
197
+ const probing = new Set();
198
+ /** Forget what the default rule has settled (for a page that wants to look again, and for the tests). */
199
+ export function forgetGibsDays() {
200
+ settled.clear();
201
+ probing.clear();
202
+ }
203
+ const anySignal = (signals) => (typeof AbortSignal.any === "function" ? AbortSignal.any(signals) : signals[0]);
204
+ async function pictureIsBlank(image) {
205
+ const CanvasCtor = globalThis.OffscreenCanvas;
206
+ if (typeof CanvasCtor !== "function")
207
+ return false;
208
+ try {
209
+ const canvas = new CanvasCtor(8, 8);
210
+ const ctx = canvas.getContext("2d");
211
+ if (!ctx)
212
+ return false;
213
+ ctx.drawImage(image, 0, 0, 8, 8);
214
+ return samplesAreBlank(ctx.getImageData(0, 0, 8, 8).data);
215
+ }
216
+ catch {
217
+ return false;
218
+ }
219
+ }
220
+ /**
221
+ * A map source that reads NASA's imagery service directly. It declares its own grid (512 pixel tiles, the Geographic matrix, which is not the package's pyramid). `need` names no tile for a day outside the layer's range.
222
+ * `load` gives a tile two seconds, and treats a 404 or an all-black tile as no imagery. The clouds are not taken out of the daily layers.
223
+ *
224
+ * @param options - The clock, the layer and the day rule, and the `fetch` to use.
225
+ * @returns The source. Its `layer` is `day`. It does not replace the package's own tiles: a view lays it over them, and only when the view is closer than those tiles serve.
226
+ *
227
+ * @example
228
+ * ```ts
229
+ * import { gibsTiles } from "@johnmorrisdotca/chikyu-earth/door";
230
+ *
231
+ * const source = gibsTiles({ time: () => new Date("2026-06-21T12:00:00Z") });
232
+ * console.log(source.need({ lonMin: -1, lonMax: 1, latMin: -1, latMax: 1, layer: "day" }, 50000)[0]);
233
+ * ```
234
+ */
235
+ export function gibsTiles(options) {
236
+ const known = GIBS_LAYERS[options.layer ?? DEFAULT_LAYER];
237
+ const layer = known ?? { id: options.layer ?? DEFAULT_LAYER, matrix: "250m", clouds: true, ranges: [] };
238
+ const grid = gibsGrid(layer.matrix);
239
+ const rule = options.date ?? "latest";
240
+ const get = options.fetch ?? ((url, init) => globalThis.fetch(url, init));
241
+ const decode = options.decode ?? ((blob) => createImageBitmap(blob, { premultiplyAlpha: "none", colorSpaceConversion: "none" }));
242
+ /** One tile of one day, as `load` reads it: nothing for a 404, a blank picture, a slow answer or a failure. */
243
+ const fetchTile = async (key, signal) => {
244
+ const parts = tileKeyParts(key);
245
+ const day = key.split("/")[0];
246
+ const level = parts ? grid.levels.find((one) => one.level === parts.level) : undefined;
247
+ if (!parts || !day || !level)
248
+ throw new RangeError(`"${key}" is not the key of a tile`);
249
+ if (!gridOnEarth(level, parts.col, parts.row, grid.extent))
250
+ throw new RangeError(`"${key}" is off the Earth`);
251
+ const url = `${TILE_URL}/${layer.id}/default/${day}/${layer.matrix}/${parts.level}/${parts.row}/${parts.col}.jpg`;
252
+ const timer = AbortSignal.timeout(GIBS_SLOW_MS);
253
+ let response;
254
+ try {
255
+ response = await get(url, { mode: "cors", signal: anySignal([signal, timer]) });
256
+ }
257
+ catch (error) {
258
+ throw error instanceof Error ? error : new Error(String(error));
259
+ }
260
+ if (!response.ok)
261
+ throw new Error(`The tile ${key} could not be fetched (${response.status})`);
262
+ const image = await decode(await response.blob());
263
+ if (await pictureIsBlank(image)) {
264
+ image.close?.();
265
+ throw new Error(`The tile ${key} has no imagery`);
266
+ }
267
+ return { width: image.width > 0 ? image.width : 512, height: image.height > 0 ? image.height : 512, image };
268
+ };
269
+ /** Look for the most recent day with imagery: the tile under the middle of the view, one day at a time, newest first, each given the usual two seconds. The answer, a day or none, is kept. */
270
+ const lookFor = (settledKey, start, place, detail) => {
271
+ probing.add(settledKey);
272
+ void (async () => {
273
+ let found = null;
274
+ for (const day of gibsCandidates(layer, start)) {
275
+ const keys = gridKeys(grid, place, detail, `${day}/`);
276
+ if (keys.length === 0)
277
+ break;
278
+ try {
279
+ const tile = await fetchTile(keys[0], new AbortController().signal);
280
+ tile.image.close?.();
281
+ found = day;
282
+ break;
283
+ }
284
+ catch {
285
+ // no picture for this day here: the day before
286
+ }
287
+ }
288
+ settled.set(settledKey, found);
289
+ probing.delete(settledKey);
290
+ if (found !== null)
291
+ options.changed?.();
292
+ })();
293
+ };
294
+ // an unknown layer has no published range, so no day is inside it and nothing is requested
295
+ const dayOf = (place, detail) => {
296
+ if (!known)
297
+ return undefined;
298
+ const ms = options.time().getTime();
299
+ if (fixedDay(rule, ms) !== undefined || layer.ranges.length === 0)
300
+ return gibsDay(layer, rule, ms);
301
+ const start = previousUtcDay(ms);
302
+ const settledKey = `${layer.id}|${start}`;
303
+ if (settled.has(settledKey))
304
+ return settled.get(settledKey) ?? undefined;
305
+ if (!probing.has(settledKey))
306
+ lookFor(settledKey, start, place, detail);
307
+ return undefined;
308
+ };
309
+ const source = {
310
+ kind: "tiles",
311
+ layer: "day",
312
+ info: INFO,
313
+ grid,
314
+ need(place, detail) {
315
+ if (gridLevelFor(grid, detail, 0) === undefined)
316
+ return [];
317
+ const day = dayOf(place, detail);
318
+ if (day === undefined)
319
+ return [];
320
+ return gridKeys(grid, place, detail, `${day}/`);
321
+ },
322
+ levels() {
323
+ return { tileSize: grid.tileSize, levels: grid.levels.map((level) => ({ level: level.level, width: level.width })) };
324
+ },
325
+ load: (key, signal) => fetchTile(key, signal),
326
+ bytes: (tile) => Math.ceil(tile.width * tile.height * 4 * (4 / 3)),
327
+ };
328
+ return source;
329
+ }
330
+ /**
331
+ * The finer source an element makes from its attributes, the same object while the attributes are unchanged, or `undefined` when finer tiles are off or the view is limited to the package's own data.
332
+ *
333
+ * @param time - The moment the element is showing.
334
+ * @param changed - Called when the source has found the day it will read, so the element draws again.
335
+ * @returns A reader of the element's attributes.
336
+ *
337
+ * @example
338
+ * ```ts
339
+ * import { createFinerHolder } from "@johnmorrisdotca/chikyu-earth/door";
340
+ *
341
+ * const hold = createFinerHolder(() => new Date("2026-06-21T12:00:00Z"));
342
+ * console.log(hold.source(() => null, false));
343
+ * ```
344
+ */
345
+ export function createFinerHolder(time, changed) {
346
+ let key = "";
347
+ let held;
348
+ return {
349
+ source(read, ownOnly) {
350
+ if (ownOnly || read("tiles-finer") !== "gibs")
351
+ return undefined;
352
+ const next = `${read("tiles-finer-layer") ?? ""}\n${read("tiles-finer-date") ?? ""}`;
353
+ if (held && key === next)
354
+ return held;
355
+ key = next;
356
+ const layer = read("tiles-finer-layer");
357
+ const date = read("tiles-finer-date");
358
+ held = gibsTiles({ time, ...(changed ? { changed } : {}), ...(layer ? { layer } : {}), ...(date ? { date } : {}) });
359
+ return held;
360
+ },
361
+ };
362
+ }