@deck.gl/geo-layers 8.8.4 → 8.8.7

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.
@@ -1,399 +0,0 @@
1
- import Tile2DHeader from './tile-2d-header';
2
- import { getTileIndices, tileToBoundingBox } from './utils';
3
- import { RequestScheduler } from '@loaders.gl/loader-utils';
4
- import { Matrix4 } from '@math.gl/core';
5
- // bit masks
6
- const TILE_STATE_VISITED = 1;
7
- const TILE_STATE_VISIBLE = 2;
8
- /*
9
- show cached parent tile if children are loading
10
- +-----------+ +-----+ +-----+-----+
11
- | | | | | | |
12
- | | | | | | |
13
- | | --> +-----+-----+ -> +-----+-----+
14
- | | | | | | |
15
- | | | | | | |
16
- +-----------+ +-----+ +-----+-----+
17
-
18
- show cached children tiles when parent is loading
19
- +-------+---- +------------
20
- | | |
21
- | | |
22
- | | |
23
- +-------+---- --> |
24
- | | |
25
- */
26
- export const STRATEGY_NEVER = 'never';
27
- export const STRATEGY_REPLACE = 'no-overlap';
28
- export const STRATEGY_DEFAULT = 'best-available';
29
- const DEFAULT_CACHE_SCALE = 5;
30
- const STRATEGIES = {
31
- [STRATEGY_DEFAULT]: updateTileStateDefault,
32
- [STRATEGY_REPLACE]: updateTileStateReplace,
33
- [STRATEGY_NEVER]: () => { }
34
- };
35
- /**
36
- * Manages loading and purging of tile data. This class caches recently visited tiles
37
- * and only creates new tiles if they are present.
38
- */
39
- export default class Tileset2D {
40
- /**
41
- * Takes in a function that returns tile data, a cache size, and a max and a min zoom level.
42
- * Cache size defaults to 5 * number of tiles in the current viewport
43
- */
44
- constructor(opts) {
45
- this.opts = opts;
46
- this.onTileLoad = tile => {
47
- this.opts.onTileLoad(tile);
48
- if (this.opts.maxCacheByteSize) {
49
- this._cacheByteSize += tile.byteLength;
50
- this._resizeCache();
51
- }
52
- };
53
- this._requestScheduler = new RequestScheduler({
54
- maxRequests: opts.maxRequests,
55
- throttleRequests: opts.maxRequests > 0
56
- });
57
- // Maps tile id in string {z}-{x}-{y} to a Tile object
58
- this._cache = new Map();
59
- this._tiles = [];
60
- this._dirty = false;
61
- this._cacheByteSize = 0;
62
- // Cache the last processed viewport
63
- this._viewport = null;
64
- this._selectedTiles = null;
65
- this._frameNumber = 0;
66
- this._modelMatrix = new Matrix4();
67
- this._modelMatrixInverse = new Matrix4();
68
- this.setOptions(opts);
69
- }
70
- /* Public API */
71
- get tiles() {
72
- return this._tiles;
73
- }
74
- get selectedTiles() {
75
- return this._selectedTiles;
76
- }
77
- get isLoaded() {
78
- return this._selectedTiles !== null && this._selectedTiles.every(tile => tile.isLoaded);
79
- }
80
- get needsReload() {
81
- return this._selectedTiles !== null && this._selectedTiles.some(tile => tile.needsReload);
82
- }
83
- setOptions(opts) {
84
- Object.assign(this.opts, opts);
85
- if (Number.isFinite(opts.maxZoom)) {
86
- this._maxZoom = Math.floor(opts.maxZoom);
87
- }
88
- if (Number.isFinite(opts.minZoom)) {
89
- this._minZoom = Math.ceil(opts.minZoom);
90
- }
91
- }
92
- // Clean up any outstanding tile requests.
93
- finalize() {
94
- for (const tile of this._cache.values()) {
95
- if (tile.isLoading) {
96
- tile.abort();
97
- }
98
- }
99
- this._cache.clear();
100
- this._tiles = [];
101
- this._selectedTiles = null;
102
- }
103
- reloadAll() {
104
- for (const id of this._cache.keys()) {
105
- const tile = this._cache.get(id);
106
- if (!this._selectedTiles || !this._selectedTiles.includes(tile)) {
107
- this._cache.delete(id);
108
- }
109
- else {
110
- tile.setNeedsReload();
111
- }
112
- }
113
- }
114
- /**
115
- * Update the cache with the given viewport and model matrix and triggers callback onUpdate.
116
- */
117
- update(viewport, { zRange, modelMatrix } = {}) {
118
- const modelMatrixAsMatrix4 = new Matrix4(modelMatrix);
119
- const isModelMatrixNew = !modelMatrixAsMatrix4.equals(this._modelMatrix);
120
- if (!this._viewport || !viewport.equals(this._viewport) || isModelMatrixNew) {
121
- if (isModelMatrixNew) {
122
- this._modelMatrixInverse = modelMatrixAsMatrix4.clone().invert();
123
- this._modelMatrix = modelMatrixAsMatrix4;
124
- }
125
- this._viewport = viewport;
126
- const tileIndices = this.getTileIndices({
127
- viewport,
128
- maxZoom: this._maxZoom,
129
- minZoom: this._minZoom,
130
- zRange,
131
- modelMatrix: this._modelMatrix,
132
- modelMatrixInverse: this._modelMatrixInverse
133
- });
134
- this._selectedTiles = tileIndices.map(index => this._getTile(index, true));
135
- if (this._dirty) {
136
- // Some new tiles are added
137
- this._rebuildTree();
138
- }
139
- // Check for needed reloads explicitly even if the view/matrix has not changed.
140
- }
141
- else if (this.needsReload) {
142
- this._selectedTiles = this._selectedTiles.map(tile => this._getTile(tile.index, true));
143
- }
144
- // Update tile states
145
- const changed = this.updateTileStates();
146
- this._pruneRequests();
147
- if (this._dirty) {
148
- // cache size is either the user defined maxSize or 5 * number of current tiles in the viewport.
149
- this._resizeCache();
150
- }
151
- if (changed) {
152
- this._frameNumber++;
153
- }
154
- return this._frameNumber;
155
- }
156
- /* Public interface for subclassing */
157
- /** Returns array of tile indices in the current viewport */
158
- getTileIndices({ viewport, maxZoom, minZoom, zRange, modelMatrix, modelMatrixInverse }) {
159
- const { tileSize, extent, zoomOffset } = this.opts;
160
- return getTileIndices({
161
- viewport,
162
- maxZoom,
163
- minZoom,
164
- zRange,
165
- tileSize,
166
- extent: extent,
167
- modelMatrix,
168
- modelMatrixInverse,
169
- zoomOffset
170
- });
171
- }
172
- /** Returns unique string key for a tile index */
173
- getTileId(index) {
174
- return `${index.x}-${index.y}-${index.z}`;
175
- }
176
- /** Returns a zoom level for a tile index */
177
- getTileZoom(index) {
178
- return index.z;
179
- }
180
- /** Returns additional metadata to add to tile, bbox by default */
181
- getTileMetadata(index) {
182
- const { tileSize } = this.opts;
183
- // @ts-expect-error
184
- return { bbox: tileToBoundingBox(this._viewport, index.x, index.y, index.z, tileSize) };
185
- }
186
- /** Returns index of the parent tile */
187
- getParentIndex(index) {
188
- const x = Math.floor(index.x / 2);
189
- const y = Math.floor(index.y / 2);
190
- const z = index.z - 1;
191
- return { x, y, z };
192
- }
193
- // Returns true if any tile's visibility changed
194
- updateTileStates() {
195
- const refinementStrategy = this.opts.refinementStrategy || STRATEGY_DEFAULT;
196
- const visibilities = new Array(this._cache.size);
197
- let i = 0;
198
- // Reset state
199
- for (const tile of this._cache.values()) {
200
- // save previous state
201
- visibilities[i++] = tile.isVisible;
202
- tile.isSelected = false;
203
- tile.isVisible = false;
204
- }
205
- // @ts-expect-error called only when _selectedTiles is already defined
206
- for (const tile of this._selectedTiles) {
207
- tile.isSelected = true;
208
- tile.isVisible = true;
209
- }
210
- // Strategy-specific state logic
211
- (typeof refinementStrategy === 'function'
212
- ? refinementStrategy
213
- : STRATEGIES[refinementStrategy])(Array.from(this._cache.values()));
214
- i = 0;
215
- // Check if any visibility has changed
216
- for (const tile of this._cache.values()) {
217
- if (visibilities[i++] !== tile.isVisible) {
218
- return true;
219
- }
220
- }
221
- return false;
222
- }
223
- /* Private methods */
224
- _pruneRequests() {
225
- const { maxRequests } = this.opts;
226
- const abortCandidates = [];
227
- let ongoingRequestCount = 0;
228
- for (const tile of this._cache.values()) {
229
- // Keep track of all the ongoing requests
230
- if (tile.isLoading) {
231
- ongoingRequestCount++;
232
- if (!tile.isSelected && !tile.isVisible) {
233
- abortCandidates.push(tile);
234
- }
235
- }
236
- }
237
- while (maxRequests > 0 && ongoingRequestCount > maxRequests && abortCandidates.length > 0) {
238
- // There are too many ongoing requests, so abort some that are unselected
239
- const tile = abortCandidates.shift();
240
- tile.abort();
241
- ongoingRequestCount--;
242
- }
243
- }
244
- // This needs to be called every time some tiles have been added/removed from cache
245
- _rebuildTree() {
246
- const { _cache } = this;
247
- // Reset states
248
- for (const tile of _cache.values()) {
249
- tile.parent = null;
250
- if (tile.children) {
251
- tile.children.length = 0;
252
- }
253
- }
254
- // Rebuild tree
255
- for (const tile of _cache.values()) {
256
- const parent = this._getNearestAncestor(tile);
257
- tile.parent = parent;
258
- if (parent?.children) {
259
- parent.children.push(tile);
260
- }
261
- }
262
- }
263
- /**
264
- * Clear tiles that are not visible when the cache is full
265
- */
266
- /* eslint-disable complexity */
267
- _resizeCache() {
268
- const { _cache, opts } = this;
269
- const maxCacheSize = opts.maxCacheSize ||
270
- // @ts-expect-error called only when selectedTiles is initialized
271
- (opts.maxCacheByteSize ? Infinity : DEFAULT_CACHE_SCALE * this.selectedTiles.length);
272
- const maxCacheByteSize = opts.maxCacheByteSize || Infinity;
273
- const overflown = _cache.size > maxCacheSize || this._cacheByteSize > maxCacheByteSize;
274
- if (overflown) {
275
- for (const [id, tile] of _cache) {
276
- if (!tile.isVisible) {
277
- // delete tile
278
- this._cacheByteSize -= opts.maxCacheByteSize ? tile.byteLength : 0;
279
- _cache.delete(id);
280
- this.opts.onTileUnload(tile);
281
- }
282
- if (_cache.size <= maxCacheSize && this._cacheByteSize <= maxCacheByteSize) {
283
- break;
284
- }
285
- }
286
- this._rebuildTree();
287
- this._dirty = true;
288
- }
289
- if (this._dirty) {
290
- // sort by zoom level so that smaller tiles are displayed on top
291
- this._tiles = Array.from(this._cache.values()).sort((t1, t2) => t1.zoom - t2.zoom);
292
- this._dirty = false;
293
- }
294
- }
295
- _getTile(index, create) {
296
- const id = this.getTileId(index);
297
- let tile = this._cache.get(id);
298
- let needsReload = false;
299
- if (!tile && create) {
300
- tile = new Tile2DHeader(index);
301
- Object.assign(tile, this.getTileMetadata(tile.index));
302
- Object.assign(tile, { id, zoom: this.getTileZoom(tile.index) });
303
- needsReload = true;
304
- this._cache.set(id, tile);
305
- this._dirty = true;
306
- }
307
- else if (tile && tile.needsReload) {
308
- needsReload = true;
309
- }
310
- if (tile && needsReload) {
311
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
312
- tile.loadData({
313
- getData: this.opts.getTileData,
314
- requestScheduler: this._requestScheduler,
315
- onLoad: this.onTileLoad,
316
- onError: this.opts.onTileError
317
- });
318
- }
319
- return tile;
320
- }
321
- _getNearestAncestor(tile) {
322
- const { _minZoom = 0 } = this;
323
- let index = tile.index;
324
- while (this.getTileZoom(index) > _minZoom) {
325
- index = this.getParentIndex(index);
326
- const parent = this._getTile(index);
327
- if (parent) {
328
- return parent;
329
- }
330
- }
331
- return null;
332
- }
333
- }
334
- /* -- Refinement strategies --*/
335
- /* eslint-disable max-depth */
336
- // For all the selected && pending tiles:
337
- // - pick the closest ancestor as placeholder
338
- // - if no ancestor is visible, pick the closest children as placeholder
339
- function updateTileStateDefault(allTiles) {
340
- for (const tile of allTiles) {
341
- tile.state = 0;
342
- }
343
- for (const tile of allTiles) {
344
- if (tile.isSelected && !getPlaceholderInAncestors(tile)) {
345
- getPlaceholderInChildren(tile);
346
- }
347
- }
348
- for (const tile of allTiles) {
349
- tile.isVisible = Boolean(tile.state & TILE_STATE_VISIBLE);
350
- }
351
- }
352
- // Until a selected tile and all its selected siblings are loaded, use the closest ancestor as placeholder
353
- function updateTileStateReplace(allTiles) {
354
- for (const tile of allTiles) {
355
- tile.state = 0;
356
- }
357
- for (const tile of allTiles) {
358
- if (tile.isSelected) {
359
- getPlaceholderInAncestors(tile);
360
- }
361
- }
362
- // Always process parents first
363
- const sortedTiles = Array.from(allTiles).sort((t1, t2) => t1.zoom - t2.zoom);
364
- for (const tile of sortedTiles) {
365
- tile.isVisible = Boolean(tile.state & TILE_STATE_VISIBLE);
366
- if (tile.children && (tile.isVisible || tile.state & TILE_STATE_VISITED)) {
367
- // If the tile is rendered, or if the tile has been explicitly hidden, hide all of its children
368
- for (const child of tile.children) {
369
- child.state = TILE_STATE_VISITED;
370
- }
371
- }
372
- else if (tile.isSelected) {
373
- getPlaceholderInChildren(tile);
374
- }
375
- }
376
- }
377
- // Walk up the tree until we find one ancestor that is loaded. Returns true if successful.
378
- function getPlaceholderInAncestors(startTile) {
379
- let tile = startTile;
380
- while (tile) {
381
- if (tile.isLoaded || tile.content) {
382
- tile.state |= TILE_STATE_VISIBLE;
383
- return true;
384
- }
385
- tile = tile.parent;
386
- }
387
- return false;
388
- }
389
- // Recursively set children as placeholder
390
- function getPlaceholderInChildren(tile) {
391
- for (const child of tile.children) {
392
- if (child.isLoaded || child.content) {
393
- child.state |= TILE_STATE_VISIBLE;
394
- }
395
- else {
396
- getPlaceholderInChildren(child);
397
- }
398
- }
399
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,197 +0,0 @@
1
- import { getOSMTileIndices } from './tile-2d-traversal';
2
- const TILE_SIZE = 512;
3
- const DEFAULT_EXTENT = [-Infinity, -Infinity, Infinity, Infinity];
4
- export const urlType = {
5
- type: 'url',
6
- value: null,
7
- validate: (value, propType) => (propType.optional && value === null) ||
8
- typeof value === 'string' ||
9
- (Array.isArray(value) && value.every(url => typeof url === 'string')),
10
- equals: (value1, value2) => {
11
- if (value1 === value2) {
12
- return true;
13
- }
14
- if (!Array.isArray(value1) || !Array.isArray(value2)) {
15
- return false;
16
- }
17
- const len = value1.length;
18
- if (len !== value2.length) {
19
- return false;
20
- }
21
- for (let i = 0; i < len; i++) {
22
- if (value1[i] !== value2[i]) {
23
- return false;
24
- }
25
- }
26
- return true;
27
- }
28
- };
29
- function transformBox(bbox, modelMatrix) {
30
- const transformedCoords = [
31
- // top-left
32
- modelMatrix.transformAsPoint([bbox[0], bbox[1]]),
33
- // top-right
34
- modelMatrix.transformAsPoint([bbox[2], bbox[1]]),
35
- // bottom-left
36
- modelMatrix.transformAsPoint([bbox[0], bbox[3]]),
37
- // bottom-right
38
- modelMatrix.transformAsPoint([bbox[2], bbox[3]])
39
- ];
40
- const transformedBox = [
41
- // Minimum x coord
42
- Math.min(...transformedCoords.map(i => i[0])),
43
- // Minimum y coord
44
- Math.min(...transformedCoords.map(i => i[1])),
45
- // Max x coord
46
- Math.max(...transformedCoords.map(i => i[0])),
47
- // Max y coord
48
- Math.max(...transformedCoords.map(i => i[1]))
49
- ];
50
- return transformedBox;
51
- }
52
- function stringHash(s) {
53
- return Math.abs(s.split('').reduce((a, b) => ((a << 5) - a + b.charCodeAt(0)) | 0, 0));
54
- }
55
- export function getURLFromTemplate(template, tile) {
56
- if (!template || !template.length) {
57
- return null;
58
- }
59
- const { index, id } = tile;
60
- if (Array.isArray(template)) {
61
- const i = stringHash(id) % template.length;
62
- template = template[i];
63
- }
64
- let url = template;
65
- for (const key of Object.keys(index)) {
66
- const regex = new RegExp(`{${key}}`, 'g');
67
- url = url.replace(regex, String(index[key]));
68
- }
69
- // Back-compatible support for {-y}
70
- if (Number.isInteger(index.y) && Number.isInteger(index.z)) {
71
- url = url.replace(/\{-y\}/g, String(Math.pow(2, index.z) - index.y - 1));
72
- }
73
- return url;
74
- }
75
- /**
76
- * gets the bounding box of a viewport
77
- */
78
- function getBoundingBox(viewport, zRange, extent) {
79
- let bounds;
80
- if (zRange && zRange.length === 2) {
81
- const [minZ, maxZ] = zRange;
82
- const bounds0 = viewport.getBounds({ z: minZ });
83
- const bounds1 = viewport.getBounds({ z: maxZ });
84
- bounds = [
85
- Math.min(bounds0[0], bounds1[0]),
86
- Math.min(bounds0[1], bounds1[1]),
87
- Math.max(bounds0[2], bounds1[2]),
88
- Math.max(bounds0[3], bounds1[3])
89
- ];
90
- }
91
- else {
92
- bounds = viewport.getBounds();
93
- }
94
- if (!viewport.isGeospatial) {
95
- return [
96
- // Top corner should not be more then bottom corner in either direction
97
- Math.max(Math.min(bounds[0], extent[2]), extent[0]),
98
- Math.max(Math.min(bounds[1], extent[3]), extent[1]),
99
- // Bottom corner should not be less then top corner in either direction
100
- Math.min(Math.max(bounds[2], extent[0]), extent[2]),
101
- Math.min(Math.max(bounds[3], extent[1]), extent[3])
102
- ];
103
- }
104
- return [
105
- Math.max(bounds[0], extent[0]),
106
- Math.max(bounds[1], extent[1]),
107
- Math.min(bounds[2], extent[2]),
108
- Math.min(bounds[3], extent[3])
109
- ];
110
- }
111
- function getIndexingCoords(bbox, scale, modelMatrixInverse) {
112
- if (modelMatrixInverse) {
113
- const transformedTileIndex = transformBox(bbox, modelMatrixInverse).map(i => (i * scale) / TILE_SIZE);
114
- return transformedTileIndex;
115
- }
116
- return bbox.map(i => (i * scale) / TILE_SIZE);
117
- }
118
- function getScale(z, tileSize) {
119
- return (Math.pow(2, z) * TILE_SIZE) / tileSize;
120
- }
121
- // https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
122
- export function osmTile2lngLat(x, y, z) {
123
- const scale = getScale(z, TILE_SIZE);
124
- const lng = (x / scale) * 360 - 180;
125
- const n = Math.PI - (2 * Math.PI * y) / scale;
126
- const lat = (180 / Math.PI) * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
127
- return [lng, lat];
128
- }
129
- function tile2XY(x, y, z, tileSize) {
130
- const scale = getScale(z, tileSize);
131
- return [(x / scale) * TILE_SIZE, (y / scale) * TILE_SIZE];
132
- }
133
- export function tileToBoundingBox(viewport, x, y, z, tileSize = TILE_SIZE) {
134
- if (viewport.isGeospatial) {
135
- const [west, north] = osmTile2lngLat(x, y, z);
136
- const [east, south] = osmTile2lngLat(x + 1, y + 1, z);
137
- return { west, north, east, south };
138
- }
139
- const [left, top] = tile2XY(x, y, z, tileSize);
140
- const [right, bottom] = tile2XY(x + 1, y + 1, z, tileSize);
141
- return { left, top, right, bottom };
142
- }
143
- function getIdentityTileIndices(viewport, z, tileSize, extent, modelMatrixInverse) {
144
- const bbox = getBoundingBox(viewport, null, extent);
145
- const scale = getScale(z, tileSize);
146
- const [minX, minY, maxX, maxY] = getIndexingCoords(bbox, scale, modelMatrixInverse);
147
- const indices = [];
148
- /*
149
- | TILE | TILE | TILE |
150
- |(minX) |(maxX)
151
- */
152
- for (let x = Math.floor(minX); x < maxX; x++) {
153
- for (let y = Math.floor(minY); y < maxY; y++) {
154
- indices.push({ x, y, z });
155
- }
156
- }
157
- return indices;
158
- }
159
- /**
160
- * Returns all tile indices in the current viewport. If the current zoom level is smaller
161
- * than minZoom, return an empty array. If the current zoom level is greater than maxZoom,
162
- * return tiles that are on maxZoom.
163
- */
164
- // eslint-disable-next-line complexity
165
- export function getTileIndices({ viewport, maxZoom, minZoom, zRange, extent, tileSize = TILE_SIZE, modelMatrix, modelMatrixInverse, zoomOffset = 0 }) {
166
- let z = viewport.isGeospatial
167
- ? Math.round(viewport.zoom + Math.log2(TILE_SIZE / tileSize)) + zoomOffset
168
- : Math.ceil(viewport.zoom) + zoomOffset;
169
- if (typeof minZoom === 'number' && Number.isFinite(minZoom) && z < minZoom) {
170
- if (!extent) {
171
- return [];
172
- }
173
- z = minZoom;
174
- }
175
- if (typeof maxZoom === 'number' && Number.isFinite(maxZoom) && z > maxZoom) {
176
- z = maxZoom;
177
- }
178
- let transformedExtent = extent;
179
- if (modelMatrix && modelMatrixInverse && extent && !viewport.isGeospatial) {
180
- transformedExtent = transformBox(extent, modelMatrix);
181
- }
182
- return viewport.isGeospatial
183
- ? getOSMTileIndices(viewport, z, zRange, extent)
184
- : getIdentityTileIndices(viewport, z, tileSize, transformedExtent || DEFAULT_EXTENT, modelMatrixInverse);
185
- }
186
- /**
187
- * Returns true if s is a valid URL template
188
- */
189
- export function isURLTemplate(s) {
190
- return /(?=.*{z})(?=.*{x})(?=.*({y}|{-y}))/.test(s);
191
- }
192
- export function isGeoBoundingBox(v) {
193
- return (Number.isFinite(v.west) &&
194
- Number.isFinite(v.north) &&
195
- Number.isFinite(v.east) &&
196
- Number.isFinite(v.south));
197
- }
@@ -1,92 +0,0 @@
1
- // Copyright (c) 2015 - 2017 Uber Technologies, Inc.
2
- //
3
- // Permission is hereby granted, free of charge, to any person obtaining a copy
4
- // of this software and associated documentation files (the "Software"), to deal
5
- // in the Software without restriction, including without limitation the rights
6
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
- // copies of the Software, and to permit persons to whom the Software is
8
- // furnished to do so, subject to the following conditions:
9
- //
10
- // The above copyright notice and this permission notice shall be included in
11
- // all copies or substantial portions of the Software.
12
- //
13
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
- // THE SOFTWARE.
20
- import { PathLayer } from '@deck.gl/layers';
21
- const defaultProps = {
22
- fadeTrail: true,
23
- trailLength: { type: 'number', value: 120, min: 0 },
24
- currentTime: { type: 'number', value: 0, min: 0 },
25
- getTimestamps: { type: 'accessor', value: null }
26
- };
27
- export default class TripsLayer extends PathLayer {
28
- getShaders() {
29
- const shaders = super.getShaders();
30
- shaders.inject = {
31
- 'vs:#decl': `\
32
- uniform float trailLength;
33
- attribute float instanceTimestamps;
34
- attribute float instanceNextTimestamps;
35
- varying float vTime;
36
- `,
37
- // Timestamp of the vertex
38
- 'vs:#main-end': `\
39
- vTime = instanceTimestamps + (instanceNextTimestamps - instanceTimestamps) * vPathPosition.y / vPathLength;
40
- `,
41
- 'fs:#decl': `\
42
- uniform bool fadeTrail;
43
- uniform float trailLength;
44
- uniform float currentTime;
45
- varying float vTime;
46
- `,
47
- // Drop the segments outside of the time window
48
- 'fs:#main-start': `\
49
- if(vTime > currentTime || (fadeTrail && (vTime < currentTime - trailLength))) {
50
- discard;
51
- }
52
- `,
53
- // Fade the color (currentTime - 100%, end of trail - 0%)
54
- 'fs:DECKGL_FILTER_COLOR': `\
55
- if(fadeTrail) {
56
- color.a *= 1.0 - (currentTime - vTime) / trailLength;
57
- }
58
- `
59
- };
60
- return shaders;
61
- }
62
- initializeState() {
63
- super.initializeState();
64
- const attributeManager = this.getAttributeManager();
65
- attributeManager.addInstanced({
66
- timestamps: {
67
- size: 1,
68
- accessor: 'getTimestamps',
69
- shaderAttributes: {
70
- instanceTimestamps: {
71
- vertexOffset: 0
72
- },
73
- instanceNextTimestamps: {
74
- vertexOffset: 1
75
- }
76
- }
77
- }
78
- });
79
- }
80
- draw(params) {
81
- const { fadeTrail, trailLength, currentTime } = this.props;
82
- params.uniforms = {
83
- ...params.uniforms,
84
- fadeTrail,
85
- trailLength,
86
- currentTime
87
- };
88
- super.draw(params);
89
- }
90
- }
91
- TripsLayer.layerName = 'TripsLayer';
92
- TripsLayer.defaultProps = defaultProps;