/
Model.js
2690 lines (2327 loc) · 105 KB
/
Model.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/BoundingSphere',
'../Core/Cartesian2',
'../Core/Cartesian3',
'../Core/Cartesian4',
'../Core/clone',
'../Core/combine',
'../Core/defaultValue',
'../Core/defined',
'../Core/defineProperties',
'../Core/destroyObject',
'../Core/DeveloperError',
'../Core/Event',
'../Core/IndexDatatype',
'../Core/loadArrayBuffer',
'../Core/loadImage',
'../Core/loadText',
'../Core/Math',
'../Core/Matrix2',
'../Core/Matrix3',
'../Core/Matrix4',
'../Core/PrimitiveType',
'../Core/Quaternion',
'../Core/Queue',
'../Core/RuntimeError',
'../Renderer/BufferUsage',
'../Renderer/DrawCommand',
'../Renderer/ShaderSource',
'../Renderer/TextureMinificationFilter',
'../Renderer/TextureWrap',
'../ThirdParty/gltfDefaults',
'../ThirdParty/Uri',
'./getModelAccessor',
'./ModelAnimationCache',
'./ModelAnimationCollection',
'./ModelMaterial',
'./ModelMesh',
'./ModelNode',
'./Pass',
'./SceneMode'
], function(
BoundingSphere,
Cartesian2,
Cartesian3,
Cartesian4,
clone,
combine,
defaultValue,
defined,
defineProperties,
destroyObject,
DeveloperError,
Event,
IndexDatatype,
loadArrayBuffer,
loadImage,
loadText,
CesiumMath,
Matrix2,
Matrix3,
Matrix4,
PrimitiveType,
Quaternion,
Queue,
RuntimeError,
BufferUsage,
DrawCommand,
ShaderSource,
TextureMinificationFilter,
TextureWrap,
gltfDefaults,
Uri,
getModelAccessor,
ModelAnimationCache,
ModelAnimationCollection,
ModelMaterial,
ModelMesh,
ModelNode,
Pass,
SceneMode) {
"use strict";
/*global WebGLRenderingContext*/
var yUpToZUp = Matrix4.fromRotationTranslation(Matrix3.fromRotationX(CesiumMath.PI_OVER_TWO));
var ModelState = {
NEEDS_LOAD : 0,
LOADING : 1,
LOADED : 2,
FAILED : 3
};
function LoadResources() {
this.buffersToCreate = new Queue();
this.buffers = {};
this.pendingBufferLoads = 0;
this.programsToCreate = new Queue();
this.shaders = {};
this.pendingShaderLoads = 0;
this.texturesToCreate = new Queue();
this.pendingTextureLoads = 0;
this.createSamplers = true;
this.createSkins = true;
this.createRuntimeAnimations = true;
this.createVertexArrays = true;
this.createRenderStates = true;
this.createUniformMaps = true;
this.createRuntimeNodes = true;
this.skinnedNodesNames = [];
}
LoadResources.prototype.finishedPendingLoads = function() {
return ((this.pendingBufferLoads === 0) &&
(this.pendingShaderLoads === 0) &&
(this.pendingTextureLoads === 0));
};
LoadResources.prototype.finishedResourceCreation = function() {
return ((this.buffersToCreate.length === 0) &&
(this.programsToCreate.length === 0) &&
(this.texturesToCreate.length === 0));
};
LoadResources.prototype.finishedBuffersCreation = function() {
return ((this.pendingBufferLoads === 0) && (this.buffersToCreate.length === 0));
};
LoadResources.prototype.finishedProgramCreation = function() {
return ((this.pendingShaderLoads === 0) && (this.programsToCreate.length === 0));
};
LoadResources.prototype.finishedTextureCreation = function() {
return ((this.pendingTextureLoads === 0) && (this.texturesToCreate.length === 0));
};
///////////////////////////////////////////////////////////////////////////
// glTF JSON can be big given embedded geometry, textures, and animations, so we
// cache it across all models using the same url/cache-key. This also reduces the
// slight overhead in assigning defaults to missing values.
//
// Note that this is a global cache, compared to renderer resources, which
// are cached per context.
var CachedGltf = function(options) {
this._gltf = gltfDefaults(options.gltf);
this.ready = options.ready;
this.modelsToLoad = [];
this.count = 0;
};
defineProperties(CachedGltf.prototype, {
gltf : {
set : function(value) {
this._gltf = gltfDefaults(value);
},
get : function() {
return this._gltf;
}
}
});
var gltfCache = {};
function getAnimationIds(cachedGltf) {
var animationIds = [];
if (defined(cachedGltf) && defined(cachedGltf.gltf)) {
var animations = cachedGltf.gltf.animations;
for (var name in animations) {
if (animations.hasOwnProperty(name)) {
animationIds.push(name);
}
}
}
return animationIds;
}
///////////////////////////////////////////////////////////////////////////
/**
* A 3D model based on glTF, the runtime asset format for WebGL, OpenGL ES, and OpenGL.
* <p>
* Cesium includes support for geometry and materials, glTF animations, and glTF skinning.
* In addition, individual glTF nodes are pickable with {@link Scene#pick} and animatable
* with {@link Model#getNode}. glTF cameras and lights are not currently supported.
* </p>
* <p>
* An external glTF asset is created with {@link Model.fromGltf}. glTF JSON can also be
* created at runtime and passed to this constructor function. In either case, the
* {@link Model#readyToRender} event is fired when the model is ready to render, i.e.,
* when the external binary, image, and shader files are downloaded and the WebGL
* resources are created.
* </p>
*
* @alias Model
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Object} [options.gltf] The object for the glTF JSON.
* @param {String} [options.basePath=''] The base path that paths in the glTF JSON are relative to.
* @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
* @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
* @param {Number} [options.scale=1.0] A uniform scale applied to this model.
* @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
* @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}.
* @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}.
* @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
* @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
*
* @see Model.fromGltf
* @see Model#readyToRender
*
* @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=3D%20Models.html|Cesium Sandcastle Models Demo}
*/
var Model = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
var cacheKey = options.cacheKey;
this._cacheKey = cacheKey;
this._cachedGltf = undefined;
this._releaseGltfJson = defaultValue(options.releaseGltfJson, false);
this._animationIds = undefined;
var cachedGltf;
if (defined(cacheKey) && defined(gltfCache[cacheKey]) && gltfCache[cacheKey].ready) {
// glTF JSON is in cache and ready
cachedGltf = gltfCache[cacheKey];
++cachedGltf.count;
} else {
// glTF was explicitly provided, e.g., when a user uses the Model constructor directly
if (defined(options.gltf)) {
cachedGltf = new CachedGltf({
gltf : options.gltf,
ready : true
});
cachedGltf.count = 1;
if (defined(cacheKey)) {
gltfCache[cacheKey] = cachedGltf;
}
}
}
setCachedGltf(this, cachedGltf);
this._basePath = defaultValue(options.basePath, '');
var docUri = new Uri(document.location.href);
var modelUri = new Uri(this._basePath);
this._baseUri = modelUri.resolve(docUri);
/**
* Determines if the model primitive will be shown.
*
* @type {Boolean}
*
* @default true
*/
this.show = defaultValue(options.show, true);
/**
* The 4x4 transformation matrix that transforms the model from model to world coordinates.
* When this is the identity matrix, the model is 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}.
*
* @type {Matrix4}
*
* @default {@link Matrix4.IDENTITY}
*
* @example
* var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
* m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
*/
this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY));
this._modelMatrix = Matrix4.clone(this.modelMatrix);
/**
* A uniform scale applied to this model before the {@link Model#modelMatrix}.
* Values greater than <code>1.0</code> increase the size of the model; values
* less than <code>1.0</code> decrease.
*
* @type {Number}
*
* @default 1.0
*/
this.scale = defaultValue(options.scale, 1.0);
this._scale = this.scale;
/**
* The approximate minimum pixel size of the model regardless of zoom.
* This can be used to ensure that a model is visible even when the viewer
* zooms out. When <code>0.0</code>, no minimum size is enforced.
*
* @type {Number}
*
* @default 0.0
*/
this.minimumPixelSize = defaultValue(options.minimumPixelSize, 0.0);
this._minimumPixelSize = this.minimumPixelSize;
/**
* User-defined object returned when the model is picked.
*
* @type Object
*
* @default undefined
*
* @see Scene#pick
*/
this.id = options.id;
this._id = options.id;
/**
* Used for picking primitives that wrap a model.
*
* @private
*/
this.pickPrimitive = options.pickPrimitive;
this._allowPicking = defaultValue(options.allowPicking, true);
/**
* The event fired when this model is ready to render, i.e., when the external binary, image,
* and shader files were downloaded and the WebGL resources were created.
* <p>
* This event is fired at the end of the frame before the first frame the model is rendered in.
* </p>
*
* @type {Event}
* @default new Event()
*
* @example
* // Play all animations at half-speed when the model is ready to render
* model.readyToRender.addEventListener(function(model) {
* model.activeAnimations.addAll({
* speedup : 0.5
* });
* });
*
* @see Model#ready
*/
this.readyToRender = new Event();
this._ready = false;
/**
* The currently playing glTF animations.
*
* @type {ModelAnimationCollection}
*/
this.activeAnimations = new ModelAnimationCollection(this);
this._asynchronous = defaultValue(options.asynchronous, true);
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the bounding sphere for each draw command in the model. A glTF primitive corresponds
* to one draw command. A glTF mesh has an array of primitives, often of length one.
* </p>
*
* @type {Boolean}
*
* @default false
*/
this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false);
this._debugShowBoudingVolume = false;
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the model in wireframe.
* </p>
*
* @type {Boolean}
*
* @default false
*/
this.debugWireframe = defaultValue(options.debugWireframe, false);
this._debugWireframe = false;
this._computedModelMatrix = new Matrix4(); // Derived from modelMatrix and scale
this._initialRadius = undefined; // Radius without model's scale property, model-matrix scale, animations, or skins
this._boundingSphere = undefined;
this._state = ModelState.NEEDS_LOAD;
this._loadError = undefined;
this._loadResources = undefined;
this._perNodeShowDirty = false; // true when the Cesium API was used to change a node's show property
this._cesiumAnimationsDirty = false; // true when the Cesium API, not a glTF animation, changed a node transform
this._maxDirtyNumber = 0; // Used in place of a dirty boolean flag to avoid an extra graph traversal
this._runtime = {
animations : undefined,
rootNodes : undefined,
nodes : undefined, // Indexed with the node property's name, i.e., glTF id
nodesByName : undefined, // Indexed with name property in the node
skinnedNodes : undefined,
meshesByName : undefined, // Indexed with the name property in the mesh
materialsByName : undefined, // Indexed with the name property in the material
materialsById : undefined // Indexed with the material's property name
};
this._uniformMaps = {}; // Not cached since it can be targeted by glTF animation
this._rendererResources = { // Cached between models with the same url/cache-key
buffers : {},
vertexArrays : {},
programs : {},
pickPrograms : {},
textures : {},
samplers : {},
renderStates : {}
};
this._cachedRendererResources = undefined;
this._loadRendererResourcesFromCache = false;
this._nodeCommands = [];
this._pickIds = [];
};
function setCachedGltf(model, cachedGltf) {
model._cachedGltf = cachedGltf;
model._animationIds = getAnimationIds(cachedGltf);
}
defineProperties(Model.prototype, {
/**
* The object for the glTF JSON, including properties with default values omitted
* from the JSON provided to this model.
*
* @memberof Model.prototype
*
* @type {Object}
* @readonly
*
* @default undefined
*/
gltf : {
get : function() {
return defined(this._cachedGltf) ? this._cachedGltf.gltf : undefined;
}
},
/**
* When <code>true</code>, the glTF JSON is not stored with the model once the model is
* loaded (when {@link Model#ready} is <code>true</code>). This saves memory when
* geometry, textures, and animations are embedded in the .gltf file, which is the
* default for the {@link http://cesiumjs.org/convertmodel.html|Cesium model converter}.
* This is especially useful for cases like 3D buildings, where each .gltf model is unique
* and caching the glTF JSON is not effective.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default false
*
* @private
*/
releaseGltfJson : {
get : function() {
return this._releaseGltfJson;
}
},
/**
* The key identifying this model in the model cache for glTF JSON, renderer resources, and animations.
* Caching saves memory and improves loading speed when several models with the same url are created.
* <p>
* This key is automatically generated when the model is created with {@link Model.fromGltf}. If the model
* is created directly from glTF JSON using the {@link Model} constructor, this key can be manually
* provided; otherwise, the model will not be changed.
* </p>
*
* @memberof Model.prototype
*
* @type {String}
* @readonly
*
* @private
*/
cacheKey : {
get : function() {
return this._cacheKey;
}
},
/**
* The base path that paths in the glTF JSON are relative to. The base
* path is the same path as the path containing the .json file
* minus the .json file, when binary, image, and shader files are
* in the same directory as the .json. When this is <code>''</code>,
* the app's base path is used.
*
* @memberof Model.prototype
*
* @type {String}
* @readonly
*
* @default ''
*/
basePath : {
get : function() {
return this._basePath;
}
},
/**
* The model's bounding sphere in its local coordinate system. This does not take into
* account glTF animation and skins or {@link Model#scale}.
*
* @memberof Model.prototype
*
* @type {BoundingSphere}
* @readonly
*
* @default undefined
*
* @exception {DeveloperError} The model is not loaded. Wait for the model's readyToRender event or ready property.
*
* @example
* // Center in WGS84 coordinates
* var center = Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, new Cesium.Cartesian3());
*/
boundingSphere : {
get : function() {
//>>includeStart('debug', pragmas.debug);
if (this._state !== ModelState.LOADED) {
throw new DeveloperError('The model is not loaded. Wait for the model\'s readyToRender event or ready property.');
}
//>>includeEnd('debug');
this._boundingSphere.radius = (this.scale * Matrix4.getMaximumScale(this.modelMatrix)) * this._initialRadius;
return this._boundingSphere;
}
},
/**
* When <code>true</code>, this model is ready to render, i.e., the external binary, image,
* and shader files were downloaded and the WebGL resources were created. This is set to
* <code>true</code> right before {@link Model#readyToRender} is fired.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default false
*
* @see Model#readyToRender
*/
ready : {
get : function() {
return this._ready;
}
},
/**
* Determines if model WebGL resource creation will be spread out over several frames or
* block until completion once all glTF files are loaded.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default true
*/
asynchronous : {
get : function() {
return this._asynchronous;
}
},
/**
* When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}. When <code>false</code>, GPU memory is saved.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default true
*/
allowPicking : {
get : function() {
return this._allowPicking;
}
}
});
/**
* Creates a model from a glTF asset. When the model is ready to render, i.e., when the external binary, image,
* and shader files are downloaded and the WebGL resources are created, the {@link Model#readyToRender} event is fired.
*
* @param {Object} options Object with the following properties:
* @param {String} options.url The url to the .gltf file.
* @param {Object} [options.headers] HTTP headers to send with the request.
* @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
* @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
* @param {Number} [options.scale=1.0] A uniform scale applied to this model.
* @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
* @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}.
* @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each {@link DrawCommand} in the model.
* @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
* @returns {Model} The newly created model.
*
* @see Model#readyToRender
*
* @example
* // Example 1. Create a model from a glTF asset
* var model = scene.primitives.add(Cesium.Model.fromGltf({
* url : './duck/duck.json'
* }));
*
* @example
* // Example 2. Create model and provide all properties and events
* var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
* var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
*
* var model = scene.primitives.add(Model.fromGltf({
* url : './duck/duck.json',
* show : true, // default
* modelMatrix : modelMatrix,
* scale : 2.0, // double size
* minimumPixelSize : 128, // never smaller than 128 pixels
* allowPicking : false, // not pickable
* debugShowBoundingVolume : false, // default
* debugWireframe : false
* }));
*
* model.readyToRender.addEventListener(function(model) {
* // Play all animations when the model is ready to render
* model.activeAnimations.addAll();
* });
*/
Model.fromGltf = function(options) {
//>>includeStart('debug', pragmas.debug);
if (!defined(options) || !defined(options.url)) {
throw new DeveloperError('options.url is required');
}
//>>includeEnd('debug');
var url = options.url;
var basePath = '';
var i = url.lastIndexOf('/');
if (i !== -1) {
basePath = url.substring(0, i + 1);
}
var cacheKey = options.cacheKey;
if (!defined(cacheKey)) {
// Use absolute URL, since two URLs with different relative paths could point to the same model.
var docUri = new Uri(document.location.href);
var modelUri = new Uri(url);
cacheKey = modelUri.resolve(docUri).toString();
}
options = clone(options);
options.basePath = basePath;
options.cacheKey = cacheKey;
var model = new Model(options);
var cachedGltf = gltfCache[cacheKey];
if (!defined(cachedGltf)) {
cachedGltf = new CachedGltf({
ready : false
});
cachedGltf.count = 1;
cachedGltf.modelsToLoad.push(model);
setCachedGltf(model, cachedGltf);
gltfCache[cacheKey] = cachedGltf;
loadText(url, options.headers).then(function(data) {
cachedGltf.gltf = JSON.parse(data);
var models = cachedGltf.modelsToLoad;
var length = models.length;
for (var i = 0; i < length; ++i) {
var m = models[i];
if (!m.isDestroyed()) {
setCachedGltf(m, cachedGltf);
}
}
cachedGltf.modelsToLoad = undefined;
cachedGltf.ready = true;
}).otherwise(getFailedLoadFunction(model, 'gltf', url));
} else if (!cachedGltf.ready) {
// Cache hit but the loadText() request is still pending
++cachedGltf.count;
cachedGltf.modelsToLoad.push(model);
}
// else if the cached glTF is defined and ready, the
// model constructor will pick it up using the cache key.
return model;
};
/**
* For the unit tests to verify model caching.
*
* @private
*/
Model._gltfCache = gltfCache;
function getRuntime(model, runtimeName, name) {
//>>includeStart('debug', pragmas.debug);
if (model._state !== ModelState.LOADED) {
throw new DeveloperError('The model is not loaded. Wait for the model\'s readyToRender event or ready property.');
}
if (!defined(name)) {
throw new DeveloperError('name is required.');
}
//>>includeEnd('debug');
return (model._runtime[runtimeName])[name];
}
/**
* Returns the glTF node with the given <code>name</code> property. This is used to
* modify a node's transform for animation outside of glTF animations.
*
* @param {String} name The glTF name of the node.
* @returns {ModelNode} The node or <code>undefined</code> if no node with <code>name</code> exists.
*
* @exception {DeveloperError} The model is not loaded. Wait for the model's readyToRender event or ready property.
*
* @example
* // Apply non-uniform scale to node LOD3sp
* var node = model.getNode('LOD3sp');
* node.matrix =Cesium. Matrix4.fromScale(new Cesium.Cartesian3(5.0, 1.0, 1.0), node.matrix);
*/
Model.prototype.getNode = function(name) {
var node = getRuntime(this, 'nodesByName', name);
return defined(node) ? node.publicNode : undefined;
};
/**
* Returns the glTF mesh with the given <code>name</code> property.
*
* @param {String} name The glTF name of the mesh.
*
* @returns {ModelMesh} The mesh or <code>undefined</code> if no mesh with <code>name</code> exists.
*
* @exception {DeveloperError} The model is not loaded. Wait for the model's readyToRender event or ready property.
*/
Model.prototype.getMesh = function(name) {
return getRuntime(this, 'meshesByName', name);
};
/**
* Returns the glTF material with the given <code>name</code> property.
*
* @param {String} name The glTF name of the material.
* @returns {ModelMaterial} The material or <code>undefined</code> if no material with <code>name</code> exists.
*
* @exception {DeveloperError} The model is not loaded. Wait for the model's readyToRender event or ready property.
*/
Model.prototype.getMaterial = function(name) {
return getRuntime(this, 'materialsByName', name);
};
var aMinScratch = new Cartesian3();
var aMaxScratch = new Cartesian3();
function computeBoundingSphere(gltf) {
var gltfNodes = gltf.nodes;
var gltfMeshes = gltf.meshes;
var gltfAccessors = gltf.accessors;
var rootNodes = gltf.scenes[gltf.scene].nodes;
var rootNodesLength = rootNodes.length;
var nodeStack = [];
var min = new Cartesian3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var max = new Cartesian3(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
for (var i = 0; i < rootNodesLength; ++i) {
var n = gltfNodes[rootNodes[i]];
n._transformToRoot = getTransform(n);
nodeStack.push(n);
while (nodeStack.length > 0) {
n = nodeStack.pop();
var transformToRoot = n._transformToRoot;
var meshes = defaultValue(n.meshes, defined(n.instanceSkin) ? n.instanceSkin.meshes : undefined);
if (defined(meshes)) {
var meshesLength = meshes.length;
for (var j = 0; j < meshesLength; ++j) {
var primitives = gltfMeshes[meshes[j]].primitives;
var primitivesLength = primitives.length;
for (var m = 0; m < primitivesLength; ++m) {
var position = primitives[m].attributes.POSITION;
if (defined(position)) {
var accessor = gltfAccessors[position];
var aMin = Cartesian3.fromArray(accessor.min, 0, aMinScratch);
var aMax = Cartesian3.fromArray(accessor.max, 0, aMaxScratch);
if (defined(min) && defined(max)) {
Matrix4.multiplyByPoint(transformToRoot, aMin, aMin);
Matrix4.multiplyByPoint(transformToRoot, aMax, aMax);
Cartesian3.minimumByComponent(min, aMin, min);
Cartesian3.maximumByComponent(max, aMax, max);
}
}
}
}
}
var children = n.children;
var childrenLength = children.length;
for (var k = 0; k < childrenLength; ++k) {
var child = gltfNodes[children[k]];
child._transformToRoot = getTransform(child);
Matrix4.multiplyTransformation(transformToRoot, child._transformToRoot, child._transformToRoot);
nodeStack.push(child);
}
delete n._transformToRoot;
}
}
var boundingSphere = BoundingSphere.fromCornerPoints(min, max);
return BoundingSphere.transformWithoutScale(boundingSphere, yUpToZUp, boundingSphere);
}
///////////////////////////////////////////////////////////////////////////
function getFailedLoadFunction(model, type, path) {
return function() {
model._loadError = new RuntimeError('Failed to load external ' + type + ': ' + path);
model._state = ModelState.FAILED;
};
}
function bufferLoad(model, name) {
return function(arrayBuffer) {
var loadResources = model._loadResources;
loadResources.buffers[name] = arrayBuffer;
--loadResources.pendingBufferLoads;
};
}
function parseBuffers(model) {
var buffers = model.gltf.buffers;
for (var name in buffers) {
if (buffers.hasOwnProperty(name)) {
++model._loadResources.pendingBufferLoads;
var buffer = buffers[name];
var uri = new Uri(buffer.uri);
var bufferPath = uri.resolve(model._baseUri).toString();
loadArrayBuffer(bufferPath).then(bufferLoad(model, name)).otherwise(getFailedLoadFunction(model, 'buffer', bufferPath));
}
}
}
function parseBufferViews(model) {
var bufferViews = model.gltf.bufferViews;
for (var name in bufferViews) {
if (bufferViews.hasOwnProperty(name)) {
model._loadResources.buffersToCreate.enqueue(name);
}
}
}
function shaderLoad(model, name) {
return function(source) {
var loadResources = model._loadResources;
loadResources.shaders[name] = source;
--loadResources.pendingShaderLoads;
};
}
function parseShaders(model) {
var shaders = model.gltf.shaders;
for (var name in shaders) {
if (shaders.hasOwnProperty(name)) {
++model._loadResources.pendingShaderLoads;
var shader = shaders[name];
var uri = new Uri(shader.uri);
var shaderPath = uri.resolve(model._baseUri).toString();
loadText(shaderPath).then(shaderLoad(model, name)).otherwise(getFailedLoadFunction(model, 'shader', shaderPath));
}
}
}
function parsePrograms(model) {
var programs = model.gltf.programs;
for (var name in programs) {
if (programs.hasOwnProperty(name)) {
model._loadResources.programsToCreate.enqueue(name);
}
}
}
function imageLoad(model, name) {
return function(image) {
var loadResources = model._loadResources;
--loadResources.pendingTextureLoads;
loadResources.texturesToCreate.enqueue({
name : name,
image : image
});
};
}
function parseTextures(model) {
var images = model.gltf.images;
var textures = model.gltf.textures;
for (var name in textures) {
if (textures.hasOwnProperty(name)) {
++model._loadResources.pendingTextureLoads;
var texture = textures[name];
var uri = new Uri(images[texture.source].uri);
var imagePath = uri.resolve(model._baseUri).toString();
loadImage(imagePath).then(imageLoad(model, name)).otherwise(getFailedLoadFunction(model, 'image', imagePath));
}
}
}
var nodeAxisScratch = new Cartesian3();
var nodeTranslationScratch = new Cartesian3();
var nodeQuaternionScratch = new Quaternion();
var nodeScaleScratch = new Cartesian3();
function getTransform(node) {
if (defined(node.matrix)) {
return Matrix4.fromArray(node.matrix);
}
var axis = Cartesian3.fromArray(node.rotation, 0, nodeAxisScratch);
return Matrix4.fromTranslationQuaternionRotationScale(
Cartesian3.fromArray(node.translation, 0, nodeTranslationScratch),
Quaternion.fromAxisAngle(axis, node.rotation[3], nodeQuaternionScratch),
Cartesian3.fromArray(node.scale, 0 , nodeScaleScratch));
}
function parseNodes(model) {
var runtimeNodes = {};
var runtimeNodesByName = {};
var skinnedNodes = [];
var skinnedNodesNames = model._loadResources.skinnedNodesNames;
var nodes = model.gltf.nodes;
for (var name in nodes) {
if (nodes.hasOwnProperty(name)) {
var node = nodes[name];
var runtimeNode = {
// Animation targets
matrix : undefined,
translation : undefined,
rotation : undefined,
scale : undefined,
// Per-node show inherited from parent
computedShow : true,
// Computed transforms
transformToRoot : new Matrix4(),
computedMatrix : new Matrix4(),
dirtyNumber : 0, // The frame this node was made dirty by an animation; for graph traversal
// Rendering
commands : [], // empty for transform, light, and camera nodes
// Skinned node
inverseBindMatrices : undefined, // undefined when node is not skinned
bindShapeMatrix : undefined, // undefined when node is not skinned or identity
joints : [], // empty when node is not skinned
computedJointMatrices : [], // empty when node is not skinned
// Joint node
jointName : node.jointName, // undefined when node is not a joint
// Graph pointers
children : [], // empty for leaf nodes
parents : [], // empty for root nodes
// Publicly-accessible ModelNode instance to modify animation targets
publicNode : undefined
};
runtimeNode.publicNode = new ModelNode(model, node, runtimeNode, name, getTransform(node));
runtimeNodes[name] = runtimeNode;
runtimeNodesByName[node.name] = runtimeNode;
if (defined(node.instanceSkin)) {
skinnedNodesNames.push(name);