-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
terrain.js
1514 lines (1346 loc) · 64.3 KB
/
terrain.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
import Point from '@mapbox/point-geometry';
import SourceCache from '../source/source_cache.js';
import {OverscaledTileID} from '../source/tile_id.js';
import Tile from '../source/tile.js';
import rasterBoundsAttributes from '../data/raster_bounds_attributes.js';
import {RasterBoundsArray, TriangleIndexArray, LineIndexArray} from '../data/array_types.js';
import SegmentVector from '../data/segment.js';
import Texture from '../render/texture.js';
import Program from '../render/program.js';
import {Uniform1i, Uniform1f, Uniform2f, Uniform4f, UniformMatrix4f} from '../render/uniform_binding.js';
import {prepareDEMTexture} from '../render/draw_hillshade.js';
import EXTENT from '../data/extent.js';
import {clamp, warnOnce} from '../util/util.js';
import assert from 'assert';
import {vec3, mat4, vec4} from 'gl-matrix';
import getWorkerPool from '../util/global_worker_pool.js';
import Dispatcher from '../util/dispatcher.js';
import GeoJSONSource from '../source/geojson_source.js';
import ImageSource from '../source/image_source.js';
import RasterDEMTileSource from '../source/raster_dem_tile_source.js';
import RasterTileSource from '../source/raster_tile_source.js';
import Color from '../style-spec/util/color.js';
import StencilMode from '../gl/stencil_mode.js';
import {DepthStencilAttachment} from '../gl/value.js';
import {drawTerrainRaster, drawTerrainDepth} from './draw_terrain_raster.js';
import type RasterStyleLayer from '../style/style_layer/raster_style_layer.js';
import {Elevation} from './elevation.js';
import Framebuffer from '../gl/framebuffer.js';
import ColorMode from '../gl/color_mode.js';
import DepthMode from '../gl/depth_mode.js';
import CullFaceMode from '../gl/cull_face_mode.js';
import {clippingMaskUniformValues} from '../render/program/clipping_mask_program.js';
import MercatorCoordinate, {mercatorZfromAltitude} from '../geo/mercator_coordinate.js';
import browser from '../util/browser.js';
import DEMData from '../data/dem_data.js';
import rasterFade from '../render/raster_fade.js';
import {create as createSource} from '../source/source.js';
import type Map from '../ui/map.js';
import type Painter from '../render/painter.js';
import type Style from '../style/style.js';
import type StyleLayer from '../style/style_layer.js';
import type VertexBuffer from '../gl/vertex_buffer.js';
import type IndexBuffer from '../gl/index_buffer.js';
import type Context from '../gl/context.js';
import type {UniformLocations, UniformValues} from '../render/uniform_binding.js';
import type Transform from '../geo/transform.js';
import type {DEMEncoding} from '../data/dem_data.js';
export const GRID_DIM = 128;
const FBO_POOL_SIZE = 5;
const RENDER_CACHE_MAX_SIZE = 50;
type RenderBatch = {
start: number;
end: number;
}
/**
* Proxy source cache gets ideal screen tile cover coordinates. All the other
* source caches's coordinates get mapped to subrects of proxy coordinates (or
* vice versa, subrects of larger tiles from all source caches get mapped to
* full proxy tile). This happens on every draw call in Terrain.updateTileBinding.
* Approach is used here for terrain : all the visible source tiles of all the
* source caches get rendered to proxy source cache textures and then draped over
* terrain. It is in future reusable for handling overscalling as buckets could be
* constructed only for proxy tile content, not for full overscalled vector tile.
*/
class ProxySourceCache extends SourceCache {
renderCache: Array<FBO>;
renderCachePool: Array<number>;
proxyCachedFBO: {[string | number]: {[string | number]: number}};
constructor(map: Map) {
const source = createSource('proxy', {
type: 'geojson',
maxzoom: map.transform.maxZoom
}, new Dispatcher(getWorkerPool(), null), map.style);
super('proxy', source, false);
source.setEventedParent(this);
// This source is not to be added as a map source: we use it's tile management.
// For that, initialize internal structures used for tile cover update.
this.map = ((this.getSource(): any): GeoJSONSource).map = map;
this.used = this._sourceLoaded = true;
this.renderCache = [];
this.renderCachePool = [];
this.proxyCachedFBO = {};
}
// Override for transient nature of cover here: don't cache and retain.
/* eslint-disable no-unused-vars */
update(transform: Transform, tileSize?: number, updateForTerrain?: boolean) {
if (transform.freezeTileCoverage) { return; }
this.transform = transform;
const idealTileIDs = transform.coveringTiles({
tileSize: this._source.tileSize,
minzoom: this._source.minzoom,
maxzoom: this._source.maxzoom,
roundZoom: this._source.roundZoom,
reparseOverscaled: this._source.reparseOverscaled,
useElevationData: true
});
const incoming: {[string]: string} = idealTileIDs.reduce((acc, tileID) => {
acc[tileID.key] = '';
if (!this._tiles[tileID.key]) {
const tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor(), transform.tileZoom);
tile.state = 'loaded';
this._tiles[tileID.key] = tile;
}
return acc;
}, {});
for (const id in this._tiles) {
if (!(id in incoming)) {
this.freeFBO(id);
this._tiles[id].state = 'unloaded';
delete this._tiles[id];
}
}
}
freeFBO(id: string) {
const fbos = this.proxyCachedFBO[id];
if (fbos !== undefined) {
const fboIds = ((Object.values(fbos): any): Array<number>);
this.renderCachePool.push(...fboIds);
delete this.proxyCachedFBO[id];
}
}
deallocRenderCache() {
this.renderCache.forEach(fbo => fbo.fb.destroy());
this.renderCache = [];
this.renderCachePool = [];
this.proxyCachedFBO = {};
}
}
/**
* Canonical, wrap and overscaledZ contain information of original source cache tile.
* This tile gets ortho-rendered to proxy tile (defined by proxyTileKey).
* posMatrix holds orthographic, scaling and translation information that is used
* for rendering original tile content to a proxy tile. Proxy tile covers whole
* or sub-rectangle of the original tile.
*/
class ProxiedTileID extends OverscaledTileID {
proxyTileKey: number;
constructor(tileID: OverscaledTileID, proxyTileKey: number, posMatrix: Float32Array) {
super(tileID.overscaledZ, tileID.wrap, tileID.canonical.z, tileID.canonical.x, tileID.canonical.y);
this.proxyTileKey = proxyTileKey;
this.posMatrix = posMatrix;
}
}
type OverlapStencilType = false | 'Clip' | 'Mask';
type FBO = {fb: Framebuffer, tex: Texture, dirty: boolean, ref: number};
export class Terrain extends Elevation {
terrainTileForTile: {[number | string]: Tile};
prevTerrainTileForTile: {[number | string]: Tile};
painter: Painter;
sourceCache: SourceCache;
gridBuffer: VertexBuffer;
gridIndexBuffer: IndexBuffer;
gridSegments: SegmentVector;
gridNoSkirtSegments: SegmentVector;
wireframeSegments: SegmentVector;
wireframeIndexBuffer: IndexBuffer;
proxiedCoords: {[string]: Array<ProxiedTileID>};
proxyCoords: Array<OverscaledTileID>;
proxyToSource: {[number]: {[string]: Array<ProxiedTileID>}};
proxySourceCache: ProxySourceCache;
renderingToTexture: boolean;
_style: Style;
orthoMatrix: mat4;
enabled: boolean;
renderCached: boolean;
forceRenderCached: boolean; // debugging purpose.
_visibleDemTiles: Array<Tile>;
_sourceTilesOverlap: {[string]: boolean};
_overlapStencilMode: StencilMode;
_overlapStencilType: OverlapStencilType;
_exaggeration: number;
_depthFBO: Framebuffer;
_depthTexture: Texture;
_previousZoom: number;
_updateTimestamp: number;
_useVertexMorphing: boolean;
pool: Array<FBO>;
currentFBO: FBO;
renderedToTile: boolean;
_drapedRenderBatches: Array<RenderBatch>;
_findCoveringTileCache: {[string]: {[number]: ?number}};
_tilesDirty: {[string]: {[number]: boolean}};
_invalidateRenderCache: boolean;
_emptyDEMTexture: ?Texture;
_initializing: ?boolean;
_emptyDEMTextureDirty: ?boolean;
constructor(painter: Painter, style: Style) {
super();
this.painter = painter;
this.terrainTileForTile = {};
this.prevTerrainTileForTile = {};
// Terrain rendering grid is 129x129 cell grid, made by 130x130 points.
// 130 vertices map to 128 DEM data + 1px padding on both sides.
// DEM texture is padded (1, 1, 1, 1) and padding pixels are backfilled
// by neighboring tile edges. This way we achieve tile stitching as
// edge vertices from neighboring tiles evaluate to the same 3D point.
const [triangleGridArray, triangleGridIndices, skirtIndicesOffset] = createGrid(GRID_DIM + 1);
const context = painter.context;
this.gridBuffer = context.createVertexBuffer(triangleGridArray, rasterBoundsAttributes.members);
this.gridIndexBuffer = context.createIndexBuffer(triangleGridIndices);
this.gridSegments = SegmentVector.simpleSegment(0, 0, triangleGridArray.length, triangleGridIndices.length);
this.gridNoSkirtSegments = SegmentVector.simpleSegment(0, 0, triangleGridArray.length, skirtIndicesOffset);
this.proxyCoords = [];
this.proxiedCoords = {};
this._visibleDemTiles = [];
this._drapedRenderBatches = [];
this._sourceTilesOverlap = {};
this.proxySourceCache = new ProxySourceCache(style.map);
this.orthoMatrix = mat4.create();
mat4.ortho(this.orthoMatrix, 0, EXTENT, 0, EXTENT, 0, 1);
const gl = context.gl;
this._overlapStencilMode = new StencilMode({func: gl.GEQUAL, mask: 0xFF}, 0, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);
this._previousZoom = painter.transform.zoom;
this.pool = [];
this._findCoveringTileCache = {};
this._tilesDirty = {};
this.style = style;
this._useVertexMorphing = true;
this._exaggeration = 1;
}
set style(style: Style) {
style.on('data', this._onStyleDataEvent.bind(this));
style.on('neworder', this._checkRenderCacheEfficiency.bind(this));
this._style = style;
this._checkRenderCacheEfficiency();
}
/*
* Validate terrain and update source cache used for elevation.
* Explicitly pass transform to update elevation (Transform.updateElevation)
* before using transform for source cache update.
* cameraChanging is true when camera is zooming, panning or orbiting.
*/
update(style: Style, transform: Transform, cameraChanging: boolean) {
if (style && style.terrain) {
if (this._style !== style) {
this.style = style;
}
this.enabled = true;
const terrainProps = style.terrain.properties;
this.sourceCache = ((style._getSourceCache(terrainProps.get('source')): any): SourceCache);
this._exaggeration = terrainProps.get('exaggeration');
const updateSourceCache = () => {
if (this.sourceCache.used) {
warnOnce(`Raster DEM source '${this.sourceCache.id}' is used both for terrain and as layer source.\n` +
'This leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.');
}
// Lower tile zoom is sufficient for terrain, given the size of terrain grid.
const demScale = this.sourceCache.getSource().tileSize / GRID_DIM;
const proxyTileSize = this.proxySourceCache.getSource().tileSize;
// Dem tile needs to be parent or at least of the same zoom level as proxy tile.
// Tile cover roundZoom behavior is set to the same as for proxy (false) in SourceCache.update().
this.sourceCache.update(transform, demScale * proxyTileSize, true);
// As a result of update, we get new set of tiles: reset lookup cache.
this._findCoveringTileCache[this.sourceCache.id] = {};
};
if (!this.sourceCache.usedForTerrain) {
// Init cache entry.
this._findCoveringTileCache[this.sourceCache.id] = {};
// When toggling terrain on/off load available terrain tiles from cache
// before reading elevation at center.
this.sourceCache.usedForTerrain = true;
updateSourceCache();
this._initializing = true;
}
updateSourceCache();
// Camera, when changing, gets constrained over terrain. Issue constrainCameraOverTerrain = true
// here to cover potential under terrain situation on data or style change.
transform.updateElevation(!cameraChanging);
// Reset tile lookup cache and update draped tiles coordinates.
this._findCoveringTileCache[this.proxySourceCache.id] = {};
this.proxySourceCache.update(transform);
this._emptyDEMTextureDirty = true;
} else {
this._disable();
}
}
_checkRenderCacheEfficiency() {
const renderCacheInfo = this.renderCacheEfficiency(this._style);
if (this._style.map._optimizeForTerrain) {
assert(renderCacheInfo.efficiency === 100);
} else if (renderCacheInfo.efficiency !== 100) {
warnOnce(`Terrain render cache efficiency is not optimal (${renderCacheInfo.efficiency}%) and performance
may be affected negatively, consider placing all background, fill and line layers before layer
with id '${renderCacheInfo.firstUndrapedLayer}' or create a map using optimizeForTerrain: true option.`);
}
}
_onStyleDataEvent(event: any) {
if (event.coord && event.dataType === 'source') {
this._clearRenderCacheForTile(event.sourceCacheId, event.coord);
} else if (event.dataType === 'style') {
this._invalidateRenderCache = true;
}
}
// Terrain
_disable() {
if (!this.enabled) return;
this.enabled = false;
this.proxySourceCache.deallocRenderCache();
if (this._style) {
for (const id in this._style._sourceCaches) {
this._style._sourceCaches[id].usedForTerrain = false;
}
}
}
destroy() {
this._disable();
if (this._emptyDEMTexture) this._emptyDEMTexture.destroy();
this.pool.forEach(fbo => fbo.fb.destroy());
this.pool = [];
if (this._depthFBO) {
this._depthFBO.destroy();
delete this._depthFBO;
delete this._depthTexture;
}
}
// Implements Elevation::_source.
_source(): ?SourceCache {
return this.enabled ? this.sourceCache : null;
}
// Implements Elevation::exaggeration.
exaggeration(): number {
return this._exaggeration;
}
get visibleDemTiles(): Array<Tile> {
return this._visibleDemTiles;
}
get drapeBufferSize(): [number, number] {
const extent = this.proxySourceCache.getSource().tileSize * 2; // *2 is to avoid upscaling bitmap on zoom.
return [extent, extent];
}
set useVertexMorphing(enable: boolean) {
this._useVertexMorphing = enable;
}
// For every renderable coordinate in every source cache, assign one proxy
// tile (see _setupProxiedCoordsForOrtho). Mapping of source tile to proxy
// tile is modeled by ProxiedTileID. In general case, source and proxy tile
// are of different zoom: ProxiedTileID.posMatrix models ortho, scale and
// translate from source to proxy. This matrix is used when rendering source
// tile to proxy tile's texture.
// One proxy tile can have multiple source tiles, or pieces of source tiles,
// that get rendered to it.
// For each proxy tile we assign one terrain tile (_assignTerrainTiles). The
// terrain tile provides elevation data when rendering (draping) proxy tile
// texture over terrain grid.
updateTileBinding(sourcesCoords: {[string]: Array<OverscaledTileID>}) {
if (!this.enabled) return;
this.prevTerrainTileForTile = this.terrainTileForTile;
const psc = this.proxySourceCache;
const tr = this.painter.transform;
if (this._initializing) {
// Don't activate terrain until center tile gets loaded.
this._initializing = tr._centerAltitude === 0 && this.getAtPoint(MercatorCoordinate.fromLngLat(tr.center), -1) === -1;
this._emptyDEMTextureDirty = !this._initializing;
}
const options = this.painter.options;
this.renderCached = (options.zooming || options.moving || options.rotating || !!this.forceRenderCached) && !this._invalidateRenderCache;
this._invalidateRenderCache = false;
const coords = this.proxyCoords = psc.getIds().map((id) => {
const tileID = psc.getTileByID(id).tileID;
tileID.posMatrix = tr.calculatePosMatrix(tileID.toUnwrapped());
return tileID;
});
sortByDistanceToCamera(coords, this.painter);
this._previousZoom = tr.zoom;
const previousProxyToSource = this.proxyToSource || {};
this.proxyToSource = {};
coords.forEach((tileID) => {
this.proxyToSource[tileID.key] = {};
});
this.terrainTileForTile = {};
const sourceCaches = this._style._sourceCaches;
for (const id in sourceCaches) {
const sourceCache = sourceCaches[id];
if (!sourceCache.used) continue;
if (sourceCache !== this.sourceCache) this._findCoveringTileCache[sourceCache.id] = {};
this._setupProxiedCoordsForOrtho(sourceCache, sourcesCoords[id], previousProxyToSource);
if (sourceCache.usedForTerrain) continue;
const coordinates = sourcesCoords[id];
if (sourceCache.getSource().reparseOverscaled) {
// Do this for layers that are not rasterized to proxy tile.
this._assignTerrainTiles(coordinates);
}
}
// Background has no source. Using proxy coords with 1-1 ortho (this.proxiedCoords[psc.id])
// when rendering background to proxy tiles.
this.proxiedCoords[psc.id] = coords.map(tileID => new ProxiedTileID(tileID, tileID.key, this.orthoMatrix));
this._assignTerrainTiles(coords);
this._prepareDEMTextures();
this._setupDrapedRenderBatches();
this._setupRenderCache(previousProxyToSource);
this.renderingToTexture = false;
this._initFBOPool();
this._updateTimestamp = browser.now();
// Gather all dem tiles that are assigned to proxy tiles
const visibleKeys = {};
this._visibleDemTiles = [];
for (const id of this.proxyCoords) {
const demTile = this.terrainTileForTile[id.key];
if (!demTile)
continue;
const key = demTile.tileID.key;
if (key in visibleKeys)
continue;
this._visibleDemTiles.push(demTile);
visibleKeys[key] = key;
}
}
_assignTerrainTiles(coords: Array<OverscaledTileID>) {
if (this._initializing) return;
coords.forEach((tileID) => {
if (this.terrainTileForTile[tileID.key]) return;
const demTile = this._findTileCoveringTileID(tileID, this.sourceCache);
if (demTile) this.terrainTileForTile[tileID.key] = demTile;
});
}
_prepareDEMTextures() {
const context = this.painter.context;
const gl = context.gl;
for (const key in this.terrainTileForTile) {
const tile = this.terrainTileForTile[key];
const dem = tile.dem;
if (dem && (!tile.demTexture || tile.needsDEMTextureUpload)) {
context.activeTexture.set(gl.TEXTURE1);
prepareDEMTexture(this.painter, tile, dem);
}
}
}
_prepareDemTileUniforms(proxyTile: Tile, demTile: ?Tile, uniforms: UniformValues<TerrainUniformsType>, uniformSuffix: ?string): boolean {
if (!demTile || demTile.demTexture == null)
return false;
assert(demTile.dem);
const proxyId = proxyTile.tileID.canonical;
const demId = demTile.tileID.canonical;
const demScaleBy = Math.pow(2, demId.z - proxyId.z);
const suffix = uniformSuffix || "";
uniforms[`u_dem_tl${suffix}`] = [proxyId.x * demScaleBy % 1, proxyId.y * demScaleBy % 1];
uniforms[`u_dem_scale${suffix}`] = demScaleBy;
return true;
}
get emptyDEMTexture(): Texture {
return !this._emptyDEMTextureDirty && this._emptyDEMTexture ?
this._emptyDEMTexture : this._updateEmptyDEMTexture();
}
_getLoadedAreaMinimum(): number {
let nonzero = 0;
const min = this._visibleDemTiles.reduce((acc, tile) => {
if (!tile.dem) return acc;
const m = tile.dem.tree.minimums[0];
acc += m;
if (m > 0) nonzero++;
return acc;
}, 0);
return nonzero ? min / nonzero : 0;
}
_updateEmptyDEMTexture(): Texture {
const context = this.painter.context;
const gl = context.gl;
context.activeTexture.set(gl.TEXTURE2);
const min = this._getLoadedAreaMinimum();
const image = {
width: 1, height: 1,
data: new Uint8Array(DEMData.pack(min, ((this.sourceCache.getSource(): any): RasterDEMTileSource).encoding))
};
this._emptyDEMTextureDirty = false;
let texture = this._emptyDEMTexture;
if (!texture) {
texture = this._emptyDEMTexture = new Texture(context, image, gl.RGBA, {premultiply: false});
} else {
texture.update(image, {premultiply: false});
}
return texture;
}
// useDepthForOcclusion: Pre-rendered depth to texture (this._depthTexture) is
// used to hide (actually moves all object's vertices out of viewport).
// useMeterToDem: u_meter_to_dem uniform is not used for all terrain programs,
// optimization to avoid unnecessary computation and upload.
setupElevationDraw(tile: Tile, program: Program<*>,
options?: {
useDepthForOcclusion?: boolean,
useMeterToDem?: boolean,
labelPlaneMatrixInv?: ?Float32Array,
morphing?: { srcDemTile: Tile, dstDemTile: Tile, phase: number }
}) {
const context = this.painter.context;
const gl = context.gl;
const uniforms = defaultTerrainUniforms(((this.sourceCache.getSource(): any): RasterDEMTileSource).encoding);
uniforms['u_dem_size'] = this.sourceCache.getSource().tileSize;
uniforms['u_exaggeration'] = this.exaggeration();
let demTile = null;
let prevDemTile = null;
let morphingPhase = 1.0;
if (options && options.morphing && this._useVertexMorphing) {
const srcTile = options.morphing.srcDemTile;
const dstTile = options.morphing.dstDemTile;
morphingPhase = options.morphing.phase;
if (srcTile && dstTile) {
if (this._prepareDemTileUniforms(tile, srcTile, uniforms, "_prev"))
prevDemTile = srcTile;
if (this._prepareDemTileUniforms(tile, dstTile, uniforms))
demTile = dstTile;
}
}
if (prevDemTile && demTile) {
// Both DEM textures are expected to be correctly set if geomorphing is enabled
context.activeTexture.set(gl.TEXTURE2);
(demTile.demTexture: any).bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);
context.activeTexture.set(gl.TEXTURE4);
(prevDemTile.demTexture: any).bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);
uniforms["u_dem_lerp"] = morphingPhase;
} else {
demTile = this.terrainTileForTile[tile.tileID.key];
context.activeTexture.set(gl.TEXTURE2);
const demTexture = this._prepareDemTileUniforms(tile, demTile, uniforms) ?
(demTile.demTexture: any) : this.emptyDEMTexture;
demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);
}
if (options && options.useDepthForOcclusion) {
context.activeTexture.set(gl.TEXTURE3);
this._depthTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);
uniforms['u_depth_size_inv'] = [1 / this._depthFBO.width, 1 / this._depthFBO.height];
}
if (options && options.useMeterToDem && demTile) {
const meterToDEM = (1 << demTile.tileID.canonical.z) * mercatorZfromAltitude(1, this.painter.transform.center.lat) * this.sourceCache.getSource().tileSize;
uniforms['u_meter_to_dem'] = meterToDEM;
}
if (options && options.labelPlaneMatrixInv) {
uniforms['u_label_plane_matrix_inv'] = options.labelPlaneMatrixInv;
}
program.setTerrainUniformValues(context, uniforms);
}
// For each proxy tile, render all layers until the non-draped layer (and
// render the tile to the screen) before advancing to the next proxy tile.
// Returns the last drawn index that is used as a start
// layer for interleaved draped rendering.
// Apart to layer-by-layer rendering used in 2D, here we have proxy-tile-by-proxy-tile
// rendering.
renderBatch(startLayerIndex: number): number {
if (this._drapedRenderBatches.length === 0) {
return startLayerIndex + 1;
}
this.renderingToTexture = true;
const painter = this.painter;
const context = this.painter.context;
const psc = this.proxySourceCache;
const proxies = this.proxiedCoords[psc.id];
const setupRenderToScreen = () => {
context.bindFramebuffer.set(null);
context.viewport.set([0, 0, painter.width, painter.height]);
this.renderingToTexture = false;
};
// Consume batch of sequential drape layers and move next
const drapedLayerBatch = this._drapedRenderBatches.shift();
assert(drapedLayerBatch.start === startLayerIndex);
let drawAsRasterCoords = [];
const layerIds = painter.style.order;
let poolIndex = 0;
for (let i = 0; i < proxies.length; i++) {
const proxy = proxies[i];
// bind framebuffer and assign texture to the tile (texture used in drawTerrainRaster).
const tile = psc.getTileByID(proxy.proxyTileKey);
const renderCacheIndex = psc.proxyCachedFBO[proxy.key] ? psc.proxyCachedFBO[proxy.key][startLayerIndex] : undefined;
let fbo;
if (renderCacheIndex !== undefined) {
fbo = this.currentFBO = psc.renderCache[renderCacheIndex];
} else {
fbo = this.currentFBO = this.pool[poolIndex++];
}
tile.texture = fbo.tex;
if (renderCacheIndex !== undefined && !fbo.dirty) {
// Use cached render from previous pass, no need to render again.
drawAsRasterCoords.push(tile.tileID);
continue;
}
context.bindFramebuffer.set(fbo.fb.framebuffer);
this.renderedToTile = false; // reset flag.
if (fbo.dirty) {
// Clear on start.
context.clear({color: Color.transparent});
fbo.dirty = false;
}
let currentStencilSource; // There is no need to setup stencil for the same source for consecutive layers.
for (let j = drapedLayerBatch.start; j <= drapedLayerBatch.end; ++j) {
const layer = painter.style._layers[layerIds[j]];
const hidden = layer.isHidden(painter.transform.zoom);
assert(this._style.isLayerDraped(layer) || hidden);
if (hidden) continue;
const sourceCache = painter.style._getLayerSourceCache(layer);
const proxiedCoords = sourceCache ? this.proxyToSource[proxy.key][sourceCache.id] : [proxy];
if (!proxiedCoords) continue; // when tile is not loaded yet for the source cache.
const coords = ((proxiedCoords: any): Array<OverscaledTileID>);
context.viewport.set([0, 0, fbo.fb.width, fbo.fb.height]);
if (currentStencilSource !== (sourceCache ? sourceCache.id : null)) {
this._setupStencil(proxiedCoords, layer, sourceCache);
currentStencilSource = sourceCache ? sourceCache.id : null;
}
painter.renderLayer(painter, sourceCache, layer, coords);
}
fbo.dirty = this.renderedToTile;
if (this.renderedToTile) drawAsRasterCoords.push(tile.tileID);
if (poolIndex === FBO_POOL_SIZE) {
poolIndex = 0;
if (drawAsRasterCoords.length > 0) {
setupRenderToScreen();
drawTerrainRaster(painter, this, psc, drawAsRasterCoords, this._updateTimestamp);
this.renderingToTexture = true;
drawAsRasterCoords = [];
}
}
}
setupRenderToScreen();
if (drawAsRasterCoords.length > 0) {
drawTerrainRaster(painter, this, psc, drawAsRasterCoords, this._updateTimestamp);
}
return drapedLayerBatch.end + 1;
}
postRender() {
// Make sure we consumed all the draped terrain batches at this point
assert(this._drapedRenderBatches.length === 0);
}
renderCacheEfficiency(style: Style): Object {
const layerCount = style.order.length;
if (layerCount === 0) {
return {efficiency: 100.0};
}
let uncacheableLayerCount = 0;
let drapedLayerCount = 0;
let reachedUndrapedLayer = false;
let firstUndrapedLayer;
for (let i = 0; i < layerCount; ++i) {
const layer = style._layers[style.order[i]];
if (!this._style.isLayerDraped(layer)) {
if (!reachedUndrapedLayer) {
reachedUndrapedLayer = true;
firstUndrapedLayer = layer.id;
}
} else {
if (reachedUndrapedLayer) {
++uncacheableLayerCount;
}
++drapedLayerCount;
}
}
if (drapedLayerCount === 0) {
return {efficiency: 100.0};
}
return {efficiency: (1.0 - uncacheableLayerCount / drapedLayerCount) * 100.0, firstUndrapedLayer};
}
getMinElevationBelowMSL(): number {
let min = 0.0;
// The maximum DEM error in meters to be conservative (SRTM).
const maxDEMError = 30.0;
this._visibleDemTiles.filter(tile => tile.dem).forEach(tile => {
const minMaxTree = (tile.dem: any).tree;
min = Math.min(min, minMaxTree.minimums[0]);
});
return min === 0.0 ? min : (min - maxDEMError) * this._exaggeration;
}
// Performs raycast against visible DEM tiles on the screen and returns the distance travelled along the ray.
// x & y components of the position are expected to be in normalized mercator coordinates [0, 1] and z in meters.
raycast(pos: vec3, dir: vec3, exaggeration: number): ?number {
if (!this._visibleDemTiles)
return null;
// Perform initial raycasts against root nodes of the available dem tiles
// and use this information to sort them from closest to furthest.
const preparedTiles = this._visibleDemTiles.filter(tile => tile.dem).map(tile => {
const id = tile.tileID;
const tiles = Math.pow(2.0, id.overscaledZ);
const {x, y} = id.canonical;
// Compute tile boundaries in mercator coordinates
const minx = x / tiles;
const maxx = (x + 1) / tiles;
const miny = y / tiles;
const maxy = (y + 1) / tiles;
const tree = (tile.dem: any).tree;
return {
minx, miny, maxx, maxy,
t: tree.raycastRoot(minx, miny, maxx, maxy, pos, dir, exaggeration),
tile
};
});
preparedTiles.sort((a, b) => {
const at = a.t !== null ? a.t : Number.MAX_VALUE;
const bt = b.t !== null ? b.t : Number.MAX_VALUE;
return at - bt;
});
for (const obj of preparedTiles) {
if (obj.t == null)
return null;
// Perform more accurate raycast against the dem tree. First intersection is the closest on
// as all tiles are sorted from closest to furthest
const tree = (obj.tile.dem: any).tree;
const t = tree.raycast(obj.minx, obj.miny, obj.maxx, obj.maxy, pos, dir, exaggeration);
if (t != null)
return t;
}
return null;
}
_createFBO(): FBO {
const painter = this.painter;
const context = painter.context;
const gl = context.gl;
const bufferSize = this.drapeBufferSize;
context.activeTexture.set(gl.TEXTURE0);
const tex = new Texture(context, {width: bufferSize[0], height: bufferSize[1], data: null}, gl.RGBA);
tex.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
const fb = context.createFramebuffer(bufferSize[0], bufferSize[1], false);
fb.colorAttachment.set(tex.texture);
if (context.extTextureFilterAnisotropic && !context.extTextureFilterAnisotropicForceOff) {
gl.texParameterf(gl.TEXTURE_2D,
context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,
context.extTextureFilterAnisotropicMax);
}
return {fb, tex, dirty: false, ref: 1};
}
_initFBOPool() {
while (this.pool.length < Math.min(FBO_POOL_SIZE, this.proxyCoords.length)) {
this.pool.push(this._createFBO());
}
}
_shouldDisableRenderCache(): boolean {
// Disable render caches on dynamic events due to fading.
const isCrossFading = id => {
const layer = this._style._layers[id];
const isHidden = !layer.isHidden(this.painter.transform.zoom);
const crossFade = layer.getCrossfadeParameters();
const isFading = !!crossFade && crossFade.t !== 1;
return layer.type !== 'custom' && !isHidden && isFading;
};
return !this.renderCached || this._style.order.some(isCrossFading);
}
_clearRasterFadeFromRenderCache() {
let hasRasterSource = false;
for (const id in this._style._sourceCaches) {
if (this._style._sourceCaches[id]._source instanceof RasterTileSource) {
hasRasterSource = true;
break;
}
}
if (!hasRasterSource) {
return;
}
// Check if any raster tile is in a fading state
for (let i = 0; i < this._style.order.length; ++i) {
const layer = this._style._layers[this._style.order[i]];
const isHidden = layer.isHidden(this.painter.transform.zoom);
const sourceCache = this._style._getLayerSourceCache(layer);
if (layer.type !== 'raster' || isHidden || !sourceCache) { continue; }
const rasterLayer = ((layer: any): RasterStyleLayer);
const fadeDuration = rasterLayer.paint.get('raster-fade-duration');
for (const proxy of this.proxyCoords) {
const proxiedCoords = this.proxyToSource[proxy.key][sourceCache.id];
const coords = ((proxiedCoords: any): Array<OverscaledTileID>);
if (!coords) { continue; }
for (const coord of coords) {
const tile = sourceCache.getTile(coord);
const parent = sourceCache.findLoadedParent(coord, 0);
const fade = rasterFade(tile, parent, sourceCache, this.painter.transform, fadeDuration);
const isFading = fade.opacity !== 1 || fade.mix !== 0;
if (isFading) {
this._clearRenderCacheForTile(sourceCache.id, coord);
}
}
}
}
}
_setupDrapedRenderBatches() {
const layerIds = this._style.order;
const layerCount = layerIds.length;
if (layerCount === 0) {
return;
}
const batches = [];
let currentLayer = 0;
let layer = this._style._layers[layerIds[currentLayer]];
while (!this._style.isLayerDraped(layer) && layer.isHidden(this.painter.transform.zoom) && ++currentLayer < layerCount) {
layer = this._style._layers[layerIds[currentLayer]];
}
let batchStart;
for (; currentLayer < layerCount; ++currentLayer) {
const layer = this._style._layers[layerIds[currentLayer]];
if (layer.isHidden(this.painter.transform.zoom)) {
continue;
}
if (!this._style.isLayerDraped(layer)) {
if (batchStart !== undefined) {
batches.push({start: batchStart, end: currentLayer - 1});
batchStart = undefined;
}
continue;
}
if (batchStart === undefined) {
batchStart = currentLayer;
}
}
if (batchStart !== undefined) {
batches.push({start: batchStart, end: currentLayer - 1});
}
if (this._style.map._optimizeForTerrain) {
// Draped first approach should result in a single or no batch
assert(batches.length === 1 || batches.length === 0);
}
this._drapedRenderBatches = batches;
}
_setupRenderCache(previousProxyToSource: {[number]: {[string]: Array<ProxiedTileID>}}) {
const psc = this.proxySourceCache;
if (this._shouldDisableRenderCache()) {
if (psc.renderCache.length > psc.renderCachePool.length) {
const used = ((Object.values(psc.proxyCachedFBO): any): Array<{[string | number]: number}>);
psc.proxyCachedFBO = {};
for (let i = 0; i < used.length; ++i) {
const fbos = ((Object.values(used[i]): any): Array<number>);
psc.renderCachePool.push(...fbos);
}
assert(psc.renderCache.length === psc.renderCachePool.length);
}
return;
}
this._clearRasterFadeFromRenderCache();
const coords = this.proxyCoords;
const dirty = this._tilesDirty;
for (let i = coords.length - 1; i >= 0; i--) {
const proxy = coords[i];
const tile = psc.getTileByID(proxy.key);
if (psc.proxyCachedFBO[proxy.key] !== undefined) {
assert(tile.texture);
const prev = previousProxyToSource[proxy.key];
assert(prev);
// Reuse previous render from cache if there was no change of
// content that was used to render proxy tile.
const current = this.proxyToSource[proxy.key];
let equal = 0;
for (const source in current) {
const tiles = current[source];
const prevTiles = prev[source];
if (!prevTiles || prevTiles.length !== tiles.length ||
tiles.some((t, index) => (t !== prevTiles[index] || (dirty[source] && dirty[source].hasOwnProperty(t.key))))) {
equal = -1;
break;
}
++equal;
}
// dirty === false: doesn't need to be rendered to, just use cached render.
for (const proxyFBO in psc.proxyCachedFBO[proxy.key]) {
psc.renderCache[psc.proxyCachedFBO[proxy.key][proxyFBO]].dirty = equal < 0 || equal !== Object.values(prev).length;
}
} else {
for (let j = 0; j < this._drapedRenderBatches.length; ++j) {
const batch = this._drapedRenderBatches[j];
// Assign renderCache FBO if there are available FBOs in pool.
let index = psc.renderCachePool.pop();
if (index === undefined && psc.renderCache.length < RENDER_CACHE_MAX_SIZE) {
index = psc.renderCache.length;
psc.renderCache.push(this._createFBO());
// assert(psc.renderCache.length <= coords.length);
}
if (index !== undefined) {
if (psc.proxyCachedFBO[proxy.key] === undefined)
psc.proxyCachedFBO[proxy.key] = {};
psc.proxyCachedFBO[proxy.key][batch.start] = index;
psc.renderCache[index].dirty = true; // needs to be rendered to.
}
}
}
}
this._tilesDirty = {};
}
_setupStencil(proxiedCoords: Array<ProxiedTileID>, layer: StyleLayer, sourceCache?: SourceCache) {
if (!sourceCache || !this._sourceTilesOverlap[sourceCache.id]) {
if (this._overlapStencilType) this._overlapStencilType = false;
return;
}
const context = this.painter.context;
const gl = context.gl;