-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathBillboardCollection.js
1312 lines (1159 loc) · 52.5 KB
/
BillboardCollection.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/defined',
'../Core/DeveloperError',
'../Core/Color',
'../Core/defaultValue',
'../Core/destroyObject',
'../Core/Cartesian2',
'../Core/Cartesian3',
'../Core/EncodedCartesian3',
'../Core/Matrix4',
'../Core/ComponentDatatype',
'../Core/IndexDatatype',
'../Core/PrimitiveType',
'../Core/BoundingSphere',
'../Renderer/BlendingState',
'../Renderer/BufferUsage',
'../Renderer/CommandLists',
'../Renderer/DrawCommand',
'../Renderer/VertexArrayFacade',
'../Renderer/createShaderSource',
'./SceneMode',
'./Billboard',
'./HorizontalOrigin',
'../Shaders/BillboardCollectionVS',
'../Shaders/BillboardCollectionFS'
], function(
defined,
DeveloperError,
Color,
defaultValue,
destroyObject,
Cartesian2,
Cartesian3,
EncodedCartesian3,
Matrix4,
ComponentDatatype,
IndexDatatype,
PrimitiveType,
BoundingSphere,
BlendingState,
BufferUsage,
CommandLists,
DrawCommand,
VertexArrayFacade,
createShaderSource,
SceneMode,
Billboard,
HorizontalOrigin,
BillboardCollectionVS,
BillboardCollectionFS) {
"use strict";
var SHOW_INDEX = Billboard.SHOW_INDEX;
var POSITION_INDEX = Billboard.POSITION_INDEX;
var PIXEL_OFFSET_INDEX = Billboard.PIXEL_OFFSET_INDEX;
var EYE_OFFSET_INDEX = Billboard.EYE_OFFSET_INDEX;
var HORIZONTAL_ORIGIN_INDEX = Billboard.HORIZONTAL_ORIGIN_INDEX;
var VERTICAL_ORIGIN_INDEX = Billboard.VERTICAL_ORIGIN_INDEX;
var SCALE_INDEX = Billboard.SCALE_INDEX;
var IMAGE_INDEX_INDEX = Billboard.IMAGE_INDEX_INDEX;
var COLOR_INDEX = Billboard.COLOR_INDEX;
var ROTATION_INDEX = Billboard.ROTATION_INDEX;
var ALIGNED_AXIS_INDEX = Billboard.ALIGNED_AXIS_INDEX;
var SCALE_BY_DISTANCE_INDEX = Billboard.SCALE_BY_DISTANCE_INDEX;
var NUMBER_OF_PROPERTIES = Billboard.NUMBER_OF_PROPERTIES;
// PERFORMANCE_IDEA: Use vertex compression so we don't run out of
// vec4 attributes (WebGL minimum: 8)
var attributeIndices = {
positionHigh : 0,
positionLow : 1,
pixelOffset : 2,
eyeOffsetAndScale : 3,
textureCoordinatesAndImageSize : 4,
originAndShow : 5,
direction : 6,
pickColor : 7, // pickColor and color shared an index because pickColor is only used during
color : 7, // the 'pick' pass and 'color' is only used during the 'color' pass.
rotationAndAlignedAxis : 8,
scaleByDistance : 9
};
// Identifies to the VertexArrayFacade the attributes that are used only for the pick
// pass or only for the color pass.
var allPassPurpose = 'all';
var colorPassPurpose = 'color';
var pickPassPurpose = 'pick';
var emptyArray = [];
/**
* A renderable collection of billboards. Billboards are viewport-aligned
* images positioned in the 3D scene.
* <br /><br />
* <div align='center'>
* <img src='images/Billboard.png' width='400' height='300' /><br />
* Example billboards
* </div>
* <br /><br />
* Billboards are added and removed from the collection using {@link BillboardCollection#add}
* and {@link BillboardCollection#remove}. All billboards in a collection reference images
* from the same texture atlas, which is assigned using {@link BillboardCollection#setTextureAtlas}.
*
* @alias BillboardCollection
* @constructor
*
* @performance For best performance, prefer a few collections, each with many billboards, to
* many collections with only a few billboards each. Organize collections so that billboards
* with the same update frequency are in the same collection, i.e., billboards that do not
* change should be in one collection; billboards that change every frame should be in another
* collection; and so on.
*
* @see BillboardCollection#add
* @see BillboardCollection#remove
* @see BillboardCollection#setTextureAtlas
* @see Billboard
* @see TextureAtlas
* @see LabelCollection
*
* @example
* // Create a billboard collection with two billboards
* var billboards = new BillboardCollection();
* var atlas = context.createTextureAtlas({images : images});
* billboards.setTextureAtlas(atlas);
* billboards.add({
* position : { x : 1.0, y : 2.0, z : 3.0 },
* imageIndex : 0
* });
* billboards.add({
* position : { x : 4.0, y : 5.0, z : 6.0 },
* imageIndex : 1
* });
*
* @demo <a href="http://cesium.agi.com/Cesium/Apps/Sandcastle/index.html?src=Billboards.html">Cesium Sandcastle Billboard Demo</a>
*/
var BillboardCollection = function() {
this._textureAtlas = undefined;
this._textureAtlasGUID = undefined;
this._destroyTextureAtlas = true;
this._sp = undefined;
this._rs = undefined;
this._vaf = undefined;
this._spPick = undefined;
this._billboards = [];
this._billboardsToUpdate = [];
this._billboardsToUpdateIndex = 0;
this._billboardsRemoved = false;
this._createVertexArray = false;
this._shaderRotation = false;
this._compiledShaderRotation = false;
this._compiledShaderRotationPick = false;
this._shaderScaleByDistance = false;
this._compiledShaderScaleByDistance = false;
this._compiledShaderScaleByDistancePick = false;
this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES);
this._maxSize = 0.0;
this._maxEyeOffset = 0.0;
this._maxScale = 1.0;
this._maxPixelOffset = 0.0;
this._allHorizontalCenter = true;
this._baseVolume = new BoundingSphere();
this._baseVolume2D = new BoundingSphere();
this._boundingVolume = new BoundingSphere();
this._colorCommands = [];
this._pickCommands = [];
this._commandLists = new CommandLists();
/**
* The 4x4 transformation matrix that transforms each billboard in this collection from model to world coordinates.
* When this is the identity matrix, the billboards are drawn in world coordinates, i.e., Earth's WGS84 coordinates.
* Local reference frames can be used by providing a different transformation matrix, like that returned
* by {@link Transforms.eastNorthUpToFixedFrame}. This matrix is available to GLSL vertex and fragment
* shaders via {@link czm_model} and derived uniforms.
*
* @type {Matrix4}
* @default {@link Matrix4.IDENTITY}
*
* @see Transforms.eastNorthUpToFixedFrame
* @see czm_model
*
* @example
* var center = ellipsoid.cartographicToCartesian(Cartographic.fromDegrees(-75.59777, 40.03883));
* billboards.modelMatrix = Transforms.eastNorthUpToFixedFrame(center);
* billboards.add({ imageIndex: 0, position : new Cartesian3(0.0, 0.0, 0.0) }); // center
* billboards.add({ imageIndex: 0, position : new Cartesian3(1000000.0, 0.0, 0.0) }); // east
* billboards.add({ imageIndex: 0, position : new Cartesian3(0.0, 1000000.0, 0.0) }); // north
* billboards.add({ imageIndex: 0, position : new Cartesian3(0.0, 0.0, 1000000.0) }); // up
* ]);
*/
this.modelMatrix = Matrix4.IDENTITY.clone();
this._modelMatrix = Matrix4.IDENTITY.clone();
this._mode = SceneMode.SCENE3D;
this._projection = undefined;
// The buffer usage for each attribute is determined based on the usage of the attribute over time.
this._buffersUsage = [
BufferUsage.STATIC_DRAW, // SHOW_INDEX
BufferUsage.STATIC_DRAW, // POSITION_INDEX
BufferUsage.STATIC_DRAW, // PIXEL_OFFSET_INDEX
BufferUsage.STATIC_DRAW, // EYE_OFFSET_INDEX
BufferUsage.STATIC_DRAW, // HORIZONTAL_ORIGIN_INDEX
BufferUsage.STATIC_DRAW, // VERTICAL_ORIGIN_INDEX
BufferUsage.STATIC_DRAW, // SCALE_INDEX
BufferUsage.STATIC_DRAW, // IMAGE_INDEX_INDEX
BufferUsage.STATIC_DRAW, // COLOR_INDEX
BufferUsage.STATIC_DRAW, // ROTATION_INDEX
BufferUsage.STATIC_DRAW, // ALIGNED_AXIS_INDEX
BufferUsage.STATIC_DRAW // SCALE_BY_DISTANCE_INDEX
];
var that = this;
this._uniforms = {
u_atlas : function() {
return that._textureAtlas.getTexture();
}
};
};
/**
* Creates and adds a billboard with the specified initial properties to the collection.
* The added billboard is returned so it can be modified or removed from the collection later.
*
* @memberof BillboardCollection
*
* @param {Object}[billboard=undefined] A template describing the billboard's properties as shown in Example 1.
*
* @returns {Billboard} The billboard that was added to the collection.
*
* @performance Calling <code>add</code> is expected constant time. However, when
* {@link BillboardCollection#update} is called, the collection's vertex buffer
* is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead. For
* best performance, add as many billboards as possible before calling <code>update</code>.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#remove
* @see BillboardCollection#removeAll
* @see BillboardCollection#update
*
* @example
* // Example 1: Add a billboard, specifying all the default values.
* var b = billboards.add({
* show : true,
* position : Cartesian3.ZERO,
* pixelOffset : Cartesian2.ZERO,
* eyeOffset : Cartesian3.ZERO,
* horizontalOrigin : HorizontalOrigin.CENTER,
* verticalOrigin : VerticalOrigin.CENTER,
* scale : 1.0,
* scaleByDistance : new NearFarScalar(5e6, 1.0, 2e7, 0.0),
* imageIndex : 0,
* color : Color.WHITE
* });
*
* // Example 2: Specify only the billboard's cartographic position.
* var b = billboards.add({
* position : ellipsoid.cartographicToCartesian(new Cartographic(longitude, latitude, height))
* });
*/
BillboardCollection.prototype.add = function(billboard) {
var b = new Billboard(billboard, this);
b._index = this._billboards.length;
this._billboards.push(b);
this._createVertexArray = true;
return b;
};
/**
* Removes a billboard from the collection.
*
* @memberof BillboardCollection
*
* @param {Billboard} billboard The billboard to remove.
*
* @returns {Boolean} <code>true</code> if the billboard was removed; <code>false</code> if the billboard was not found in the collection.
*
* @performance Calling <code>remove</code> is expected constant time. However, when
* {@link BillboardCollection#update} is called, the collection's vertex buffer
* is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead. For
* best performance, remove as many billboards as possible before calling <code>update</code>.
* If you intend to temporarily hide a billboard, it is usually more efficient to call
* {@link Billboard#setShow} instead of removing and re-adding the billboard.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#add
* @see BillboardCollection#removeAll
* @see BillboardCollection#update
* @see Billboard#setShow
*
* @example
* var b = billboards.add(...);
* billboards.remove(b); // Returns true
*/
BillboardCollection.prototype.remove = function(billboard) {
if (this.contains(billboard)) {
this._billboards[billboard._index] = null; // Removed later
this._billboardsRemoved = true;
this._createVertexArray = true;
billboard._destroy();
return true;
}
return false;
};
/**
* Removes all billboards from the collection.
*
* @performance <code>O(n)</code>. It is more efficient to remove all the billboards
* from a collection and then add new ones than to create a new collection entirely.
*
* @memberof BillboardCollection
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#add
* @see BillboardCollection#remove
* @see BillboardCollection#update
*
* @example
* billboards.add(...);
* billboards.add(...);
* billboards.removeAll();
*/
BillboardCollection.prototype.removeAll = function() {
this._destroyBillboards();
this._billboards = [];
this._billboardsToUpdate = [];
this._billboardsToUpdateIndex = 0;
this._billboardsRemoved = false;
this._createVertexArray = true;
};
function removeBillboards(billboardCollection) {
if (billboardCollection._billboardsRemoved) {
billboardCollection._billboardsRemoved = false;
var newBillboards = [];
var billboards = billboardCollection._billboards;
var length = billboards.length;
for (var i = 0, j = 0; i < length; ++i) {
var billboard = billboards[i];
if (billboard) {
billboard._index = j++;
newBillboards.push(billboard);
}
}
billboardCollection._billboards = newBillboards;
}
}
BillboardCollection.prototype._updateBillboard = function(billboard, propertyChanged) {
if (!billboard._dirty) {
this._billboardsToUpdate[this._billboardsToUpdateIndex++] = billboard;
}
++this._propertiesChanged[propertyChanged];
};
/**
* Check whether this collection contains a given billboard.
*
* @memberof BillboardCollection
*
* @param {Billboard} billboard The billboard to check for.
*
* @returns {Boolean} true if this collection contains the billboard, false otherwise.
*
* @see BillboardCollection#get
*/
BillboardCollection.prototype.contains = function(billboard) {
return defined(billboard) && billboard._billboardCollection === this;
};
/**
* Returns the billboard in the collection at the specified index. Indices are zero-based
* and increase as billboards are added. Removing a billboard shifts all billboards after
* it to the left, changing their indices. This function is commonly used with
* {@link BillboardCollection#getLength} to iterate over all the billboards
* in the collection.
*
* @memberof BillboardCollection
*
* @param {Number} index The zero-based index of the billboard.
*
* @returns {Billboard} The billboard at the specified index.
*
* @performance Expected constant time. If billboards were removed from the collection and
* {@link BillboardCollection#update} was not called, an implicit <code>O(n)</code>
* operation is performed.
*
* @exception {DeveloperError} index is required.
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#getLength
*
* @example
* // Toggle the show property of every billboard in the collection
* var len = billboards.getLength();
* for (var i = 0; i < len; ++i) {
* var b = billboards.get(i);
* b.setShow(!b.getShow());
* }
*/
BillboardCollection.prototype.get = function(index) {
if (!defined(index)) {
throw new DeveloperError('index is required.');
}
removeBillboards(this);
return this._billboards[index];
};
/**
* Returns the number of billboards in this collection. This is commonly used with
* {@link BillboardCollection#get} to iterate over all the billboards
* in the collection.
*
* @memberof BillboardCollection
*
* @returns {Number} The number of billboards in this collection.
*
* @performance Expected constant time. If billboards were removed from the collection and
* {@link BillboardCollection#update} was not called, an implicit <code>O(n)</code>
* operation is performed.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#get
*
* @example
* // Toggle the show property of every billboard in the collection
* var len = billboards.getLength();
* for (var i = 0; i < len; ++i) {
* var b = billboards.get(i);
* b.setShow(!b.getShow());
* }
*/
BillboardCollection.prototype.getLength = function() {
removeBillboards(this);
return this._billboards.length;
};
/**
* DOC_TBA
*
* @memberof BillboardCollection
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#setTextureAtlas
* @see Billboard#setImageIndex
*/
BillboardCollection.prototype.getTextureAtlas = function() {
return this._textureAtlas;
};
/**
* DOC_TBA
*
* @memberof BillboardCollection
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#getTextureAtlas
* @see Billboard#setImageIndex
*
* @example
* // Assigns a texture atlas with two images to a billboard collection.
* // Two billboards, each referring to one of the images, are then
* // added to the collection.
* var billboards = new BillboardCollection();
* var images = [image0, image1];
* var atlas = context.createTextureAtlas({images : images});
* billboards.setTextureAtlas(atlas);
* billboards.add({
* // ...
* imageIndex : 0
* });
* billboards.add({
* // ...
* imageIndex : 1
* });
*/
BillboardCollection.prototype.setTextureAtlas = function(value) {
if (this._textureAtlas !== value) {
this._textureAtlas = this._destroyTextureAtlas && this._textureAtlas && this._textureAtlas.destroy();
this._textureAtlas = value;
this._createVertexArray = true; // New per-billboard texture coordinates
}
};
/**
* Returns <code>true</code> if the texture atlas is destroyed when the collection is
* destroyed; otherwise, <code>false</code>.
*
* @memberof BillboardCollection
*
* @returns <code>true</code> if the texture atlas is destroyed when the collection is
* destroyed; otherwise, <code>false</code>.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#setDestroyTextureAtlas
*/
BillboardCollection.prototype.getDestroyTextureAtlas = function() {
return this._destroyTextureAtlas;
};
/**
* Determines if the texture atlas is destroyed when the collection is destroyed. If the texture
* atlas is used by more than one collection, set this to <code>false</code>, and explicitly
* destroy the atlas to avoid attempting to destroy it multiple times.
*
* @memberof BillboardCollection
*
* @param {Boolean} value Indicates if the texture atlas is destroyed when the collection is destroyed.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see BillboardCollection#getDestroyTextureAtlas
* @see BillboardCollection#setTextureAtlas
* @see BillboardCollection#destroy
*
* @example
* // Destroy a billboard collection but not its texture atlas.
*
* var atlas = context.createTextureAtlas({images : images});
* billboards.setTextureAtlas(atlas);
* billboards.setDestroyTextureAtlas(false);
* billboards = billboards.destroy();
* console.log(atlas.isDestroyed()); // False
*/
BillboardCollection.prototype.setDestroyTextureAtlas = function(value) {
this._destroyTextureAtlas = value;
};
function getDirectionsVertexBuffer(context) {
var sixteenK = 16 * 1024;
var directionsVertexBuffer = context.cache.billboardCollection_directionsVertexBuffer;
if (defined(directionsVertexBuffer)) {
return directionsVertexBuffer;
}
var directions = new Uint8Array(sixteenK * 4 * 2);
for (var i = 0, j = 0; i < sixteenK; ++i) {
directions[j++] = 0;
directions[j++] = 0;
directions[j++] = 255;
directions[j++] = 0.0;
directions[j++] = 255;
directions[j++] = 255;
directions[j++] = 0.0;
directions[j++] = 255;
}
// PERFORMANCE_IDEA: Should we reference count billboard collections, and eventually delete this?
// Is this too much memory to allocate up front? Should we dynamically grow it?
directionsVertexBuffer = context.createVertexBuffer(directions, BufferUsage.STATIC_DRAW);
directionsVertexBuffer.setVertexArrayDestroyable(false);
context.cache.billboardCollection_directionsVertexBuffer = directionsVertexBuffer;
return directionsVertexBuffer;
}
function getIndexBuffer(context) {
var sixteenK = 16 * 1024;
var indexBuffer = context.cache.billboardCollection_indexBuffer;
if (defined(indexBuffer)) {
return indexBuffer;
}
var length = sixteenK * 6;
var indices = new Uint16Array(length);
for (var i = 0, j = 0; i < length; i += 6, j += 4) {
indices[i] = j;
indices[i + 1] = j + 1;
indices[i + 2] = j + 2;
indices[i + 3] = j + 0;
indices[i + 4] = j + 2;
indices[i + 5] = j + 3;
}
// PERFORMANCE_IDEA: Should we reference count billboard collections, and eventually delete this?
// Is this too much memory to allocate up front? Should we dynamically grow it?
indexBuffer = context.createIndexBuffer(indices, BufferUsage.STATIC_DRAW, IndexDatatype.UNSIGNED_SHORT);
indexBuffer.setVertexArrayDestroyable(false);
context.cache.billboardCollection_indexBuffer = indexBuffer;
return indexBuffer;
}
BillboardCollection.prototype.computeNewBuffersUsage = function() {
var buffersUsage = this._buffersUsage;
var usageChanged = false;
var properties = this._propertiesChanged;
for ( var k = 0; k < NUMBER_OF_PROPERTIES; ++k) {
var newUsage = (properties[k] === 0) ? BufferUsage.STATIC_DRAW : BufferUsage.STREAM_DRAW;
usageChanged = usageChanged || (buffersUsage[k] !== newUsage);
buffersUsage[k] = newUsage;
}
return usageChanged;
};
function createVAF(context, numberOfBillboards, buffersUsage) {
// Different billboard collections share the same vertex buffer for directions.
var directionVertexBuffer = getDirectionsVertexBuffer(context);
return new VertexArrayFacade(context, [{
index : attributeIndices.positionHigh,
componentsPerAttribute : 3,
componentDatatype : ComponentDatatype.FLOAT,
usage : buffersUsage[POSITION_INDEX]
}, {
index : attributeIndices.positionLow,
componentsPerAttribute : 3,
componentDatatype : ComponentDatatype.FLOAT,
usage : buffersUsage[POSITION_INDEX]
}, {
index : attributeIndices.pixelOffset,
componentsPerAttribute : 2,
componentDatatype : ComponentDatatype.FLOAT,
usage : buffersUsage[PIXEL_OFFSET_INDEX]
}, {
index : attributeIndices.eyeOffsetAndScale,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.FLOAT,
usage : buffersUsage[SCALE_INDEX] // buffersUsage[EYE_OFFSET_INDEX] ignored
}, {
index : attributeIndices.textureCoordinatesAndImageSize,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.FLOAT,
usage : buffersUsage[IMAGE_INDEX_INDEX]
}, {
index : attributeIndices.pickColor,
componentsPerAttribute : 4,
normalize : true,
componentDatatype : ComponentDatatype.UNSIGNED_BYTE,
usage : BufferUsage.STATIC_DRAW,
purpose : pickPassPurpose
}, {
index : attributeIndices.color,
componentsPerAttribute : 4,
normalize : true,
componentDatatype : ComponentDatatype.UNSIGNED_BYTE,
usage : buffersUsage[COLOR_INDEX],
purpose : colorPassPurpose
}, {
index : attributeIndices.originAndShow,
componentsPerAttribute : 3,
componentDatatype : ComponentDatatype.BYTE,
usage : buffersUsage[SHOW_INDEX] // buffersUsage[HORIZONTAL_ORIGIN_INDEX] and buffersUsage[VERTICAL_ORIGIN_INDEX] ignored
}, {
index : attributeIndices.direction,
vertexBuffer : directionVertexBuffer,
componentsPerAttribute : 2,
normalize : true,
componentDatatype : ComponentDatatype.UNSIGNED_BYTE
}, {
index : attributeIndices.rotationAndAlignedAxis,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.FLOAT,
usage : buffersUsage[ROTATION_INDEX] // buffersUsage[ALIGNED_AXIS_INDEX] ignored
}, {
index : attributeIndices.scaleByDistance,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.FLOAT,
usage : buffersUsage[SCALE_BY_DISTANCE_INDEX]
}], 4 * numberOfBillboards); // 4 vertices per billboard
}
///////////////////////////////////////////////////////////////////////////
// Four vertices per billboard. Each has the same position, etc., but a different screen-space direction vector.
// PERFORMANCE_IDEA: Save memory if a property is the same for all billboards, use a latched attribute state,
// instead of storing it in a vertex buffer.
var writePositionScratch = new EncodedCartesian3();
function writePosition(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var position = billboard._getActualPosition();
if (billboardCollection._mode === SceneMode.SCENE3D) {
billboardCollection._baseVolume.expand(position, billboardCollection._baseVolume);
}
EncodedCartesian3.fromCartesian(position, writePositionScratch);
var allPurposeWriters = vafWriters[allPassPurpose];
var positionHighWriter = allPurposeWriters[attributeIndices.positionHigh];
var high = writePositionScratch.high;
positionHighWriter(i + 0, high.x, high.y, high.z);
positionHighWriter(i + 1, high.x, high.y, high.z);
positionHighWriter(i + 2, high.x, high.y, high.z);
positionHighWriter(i + 3, high.x, high.y, high.z);
var positionLowWriter = allPurposeWriters[attributeIndices.positionLow];
var low = writePositionScratch.low;
positionLowWriter(i + 0, low.x, low.y, low.z);
positionLowWriter(i + 1, low.x, low.y, low.z);
positionLowWriter(i + 2, low.x, low.y, low.z);
positionLowWriter(i + 3, low.x, low.y, low.z);
}
function writePixelOffset(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var pixelOffset = billboard.getPixelOffset();
billboardCollection._maxPixelOffset = Math.max(billboardCollection._maxPixelOffset, pixelOffset.x, pixelOffset.y);
var allPurposeWriters = vafWriters[allPassPurpose];
var writer = allPurposeWriters[attributeIndices.pixelOffset];
writer(i + 0, pixelOffset.x, pixelOffset.y);
writer(i + 1, pixelOffset.x, pixelOffset.y);
writer(i + 2, pixelOffset.x, pixelOffset.y);
writer(i + 3, pixelOffset.x, pixelOffset.y);
}
function writeEyeOffsetAndScale(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var eyeOffset = billboard.getEyeOffset();
var scale = billboard.getScale();
billboardCollection._maxEyeOffset = Math.max(billboardCollection._maxEyeOffset, Math.abs(eyeOffset.x), Math.abs(eyeOffset.y), Math.abs(eyeOffset.z));
billboardCollection._maxScale = Math.max(billboardCollection._maxScale, scale);
var allPurposeWriters = vafWriters[allPassPurpose];
var writer = allPurposeWriters[attributeIndices.eyeOffsetAndScale];
writer(i + 0, eyeOffset.x, eyeOffset.y, eyeOffset.z, scale);
writer(i + 1, eyeOffset.x, eyeOffset.y, eyeOffset.z, scale);
writer(i + 2, eyeOffset.x, eyeOffset.y, eyeOffset.z, scale);
writer(i + 3, eyeOffset.x, eyeOffset.y, eyeOffset.z, scale);
}
function writePickColor(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var pickWriters = vafWriters[pickPassPurpose];
var writer = pickWriters[attributeIndices.pickColor];
var pickColor = billboard.getPickId(context).color;
var red = Color.floatToByte(pickColor.red);
var green = Color.floatToByte(pickColor.green);
var blue = Color.floatToByte(pickColor.blue);
var alpha = Color.floatToByte(pickColor.alpha);
writer(i + 0, red, green, blue, alpha);
writer(i + 1, red, green, blue, alpha);
writer(i + 2, red, green, blue, alpha);
writer(i + 3, red, green, blue, alpha);
}
function writeColor(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var colorWriters = vafWriters[colorPassPurpose];
var writer = colorWriters[attributeIndices.color];
var color = billboard.getColor();
var red = Color.floatToByte(color.red);
var green = Color.floatToByte(color.green);
var blue = Color.floatToByte(color.blue);
var alpha = Color.floatToByte(color.alpha);
writer(i + 0, red, green, blue, alpha);
writer(i + 1, red, green, blue, alpha);
writer(i + 2, red, green, blue, alpha);
writer(i + 3, red, green, blue, alpha);
}
function writeOriginAndShow(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var horizontalOrigin = billboard.getHorizontalOrigin().value;
var verticalOrigin = billboard.getVerticalOrigin().value;
var show = billboard.getShow();
// If the color alpha is zero, do not show this billboard. This lets us avoid providing
// color during the pick pass and also eliminates a discard in the fragment shader.
if (billboard.getColor().alpha === 0.0) {
show = false;
}
billboardCollection._allHorizontalCenter = billboardCollection._allHorizontalCenter && horizontalOrigin === HorizontalOrigin.CENTER.value;
var allPurposeWriters = vafWriters[allPassPurpose];
var writer = allPurposeWriters[attributeIndices.originAndShow];
writer(i + 0, horizontalOrigin, verticalOrigin, show);
writer(i + 1, horizontalOrigin, verticalOrigin, show);
writer(i + 2, horizontalOrigin, verticalOrigin, show);
writer(i + 3, horizontalOrigin, verticalOrigin, show);
}
function writeTextureCoordinatesAndImageSize(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var bottomLeftX = 0;
var bottomLeftY = 0;
var width = 0;
var height = 0;
var index = billboard.getImageIndex();
if (index !== -1) {
var imageRectangle = textureAtlasCoordinates[index];
if (!defined(imageRectangle)) {
throw new DeveloperError('Invalid billboard image index: ' + index);
}
bottomLeftX = imageRectangle.x;
bottomLeftY = imageRectangle.y;
width = imageRectangle.width;
height = imageRectangle.height;
}
var topRightX = bottomLeftX + width;
var topRightY = bottomLeftY + height;
var dimensions = billboardCollection._textureAtlas.getTexture().getDimensions();
var imageWidth = defaultValue(billboard.getWidth(), dimensions.x * width) * 0.5;
var imageHeight = defaultValue(billboard.getHeight(), dimensions.y * height) * 0.5;
billboardCollection._maxSize = Math.max(billboardCollection._maxSize, imageWidth, imageHeight);
var allPurposeWriters = vafWriters[allPassPurpose];
var writer = allPurposeWriters[attributeIndices.textureCoordinatesAndImageSize];
writer(i + 0, bottomLeftX, bottomLeftY, imageWidth, imageHeight); // Lower Left
writer(i + 1, topRightX, bottomLeftY, imageWidth, imageHeight); // Lower Right
writer(i + 2, topRightX, topRightY, imageWidth, imageHeight); // Upper Right
writer(i + 3, bottomLeftX, topRightY, imageWidth, imageHeight); // Upper Left
}
function writeRotationAndAlignedAxis(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var rotation = billboard.getRotation();
var alignedAxis = billboard.getAlignedAxis();
if (rotation !== 0.0 || !Cartesian3.equals(alignedAxis, Cartesian3.ZERO)) {
billboardCollection._shaderRotation = true;
}
var x = alignedAxis.x;
var y = alignedAxis.y;
var z = alignedAxis.z;
var allPurposeWriters = vafWriters[allPassPurpose];
var writer = allPurposeWriters[attributeIndices.rotationAndAlignedAxis];
writer(i + 0, rotation, x, y, z);
writer(i + 1, rotation, x, y, z);
writer(i + 2, rotation, x, y, z);
writer(i + 3, rotation, x, y, z);
}
function writeScaleByDistance(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
var i = billboard._index * 4;
var allPurposeWriters = vafWriters[allPassPurpose];
var writer = allPurposeWriters[attributeIndices.scaleByDistance];
var near = 0.0;
var nearValue = 0.0;
var far = 0.0;
var farValue = 0.0;
var scale = billboard.getScaleByDistance();
if (defined(scale)) {
near = scale.near;
nearValue = scale.nearValue;
far = scale.far;
farValue = scale.farValue;
if (nearValue !== 1.0 || farValue !== 1.0) {
// scale by distance calculation in shader need not be enabled
// until a billboard with near and far !== 1.0 is found
billboardCollection._shaderScaleByDistance = true;
}
}
writer(i + 0, near, nearValue, far, farValue);
writer(i + 1, near, nearValue, far, farValue);
writer(i + 2, near, nearValue, far, farValue);
writer(i + 3, near, nearValue, far, farValue);
}
function writeBillboard(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard) {
writePosition(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writePixelOffset(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writeEyeOffsetAndScale(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writePickColor(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writeColor(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writeOriginAndShow(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writeTextureCoordinatesAndImageSize(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writeRotationAndAlignedAxis(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
writeScaleByDistance(billboardCollection, context, textureAtlasCoordinates, vafWriters, billboard);
}
function recomputeActualPositions(billboardCollection, billboards, length, frameState, modelMatrix, recomputeBoundingVolume) {
var boundingVolume;
if (frameState.mode === SceneMode.SCENE3D) {
boundingVolume = billboardCollection._baseVolume;
} else {
boundingVolume = billboardCollection._baseVolume2D;
}
var positions = [];
for ( var i = 0; i < length; ++i) {
var billboard = billboards[i];
var position = billboard.getPosition();
var actualPosition = Billboard._computeActualPosition(position, frameState, modelMatrix);
if (defined(actualPosition)) {
billboard._setActualPosition(actualPosition);
if (recomputeBoundingVolume) {
positions.push(actualPosition);
} else {
boundingVolume.expand(actualPosition, boundingVolume);
}
}
}
if (recomputeBoundingVolume) {
BoundingSphere.fromPoints(positions, boundingVolume);
}
}
function updateMode(billboardCollection, frameState) {
var mode = frameState.mode;
var projection = frameState.scene2D.projection;
var billboards = billboardCollection._billboards;
var billboardsToUpdate = billboardCollection._billboardsToUpdate;
var modelMatrix = billboardCollection._modelMatrix;
if (billboardCollection._mode !== mode ||
billboardCollection._projection !== projection ||
mode !== SceneMode.SCENE3D &&
!modelMatrix.equals(billboardCollection.modelMatrix)) {
billboardCollection._mode = mode;
billboardCollection._projection = projection;
billboardCollection.modelMatrix.clone(modelMatrix);
billboardCollection._createVertexArray = true;
if (mode === SceneMode.SCENE3D || mode === SceneMode.SCENE2D || mode === SceneMode.COLUMBUS_VIEW) {
recomputeActualPositions(billboardCollection, billboards, billboards.length, frameState, modelMatrix, true);
}
} else if (mode === SceneMode.MORPHING) {
recomputeActualPositions(billboardCollection, billboards, billboards.length, frameState, modelMatrix, true);
} else if (mode === SceneMode.SCENE2D || mode === SceneMode.COLUMBUS_VIEW) {
recomputeActualPositions(billboardCollection, billboardsToUpdate, billboardCollection._billboardsToUpdateIndex, frameState, modelMatrix, false);
}
}
var scratchCanvasDimensions = new Cartesian2();
var scratchToCenter = new Cartesian3();
var scratchProj = new Cartesian3();
function updateBoundingVolume(collection, context, frameState, boundingVolume) {
var camera = frameState.camera;
var frustum = camera.frustum;
var pixelScale;
var size;
var offset;
var toCenter = camera.positionWC.subtract(boundingVolume.center, scratchToCenter);
var proj = camera.directionWC.multiplyByScalar(toCenter.dot(camera.directionWC), scratchProj);
var distance = Math.max(0.0, proj.magnitude() - boundingVolume.radius);
var canvas = context.getCanvas();
scratchCanvasDimensions.x = canvas.clientWidth;
scratchCanvasDimensions.y = canvas.clientHeight;
var pixelSize = frustum.getPixelSize(scratchCanvasDimensions, distance);
pixelScale = Math.max(pixelSize.x, pixelSize.y);
size = pixelScale * collection._maxScale * collection._maxSize * 2.0;
if (collection._allHorizontalCenter) {
size *= 0.5;
}
offset = pixelScale * collection._maxPixelOffset + collection._maxEyeOffset;
boundingVolume.radius += size + offset;
}
/**
* @private
*/
BillboardCollection.prototype.update = function(context, frameState, commandList) {
var textureAtlas = this._textureAtlas;
if (!defined(textureAtlas)) {