@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,121 @@
1
+ import { CELESTIAL_CUBE_SCHEME, CelestialTileSource, parseCelestialDataset, type ICelestialDataset } from "../cube/celestial-dataset";
2
+ import {
3
+ WEB_MERCATOR_SCHEME,
4
+ WebMercatorDatasetSource,
5
+ parseWebMercatorDataset,
6
+ type IWebMercatorDataset,
7
+ type IWebMercatorDatasetSourceOptions,
8
+ } from "../mercator/web-mercator-dataset";
9
+ import type { FetchFunction } from "../sources/tile-http-client";
10
+
11
+ /** A dataset descriptor of a tile service, on any tiling scheme this package knows. */
12
+ export type TileDataset = ICelestialDataset | IWebMercatorDataset;
13
+
14
+ /** The tile source of a dataset, on its own scheme. */
15
+ export type TileDatasetSource = CelestialTileSource | WebMercatorDatasetSource;
16
+
17
+ /** Schemes {@link parseTileDataset} reads. */
18
+ export const TILE_DATASET_SCHEMES: readonly string[] = [CELESTIAL_CUBE_SCHEME, WEB_MERCATOR_SCHEME];
19
+
20
+ /**
21
+ * Checks the JSON value of a dataset descriptor and reads it on its scheme.
22
+ *
23
+ * @throws RangeError When the scheme is unknown, or a member is missing or invalid.
24
+ */
25
+ export function parseTileDataset(value: unknown): TileDataset {
26
+ const scheme = typeof value === "object" && value !== null ? (value as Record<string, unknown>).scheme : undefined;
27
+ if (scheme === CELESTIAL_CUBE_SCHEME) return parseCelestialDataset(value);
28
+ if (scheme === WEB_MERCATOR_SCHEME) return parseWebMercatorDataset(value);
29
+ throw new RangeError(`Unknown dataset scheme ${String(scheme)}: expected one of ${TILE_DATASET_SCHEMES.join(", ")}.`);
30
+ }
31
+
32
+ /** Whether a descriptor is on the Web Mercator scheme. */
33
+ export function isWebMercatorDataset(dataset: TileDataset): dataset is IWebMercatorDataset {
34
+ return dataset.scheme === WEB_MERCATOR_SCHEME;
35
+ }
36
+
37
+ /** Options of {@link createTileDatasetSource}. */
38
+ export type ITileDatasetSourceOptions = IWebMercatorDatasetSourceOptions;
39
+
40
+ /** The tile source of a dataset: a cube source or a Web Mercator one, as its scheme says. */
41
+ export function createTileDatasetSource(dataset: TileDataset | unknown, options: ITileDatasetSourceOptions = {}): TileDatasetSource {
42
+ const parsed = parseTileDataset(dataset);
43
+ return isWebMercatorDataset(parsed) ? new WebMercatorDatasetSource(parsed, options) : new CelestialTileSource(parsed, options.client ? { client: options.client } : {});
44
+ }
45
+
46
+ /**
47
+ * What a descriptor may be used for, as its optional `usage` member says. `"development"` marks a source whose terms
48
+ * cover development only, such as tiles read straight from a commercial map service: an application must never ship it.
49
+ * Without the member, the descriptor is `"public"`.
50
+ */
51
+ export type TileDatasetUsage = "public" | "development";
52
+
53
+ /**
54
+ * The usage a descriptor declares.
55
+ *
56
+ * @throws RangeError When `usage` is neither `"public"` nor `"development"`.
57
+ */
58
+ export function tileDatasetUsage(value: unknown): TileDatasetUsage {
59
+ const usage = typeof value === "object" && value !== null ? (value as Record<string, unknown>).usage : undefined;
60
+ if (usage === undefined || usage === "public") return "public";
61
+ if (usage === "development") return usage;
62
+ throw new RangeError(`Unknown dataset usage ${String(usage)}: expected "public" or "development".`);
63
+ }
64
+
65
+ /** The error of a descriptor refused because it is for development only and the application runs in production. */
66
+ export class DevelopmentDatasetError extends Error {
67
+ constructor(readonly url: string) {
68
+ super(`${url} is for development only and is not used in production.`);
69
+ this.name = "DevelopmentDatasetError";
70
+ }
71
+ }
72
+
73
+ /** Options of {@link loadTileDataset}. */
74
+ export interface ILoadTileDatasetOptions {
75
+ /** Whether the application runs in production: a descriptor for development only is then refused. */
76
+ production?: boolean;
77
+ /** The fetch of the host; the global one by default. */
78
+ fetch?: FetchFunction;
79
+ /** Whether a descriptor answered 404 reads as absent instead of failing. */
80
+ optional?: boolean;
81
+ signal?: AbortSignal;
82
+ }
83
+
84
+ /** Whether a template is already an absolute URL. */
85
+ const ABSOLUTE = /^[a-z][a-z\d+.-]*:/i;
86
+
87
+ /**
88
+ * Resolves a relative template against the URL of its descriptor, as a relative URI of 3D Tiles resolves against its
89
+ * tileset: a static bucket can serve `./{z}/{x}/{y}.png` next to its `imagery.json`. Braces stay unescaped.
90
+ */
91
+ export function resolveTileTemplate(template: string, descriptorUrl: string): string {
92
+ if (ABSOLUTE.test(template)) return template;
93
+ return new URL(template, descriptorUrl).href.replace(/%7B/gi, "{").replace(/%7D/gi, "}");
94
+ }
95
+
96
+ /**
97
+ * Reads a dataset descriptor from a URL: either the descriptor itself (`.../imagery.json`), or a service and the name
98
+ * of its descriptor through {@link tileDatasetUrl}. The tiles template is resolved against the descriptor URL, then
99
+ * the descriptor is checked on its scheme. This is the one loader the applications of SpaceXR share.
100
+ *
101
+ * @returns The descriptor, or `undefined` for a missing optional one.
102
+ * @throws Error When the request fails, RangeError when the descriptor is invalid, {@link DevelopmentDatasetError}
103
+ * when it is for development only and `production` is set.
104
+ */
105
+ export async function loadTileDataset(url: string, options: ILoadTileDatasetOptions = {}): Promise<TileDataset | undefined> {
106
+ const fetcher = options.fetch ?? ((input: string, init?: RequestInit) => fetch(input, init));
107
+ const href = new URL(url, typeof location === "undefined" ? undefined : location.href).href;
108
+ if (/^[a-z][a-z\d+.-]*:\/\/[^/]*@/i.test(href)) throw new RangeError("A dataset URL must not carry credentials.");
109
+ const response = await fetcher(href, options.signal ? { signal: options.signal } : undefined);
110
+ if (options.optional && response.status === 404) return undefined;
111
+ if (!response.ok) throw new Error(`${href} answered ${response.status}.`);
112
+ const descriptor = (await response.json()) as Record<string, unknown>;
113
+ if (tileDatasetUsage(descriptor) === "development" && options.production) throw new DevelopmentDatasetError(href);
114
+ if (typeof descriptor?.tiles === "string") descriptor.tiles = resolveTileTemplate(descriptor.tiles, href);
115
+ return parseTileDataset(descriptor);
116
+ }
117
+
118
+ /** The URL of the descriptor `name.json` of a tile service, such as `elevation` or `imagery`. */
119
+ export function tileDatasetUrl(service: string, name: string): string {
120
+ return new URL(`${name}.json`, `${service.replace(/\/+$/, "")}/`).href;
121
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export * from "./addressing";
2
+ export * from "./bake";
3
+ export * from "./cube";
4
+ export * from "./datasets";
5
+ export * from "./mercator";
6
+ export * from "./pyramid";
7
+ export * from "./reprojection";
8
+ export * from "./sources";
9
+ export * from "./surface";
@@ -0,0 +1,3 @@
1
+ export * from "./web-mercator-tile-metrics";
2
+ export * from "./web-mercator-tile-surface";
3
+ export * from "./web-mercator-dataset";
@@ -0,0 +1,215 @@
1
+ import { Ellipsoid, GeodeticSystem } from "@spacexr/geodesy";
2
+
3
+ import { assertRasterRegistration, type ITileAddress, type RasterRegistration } from "../addressing";
4
+ import { TileHttpClient, type ITileHttpClientOptions, type TileFetchResult } from "../sources/tile-http-client";
5
+ import { validateTileUrlTemplate } from "../sources/url-template";
6
+ import { WebTileSource } from "../sources/web-tile-source";
7
+ import { WebMercatorTileMetrics } from "./web-mercator-tile-metrics";
8
+
9
+ /** Scheme of the Web Mercator datasets of this version of the specification. */
10
+ export const WEB_MERCATOR_SCHEME = "spacexr-web-mercator/1";
11
+
12
+ /** What the tiles of a dataset hold. */
13
+ export type TileDatasetContent = "elevation" | "imagery" | "normals";
14
+
15
+ /** A rectangle in degrees of longitude and latitude on the reference surface of a dataset. */
16
+ export interface IDatasetBounds {
17
+ readonly west: number;
18
+ readonly south: number;
19
+ readonly east: number;
20
+ readonly north: number;
21
+ }
22
+
23
+ /**
24
+ * Descriptor of a Web Mercator (EPSG:3857 tiling, XYZ addressing, `y` from the north) dataset of a tile service: a
25
+ * provider such as an elevation or imagery pyramid is described by this data, never by code.
26
+ */
27
+ export interface IWebMercatorDataset {
28
+ /** This specification and its version: {@link WEB_MERCATOR_SCHEME}. */
29
+ readonly scheme: string;
30
+ /** Catalogue name of the body, such as `Earth`. */
31
+ readonly body: string;
32
+ /** Radii `a`, `b`, `c` of the ellipsoid of revolution the tiles are computed on, in metres: `a` equals `b`. */
33
+ readonly referenceRadii: readonly [number, number, number];
34
+ readonly content: TileDatasetContent;
35
+ /** Tile format: `terrarium` heights, `mapzen-normal` normals, or an image format such as `png`, `jpeg`, `webp`. */
36
+ readonly encoding: string;
37
+ /** Pixels per tile side. */
38
+ readonly tileSize: number;
39
+ /** Levels available inside {@link bounds}, from `minLOD` to `maxLOD`. */
40
+ readonly minLOD: number;
41
+ readonly maxLOD: number;
42
+ /** Where the dataset has tiles; the whole Web Mercator square when absent. A tile outside is never requested. */
43
+ readonly bounds?: IDatasetBounds;
44
+ /** Where the samples of the tiles lie: `area` for images, the usual case. */
45
+ readonly registration: RasterRegistration;
46
+ /** URL template; a relative one is resolved against the URL of its descriptor by {@link loadTileDataset}. */
47
+ readonly tiles: string;
48
+ /** Values of `{s}` in the template, rotated between requests. */
49
+ readonly subdomains?: readonly string[];
50
+ /** Text applications must display with the tiles. */
51
+ readonly attribution: string;
52
+ }
53
+
54
+ function fail(message: string): never {
55
+ throw new RangeError(`Invalid Web Mercator dataset: ${message}`);
56
+ }
57
+
58
+ function text(value: Record<string, unknown>, name: string): string {
59
+ const member = value[name];
60
+ if (typeof member !== "string" || member.length === 0) fail(`${name} must be a non-empty string.`);
61
+ return member;
62
+ }
63
+
64
+ function level(value: Record<string, unknown>, name: string): number {
65
+ const member = value[name];
66
+ if (!Number.isInteger(member) || (member as number) < 0 || (member as number) > 30) fail(`${name} must be a level from 0 to 30.`);
67
+ return member as number;
68
+ }
69
+
70
+ function bounds(value: unknown): IDatasetBounds | undefined {
71
+ if (value === undefined) return undefined;
72
+ if (typeof value !== "object" || value === null) fail("bounds must be an object.");
73
+ const box = value as Record<string, unknown>;
74
+ const [west, south, east, north] = ["west", "south", "east", "north"].map((name) => box[name]);
75
+ if (![west, south, east, north].every((v) => typeof v === "number" && Number.isFinite(v))) fail("bounds needs four finite numbers of degrees.");
76
+ const w = west as number,
77
+ s = south as number,
78
+ e = east as number,
79
+ n = north as number;
80
+ if (w < -180 || e > 180 || w >= e || s < -90 || n > 90 || s >= n) fail("bounds must satisfy -180 <= west < east <= 180 and -90 <= south < north <= 90.");
81
+ return { west: w, south: s, east: e, north: n };
82
+ }
83
+
84
+ /**
85
+ * Checks the JSON value of a Web Mercator dataset descriptor.
86
+ *
87
+ * @throws RangeError When a member is missing or invalid, naming it. A scheme of another version is rejected.
88
+ * @throws TileUrlTemplateError When the URL template uses an unknown variable.
89
+ */
90
+ export function parseWebMercatorDataset(value: unknown): IWebMercatorDataset {
91
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail("the descriptor must be an object.");
92
+ const source = value as Record<string, unknown>;
93
+ const scheme = text(source, "scheme");
94
+ if (scheme !== WEB_MERCATOR_SCHEME) fail(`scheme ${scheme} is not supported, expected ${WEB_MERCATOR_SCHEME}.`);
95
+ const radii = source.referenceRadii;
96
+ if (!Array.isArray(radii) || radii.length !== 3 || radii.some((radius) => typeof radius !== "number" || !Number.isFinite(radius) || radius <= 0)) {
97
+ fail("referenceRadii must be three positive numbers of metres.");
98
+ }
99
+ if (radii[0] !== radii[1]) fail("referenceRadii must describe an ellipsoid of revolution: a equals b.");
100
+ const content = source.content;
101
+ if (content !== "elevation" && content !== "imagery" && content !== "normals") fail("content must be elevation, imagery or normals.");
102
+ const tileSize = source.tileSize;
103
+ if (!Number.isInteger(tileSize) || (tileSize as number) < 1) fail("tileSize must be a positive integer.");
104
+ const minLOD = level(source, "minLOD");
105
+ const maxLOD = level(source, "maxLOD");
106
+ if (minLOD > maxLOD) fail("minLOD must not exceed maxLOD.");
107
+ const registration = (source.registration ?? "area") as RasterRegistration;
108
+ try {
109
+ assertRasterRegistration(registration);
110
+ } catch {
111
+ fail("registration must be area or point.");
112
+ }
113
+ const rawSubdomains = source.subdomains;
114
+ if (rawSubdomains !== undefined && (!Array.isArray(rawSubdomains) || rawSubdomains.some((s) => typeof s !== "string" || s.length === 0))) {
115
+ fail("subdomains must be an array of non-empty strings.");
116
+ }
117
+ const subdomains = rawSubdomains as string[] | undefined;
118
+ const tiles = text(source, "tiles");
119
+ validateTileUrlTemplate(tiles, subdomains ? { subdomains } : {});
120
+ const box = bounds(source.bounds);
121
+ return {
122
+ scheme,
123
+ body: text(source, "body"),
124
+ referenceRadii: [radii[0] as number, radii[1] as number, radii[2] as number],
125
+ content,
126
+ encoding: text(source, "encoding"),
127
+ tileSize: tileSize as number,
128
+ minLOD,
129
+ maxLOD,
130
+ ...(box ? { bounds: box } : {}),
131
+ registration,
132
+ tiles,
133
+ ...(subdomains ? { subdomains: [...subdomains] } : {}),
134
+ attribution: text(source, "attribution"),
135
+ };
136
+ }
137
+
138
+ /**
139
+ * The JSON value of a Web Mercator dataset descriptor, as {@link parseWebMercatorDataset} reads it back: the members of
140
+ * the dataset, checked, with `extras` written as given (the parser keeps no member it does not know).
141
+ *
142
+ * @throws RangeError When a member is invalid, as {@link parseWebMercatorDataset} would report it.
143
+ */
144
+ export function webMercatorDatasetDescriptor(dataset: Omit<IWebMercatorDataset, "scheme">, extras?: Record<string, unknown>): Record<string, unknown> {
145
+ const checked = parseWebMercatorDataset({ ...dataset, scheme: WEB_MERCATOR_SCHEME });
146
+ return { ...checked, ...(extras ? { extras } : {}) };
147
+ }
148
+
149
+ /** Options of {@link WebMercatorDatasetSource}. */
150
+ export interface IWebMercatorDatasetSourceOptions {
151
+ /** Shared client, or options used to create a dedicated one. */
152
+ client?: TileHttpClient | ITileHttpClientOptions;
153
+ /**
154
+ * Geodetic system of the tiles; by default one built from the radii of the descriptor. Give the system of the
155
+ * application when it is the same ellipsoid, so that its metrics compare equal.
156
+ */
157
+ geodeticSystem?: GeodeticSystem;
158
+ }
159
+
160
+ /** Longitude and latitude in degrees of the north-west corner of a Web Mercator tile. */
161
+ function corner(lod: number, x: number, y: number): { longitude: number; latitude: number } {
162
+ const n = 2 ** lod;
163
+ return { longitude: (x / n) * 360 - 180, latitude: (Math.atan(Math.sinh(Math.PI * (1 - (2 * y) / n))) * 180) / Math.PI };
164
+ }
165
+
166
+ /**
167
+ * Tiles of a Web Mercator dataset over HTTP. Like the cube source of a tile service, it never requests a tile the
168
+ * descriptor does not declare: a level out of range, or a tile outside the bounds, resolves as absent.
169
+ */
170
+ export class WebMercatorDatasetSource {
171
+ public readonly dataset: IWebMercatorDataset;
172
+ public readonly metrics: WebMercatorTileMetrics;
173
+ /** The HTTP source of the tiles, for consumers that take a {@link WebTileSource}. */
174
+ public readonly source: WebTileSource;
175
+
176
+ /** @param dataset - The descriptor, or its JSON value, checked by {@link parseWebMercatorDataset}. */
177
+ public constructor(dataset: IWebMercatorDataset | unknown, options: IWebMercatorDatasetSourceOptions = {}) {
178
+ this.dataset = parseWebMercatorDataset(dataset);
179
+ const [a, , c] = this.dataset.referenceRadii;
180
+ const system = options.geodeticSystem ?? new GeodeticSystem(Ellipsoid.fromAxes(this.dataset.body, a, c));
181
+ this.metrics = new WebMercatorTileMetrics({ minLOD: 0, maxLOD: this.dataset.maxLOD, tileSize: this.dataset.tileSize }, system);
182
+ this.source = new WebTileSource({
183
+ id: `${this.dataset.body}-${this.dataset.content}`,
184
+ urlTemplate: this.dataset.tiles,
185
+ metrics: this.metrics,
186
+ registration: this.dataset.registration,
187
+ attribution: this.dataset.attribution,
188
+ ...(this.dataset.subdomains ? { subdomains: [...this.dataset.subdomains] } : {}),
189
+ ...(options.client ? { client: options.client } : {}),
190
+ });
191
+ }
192
+
193
+ public get attribution(): string {
194
+ return this.dataset.attribution;
195
+ }
196
+
197
+ /** Whether the dataset declares a tile: its level is in range and it meets the bounds. */
198
+ public isAvailable(address: ITileAddress): boolean {
199
+ const { lod, x, y } = address;
200
+ if (!Number.isInteger(lod) || lod < this.dataset.minLOD || lod > this.dataset.maxLOD) return false;
201
+ const n = 2 ** lod;
202
+ if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0 || x >= n || y >= n) return false;
203
+ const box = this.dataset.bounds;
204
+ if (!box) return true;
205
+ const northWest = corner(lod, x, y),
206
+ southEast = corner(lod, x + 1, y + 1);
207
+ return northWest.longitude < box.east && southEast.longitude > box.west && southEast.latitude < box.north && northWest.latitude > box.south;
208
+ }
209
+
210
+ /** Fetches a tile; a tile the dataset does not declare resolves as absent, like a 404, without any request. */
211
+ public async fetchTile(address: ITileAddress, signal?: AbortSignal): Promise<TileFetchResult> {
212
+ if (!this.isAvailable(address)) return { status: "absent", url: "", httpStatus: 404 };
213
+ return this.source.fetchTile(address, signal);
214
+ }
215
+ }
@@ -0,0 +1,119 @@
1
+ import { GeodeticSystem } from "@spacexr/geodesy";
2
+
3
+ import { CellCoordinateReference, type ICartesian2, type IGeographic2, type ITileMetrics } from "../addressing/metrics";
4
+
5
+ const WEB_MERCATOR_MAX_LATITUDE = 85.0511287798066;
6
+
7
+ export interface IWebMercatorTileMetricsOptions {
8
+ minLOD: number;
9
+ maxLOD: number;
10
+ tileSize?: number;
11
+ cellSize?: number;
12
+ cellCoordinateReference?: CellCoordinateReference;
13
+ overlap?: number;
14
+ }
15
+
16
+ function clamp(value: number, minimum: number, maximum: number): number {
17
+ return Math.min(Math.max(value, minimum), maximum);
18
+ }
19
+
20
+ /** Immutable EPSG:3857 tile metrics backed by a geodetic ellipsoid. */
21
+ export class WebMercatorTileMetrics implements ITileMetrics {
22
+ public readonly minLatitude = -WEB_MERCATOR_MAX_LATITUDE;
23
+ public readonly maxLatitude = WEB_MERCATOR_MAX_LATITUDE;
24
+ public readonly minLongitude = -180;
25
+ public readonly maxLongitude = 180;
26
+ public readonly minLOD: number;
27
+ public readonly maxLOD: number;
28
+ public readonly tileSize: number;
29
+ public readonly cellSize: number;
30
+ public readonly cellCoordinateReference: CellCoordinateReference;
31
+ public readonly overlap: number;
32
+
33
+ public constructor(
34
+ options: IWebMercatorTileMetricsOptions,
35
+ public readonly geodeticSystem: GeodeticSystem
36
+ ) {
37
+ if (!geodeticSystem) throw new TypeError("An explicit geodetic system is required.");
38
+ if (!Number.isInteger(options.minLOD) || !Number.isInteger(options.maxLOD) || options.minLOD < 0 || options.maxLOD < options.minLOD)
39
+ throw new RangeError("Tile metrics require integer LOD bounds with 0 <= minLOD <= maxLOD.");
40
+ const tileSize = options.tileSize ?? 256;
41
+ if (!Number.isFinite(tileSize) || tileSize <= 0) throw new RangeError("Tile size must be a positive finite number.");
42
+
43
+ this.minLOD = options.minLOD;
44
+ this.maxLOD = options.maxLOD;
45
+ this.tileSize = tileSize;
46
+ this.cellSize = options.cellSize ?? 1;
47
+ this.cellCoordinateReference = options.cellCoordinateReference ?? CellCoordinateReference.Center;
48
+ this.overlap = options.overlap ?? 0;
49
+ }
50
+
51
+ public mapSize(levelOfDetail: number): number {
52
+ this.assertLOD(levelOfDetail);
53
+ return this.tileSize * 2 ** levelOfDetail;
54
+ }
55
+
56
+ public mapScale(latitudeDegrees: number, levelOfDetail: number, pixelsPerUnit: number): number {
57
+ if (pixelsPerUnit === 0) return Number.POSITIVE_INFINITY;
58
+ const resolution = this.groundResolution(latitudeDegrees, levelOfDetail);
59
+ return resolution === 0 ? Number.POSITIVE_INFINITY : 1 / (resolution * pixelsPerUnit);
60
+ }
61
+
62
+ public groundResolution(latitudeDegrees: number, levelOfDetail: number): number {
63
+ const latitude = clamp(latitudeDegrees, this.minLatitude, this.maxLatitude);
64
+ const circumference = 2 * Math.PI * this.geodeticSystem.ellipsoid.semiMajorAxis;
65
+ return (Math.cos((latitude * Math.PI) / 180) * circumference) / this.mapSize(levelOfDetail);
66
+ }
67
+
68
+ public getLatLonToTileXY(latitudeDegrees: number, longitudeDegrees: number, levelOfDetail: number): ICartesian2 {
69
+ const point = this.getLatLonToPointXY(latitudeDegrees, longitudeDegrees, levelOfDetail);
70
+ const tile = this.getPointXYToTileXY(point.x, point.y);
71
+ // The east and south map edges belong to the last tile, not to a tile beyond the pyramid.
72
+ const lastTile = 2 ** levelOfDetail - 1;
73
+ return { x: Math.min(tile.x, lastTile), y: Math.min(tile.y, lastTile) };
74
+ }
75
+
76
+ public getTileXYToLatLon(x: number, y: number, levelOfDetail: number): IGeographic2 {
77
+ const point = this.getTileXYToPointXY(x, y);
78
+ return this.getPointXYToLatLon(point.x, point.y, levelOfDetail);
79
+ }
80
+
81
+ public getLatLonToPointXY(latitudeDegrees: number, longitudeDegrees: number, levelOfDetail: number): ICartesian2 {
82
+ const latitude = clamp(latitudeDegrees, this.minLatitude, this.maxLatitude);
83
+ const longitude = clamp(longitudeDegrees, this.minLongitude, this.maxLongitude);
84
+ const normalizedX = (longitude + 180) / 360;
85
+ const sineLatitude = Math.sin((latitude * Math.PI) / 180);
86
+ const normalizedY = 0.5 - Math.log((1 + sineLatitude) / (1 - sineLatitude)) / (4 * Math.PI);
87
+ const mapSize = this.mapSize(levelOfDetail);
88
+ return {
89
+ x: clamp(normalizedX * mapSize, 0, mapSize),
90
+ y: clamp(normalizedY * mapSize, 0, mapSize),
91
+ };
92
+ }
93
+
94
+ public getPointXYToLatLon(x: number, y: number, levelOfDetail: number): IGeographic2 {
95
+ const mapSize = this.mapSize(levelOfDetail);
96
+ const normalizedX = clamp(x, 0, mapSize) / mapSize - 0.5;
97
+ const normalizedY = 0.5 - clamp(y, 0, mapSize) / mapSize;
98
+ return {
99
+ latitude: 90 - (360 * Math.atan(Math.exp(-normalizedY * 2 * Math.PI))) / Math.PI,
100
+ longitude: 360 * normalizedX,
101
+ };
102
+ }
103
+
104
+ public getTileXYToPointXY(x: number, y: number): ICartesian2 {
105
+ return { x: x * this.tileSize, y: y * this.tileSize };
106
+ }
107
+
108
+ public getPointXYToTileXY(x: number, y: number): ICartesian2 {
109
+ return {
110
+ x: Math.floor(x / this.tileSize),
111
+ y: Math.floor(y / this.tileSize),
112
+ };
113
+ }
114
+
115
+ private assertLOD(levelOfDetail: number): void {
116
+ if (!Number.isInteger(levelOfDetail) || levelOfDetail < this.minLOD || levelOfDetail > this.maxLOD)
117
+ throw new RangeError(`LOD ${levelOfDetail} is outside [${this.minLOD}, ${this.maxLOD}].`);
118
+ }
119
+ }
@@ -0,0 +1,52 @@
1
+ import { GeodeticSystem, type ICartesian3 } from "@spacexr/geodesy";
2
+
3
+ import { assertValidTileAddress, formatTileAddress, tileCount, type ITileAddress } from "../addressing/tile-address";
4
+ import type { ITileShapeFrame, ITileSurface } from "../addressing/tile-surface";
5
+
6
+ /**
7
+ * Tiles of a Web Mercator pyramid on an ellipsoid. Heights are geodetic, along the normal of the ellipsoid. Tiles of
8
+ * one level and row are the same shape turned about the polar axis.
9
+ */
10
+ export class WebMercatorTileSurface implements ITileSurface {
11
+ /** @param system - Geodetic system of the ellipsoid. Supplied explicitly by the caller. */
12
+ public constructor(private readonly system: GeodeticSystem) {
13
+ if (!system) throw new TypeError("An explicit geodetic system is required.");
14
+ }
15
+
16
+ public point(address: ITileAddress, s: number, t: number, height = 0, target: ICartesian3 = { x: 0, y: 0, z: 0 }): ICartesian3 {
17
+ this.assertAddress(address);
18
+ const count = tileCount(address.lod);
19
+ return this.system.geodeticRadiansToEcef(latitudeOf((address.y + t) / count), longitudeOf((address.x + s) / count), height, target);
20
+ }
21
+
22
+ public up(address: ITileAddress, s: number, t: number, target: ICartesian3 = { x: 0, y: 0, z: 0 }): ICartesian3 {
23
+ this.assertAddress(address);
24
+ const count = tileCount(address.lod);
25
+ const latitude = latitudeOf((address.y + t) / count);
26
+ const longitude = longitudeOf((address.x + s) / count);
27
+ target.x = Math.cos(latitude) * Math.cos(longitude);
28
+ target.y = Math.cos(latitude) * Math.sin(longitude);
29
+ target.z = Math.sin(latitude);
30
+ return target;
31
+ }
32
+
33
+ public shape(address: ITileAddress): ITileShapeFrame {
34
+ this.assertAddress(address);
35
+ return { key: `${address.lod}/${address.y}`, rotation: longitudeOf((address.x + 0.5) / tileCount(address.lod)) };
36
+ }
37
+
38
+ private assertAddress(address: ITileAddress): void {
39
+ assertValidTileAddress(address);
40
+ if (address.face) throw new RangeError(`Tile ${formatTileAddress(address)} does not exist: a Web Mercator pyramid has one root.`);
41
+ }
42
+ }
43
+
44
+ /** Latitude in radians of a Web Mercator ordinate, southward in `[0, 1]` over the whole pyramid. */
45
+ function latitudeOf(y: number): number {
46
+ return Math.atan(Math.sinh(Math.PI * (1 - 2 * y)));
47
+ }
48
+
49
+ /** Longitude in radians of a Web Mercator abscissa, eastward in `[0, 1]` over the whole pyramid. */
50
+ function longitudeOf(x: number): number {
51
+ return (2 * x - 1) * Math.PI;
52
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./resident-tiles";
2
+ export * from "./tile-pyramid";
@@ -0,0 +1,81 @@
1
+ import { tileAddressKey as key, type ITileAddress } from "../addressing/tile-address";
2
+ import { tileAreaInAncestor, type ITileAreaInAncestor } from "./tile-pyramid";
3
+
4
+ /** Resident tile covering a requested tile, with the part of it the requested tile covers. */
5
+ export interface IResidentTileCover<T> extends ITileAreaInAncestor {
6
+ /** Value stored for `ancestor`, the resident tile. */
7
+ value: T;
8
+ }
9
+
10
+ interface IResidentEntry<T> {
11
+ readonly address: ITileAddress;
12
+ value: T;
13
+ }
14
+
15
+ /**
16
+ * Tiles currently available to a renderer, such as texture pages or elevation pages, indexed for coverage lookups.
17
+ *
18
+ * A renderer binds the data of one pyramid to the tiles of another: imagery pages to terrain tiles, or elevation
19
+ * pages to imagery tiles. `cover` returns the deepest resident tile containing a requested tile, so that a binding
20
+ * always falls back to coarser data while finer data loads.
21
+ */
22
+ export class ResidentTiles<T> {
23
+ private readonly entries = new Map<string, IResidentEntry<T>>();
24
+
25
+ public get size(): number {
26
+ return this.entries.size;
27
+ }
28
+
29
+ public get(address: ITileAddress): T | undefined {
30
+ return this.entries.get(key(address))?.value;
31
+ }
32
+
33
+ public has(address: ITileAddress): boolean {
34
+ return this.entries.has(key(address));
35
+ }
36
+
37
+ public set(address: ITileAddress, value: T): void {
38
+ const entry = this.entries.get(key(address));
39
+ if (entry) entry.value = value;
40
+ else this.entries.set(key(address), { address: { ...address }, value });
41
+ }
42
+
43
+ public delete(address: ITileAddress): boolean {
44
+ return this.entries.delete(key(address));
45
+ }
46
+
47
+ /** Addresses of the resident tiles. */
48
+ public *addresses(): IterableIterator<ITileAddress> {
49
+ for (const entry of this.entries.values()) yield entry.address;
50
+ }
51
+
52
+ /**
53
+ * Deepest resident tile containing a tile, the tile itself included, and the part of it the tile covers.
54
+ *
55
+ * @param minLOD - Coarsest level searched. Defaults to 0.
56
+ * @returns `undefined` when no resident tile contains the tile.
57
+ */
58
+ public cover(address: ITileAddress, minLOD = 0): IResidentTileCover<T> | undefined {
59
+ for (let levels = 0; address.lod - levels >= minLOD; levels++) {
60
+ const area = tileAreaInAncestor(address, levels);
61
+ const entry = this.entries.get(key(area.ancestor));
62
+ if (entry !== undefined) return { ...area, value: entry.value };
63
+ }
64
+ return undefined;
65
+ }
66
+
67
+ /**
68
+ * Levels between a tile and the deepest resident tile inside it, at most `maxLevels` below: `0` when only the
69
+ * tile itself is resident, `undefined` when no resident tile lies inside it.
70
+ */
71
+ public depthWithin(address: ITileAddress, maxLevels = Number.POSITIVE_INFINITY): number | undefined {
72
+ let depth: number | undefined;
73
+ for (const { address: resident } of this.entries.values()) {
74
+ const levels = resident.lod - address.lod;
75
+ if ((resident.face ?? 0) !== (address.face ?? 0) || levels < 0 || levels > maxLevels || (depth !== undefined && levels <= depth)) continue;
76
+ const scale = 2 ** levels;
77
+ if (Math.floor(resident.x / scale) === address.x && Math.floor(resident.y / scale) === address.y) depth = levels;
78
+ }
79
+ return depth;
80
+ }
81
+ }