/
CentralBodySurface.js
1506 lines (1253 loc) · 63 KB
/
CentralBodySurface.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
/*global define*/
define([
'../Core/defaultValue',
'../Core/destroyObject',
'../Core/BoundingSphere',
'../Core/BoundingRectangle',
'../Core/Cartesian2',
'../Core/Cartesian3',
'../Core/Cartesian4',
'../Core/CubeMapEllipsoidTessellator',
'../Core/DeveloperError',
'../Core/Ellipsoid',
'../Core/EllipsoidalOccluder',
'../Core/Intersect',
'../Core/Matrix4',
'../Core/MeshFilters',
'../Core/Occluder',
'../Core/PrimitiveType',
'../Core/Queue',
'../Core/TaskProcessor',
'../Core/WebMercatorProjection',
'../Renderer/DrawCommand',
'../Renderer/PixelDatatype',
'../Renderer/PixelFormat',
'../Renderer/TextureMagnificationFilter',
'../Renderer/TextureMinificationFilter',
'../Renderer/TextureWrap',
'./ImageryLayer',
'./ImageryState',
'./SceneMode',
'./TerrainProvider',
'./TerrainState',
'./TileLoadQueue',
'./TileReplacementQueue',
'./TileState',
'./TileTerrain',
'../ThirdParty/when'
], function(
defaultValue,
destroyObject,
BoundingSphere,
BoundingRectangle,
Cartesian2,
Cartesian3,
Cartesian4,
CubeMapEllipsoidTessellator,
DeveloperError,
Ellipsoid,
EllipsoidalOccluder,
Intersect,
Matrix4,
MeshFilters,
Occluder,
PrimitiveType,
Queue,
TaskProcessor,
WebMercatorProjection,
DrawCommand,
PixelDatatype,
PixelFormat,
TextureMagnificationFilter,
TextureMinificationFilter,
TextureWrap,
ImageryLayer,
ImageryState,
SceneMode,
TerrainProvider,
TerrainState,
TileLoadQueue,
TileReplacementQueue,
TileState,
TileTerrain,
when) {
"use strict";
/**
* Manages and renders the terrain and imagery on the surface of a {@link CentralBody}.
* This class should be considered an implementation detail of {@link CentralBody} and not
* used directly.
*
* @alias CentralBodySurface
* @constructor
* @private
*/
var CentralBodySurface = function(description) {
if (typeof description.terrainProvider === 'undefined') {
throw new DeveloperError('description.terrainProvider is required.');
}
if (typeof description.imageryLayerCollection === 'undefined') {
throw new DeveloperError('description.imageryLayerCollection is required.');
}
this._terrainProvider = description.terrainProvider;
this._imageryLayerCollection = description.imageryLayerCollection;
this._maxScreenSpaceError = defaultValue(description.maxScreenSpaceError, 2);
this._imageryLayerCollection.layerAdded.addEventListener(CentralBodySurface.prototype._onLayerAdded, this);
this._imageryLayerCollection.layerRemoved.addEventListener(CentralBodySurface.prototype._onLayerRemoved, this);
this._imageryLayerCollection.layerMoved.addEventListener(CentralBodySurface.prototype._onLayerMoved, this);
this._imageryLayerCollection.layerShownOrHidden.addEventListener(CentralBodySurface.prototype._onLayerShownOrHidden, this);
this._layerOrderChanged = false;
var terrainTilingScheme = this._terrainProvider.getTilingScheme();
this._levelZeroTiles = terrainTilingScheme.createLevelZeroTiles();
this._tilesToRenderByTextureCount = [];
this._tileCommands = [];
this._tileCommandUniformMaps = [];
this._tileTraversalQueue = new Queue();
this._tileLoadQueue = new TileLoadQueue();
this._tileReplacementQueue = new TileReplacementQueue();
this._tileCacheSize = 100;
// The number of milliseconds each frame to allow for processing the tile load queue.
// At least one tile will be processed per frame (assuming that any need processing),
// even if this value is 0.
this._loadQueueTimeSlice = 5;
var ellipsoid = terrainTilingScheme.getEllipsoid();
this._ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid, Cartesian3.ZERO);
this._waterMaskSampler = undefined;
this._allWaterTexture = undefined;
this._allLandTexture = undefined;
this._debug = {
enableDebugOutput : false,
boundingSphereTile : undefined,
boundingSphereVA : undefined,
maxDepth : 0,
tilesVisited : 0,
tilesCulled : 0,
tilesRendered : 0,
texturesRendered : 0,
tilesWaitingForChildren : 0,
lastMaxDepth : -1,
lastTilesVisited : -1,
lastTilesCulled : -1,
lastTilesRendered : -1,
lastTexturesRendered : -1,
lastTilesWaitingForChildren : -1,
suspendLodUpdate : false
};
};
CentralBodySurface.prototype.update = function(context, frameState, colorCommandList, centralBodyUniformMap, shaderSet, renderState, mode, projection) {
updateLayers(this);
selectTilesForRendering(this, context, frameState);
processTileLoadQueue(this, context, frameState);
createRenderCommandsForSelectedTiles(this, context, frameState, shaderSet, mode, projection, centralBodyUniformMap, colorCommandList, renderState);
debugCreateRenderCommandsForTileBoundingSphere(this, context, frameState, centralBodyUniformMap, shaderSet, renderState, colorCommandList);
};
CentralBodySurface.prototype.getTerrainProvider = function() {
return this._terrainProvider;
};
CentralBodySurface.prototype.setTerrainProvider = function(terrainProvider) {
if (this._terrainProvider === terrainProvider) {
return;
}
if (typeof terrainProvider === 'undefined') {
throw new DeveloperError('terrainProvider is required.');
}
this._terrainProvider = terrainProvider;
// Clear the replacement queue
var replacementQueue = this._tileReplacementQueue;
replacementQueue.head = undefined;
replacementQueue.tail = undefined;
replacementQueue.count = 0;
// Free and recreate the level zero tiles.
var levelZeroTiles = this._levelZeroTiles;
for (var i = 0; i < levelZeroTiles.length; ++i) {
levelZeroTiles[i].freeResources();
}
var terrainTilingScheme = this._terrainProvider.getTilingScheme();
this._levelZeroTiles = terrainTilingScheme.createLevelZeroTiles();
};
CentralBodySurface.prototype._onLayerAdded = function(layer, index) {
if (typeof this._levelZeroTiles === 'undefined') {
return;
}
// create TileImagerys for this layer for all previously loaded tiles
if (layer.show) {
var tile = this._tileReplacementQueue.head;
while (typeof tile !== 'undefined') {
if (layer._createTileImagerySkeletons(tile, this._terrainProvider)) {
tile.state = TileState.LOADING;
}
tile = tile.replacementNext;
}
this._layerOrderChanged = true;
}
};
CentralBodySurface.prototype._onLayerRemoved = function(layer, index) {
if (typeof this._levelZeroTiles === 'undefined') {
return;
}
// destroy TileImagerys for this layer for all previously loaded tiles
var tile = this._tileReplacementQueue.head;
while (typeof tile !== 'undefined') {
var tileImageryCollection = tile.imagery;
var startIndex = -1;
var numDestroyed = 0;
for ( var i = 0, len = tileImageryCollection.length; i < len; ++i) {
var tileImagery = tileImageryCollection[i];
var imagery = tileImagery.imagery;
if (imagery.imageryLayer === layer) {
if (startIndex === -1) {
startIndex = i;
}
tileImagery.freeResources();
++numDestroyed;
} else if (startIndex !== -1) {
// iterated past the section of TileImagerys belonging to this layer, no need to continue.
break;
}
}
if (startIndex !== -1) {
tileImageryCollection.splice(startIndex, numDestroyed);
}
// If the base layer has been removed, mark the tile as non-renderable.
if (layer.isBaseLayer()) {
tile.isRenderable = false;
}
tile = tile.replacementNext;
}
};
CentralBodySurface.prototype._onLayerMoved = function(layer, newIndex, oldIndex) {
if (typeof this._levelZeroTiles === 'undefined') {
return;
}
this._layerOrderChanged = true;
};
CentralBodySurface.prototype._onLayerShownOrHidden = function(layer, index, show) {
if (typeof this._levelZeroTiles === 'undefined') {
return;
}
if (show) {
this._onLayerAdded(layer, index);
} else {
this._onLayerRemoved(layer, index);
}
};
/**
* 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.
*
* @memberof CentralBodySurface
*
* @return {Boolean} True if this object was destroyed; otherwise, false.
*
* @see CentralBodySurface#destroy
*/
CentralBodySurface.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.
*
* @memberof CentralBodySurface
*
* @return {undefined}
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see CentralBodySurface#isDestroyed
*/
CentralBodySurface.prototype.destroy = function() {
var levelZeroTiles = this._levelZeroTiles;
for (var i = 0; i < levelZeroTiles.length; ++i) {
levelZeroTiles[i].freeResources();
}
this._imageryLayerCollection.destroy();
var debug = this._debug;
if (typeof debug !== 'undefined') {
if (typeof debug.boundingSphereVA !== 'undefined') {
debug.boundingSphereVA.destroy();
}
}
if (typeof this._allWaterTexture !== 'undefined') {
this._allWaterTexture.destroy();
}
if (typeof this._allLandTexture !== 'undefined') {
this._allLandTexture.destroy();
}
return destroyObject(this);
};
function sortTileImageryByLayerIndex(a, b) {
return a.imagery.imageryLayer._layerIndex - b.imagery.imageryLayer._layerIndex;
}
function updateLayers(surface) {
surface._imageryLayerCollection._update();
if (surface._layerOrderChanged) {
surface._layerOrderChanged = false;
// Sort the TileImagery instances in each tile by the layer index.
var tile = surface._tileReplacementQueue.head;
while (typeof tile !== 'undefined') {
tile.imagery.sort(sortTileImageryByLayerIndex);
tile = tile.replacementNext;
}
}
}
function selectTilesForRendering(surface, context, frameState) {
var debug = surface._debug;
if (debug.suspendLodUpdate) {
return;
}
var i, len;
// Clear the render list.
var tilesToRenderByTextureCount = surface._tilesToRenderByTextureCount;
for (i = 0, len = tilesToRenderByTextureCount.length; i < len; ++i) {
var tiles = tilesToRenderByTextureCount[i];
if (typeof tiles !== 'undefined') {
tiles.length = 0;
}
}
// We can't render anything before the level zero tiles exist.
if (typeof surface._levelZeroTiles === 'undefined') {
return;
}
var traversalQueue = surface._tileTraversalQueue;
traversalQueue.clear();
debug.maxDepth = 0;
debug.tilesVisited = 0;
debug.tilesCulled = 0;
debug.tilesRendered = 0;
debug.texturesRendered = 0;
debug.tilesWaitingForChildren = 0;
surface._tileLoadQueue.clear();
surface._tileLoadQueue.markInsertionPoint();
surface._tileReplacementQueue.markStartOfRenderFrame();
var cameraPosition = frameState.camera.getPositionWC();
var ellipsoid = surface._terrainProvider.getTilingScheme().getEllipsoid();
var cameraPositionCartographic = ellipsoid.cartesianToCartographic(cameraPosition);
surface._ellipsoidalOccluder.setCameraPosition(cameraPosition);
var tile;
// Enqueue the root tiles that are renderable and visible.
var levelZeroTiles = surface._levelZeroTiles;
for (i = 0, len = levelZeroTiles.length; i < len; ++i) {
tile = levelZeroTiles[i];
if (tile.state !== TileState.READY) {
queueTileLoad(surface, tile);
}
if (tile.isRenderable && isTileVisible(surface, frameState, tile)) {
traversalQueue.enqueue(tile);
} else {
++debug.tilesCulled;
}
}
// Traverse the tiles in breadth-first order.
// This ordering allows us to load bigger, lower-detail tiles before smaller, higher-detail ones.
// This maximizes the average detail across the scene and results in fewer sharp transitions
// between very different LODs.
while (typeof (tile = traversalQueue.dequeue()) !== 'undefined') {
++debug.tilesVisited;
surface._tileReplacementQueue.markTileRendered(tile);
if (tile.level > debug.maxDepth) {
debug.maxDepth = tile.level;
}
// There are a few different algorithms we could use here.
// This one doesn't load children unless we refine to them.
// We may want to revisit this in the future.
if (screenSpaceError(surface, context, frameState, cameraPosition, cameraPositionCartographic, tile) < surface._maxScreenSpaceError) {
// This tile meets SSE requirements, so render it.
addTileToRenderList(surface, tile);
} else if (queueChildrenLoadAndDetermineIfChildrenAreAllRenderable(surface, frameState, tile)) {
// SSE is not good enough and children are loaded, so refine.
var children = tile.children;
// PERFORMANCE_IDEA: traverse children front-to-back so we can avoid sorting by distance later.
for (i = 0, len = children.length; i < len; ++i) {
if (isTileVisible(surface, frameState, children[i])) {
traversalQueue.enqueue(children[i]);
} else {
++debug.tilesCulled;
}
}
} else {
++debug.tilesWaitingForChildren;
// SSE is not good enough but not all children are loaded, so render this tile anyway.
addTileToRenderList(surface, tile);
}
}
if (debug.enableDebugOutput) {
if (debug.tilesVisited !== debug.lastTilesVisited ||
debug.tilesRendered !== debug.lastTilesRendered ||
debug.texturesRendered !== debug.lastTexturesRendered ||
debug.tilesCulled !== debug.lastTilesCulled ||
debug.maxDepth !== debug.lastMaxDepth ||
debug.tilesWaitingForChildren !== debug.lastTilesWaitingForChildren) {
/*global console*/
console.log('Visited ' + debug.tilesVisited + ', Rendered: ' + debug.tilesRendered + ', Textures: ' + debug.texturesRendered + ', Culled: ' + debug.tilesCulled + ', Max Depth: ' + debug.maxDepth + ', Waiting for children: ' + debug.tilesWaitingForChildren);
debug.lastTilesVisited = debug.tilesVisited;
debug.lastTilesRendered = debug.tilesRendered;
debug.lastTexturesRendered = debug.texturesRendered;
debug.lastTilesCulled = debug.tilesCulled;
debug.lastMaxDepth = debug.maxDepth;
debug.lastTilesWaitingForChildren = debug.tilesWaitingForChildren;
}
}
}
function screenSpaceError(surface, context, frameState, cameraPosition, cameraPositionCartographic, tile) {
if (frameState.mode === SceneMode.SCENE2D) {
return screenSpaceError2D(surface, context, frameState, cameraPosition, cameraPositionCartographic, tile);
}
var extent = tile.extent;
var latitudeFactor = 1.0;
// Adjust by latitude in 3D only.
if (frameState.mode === SceneMode.SCENE3D) {
var latitudeClosestToEquator = 0.0;
if (extent.south > 0.0) {
latitudeClosestToEquator = extent.south;
} else if (extent.north < 0.0) {
latitudeClosestToEquator = extent.north;
}
latitudeFactor = Math.cos(latitudeClosestToEquator);
}
var maxGeometricError = latitudeFactor * surface._terrainProvider.getLevelMaximumGeometricError(tile.level);
var distance = Math.sqrt(distanceSquaredToTile(frameState, cameraPosition, cameraPositionCartographic, tile));
tile.distance = distance;
var canvas = context.getCanvas();
var height = canvas.clientHeight;
var camera = frameState.camera;
var frustum = camera.frustum;
var fovy = frustum.fovy;
// PERFORMANCE_IDEA: factor out stuff that's constant across tiles.
return (maxGeometricError * height) / (2 * distance * Math.tan(0.5 * fovy));
}
function screenSpaceError2D(surface, context, frameState, cameraPosition, cameraPositionCartographic, tile) {
var camera = frameState.camera;
var frustum = camera.frustum;
var canvas = context.getCanvas();
var width = canvas.clientWidth;
var height = canvas.clientHeight;
var maxGeometricError = surface._terrainProvider.getLevelMaximumGeometricError(tile.level);
var pixelSize = Math.max(frustum.top - frustum.bottom, frustum.right - frustum.left) / Math.max(width, height);
return maxGeometricError / pixelSize;
}
function addTileToRenderList(surface, tile) {
var readyTextureCount = 0;
var tileImageryCollection = tile.imagery;
for ( var i = 0, len = tileImageryCollection.length; i < len; ++i) {
var tileImagery = tileImageryCollection[i];
if (tileImagery.imagery.state === ImageryState.READY) {
++readyTextureCount;
}
}
var tileSet = surface._tilesToRenderByTextureCount[readyTextureCount];
if (typeof tileSet === 'undefined') {
tileSet = [];
surface._tilesToRenderByTextureCount[readyTextureCount] = tileSet;
}
tileSet.push(tile);
var debug = surface._debug;
++debug.tilesRendered;
debug.texturesRendered += readyTextureCount;
}
var boundingSphereScratch = new BoundingSphere();
function isTileVisible(surface, frameState, tile) {
var cullingVolume = frameState.cullingVolume;
var boundingVolume = tile.boundingSphere3D;
if (frameState.mode !== SceneMode.SCENE3D) {
boundingVolume = boundingSphereScratch;
BoundingSphere.fromExtentWithHeights2D(tile.extent, frameState.scene2D.projection, tile.minimumHeight, tile.maximumHeight, boundingVolume);
boundingVolume.center = new Cartesian3(boundingVolume.center.z, boundingVolume.center.x, boundingVolume.center.y);
if (frameState.mode === SceneMode.MORPHING) {
boundingVolume = BoundingSphere.union(tile.boundingSphere3D, boundingVolume, boundingVolume);
}
}
if (cullingVolume.getVisibility(boundingVolume) === Intersect.OUTSIDE) {
return false;
}
if (frameState.mode === SceneMode.SCENE3D) {
var occludeePointInScaledSpace = tile.occludeePointInScaledSpace;
if (typeof occludeePointInScaledSpace === 'undefined') {
return true;
}
return surface._ellipsoidalOccluder.isScaledSpacePointVisible(occludeePointInScaledSpace);
}
return true;
}
var southwestCornerScratch = new Cartesian3();
var northeastCornerScratch = new Cartesian3();
var negativeUnitY = Cartesian3.UNIT_Y.negate();
var negativeUnitZ = Cartesian3.UNIT_Z.negate();
var vectorScratch = new Cartesian3();
function distanceSquaredToTile(frameState, cameraCartesianPosition, cameraCartographicPosition, tile) {
var southwestCornerCartesian = tile.southwestCornerCartesian;
var northeastCornerCartesian = tile.northeastCornerCartesian;
var westNormal = tile.westNormal;
var southNormal = tile.southNormal;
var eastNormal = tile.eastNormal;
var northNormal = tile.northNormal;
var maximumHeight = tile.maximumHeight;
if (frameState.mode !== SceneMode.SCENE3D) {
southwestCornerCartesian = frameState.scene2D.projection.project(tile.extent.getSouthwest(), southwestCornerScratch);
southwestCornerCartesian.z = southwestCornerCartesian.y;
southwestCornerCartesian.y = southwestCornerCartesian.x;
southwestCornerCartesian.x = 0.0;
northeastCornerCartesian = frameState.scene2D.projection.project(tile.extent.getNortheast(), northeastCornerScratch);
northeastCornerCartesian.z = northeastCornerCartesian.y;
northeastCornerCartesian.y = northeastCornerCartesian.x;
northeastCornerCartesian.x = 0.0;
westNormal = negativeUnitY;
eastNormal = Cartesian3.UNIT_Y;
southNormal = negativeUnitZ;
northNormal = Cartesian3.UNIT_Z;
maximumHeight = 0.0;
}
var vectorFromSouthwestCorner = cameraCartesianPosition.subtract(southwestCornerCartesian, vectorScratch);
var distanceToWestPlane = vectorFromSouthwestCorner.dot(westNormal);
var distanceToSouthPlane = vectorFromSouthwestCorner.dot(southNormal);
var vectorFromNortheastCorner = cameraCartesianPosition.subtract(northeastCornerCartesian, vectorScratch);
var distanceToEastPlane = vectorFromNortheastCorner.dot(eastNormal);
var distanceToNorthPlane = vectorFromNortheastCorner.dot(northNormal);
var cameraHeight;
if (frameState.mode === SceneMode.SCENE3D) {
cameraHeight = cameraCartographicPosition.height;
} else {
cameraHeight = cameraCartesianPosition.x;
}
var distanceFromTop = cameraHeight - maximumHeight;
var result = 0.0;
if (distanceToWestPlane > 0.0) {
result += distanceToWestPlane * distanceToWestPlane;
} else if (distanceToEastPlane > 0.0) {
result += distanceToEastPlane * distanceToEastPlane;
}
if (distanceToSouthPlane > 0.0) {
result += distanceToSouthPlane * distanceToSouthPlane;
} else if (distanceToNorthPlane > 0.0) {
result += distanceToNorthPlane * distanceToNorthPlane;
}
if (distanceFromTop > 0.0) {
result += distanceFromTop * distanceFromTop;
}
return result;
}
function queueChildrenLoadAndDetermineIfChildrenAreAllRenderable(surface, frameState, tile) {
var allRenderable = true;
var children = tile.getChildren();
for (var i = 0, len = children.length; i < len; ++i) {
var child = children[i];
surface._tileReplacementQueue.markTileRendered(child);
if (child.state !== TileState.READY) {
queueTileLoad(surface, child);
}
if (!child.isRenderable) {
allRenderable = false;
}
}
return allRenderable;
}
function queueTileLoad(surface, tile) {
surface._tileLoadQueue.insertBeforeInsertionPoint(tile);
}
function processTileLoadQueue(surface, context, frameState) {
var tileLoadQueue = surface._tileLoadQueue;
var terrainProvider = surface._terrainProvider;
var tile = tileLoadQueue.head;
if (typeof tile === 'undefined') {
return;
}
// Remove any tiles that were not used this frame beyond the number
// we're allowed to keep.
surface._tileReplacementQueue.trimTiles(surface._tileCacheSize);
var startTime = Date.now();
var timeSlice = surface._loadQueueTimeSlice;
var endTime = startTime + timeSlice;
do {
var i, len;
if (tile.state === TileState.START) {
prepareNewTile(surface, terrainProvider, tile);
tile.state = TileState.LOADING;
}
if (tile.state === TileState.LOADING) {
processTerrainStateMachine(surface, context, terrainProvider, tile);
}
var isRenderable = typeof tile.vertexArray !== 'undefined';
var isDoneLoading = typeof tile.loadedTerrain === 'undefined' && typeof tile.upsampledTerrain === 'undefined';
var didSomeWork = false;
// Transition imagery states
var tileImageryCollection = tile.imagery;
for (i = 0, len = tileImageryCollection.length; i < len; ++i) {
if (didSomeWork && Date.now() >= endTime) {
break;
}
var tileImagery = tileImageryCollection[i];
var imagery = tileImagery.imagery;
var imageryLayer = imagery.imageryLayer;
if (imagery.state === ImageryState.PLACEHOLDER) {
if (imageryLayer.getImageryProvider().isReady()) {
// Remove the placeholder and add the actual skeletons (if any)
// at the same position. Then continue the loop at the same index.
tileImagery.freeResources();
tileImageryCollection.splice(i, 1);
imageryLayer._createTileImagerySkeletons(tile, terrainProvider, i);
--i;
len = tileImageryCollection.length;
}
didSomeWork = true;
}
if (imagery.state === ImageryState.UNLOADED) {
imagery.state = ImageryState.TRANSITIONING;
imageryLayer._requestImagery(imagery);
didSomeWork = true;
}
if (imagery.state === ImageryState.RECEIVED) {
imagery.state = ImageryState.TRANSITIONING;
imageryLayer._createTexture(context, imagery);
didSomeWork = true;
}
if (imagery.state === ImageryState.TEXTURE_LOADED) {
imagery.state = ImageryState.TRANSITIONING;
imageryLayer._reprojectTexture(context, imagery);
didSomeWork = true;
}
if (imagery.state === ImageryState.FAILED || imagery.state === ImageryState.INVALID) {
// re-associate TileImagery with a parent Imagery that is not failed or invalid.
var parent = imagery.parent;
while (typeof parent !== 'undefined' && (parent.state === ImageryState.FAILED || parent.state === ImageryState.INVALID)) {
parent = parent.parent;
}
// If there's no valid parent, remove this TileImagery from the tile.
if (typeof parent === 'undefined') {
tileImagery.freeResources();
tileImageryCollection.splice(i, 1);
--i;
len = tileImageryCollection.length;
continue;
}
// use that parent imagery instead, storing the original imagery
// in originalImagery to keep it alive
tileImagery.originalImagery = imagery;
parent.addReference();
tileImagery.imagery = parent;
imagery = parent;
didSomeWork = true;
}
var imageryDoneLoading = imagery.state === ImageryState.READY;
if (imageryDoneLoading && typeof tileImagery.textureTranslationAndScale === 'undefined') {
tileImagery.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(tile, tileImagery);
didSomeWork = true;
}
isRenderable = isRenderable && imageryDoneLoading;
isDoneLoading = isDoneLoading && imageryDoneLoading;
}
var next = tile.loadNext;
// The tile becomes renderable when the terrain and all imagery data are loaded.
if (i === len && isRenderable) {
tile.isRenderable = true;
if (isDoneLoading) {
tile.state = TileState.READY;
tileLoadQueue.remove(tile);
}
}
tile = next;
} while (Date.now() < endTime && typeof tile !== 'undefined');
}
var cartesian3Scratch = new Cartesian3();
var cartesian3Scratch2 = new Cartesian3();
var southeastScratch = new Cartesian3();
var northwestScratch = new Cartesian3();
function prepareNewTile(surface, terrainProvider, tile) {
surface._tileReplacementQueue.markTileRendered(tile);
var upsampleTileDetails = getUpsampleTileDetails(surface, tile);
if (typeof upsampleTileDetails !== 'undefined') {
tile.upsampledTerrain = new TileTerrain(upsampleTileDetails);
}
if (isDataAvailable(tile)) {
tile.loadedTerrain = new TileTerrain();
}
// Map imagery tiles to this terrain tile
var imageryLayerCollection = surface._imageryLayerCollection;
for (var i = 0, len = imageryLayerCollection.getLength(); i < len; ++i) {
var layer = imageryLayerCollection.get(i);
if (layer.show) {
layer._createTileImagerySkeletons(tile, terrainProvider);
}
}
var ellipsoid = tile.tilingScheme.getEllipsoid();
// Compute tile extent boundaries for estimating the distance to the tile.
var extent = tile.extent;
ellipsoid.cartographicToCartesian(extent.getSouthwest(), tile.southwestCornerCartesian);
var southeastCornerCartesian = ellipsoid.cartographicToCartesian(extent.getSoutheast(), southeastScratch);
ellipsoid.cartographicToCartesian(extent.getNortheast(), tile.northeastCornerCartesian);
var northwestCornerCartesian = ellipsoid.cartographicToCartesian(extent.getNorthwest(), northwestScratch);
Cartesian3.UNIT_Z.cross(tile.southwestCornerCartesian.negate(cartesian3Scratch), cartesian3Scratch).normalize(tile.westNormal);
tile.northeastCornerCartesian.negate(cartesian3Scratch).cross(Cartesian3.UNIT_Z, cartesian3Scratch).normalize(tile.eastNormal);
ellipsoid.geodeticSurfaceNormal(southeastCornerCartesian, cartesian3Scratch).cross(tile.southwestCornerCartesian.subtract(southeastCornerCartesian, cartesian3Scratch2), cartesian3Scratch).normalize(tile.southNormal);
ellipsoid.geodeticSurfaceNormal(northwestCornerCartesian, cartesian3Scratch).cross(tile.northeastCornerCartesian.subtract(northwestCornerCartesian, cartesian3Scratch2), cartesian3Scratch).normalize(tile.northNormal);
}
function processTerrainStateMachine(surface, context, terrainProvider, tile) {
var loaded = tile.loadedTerrain;
var upsampled = tile.upsampledTerrain;
var suspendUpsampling = false;
if (typeof loaded !== 'undefined') {
loaded.processLoadStateMachine(context, terrainProvider, tile.x, tile.y, tile.level);
// Publish the terrain data on the tile as soon as it is available.
// We'll potentially need it to upsample child tiles.
if (loaded.state.value >= TerrainState.RECEIVED.value) {
if (tile.terrainData !== loaded.data) {
tile.terrainData = loaded.data;
// If there's a water mask included in the terrain data, create a
// texture for it.
var waterMask = tile.terrainData.getWaterMask();
if (typeof waterMask !== 'undefined') {
if (typeof tile.waterMaskTexture !== 'undefined') {
--tile.waterMaskTexture.referenceCount;
if (tile.waterMaskTexture.referenceCount === 0) {
tile.waterMaskTexture.destroy();
}
}
tile.waterMaskTexture = createWaterMaskTexture(surface, context, waterMask);
tile.waterMaskTranslationAndScale.x = 0.0;
tile.waterMaskTranslationAndScale.y = 0.0;
tile.waterMaskTranslationAndScale.z = 1.0;
tile.waterMaskTranslationAndScale.w = 1.0;
}
propagateNewLoadedDataToChildren(tile);
}
suspendUpsampling = true;
}
if (loaded.state === TerrainState.READY) {
loaded.publishToTile(tile);
// No further loading or upsampling is necessary.
tile.loadedTerrain = undefined;
tile.upsampledTerrain = undefined;
} else if (loaded.state === TerrainState.FAILED || loaded.state === TerrainState.NOT_AVAILABLE) {
// Loading failed for some reason, or data is simply not available,
// so no need to continue trying to load. Any retrying will happen before we
// reach this point.
tile.loadedTerrain = undefined;
}
}
if (!suspendUpsampling && typeof upsampled !== 'undefined') {
upsampled.processUpsampleStateMachine(context, terrainProvider, tile.x, tile.y, tile.level);
// Publish the terrain data on the tile as soon as it is available.
// We'll potentially need it to upsample child tiles.
// It's safe to overwrite terrainData because we won't get here after
// loaded terrain data has been received.
if (upsampled.state.value >= TerrainState.RECEIVED.value) {
if (tile.terrainData !== upsampled.data) {
tile.terrainData = upsampled.data;
// If the terrain provider has a water mask, "upsample" that as well
// by computing texture translation and scale.
if (terrainProvider.hasWaterMask) {
upsampleWaterMask(surface, context, tile);
}
propagateNewUpsampledDataToChildren(tile);
}
}
if (upsampled.state === TerrainState.READY) {
upsampled.publishToTile(tile);
// No further upsampling is necessary. We need to continue loading, though.
tile.upsampledTerrain = undefined;
} else if (upsampled.state === TerrainState.FAILED || upsampled.state === TerrainState.NOT_AVAILABLE) {
// Upsampling failed for some reason. This is pretty much a catastrophic failure,
// but maybe we'll be saved by loading.
tile.upsampledTerrain = undefined;
}
}
}
function getUpsampleTileDetails(surface, tile) {
// Find the nearest ancestor with loaded terrain.
var sourceTile = tile.parent;
while (typeof sourceTile !== 'undefined' && typeof sourceTile.terrainData === 'undefined') {
sourceTile = sourceTile.parent;
}
if (typeof sourceTile === 'undefined') {
// No ancestors have loaded terrain - try again later.
return undefined;
}
return {
data : sourceTile.terrainData,
x : sourceTile.x,
y : sourceTile.y,
level : sourceTile.level
};
}
function propagateNewUpsampledDataToChildren(tile) {
// Now that there's new data for this tile:
// - child tiles that were previously upsampled need to be re-upsampled based on the new data.
// Generally this is only necessary when a child tile is upsampled, and then one
// of its ancestors receives new (better) data and we want to re-upsample from the
// new data.
if (typeof tile.children !== 'undefined') {
for (var childIndex = 0; childIndex < 4; ++childIndex) {
var childTile = tile.children[childIndex];
if (childTile.state !== TileState.START) {
if (typeof childTile.terrainData !== 'undefined' && !childTile.terrainData.wasCreatedByUpsampling()) {
// Data for the child tile has already been loaded.
continue;
}
// Restart the upsampling process, no matter its current state.
// We create a new instance rather than just restarting the existing one
// because there could be an asynchronous operation pending on the existing one.
if (typeof childTile.upsampledTerrain !== 'undefined') {
childTile.upsampledTerrain.freeResources();
}
childTile.upsampledTerrain = new TileTerrain({
data : tile.terrainData,
x : tile.x,
y : tile.y,
level : tile.level
});
childTile.state = TileState.LOADING;
}
}
}
}
function propagateNewLoadedDataToChildren(tile) {
// Now that there's new data for this tile:
// - child tiles that were previously upsampled need to be re-upsampled based on the new data.
// - child tiles that were previously deemed unavailable may now be available.
if (typeof tile.children !== 'undefined') {
for (var childIndex = 0; childIndex < 4; ++childIndex) {
var childTile = tile.children[childIndex];
if (childTile.state !== TileState.START) {
if (typeof childTile.terrainData !== 'undefined' && !childTile.terrainData.wasCreatedByUpsampling()) {
// Data for the child tile has already been loaded.
continue;
}
// Restart the upsampling process, no matter its current state.
// We create a new instance rather than just restarting the existing one
// because there could be an asynchronous operation pending on the existing one.
if (typeof childTile.upsampledTerrain !== 'undefined') {
childTile.upsampledTerrain.freeResources();
}
childTile.upsampledTerrain = new TileTerrain({
data : tile.terrainData,
x : tile.x,
y : tile.y,
level : tile.level
});
if (tile.terrainData.isChildAvailable(tile.x, tile.y, childTile.x, childTile.y)) {
// Data is available for the child now. It might have been before, too.