-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
GlobeSurfaceTileProvider.js
1853 lines (1612 loc) · 80.5 KB
/
GlobeSurfaceTileProvider.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
define([
'../Core/AttributeCompression',
'../Core/BoundingSphere',
'../Core/BoxOutlineGeometry',
'../Core/Cartesian2',
'../Core/Cartesian3',
'../Core/Cartesian4',
'../Core/Cartographic',
'../Core/Color',
'../Core/ColorGeometryInstanceAttribute',
'../Core/combine',
'../Core/defaultValue',
'../Core/defined',
'../Core/defineProperties',
'../Core/destroyObject',
'../Core/DeveloperError',
'../Core/Event',
'../Core/GeometryInstance',
'../Core/GeometryPipeline',
'../Core/IndexDatatype',
'../Core/Intersect',
'../Core/Math',
'../Core/Matrix3',
'../Core/Matrix4',
'../Core/OrientedBoundingBox',
'../Core/OrthographicFrustum',
'../Core/PrimitiveType',
'../Core/Rectangle',
'../Core/SphereOutlineGeometry',
'../Core/TerrainEncoding',
'../Core/TerrainMesh',
'../Core/TerrainQuantization',
'../Core/Visibility',
'../Core/WebMercatorProjection',
'../Renderer/Buffer',
'../Renderer/BufferUsage',
'../Renderer/ContextLimits',
'../Renderer/DrawCommand',
'../Renderer/Pass',
'../Renderer/RenderState',
'../Renderer/VertexArray',
'./BlendingState',
'./DepthFunction',
'./ImageryState',
'./PerInstanceColorAppearance',
'./Primitive',
'./TileBoundingRegion',
'./TileSelectionResult',
'./ClippingPlaneCollection',
'./GlobeSurfaceTile',
'./ImageryLayer',
'./QuadtreeTileLoadState',
'./SceneMode',
'./ShadowMode',
'./TerrainFillMesh'
], function(
AttributeCompression,
BoundingSphere,
BoxOutlineGeometry,
Cartesian2,
Cartesian3,
Cartesian4,
Cartographic,
Color,
ColorGeometryInstanceAttribute,
combine,
defaultValue,
defined,
defineProperties,
destroyObject,
DeveloperError,
Event,
GeometryInstance,
GeometryPipeline,
IndexDatatype,
Intersect,
CesiumMath,
Matrix3,
Matrix4,
OrientedBoundingBox,
OrthographicFrustum,
PrimitiveType,
Rectangle,
SphereOutlineGeometry,
TerrainEncoding,
TerrainMesh,
TerrainQuantization,
Visibility,
WebMercatorProjection,
Buffer,
BufferUsage,
ContextLimits,
DrawCommand,
Pass,
RenderState,
VertexArray,
BlendingState,
DepthFunction,
ImageryState,
PerInstanceColorAppearance,
Primitive,
TileBoundingRegion,
TileSelectionResult,
ClippingPlaneCollection,
GlobeSurfaceTile,
ImageryLayer,
QuadtreeTileLoadState,
SceneMode,
ShadowMode,
TerrainFillMesh) {
'use strict';
/**
* Provides quadtree tiles representing the surface of the globe. This type is intended to be used
* with {@link QuadtreePrimitive}.
*
* @alias GlobeSurfaceTileProvider
* @constructor
*
* @param {TerrainProvider} options.terrainProvider The terrain provider that describes the surface geometry.
* @param {ImageryLayerCollection} option.imageryLayers The collection of imagery layers describing the shading of the surface.
* @param {GlobeSurfaceShaderSet} options.surfaceShaderSet The set of shaders used to render the surface.
*
* @private
*/
function GlobeSurfaceTileProvider(options) {
//>>includeStart('debug', pragmas.debug);
if (!defined(options)) {
throw new DeveloperError('options is required.');
}
if (!defined(options.terrainProvider)) {
throw new DeveloperError('options.terrainProvider is required.');
} else if (!defined(options.imageryLayers)) {
throw new DeveloperError('options.imageryLayers is required.');
} else if (!defined(options.surfaceShaderSet)) {
throw new DeveloperError('options.surfaceShaderSet is required.');
}
//>>includeEnd('debug');
this.lightingFadeOutDistance = 6500000.0;
this.lightingFadeInDistance = 9000000.0;
this.hasWaterMask = false;
this.oceanNormalMap = undefined;
this.zoomedOutOceanSpecularIntensity = 0.5;
this.enableLighting = false;
this.showGroundAtmosphere = false;
this.shadows = ShadowMode.RECEIVE_ONLY;
/**
* The color to use to highlight fill tiles. If undefined, fill tiles are not
* highlighted at all. The alpha value is used to alpha blend with the tile's
* actual color.
*/
this.fillHighlightColor = undefined;
this.hueShift = 0.0;
this.saturationShift = 0.0;
this.brightnessShift = 0.0;
this._quadtree = undefined;
this._terrainProvider = options.terrainProvider;
this._imageryLayers = options.imageryLayers;
this._surfaceShaderSet = options.surfaceShaderSet;
this._renderState = undefined;
this._blendRenderState = undefined;
this._errorEvent = new Event();
this._imageryLayers.layerAdded.addEventListener(GlobeSurfaceTileProvider.prototype._onLayerAdded, this);
this._imageryLayers.layerRemoved.addEventListener(GlobeSurfaceTileProvider.prototype._onLayerRemoved, this);
this._imageryLayers.layerMoved.addEventListener(GlobeSurfaceTileProvider.prototype._onLayerMoved, this);
this._imageryLayers.layerShownOrHidden.addEventListener(GlobeSurfaceTileProvider.prototype._onLayerShownOrHidden, this);
this._imageryLayersUpdatedEvent = new Event();
this._layerOrderChanged = false;
this._tilesToRenderByTextureCount = [];
this._drawCommands = [];
this._uniformMaps = [];
this._usedDrawCommands = 0;
this._debug = {
wireframe : false,
boundingSphereTile : undefined
};
this._baseColor = undefined;
this._firstPassInitialColor = undefined;
this.baseColor = new Color(0.0, 0.0, 0.5, 1.0);
/**
* A property specifying a {@link ClippingPlaneCollection} used to selectively disable rendering on the outside of each plane.
* @type {ClippingPlaneCollection}
* @private
*/
this._clippingPlanes = undefined;
/**
* A property specifying a {@link Rectangle} used to selectively limit terrain and imagery rendering.
* @type {Rectangle}
*/
this.cartographicLimitRectangle = Rectangle.clone(Rectangle.MAX_VALUE);
this._hasLoadedTilesThisFrame = false;
this._hasFillTilesThisFrame = false;
}
defineProperties(GlobeSurfaceTileProvider.prototype, {
/**
* Gets or sets the color of the globe when no imagery is available.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {Color}
*/
baseColor : {
get : function() {
return this._baseColor;
},
set : function(value) {
//>>includeStart('debug', pragmas.debug);
if (!defined(value)) {
throw new DeveloperError('value is required.');
}
//>>includeEnd('debug');
this._baseColor = value;
this._firstPassInitialColor = Cartesian4.fromColor(value, this._firstPassInitialColor);
}
},
/**
* Gets or sets the {@link QuadtreePrimitive} for which this provider is
* providing tiles. This property may be undefined if the provider is not yet associated
* with a {@link QuadtreePrimitive}.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {QuadtreePrimitive}
*/
quadtree : {
get : function() {
return this._quadtree;
},
set : function(value) {
//>>includeStart('debug', pragmas.debug);
if (!defined(value)) {
throw new DeveloperError('value is required.');
}
//>>includeEnd('debug');
this._quadtree = value;
}
},
/**
* Gets a value indicating whether or not the provider is ready for use.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {Boolean}
*/
ready : {
get : function() {
return this._terrainProvider.ready && (this._imageryLayers.length === 0 || this._imageryLayers.get(0).imageryProvider.ready);
}
},
/**
* Gets the tiling scheme used by the provider. This property should
* not be accessed before {@link GlobeSurfaceTileProvider#ready} returns true.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {TilingScheme}
*/
tilingScheme : {
get : function() {
return this._terrainProvider.tilingScheme;
}
},
/**
* Gets an event that is raised when the geometry provider encounters an asynchronous error. By subscribing
* to the event, you will be notified of the error and can potentially recover from it. Event listeners
* are passed an instance of {@link TileProviderError}.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {Event}
*/
errorEvent : {
get : function() {
return this._errorEvent;
}
},
/**
* Gets an event that is raised when an imagery layer is added, shown, hidden, moved, or removed.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {Event}
*/
imageryLayersUpdatedEvent : {
get : function() {
return this._imageryLayersUpdatedEvent;
}
},
/**
* Gets or sets the terrain provider that describes the surface geometry.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {TerrainProvider}
*/
terrainProvider : {
get : function() {
return this._terrainProvider;
},
set : function(terrainProvider) {
if (this._terrainProvider === terrainProvider) {
return;
}
//>>includeStart('debug', pragmas.debug);
if (!defined(terrainProvider)) {
throw new DeveloperError('terrainProvider is required.');
}
//>>includeEnd('debug');
this._terrainProvider = terrainProvider;
if (defined(this._quadtree)) {
this._quadtree.invalidateAllTiles();
}
}
},
/**
* The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
*
* @type {ClippingPlaneCollection}
*
* @private
*/
clippingPlanes : {
get : function() {
return this._clippingPlanes;
},
set : function(value) {
ClippingPlaneCollection.setOwner(value, this, '_clippingPlanes');
}
}
});
function sortTileImageryByLayerIndex(a, b) {
var aImagery = a.loadingImagery;
if (!defined(aImagery)) {
aImagery = a.readyImagery;
}
var bImagery = b.loadingImagery;
if (!defined(bImagery)) {
bImagery = b.readyImagery;
}
return aImagery.imageryLayer._layerIndex - bImagery.imageryLayer._layerIndex;
}
/**
* Make updates to the tile provider that are not involved in rendering. Called before the render update cycle.
*/
GlobeSurfaceTileProvider.prototype.update = function(frameState) {
// update collection: imagery indices, base layers, raise layer show/hide event
this._imageryLayers._update();
};
function updateCredits(surface, frameState) {
var creditDisplay = frameState.creditDisplay;
if (surface._terrainProvider.ready && defined(surface._terrainProvider.credit)) {
creditDisplay.addCredit(surface._terrainProvider.credit);
}
var imageryLayers = surface._imageryLayers;
for (var i = 0, len = imageryLayers.length; i < len; ++i) {
var imageryProvider = imageryLayers.get(i).imageryProvider;
if (imageryProvider.ready && defined(imageryProvider.credit)) {
creditDisplay.addCredit(imageryProvider.credit);
}
}
}
/**
* Called at the beginning of each render frame, before {@link QuadtreeTileProvider#showTileThisFrame}
* @param {FrameState} frameState The frame state.
*/
GlobeSurfaceTileProvider.prototype.initialize = function(frameState) {
// update each layer for texture reprojection.
this._imageryLayers.queueReprojectionCommands(frameState);
if (this._layerOrderChanged) {
this._layerOrderChanged = false;
// Sort the TileImagery instances in each tile by the layer index.
this._quadtree.forEachLoadedTile(function(tile) {
tile.data.imagery.sort(sortTileImageryByLayerIndex);
});
}
// Add credits for terrain and imagery providers.
updateCredits(this, frameState);
};
/**
* Called at the beginning of the update cycle for each render frame, before {@link QuadtreeTileProvider#showTileThisFrame}
* or any other functions.
*
* @param {FrameState} frameState The frame state.
*/
GlobeSurfaceTileProvider.prototype.beginUpdate = function(frameState) {
var tilesToRenderByTextureCount = this._tilesToRenderByTextureCount;
for (var i = 0, len = tilesToRenderByTextureCount.length; i < len; ++i) {
var tiles = tilesToRenderByTextureCount[i];
if (defined(tiles)) {
tiles.length = 0;
}
}
// update clipping planes
var clippingPlanes = this._clippingPlanes;
if (defined(clippingPlanes) && clippingPlanes.enabled) {
clippingPlanes.update(frameState);
}
this._usedDrawCommands = 0;
this._hasLoadedTilesThisFrame = false;
this._hasFillTilesThisFrame = false;
};
/**
* Called at the end of the update cycle for each render frame, after {@link QuadtreeTileProvider#showTileThisFrame}
* and any other functions.
*
* @param {FrameState} frameState The frame state.
*/
GlobeSurfaceTileProvider.prototype.endUpdate = function(frameState) {
if (!defined(this._renderState)) {
this._renderState = RenderState.fromCache({ // Write color and depth
cull : {
enabled : true
},
depthTest : {
enabled : true,
func : DepthFunction.LESS
}
});
this._blendRenderState = RenderState.fromCache({ // Write color and depth
cull : {
enabled : true
},
depthTest : {
enabled : true,
func : DepthFunction.LESS_OR_EQUAL
},
blending : BlendingState.ALPHA_BLEND
});
}
// If this frame has a mix of loaded and fill tiles, we need to propagate
// loaded heights to the fill tiles.
if (this._hasFillTilesThisFrame && this._hasLoadedTilesThisFrame) {
TerrainFillMesh.updateFillTiles(this, this._quadtree._tilesToRender, frameState);
}
// Add the tile render commands to the command list, sorted by texture count.
var tilesToRenderByTextureCount = this._tilesToRenderByTextureCount;
for (var textureCountIndex = 0, textureCountLength = tilesToRenderByTextureCount.length; textureCountIndex < textureCountLength; ++textureCountIndex) {
var tilesToRender = tilesToRenderByTextureCount[textureCountIndex];
if (!defined(tilesToRender)) {
continue;
}
for (var tileIndex = 0, tileLength = tilesToRender.length; tileIndex < tileLength; ++tileIndex) {
addDrawCommandsForTile(this, tilesToRender[tileIndex], frameState);
}
}
};
/**
* Adds draw commands for tiles rendered in the previous frame for a pick pass.
*
* @param {FrameState} frameState The frame state.
*/
GlobeSurfaceTileProvider.prototype.updateForPick = function(frameState) {
// Add the tile pick commands from the tiles drawn last frame.
var drawCommands = this._drawCommands;
for (var i = 0, length = this._usedDrawCommands; i < length; ++i) {
frameState.commandList.push(drawCommands[i]);
}
};
/**
* Cancels any imagery re-projections in the queue.
*/
GlobeSurfaceTileProvider.prototype.cancelReprojections = function() {
this._imageryLayers.cancelReprojections();
};
/**
* Gets the maximum geometric error allowed in a tile at a given level, in meters. This function should not be
* called before {@link GlobeSurfaceTileProvider#ready} returns true.
*
* @param {Number} level The tile level for which to get the maximum geometric error.
* @returns {Number} The maximum geometric error in meters.
*/
GlobeSurfaceTileProvider.prototype.getLevelMaximumGeometricError = function(level) {
return this._terrainProvider.getLevelMaximumGeometricError(level);
};
/**
* Loads, or continues loading, a given tile. This function will continue to be called
* until {@link QuadtreeTile#state} is no longer {@link QuadtreeTileLoadState#LOADING}. This function should
* not be called before {@link GlobeSurfaceTileProvider#ready} returns true.
*
* @param {FrameState} frameState The frame state.
* @param {QuadtreeTile} tile The tile to load.
*
* @exception {DeveloperError} <code>loadTile</code> must not be called before the tile provider is ready.
*/
GlobeSurfaceTileProvider.prototype.loadTile = function(frameState, tile) {
// We don't want to load imagery until we're certain that the terrain tiles are actually visible.
// So if our bounding volume isn't accurate because it came from another tile, load terrain only
// initially. If we load some terrain and suddenly have a more accurate bounding volume and the
// tile is _still_ visible, give the tile a chance to load imagery immediately rather than
// waiting for next frame.
var surfaceTile = tile.data;
var terrainOnly = true;
var terrainStateBefore;
if (defined(surfaceTile)) {
terrainOnly = surfaceTile.boundingVolumeSourceTile !== tile;
terrainStateBefore = surfaceTile.terrainState;
}
GlobeSurfaceTile.processStateMachine(tile, frameState, this.terrainProvider, this._imageryLayers, terrainOnly);
surfaceTile = tile.data;
if (terrainOnly && terrainStateBefore !== tile.data.terrainState) {
// Terrain state changed. If:
// a) The tile is visible, and
// b) The bounding volume is accurate (updated as a side effect of computing visibility)
// Then we'll load imagery, too.
if (this.computeTileVisibility(tile, frameState, this.quadtree.occluders) && surfaceTile.boundingVolumeSourceTile === tile) {
terrainOnly = false;
GlobeSurfaceTile.processStateMachine(tile, frameState, this.terrainProvider, this._imageryLayers, terrainOnly);
}
}
};
var boundingSphereScratch = new BoundingSphere();
var rectangleIntersectionScratch = new Rectangle();
var splitCartographicLimitRectangleScratch = new Rectangle();
var rectangleCenterScratch = new Cartographic();
// cartographicLimitRectangle may span the IDL, but tiles never will.
function clipRectangleAntimeridian(tileRectangle, cartographicLimitRectangle) {
if (cartographicLimitRectangle.west < cartographicLimitRectangle.east) {
return cartographicLimitRectangle;
}
var splitRectangle = Rectangle.clone(cartographicLimitRectangle, splitCartographicLimitRectangleScratch);
var tileCenter = Rectangle.center(tileRectangle, rectangleCenterScratch);
if (tileCenter.longitude > 0.0) {
splitRectangle.east = CesiumMath.PI;
} else {
splitRectangle.west = -CesiumMath.PI;
}
return splitRectangle;
}
/**
* Determines the visibility of a given tile. The tile may be fully visible, partially visible, or not
* visible at all. Tiles that are renderable and are at least partially visible will be shown by a call
* to {@link GlobeSurfaceTileProvider#showTileThisFrame}.
*
* @param {QuadtreeTile} tile The tile instance.
* @param {FrameState} frameState The state information about the current frame.
* @param {QuadtreeOccluders} occluders The objects that may occlude this tile.
*
* @returns {Visibility} The visibility of the tile.
*/
GlobeSurfaceTileProvider.prototype.computeTileVisibility = function(tile, frameState, occluders) {
var distance = this.computeDistanceToTile(tile, frameState);
tile._distance = distance;
if (frameState.fog.enabled) {
if (CesiumMath.fog(distance, frameState.fog.density) >= 1.0) {
// Tile is completely in fog so return that it is not visible.
return Visibility.NONE;
}
}
var surfaceTile = tile.data;
var tileBoundingRegion = surfaceTile.tileBoundingRegion;
if (surfaceTile.boundingVolumeSourceTile === undefined) {
// We have no idea where this tile is, so let's just call it partially visible.
return Visibility.PARTIAL;
}
var cullingVolume = frameState.cullingVolume;
var boundingVolume = surfaceTile.orientedBoundingBox;
// Check if the tile is outside the limit area in cartographic space
surfaceTile.clippedByBoundaries = false;
var clippedCartographicLimitRectangle = clipRectangleAntimeridian(tile.rectangle, this.cartographicLimitRectangle);
var areaLimitIntersection = Rectangle.simpleIntersection(clippedCartographicLimitRectangle, tile.rectangle, rectangleIntersectionScratch);
if (!defined(areaLimitIntersection)) {
return Visibility.NONE;
}
if (!Rectangle.equals(areaLimitIntersection, tile.rectangle)) {
surfaceTile.clippedByBoundaries = true;
}
if (frameState.mode !== SceneMode.SCENE3D) {
boundingVolume = boundingSphereScratch;
BoundingSphere.fromRectangleWithHeights2D(tile.rectangle, frameState.mapProjection, tileBoundingRegion.minimumHeight, tileBoundingRegion.maximumHeight, boundingVolume);
Cartesian3.fromElements(boundingVolume.center.z, boundingVolume.center.x, boundingVolume.center.y, boundingVolume.center);
if (frameState.mode === SceneMode.MORPHING && surfaceTile.mesh !== undefined) {
boundingVolume = BoundingSphere.union(surfaceTile.mesh.boundingSphere3D, boundingVolume, boundingVolume);
}
}
var clippingPlanes = this._clippingPlanes;
if (defined(clippingPlanes) && clippingPlanes.enabled) {
var planeIntersection = clippingPlanes.computeIntersectionWithBoundingVolume(boundingVolume);
tile.isClipped = (planeIntersection !== Intersect.INSIDE);
if (planeIntersection === Intersect.OUTSIDE) {
return Visibility.NONE;
}
}
var intersection = cullingVolume.computeVisibility(boundingVolume);
if (intersection === Intersect.OUTSIDE) {
return Visibility.NONE;
}
var ortho3D = frameState.mode === SceneMode.SCENE3D && frameState.camera.frustum instanceof OrthographicFrustum;
if (frameState.mode === SceneMode.SCENE3D && !ortho3D && defined(occluders)) {
var occludeePointInScaledSpace = surfaceTile.occludeePointInScaledSpace;
if (!defined(occludeePointInScaledSpace)) {
return intersection;
}
if (occluders.ellipsoid.isScaledSpacePointVisible(occludeePointInScaledSpace)) {
return intersection;
}
return Visibility.NONE;
}
return intersection;
};
/**
* Determines if the given tile can be refined
* @param {QuadtreeTile} tile The tile to check.
* @returns {boolean} True if the tile can be refined, false if it cannot.
*/
GlobeSurfaceTileProvider.prototype.canRefine = function(tile) {
// Only allow refinement it we know whether or not the children of this tile exist.
// For a tileset with `availability`, we'll always be able to refine.
// We can ask for availability of _any_ child tile because we only need to confirm
// that we get a yes or no answer, it doesn't matter what the answer is.
if (defined(tile.data.terrainData)) {
return true;
}
var childAvailable = this.terrainProvider.getTileDataAvailable(tile.x * 2, tile.y * 2, tile.level + 1);
return childAvailable !== undefined;
};
var tileDirectionScratch = new Cartesian3();
/**
* Determines the priority for loading this tile. Lower priority values load sooner.
* @param {QuatreeTile} tile The tile.
* @param {FrameState} frameState The frame state.
* @returns {Number} The load priority value.
*/
GlobeSurfaceTileProvider.prototype.computeTileLoadPriority = function(tile, frameState) {
var surfaceTile = tile.data;
if (surfaceTile === undefined) {
return 0.0;
}
var obb = surfaceTile.orientedBoundingBox;
if (obb === undefined) {
return 0.0;
}
var cameraPosition = frameState.camera.positionWC;
var cameraDirection = frameState.camera.directionWC;
var tileDirection = Cartesian3.normalize(Cartesian3.subtract(obb.center, cameraPosition, tileDirectionScratch), tileDirectionScratch);
return (1.0 - Cartesian3.dot(tileDirection, cameraDirection)) * tile._distance;
};
var modifiedModelViewScratch = new Matrix4();
var modifiedModelViewProjectionScratch = new Matrix4();
var tileRectangleScratch = new Cartesian4();
var localizedCartographicLimitRectangleScratch = new Cartesian4();
var rtcScratch = new Cartesian3();
var centerEyeScratch = new Cartesian3();
var southwestScratch = new Cartesian3();
var northeastScratch = new Cartesian3();
/**
* Shows a specified tile in this frame. The provider can cause the tile to be shown by adding
* render commands to the commandList, or use any other method as appropriate. The tile is not
* expected to be visible next frame as well, unless this method is called next frame, too.
*
* @param {QuadtreeTile} tile The tile instance.
* @param {FrameState} frameState The state information of the current rendering frame.
* @param {QuadtreeTile} [nearestRenderableTile] The nearest ancestor tile that is renderable.
*/
GlobeSurfaceTileProvider.prototype.showTileThisFrame = function(tile, frameState, nearestRenderableTile) {
var readyTextureCount = 0;
var tileImageryCollection = tile.data.imagery;
for (var i = 0, len = tileImageryCollection.length; i < len; ++i) {
var tileImagery = tileImageryCollection[i];
if (defined(tileImagery.readyImagery) && tileImagery.readyImagery.imageryLayer.alpha !== 0.0) {
++readyTextureCount;
}
}
var tileSet = this._tilesToRenderByTextureCount[readyTextureCount];
if (!defined(tileSet)) {
tileSet = [];
this._tilesToRenderByTextureCount[readyTextureCount] = tileSet;
}
tileSet.push(tile);
var surfaceTile = tile.data;
if (nearestRenderableTile !== undefined && nearestRenderableTile !== tile) {
this._hasFillTilesThisFrame = true;
surfaceTile.renderableTile = nearestRenderableTile;
// The renderable tile may have previously deferred to an ancestor.
// But we know it's renderable now, so mark it as such.
nearestRenderableTile.data.renderableTile = undefined;
} else {
this._hasLoadedTilesThisFrame = true;
surfaceTile.renderableTile = undefined;
}
var debug = this._debug;
++debug.tilesRendered;
debug.texturesRendered += readyTextureCount;
};
var cornerPositionsScratch = [new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3()];
function computeOccludeePoint(tileProvider, center, rectangle, height, result) {
var ellipsoidalOccluder = tileProvider.quadtree._occluders.ellipsoid;
var ellipsoid = ellipsoidalOccluder.ellipsoid;
var cornerPositions = cornerPositionsScratch;
Cartesian3.fromRadians(rectangle.west, rectangle.south, height, ellipsoid, cornerPositions[0]);
Cartesian3.fromRadians(rectangle.east, rectangle.south, height, ellipsoid, cornerPositions[1]);
Cartesian3.fromRadians(rectangle.west, rectangle.north, height, ellipsoid, cornerPositions[2]);
Cartesian3.fromRadians(rectangle.east, rectangle.north, height, ellipsoid, cornerPositions[3]);
return ellipsoidalOccluder.computeHorizonCullingPoint(center, cornerPositions, result);
}
/**
* Gets the distance from the camera to the closest point on the tile. This is used for level-of-detail selection.
*
* @param {QuadtreeTile} tile The tile instance.
* @param {FrameState} frameState The state information of the current rendering frame.
*
* @returns {Number} The distance from the camera to the closest point on the tile, in meters.
*/
GlobeSurfaceTileProvider.prototype.computeDistanceToTile = function(tile, frameState) {
// The distance should be:
// 1. the actual distance to the tight-fitting bounding volume, or
// 2. a distance that is equal to or greater than the actual distance to the tight-fitting bounding volume.
//
// When we don't know the min/max heights for a tile, but we do know the min/max of an ancestor tile, we can
// build a tight-fitting bounding volume horizontally, but not vertically. The min/max heights from the
// ancestor will likely form a volume that is much bigger than it needs to be. This means that the volume may
// be deemed to be much closer to the camera than it really is, causing us to select tiles that are too detailed.
// Loading too-detailed tiles is super expensive, so we don't want to do that. We don't know where the child
// tile really lies within the parent range of heights, but we _do_ know the child tile can't be any closer than
// the ancestor height surface (min or max) that is _farthest away_ from the camera. So if we compute distance
// based that conservative metric, we may end up loading tiles that are not detailed enough, but that's much
// better (faster) than loading tiles that are too detailed.
var heightSource = updateTileBoundingRegion(tile, this.terrainProvider, frameState);
var surfaceTile = tile.data;
var tileBoundingRegion = surfaceTile.tileBoundingRegion;
if (heightSource === undefined) {
// Can't find any min/max heights anywhere? Ok, let's just say the
// tile is really far away so we'll load and render it rather than
// refining.
return 9999999999.0;
} else if (surfaceTile.boundingVolumeSourceTile !== heightSource) {
// Heights are from a new source tile, so update the bounding volume.
surfaceTile.boundingVolumeSourceTile = heightSource;
surfaceTile.orientedBoundingBox = OrientedBoundingBox.fromRectangle(
tile.rectangle,
tileBoundingRegion.minimumHeight,
tileBoundingRegion.maximumHeight,
tile.tilingScheme.ellipsoid,
surfaceTile.orientedBoundingBox);
surfaceTile.occludeePointInScaledSpace = computeOccludeePoint(this, surfaceTile.orientedBoundingBox.center, tile.rectangle, tileBoundingRegion.maximumHeight, surfaceTile.occludeePointInScaledSpace);
}
var min = tileBoundingRegion.minimumHeight;
var max = tileBoundingRegion.maximumHeight;
if (surfaceTile.boundingVolumeSourceTile !== tile) {
var cameraHeight = frameState.camera.positionCartographic.height;
var distanceToMin = Math.abs(cameraHeight - min);
var distanceToMax = Math.abs(cameraHeight - max);
if (distanceToMin > distanceToMax) {
tileBoundingRegion.minimumHeight = min;
tileBoundingRegion.maximumHeight = min;
} else {
tileBoundingRegion.minimumHeight = max;
tileBoundingRegion.maximumHeight = max;
}
}
var result = tileBoundingRegion.distanceToCamera(frameState);
tileBoundingRegion.minimumHeight = min;
tileBoundingRegion.maximumHeight = max;
return result;
};
function updateTileBoundingRegion(tile, terrainProvider, frameState) {
var surfaceTile = tile.data;
if (surfaceTile === undefined) {
surfaceTile = tile.data = new GlobeSurfaceTile();
}
if (surfaceTile.tileBoundingRegion === undefined) {
surfaceTile.tileBoundingRegion = new TileBoundingRegion({
computeBoundingVolumes : false,
rectangle : tile.rectangle,
ellipsoid : tile.tilingScheme.ellipsoid,
minimumHeight : 0.0,
maximumHeight : 0.0
});
}
var terrainData = surfaceTile.terrainData;
var mesh = surfaceTile.mesh;
var tileBoundingRegion = surfaceTile.tileBoundingRegion;
if (mesh !== undefined && mesh.minimumHeight !== undefined && mesh.maximumHeight !== undefined) {
// We have tight-fitting min/max heights from the mesh.
tileBoundingRegion.minimumHeight = mesh.minimumHeight;
tileBoundingRegion.maximumHeight = mesh.maximumHeight;
return tile;
}
if (terrainData !== undefined && terrainData._minimumHeight !== undefined && terrainData._maximumHeight !== undefined) {
// We have tight-fitting min/max heights from the terrain data.
tileBoundingRegion.minimumHeight = terrainData._minimumHeight * frameState.terrainExaggeration;
tileBoundingRegion.maximumHeight = terrainData._maximumHeight * frameState.terrainExaggeration;
return tile;
}
var bvh = surfaceTile.getBoundingVolumeHierarchy(tile);
if (bvh !== undefined && bvh[0] === bvh[0] && bvh[1] === bvh[1]) {
// Have a BVH that covers this tile and the heights are not NaN.
tileBoundingRegion.minimumHeight = bvh[0] * frameState.terrainExaggeration;
tileBoundingRegion.maximumHeight = bvh[1] * frameState.terrainExaggeration;
return tile;
}
// No accurate BVH data available, so we're stuck with min/max heights from an ancestor tile.
tileBoundingRegion.minimumHeight = Number.NaN;
tileBoundingRegion.maximumHeight = Number.NaN;
var ancestor = tile.parent;
while (ancestor !== undefined) {
var ancestorSurfaceTile = ancestor.data;
if (ancestorSurfaceTile !== undefined) {
var ancestorMesh = ancestorSurfaceTile.mesh;
if (ancestorMesh !== undefined && ancestorMesh.minimumHeight !== undefined && ancestorMesh.maximumHeight !== undefined) {
tileBoundingRegion.minimumHeight = ancestorMesh.minimumHeight;
tileBoundingRegion.maximumHeight = ancestorMesh.maximumHeight;
return ancestor;
}
var ancestorTerrainData = ancestorSurfaceTile.terrainData;
if (ancestorTerrainData !== undefined && ancestorTerrainData._minimumHeight !== undefined && ancestorTerrainData._maximumHeight !== undefined) {
tileBoundingRegion.minimumHeight = ancestorTerrainData._minimumHeight * frameState.terrainExaggeration;
tileBoundingRegion.maximumHeight = ancestorTerrainData._maximumHeight * frameState.terrainExaggeration;
return ancestor;
}
var ancestorBvh = ancestorSurfaceTile._bvh;
if (ancestorBvh !== undefined && ancestorBvh[0] === ancestorBvh[0] && ancestorBvh[1] === ancestorBvh[1]) {
tileBoundingRegion.minimumHeight = ancestorBvh[0] * frameState.terrainExaggeration;
tileBoundingRegion.maximumHeight = ancestorBvh[1] * frameState.terrainExaggeration;
return ancestor;
}
}
ancestor = ancestor.parent;
}
return undefined;
}
/**
* Returns true if this object was destroyed; otherwise, false.
* <br /><br />
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {Boolean} True if this object was destroyed; otherwise, false.
*
* @see GlobeSurfaceTileProvider#destroy
*/
GlobeSurfaceTileProvider.prototype.isDestroyed = function() {
return false;
};
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
*
* @example
* provider = provider && provider();
*
* @see GlobeSurfaceTileProvider#isDestroyed
*/
GlobeSurfaceTileProvider.prototype.destroy = function() {
this._tileProvider = this._tileProvider && this._tileProvider.destroy();
this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();
return destroyObject(this);
};
function getTileReadyCallback(tileImageriesToFree, layer, terrainProvider) {
return function(tile) {
var tileImagery;
var imagery;
var startIndex = -1;
var tileImageryCollection = tile.data.imagery;
var length = tileImageryCollection.length;
var i;
for (i = 0; i < length; ++i) {
tileImagery = tileImageryCollection[i];
imagery = defaultValue(tileImagery.readyImagery, tileImagery.loadingImagery);
if (imagery.imageryLayer === layer) {
startIndex = i;
break;
}
}
if (startIndex !== -1) {
var endIndex = startIndex + tileImageriesToFree;
tileImagery = tileImageryCollection[endIndex];
imagery = defined(tileImagery) ? defaultValue(tileImagery.readyImagery, tileImagery.loadingImagery) : undefined;
if (!defined(imagery) || imagery.imageryLayer !== layer) {
// Return false to keep the callback if we have to wait on the skeletons
// Return true to remove the callback if something went wrong
return !(layer._createTileImagerySkeletons(tile, terrainProvider, endIndex));
}
for (i = startIndex; i < endIndex; ++i) {
tileImageryCollection[i].freeResources();
}
tileImageryCollection.splice(startIndex, tileImageriesToFree);
}
return true; // Everything is done, so remove the callback
};
}
GlobeSurfaceTileProvider.prototype._onLayerAdded = function(layer, index) {
if (layer.show) {
var terrainProvider = this._terrainProvider;
var that = this;
var imageryProvider = layer.imageryProvider;
var tileImageryUpdatedEvent = this._imageryLayersUpdatedEvent;
imageryProvider._reload = function() {
// Clear the layer's cache
layer._imageryCache = {};
that._quadtree.forEachLoadedTile(function(tile) {
// If this layer is still waiting to for the loaded callback, just return
if (defined(tile._loadedCallbacks[layer._layerIndex])) {
return;
}