@spacexr/tiles 0.0.0-stage → 0.1.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 (119) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +57 -2
  3. package/dist/addressing/index.d.ts +16 -0
  4. package/dist/addressing/index.js +4 -0
  5. package/dist/addressing/index.js.map +1 -0
  6. package/dist/bake/index.d.ts +91 -0
  7. package/dist/bake/index.js +3 -0
  8. package/dist/bake/index.js.map +1 -0
  9. package/dist/celestial-dataset-CUIsplKO.d.ts +99 -0
  10. package/dist/chunk-2HLQXRDD.js +246 -0
  11. package/dist/chunk-2HLQXRDD.js.map +1 -0
  12. package/dist/chunk-6YNCRDEE.js +170 -0
  13. package/dist/chunk-6YNCRDEE.js.map +1 -0
  14. package/dist/chunk-7AWV2IEK.js +79 -0
  15. package/dist/chunk-7AWV2IEK.js.map +1 -0
  16. package/dist/chunk-ESLGXWQR.js +219 -0
  17. package/dist/chunk-ESLGXWQR.js.map +1 -0
  18. package/dist/chunk-FB57CZDK.js +312 -0
  19. package/dist/chunk-FB57CZDK.js.map +1 -0
  20. package/dist/chunk-GRTG4WNA.js +44 -0
  21. package/dist/chunk-GRTG4WNA.js.map +1 -0
  22. package/dist/chunk-HVYN4AIT.js +45 -0
  23. package/dist/chunk-HVYN4AIT.js.map +1 -0
  24. package/dist/chunk-IGNRXAW3.js +77 -0
  25. package/dist/chunk-IGNRXAW3.js.map +1 -0
  26. package/dist/chunk-QGTREKHS.js +145 -0
  27. package/dist/chunk-QGTREKHS.js.map +1 -0
  28. package/dist/chunk-SPDRAY37.js +56 -0
  29. package/dist/chunk-SPDRAY37.js.map +1 -0
  30. package/dist/chunk-TA4BEVHL.js +81 -0
  31. package/dist/chunk-TA4BEVHL.js.map +1 -0
  32. package/dist/chunk-TGOB5HT5.js +149 -0
  33. package/dist/chunk-TGOB5HT5.js.map +1 -0
  34. package/dist/chunk-X6ZJ2PDY.js +104 -0
  35. package/dist/chunk-X6ZJ2PDY.js.map +1 -0
  36. package/dist/chunk-XTY4HCPY.js +22 -0
  37. package/dist/chunk-XTY4HCPY.js.map +1 -0
  38. package/dist/chunk-Y66PNDG2.js +107 -0
  39. package/dist/chunk-Y66PNDG2.js.map +1 -0
  40. package/dist/chunk-YEACOJOC.js +51 -0
  41. package/dist/chunk-YEACOJOC.js.map +1 -0
  42. package/dist/cube/index.d.ts +160 -0
  43. package/dist/cube/index.js +9 -0
  44. package/dist/cube/index.js.map +1 -0
  45. package/dist/datasets/index.d.ts +75 -0
  46. package/dist/datasets/index.js +11 -0
  47. package/dist/datasets/index.js.map +1 -0
  48. package/dist/index.d.ts +22 -0
  49. package/dist/index.js +18 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/mercator/index.d.ts +24 -0
  52. package/dist/mercator/index.js +8 -0
  53. package/dist/mercator/index.js.map +1 -0
  54. package/dist/metrics-HGbzqj6L.d.ts +45 -0
  55. package/dist/pyramid/index.d.ts +156 -0
  56. package/dist/pyramid/index.js +4 -0
  57. package/dist/pyramid/index.js.map +1 -0
  58. package/dist/raster-registration-CgBxrhDB.d.ts +19 -0
  59. package/dist/reference-surface-CsTtrNsc.d.ts +49 -0
  60. package/dist/reprojection/index.d.ts +255 -0
  61. package/dist/reprojection/index.js +6 -0
  62. package/dist/reprojection/index.js.map +1 -0
  63. package/dist/sources/index.d.ts +55 -0
  64. package/dist/sources/index.js +7 -0
  65. package/dist/sources/index.js.map +1 -0
  66. package/dist/surface/index.d.ts +15 -0
  67. package/dist/surface/index.js +4 -0
  68. package/dist/surface/index.js.map +1 -0
  69. package/dist/tile-D-jjIRRA.d.ts +53 -0
  70. package/dist/tile-address-BkfSftp6.d.ts +66 -0
  71. package/dist/tile-http-client-BHZOtGX7.d.ts +73 -0
  72. package/dist/tile-neighbors-LfvV7oiX.d.ts +48 -0
  73. package/dist/tile-surface-s9Zi6X9_.d.ts +40 -0
  74. package/dist/tile-topology-B6xHYqPb.d.ts +51 -0
  75. package/dist/web-mercator-dataset-Dmou8byO.d.ts +125 -0
  76. package/dist/web-tile-source-DrZDBIm6.d.ts +92 -0
  77. package/package.json +122 -5
  78. package/src/addressing/index.ts +8 -0
  79. package/src/addressing/metrics.ts +48 -0
  80. package/src/addressing/raster-registration.ts +22 -0
  81. package/src/addressing/tile-address.ts +130 -0
  82. package/src/addressing/tile-edge-rotation.ts +13 -0
  83. package/src/addressing/tile-neighbors.ts +73 -0
  84. package/src/addressing/tile-surface.ts +44 -0
  85. package/src/addressing/tile-topology.ts +86 -0
  86. package/src/addressing/tile.ts +73 -0
  87. package/src/bake/bake-pyramid.ts +106 -0
  88. package/src/bake/index.ts +2 -0
  89. package/src/bake/pyramid-levels.ts +63 -0
  90. package/src/cube/celestial-dataset.ts +182 -0
  91. package/src/cube/cube-face.ts +51 -0
  92. package/src/cube/cube-geometric-error.ts +30 -0
  93. package/src/cube/cube-mapping.ts +101 -0
  94. package/src/cube/cube-neighbors.ts +198 -0
  95. package/src/cube/cube-tile-surface.ts +30 -0
  96. package/src/cube/index.ts +6 -0
  97. package/src/datasets/index.ts +1 -0
  98. package/src/datasets/tile-dataset.ts +121 -0
  99. package/src/index.ts +9 -0
  100. package/src/mercator/index.ts +3 -0
  101. package/src/mercator/web-mercator-dataset.ts +215 -0
  102. package/src/mercator/web-mercator-tile-metrics.ts +119 -0
  103. package/src/mercator/web-mercator-tile-surface.ts +52 -0
  104. package/src/pyramid/index.ts +2 -0
  105. package/src/pyramid/resident-tiles.ts +81 -0
  106. package/src/pyramid/tile-pyramid.ts +285 -0
  107. package/src/reprojection/cube-resampling.ts +159 -0
  108. package/src/reprojection/index.ts +4 -0
  109. package/src/reprojection/source-projection.ts +196 -0
  110. package/src/reprojection/source-tile-matrix.ts +100 -0
  111. package/src/reprojection/wmts-capabilities.ts +112 -0
  112. package/src/sources/index.ts +4 -0
  113. package/src/sources/tile-http-client.ts +154 -0
  114. package/src/sources/tile-layer-changes.ts +88 -0
  115. package/src/sources/url-template.ts +96 -0
  116. package/src/sources/web-tile-source.ts +73 -0
  117. package/src/surface/directions.ts +27 -0
  118. package/src/surface/index.ts +2 -0
  119. package/src/surface/reference-surface.ts +88 -0
@@ -0,0 +1,285 @@
1
+ import { ancestorTileAddress, tileAddressKey as key, type ITileAddress } from "../addressing/tile-address";
2
+ import { tileNeighborAddress, type TileNeighbor } from "../addressing/tile-neighbors";
3
+
4
+ /**
5
+ * Loads the content of one tile, or `undefined` when the pyramid has no such tile.
6
+ *
7
+ * @param signal - Aborts when nobody waits for the tile any more. A loader may ignore it.
8
+ */
9
+ export type TileContentLoader<T> = (address: ITileAddress, signal?: AbortSignal) => Promise<T | undefined>;
10
+
11
+ /** Part of an ancestor tile covered by a tile, in normalized ancestor coordinates, `west` and `north` from 0. */
12
+ export interface ITileAreaInAncestor {
13
+ ancestor: ITileAddress;
14
+ west: number;
15
+ north: number;
16
+ /** Width and height of the area, `1 / 2^levels`. */
17
+ size: number;
18
+ }
19
+
20
+ /** The ancestor `levels` levels above a tile and the part of it the tile covers. */
21
+ export function tileAreaInAncestor(address: ITileAddress, levels: number): ITileAreaInAncestor {
22
+ const ancestor = ancestorTileAddress(address, levels);
23
+ const scale = 2 ** (address.lod - ancestor.lod);
24
+ return {
25
+ ancestor,
26
+ west: (address.x - ancestor.x * scale) / scale,
27
+ north: (address.y - ancestor.y * scale) / scale,
28
+ size: 1 / scale,
29
+ };
30
+ }
31
+
32
+ export interface ITilePyramidOptions<T> {
33
+ load: TileContentLoader<T>;
34
+ /** Deepest level of the pyramid; deeper tiles use the sub-area of their ancestor at this level (overzoom). */
35
+ maxLOD: number;
36
+ /**
37
+ * Level of the pyramid tile serving a tile, for a sparse pyramid whose depth varies from place to place. A tile deeper
38
+ * than the data at its place then uses the sub-area of its ancestor there. Defaults to the same level everywhere.
39
+ */
40
+ servingLevel?: (address: ITileAddress) => number;
41
+ /** Tiles kept in memory. Defaults to 256. */
42
+ cacheEntries?: number;
43
+ /**
44
+ * Time a load nobody waits for any more goes on before it is aborted, so that a tile coming back right away, as when
45
+ * a zoom turns around, does not load twice. Defaults to 0: at once.
46
+ */
47
+ abortDelayMilliseconds?: number;
48
+ /** Wraps columns around the antimeridian, for pyramids covering every longitude. Defaults to false. */
49
+ wrapX?: boolean;
50
+ /**
51
+ * Neighbours loaded with every tile, or with a given tile, for contents that need them: `[E, S, SE]` to stitch the
52
+ * extra column and row of a raster, or every position to prepare a move. A missing or failing neighbour is ignored.
53
+ * Defaults to none.
54
+ */
55
+ prefetch?: readonly TileNeighbor[] | ((address: ITileAddress) => readonly TileNeighbor[]);
56
+ /** Called when the content of a tile is loaded and still cached. */
57
+ onLoad?: (address: ITileAddress, content: T) => void;
58
+ /** Called when a tile leaves the cache. */
59
+ onEvict?: (address: ITileAddress) => void;
60
+ }
61
+
62
+ /** Content of the pyramid tile serving a tile, with the part of it the tile covers. */
63
+ export interface ITilePyramidRegion<T> extends ITileAreaInAncestor {
64
+ /** Tile requested. */
65
+ address: ITileAddress;
66
+ /** Content of `ancestor`, the tile itself up to `maxLOD`. */
67
+ content: T;
68
+ }
69
+
70
+ interface ITilePyramidEntry<T> {
71
+ readonly address: ITileAddress;
72
+ readonly loading: Promise<T | undefined>;
73
+ content: T | undefined;
74
+ /** Aborts the load once nobody waits for it. */
75
+ readonly controller: AbortController;
76
+ /** Requests still waiting with a signal of their own. */
77
+ waiting: number;
78
+ /** A request without a signal, which cannot leave: the load always ends. */
79
+ pinned: boolean;
80
+ settled: boolean;
81
+ /** Pending abort of a load nobody waits for, which a new request cancels. */
82
+ abortTimer: ReturnType<typeof setTimeout> | undefined;
83
+ }
84
+
85
+ /**
86
+ * Tiles of a pyramid loaded on demand, whatever their content: rasters, meshes, vector data.
87
+ *
88
+ * Each tile loads once and is shared by every request, including the requests of deeper tiles beyond `maxLOD`, which
89
+ * use a sub-area of their ancestor. The least recently used tiles leave the cache, except the tiles retained by their
90
+ * users, which may exceed its capacity. Neighbours listed in `prefetch` load with every tile.
91
+ */
92
+ export class TilePyramid<T> {
93
+ public readonly maxLOD: number;
94
+ private readonly options: ITilePyramidOptions<T>;
95
+ private readonly cacheEntries: number;
96
+ private readonly entries = new Map<string, ITilePyramidEntry<T>>();
97
+ /** Retain counts of the pyramid tiles that must stay in the cache. */
98
+ private readonly retained = new Map<string, number>();
99
+
100
+ public constructor(options: ITilePyramidOptions<T>) {
101
+ if (!Number.isInteger(options.maxLOD) || options.maxLOD < 0) throw new RangeError("maxLOD must be a non-negative integer.");
102
+ this.options = options;
103
+ this.maxLOD = options.maxLOD;
104
+ this.cacheEntries = options.cacheEntries ?? 256;
105
+ }
106
+
107
+ /** Number of tiles in memory, loaded or loading. */
108
+ public get size(): number {
109
+ return this.entries.size;
110
+ }
111
+
112
+ /** Level of the pyramid tile serving a tile level. */
113
+ public sourceLevel(lod: number): number {
114
+ return Math.min(lod, this.maxLOD);
115
+ }
116
+
117
+ /** The pyramid tile serving a tile and the part of it the tile covers. */
118
+ public areaOf(address: ITileAddress): ITileAreaInAncestor {
119
+ const level = this.options.servingLevel ? Math.min(this.options.servingLevel(address), this.sourceLevel(address.lod)) : this.sourceLevel(address.lod);
120
+ return tileAreaInAncestor(address, address.lod - level);
121
+ }
122
+
123
+ /** Loaded content of a pyramid tile, without loading it. */
124
+ public get(address: ITileAddress): T | undefined {
125
+ return this.entries.get(key(address))?.content;
126
+ }
127
+
128
+ /**
129
+ * Loads the pyramid tile serving a tile, with its prefetched neighbours.
130
+ *
131
+ * @param signal - Withdraws this request, which then rejects with its reason. A load every request has withdrawn from
132
+ * is aborted and leaves the cache; a load another request still waits for goes on.
133
+ * @returns The content and the part of it the tile covers, or `undefined` when the pyramid has no tile there.
134
+ */
135
+ public async load(address: ITileAddress, signal?: AbortSignal): Promise<ITilePyramidRegion<T> | undefined> {
136
+ const area = this.areaOf(address);
137
+ const content = await this.loadTile(area.ancestor, signal);
138
+ return content === undefined ? undefined : { ...area, address: { ...address }, content };
139
+ }
140
+
141
+ /**
142
+ * Loads one tile of the pyramid itself, with its prefetched neighbours, whatever tile `servingLevel` would serve at
143
+ * its address: for contents made from other tiles of the pyramid, such as a tile generated from its parent.
144
+ *
145
+ * @param signal - Withdraws this request; see {@link load}.
146
+ * @returns Its content, or `undefined` when the pyramid has no tile there.
147
+ */
148
+ public async loadTile(address: ITileAddress, signal?: AbortSignal): Promise<T | undefined> {
149
+ const { prefetch = [] } = this.options;
150
+ const neighbors = (typeof prefetch === "function" ? prefetch(address) : prefetch)
151
+ .map((position) => tileNeighborAddress(address, position, { wrapX: this.options.wrapX ?? false }))
152
+ .filter((neighbor) => neighbor !== undefined);
153
+ const [content] = await Promise.all([this.tile(address, signal), ...neighbors.map((neighbor) => this.tile(neighbor, signal).catch(() => undefined))]);
154
+ return content;
155
+ }
156
+
157
+ /**
158
+ * Keeps the pyramid tile serving a tile in the cache until it is released as many times, for example while a
159
+ * renderer displays data sampled from it. A retained tile still has to be loaded.
160
+ */
161
+ public retain(address: ITileAddress): void {
162
+ const tileKey = key(this.areaOf(address).ancestor);
163
+ this.retained.set(tileKey, (this.retained.get(tileKey) ?? 0) + 1);
164
+ }
165
+
166
+ /** Releases a tile retained with {@link retain}; the cache then evicts it like any other once it is full. */
167
+ public release(address: ITileAddress): void {
168
+ const tileKey = key(this.areaOf(address).ancestor);
169
+ const count = (this.retained.get(tileKey) ?? 0) - 1;
170
+ if (count > 0) this.retained.set(tileKey, count);
171
+ else this.retained.delete(tileKey);
172
+ this.evictOverflow();
173
+ }
174
+
175
+ /** Removes a tile from the cache. */
176
+ public delete(address: ITileAddress): boolean {
177
+ const deleted = this.entries.delete(key(address));
178
+ if (deleted) this.options.onEvict?.(address);
179
+ return deleted;
180
+ }
181
+
182
+ /**
183
+ * Forgets the tiles whose data changed, such as those meeting an edited area: the next request of each loads it
184
+ * again, the other tiles stay cached. A load under way for one of them still answers its requests, but its content
185
+ * is not kept: it may predate the change.
186
+ *
187
+ * @returns The tiles forgotten.
188
+ */
189
+ public invalidate(affects: (address: ITileAddress) => boolean): ITileAddress[] {
190
+ const forgotten: ITileAddress[] = [];
191
+ for (const entry of [...this.entries.values()]) {
192
+ if (!affects(entry.address)) continue;
193
+ this.delete(entry.address);
194
+ forgotten.push({ ...entry.address });
195
+ }
196
+ return forgotten;
197
+ }
198
+
199
+ private tile(address: ITileAddress, signal?: AbortSignal): Promise<T | undefined> {
200
+ const tileKey = key(address);
201
+ const cached = this.entries.get(tileKey);
202
+ if (cached) {
203
+ // Most recently used last.
204
+ this.entries.delete(tileKey);
205
+ this.entries.set(tileKey, cached);
206
+ return this.wait(cached, signal);
207
+ }
208
+ const controller = new AbortController();
209
+ const loading = this.options.load(address, controller.signal).then((content) => {
210
+ entry.settled = true;
211
+ // A tile evicted while loading, or replaced since, is dropped.
212
+ if (this.entries.get(tileKey) === entry) {
213
+ entry.content = content;
214
+ if (content !== undefined) this.options.onLoad?.(entry.address, content);
215
+ }
216
+ return content;
217
+ });
218
+ const entry: ITilePyramidEntry<T> = { address: { ...address }, loading, content: undefined, controller, waiting: 0, pinned: false, settled: false, abortTimer: undefined };
219
+ loading.catch(() => {
220
+ entry.settled = true;
221
+ if (this.entries.get(tileKey) === entry) this.entries.delete(tileKey);
222
+ });
223
+ this.entries.set(tileKey, entry);
224
+ this.evictOverflow();
225
+ return this.wait(entry, signal);
226
+ }
227
+
228
+ /** Aborts a load and forgets it, unless a request came back or it ended in the meantime. */
229
+ private abortUnwanted(entry: ITilePyramidEntry<T>, reason: unknown): void {
230
+ entry.abortTimer = undefined;
231
+ if (entry.waiting > 0 || entry.pinned || entry.settled) return;
232
+ entry.controller.abort(reason);
233
+ if (this.entries.get(key(entry.address)) === entry) this.delete(entry.address);
234
+ }
235
+
236
+ /** Waits for a load until the signal withdraws this request: the last one to leave aborts the load. */
237
+ private wait(entry: ITilePyramidEntry<T>, signal?: AbortSignal): Promise<T | undefined> {
238
+ if (entry.settled) return entry.loading;
239
+ clearTimeout(entry.abortTimer);
240
+ entry.abortTimer = undefined;
241
+ if (!signal) {
242
+ entry.pinned = true;
243
+ return entry.loading;
244
+ }
245
+ entry.waiting++;
246
+ return new Promise((resolve, reject) => {
247
+ const withdraw = (): void => {
248
+ entry.waiting--;
249
+ reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
250
+ if (entry.waiting > 0 || entry.pinned || entry.settled) return;
251
+ const delay = this.options.abortDelayMilliseconds ?? 0;
252
+ if (delay > 0) entry.abortTimer = setTimeout(() => this.abortUnwanted(entry, signal.reason), delay);
253
+ else this.abortUnwanted(entry, signal.reason);
254
+ };
255
+ if (signal.aborted) {
256
+ withdraw();
257
+ return;
258
+ }
259
+ signal.addEventListener("abort", withdraw, { once: true });
260
+ const leave = (): void => {
261
+ signal.removeEventListener("abort", withdraw);
262
+ entry.waiting--;
263
+ };
264
+ entry.loading.then(
265
+ (content) => {
266
+ leave();
267
+ resolve(content);
268
+ },
269
+ (error: unknown) => {
270
+ leave();
271
+ reject(error);
272
+ }
273
+ );
274
+ });
275
+ }
276
+
277
+ /** Evicts the least recently used tiles that are not retained while the cache exceeds its capacity. */
278
+ private evictOverflow(): void {
279
+ if (this.entries.size <= this.cacheEntries) return;
280
+ for (const [tileKey, entry] of this.entries) {
281
+ if (this.entries.size <= this.cacheEntries) return;
282
+ if (!this.retained.has(tileKey)) this.delete(entry.address);
283
+ }
284
+ }
285
+ }
@@ -0,0 +1,159 @@
1
+ import type { ICartesian3 } from "@spacexr/geodesy";
2
+
3
+ import { tileCount, type ITileAddress } from "../addressing/tile-address";
4
+ import { cubeTileDirection } from "../cube/cube-mapping";
5
+ import type { ReferenceSurface } from "../surface/reference-surface";
6
+ import type { IMapPosition, ISourceProjection } from "./source-projection";
7
+ import { sourcePixelAt, sourcePixelCoordinates, type ISourceTile, type ISourceTileMatrix } from "./source-tile-matrix";
8
+
9
+ /** A raster source seen from the cube: its projection and the level it is read at. */
10
+ export interface ICubeSourceLevel {
11
+ projection: ISourceProjection;
12
+ matrix: ISourceTileMatrix;
13
+ }
14
+
15
+ /** Period of a map, in pixels of a matrix, when it wraps around the body. */
16
+ function periodPixels({ projection, matrix }: ICubeSourceLevel): number | undefined {
17
+ return projection.periodX === undefined ? undefined : projection.periodX / matrix.pixelSize;
18
+ }
19
+
20
+ /**
21
+ * Coarsest level of a source at least as fine as a level of the cube, the last one otherwise. It depends on the level of
22
+ * the cube alone, so both sides of a tile edge read the same level. On a global geographic source, it is `lod + 1`.
23
+ *
24
+ * @param bodyRadius - Radius of the body, in metres.
25
+ * @param lod - Level of the cube.
26
+ * @param tileSize - Cells per side of the tiles of the cube.
27
+ * @param matrices - Levels of the source, from the coarsest.
28
+ * @throws RangeError When the source has no level.
29
+ */
30
+ export function cubeSourceMatrix(projection: ISourceProjection, matrices: readonly ISourceTileMatrix[], bodyRadius: number, lod: number, tileSize = 256): ISourceTileMatrix {
31
+ if (matrices.length === 0) throw new RangeError("The source has no level.");
32
+ const spacing = (Math.PI / 2) * (bodyRadius / (tileSize * tileCount(lod)));
33
+ return matrices.find((matrix) => matrix.pixelSize * projection.metresPerUnit <= spacing * (1 + 1e-9)) ?? matrices[matrices.length - 1]!;
34
+ }
35
+
36
+ /** Runs through the `(tileSize + 1)^2` samples of a tile of the cube, in rows from its north-west corner. */
37
+ function forEachSample(address: ITileAddress, tileSize: number, visit: (index: number, direction: Readonly<ICartesian3>) => void): void {
38
+ const side = tileSize + 1;
39
+ const direction: ICartesian3 = { x: 0, y: 0, z: 0 };
40
+ for (let row = 0; row < side; row++) {
41
+ for (let column = 0; column < side; column++) {
42
+ cubeTileDirection(address, column / tileSize, row / tileSize, direction);
43
+ visit(row * side + column, direction);
44
+ }
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The tiles of a source that the samples of a tile of the cube read, to load before {@link resampleCubeTile}.
50
+ *
51
+ * @param tileSize - Cells per side of the tile of the cube. Defaults to 256.
52
+ */
53
+ export function cubeTileSourceTiles(address: ITileAddress, source: ICubeSourceLevel, tileSize = 256): ISourceTile[] {
54
+ const found = new Map<string, ISourceTile>();
55
+ const period = periodPixels(source);
56
+ const position: IMapPosition = { x: 0, y: 0 };
57
+ const pixel: IMapPosition = { x: 0, y: 0 };
58
+ forEachSample(address, tileSize, (_index, direction) => {
59
+ sourcePixelCoordinates(source.matrix, source.projection.forward(direction, position), pixel);
60
+ const left = Math.floor(pixel.x);
61
+ const top = Math.floor(pixel.y);
62
+ for (const [dx, dy] of [
63
+ [0, 0],
64
+ [1, 0],
65
+ [0, 1],
66
+ [1, 1],
67
+ ] as const) {
68
+ const at = sourcePixelAt(source.matrix, left + dx, top + dy, period);
69
+ if (at) found.set(`${at.column}/${at.row}`, { column: at.column, row: at.row });
70
+ }
71
+ });
72
+ return [...found.values()];
73
+ }
74
+
75
+ /**
76
+ * Value of a source at a pixel of a loaded tile, `NaN` where it has none: a missing tile, or its no-data value.
77
+ *
78
+ * @param column - Column of the tile.
79
+ * @param row - Row of the tile.
80
+ * @param x - Pixel in the tile.
81
+ * @param y - Pixel in the tile.
82
+ * @param channel - Channel of the pixel.
83
+ */
84
+ export type SourcePixelReader = (column: number, row: number, x: number, y: number, channel: number) => number;
85
+
86
+ export interface IResampleCubeTileOptions {
87
+ /** Cells per side of the tile of the cube. Defaults to 256: 257 samples per side. */
88
+ tileSize?: number;
89
+ /** Channels per sample. Defaults to 1. */
90
+ channels?: number;
91
+ /** Receives the samples, channels interleaved. Defaults to a new array. */
92
+ target?: Float32Array;
93
+ }
94
+
95
+ /**
96
+ * Reads a source at the samples of a tile of the cube, bilinearly in its pixels: `(tileSize + 1)^2` samples in point
97
+ * registration. A sample depends on its direction alone, so tiles sharing an edge hold the same samples on it, across cube
98
+ * faces included. Pixels without data are left out of the interpolation; a sample with none is `NaN`.
99
+ *
100
+ * @throws RangeError When a supplied target has another length.
101
+ */
102
+ export function resampleCubeTile(address: ITileAddress, source: ICubeSourceLevel, read: SourcePixelReader, options: IResampleCubeTileOptions = {}): Float32Array {
103
+ const tileSize = options.tileSize ?? 256;
104
+ const channels = options.channels ?? 1;
105
+ const length = (tileSize + 1) ** 2 * channels;
106
+ const data = options.target ?? new Float32Array(length);
107
+ if (data.length !== length) throw new RangeError(`A tile of ${tileSize} cells needs ${length} values, not ${data.length}.`);
108
+ const period = periodPixels(source);
109
+ const position: IMapPosition = { x: 0, y: 0 };
110
+ const pixel: IMapPosition = { x: 0, y: 0 };
111
+ forEachSample(address, tileSize, (index, direction) => {
112
+ sourcePixelCoordinates(source.matrix, source.projection.forward(direction, position), pixel);
113
+ const left = Math.floor(pixel.x);
114
+ const top = Math.floor(pixel.y);
115
+ const fx = pixel.x - left;
116
+ const fy = pixel.y - top;
117
+ for (let channel = 0; channel < channels; channel++) {
118
+ let sum = 0;
119
+ let weights = 0;
120
+ for (const [dx, dy, weight] of [
121
+ [0, 0, (1 - fx) * (1 - fy)],
122
+ [1, 0, fx * (1 - fy)],
123
+ [0, 1, (1 - fx) * fy],
124
+ [1, 1, fx * fy],
125
+ ] as const) {
126
+ if (weight === 0) continue;
127
+ const at = sourcePixelAt(source.matrix, left + dx, top + dy, period);
128
+ const value = at ? read(at.column, at.row, at.x, at.y, channel) : Number.NaN;
129
+ if (Number.isNaN(value)) continue;
130
+ sum += value * weight;
131
+ weights += weight;
132
+ }
133
+ data[index * channels + channel] = weights > 0 ? sum / weights : Number.NaN;
134
+ }
135
+ });
136
+ return data;
137
+ }
138
+
139
+ /**
140
+ * Radial height over a reference surface of a source whose heights are radial over a sphere, such as LOLA over 1737.4 km:
141
+ * `h + sourceRadius - radius(direction)`. It is the height itself when both surfaces are that sphere.
142
+ */
143
+ export function rebaseRadialHeight(height: number, sourceRadius: number, reference: ReferenceSurface, direction: Readonly<ICartesian3>): number {
144
+ return height + sourceRadius - reference.radius(direction);
145
+ }
146
+
147
+ /**
148
+ * Weight of a polar source against a global one, from a unit direction: 0 up to `fromDegrees` of latitude, 1 from
149
+ * `toDegrees`, smooth in between. It depends on the direction alone, so shared edges stay identical. Latitudes are
150
+ * planetocentric and absolute.
151
+ *
152
+ * @throws RangeError When `toDegrees` does not exceed `fromDegrees`.
153
+ */
154
+ export function capBlendWeight(direction: Readonly<ICartesian3>, fromDegrees: number, toDegrees: number): number {
155
+ if (!(toDegrees > fromDegrees)) throw new RangeError("A cap blend must end beyond its start.");
156
+ const latitude = (Math.atan2(Math.abs(direction.z), Math.hypot(direction.x, direction.y)) * 180) / Math.PI;
157
+ const t = Math.min(Math.max((latitude - fromDegrees) / (toDegrees - fromDegrees), 0), 1);
158
+ return t * t * (3 - 2 * t);
159
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./cube-resampling";
2
+ export * from "./source-projection";
3
+ export * from "./source-tile-matrix";
4
+ export * from "./wmts-capabilities";
@@ -0,0 +1,196 @@
1
+ import type { ICartesian3 } from "@spacexr/geodesy";
2
+
3
+ const DEGREES = 180 / Math.PI;
4
+
5
+ /** Position in the map of a source: degrees for a geographic source, metres for a projected one. */
6
+ export interface IMapPosition {
7
+ x: number;
8
+ y: number;
9
+ }
10
+
11
+ /**
12
+ * Projection of a raster source: from a unit direction of the body-fixed frame to the map of the source, and back. The
13
+ * unit directions go through it, whatever the source. Latitude conventions are explicit: each
14
+ * projection states which latitude its source uses.
15
+ */
16
+ export interface ISourceProjection {
17
+ /** Map position of a unit direction. */
18
+ forward(direction: Readonly<ICartesian3>, target?: IMapPosition): IMapPosition;
19
+ /** Unit direction of a map position. */
20
+ inverse(x: number, y: number, target?: ICartesian3): ICartesian3;
21
+ /** Metres on the ground per map unit, at the reference of the map. */
22
+ readonly metresPerUnit: number;
23
+ /** Width of the map along `x` when it wraps around the body, as a global geographic map does. */
24
+ readonly periodX: number | undefined;
25
+ }
26
+
27
+ export interface IGeographicProjectionOptions {
28
+ /** Equatorial radius of the body, in metres. */
29
+ semiMajorAxis: number;
30
+ /**
31
+ * Polar radius of the ellipsoid of the source, for a source with geodetic latitudes such as EPSG:4326. Defaults to
32
+ * `semiMajorAxis`: on a sphere, latitudes are planetocentric.
33
+ */
34
+ semiMinorAxis?: number;
35
+ /** Longitude of the centre of the map, in degrees. Defaults to 0: longitudes run from -180 to 180. */
36
+ centralMeridianDegrees?: number;
37
+ }
38
+
39
+ /** Geographic map, plate carree: `x` is the longitude and `y` the latitude, in degrees. */
40
+ export class GeographicProjection implements ISourceProjection {
41
+ public readonly metresPerUnit: number;
42
+ public readonly periodX = 360;
43
+ private readonly squaredRatio: number;
44
+ private readonly centralMeridian: number;
45
+
46
+ public constructor(options: IGeographicProjectionOptions) {
47
+ const { semiMajorAxis: a, semiMinorAxis: b = a } = options;
48
+ if (!(a > 0) || !(b > 0)) throw new RangeError("The radii of a projection must be positive.");
49
+ this.metresPerUnit = (Math.PI / 180) * a;
50
+ this.squaredRatio = (a * a) / (b * b);
51
+ this.centralMeridian = options.centralMeridianDegrees ?? 0;
52
+ }
53
+
54
+ public forward(direction: Readonly<ICartesian3>, target: IMapPosition = { x: 0, y: 0 }): IMapPosition {
55
+ // tan(geodetic) = (a^2 / b^2) tan(planetocentric); the ratio is 1 on a sphere.
56
+ target.y = Math.atan2(direction.z * this.squaredRatio, Math.hypot(direction.x, direction.y)) * DEGREES;
57
+ target.x = wrapDegrees(Math.atan2(direction.y, direction.x) * DEGREES - this.centralMeridian);
58
+ return target;
59
+ }
60
+
61
+ public inverse(x: number, y: number, target: ICartesian3 = { x: 0, y: 0, z: 0 }): ICartesian3 {
62
+ const longitude = (x + this.centralMeridian) / DEGREES;
63
+ const latitude = Math.atan2(Math.sin(y / DEGREES), Math.cos(y / DEGREES) * this.squaredRatio);
64
+ target.x = Math.cos(latitude) * Math.cos(longitude);
65
+ target.y = Math.cos(latitude) * Math.sin(longitude);
66
+ target.z = Math.sin(latitude);
67
+ return target;
68
+ }
69
+ }
70
+
71
+ function wrapDegrees(degrees: number): number {
72
+ if (degrees < -180) return degrees + 360;
73
+ if (degrees >= 180) return degrees - 360;
74
+ return degrees;
75
+ }
76
+
77
+ export interface IPolarStereographicProjectionOptions {
78
+ pole: "north" | "south";
79
+ /** Radius of the sphere of the map, in metres. */
80
+ radius: number;
81
+ /** `central_meridian` of the source, in degrees. Defaults to 0. */
82
+ centralMeridianDegrees?: number;
83
+ /** Defaults to 0. */
84
+ falseEasting?: number;
85
+ /** Defaults to 0. */
86
+ falseNorthing?: number;
87
+ }
88
+
89
+ /**
90
+ * Polar stereographic map on a sphere, true to scale at the pole, in metres. It reads the direction without any latitude
91
+ * or longitude, so the pole is a point like any other:
92
+ *
93
+ * ```text
94
+ * south: x = 2R dy / (1 - dz), y = 2R dx / (1 - dz)
95
+ * north: x = 2R dy / (1 + dz), y = -2R dx / (1 + dz)
96
+ * ```
97
+ *
98
+ * with `dx`, `dy` turned by the central meridian. It matches `Stereographic_South_Pole` of ESRI and EPSG on a sphere.
99
+ */
100
+ export class PolarStereographicProjection implements ISourceProjection {
101
+ public readonly metresPerUnit = 1;
102
+ public readonly periodX = undefined;
103
+ private readonly south: boolean;
104
+ private readonly diameter: number;
105
+ private readonly cosine: number;
106
+ private readonly sine: number;
107
+ private readonly falseEasting: number;
108
+ private readonly falseNorthing: number;
109
+
110
+ public constructor(options: IPolarStereographicProjectionOptions) {
111
+ if (!(options.radius > 0)) throw new RangeError("The radius of a projection must be positive.");
112
+ this.south = options.pole === "south";
113
+ this.diameter = 2 * options.radius;
114
+ const meridian = (options.centralMeridianDegrees ?? 0) / DEGREES;
115
+ this.cosine = Math.cos(meridian);
116
+ this.sine = Math.sin(meridian);
117
+ this.falseEasting = options.falseEasting ?? 0;
118
+ this.falseNorthing = options.falseNorthing ?? 0;
119
+ }
120
+
121
+ public forward(direction: Readonly<ICartesian3>, target: IMapPosition = { x: 0, y: 0 }): IMapPosition {
122
+ const { x, y, z } = direction;
123
+ const dx = x * this.cosine + y * this.sine;
124
+ const dy = y * this.cosine - x * this.sine;
125
+ const scale = this.diameter / (this.south ? 1 - z : 1 + z);
126
+ target.x = dy * scale + this.falseEasting;
127
+ target.y = (this.south ? dx : -dx) * scale + this.falseNorthing;
128
+ return target;
129
+ }
130
+
131
+ public inverse(x: number, y: number, target: ICartesian3 = { x: 0, y: 0, z: 0 }): ICartesian3 {
132
+ const mapX = (x - this.falseEasting) / this.diameter;
133
+ const mapY = ((this.south ? y : -y) - (this.south ? this.falseNorthing : -this.falseNorthing)) / this.diameter;
134
+ const squared = mapX * mapX + mapY * mapY;
135
+ const denominator = 1 + squared;
136
+ const along = (2 * mapY) / denominator;
137
+ const across = (2 * mapX) / denominator;
138
+ target.x = along * this.cosine - across * this.sine;
139
+ target.y = along * this.sine + across * this.cosine;
140
+ target.z = ((this.south ? -1 : 1) * (1 - squared)) / denominator;
141
+ return target;
142
+ }
143
+ }
144
+
145
+ export interface IWebMercatorProjectionOptions {
146
+ /** Radius of the map, in metres. Supplied explicitly in metres. */
147
+ semiMajorAxis: number;
148
+ /** Polar radius of the ellipsoid of the latitudes. Supplied explicitly by the caller. */
149
+ semiMinorAxis?: number;
150
+ }
151
+
152
+ /**
153
+ * Web Mercator map, EPSG:3857, in metres: spherical formulas applied to geodetic latitudes. It stops at 85.05 degrees: the
154
+ * positions beyond it fall outside the tile matrices, so another source must cover the caps.
155
+ */
156
+ export class WebMercatorProjection implements ISourceProjection {
157
+ public readonly metresPerUnit = 1;
158
+ public readonly periodX: number;
159
+ private readonly radius: number;
160
+ private readonly squaredRatio: number;
161
+
162
+ public constructor(options: IWebMercatorProjectionOptions) {
163
+ this.radius = options.semiMajorAxis;
164
+ if (!(this.radius > 0) || !Number.isFinite(this.radius)) throw new RangeError("A projection requires a positive finite radius.");
165
+ const b = options.semiMinorAxis ?? options.semiMajorAxis;
166
+ this.squaredRatio = (this.radius * this.radius) / (b * b);
167
+ this.periodX = 2 * Math.PI * this.radius;
168
+ }
169
+
170
+ public forward(direction: Readonly<ICartesian3>, target: IMapPosition = { x: 0, y: 0 }): IMapPosition {
171
+ const latitude = Math.atan2(direction.z * this.squaredRatio, Math.hypot(direction.x, direction.y));
172
+ target.x = this.radius * Math.atan2(direction.y, direction.x);
173
+ // Infinite at the poles: those positions fall outside every tile matrix.
174
+ target.y = this.radius * Math.log(Math.tan(Math.PI / 4 + latitude / 2));
175
+ return target;
176
+ }
177
+
178
+ public inverse(x: number, y: number, target: ICartesian3 = { x: 0, y: 0, z: 0 }): ICartesian3 {
179
+ const longitude = x / this.radius;
180
+ const geodetic = 2 * Math.atan(Math.exp(y / this.radius)) - Math.PI / 2;
181
+ const latitude = Math.atan2(Math.sin(geodetic), Math.cos(geodetic) * this.squaredRatio);
182
+ target.x = Math.cos(latitude) * Math.cos(longitude);
183
+ target.y = Math.cos(latitude) * Math.sin(longitude);
184
+ target.z = Math.sin(latitude);
185
+ return target;
186
+ }
187
+ }
188
+
189
+ /** Longitude and geodetic latitude of a unit direction on a biaxial ellipsoid, in degrees, for the sources that use them. */
190
+ export function geodeticOfDirection(direction: Readonly<ICartesian3>, semiMajorAxis: number, semiMinorAxis: number): { latitude: number; longitude: number } {
191
+ const ratio = (semiMajorAxis * semiMajorAxis) / (semiMinorAxis * semiMinorAxis);
192
+ return {
193
+ latitude: Math.atan2(direction.z * ratio, Math.hypot(direction.x, direction.y)) * DEGREES,
194
+ longitude: Math.atan2(direction.y, direction.x) * DEGREES,
195
+ };
196
+ }