-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
ImageryLayer.js
1079 lines (950 loc) · 49.1 KB
/
ImageryLayer.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/Cartesian2',
'../Core/Cartesian4',
'../Core/defaultValue',
'../Core/defined',
'../Core/defineProperties',
'../Core/destroyObject',
'../Core/FeatureDetection',
'../Core/GeographicTilingScheme',
'../Core/IndexDatatype',
'../Core/Math',
'../Core/PixelFormat',
'../Core/Rectangle',
'../Core/TerrainProvider',
'../Core/TileProviderError',
'../Core/WebMercatorProjection',
'../Core/WebMercatorTilingScheme',
'../Renderer/Buffer',
'../Renderer/BufferUsage',
'../Renderer/ComputeCommand',
'../Renderer/ContextLimits',
'../Renderer/MipmapHint',
'../Renderer/Sampler',
'../Renderer/ShaderProgram',
'../Renderer/ShaderSource',
'../Renderer/Texture',
'../Renderer/TextureMagnificationFilter',
'../Renderer/TextureMinificationFilter',
'../Renderer/TextureWrap',
'../Renderer/VertexArray',
'../Shaders/ReprojectWebMercatorFS',
'../Shaders/ReprojectWebMercatorVS',
'../ThirdParty/when',
'./Imagery',
'./ImageryState',
'./TileImagery'
], function(
Cartesian2,
Cartesian4,
defaultValue,
defined,
defineProperties,
destroyObject,
FeatureDetection,
GeographicTilingScheme,
IndexDatatype,
CesiumMath,
PixelFormat,
Rectangle,
TerrainProvider,
TileProviderError,
WebMercatorProjection,
WebMercatorTilingScheme,
Buffer,
BufferUsage,
ComputeCommand,
ContextLimits,
MipmapHint,
Sampler,
ShaderProgram,
ShaderSource,
Texture,
TextureMagnificationFilter,
TextureMinificationFilter,
TextureWrap,
VertexArray,
ReprojectWebMercatorFS,
ReprojectWebMercatorVS,
when,
Imagery,
ImageryState,
TileImagery) {
'use strict';
/**
* An imagery layer that displays tiled image data from a single imagery provider
* on a {@link Globe}.
*
* @alias ImageryLayer
* @constructor
*
* @param {ImageryProvider} imageryProvider The imagery provider to use.
* @param {Object} [options] Object with the following properties:
* @param {Rectangle} [options.rectangle=imageryProvider.rectangle] The rectangle of the layer. This rectangle
* can limit the visible portion of the imagery provider.
* @param {Number|Function} [options.alpha=1.0] The alpha blending value of this layer, from 0.0 to 1.0.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the alpha is required, and it is expected to return
* the alpha value to use for the tile.
* @param {Number|Function} [options.brightness=1.0] The brightness of this layer. 1.0 uses the unmodified imagery
* color. Less than 1.0 makes the imagery darker while greater than 1.0 makes it brighter.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the brightness is required, and it is expected to return
* the brightness value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
* @param {Number|Function} [options.contrast=1.0] The contrast of this layer. 1.0 uses the unmodified imagery color.
* Less than 1.0 reduces the contrast while greater than 1.0 increases it.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the contrast is required, and it is expected to return
* the contrast value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
* @param {Number|Function} [options.hue=0.0] The hue of this layer. 0.0 uses the unmodified imagery color.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates
* of the imagery tile for which the hue is required, and it is expected to return
* the contrast value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
* @param {Number|Function} [options.saturation=1.0] The saturation of this layer. 1.0 uses the unmodified imagery color.
* Less than 1.0 reduces the saturation while greater than 1.0 increases it.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates
* of the imagery tile for which the saturation is required, and it is expected to return
* the contrast value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
* @param {Number|Function} [options.gamma=1.0] The gamma correction to apply to this layer. 1.0 uses the unmodified imagery color.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the gamma is required, and it is expected to return
* the gamma value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
* @param {Boolean} [options.show=true] True if the layer is shown; otherwise, false.
* @param {Number} [options.maximumAnisotropy=maximum supported] The maximum anisotropy level to use
* for texture filtering. If this parameter is not specified, the maximum anisotropy supported
* by the WebGL stack will be used. Larger values make the imagery look better in horizon
* views.
* @param {Number} [options.minimumTerrainLevel] The minimum terrain level-of-detail at which to show this imagery layer,
* or undefined to show it at all levels. Level zero is the least-detailed level.
* @param {Number} [options.maximumTerrainLevel] The maximum terrain level-of-detail at which to show this imagery layer,
* or undefined to show it at all levels. Level zero is the least-detailed level.
*/
function ImageryLayer(imageryProvider, options) {
this._imageryProvider = imageryProvider;
options = defaultValue(options, {});
/**
* The alpha blending value of this layer, with 0.0 representing fully transparent and
* 1.0 representing fully opaque.
*
* @type {Number}
* @default 1.0
*/
this.alpha = defaultValue(options.alpha, defaultValue(imageryProvider.defaultAlpha, 1.0));
/**
* The brightness of this layer. 1.0 uses the unmodified imagery color. Less than 1.0
* makes the imagery darker while greater than 1.0 makes it brighter.
*
* @type {Number}
* @default {@link ImageryLayer.DEFAULT_BRIGHTNESS}
*/
this.brightness = defaultValue(options.brightness, defaultValue(imageryProvider.defaultBrightness, ImageryLayer.DEFAULT_BRIGHTNESS));
/**
* The contrast of this layer. 1.0 uses the unmodified imagery color. Less than 1.0 reduces
* the contrast while greater than 1.0 increases it.
*
* @type {Number}
* @default {@link ImageryLayer.DEFAULT_CONTRAST}
*/
this.contrast = defaultValue(options.contrast, defaultValue(imageryProvider.defaultContrast, ImageryLayer.DEFAULT_CONTRAST));
/**
* The hue of this layer in radians. 0.0 uses the unmodified imagery color.
*
* @type {Number}
* @default {@link ImageryLayer.DEFAULT_HUE}
*/
this.hue = defaultValue(options.hue, defaultValue(imageryProvider.defaultHue, ImageryLayer.DEFAULT_HUE));
/**
* The saturation of this layer. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
* saturation while greater than 1.0 increases it.
*
* @type {Number}
* @default {@link ImageryLayer.DEFAULT_SATURATION}
*/
this.saturation = defaultValue(options.saturation, defaultValue(imageryProvider.defaultSaturation, ImageryLayer.DEFAULT_SATURATION));
/**
* The gamma correction to apply to this layer. 1.0 uses the unmodified imagery color.
*
* @type {Number}
* @default {@link ImageryLayer.DEFAULT_GAMMA}
*/
this.gamma = defaultValue(options.gamma, defaultValue(imageryProvider.defaultGamma, ImageryLayer.DEFAULT_GAMMA));
/**
* Determines if this layer is shown.
*
* @type {Boolean}
* @default true
*/
this.show = defaultValue(options.show, true);
this._minimumTerrainLevel = options.minimumTerrainLevel;
this._maximumTerrainLevel = options.maximumTerrainLevel;
this._rectangle = defaultValue(options.rectangle, Rectangle.MAX_VALUE);
this._maximumAnisotropy = options.maximumAnisotropy;
this._imageryCache = {};
this._skeletonPlaceholder = new TileImagery(Imagery.createPlaceholder(this));
// The value of the show property on the last update.
this._show = true;
// The index of this layer in the ImageryLayerCollection.
this._layerIndex = -1;
// true if this is the base (lowest shown) layer.
this._isBaseLayer = false;
this._requestImageError = undefined;
this._reprojectComputeCommands = [];
}
defineProperties(ImageryLayer.prototype, {
/**
* Gets the imagery provider for this layer.
* @memberof ImageryLayer.prototype
* @type {ImageryProvider}
* @readonly
*/
imageryProvider : {
get: function() {
return this._imageryProvider;
}
},
/**
* Gets the rectangle of this layer. If this rectangle is smaller than the rectangle of the
* {@link ImageryProvider}, only a portion of the imagery provider is shown.
* @memberof ImageryLayer.prototype
* @type {Rectangle}
* @readonly
*/
rectangle: {
get: function() {
return this._rectangle;
}
}
});
/**
* This value is used as the default brightness for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the brightness of the imagery.
* @type {Number}
* @default 1.0
*/
ImageryLayer.DEFAULT_BRIGHTNESS = 1.0;
/**
* This value is used as the default contrast for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the contrast of the imagery.
* @type {Number}
* @default 1.0
*/
ImageryLayer.DEFAULT_CONTRAST = 1.0;
/**
* This value is used as the default hue for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the hue of the imagery.
* @type {Number}
* @default 0.0
*/
ImageryLayer.DEFAULT_HUE = 0.0;
/**
* This value is used as the default saturation for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the saturation of the imagery.
* @type {Number}
* @default 1.0
*/
ImageryLayer.DEFAULT_SATURATION = 1.0;
/**
* This value is used as the default gamma for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the gamma of the imagery.
* @type {Number}
* @default 1.0
*/
ImageryLayer.DEFAULT_GAMMA = 1.0;
/**
* Gets a value indicating whether this layer is the base layer in the
* {@link ImageryLayerCollection}. The base layer is the one that underlies all
* others. It is special in that it is treated as if it has global rectangle, even if
* it actually does not, by stretching the texels at the edges over the entire
* globe.
*
* @returns {Boolean} true if this is the base layer; otherwise, false.
*/
ImageryLayer.prototype.isBaseLayer = function() {
return this._isBaseLayer;
};
/**
* 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 ImageryLayer#destroy
*/
ImageryLayer.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.
*
* @returns {undefined}
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
*
* @example
* imageryLayer = imageryLayer && imageryLayer.destroy();
*
* @see ImageryLayer#isDestroyed
*/
ImageryLayer.prototype.destroy = function() {
return destroyObject(this);
};
var imageryBoundsScratch = new Rectangle();
var tileImageryBoundsScratch = new Rectangle();
var clippedRectangleScratch = new Rectangle();
var terrainRectangleScratch = new Rectangle();
/**
* Computes the intersection of this layer's rectangle with the imagery provider's availability rectangle,
* producing the overall bounds of imagery that can be produced by this layer.
*
* @returns {Promise.<Rectangle>} A promise to a rectangle which defines the overall bounds of imagery that can be produced by this layer.
*
* @example
* // Zoom to an imagery layer.
* imageryLayer.getViewableRectangle().then(function (rectangle) {
* return camera.flyTo({
* destination: rectangle
* });
* });
*/
ImageryLayer.prototype.getViewableRectangle = function() {
var imageryProvider = this._imageryProvider;
var rectangle = this._rectangle;
return imageryProvider.readyPromise.then(function() {
return Rectangle.intersection(imageryProvider.rectangle, rectangle);
});
};
/**
* Create skeletons for the imagery tiles that partially or completely overlap a given terrain
* tile.
*
* @private
*
* @param {Tile} tile The terrain tile.
* @param {TerrainProvider} terrainProvider The terrain provider associated with the terrain tile.
* @param {Number} insertionPoint The position to insert new skeletons before in the tile's imagery list.
* @returns {Boolean} true if this layer overlaps any portion of the terrain tile; otherwise, false.
*/
ImageryLayer.prototype._createTileImagerySkeletons = function(tile, terrainProvider, insertionPoint) {
var surfaceTile = tile.data;
if (defined(this._minimumTerrainLevel) && tile.level < this._minimumTerrainLevel) {
return false;
}
if (defined(this._maximumTerrainLevel) && tile.level > this._maximumTerrainLevel) {
return false;
}
var imageryProvider = this._imageryProvider;
if (!defined(insertionPoint)) {
insertionPoint = surfaceTile.imagery.length;
}
if (!imageryProvider.ready) {
// The imagery provider is not ready, so we can't create skeletons, yet.
// Instead, add a placeholder so that we'll know to create
// the skeletons once the provider is ready.
this._skeletonPlaceholder.loadingImagery.addReference();
surfaceTile.imagery.splice(insertionPoint, 0, this._skeletonPlaceholder);
return true;
}
// Use Web Mercator for our texture coordinate computations if this imagery layer uses
// that projection and the terrain tile falls entirely inside the valid bounds of the
// projection.
var useWebMercatorT = imageryProvider.tilingScheme instanceof WebMercatorTilingScheme &&
tile.rectangle.north < WebMercatorProjection.MaximumLatitude &&
tile.rectangle.south > -WebMercatorProjection.MaximumLatitude;
// Compute the rectangle of the imagery from this imageryProvider that overlaps
// the geometry tile. The ImageryProvider and ImageryLayer both have the
// opportunity to constrain the rectangle. The imagery TilingScheme's rectangle
// always fully contains the ImageryProvider's rectangle.
var imageryBounds = Rectangle.intersection(imageryProvider.rectangle, this._rectangle, imageryBoundsScratch);
var rectangle = Rectangle.intersection(tile.rectangle, imageryBounds, tileImageryBoundsScratch);
if (!defined(rectangle)) {
// There is no overlap between this terrain tile and this imagery
// provider. Unless this is the base layer, no skeletons need to be created.
// We stretch texels at the edge of the base layer over the entire globe.
if (!this.isBaseLayer()) {
return false;
}
var baseImageryRectangle = imageryBounds;
var baseTerrainRectangle = tile.rectangle;
rectangle = tileImageryBoundsScratch;
if (baseTerrainRectangle.south >= baseImageryRectangle.north) {
rectangle.north = rectangle.south = baseImageryRectangle.north;
} else if (baseTerrainRectangle.north <= baseImageryRectangle.south) {
rectangle.north = rectangle.south = baseImageryRectangle.south;
} else {
rectangle.south = Math.max(baseTerrainRectangle.south, baseImageryRectangle.south);
rectangle.north = Math.min(baseTerrainRectangle.north, baseImageryRectangle.north);
}
if (baseTerrainRectangle.west >= baseImageryRectangle.east) {
rectangle.west = rectangle.east = baseImageryRectangle.east;
} else if (baseTerrainRectangle.east <= baseImageryRectangle.west) {
rectangle.west = rectangle.east = baseImageryRectangle.west;
} else {
rectangle.west = Math.max(baseTerrainRectangle.west, baseImageryRectangle.west);
rectangle.east = Math.min(baseTerrainRectangle.east, baseImageryRectangle.east);
}
}
var latitudeClosestToEquator = 0.0;
if (rectangle.south > 0.0) {
latitudeClosestToEquator = rectangle.south;
} else if (rectangle.north < 0.0) {
latitudeClosestToEquator = rectangle.north;
}
// Compute the required level in the imagery tiling scheme.
// The errorRatio should really be imagerySSE / terrainSSE rather than this hard-coded value.
// But first we need configurable imagery SSE and we need the rendering to be able to handle more
// images attached to a terrain tile than there are available texture units. So that's for the future.
var errorRatio = 1.0;
var targetGeometricError = errorRatio * terrainProvider.getLevelMaximumGeometricError(tile.level);
var imageryLevel = getLevelWithMaximumTexelSpacing(this, targetGeometricError, latitudeClosestToEquator);
imageryLevel = Math.max(0, imageryLevel);
var maximumLevel = imageryProvider.maximumLevel;
if (imageryLevel > maximumLevel) {
imageryLevel = maximumLevel;
}
if (defined(imageryProvider.minimumLevel)) {
var minimumLevel = imageryProvider.minimumLevel;
if (imageryLevel < minimumLevel) {
imageryLevel = minimumLevel;
}
}
var imageryTilingScheme = imageryProvider.tilingScheme;
var northwestTileCoordinates = imageryTilingScheme.positionToTileXY(Rectangle.northwest(rectangle), imageryLevel);
var southeastTileCoordinates = imageryTilingScheme.positionToTileXY(Rectangle.southeast(rectangle), imageryLevel);
// If the southeast corner of the rectangle lies very close to the north or west side
// of the southeast tile, we don't actually need the southernmost or easternmost
// tiles.
// Similarly, if the northwest corner of the rectangle lies very close to the south or east side
// of the northwest tile, we don't actually need the northernmost or westernmost tiles.
// We define "very close" as being within 1/512 of the width of the tile.
var veryCloseX = tile.rectangle.width / 512.0;
var veryCloseY = tile.rectangle.height / 512.0;
var northwestTileRectangle = imageryTilingScheme.tileXYToRectangle(northwestTileCoordinates.x, northwestTileCoordinates.y, imageryLevel);
if (Math.abs(northwestTileRectangle.south - tile.rectangle.north) < veryCloseY && northwestTileCoordinates.y < southeastTileCoordinates.y) {
++northwestTileCoordinates.y;
}
if (Math.abs(northwestTileRectangle.east - tile.rectangle.west) < veryCloseX && northwestTileCoordinates.x < southeastTileCoordinates.x) {
++northwestTileCoordinates.x;
}
var southeastTileRectangle = imageryTilingScheme.tileXYToRectangle(southeastTileCoordinates.x, southeastTileCoordinates.y, imageryLevel);
if (Math.abs(southeastTileRectangle.north - tile.rectangle.south) < veryCloseY && southeastTileCoordinates.y > northwestTileCoordinates.y) {
--southeastTileCoordinates.y;
}
if (Math.abs(southeastTileRectangle.west - tile.rectangle.east) < veryCloseX && southeastTileCoordinates.x > northwestTileCoordinates.x) {
--southeastTileCoordinates.x;
}
// Create TileImagery instances for each imagery tile overlapping this terrain tile.
// We need to do all texture coordinate computations in the imagery tile's tiling scheme.
var terrainRectangle = Rectangle.clone(tile.rectangle, terrainRectangleScratch);
var imageryRectangle = imageryTilingScheme.tileXYToRectangle(northwestTileCoordinates.x, northwestTileCoordinates.y, imageryLevel);
var clippedImageryRectangle = Rectangle.intersection(imageryRectangle, imageryBounds, clippedRectangleScratch);
var imageryTileXYToRectangle;
if (useWebMercatorT) {
imageryTilingScheme.rectangleToNativeRectangle(terrainRectangle, terrainRectangle);
imageryTilingScheme.rectangleToNativeRectangle(imageryRectangle, imageryRectangle);
imageryTilingScheme.rectangleToNativeRectangle(clippedImageryRectangle, clippedImageryRectangle);
imageryTilingScheme.rectangleToNativeRectangle(imageryBounds, imageryBounds);
imageryTileXYToRectangle = imageryTilingScheme.tileXYToNativeRectangle.bind(imageryTilingScheme);
veryCloseX = terrainRectangle.width / 512.0;
veryCloseY = terrainRectangle.height / 512.0;
} else {
imageryTileXYToRectangle = imageryTilingScheme.tileXYToRectangle.bind(imageryTilingScheme);
}
var minU;
var maxU = 0.0;
var minV = 1.0;
var maxV;
// If this is the northern-most or western-most tile in the imagery tiling scheme,
// it may not start at the northern or western edge of the terrain tile.
// Calculate where it does start.
if (!this.isBaseLayer() && Math.abs(clippedImageryRectangle.west - terrainRectangle.west) >= veryCloseX) {
maxU = Math.min(1.0, (clippedImageryRectangle.west - terrainRectangle.west) / terrainRectangle.width);
}
if (!this.isBaseLayer() && Math.abs(clippedImageryRectangle.north - terrainRectangle.north) >= veryCloseY) {
minV = Math.max(0.0, (clippedImageryRectangle.north - terrainRectangle.south) / terrainRectangle.height);
}
var initialMinV = minV;
for ( var i = northwestTileCoordinates.x; i <= southeastTileCoordinates.x; i++) {
minU = maxU;
imageryRectangle = imageryTileXYToRectangle(i, northwestTileCoordinates.y, imageryLevel);
clippedImageryRectangle = Rectangle.simpleIntersection(imageryRectangle, imageryBounds, clippedRectangleScratch);
if (!defined(clippedImageryRectangle)) {
continue;
}
maxU = Math.min(1.0, (clippedImageryRectangle.east - terrainRectangle.west) / terrainRectangle.width);
// If this is the eastern-most imagery tile mapped to this terrain tile,
// and there are more imagery tiles to the east of this one, the maxU
// should be 1.0 to make sure rounding errors don't make the last
// image fall shy of the edge of the terrain tile.
if (i === southeastTileCoordinates.x && (this.isBaseLayer() || Math.abs(clippedImageryRectangle.east - terrainRectangle.east) < veryCloseX)) {
maxU = 1.0;
}
minV = initialMinV;
for ( var j = northwestTileCoordinates.y; j <= southeastTileCoordinates.y; j++) {
maxV = minV;
imageryRectangle = imageryTileXYToRectangle(i, j, imageryLevel);
clippedImageryRectangle = Rectangle.simpleIntersection(imageryRectangle, imageryBounds, clippedRectangleScratch);
if (!defined(clippedImageryRectangle)) {
continue;
}
minV = Math.max(0.0, (clippedImageryRectangle.south - terrainRectangle.south) / terrainRectangle.height);
// If this is the southern-most imagery tile mapped to this terrain tile,
// and there are more imagery tiles to the south of this one, the minV
// should be 0.0 to make sure rounding errors don't make the last
// image fall shy of the edge of the terrain tile.
if (j === southeastTileCoordinates.y && (this.isBaseLayer() || Math.abs(clippedImageryRectangle.south - terrainRectangle.south) < veryCloseY)) {
minV = 0.0;
}
var texCoordsRectangle = new Cartesian4(minU, minV, maxU, maxV);
var imagery = this.getImageryFromCache(i, j, imageryLevel);
surfaceTile.imagery.splice(insertionPoint, 0, new TileImagery(imagery, texCoordsRectangle, useWebMercatorT));
++insertionPoint;
}
}
return true;
};
/**
* Calculate the translation and scale for a particular {@link TileImagery} attached to a
* particular terrain tile.
*
* @private
*
* @param {Tile} tile The terrain tile.
* @param {TileImagery} tileImagery The imagery tile mapping.
* @returns {Cartesian4} The translation and scale where X and Y are the translation and Z and W
* are the scale.
*/
ImageryLayer.prototype._calculateTextureTranslationAndScale = function(tile, tileImagery) {
var imageryRectangle = tileImagery.readyImagery.rectangle;
var terrainRectangle = tile.rectangle;
if (tileImagery.useWebMercatorT) {
var tilingScheme = tileImagery.readyImagery.imageryLayer.imageryProvider.tilingScheme;
imageryRectangle = tilingScheme.rectangleToNativeRectangle(imageryRectangle, imageryBoundsScratch);
terrainRectangle = tilingScheme.rectangleToNativeRectangle(terrainRectangle, terrainRectangleScratch);
}
var terrainWidth = terrainRectangle.width;
var terrainHeight = terrainRectangle.height;
var scaleX = terrainWidth / imageryRectangle.width;
var scaleY = terrainHeight / imageryRectangle.height;
return new Cartesian4(
scaleX * (terrainRectangle.west - imageryRectangle.west) / terrainWidth,
scaleY * (terrainRectangle.south - imageryRectangle.south) / terrainHeight,
scaleX,
scaleY);
};
/**
* Request a particular piece of imagery from the imagery provider. This method handles raising an
* error event if the request fails, and retrying the request if necessary.
*
* @private
*
* @param {Imagery} imagery The imagery to request.
*/
ImageryLayer.prototype._requestImagery = function(imagery) {
var imageryProvider = this._imageryProvider;
var that = this;
function success(image) {
if (!defined(image)) {
return failure();
}
imagery.image = image;
imagery.state = ImageryState.RECEIVED;
TileProviderError.handleSuccess(that._requestImageError);
}
function failure(e) {
// Initially assume failure. handleError may retry, in which case the state will
// change to TRANSITIONING.
imagery.state = ImageryState.FAILED;
var message = 'Failed to obtain image tile X: ' + imagery.x + ' Y: ' + imagery.y + ' Level: ' + imagery.level + '.';
that._requestImageError = TileProviderError.handleError(
that._requestImageError,
imageryProvider,
imageryProvider.errorEvent,
message,
imagery.x, imagery.y, imagery.level,
doRequest,
e);
}
function doRequest() {
imagery.state = ImageryState.TRANSITIONING;
var imagePromise = imageryProvider.requestImage(imagery.x, imagery.y, imagery.level);
if (!defined(imagePromise)) {
// Too many parallel requests, so postpone loading tile.
imagery.state = ImageryState.UNLOADED;
return;
}
if (defined(imageryProvider.getTileCredits)) {
imagery.credits = imageryProvider.getTileCredits(imagery.x, imagery.y, imagery.level);
}
when(imagePromise, success, failure);
}
doRequest();
};
/**
* Create a WebGL texture for a given {@link Imagery} instance.
*
* @private
*
* @param {Context} context The rendered context to use to create textures.
* @param {Imagery} imagery The imagery for which to create a texture.
*/
ImageryLayer.prototype._createTexture = function(context, imagery) {
var imageryProvider = this._imageryProvider;
// If this imagery provider has a discard policy, use it to check if this
// image should be discarded.
if (defined(imageryProvider.tileDiscardPolicy)) {
var discardPolicy = imageryProvider.tileDiscardPolicy;
if (defined(discardPolicy)) {
// If the discard policy is not ready yet, transition back to the
// RECEIVED state and we'll try again next time.
if (!discardPolicy.isReady()) {
imagery.state = ImageryState.RECEIVED;
return;
}
// Mark discarded imagery tiles invalid. Parent imagery will be used instead.
if (discardPolicy.shouldDiscardImage(imagery.image)) {
imagery.state = ImageryState.INVALID;
return;
}
}
}
// Imagery does not need to be discarded, so upload it to WebGL.
var texture = new Texture({
context : context,
source : imagery.image,
pixelFormat : imageryProvider.hasAlphaChannel ? PixelFormat.RGBA : PixelFormat.RGB
});
if (imageryProvider.tilingScheme instanceof WebMercatorTilingScheme) {
imagery.textureWebMercator = texture;
} else {
imagery.texture = texture;
}
imagery.image = undefined;
imagery.state = ImageryState.TEXTURE_LOADED;
};
function finalizeReprojectTexture(imageryLayer, context, imagery, texture) {
// Use mipmaps if this texture has power-of-two dimensions.
if (CesiumMath.isPowerOfTwo(texture.width) && CesiumMath.isPowerOfTwo(texture.height)) {
var mipmapSampler = context.cache.imageryLayer_mipmapSampler;
if (!defined(mipmapSampler)) {
var maximumSupportedAnisotropy = ContextLimits.maximumTextureFilterAnisotropy;
mipmapSampler = context.cache.imageryLayer_mipmapSampler = new Sampler({
wrapS : TextureWrap.CLAMP_TO_EDGE,
wrapT : TextureWrap.CLAMP_TO_EDGE,
minificationFilter : TextureMinificationFilter.LINEAR_MIPMAP_LINEAR,
magnificationFilter : TextureMagnificationFilter.LINEAR,
maximumAnisotropy : Math.min(maximumSupportedAnisotropy, defaultValue(imageryLayer._maximumAnisotropy, maximumSupportedAnisotropy))
});
}
texture.generateMipmap(MipmapHint.NICEST);
texture.sampler = mipmapSampler;
} else {
var nonMipmapSampler = context.cache.imageryLayer_nonMipmapSampler;
if (!defined(nonMipmapSampler)) {
nonMipmapSampler = context.cache.imageryLayer_nonMipmapSampler = new Sampler({
wrapS : TextureWrap.CLAMP_TO_EDGE,
wrapT : TextureWrap.CLAMP_TO_EDGE,
minificationFilter : TextureMinificationFilter.LINEAR,
magnificationFilter : TextureMagnificationFilter.LINEAR
});
}
texture.sampler = nonMipmapSampler;
}
imagery.state = ImageryState.READY;
}
/**
* Enqueues a command re-projecting a texture to a {@link GeographicProjection} on the next update, if necessary, and generate
* mipmaps for the geographic texture.
*
* @private
*
* @param {FrameState} frameState The frameState.
* @param {Imagery} imagery The imagery instance to reproject.
* @param {Boolean} [needGeographicProjection=true] True to reproject to geographic, or false if Web Mercator is fine.
*/
ImageryLayer.prototype._reprojectTexture = function(frameState, imagery, needGeographicProjection) {
var texture = imagery.textureWebMercator || imagery.texture;
var rectangle = imagery.rectangle;
var context = frameState.context;
needGeographicProjection = defaultValue(needGeographicProjection, true);
// Reproject this texture if it is not already in a geographic projection and
// the pixels are more than 1e-5 radians apart. The pixel spacing cutoff
// avoids precision problems in the reprojection transformation while making
// no noticeable difference in the georeferencing of the image.
if (needGeographicProjection &&
!(this._imageryProvider.tilingScheme instanceof GeographicTilingScheme) &&
rectangle.width / texture.width > 1e-5) {
var that = this;
imagery.addReference();
var computeCommand = new ComputeCommand({
persists : true,
owner : this,
// Update render resources right before execution instead of now.
// This allows different ImageryLayers to share the same vao and buffers.
preExecute : function(command) {
reprojectToGeographic(command, context, texture, imagery.rectangle);
},
postExecute : function(outputTexture) {
imagery.texture = outputTexture;
finalizeReprojectTexture(that, context, imagery, outputTexture);
imagery.releaseReference();
}
});
this._reprojectComputeCommands.push(computeCommand);
} else {
finalizeReprojectTexture(this, context, imagery, texture);
}
};
/**
* Updates frame state to execute any queued texture re-projections.
*
* @private
*
* @param {FrameState} frameState The frameState.
*/
ImageryLayer.prototype.queueReprojectionCommands = function(frameState) {
var computeCommands = this._reprojectComputeCommands;
var length = computeCommands.length;
for (var i = 0; i < length; ++i) {
frameState.commandList.push(computeCommands[i]);
}
computeCommands.length = 0;
};
/**
* Cancels re-projection commands queued for the next frame.
*
* @private
*/
ImageryLayer.prototype.cancelReprojections = function() {
this._reprojectComputeCommands.length = 0;
};
ImageryLayer.prototype.getImageryFromCache = function(x, y, level, imageryRectangle) {
var cacheKey = getImageryCacheKey(x, y, level);
var imagery = this._imageryCache[cacheKey];
if (!defined(imagery)) {
imagery = new Imagery(this, x, y, level, imageryRectangle);
this._imageryCache[cacheKey] = imagery;
}
imagery.addReference();
return imagery;
};
ImageryLayer.prototype.removeImageryFromCache = function(imagery) {
var cacheKey = getImageryCacheKey(imagery.x, imagery.y, imagery.level);
delete this._imageryCache[cacheKey];
};
function getImageryCacheKey(x, y, level) {
return JSON.stringify([x, y, level]);
}
var uniformMap = {
u_textureDimensions : function() {
return this.textureDimensions;
},
u_texture : function() {
return this.texture;
},
textureDimensions : new Cartesian2(),
texture : undefined
};
var float32ArrayScratch = FeatureDetection.supportsTypedArrays() ? new Float32Array(2 * 64) : undefined;
function reprojectToGeographic(command, context, texture, rectangle) {
// This function has gone through a number of iterations, because GPUs are awesome.
//
// Originally, we had a very simple vertex shader and computed the Web Mercator texture coordinates
// per-fragment in the fragment shader. That worked well, except on mobile devices, because
// fragment shaders have limited precision on many mobile devices. The result was smearing artifacts
// at medium zoom levels because different geographic texture coordinates would be reprojected to Web
// Mercator as the same value.
//
// Our solution was to reproject to Web Mercator in the vertex shader instead of the fragment shader.
// This required far more vertex data. With fragment shader reprojection, we only needed a single quad.
// But to achieve the same precision with vertex shader reprojection, we needed a vertex for each
// output pixel. So we used a grid of 256x256 vertices, because most of our imagery
// tiles are 256x256. Fortunately the grid could be created and uploaded to the GPU just once and
// re-used for all reprojections, so the performance was virtually unchanged from our original fragment
// shader approach. See https://github.com/AnalyticalGraphicsInc/cesium/pull/714.
//
// Over a year later, we noticed (https://github.com/AnalyticalGraphicsInc/cesium/issues/2110)
// that our reprojection code was creating a rare but severe artifact on some GPUs (Intel HD 4600
// for one). The problem was that the GLSL sin function on these GPUs had a discontinuity at fine scales in
// a few places.
//
// We solved this by implementing a more reliable sin function based on the CORDIC algorithm
// (https://github.com/AnalyticalGraphicsInc/cesium/pull/2111). Even though this was a fair
// amount of code to be executing per vertex, the performance seemed to be pretty good on most GPUs.
// Unfortunately, on some GPUs, the performance was absolutely terrible
// (https://github.com/AnalyticalGraphicsInc/cesium/issues/2258).
//
// So that brings us to our current solution, the one you see here. Effectively, we compute the Web
// Mercator texture coordinates on the CPU and store the T coordinate with each vertex (the S coordinate
// is the same in Geographic and Web Mercator). To make this faster, we reduced our reprojection mesh
// to be only 2 vertices wide and 64 vertices high. We should have reduced the width to 2 sooner,
// because the extra vertices weren't buying us anything. The height of 64 means we are technically
// doing a slightly less accurate reprojection than we were before, but we can't see the difference
// so it's worth the 4x speedup.
var reproject = context.cache.imageryLayer_reproject;
if (!defined(reproject)) {
reproject = context.cache.imageryLayer_reproject = {
vertexArray : undefined,
shaderProgram : undefined,
sampler : undefined,
destroy : function() {
if (defined(this.framebuffer)) {
this.framebuffer.destroy();
}
if (defined(this.vertexArray)) {
this.vertexArray.destroy();
}
if (defined(this.shaderProgram)) {
this.shaderProgram.destroy();
}
}
};
var positions = new Float32Array(2 * 64 * 2);
var index = 0;
for (var j = 0; j < 64; ++j) {
var y = j / 63.0;
positions[index++] = 0.0;
positions[index++] = y;
positions[index++] = 1.0;
positions[index++] = y;
}
var reprojectAttributeIndices = {
position : 0,
webMercatorT : 1
};
var indices = TerrainProvider.getRegularGridIndices(2, 64);
var indexBuffer = Buffer.createIndexBuffer({
context : context,
typedArray : indices,
usage : BufferUsage.STATIC_DRAW,
indexDatatype : IndexDatatype.UNSIGNED_SHORT
});
reproject.vertexArray = new VertexArray({
context : context,
attributes : [{
index : reprojectAttributeIndices.position,
vertexBuffer : Buffer.createVertexBuffer({
context : context,
typedArray : positions,
usage : BufferUsage.STATIC_DRAW
}),
componentsPerAttribute : 2
},{
index : reprojectAttributeIndices.webMercatorT,
vertexBuffer : Buffer.createVertexBuffer({
context : context,
sizeInBytes : 64 * 2 * 4,
usage : BufferUsage.STREAM_DRAW
}),
componentsPerAttribute : 1
}],
indexBuffer : indexBuffer
});
var vs = new ShaderSource({
sources : [ReprojectWebMercatorVS]
});
reproject.shaderProgram = ShaderProgram.fromCache({
context : context,
vertexShaderSource : vs,
fragmentShaderSource : ReprojectWebMercatorFS,
attributeLocations : reprojectAttributeIndices
});
reproject.sampler = new Sampler({
wrapS : TextureWrap.CLAMP_TO_EDGE,
wrapT : TextureWrap.CLAMP_TO_EDGE,
minificationFilter : TextureMinificationFilter.LINEAR,
magnificationFilter : TextureMagnificationFilter.LINEAR
});
}
texture.sampler = reproject.sampler;