@tangram.gl/basemap-layers 0.0.1 → 10.0.0-alpha.3

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 (139) hide show
  1. package/README.md +12 -7
  2. package/THIRD-PARTY-NOTICES.md +7 -5
  3. package/dist/geojson-task-worker.js +3166 -0
  4. package/dist/geojson-task-worker.js.map +6 -0
  5. package/dist/geojson-worker.js +1089 -7
  6. package/dist/geojson-worker.js.map +3 -3
  7. package/dist/index.cjs +9588 -2093
  8. package/dist/index.cjs.map +3 -3
  9. package/dist/index.js +9599 -2090
  10. package/dist/index.js.map +3 -3
  11. package/dist/map-style.cjs +456 -20
  12. package/dist/map-style.cjs.map +3 -3
  13. package/dist/map-style.js +456 -19
  14. package/dist/map-style.js.map +2 -2
  15. package/dist/types/basemap-error.d.ts +52 -0
  16. package/dist/types/basemap-layer.d.ts +378 -25
  17. package/dist/types/basemap-protocol.d.ts +91 -0
  18. package/dist/types/basemap-request.d.ts +73 -0
  19. package/dist/types/circle-layer.d.ts +65 -8
  20. package/dist/types/color-relief-layer.d.ts +184 -0
  21. package/dist/types/dem-pixels.d.ts +40 -0
  22. package/dist/types/feature-state.d.ts +55 -0
  23. package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
  24. package/dist/types/fill-outline-extension.d.ts +2 -3
  25. package/dist/types/fill-pattern.d.ts +35 -3
  26. package/dist/types/fill-style-extensions.d.ts +11 -59
  27. package/dist/types/geojson-resource.d.ts +18 -0
  28. package/dist/types/geojson-source.d.ts +13 -2
  29. package/dist/types/geojson-task-handler.d.ts +2 -0
  30. package/dist/types/geojson-task.d.ts +26 -0
  31. package/dist/types/geojson-tiler.d.ts +29 -2
  32. package/dist/types/geojson-worker.d.ts +5 -1
  33. package/dist/types/globe-horizon-extension.d.ts +2 -45
  34. package/dist/types/globe-layers.d.ts +141 -45
  35. package/dist/types/globe-line-angle-extension.d.ts +20 -17
  36. package/dist/types/glyph-store.d.ts +10 -1
  37. package/dist/types/heatmap-layer.d.ts +99 -0
  38. package/dist/types/hillshade-layer.d.ts +159 -27
  39. package/dist/types/icon-text-fit.d.ts +92 -0
  40. package/dist/types/image-source-layer.d.ts +142 -0
  41. package/dist/types/index.d.ts +25 -1
  42. package/dist/types/line-blur-extension.d.ts +3 -11
  43. package/dist/types/line-dash-extension.d.ts +53 -0
  44. package/dist/types/line-gradient-extension.d.ts +69 -0
  45. package/dist/types/line-metrics.d.ts +24 -0
  46. package/dist/types/line-pattern-extension.d.ts +50 -0
  47. package/dist/types/line-shape-extension.d.ts +76 -0
  48. package/dist/types/map-style-loader.d.ts +1 -1
  49. package/dist/types/map-style.d.ts +2 -2
  50. package/dist/types/mvt-label-layer.d.ts +111 -20
  51. package/dist/types/pmtiles-source.d.ts +38 -0
  52. package/dist/types/projected-background-layer.d.ts +63 -0
  53. package/dist/types/projected-bitmap-layer.d.ts +58 -0
  54. package/dist/types/projected-tile-data.d.ts +16 -0
  55. package/dist/types/projected-tile-selection.d.ts +72 -0
  56. package/dist/types/projected-tileset.d.ts +92 -0
  57. package/dist/types/projected-viewport.d.ts +76 -0
  58. package/dist/types/raster-color-extension.d.ts +4 -7
  59. package/dist/types/raster-fade.d.ts +155 -0
  60. package/dist/types/raster-tile-fingerprint.d.ts +11 -0
  61. package/dist/types/raster-tile-loader.d.ts +80 -0
  62. package/dist/types/shader-injection-plugin.d.ts +8 -0
  63. package/dist/types/source-features.d.ts +58 -0
  64. package/dist/types/source-tiles.d.ts +32 -0
  65. package/dist/types/sprite.d.ts +37 -3
  66. package/dist/types/stretch-icon-layer.d.ts +28 -0
  67. package/dist/types/style-accessor.d.ts +50 -12
  68. package/dist/types/style-expression.d.ts +22 -2
  69. package/dist/types/style-resolver.d.ts +47 -2
  70. package/dist/types/terrain-query.d.ts +39 -0
  71. package/dist/types/zoom-load-gate.d.ts +22 -0
  72. package/dist/types/zoom-paint-extension.d.ts +80 -11
  73. package/package.json +24 -21
  74. package/src/basemap-error.ts +82 -0
  75. package/src/basemap-layer.ts +1289 -101
  76. package/src/basemap-protocol.ts +353 -0
  77. package/src/basemap-request.ts +212 -0
  78. package/src/circle-layer.ts +430 -54
  79. package/src/color-relief-layer.ts +572 -0
  80. package/src/dem-pixels.ts +174 -0
  81. package/src/feature-state.ts +164 -0
  82. package/src/fill-extrusion-lighting-extension.ts +126 -9
  83. package/src/fill-outline-extension.ts +4 -4
  84. package/src/fill-pattern.ts +87 -9
  85. package/src/fill-style-extensions.ts +114 -44
  86. package/src/geojson-resource.ts +58 -0
  87. package/src/geojson-source.ts +106 -85
  88. package/src/geojson-task-handler.ts +11 -0
  89. package/src/geojson-task-worker.ts +8 -0
  90. package/src/geojson-task.ts +34 -0
  91. package/src/geojson-tiler.ts +270 -4
  92. package/src/geojson-worker.ts +36 -6
  93. package/src/globe-horizon-extension.ts +14 -4
  94. package/src/globe-layers.ts +1905 -406
  95. package/src/globe-line-angle-extension.ts +183 -23
  96. package/src/glyph-store.ts +28 -6
  97. package/src/heatmap-layer.ts +591 -0
  98. package/src/hillshade-layer.ts +309 -88
  99. package/src/icon-text-fit.ts +358 -0
  100. package/src/image-source-layer.ts +380 -0
  101. package/src/index.ts +58 -1
  102. package/src/line-blur-extension.ts +14 -12
  103. package/src/line-dash-extension.ts +303 -0
  104. package/src/line-gradient-extension.ts +191 -0
  105. package/src/line-metrics.ts +90 -0
  106. package/src/line-pattern-extension.ts +173 -0
  107. package/src/line-shape-extension.ts +272 -0
  108. package/src/map-style-loader.ts +5 -4
  109. package/src/map-style.ts +2 -1
  110. package/src/mvt-label-layer.ts +568 -144
  111. package/src/pmtiles-source.ts +276 -0
  112. package/src/projected-background-layer.ts +202 -0
  113. package/src/projected-bitmap-layer.ts +262 -0
  114. package/src/projected-tile-data.ts +132 -0
  115. package/src/projected-tile-selection.ts +605 -0
  116. package/src/projected-tileset.ts +183 -0
  117. package/src/projected-viewport.ts +254 -0
  118. package/src/raster-color-extension.ts +43 -18
  119. package/src/raster-fade.ts +319 -0
  120. package/src/raster-tile-fingerprint.ts +31 -0
  121. package/src/raster-tile-loader.ts +211 -0
  122. package/src/shader-injection-plugin.ts +25 -0
  123. package/src/source-features.ts +170 -0
  124. package/src/source-tiles.ts +102 -0
  125. package/src/sprite.ts +122 -15
  126. package/src/stretch-icon-layer.ts +87 -0
  127. package/src/style-accessor.ts +105 -17
  128. package/src/style-expression.ts +80 -3
  129. package/src/style-resolver.ts +200 -22
  130. package/src/terrain-query.ts +86 -0
  131. package/src/text-layout.ts +2 -3
  132. package/src/zoom-load-gate.ts +57 -0
  133. package/src/zoom-paint-extension.ts +245 -47
  134. package/dist/types/arabic-shaping.d.ts +0 -7
  135. package/dist/types/bidi.d.ts +0 -8
  136. package/dist/types/polylabel.d.ts +0 -17
  137. package/src/arabic-shaping.ts +0 -366
  138. package/src/bidi.ts +0 -199
  139. package/src/polylabel.ts +0 -312
@@ -0,0 +1,276 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {RangeResponse, Source} from 'pmtiles';
6
+ import {bytesToHeader, Compression, PMTiles, TileType} from 'pmtiles';
7
+ import {transformBasemapRequest} from './basemap-request';
8
+ import type {BasemapLoadOptions, BasemapSource} from './style-resolver';
9
+
10
+ /** The URL prefix of a PMTiles archive, as in the `pmtiles` protocol of MapLibre GL JS. */
11
+ export const PMTILES_PROTOCOL = 'pmtiles://';
12
+
13
+ /** The tile type that each source type draws, by PMTiles tile type. */
14
+ const TILE_TYPES: Record<number, {sourceTypes: string[]; mimeType: string; name: string}> = {
15
+ [TileType.Mvt]: {
16
+ sourceTypes: ['vector'],
17
+ mimeType: 'application/vnd.mapbox-vector-tile',
18
+ name: 'MVT'
19
+ },
20
+ [TileType.Png]: {sourceTypes: ['raster', 'raster-dem'], mimeType: 'image/png', name: 'PNG'},
21
+ [TileType.Jpeg]: {sourceTypes: ['raster', 'raster-dem'], mimeType: 'image/jpeg', name: 'JPEG'},
22
+ [TileType.Webp]: {sourceTypes: ['raster', 'raster-dem'], mimeType: 'image/webp', name: 'WebP'},
23
+ [TileType.Avif]: {sourceTypes: ['raster', 'raster-dem'], mimeType: 'image/avif', name: 'AVIF'}
24
+ };
25
+
26
+ /** Tile and directory compressions that the archive reader decompresses. */
27
+ const SUPPORTED_COMPRESSIONS = new Set([Compression.None, Compression.Gzip]);
28
+
29
+ /** The archive URL and tile index of a tile URL expanded from a PMTiles tile template. */
30
+ const TILE_URL = /^pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)$/;
31
+
32
+ /** Whether `url` names a PMTiles archive (`pmtiles://<archive URL>`). */
33
+ export function isPMTilesUrl(url: unknown): url is string {
34
+ return typeof url === 'string' && url.startsWith(PMTILES_PROTOCOL);
35
+ }
36
+
37
+ /** The tile template of an archive: `pmtiles://<archive URL>/{z}/{x}/{y}`. */
38
+ export function getPMTilesTileTemplate(archiveUrl: string): string {
39
+ return `${PMTILES_PROTOCOL}${archiveUrl}/{z}/{x}/{y}`;
40
+ }
41
+
42
+ /** The archive URL and tile index of a tile URL, or null for another URL. */
43
+ export function parsePMTilesTileUrl(
44
+ url: string
45
+ ): {archiveUrl: string; z: number; x: number; y: number} | null {
46
+ const match = TILE_URL.exec(url);
47
+ return match
48
+ ? {archiveUrl: match[1], z: Number(match[2]), x: Number(match[3]), y: Number(match[4])}
49
+ : null;
50
+ }
51
+
52
+ /**
53
+ * Reads byte ranges of an archive with HTTP range requests, through the `fetch` and `fetchOptions`
54
+ * of the load options.
55
+ */
56
+ class FetchRangeSource implements Source {
57
+ private tileDataOffset = Infinity;
58
+ private tileDataEnd = Infinity;
59
+ constructor(
60
+ private readonly url: string,
61
+ private readonly loadOptions: BasemapLoadOptions | undefined
62
+ ) {}
63
+
64
+ getKey(): string {
65
+ return this.url;
66
+ }
67
+
68
+ async getBytes(offset: number, length: number, signal?: AbortSignal): Promise<RangeResponse> {
69
+ let response = await this.fetchRange(offset, offset + length - 1, signal);
70
+ // An archive shorter than the first read, which is 16 KiB: some servers refuse the range.
71
+ if (offset === 0 && response.status === 416) {
72
+ const size = Number(response.headers.get('Content-Range')?.match(/^bytes \*\/(\d+)$/)?.[1]);
73
+ await response.body?.cancel();
74
+ if (!size) {
75
+ throw new Error(`PMTiles archive ${this.url}: no size in the 416 response`);
76
+ }
77
+ response = await this.fetchRange(0, size - 1, signal);
78
+ }
79
+ if (!response.ok) {
80
+ await response.body?.cancel();
81
+ throw new Error(`Failed to load PMTiles archive: ${this.url} (${response.status})`);
82
+ }
83
+ const data = await this.readAtMost(response, length);
84
+ if (offset === 0 && data.byteLength >= 127) {
85
+ const header = bytesToHeader(data.slice(0, 127));
86
+ this.tileDataOffset = header.tileDataOffset;
87
+ this.tileDataEnd = header.tileDataOffset + (header.tileDataLength ?? 0);
88
+ }
89
+ return {data};
90
+ }
91
+
92
+ /**
93
+ * The body of a range response, which a server that ignores `Range` sends as the whole archive:
94
+ * a body longer than `length` bytes, by its `Content-Length` or as it streams in, is cancelled
95
+ * at once, not downloaded.
96
+ */
97
+ private async readAtMost(response: Response, length: number): Promise<ArrayBuffer> {
98
+ const tooLong = () =>
99
+ new Error(
100
+ `PMTiles archive ${this.url}: the server returned more bytes than requested. It must ` +
101
+ 'support HTTP range requests.'
102
+ );
103
+ if (Number(response.headers.get('Content-Length')) > length) {
104
+ await response.body?.cancel();
105
+ throw tooLong();
106
+ }
107
+ if (!response.body) {
108
+ return response.arrayBuffer();
109
+ }
110
+ const reader = response.body.getReader();
111
+ const chunks: Uint8Array[] = [];
112
+ let size = 0;
113
+ for (;;) {
114
+ const {done, value} = await reader.read();
115
+ if (done) {
116
+ break;
117
+ }
118
+ size += value.byteLength;
119
+ if (size > length) {
120
+ await reader.cancel();
121
+ throw tooLong();
122
+ }
123
+ chunks.push(value);
124
+ }
125
+ const data = new Uint8Array(size);
126
+ let offset = 0;
127
+ for (const chunk of chunks) {
128
+ data.set(chunk, offset);
129
+ offset += chunk.byteLength;
130
+ }
131
+ return data.buffer;
132
+ }
133
+
134
+ private fetchRange(first: number, last: number, signal?: AbortSignal): Promise<Response> {
135
+ const fetchOptions = this.loadOptions?.fetchOptions;
136
+ const headers = new Headers(fetchOptions?.headers);
137
+ headers.set('Range', `bytes=${first}-${last}`);
138
+ const fetchFn = this.loadOptions?.fetch || fetch;
139
+ const request = transformBasemapRequest(this.loadOptions?.transformRequest, this.url,
140
+ first >= this.tileDataOffset && first < this.tileDataEnd ? 'Tile' : 'Source', {...fetchOptions, headers, ...(signal ? {signal} : {})});
141
+ const requestHeaders = new Headers(request.init?.headers);
142
+ requestHeaders.set('Range', `bytes=${first}-${last}`);
143
+ return fetchFn(request.url, {...request.init, headers: requestHeaders});
144
+ }
145
+ }
146
+
147
+ /** Load options without a `fetch` or `fetchOptions` of their own share this key. */
148
+ const DEFAULT_KEY = {};
149
+
150
+ /**
151
+ * The most archive readers kept open per `fetch` and `fetchOptions`. Past it, the least recently
152
+ * used reader is released, with the header and directories it has read.
153
+ */
154
+ export const MAX_OPEN_ARCHIVES = 32;
155
+
156
+ /** Opened archives, by `fetch`, by `fetchOptions` and by archive URL, least recently used first. */
157
+ const archives = new WeakMap<object, WeakMap<object, WeakMap<object, Map<string, PMTiles>>>>();
158
+
159
+ /**
160
+ * The reader of an archive, opened once per archive URL, `fetch` and `fetchOptions`: it keeps the
161
+ * header and directories it has read, while it is one of the `MAX_OPEN_ARCHIVES` most recently
162
+ * used.
163
+ */
164
+ function getArchive(url: string, loadOptions: BasemapLoadOptions | undefined): PMTiles {
165
+ const fetchKey = loadOptions?.fetch || DEFAULT_KEY;
166
+ const fetchOptionsKey = loadOptions?.fetchOptions || DEFAULT_KEY;
167
+ let byFetchOptions = archives.get(fetchKey);
168
+ if (!byFetchOptions) {
169
+ byFetchOptions = new WeakMap();
170
+ archives.set(fetchKey, byFetchOptions);
171
+ }
172
+ let byTransform = byFetchOptions.get(fetchOptionsKey);
173
+ if (!byTransform) {
174
+ byTransform = new WeakMap();
175
+ byFetchOptions.set(fetchOptionsKey, byTransform);
176
+ }
177
+ const transformKey = loadOptions?.transformRequest || DEFAULT_KEY;
178
+ let byUrl = byTransform.get(transformKey);
179
+ if (!byUrl) {
180
+ byUrl = new Map();
181
+ byTransform.set(transformKey, byUrl);
182
+ }
183
+ let archive = byUrl.get(url);
184
+ if (archive) {
185
+ byUrl.delete(url);
186
+ } else {
187
+ archive = new PMTiles(new FetchRangeSource(url, loadOptions));
188
+ if (byUrl.size >= MAX_OPEN_ARCHIVES) {
189
+ const [leastRecentlyUsed] = byUrl.keys();
190
+ byUrl.delete(leastRecentlyUsed);
191
+ }
192
+ }
193
+ byUrl.set(url, archive);
194
+ return archive;
195
+ }
196
+
197
+ /**
198
+ * The source fields of an archive, read from its header, as MapLibre GL JS's `pmtiles` protocol
199
+ * makes them: a tile template, `minzoom`, `maxzoom` and `bounds`. Throws if the archive cannot be
200
+ * read, or if its tiles are not of a type that a `sourceType` source draws, or are compressed with
201
+ * a method other than gzip.
202
+ */
203
+ export async function getPMTilesSourceFields(
204
+ archiveUrl: string,
205
+ sourceType: string,
206
+ loadOptions?: BasemapLoadOptions
207
+ ): Promise<Partial<BasemapSource>> {
208
+ const header = await getArchive(archiveUrl, loadOptions).getHeader();
209
+ const tileType = TILE_TYPES[header.tileType];
210
+ if (!tileType?.sourceTypes.includes(sourceType)) {
211
+ throw new Error(
212
+ `PMTiles archive ${archiveUrl} holds ${tileType?.name ?? 'unknown'} tiles, which a ` +
213
+ `${sourceType} source cannot draw`
214
+ );
215
+ }
216
+ for (const compression of [header.tileCompression, header.internalCompression]) {
217
+ if (!SUPPORTED_COMPRESSIONS.has(compression)) {
218
+ throw new Error(
219
+ `PMTiles archive ${archiveUrl}: compression ${Compression[compression]} is not supported`
220
+ );
221
+ }
222
+ }
223
+ return {
224
+ tiles: [getPMTilesTileTemplate(archiveUrl)],
225
+ minzoom: header.minZoom,
226
+ maxzoom: header.maxZoom,
227
+ bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat]
228
+ };
229
+ }
230
+
231
+ /**
232
+ * A `fetch` that answers the URLs of PMTiles tile templates with the tile, read from its archive
233
+ * with range requests through the `fetch` and `fetchOptions` of `loadOptions`, and passes every
234
+ * other URL to that `fetch`. A tile the archive does not hold is an empty response (status 204).
235
+ */
236
+ export function createPMTilesFetch(loadOptions: BasemapLoadOptions | undefined): typeof fetch {
237
+ return async (input, init) => {
238
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
239
+ const tile = parsePMTilesTileUrl(url);
240
+ if (!tile) {
241
+ return (loadOptions?.fetch || fetch)(input, init);
242
+ }
243
+ const archive = getArchive(tile.archiveUrl, loadOptions);
244
+ const header = await archive.getHeader();
245
+ const response = await archive.getZxy(tile.z, tile.x, tile.y, init?.signal ?? undefined);
246
+ if (!response) {
247
+ return new Response(null, {status: 204});
248
+ }
249
+ const mimeType = TILE_TYPES[header.tileType]?.mimeType || 'application/octet-stream';
250
+ return new Response(response.data, {headers: {'Content-Type': mimeType}});
251
+ };
252
+ }
253
+
254
+ /** Load options with the PMTiles `fetch`, by the load options they extend. */
255
+ const pmtilesLoadOptions = new WeakMap<object, NonNullable<BasemapLoadOptions>>();
256
+
257
+ /**
258
+ * The load options that a source's tiles load with: for a source whose tiles are in a PMTiles
259
+ * archive, `loadOptions` with a `fetch` that reads them (see `createPMTilesFetch`), the same object
260
+ * for the same `loadOptions`; for every other source, `loadOptions` as they are.
261
+ */
262
+ export function getTileLoadOptions<LoadOptionsT extends BasemapLoadOptions | undefined>(
263
+ source: BasemapSource,
264
+ loadOptions: LoadOptionsT
265
+ ): LoadOptionsT {
266
+ if (!source.tiles?.some(isPMTilesUrl)) {
267
+ return loadOptions;
268
+ }
269
+ const key = loadOptions || DEFAULT_KEY;
270
+ let options = pmtilesLoadOptions.get(key);
271
+ if (!options) {
272
+ options = {...loadOptions, fetch: createPMTilesFetch(loadOptions)};
273
+ pmtilesLoadOptions.set(key, options);
274
+ }
275
+ return options as LoadOptionsT;
276
+ }
@@ -0,0 +1,202 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {
6
+ CompositeLayer,
7
+ FirstPersonViewport,
8
+ type Color,
9
+ type DefaultProps,
10
+ type UpdateParameters,
11
+ type Viewport
12
+ } from '@deck.gl/core';
13
+ import {SolidPolygonLayer} from '@deck.gl/layers';
14
+ import {MAX_MERCATOR_LATITUDE, getStyleZoom} from './projected-viewport';
15
+
16
+ /** How many times the longer side of the screen the background reaches from the view center. */
17
+ const BACKGROUND_REACH = 4;
18
+ /** The reach in a pitched view, which shows the ground up to its horizon. */
19
+ const PITCHED_BACKGROUND_REACH = 64;
20
+ /** The share of the reach by which the view may move before the background is made again. */
21
+ const BACKGROUND_SLACK = 0.5;
22
+ /** WGS84 equatorial radius, in meters. */
23
+ const EARTH_RADIUS = 6_378_137;
24
+
25
+ /** A square in the units of a view's coordinate reference system. */
26
+ export type BackgroundSquare = {
27
+ /** The center of the square. */
28
+ center: [number, number];
29
+ /** Half the side of the square. */
30
+ reach: number;
31
+ /** The reach that the view the square was made for needs. */
32
+ viewReach: number;
33
+ };
34
+
35
+ /** What `getBackgroundSquare` reads of a projected viewport. */
36
+ type BackgroundViewport = Pick<Viewport, 'width' | 'height' | 'scale' | 'center'> & {
37
+ pitch?: number;
38
+ unprojectFlat: (common: number[]) => number[];
39
+ };
40
+
41
+ /** Identify a geospatial first-person camera across copies of deck.gl. */
42
+ export function isGeographicFirstPersonViewport(viewport: unknown): viewport is FirstPersonViewport {
43
+ const candidate = viewport as FirstPersonViewport | undefined;
44
+ return (
45
+ candidate?.isGeospatial === true &&
46
+ (candidate.constructor as typeof FirstPersonViewport).displayName === FirstPersonViewport.displayName
47
+ );
48
+ }
49
+
50
+ /**
51
+ * A square around the view center. Keep it while the view stays well inside it at a similar
52
+ * scale. A world-sized polygon can lose coverage when clipped against a first-person frustum
53
+ * or rendered at high zoom in a projected view.
54
+ */
55
+ export function getBackgroundSquare(
56
+ viewport: BackgroundViewport,
57
+ previous?: BackgroundSquare | null
58
+ ): BackgroundSquare | null {
59
+ const [x, y] = viewport.unprojectFlat([viewport.center[0], viewport.center[1]]);
60
+ // The units of the coordinate reference system per pixel.
61
+ const origin = viewport.unprojectFlat([0, 0]);
62
+ const unit = viewport.unprojectFlat([1 / viewport.scale, 0]);
63
+ const unitsPerPixel = Math.abs(unit[0] - origin[0]);
64
+ const screen = Math.max(viewport.width, viewport.height) * unitsPerPixel;
65
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !(screen > 0) || !Number.isFinite(screen)) {
66
+ return previous ?? null;
67
+ }
68
+ let viewReach = screen * (viewport.pitch ? PITCHED_BACKGROUND_REACH : BACKGROUND_REACH);
69
+ if (isGeographicFirstPersonViewport(viewport)) {
70
+ // Cover the frustum up to the ground horizon, even when the far plane extends beyond it.
71
+ const {width, height} = viewport;
72
+ const altitude = Math.max(0, viewport.cameraPosition[2] / viewport.distanceScales.unitsPerMeter[2]);
73
+ const horizon = Math.acos(EARTH_RADIUS / (EARTH_RADIUS + altitude));
74
+ const latitudeRadians = (y * Math.PI) / 180;
75
+ const latitudeReach = (horizon * 180) / Math.PI;
76
+ const longitudeReach = horizon >= Math.PI / 2 - Math.abs(latitudeRadians)
77
+ ? 180
78
+ : (Math.asin(Math.sin(horizon) / Math.cos(latitudeRadians)) * 180) / Math.PI;
79
+ const farCorners = [[0, 0], [width, 0], [width, height], [0, height]];
80
+ const farReach = Math.max(...farCorners.map(([column, row]) => {
81
+ const [longitude, latitude] = viewport.unproject([column, row, 1]);
82
+ const delta = longitude - x;
83
+ const wrappedDelta = delta - 360 * Math.round(delta / 360);
84
+ return Math.max(
85
+ Math.min(Math.abs(wrappedDelta), longitudeReach),
86
+ Math.min(Math.abs(latitude - y), latitudeReach)
87
+ );
88
+ }));
89
+ if (Number.isFinite(farReach)) {
90
+ viewReach = Math.max(screen * BACKGROUND_REACH, farReach);
91
+ }
92
+ }
93
+ if (
94
+ previous &&
95
+ previous.viewReach >= viewReach / 2 &&
96
+ previous.viewReach <= viewReach * 2
97
+ ) {
98
+ const slack = Math.min(previous.reach * BACKGROUND_SLACK, previous.reach - viewReach);
99
+ if (Math.abs(x - previous.center[0]) <= slack && Math.abs(y - previous.center[1]) <= slack) {
100
+ return previous;
101
+ }
102
+ }
103
+ // Twice the reach of the view: the square also covers the view at half the scale.
104
+ return {center: [x, y], reach: viewReach * 2, viewReach};
105
+ }
106
+
107
+ /** Props of {@link ProjectedBackgroundLayer}. */
108
+ export type ProjectedBackgroundLayerProps = {
109
+ /** The fill color, `[r, g, b, a]`. */
110
+ getFillColor?: Color;
111
+ /**
112
+ * Whether the view is a Web Mercator map rather than a projected view: the square is then in
113
+ * longitude and latitude, cut at the latitudes of the Web Mercator world. A patterned background
114
+ * of a map draws such a square rather than the whole world, which leaves too little precision to
115
+ * place the pattern at high zoom.
116
+ */
117
+ geographic?: boolean;
118
+ /**
119
+ * `FillPatternExtension`'s pattern scale, in Web Mercator common units per image pixel. In a
120
+ * projected view the layer converts it to the view's common units, so that the pattern has the
121
+ * size it has on the Web Mercator map of the same scale.
122
+ */
123
+ getFillPatternScale?: number;
124
+ };
125
+
126
+ /**
127
+ * A background sized around a projected or first-person view. A geographic first-person view
128
+ * and a patterned Web Mercator background draw the square in longitude and latitude instead
129
+ * of projected coordinates (see `geographic`).
130
+ */
131
+ export class ProjectedBackgroundLayer extends CompositeLayer<ProjectedBackgroundLayerProps> {
132
+ static layerName = 'ProjectedBackgroundLayer';
133
+ static defaultProps: DefaultProps<ProjectedBackgroundLayerProps> = {
134
+ getFillColor: {type: 'color', value: [0, 0, 0, 255]},
135
+ geographic: false
136
+ };
137
+
138
+ declare state: {
139
+ square: BackgroundSquare | null;
140
+ polygons: number[][][];
141
+ /** The view's common units per Web Mercator common unit, where the square was made. */
142
+ commonScale: number;
143
+ };
144
+
145
+ initializeState(): void {
146
+ this.state = {square: null, polygons: [], commonScale: 1};
147
+ }
148
+
149
+ /** Also when the view leaves the square the background fills. */
150
+ shouldUpdateState(params: UpdateParameters<this>): boolean {
151
+ if (super.shouldUpdateState(params)) {
152
+ return true;
153
+ }
154
+ return (
155
+ params.changeFlags.viewportChanged &&
156
+ getBackgroundSquare(params.context.viewport, this.state.square) !== this.state.square
157
+ );
158
+ }
159
+
160
+ updateState(): void {
161
+ const square = getBackgroundSquare(this.context.viewport, this.state.square);
162
+ if (square !== this.state.square) {
163
+ const [x, y] = square?.center ?? [0, 0];
164
+ const reach = square?.reach ?? 0;
165
+ const limit = this.props.geographic ? MAX_MERCATOR_LATITUDE : Infinity;
166
+ const bottom = Math.max(y - reach, -limit);
167
+ const top = Math.min(y + reach, limit);
168
+ const polygons = square
169
+ ? [
170
+ [
171
+ [x - reach, bottom],
172
+ [x + reach, bottom],
173
+ [x + reach, top],
174
+ [x - reach, top]
175
+ ]
176
+ ]
177
+ : [];
178
+ // 1 in a Web Mercator view. It changes slowly across a view, so it is kept with the square.
179
+ const {viewport} = this.context;
180
+ const commonScale = 2 ** getStyleZoom(viewport) / viewport.scale;
181
+ this.setState({square, polygons, commonScale});
182
+ }
183
+ }
184
+
185
+ renderLayers() {
186
+ const {getFillPatternScale} = this.props;
187
+ const props = this.getSubLayerProps({
188
+ id: 'fill',
189
+ data: this.state.polygons,
190
+ // The units of the view's coordinate reference system, or longitude and latitude.
191
+ coordinateSystem: this.props.geographic ? 'lnglat' : 'cartesian',
192
+ getPolygon: (polygon: number[][]) => polygon,
193
+ getFillColor: this.props.getFillColor,
194
+ updateTriggers: {getFillColor: this.props.getFillColor}
195
+ });
196
+ // After the extension's props, which pass the scale through unchanged.
197
+ if (getFillPatternScale !== undefined) {
198
+ props.getFillPatternScale = getFillPatternScale * this.state.commonScale;
199
+ }
200
+ return new SolidPolygonLayer(props);
201
+ }
202
+ }