@babylonjs/loaders 5.0.0-rc.5 → 5.0.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/OBJ/index.d.ts +4 -4
  2. package/OBJ/index.js +4 -4
  3. package/OBJ/mtlFileLoader.d.ts +41 -41
  4. package/OBJ/mtlFileLoader.js +232 -232
  5. package/OBJ/objFileLoader.d.ts +126 -126
  6. package/OBJ/objFileLoader.js +296 -296
  7. package/OBJ/objLoadingOptions.d.ts +43 -43
  8. package/OBJ/objLoadingOptions.js +1 -1
  9. package/OBJ/solidParser.d.ts +154 -154
  10. package/OBJ/solidParser.js +693 -693
  11. package/STL/index.d.ts +1 -1
  12. package/STL/index.js +1 -1
  13. package/STL/stlFileLoader.d.ts +64 -64
  14. package/STL/stlFileLoader.js +233 -233
  15. package/glTF/1.0/glTFBinaryExtension.d.ts +13 -13
  16. package/glTF/1.0/glTFBinaryExtension.js +60 -60
  17. package/glTF/1.0/glTFLoader.d.ts +136 -136
  18. package/glTF/1.0/glTFLoader.js +1815 -1815
  19. package/glTF/1.0/glTFLoaderInterfaces.d.ts +412 -412
  20. package/glTF/1.0/glTFLoaderInterfaces.js +95 -95
  21. package/glTF/1.0/glTFLoaderUtils.d.ts +62 -62
  22. package/glTF/1.0/glTFLoaderUtils.js +250 -250
  23. package/glTF/1.0/glTFMaterialsCommonExtension.d.ts +10 -10
  24. package/glTF/1.0/glTFMaterialsCommonExtension.js +129 -129
  25. package/glTF/1.0/index.d.ts +5 -5
  26. package/glTF/1.0/index.js +5 -5
  27. package/glTF/2.0/Extensions/EXT_lights_image_based.d.ts +43 -43
  28. package/glTF/2.0/Extensions/EXT_lights_image_based.js +117 -117
  29. package/glTF/2.0/Extensions/EXT_mesh_gpu_instancing.d.ts +36 -36
  30. package/glTF/2.0/Extensions/EXT_mesh_gpu_instancing.js +88 -88
  31. package/glTF/2.0/Extensions/EXT_meshopt_compression.d.ts +34 -34
  32. package/glTF/2.0/Extensions/EXT_meshopt_compression.js +49 -49
  33. package/glTF/2.0/Extensions/EXT_texture_webp.d.ts +29 -29
  34. package/glTF/2.0/Extensions/EXT_texture_webp.js +40 -40
  35. package/glTF/2.0/Extensions/ExtrasAsMetadata.d.ts +50 -50
  36. package/glTF/2.0/Extensions/ExtrasAsMetadata.js +73 -73
  37. package/glTF/2.0/Extensions/KHR_draco_mesh_compression.d.ts +39 -39
  38. package/glTF/2.0/Extensions/KHR_draco_mesh_compression.js +112 -112
  39. package/glTF/2.0/Extensions/KHR_lights_punctual.d.ts +36 -36
  40. package/glTF/2.0/Extensions/KHR_lights_punctual.js +89 -89
  41. package/glTF/2.0/Extensions/KHR_materials_clearcoat.d.ts +39 -39
  42. package/glTF/2.0/Extensions/KHR_materials_clearcoat.js +94 -94
  43. package/glTF/2.0/Extensions/KHR_materials_emissive_strength.d.ts +38 -38
  44. package/glTF/2.0/Extensions/KHR_materials_emissive_strength.js +53 -53
  45. package/glTF/2.0/Extensions/KHR_materials_ior.d.ts +42 -42
  46. package/glTF/2.0/Extensions/KHR_materials_ior.js +62 -62
  47. package/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.d.ts +38 -38
  48. package/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.js +80 -80
  49. package/glTF/2.0/Extensions/KHR_materials_sheen.d.ts +39 -39
  50. package/glTF/2.0/Extensions/KHR_materials_sheen.js +84 -84
  51. package/glTF/2.0/Extensions/KHR_materials_specular.d.ts +38 -38
  52. package/glTF/2.0/Extensions/KHR_materials_specular.js +74 -74
  53. package/glTF/2.0/Extensions/KHR_materials_translucency.d.ts +39 -39
  54. package/glTF/2.0/Extensions/KHR_materials_translucency.js +83 -83
  55. package/glTF/2.0/Extensions/KHR_materials_transmission.d.ts +38 -38
  56. package/glTF/2.0/Extensions/KHR_materials_transmission.js +288 -288
  57. package/glTF/2.0/Extensions/KHR_materials_unlit.d.ts +38 -38
  58. package/glTF/2.0/Extensions/KHR_materials_unlit.js +73 -73
  59. package/glTF/2.0/Extensions/KHR_materials_variants.d.ts +87 -87
  60. package/glTF/2.0/Extensions/KHR_materials_variants.js +254 -254
  61. package/glTF/2.0/Extensions/KHR_materials_volume.d.ts +39 -39
  62. package/glTF/2.0/Extensions/KHR_materials_volume.js +85 -85
  63. package/glTF/2.0/Extensions/KHR_mesh_quantization.d.ts +22 -22
  64. package/glTF/2.0/Extensions/KHR_mesh_quantization.js +23 -23
  65. package/glTF/2.0/Extensions/KHR_texture_basisu.d.ts +29 -29
  66. package/glTF/2.0/Extensions/KHR_texture_basisu.js +40 -40
  67. package/glTF/2.0/Extensions/KHR_texture_transform.d.ts +33 -33
  68. package/glTF/2.0/Extensions/KHR_texture_transform.js +61 -61
  69. package/glTF/2.0/Extensions/KHR_xmp_json_ld.d.ts +32 -32
  70. package/glTF/2.0/Extensions/KHR_xmp_json_ld.js +49 -49
  71. package/glTF/2.0/Extensions/MSFT_audio_emitter.d.ts +54 -54
  72. package/glTF/2.0/Extensions/MSFT_audio_emitter.js +240 -240
  73. package/glTF/2.0/Extensions/MSFT_lod.d.ts +109 -109
  74. package/glTF/2.0/Extensions/MSFT_lod.js +369 -369
  75. package/glTF/2.0/Extensions/MSFT_minecraftMesh.d.ts +14 -14
  76. package/glTF/2.0/Extensions/MSFT_minecraftMesh.js +36 -36
  77. package/glTF/2.0/Extensions/MSFT_sRGBFactors.d.ts +14 -14
  78. package/glTF/2.0/Extensions/MSFT_sRGBFactors.js +36 -36
  79. package/glTF/2.0/Extensions/index.d.ts +26 -26
  80. package/glTF/2.0/Extensions/index.js +26 -26
  81. package/glTF/2.0/glTFLoader.d.ts +405 -405
  82. package/glTF/2.0/glTFLoader.js +2366 -2366
  83. package/glTF/2.0/glTFLoaderExtension.d.ts +152 -152
  84. package/glTF/2.0/glTFLoaderExtension.js +1 -1
  85. package/glTF/2.0/glTFLoaderInterfaces.d.ts +211 -211
  86. package/glTF/2.0/glTFLoaderInterfaces.js +1 -1
  87. package/glTF/2.0/index.d.ts +4 -4
  88. package/glTF/2.0/index.js +4 -4
  89. package/glTF/glTFFileLoader.d.ts +433 -433
  90. package/glTF/glTFFileLoader.js +927 -927
  91. package/glTF/glTFValidation.d.ts +29 -29
  92. package/glTF/glTFValidation.js +123 -123
  93. package/glTF/index.d.ts +5 -5
  94. package/glTF/index.js +5 -5
  95. package/index.d.ts +3 -3
  96. package/index.js +3 -3
  97. package/legacy/legacy-glTF.d.ts +2 -2
  98. package/legacy/legacy-glTF.js +18 -18
  99. package/legacy/legacy-glTF1.d.ts +2 -2
  100. package/legacy/legacy-glTF1.js +14 -14
  101. package/legacy/legacy-glTF1FileLoader.d.ts +2 -2
  102. package/legacy/legacy-glTF1FileLoader.js +3 -3
  103. package/legacy/legacy-glTF2.d.ts +2 -2
  104. package/legacy/legacy-glTF2.js +32 -32
  105. package/legacy/legacy-glTF2FileLoader.d.ts +2 -2
  106. package/legacy/legacy-glTF2FileLoader.js +3 -3
  107. package/legacy/legacy-glTFFileLoader.d.ts +3 -3
  108. package/legacy/legacy-glTFFileLoader.js +4 -4
  109. package/legacy/legacy-objFileLoader.d.ts +1 -1
  110. package/legacy/legacy-objFileLoader.js +12 -12
  111. package/legacy/legacy-stlFileLoader.d.ts +1 -1
  112. package/legacy/legacy-stlFileLoader.js +12 -12
  113. package/legacy/legacy.d.ts +6 -6
  114. package/legacy/legacy.js +7 -7
  115. package/package.json +3 -3
@@ -1,1816 +1,1816 @@
1
- /* eslint-disable @typescript-eslint/no-unused-vars */
2
- import { EParameterType, ETextureFilterType, ECullingType, EBlendingFunction, EShaderType, } from "./glTFLoaderInterfaces.js";
3
- import { Quaternion, Vector3, Matrix } from "@babylonjs/core/Maths/math.vector.js";
4
- import { Color3 } from "@babylonjs/core/Maths/math.color.js";
5
- import { Tools } from "@babylonjs/core/Misc/tools.js";
6
- import { Camera } from "@babylonjs/core/Cameras/camera.js";
7
- import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera.js";
8
- import { Animation } from "@babylonjs/core/Animations/animation.js";
9
- import { Bone } from "@babylonjs/core/Bones/bone.js";
10
- import { Skeleton } from "@babylonjs/core/Bones/skeleton.js";
11
- import { Effect } from "@babylonjs/core/Materials/effect.js";
12
- import { Material } from "@babylonjs/core/Materials/material.js";
13
- import { MultiMaterial } from "@babylonjs/core/Materials/multiMaterial.js";
14
- import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js";
15
- import { ShaderMaterial } from "@babylonjs/core/Materials/shaderMaterial.js";
16
- import { Texture } from "@babylonjs/core/Materials/Textures/texture.js";
17
- import { VertexData } from "@babylonjs/core/Meshes/mesh.vertexData.js";
18
- import { VertexBuffer } from "@babylonjs/core/Buffers/buffer.js";
19
- import { Geometry } from "@babylonjs/core/Meshes/geometry.js";
20
- import { SubMesh } from "@babylonjs/core/Meshes/subMesh.js";
21
- import { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js";
22
- import { Mesh } from "@babylonjs/core/Meshes/mesh.js";
23
- import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js";
24
- import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight.js";
25
- import { PointLight } from "@babylonjs/core/Lights/pointLight.js";
26
- import { SpotLight } from "@babylonjs/core/Lights/spotLight.js";
27
- import { GLTFUtils } from "./glTFLoaderUtils.js";
28
- import { GLTFFileLoader } from "../glTFFileLoader.js";
29
- import { Constants } from "@babylonjs/core/Engines/constants.js";
30
- /**
31
- * Tokenizer. Used for shaders compatibility
32
- * Automatically map world, view, projection, worldViewProjection, attributes and so on
33
- */
34
- var ETokenType;
35
- (function (ETokenType) {
36
- ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
37
- ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
38
- ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
39
- })(ETokenType || (ETokenType = {}));
40
- var Tokenizer = /** @class */ (function () {
41
- function Tokenizer(toParse) {
42
- this._pos = 0;
43
- this.currentToken = ETokenType.UNKNOWN;
44
- this.currentIdentifier = "";
45
- this.currentString = "";
46
- this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
47
- this._toParse = toParse;
48
- this._maxPos = toParse.length;
49
- }
50
- Tokenizer.prototype.getNextToken = function () {
51
- if (this.isEnd()) {
52
- return ETokenType.END_OF_INPUT;
53
- }
54
- this.currentString = this.read();
55
- this.currentToken = ETokenType.UNKNOWN;
56
- if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
57
- this.currentToken = ETokenType.IDENTIFIER;
58
- this.currentIdentifier = this.currentString;
59
- while (!this.isEnd() && (this.isLetterOrDigitPattern.test((this.currentString = this.peek())) || this.currentString === "_")) {
60
- this.currentIdentifier += this.currentString;
61
- this.forward();
62
- }
63
- }
64
- return this.currentToken;
65
- };
66
- Tokenizer.prototype.peek = function () {
67
- return this._toParse[this._pos];
68
- };
69
- Tokenizer.prototype.read = function () {
70
- return this._toParse[this._pos++];
71
- };
72
- Tokenizer.prototype.forward = function () {
73
- this._pos++;
74
- };
75
- Tokenizer.prototype.isEnd = function () {
76
- return this._pos >= this._maxPos;
77
- };
78
- return Tokenizer;
79
- }());
80
- /**
81
- * Values
82
- */
83
- var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
84
- var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
85
- var glTFAnimationPaths = ["translation", "rotation", "scale"];
86
- var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
87
- /**
88
- * Parse
89
- * @param parsedBuffers
90
- * @param gltfRuntime
91
- */
92
- var parseBuffers = function (parsedBuffers, gltfRuntime) {
93
- for (var buf in parsedBuffers) {
94
- var parsedBuffer = parsedBuffers[buf];
95
- gltfRuntime.buffers[buf] = parsedBuffer;
96
- gltfRuntime.buffersCount++;
97
- }
98
- };
99
- var parseShaders = function (parsedShaders, gltfRuntime) {
100
- for (var sha in parsedShaders) {
101
- var parsedShader = parsedShaders[sha];
102
- gltfRuntime.shaders[sha] = parsedShader;
103
- gltfRuntime.shaderscount++;
104
- }
105
- };
106
- var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
107
- for (var object in parsedObjects) {
108
- var parsedObject = parsedObjects[object];
109
- gltfRuntime[runtimeProperty][object] = parsedObject;
110
- }
111
- };
112
- /**
113
- * Utils
114
- * @param buffer
115
- */
116
- var normalizeUVs = function (buffer) {
117
- if (!buffer) {
118
- return;
119
- }
120
- for (var i = 0; i < buffer.length / 2; i++) {
121
- buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
122
- }
123
- };
124
- var getAttribute = function (attributeParameter) {
125
- if (attributeParameter.semantic === "NORMAL") {
126
- return "normal";
127
- }
128
- else if (attributeParameter.semantic === "POSITION") {
129
- return "position";
130
- }
131
- else if (attributeParameter.semantic === "JOINT") {
132
- return "matricesIndices";
133
- }
134
- else if (attributeParameter.semantic === "WEIGHT") {
135
- return "matricesWeights";
136
- }
137
- else if (attributeParameter.semantic === "COLOR") {
138
- return "color";
139
- }
140
- else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
141
- var channel = Number(attributeParameter.semantic.split("_")[1]);
142
- return "uv" + (channel === 0 ? "" : channel + 1);
143
- }
144
- return null;
145
- };
146
- /**
147
- * Loads and creates animations
148
- * @param gltfRuntime
149
- */
150
- var loadAnimations = function (gltfRuntime) {
151
- for (var anim in gltfRuntime.animations) {
152
- var animation = gltfRuntime.animations[anim];
153
- if (!animation.channels || !animation.samplers) {
154
- continue;
155
- }
156
- var lastAnimation = null;
157
- for (var i = 0; i < animation.channels.length; i++) {
158
- // Get parameters and load buffers
159
- var channel = animation.channels[i];
160
- var sampler = animation.samplers[channel.sampler];
161
- if (!sampler) {
162
- continue;
163
- }
164
- var inputData = null;
165
- var outputData = null;
166
- if (animation.parameters) {
167
- inputData = animation.parameters[sampler.input];
168
- outputData = animation.parameters[sampler.output];
169
- }
170
- else {
171
- inputData = sampler.input;
172
- outputData = sampler.output;
173
- }
174
- var bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
175
- var bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
176
- var targetId = channel.target.id;
177
- var targetNode = gltfRuntime.scene.getNodeById(targetId);
178
- if (targetNode === null) {
179
- targetNode = gltfRuntime.scene.getNodeByName(targetId);
180
- }
181
- if (targetNode === null) {
182
- Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetId + " to attach to");
183
- continue;
184
- }
185
- var isBone = targetNode instanceof Bone;
186
- // Get target path (position, rotation or scaling)
187
- var targetPath = channel.target.path;
188
- var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
189
- if (targetPathIndex !== -1) {
190
- targetPath = babylonAnimationPaths[targetPathIndex];
191
- }
192
- // Determine animation type
193
- var animationType = Animation.ANIMATIONTYPE_MATRIX;
194
- if (!isBone) {
195
- if (targetPath === "rotationQuaternion") {
196
- animationType = Animation.ANIMATIONTYPE_QUATERNION;
197
- targetNode.rotationQuaternion = new Quaternion();
198
- }
199
- else {
200
- animationType = Animation.ANIMATIONTYPE_VECTOR3;
201
- }
202
- }
203
- // Create animation and key frames
204
- var babylonAnimation = null;
205
- var keys = [];
206
- var arrayOffset = 0;
207
- var modifyKey = false;
208
- if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
209
- babylonAnimation = lastAnimation;
210
- modifyKey = true;
211
- }
212
- if (!modifyKey) {
213
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
214
- babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
215
- gltfRuntime.scene._blockEntityCollection = false;
216
- }
217
- // For each frame
218
- for (var j = 0; j < bufferInput.length; j++) {
219
- var value = null;
220
- if (targetPath === "rotationQuaternion") {
221
- // VEC4
222
- value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
223
- arrayOffset += 4;
224
- }
225
- else {
226
- // Position and scaling are VEC3
227
- value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
228
- arrayOffset += 3;
229
- }
230
- if (isBone) {
231
- var bone = targetNode;
232
- var translation = Vector3.Zero();
233
- var rotationQuaternion = new Quaternion();
234
- var scaling = Vector3.Zero();
235
- // Warning on decompose
236
- var mat = bone.getBaseMatrix();
237
- if (modifyKey && lastAnimation) {
238
- mat = lastAnimation.getKeys()[j].value;
239
- }
240
- mat.decompose(scaling, rotationQuaternion, translation);
241
- if (targetPath === "position") {
242
- translation = value;
243
- }
244
- else if (targetPath === "rotationQuaternion") {
245
- rotationQuaternion = value;
246
- }
247
- else {
248
- scaling = value;
249
- }
250
- value = Matrix.Compose(scaling, rotationQuaternion, translation);
251
- }
252
- if (!modifyKey) {
253
- keys.push({
254
- frame: bufferInput[j],
255
- value: value,
256
- });
257
- }
258
- else if (lastAnimation) {
259
- lastAnimation.getKeys()[j].value = value;
260
- }
261
- }
262
- // Finish
263
- if (!modifyKey && babylonAnimation) {
264
- babylonAnimation.setKeys(keys);
265
- targetNode.animations.push(babylonAnimation);
266
- }
267
- lastAnimation = babylonAnimation;
268
- gltfRuntime.scene.stopAnimation(targetNode);
269
- gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
270
- }
271
- }
272
- };
273
- /**
274
- * Returns the bones transformation matrix
275
- * @param node
276
- */
277
- var configureBoneTransformation = function (node) {
278
- var mat = null;
279
- if (node.translation || node.rotation || node.scale) {
280
- var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
281
- var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
282
- var position = Vector3.FromArray(node.translation || [0, 0, 0]);
283
- mat = Matrix.Compose(scale, rotation, position);
284
- }
285
- else {
286
- mat = Matrix.FromArray(node.matrix);
287
- }
288
- return mat;
289
- };
290
- /**
291
- * Returns the parent bone
292
- * @param gltfRuntime
293
- * @param skins
294
- * @param jointName
295
- * @param newSkeleton
296
- */
297
- var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
298
- // Try to find
299
- for (var i = 0; i < newSkeleton.bones.length; i++) {
300
- if (newSkeleton.bones[i].name === jointName) {
301
- return newSkeleton.bones[i];
302
- }
303
- }
304
- // Not found, search in gltf nodes
305
- var nodes = gltfRuntime.nodes;
306
- for (var nde in nodes) {
307
- var node = nodes[nde];
308
- if (!node.jointName) {
309
- continue;
310
- }
311
- var children = node.children;
312
- for (var i = 0; i < children.length; i++) {
313
- var child = gltfRuntime.nodes[children[i]];
314
- if (!child.jointName) {
315
- continue;
316
- }
317
- if (child.jointName === jointName) {
318
- var mat = configureBoneTransformation(node);
319
- var bone = new Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
320
- bone.id = nde;
321
- return bone;
322
- }
323
- }
324
- }
325
- return null;
326
- };
327
- /**
328
- * Returns the appropriate root node
329
- * @param nodesToRoot
330
- * @param id
331
- */
332
- var getNodeToRoot = function (nodesToRoot, id) {
333
- for (var i = 0; i < nodesToRoot.length; i++) {
334
- var nodeToRoot = nodesToRoot[i];
335
- for (var j = 0; j < nodeToRoot.node.children.length; j++) {
336
- var child = nodeToRoot.node.children[j];
337
- if (child === id) {
338
- return nodeToRoot.bone;
339
- }
340
- }
341
- }
342
- return null;
343
- };
344
- /**
345
- * Returns the node with the joint name
346
- * @param gltfRuntime
347
- * @param jointName
348
- */
349
- var getJointNode = function (gltfRuntime, jointName) {
350
- var nodes = gltfRuntime.nodes;
351
- var node = nodes[jointName];
352
- if (node) {
353
- return {
354
- node: node,
355
- id: jointName,
356
- };
357
- }
358
- for (var nde in nodes) {
359
- node = nodes[nde];
360
- if (node.jointName === jointName) {
361
- return {
362
- node: node,
363
- id: nde,
364
- };
365
- }
366
- }
367
- return null;
368
- };
369
- /**
370
- * Checks if a nodes is in joints
371
- * @param skins
372
- * @param id
373
- */
374
- var nodeIsInJoints = function (skins, id) {
375
- for (var i = 0; i < skins.jointNames.length; i++) {
376
- if (skins.jointNames[i] === id) {
377
- return true;
378
- }
379
- }
380
- return false;
381
- };
382
- /**
383
- * Fills the nodes to root for bones and builds hierarchy
384
- * @param gltfRuntime
385
- * @param newSkeleton
386
- * @param skins
387
- * @param nodesToRoot
388
- */
389
- var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
390
- // Creates nodes for root
391
- for (var nde in gltfRuntime.nodes) {
392
- var node = gltfRuntime.nodes[nde];
393
- var id = nde;
394
- if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
395
- continue;
396
- }
397
- // Create node to root bone
398
- var mat = configureBoneTransformation(node);
399
- var bone = new Bone(node.name || "", newSkeleton, null, mat);
400
- bone.id = id;
401
- nodesToRoot.push({ bone: bone, node: node, id: id });
402
- }
403
- // Parenting
404
- for (var i = 0; i < nodesToRoot.length; i++) {
405
- var nodeToRoot = nodesToRoot[i];
406
- var children = nodeToRoot.node.children;
407
- for (var j = 0; j < children.length; j++) {
408
- var child = null;
409
- for (var k = 0; k < nodesToRoot.length; k++) {
410
- if (nodesToRoot[k].id === children[j]) {
411
- child = nodesToRoot[k];
412
- break;
413
- }
414
- }
415
- if (child) {
416
- child.bone._parent = nodeToRoot.bone;
417
- nodeToRoot.bone.children.push(child.bone);
418
- }
419
- }
420
- }
421
- };
422
- /**
423
- * Imports a skeleton
424
- * @param gltfRuntime
425
- * @param skins
426
- * @param mesh
427
- * @param newSkeleton
428
- */
429
- var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton) {
430
- if (!newSkeleton) {
431
- newSkeleton = new Skeleton(skins.name || "", "", gltfRuntime.scene);
432
- }
433
- if (!skins.babylonSkeleton) {
434
- return newSkeleton;
435
- }
436
- // Find the root bones
437
- var nodesToRoot = [];
438
- var nodesToRootToAdd = [];
439
- getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
440
- newSkeleton.bones = [];
441
- // Joints
442
- for (var i = 0; i < skins.jointNames.length; i++) {
443
- var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
444
- if (!jointNode) {
445
- continue;
446
- }
447
- var node = jointNode.node;
448
- if (!node) {
449
- Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
450
- continue;
451
- }
452
- var id = jointNode.id;
453
- // Optimize, if the bone already exists...
454
- var existingBone = gltfRuntime.scene.getBoneById(id);
455
- if (existingBone) {
456
- newSkeleton.bones.push(existingBone);
457
- continue;
458
- }
459
- // Search for parent bone
460
- var foundBone = false;
461
- var parentBone = null;
462
- for (var j = 0; j < i; j++) {
463
- var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
464
- if (!jointNode_1) {
465
- continue;
466
- }
467
- var joint = jointNode_1.node;
468
- if (!joint) {
469
- Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
470
- continue;
471
- }
472
- var children = joint.children;
473
- if (!children) {
474
- continue;
475
- }
476
- foundBone = false;
477
- for (var k = 0; k < children.length; k++) {
478
- if (children[k] === id) {
479
- parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
480
- foundBone = true;
481
- break;
482
- }
483
- }
484
- if (foundBone) {
485
- break;
486
- }
487
- }
488
- // Create bone
489
- var mat = configureBoneTransformation(node);
490
- if (!parentBone && nodesToRoot.length > 0) {
491
- parentBone = getNodeToRoot(nodesToRoot, id);
492
- if (parentBone) {
493
- if (nodesToRootToAdd.indexOf(parentBone) === -1) {
494
- nodesToRootToAdd.push(parentBone);
495
- }
496
- }
497
- }
498
- var bone = new Bone(node.jointName || "", newSkeleton, parentBone, mat);
499
- bone.id = id;
500
- }
501
- // Polish
502
- var bones = newSkeleton.bones;
503
- newSkeleton.bones = [];
504
- for (var i = 0; i < skins.jointNames.length; i++) {
505
- var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
506
- if (!jointNode) {
507
- continue;
508
- }
509
- for (var j = 0; j < bones.length; j++) {
510
- if (bones[j].id === jointNode.id) {
511
- newSkeleton.bones.push(bones[j]);
512
- break;
513
- }
514
- }
515
- }
516
- newSkeleton.prepare();
517
- // Finish
518
- for (var i = 0; i < nodesToRootToAdd.length; i++) {
519
- newSkeleton.bones.push(nodesToRootToAdd[i]);
520
- }
521
- return newSkeleton;
522
- };
523
- /**
524
- * Imports a mesh and its geometries
525
- * @param gltfRuntime
526
- * @param node
527
- * @param meshes
528
- * @param id
529
- * @param newMesh
530
- */
531
- var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
532
- if (!newMesh) {
533
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
534
- newMesh = new Mesh(node.name || "", gltfRuntime.scene);
535
- newMesh._parentContainer = gltfRuntime.assetContainer;
536
- gltfRuntime.scene._blockEntityCollection = false;
537
- newMesh.id = id;
538
- }
539
- if (!node.babylonNode) {
540
- return newMesh;
541
- }
542
- var subMaterials = [];
543
- var vertexData = null;
544
- var verticesStarts = new Array();
545
- var verticesCounts = new Array();
546
- var indexStarts = new Array();
547
- var indexCounts = new Array();
548
- for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
549
- var meshId = meshes[meshIndex];
550
- var mesh = gltfRuntime.meshes[meshId];
551
- if (!mesh) {
552
- continue;
553
- }
554
- // Positions, normals and UVs
555
- for (var i = 0; i < mesh.primitives.length; i++) {
556
- // Temporary vertex data
557
- var tempVertexData = new VertexData();
558
- var primitive = mesh.primitives[i];
559
- if (primitive.mode !== 4) {
560
- // continue;
561
- }
562
- var attributes = primitive.attributes;
563
- var accessor = null;
564
- var buffer = null;
565
- // Set positions, normal and uvs
566
- for (var semantic in attributes) {
567
- // Link accessor and buffer view
568
- accessor = gltfRuntime.accessors[attributes[semantic]];
569
- buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
570
- if (semantic === "NORMAL") {
571
- tempVertexData.normals = new Float32Array(buffer.length);
572
- tempVertexData.normals.set(buffer);
573
- }
574
- else if (semantic === "POSITION") {
575
- if (GLTFFileLoader.HomogeneousCoordinates) {
576
- tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
577
- for (var j = 0; j < buffer.length; j += 4) {
578
- tempVertexData.positions[j] = buffer[j];
579
- tempVertexData.positions[j + 1] = buffer[j + 1];
580
- tempVertexData.positions[j + 2] = buffer[j + 2];
581
- }
582
- }
583
- else {
584
- tempVertexData.positions = new Float32Array(buffer.length);
585
- tempVertexData.positions.set(buffer);
586
- }
587
- verticesCounts.push(tempVertexData.positions.length);
588
- }
589
- else if (semantic.indexOf("TEXCOORD_") !== -1) {
590
- var channel = Number(semantic.split("_")[1]);
591
- var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : channel + 1);
592
- var uvs = new Float32Array(buffer.length);
593
- uvs.set(buffer);
594
- normalizeUVs(uvs);
595
- tempVertexData.set(uvs, uvKind);
596
- }
597
- else if (semantic === "JOINT") {
598
- tempVertexData.matricesIndices = new Float32Array(buffer.length);
599
- tempVertexData.matricesIndices.set(buffer);
600
- }
601
- else if (semantic === "WEIGHT") {
602
- tempVertexData.matricesWeights = new Float32Array(buffer.length);
603
- tempVertexData.matricesWeights.set(buffer);
604
- }
605
- else if (semantic === "COLOR") {
606
- tempVertexData.colors = new Float32Array(buffer.length);
607
- tempVertexData.colors.set(buffer);
608
- }
609
- }
610
- // Indices
611
- accessor = gltfRuntime.accessors[primitive.indices];
612
- if (accessor) {
613
- buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
614
- tempVertexData.indices = new Int32Array(buffer.length);
615
- tempVertexData.indices.set(buffer);
616
- indexCounts.push(tempVertexData.indices.length);
617
- }
618
- else {
619
- // Set indices on the fly
620
- var indices = [];
621
- for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
622
- indices.push(j);
623
- }
624
- tempVertexData.indices = new Int32Array(indices);
625
- indexCounts.push(tempVertexData.indices.length);
626
- }
627
- if (!vertexData) {
628
- vertexData = tempVertexData;
629
- }
630
- else {
631
- vertexData.merge(tempVertexData);
632
- }
633
- // Sub material
634
- var material_1 = gltfRuntime.scene.getMaterialById(primitive.material);
635
- subMaterials.push(material_1 === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
636
- // Update vertices start and index start
637
- verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
638
- indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
639
- }
640
- }
641
- var material;
642
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
643
- if (subMaterials.length > 1) {
644
- material = new MultiMaterial("multimat" + id, gltfRuntime.scene);
645
- material.subMaterials = subMaterials;
646
- }
647
- else {
648
- material = new StandardMaterial("multimat" + id, gltfRuntime.scene);
649
- }
650
- if (subMaterials.length === 1) {
651
- material = subMaterials[0];
652
- }
653
- material._parentContainer = gltfRuntime.assetContainer;
654
- if (!newMesh.material) {
655
- newMesh.material = material;
656
- }
657
- // Apply geometry
658
- new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
659
- newMesh.computeWorldMatrix(true);
660
- gltfRuntime.scene._blockEntityCollection = false;
661
- // Apply submeshes
662
- newMesh.subMeshes = [];
663
- var index = 0;
664
- for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
665
- var meshId = meshes[meshIndex];
666
- var mesh = gltfRuntime.meshes[meshId];
667
- if (!mesh) {
668
- continue;
669
- }
670
- for (var i = 0; i < mesh.primitives.length; i++) {
671
- if (mesh.primitives[i].mode !== 4) {
672
- //continue;
673
- }
674
- SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
675
- index++;
676
- }
677
- }
678
- // Finish
679
- return newMesh;
680
- };
681
- /**
682
- * Configure node transformation from position, rotation and scaling
683
- * @param newNode
684
- * @param position
685
- * @param rotation
686
- * @param scaling
687
- */
688
- var configureNode = function (newNode, position, rotation, scaling) {
689
- if (newNode.position) {
690
- newNode.position = position;
691
- }
692
- if (newNode.rotationQuaternion || newNode.rotation) {
693
- newNode.rotationQuaternion = rotation;
694
- }
695
- if (newNode.scaling) {
696
- newNode.scaling = scaling;
697
- }
698
- };
699
- /**
700
- * Configures node from transformation matrix
701
- * @param newNode
702
- * @param node
703
- */
704
- var configureNodeFromMatrix = function (newNode, node) {
705
- if (node.matrix) {
706
- var position = new Vector3(0, 0, 0);
707
- var rotation = new Quaternion();
708
- var scaling = new Vector3(0, 0, 0);
709
- var mat = Matrix.FromArray(node.matrix);
710
- mat.decompose(scaling, rotation, position);
711
- configureNode(newNode, position, rotation, scaling);
712
- }
713
- else if (node.translation && node.rotation && node.scale) {
714
- configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
715
- }
716
- newNode.computeWorldMatrix(true);
717
- };
718
- /**
719
- * Imports a node
720
- * @param gltfRuntime
721
- * @param node
722
- * @param id
723
- */
724
- var importNode = function (gltfRuntime, node, id) {
725
- var lastNode = null;
726
- if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
727
- if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
728
- return null;
729
- }
730
- }
731
- // Meshes
732
- if (node.skin) {
733
- if (node.meshes) {
734
- var skin = gltfRuntime.skins[node.skin];
735
- var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
736
- newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin);
737
- if (newMesh.skeleton === null) {
738
- newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);
739
- if (!skin.babylonSkeleton) {
740
- skin.babylonSkeleton = newMesh.skeleton;
741
- }
742
- }
743
- lastNode = newMesh;
744
- }
745
- }
746
- else if (node.meshes) {
747
- /**
748
- * Improve meshes property
749
- */
750
- var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
751
- lastNode = newMesh;
752
- }
753
- // Lights
754
- else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
755
- var light = gltfRuntime.lights[node.light];
756
- if (light) {
757
- if (light.type === "ambient") {
758
- var ambienLight = light[light.type];
759
- var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
760
- hemiLight.name = node.name || "";
761
- if (ambienLight.color) {
762
- hemiLight.diffuse = Color3.FromArray(ambienLight.color);
763
- }
764
- lastNode = hemiLight;
765
- }
766
- else if (light.type === "directional") {
767
- var directionalLight = light[light.type];
768
- var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
769
- dirLight.name = node.name || "";
770
- if (directionalLight.color) {
771
- dirLight.diffuse = Color3.FromArray(directionalLight.color);
772
- }
773
- lastNode = dirLight;
774
- }
775
- else if (light.type === "point") {
776
- var pointLight = light[light.type];
777
- var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
778
- ptLight.name = node.name || "";
779
- if (pointLight.color) {
780
- ptLight.diffuse = Color3.FromArray(pointLight.color);
781
- }
782
- lastNode = ptLight;
783
- }
784
- else if (light.type === "spot") {
785
- var spotLight = light[light.type];
786
- var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
787
- spLight.name = node.name || "";
788
- if (spotLight.color) {
789
- spLight.diffuse = Color3.FromArray(spotLight.color);
790
- }
791
- if (spotLight.fallOfAngle) {
792
- spLight.angle = spotLight.fallOfAngle;
793
- }
794
- if (spotLight.fallOffExponent) {
795
- spLight.exponent = spotLight.fallOffExponent;
796
- }
797
- lastNode = spLight;
798
- }
799
- }
800
- }
801
- // Cameras
802
- else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
803
- var camera = gltfRuntime.cameras[node.camera];
804
- if (camera) {
805
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
806
- if (camera.type === "orthographic") {
807
- var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
808
- orthoCamera.name = node.name || "";
809
- orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
810
- orthoCamera.attachControl();
811
- lastNode = orthoCamera;
812
- orthoCamera._parentContainer = gltfRuntime.assetContainer;
813
- }
814
- else if (camera.type === "perspective") {
815
- var perspectiveCamera = camera[camera.type];
816
- var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
817
- persCamera.name = node.name || "";
818
- persCamera.attachControl();
819
- if (!perspectiveCamera.aspectRatio) {
820
- perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
821
- }
822
- if (perspectiveCamera.znear && perspectiveCamera.zfar) {
823
- persCamera.maxZ = perspectiveCamera.zfar;
824
- persCamera.minZ = perspectiveCamera.znear;
825
- }
826
- lastNode = persCamera;
827
- persCamera._parentContainer = gltfRuntime.assetContainer;
828
- }
829
- gltfRuntime.scene._blockEntityCollection = false;
830
- }
831
- }
832
- // Empty node
833
- if (!node.jointName) {
834
- if (node.babylonNode) {
835
- return node.babylonNode;
836
- }
837
- else if (lastNode === null) {
838
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
839
- var dummy = new Mesh(node.name || "", gltfRuntime.scene);
840
- dummy._parentContainer = gltfRuntime.assetContainer;
841
- gltfRuntime.scene._blockEntityCollection = false;
842
- node.babylonNode = dummy;
843
- lastNode = dummy;
844
- }
845
- }
846
- if (lastNode !== null) {
847
- if (node.matrix && lastNode instanceof Mesh) {
848
- configureNodeFromMatrix(lastNode, node);
849
- }
850
- else {
851
- var translation = node.translation || [0, 0, 0];
852
- var rotation = node.rotation || [0, 0, 0, 1];
853
- var scale = node.scale || [1, 1, 1];
854
- configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
855
- }
856
- lastNode.updateCache(true);
857
- node.babylonNode = lastNode;
858
- }
859
- return lastNode;
860
- };
861
- /**
862
- * Traverses nodes and creates them
863
- * @param gltfRuntime
864
- * @param id
865
- * @param parent
866
- * @param meshIncluded
867
- */
868
- var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
869
- if (meshIncluded === void 0) { meshIncluded = false; }
870
- var node = gltfRuntime.nodes[id];
871
- var newNode = null;
872
- if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
873
- if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
874
- meshIncluded = true;
875
- }
876
- else {
877
- meshIncluded = false;
878
- }
879
- }
880
- else {
881
- meshIncluded = true;
882
- }
883
- if (!node.jointName && meshIncluded) {
884
- newNode = importNode(gltfRuntime, node, id);
885
- if (newNode !== null) {
886
- newNode.id = id;
887
- newNode.parent = parent;
888
- }
889
- }
890
- if (node.children) {
891
- for (var i = 0; i < node.children.length; i++) {
892
- traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
893
- }
894
- }
895
- };
896
- /**
897
- * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
898
- * @param gltfRuntime
899
- */
900
- var postLoad = function (gltfRuntime) {
901
- // Nodes
902
- var currentScene = gltfRuntime.currentScene;
903
- if (currentScene) {
904
- for (var i = 0; i < currentScene.nodes.length; i++) {
905
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
906
- }
907
- }
908
- else {
909
- for (var thing in gltfRuntime.scenes) {
910
- currentScene = gltfRuntime.scenes[thing];
911
- for (var i = 0; i < currentScene.nodes.length; i++) {
912
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
913
- }
914
- }
915
- }
916
- // Set animations
917
- loadAnimations(gltfRuntime);
918
- for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
919
- var skeleton = gltfRuntime.scene.skeletons[i];
920
- gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
921
- }
922
- };
923
- /**
924
- * onBind shaderrs callback to set uniforms and matrices
925
- * @param mesh
926
- * @param gltfRuntime
927
- * @param unTreatedUniforms
928
- * @param shaderMaterial
929
- * @param technique
930
- * @param material
931
- * @param onSuccess
932
- */
933
- var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
934
- var materialValues = material.values || technique.parameters;
935
- for (var unif in unTreatedUniforms) {
936
- var uniform = unTreatedUniforms[unif];
937
- var type = uniform.type;
938
- if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
939
- if (uniform.semantic && !uniform.source && !uniform.node) {
940
- GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
941
- }
942
- else if (uniform.semantic && (uniform.source || uniform.node)) {
943
- var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
944
- if (source === null) {
945
- source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || "");
946
- }
947
- if (source === null) {
948
- continue;
949
- }
950
- GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
951
- }
952
- }
953
- else {
954
- var value = materialValues[technique.uniforms[unif]];
955
- if (!value) {
956
- continue;
957
- }
958
- if (type === EParameterType.SAMPLER_2D) {
959
- var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
960
- if (texture === null || texture === undefined) {
961
- continue;
962
- }
963
- shaderMaterial.getEffect().setTexture(unif, texture);
964
- }
965
- else {
966
- GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
967
- }
968
- }
969
- }
970
- onSuccess(shaderMaterial);
971
- };
972
- /**
973
- * Prepare uniforms to send the only one time
974
- * Loads the appropriate textures
975
- * @param gltfRuntime
976
- * @param shaderMaterial
977
- * @param technique
978
- * @param material
979
- */
980
- var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
981
- var materialValues = material.values || technique.parameters;
982
- var techniqueUniforms = technique.uniforms;
983
- var _loop_1 = function (unif) {
984
- var uniform = unTreatedUniforms[unif];
985
- var type = uniform.type;
986
- var value = materialValues[techniqueUniforms[unif]];
987
- if (value === undefined) {
988
- // In case the value is the same for all materials
989
- value = uniform.value;
990
- }
991
- if (!value) {
992
- return "continue";
993
- }
994
- var onLoadTexture = function (uniformName) {
995
- return function (texture) {
996
- if (uniform.value && uniformName) {
997
- // Static uniform
998
- shaderMaterial.setTexture(uniformName, texture);
999
- delete unTreatedUniforms[uniformName];
1000
- }
1001
- };
1002
- };
1003
- // Texture (sampler2D)
1004
- if (type === EParameterType.SAMPLER_2D) {
1005
- GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
1006
- }
1007
- // Others
1008
- else {
1009
- if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
1010
- // Static uniform
1011
- delete unTreatedUniforms[unif];
1012
- }
1013
- }
1014
- };
1015
- /**
1016
- * Prepare values here (not matrices)
1017
- */
1018
- for (var unif in unTreatedUniforms) {
1019
- _loop_1(unif);
1020
- }
1021
- };
1022
- /**
1023
- * Shader compilation failed
1024
- * @param program
1025
- * @param shaderMaterial
1026
- * @param onError
1027
- */
1028
- var onShaderCompileError = function (program, shaderMaterial, onError) {
1029
- return function (effect, error) {
1030
- shaderMaterial.dispose(true);
1031
- onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
1032
- };
1033
- };
1034
- /**
1035
- * Shader compilation success
1036
- * @param gltfRuntime
1037
- * @param shaderMaterial
1038
- * @param technique
1039
- * @param material
1040
- * @param unTreatedUniforms
1041
- * @param onSuccess
1042
- */
1043
- var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
1044
- return function (_) {
1045
- prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
1046
- shaderMaterial.onBind = function (mesh) {
1047
- onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
1048
- };
1049
- };
1050
- };
1051
- /**
1052
- * Returns the appropriate uniform if already handled by babylon
1053
- * @param tokenizer
1054
- * @param technique
1055
- */
1056
- var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
1057
- for (var unif in technique.uniforms) {
1058
- var uniform = technique.uniforms[unif];
1059
- var uniformParameter = technique.parameters[uniform];
1060
- if (tokenizer.currentIdentifier === unif) {
1061
- if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
1062
- var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
1063
- if (transformIndex !== -1) {
1064
- delete unTreatedUniforms[unif];
1065
- return babylonTransforms[transformIndex];
1066
- }
1067
- }
1068
- }
1069
- }
1070
- return tokenizer.currentIdentifier;
1071
- };
1072
- /**
1073
- * All shaders loaded. Create materials one by one
1074
- * @param gltfRuntime
1075
- */
1076
- var importMaterials = function (gltfRuntime) {
1077
- // Create materials
1078
- for (var mat in gltfRuntime.materials) {
1079
- GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function () { }, function () { });
1080
- }
1081
- };
1082
- /**
1083
- * Implementation of the base glTF spec
1084
- * @hidden
1085
- */
1086
- var GLTFLoaderBase = /** @class */ (function () {
1087
- function GLTFLoaderBase() {
1088
- }
1089
- GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
1090
- var gltfRuntime = {
1091
- extensions: {},
1092
- accessors: {},
1093
- buffers: {},
1094
- bufferViews: {},
1095
- meshes: {},
1096
- lights: {},
1097
- cameras: {},
1098
- nodes: {},
1099
- images: {},
1100
- textures: {},
1101
- shaders: {},
1102
- programs: {},
1103
- samplers: {},
1104
- techniques: {},
1105
- materials: {},
1106
- animations: {},
1107
- skins: {},
1108
- extensionsUsed: [],
1109
- scenes: {},
1110
- buffersCount: 0,
1111
- shaderscount: 0,
1112
- scene: scene,
1113
- rootUrl: rootUrl,
1114
- loadedBufferCount: 0,
1115
- loadedBufferViews: {},
1116
- loadedShaderCount: 0,
1117
- importOnlyMeshes: false,
1118
- dummyNodes: [],
1119
- assetContainer: null,
1120
- };
1121
- // Parse
1122
- if (parsedData.extensions) {
1123
- parseObject(parsedData.extensions, "extensions", gltfRuntime);
1124
- }
1125
- if (parsedData.extensionsUsed) {
1126
- parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
1127
- }
1128
- if (parsedData.buffers) {
1129
- parseBuffers(parsedData.buffers, gltfRuntime);
1130
- }
1131
- if (parsedData.bufferViews) {
1132
- parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
1133
- }
1134
- if (parsedData.accessors) {
1135
- parseObject(parsedData.accessors, "accessors", gltfRuntime);
1136
- }
1137
- if (parsedData.meshes) {
1138
- parseObject(parsedData.meshes, "meshes", gltfRuntime);
1139
- }
1140
- if (parsedData.lights) {
1141
- parseObject(parsedData.lights, "lights", gltfRuntime);
1142
- }
1143
- if (parsedData.cameras) {
1144
- parseObject(parsedData.cameras, "cameras", gltfRuntime);
1145
- }
1146
- if (parsedData.nodes) {
1147
- parseObject(parsedData.nodes, "nodes", gltfRuntime);
1148
- }
1149
- if (parsedData.images) {
1150
- parseObject(parsedData.images, "images", gltfRuntime);
1151
- }
1152
- if (parsedData.textures) {
1153
- parseObject(parsedData.textures, "textures", gltfRuntime);
1154
- }
1155
- if (parsedData.shaders) {
1156
- parseShaders(parsedData.shaders, gltfRuntime);
1157
- }
1158
- if (parsedData.programs) {
1159
- parseObject(parsedData.programs, "programs", gltfRuntime);
1160
- }
1161
- if (parsedData.samplers) {
1162
- parseObject(parsedData.samplers, "samplers", gltfRuntime);
1163
- }
1164
- if (parsedData.techniques) {
1165
- parseObject(parsedData.techniques, "techniques", gltfRuntime);
1166
- }
1167
- if (parsedData.materials) {
1168
- parseObject(parsedData.materials, "materials", gltfRuntime);
1169
- }
1170
- if (parsedData.animations) {
1171
- parseObject(parsedData.animations, "animations", gltfRuntime);
1172
- }
1173
- if (parsedData.skins) {
1174
- parseObject(parsedData.skins, "skins", gltfRuntime);
1175
- }
1176
- if (parsedData.scenes) {
1177
- gltfRuntime.scenes = parsedData.scenes;
1178
- }
1179
- if (parsedData.scene && parsedData.scenes) {
1180
- gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
1181
- }
1182
- return gltfRuntime;
1183
- };
1184
- GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1185
- var buffer = gltfRuntime.buffers[id];
1186
- if (Tools.IsBase64(buffer.uri)) {
1187
- setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))); });
1188
- }
1189
- else {
1190
- Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
1191
- if (request) {
1192
- onError(request.status + " " + request.statusText);
1193
- }
1194
- });
1195
- }
1196
- };
1197
- GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1198
- var texture = gltfRuntime.textures[id];
1199
- if (!texture || !texture.source) {
1200
- onError("");
1201
- return;
1202
- }
1203
- if (texture.babylonTexture) {
1204
- onSuccess(null);
1205
- return;
1206
- }
1207
- var source = gltfRuntime.images[texture.source];
1208
- if (Tools.IsBase64(source.uri)) {
1209
- setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))); });
1210
- }
1211
- else {
1212
- Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
1213
- if (request) {
1214
- onError(request.status + " " + request.statusText);
1215
- }
1216
- });
1217
- }
1218
- };
1219
- GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess) {
1220
- var texture = gltfRuntime.textures[id];
1221
- if (texture.babylonTexture) {
1222
- onSuccess(texture.babylonTexture);
1223
- return;
1224
- }
1225
- var sampler = gltfRuntime.samplers[texture.sampler];
1226
- var createMipMaps = sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST ||
1227
- sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR ||
1228
- sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST ||
1229
- sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR;
1230
- var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
1231
- var blob = buffer == null ? new Blob() : new Blob([buffer]);
1232
- var blobURL = URL.createObjectURL(blob);
1233
- var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
1234
- var newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
1235
- if (sampler.wrapS !== undefined) {
1236
- newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
1237
- }
1238
- if (sampler.wrapT !== undefined) {
1239
- newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
1240
- }
1241
- newTexture.name = id;
1242
- texture.babylonTexture = newTexture;
1243
- onSuccess(newTexture);
1244
- };
1245
- GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1246
- var shader = gltfRuntime.shaders[id];
1247
- if (Tools.IsBase64(shader.uri)) {
1248
- var shaderString = atob(shader.uri.split(",")[1]);
1249
- if (onSuccess) {
1250
- onSuccess(shaderString);
1251
- }
1252
- }
1253
- else {
1254
- Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
1255
- if (request && onError) {
1256
- onError(request.status + " " + request.statusText);
1257
- }
1258
- });
1259
- }
1260
- };
1261
- GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1262
- var material = gltfRuntime.materials[id];
1263
- if (!material.technique) {
1264
- if (onError) {
1265
- onError("No technique found.");
1266
- }
1267
- return;
1268
- }
1269
- var technique = gltfRuntime.techniques[material.technique];
1270
- if (!technique) {
1271
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
1272
- var defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
1273
- defaultMaterial._parentContainer = gltfRuntime.assetContainer;
1274
- gltfRuntime.scene._blockEntityCollection = false;
1275
- defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
1276
- defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1277
- onSuccess(defaultMaterial);
1278
- return;
1279
- }
1280
- var program = gltfRuntime.programs[technique.program];
1281
- var states = technique.states;
1282
- var vertexShader = Effect.ShadersStore[program.vertexShader + "VertexShader"];
1283
- var pixelShader = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
1284
- var newVertexShader = "";
1285
- var newPixelShader = "";
1286
- var vertexTokenizer = new Tokenizer(vertexShader);
1287
- var pixelTokenizer = new Tokenizer(pixelShader);
1288
- var unTreatedUniforms = {};
1289
- var uniforms = [];
1290
- var attributes = [];
1291
- var samplers = [];
1292
- // Fill uniform, sampler2D and attributes
1293
- for (var unif in technique.uniforms) {
1294
- var uniform = technique.uniforms[unif];
1295
- var uniformParameter = technique.parameters[uniform];
1296
- unTreatedUniforms[unif] = uniformParameter;
1297
- if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
1298
- var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
1299
- if (transformIndex !== -1) {
1300
- uniforms.push(babylonTransforms[transformIndex]);
1301
- delete unTreatedUniforms[unif];
1302
- }
1303
- else {
1304
- uniforms.push(unif);
1305
- }
1306
- }
1307
- else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
1308
- samplers.push(unif);
1309
- }
1310
- else {
1311
- uniforms.push(unif);
1312
- }
1313
- }
1314
- for (var attr in technique.attributes) {
1315
- var attribute = technique.attributes[attr];
1316
- var attributeParameter = technique.parameters[attribute];
1317
- if (attributeParameter.semantic) {
1318
- var name_1 = getAttribute(attributeParameter);
1319
- if (name_1) {
1320
- attributes.push(name_1);
1321
- }
1322
- }
1323
- }
1324
- // Configure vertex shader
1325
- while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
1326
- var tokenType = vertexTokenizer.currentToken;
1327
- if (tokenType !== ETokenType.IDENTIFIER) {
1328
- newVertexShader += vertexTokenizer.currentString;
1329
- continue;
1330
- }
1331
- var foundAttribute = false;
1332
- for (var attr in technique.attributes) {
1333
- var attribute = technique.attributes[attr];
1334
- var attributeParameter = technique.parameters[attribute];
1335
- if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
1336
- newVertexShader += getAttribute(attributeParameter);
1337
- foundAttribute = true;
1338
- break;
1339
- }
1340
- }
1341
- if (foundAttribute) {
1342
- continue;
1343
- }
1344
- newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
1345
- }
1346
- // Configure pixel shader
1347
- while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
1348
- var tokenType = pixelTokenizer.currentToken;
1349
- if (tokenType !== ETokenType.IDENTIFIER) {
1350
- newPixelShader += pixelTokenizer.currentString;
1351
- continue;
1352
- }
1353
- newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
1354
- }
1355
- // Create shader material
1356
- var shaderPath = {
1357
- vertex: program.vertexShader + id,
1358
- fragment: program.fragmentShader + id,
1359
- };
1360
- var options = {
1361
- attributes: attributes,
1362
- uniforms: uniforms,
1363
- samplers: samplers,
1364
- needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1,
1365
- };
1366
- Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
1367
- Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
1368
- var shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
1369
- shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
1370
- shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
1371
- shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1372
- if (states && states.functions) {
1373
- var functions = states.functions;
1374
- if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
1375
- shaderMaterial.backFaceCulling = false;
1376
- }
1377
- var blendFunc = functions.blendFuncSeparate;
1378
- if (blendFunc) {
1379
- if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1380
- blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA &&
1381
- blendFunc[2] === EBlendingFunction.ONE &&
1382
- blendFunc[3] === EBlendingFunction.ONE) {
1383
- shaderMaterial.alphaMode = Constants.ALPHA_COMBINE;
1384
- }
1385
- else if (blendFunc[0] === EBlendingFunction.ONE &&
1386
- blendFunc[1] === EBlendingFunction.ONE &&
1387
- blendFunc[2] === EBlendingFunction.ZERO &&
1388
- blendFunc[3] === EBlendingFunction.ONE) {
1389
- shaderMaterial.alphaMode = Constants.ALPHA_ONEONE;
1390
- }
1391
- else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1392
- blendFunc[1] === EBlendingFunction.ONE &&
1393
- blendFunc[2] === EBlendingFunction.ZERO &&
1394
- blendFunc[3] === EBlendingFunction.ONE) {
1395
- shaderMaterial.alphaMode = Constants.ALPHA_ADD;
1396
- }
1397
- else if (blendFunc[0] === EBlendingFunction.ZERO &&
1398
- blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
1399
- blendFunc[2] === EBlendingFunction.ONE &&
1400
- blendFunc[3] === EBlendingFunction.ONE) {
1401
- shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT;
1402
- }
1403
- else if (blendFunc[0] === EBlendingFunction.DST_COLOR &&
1404
- blendFunc[1] === EBlendingFunction.ZERO &&
1405
- blendFunc[2] === EBlendingFunction.ONE &&
1406
- blendFunc[3] === EBlendingFunction.ONE) {
1407
- shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY;
1408
- }
1409
- else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1410
- blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
1411
- blendFunc[2] === EBlendingFunction.ONE &&
1412
- blendFunc[3] === EBlendingFunction.ONE) {
1413
- shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED;
1414
- }
1415
- }
1416
- }
1417
- };
1418
- return GLTFLoaderBase;
1419
- }());
1420
- export { GLTFLoaderBase };
1421
- /**
1422
- * glTF V1 Loader
1423
- * @hidden
1424
- */
1425
- var GLTFLoader = /** @class */ (function () {
1426
- function GLTFLoader() {
1427
- }
1428
- GLTFLoader.RegisterExtension = function (extension) {
1429
- if (GLTFLoader.Extensions[extension.name]) {
1430
- Tools.Error('Tool with the same name "' + extension.name + '" already exists');
1431
- return;
1432
- }
1433
- GLTFLoader.Extensions[extension.name] = extension;
1434
- };
1435
- GLTFLoader.prototype.dispose = function () {
1436
- // do nothing
1437
- };
1438
- GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) {
1439
- var _this = this;
1440
- scene.useRightHandedSystem = true;
1441
- GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1442
- gltfRuntime.assetContainer = assetContainer;
1443
- gltfRuntime.importOnlyMeshes = true;
1444
- if (meshesNames === "") {
1445
- gltfRuntime.importMeshesNames = [];
1446
- }
1447
- else if (typeof meshesNames === "string") {
1448
- gltfRuntime.importMeshesNames = [meshesNames];
1449
- }
1450
- else if (meshesNames && !(meshesNames instanceof Array)) {
1451
- gltfRuntime.importMeshesNames = [meshesNames];
1452
- }
1453
- else {
1454
- gltfRuntime.importMeshesNames = [];
1455
- Tools.Warn("Argument meshesNames must be of type string or string[]");
1456
- }
1457
- // Create nodes
1458
- _this._createNodes(gltfRuntime);
1459
- var meshes = new Array();
1460
- var skeletons = new Array();
1461
- // Fill arrays of meshes and skeletons
1462
- for (var nde in gltfRuntime.nodes) {
1463
- var node = gltfRuntime.nodes[nde];
1464
- if (node.babylonNode instanceof AbstractMesh) {
1465
- meshes.push(node.babylonNode);
1466
- }
1467
- }
1468
- for (var skl in gltfRuntime.skins) {
1469
- var skin = gltfRuntime.skins[skl];
1470
- if (skin.babylonSkeleton instanceof Skeleton) {
1471
- skeletons.push(skin.babylonSkeleton);
1472
- }
1473
- }
1474
- // Load buffers, shaders, materials, etc.
1475
- _this._loadBuffersAsync(gltfRuntime, function () {
1476
- _this._loadShadersAsync(gltfRuntime, function () {
1477
- importMaterials(gltfRuntime);
1478
- postLoad(gltfRuntime);
1479
- if (!GLTFFileLoader.IncrementalLoading && onSuccess) {
1480
- onSuccess(meshes, skeletons);
1481
- }
1482
- });
1483
- });
1484
- if (GLTFFileLoader.IncrementalLoading && onSuccess) {
1485
- onSuccess(meshes, skeletons);
1486
- }
1487
- }, onError);
1488
- return true;
1489
- };
1490
- /**
1491
- * Imports one or more meshes from a loaded gltf file and adds them to the scene
1492
- * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
1493
- * @param scene the scene the meshes should be added to
1494
- * @param assetContainer defines the asset container to use (can be null)
1495
- * @param data gltf data containing information of the meshes in a loaded file
1496
- * @param rootUrl root url to load from
1497
- * @param onProgress event that fires when loading progress has occured
1498
- * @returns a promise containg the loaded meshes, particles, skeletons and animations
1499
- */
1500
- GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, assetContainer, data, rootUrl, onProgress) {
1501
- var _this = this;
1502
- return new Promise(function (resolve, reject) {
1503
- _this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, function (meshes, skeletons) {
1504
- resolve({
1505
- meshes: meshes,
1506
- particleSystems: [],
1507
- skeletons: skeletons,
1508
- animationGroups: [],
1509
- lights: [],
1510
- transformNodes: [],
1511
- geometries: [],
1512
- });
1513
- }, onProgress, function (message) {
1514
- reject(new Error(message));
1515
- });
1516
- });
1517
- };
1518
- GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
1519
- var _this = this;
1520
- scene.useRightHandedSystem = true;
1521
- GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1522
- // Load runtime extensios
1523
- GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
1524
- // Create nodes
1525
- _this._createNodes(gltfRuntime);
1526
- // Load buffers, shaders, materials, etc.
1527
- _this._loadBuffersAsync(gltfRuntime, function () {
1528
- _this._loadShadersAsync(gltfRuntime, function () {
1529
- importMaterials(gltfRuntime);
1530
- postLoad(gltfRuntime);
1531
- if (!GLTFFileLoader.IncrementalLoading) {
1532
- onSuccess();
1533
- }
1534
- });
1535
- });
1536
- if (GLTFFileLoader.IncrementalLoading) {
1537
- onSuccess();
1538
- }
1539
- }, onError);
1540
- }, onError);
1541
- };
1542
- /**
1543
- * Imports all objects from a loaded gltf file and adds them to the scene
1544
- * @param scene the scene the objects should be added to
1545
- * @param data gltf data containing information of the meshes in a loaded file
1546
- * @param rootUrl root url to load from
1547
- * @param onProgress event that fires when loading progress has occured
1548
- * @returns a promise which completes when objects have been loaded to the scene
1549
- */
1550
- GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
1551
- var _this = this;
1552
- return new Promise(function (resolve, reject) {
1553
- _this._loadAsync(scene, data, rootUrl, function () {
1554
- resolve();
1555
- }, onProgress, function (message) {
1556
- reject(new Error(message));
1557
- });
1558
- });
1559
- };
1560
- GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
1561
- var hasShaders = false;
1562
- var processShader = function (sha, shader) {
1563
- GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
1564
- if (shaderString instanceof ArrayBuffer) {
1565
- return;
1566
- }
1567
- gltfRuntime.loadedShaderCount++;
1568
- if (shaderString) {
1569
- Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
1570
- }
1571
- if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
1572
- onload();
1573
- }
1574
- }, function () {
1575
- Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
1576
- });
1577
- };
1578
- for (var sha in gltfRuntime.shaders) {
1579
- hasShaders = true;
1580
- var shader = gltfRuntime.shaders[sha];
1581
- if (shader) {
1582
- processShader.bind(this, sha, shader)();
1583
- }
1584
- else {
1585
- Tools.Error("No shader named: " + sha);
1586
- }
1587
- }
1588
- if (!hasShaders) {
1589
- onload();
1590
- }
1591
- };
1592
- GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad) {
1593
- var hasBuffers = false;
1594
- var processBuffer = function (buf, buffer) {
1595
- GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
1596
- gltfRuntime.loadedBufferCount++;
1597
- if (bufferView) {
1598
- if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
1599
- Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
1600
- }
1601
- gltfRuntime.loadedBufferViews[buf] = bufferView;
1602
- }
1603
- if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
1604
- onLoad();
1605
- }
1606
- }, function () {
1607
- Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
1608
- });
1609
- };
1610
- for (var buf in gltfRuntime.buffers) {
1611
- hasBuffers = true;
1612
- var buffer = gltfRuntime.buffers[buf];
1613
- if (buffer) {
1614
- processBuffer.bind(this, buf, buffer)();
1615
- }
1616
- else {
1617
- Tools.Error("No buffer named: " + buf);
1618
- }
1619
- }
1620
- if (!hasBuffers) {
1621
- onLoad();
1622
- }
1623
- };
1624
- GLTFLoader.prototype._createNodes = function (gltfRuntime) {
1625
- var currentScene = gltfRuntime.currentScene;
1626
- if (currentScene) {
1627
- // Only one scene even if multiple scenes are defined
1628
- for (var i = 0; i < currentScene.nodes.length; i++) {
1629
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1630
- }
1631
- }
1632
- else {
1633
- // Load all scenes
1634
- for (var thing in gltfRuntime.scenes) {
1635
- currentScene = gltfRuntime.scenes[thing];
1636
- for (var i = 0; i < currentScene.nodes.length; i++) {
1637
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1638
- }
1639
- }
1640
- }
1641
- };
1642
- GLTFLoader.Extensions = {};
1643
- return GLTFLoader;
1644
- }());
1645
- export { GLTFLoader };
1646
- /** @hidden */
1647
- var GLTFLoaderExtension = /** @class */ (function () {
1648
- function GLTFLoaderExtension(name) {
1649
- this._name = name;
1650
- }
1651
- Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
1652
- get: function () {
1653
- return this._name;
1654
- },
1655
- enumerable: false,
1656
- configurable: true
1657
- });
1658
- /**
1659
- * Defines an override for loading the runtime
1660
- * Return true to stop further extensions from loading the runtime
1661
- * @param scene
1662
- * @param data
1663
- * @param rootUrl
1664
- * @param onSuccess
1665
- * @param onError
1666
- */
1667
- GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1668
- return false;
1669
- };
1670
- /**
1671
- * Defines an onverride for creating gltf runtime
1672
- * Return true to stop further extensions from creating the runtime
1673
- * @param gltfRuntime
1674
- * @param onSuccess
1675
- * @param onError
1676
- */
1677
- GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1678
- return false;
1679
- };
1680
- /**
1681
- * Defines an override for loading buffers
1682
- * Return true to stop further extensions from loading this buffer
1683
- * @param gltfRuntime
1684
- * @param id
1685
- * @param onSuccess
1686
- * @param onError
1687
- * @param onProgress
1688
- */
1689
- GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1690
- return false;
1691
- };
1692
- /**
1693
- * Defines an override for loading texture buffers
1694
- * Return true to stop further extensions from loading this texture data
1695
- * @param gltfRuntime
1696
- * @param id
1697
- * @param onSuccess
1698
- * @param onError
1699
- */
1700
- GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1701
- return false;
1702
- };
1703
- /**
1704
- * Defines an override for creating textures
1705
- * Return true to stop further extensions from loading this texture
1706
- * @param gltfRuntime
1707
- * @param id
1708
- * @param buffer
1709
- * @param onSuccess
1710
- * @param onError
1711
- */
1712
- GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1713
- return false;
1714
- };
1715
- /**
1716
- * Defines an override for loading shader strings
1717
- * Return true to stop further extensions from loading this shader data
1718
- * @param gltfRuntime
1719
- * @param id
1720
- * @param onSuccess
1721
- * @param onError
1722
- */
1723
- GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1724
- return false;
1725
- };
1726
- /**
1727
- * Defines an override for loading materials
1728
- * Return true to stop further extensions from loading this material
1729
- * @param gltfRuntime
1730
- * @param id
1731
- * @param onSuccess
1732
- * @param onError
1733
- */
1734
- GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1735
- return false;
1736
- };
1737
- // ---------
1738
- // Utilities
1739
- // ---------
1740
- GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1741
- GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1742
- return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
1743
- }, function () {
1744
- setTimeout(function () {
1745
- if (!onSuccess) {
1746
- return;
1747
- }
1748
- onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
1749
- });
1750
- });
1751
- };
1752
- GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1753
- GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1754
- return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
1755
- }, function () {
1756
- setTimeout(function () {
1757
- onSuccess();
1758
- });
1759
- });
1760
- };
1761
- GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1762
- GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1763
- return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1764
- }, function () {
1765
- GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1766
- });
1767
- };
1768
- GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
1769
- GLTFLoaderExtension._LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
1770
- if (buffer) {
1771
- GLTFLoaderExtension._CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1772
- }
1773
- }, onError);
1774
- };
1775
- GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1776
- GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1777
- return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1778
- }, function () {
1779
- GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1780
- });
1781
- };
1782
- GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1783
- GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1784
- return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1785
- }, function () {
1786
- GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1787
- });
1788
- };
1789
- GLTFLoaderExtension._LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1790
- GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1791
- return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1792
- }, function () {
1793
- GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1794
- });
1795
- };
1796
- GLTFLoaderExtension._CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1797
- GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1798
- return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1799
- }, function () {
1800
- GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess);
1801
- });
1802
- };
1803
- GLTFLoaderExtension._ApplyExtensions = function (func, defaultFunc) {
1804
- for (var extensionName in GLTFLoader.Extensions) {
1805
- var loaderExtension = GLTFLoader.Extensions[extensionName];
1806
- if (func(loaderExtension)) {
1807
- return;
1808
- }
1809
- }
1810
- defaultFunc();
1811
- };
1812
- return GLTFLoaderExtension;
1813
- }());
1814
- export { GLTFLoaderExtension };
1815
- GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ import { EParameterType, ETextureFilterType, ECullingType, EBlendingFunction, EShaderType, } from "./glTFLoaderInterfaces";
3
+ import { Quaternion, Vector3, Matrix } from "@babylonjs/core/Maths/math.vector.js";
4
+ import { Color3 } from "@babylonjs/core/Maths/math.color.js";
5
+ import { Tools } from "@babylonjs/core/Misc/tools.js";
6
+ import { Camera } from "@babylonjs/core/Cameras/camera.js";
7
+ import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera.js";
8
+ import { Animation } from "@babylonjs/core/Animations/animation.js";
9
+ import { Bone } from "@babylonjs/core/Bones/bone.js";
10
+ import { Skeleton } from "@babylonjs/core/Bones/skeleton.js";
11
+ import { Effect } from "@babylonjs/core/Materials/effect.js";
12
+ import { Material } from "@babylonjs/core/Materials/material.js";
13
+ import { MultiMaterial } from "@babylonjs/core/Materials/multiMaterial.js";
14
+ import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js";
15
+ import { ShaderMaterial } from "@babylonjs/core/Materials/shaderMaterial.js";
16
+ import { Texture } from "@babylonjs/core/Materials/Textures/texture.js";
17
+ import { VertexData } from "@babylonjs/core/Meshes/mesh.vertexData.js";
18
+ import { VertexBuffer } from "@babylonjs/core/Buffers/buffer.js";
19
+ import { Geometry } from "@babylonjs/core/Meshes/geometry.js";
20
+ import { SubMesh } from "@babylonjs/core/Meshes/subMesh.js";
21
+ import { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js";
22
+ import { Mesh } from "@babylonjs/core/Meshes/mesh.js";
23
+ import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js";
24
+ import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight.js";
25
+ import { PointLight } from "@babylonjs/core/Lights/pointLight.js";
26
+ import { SpotLight } from "@babylonjs/core/Lights/spotLight.js";
27
+ import { GLTFUtils } from "./glTFLoaderUtils";
28
+ import { GLTFFileLoader } from "../glTFFileLoader";
29
+ import { Constants } from "@babylonjs/core/Engines/constants.js";
30
+ /**
31
+ * Tokenizer. Used for shaders compatibility
32
+ * Automatically map world, view, projection, worldViewProjection, attributes and so on
33
+ */
34
+ var ETokenType;
35
+ (function (ETokenType) {
36
+ ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
37
+ ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
38
+ ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
39
+ })(ETokenType || (ETokenType = {}));
40
+ var Tokenizer = /** @class */ (function () {
41
+ function Tokenizer(toParse) {
42
+ this._pos = 0;
43
+ this.currentToken = ETokenType.UNKNOWN;
44
+ this.currentIdentifier = "";
45
+ this.currentString = "";
46
+ this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
47
+ this._toParse = toParse;
48
+ this._maxPos = toParse.length;
49
+ }
50
+ Tokenizer.prototype.getNextToken = function () {
51
+ if (this.isEnd()) {
52
+ return ETokenType.END_OF_INPUT;
53
+ }
54
+ this.currentString = this.read();
55
+ this.currentToken = ETokenType.UNKNOWN;
56
+ if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
57
+ this.currentToken = ETokenType.IDENTIFIER;
58
+ this.currentIdentifier = this.currentString;
59
+ while (!this.isEnd() && (this.isLetterOrDigitPattern.test((this.currentString = this.peek())) || this.currentString === "_")) {
60
+ this.currentIdentifier += this.currentString;
61
+ this.forward();
62
+ }
63
+ }
64
+ return this.currentToken;
65
+ };
66
+ Tokenizer.prototype.peek = function () {
67
+ return this._toParse[this._pos];
68
+ };
69
+ Tokenizer.prototype.read = function () {
70
+ return this._toParse[this._pos++];
71
+ };
72
+ Tokenizer.prototype.forward = function () {
73
+ this._pos++;
74
+ };
75
+ Tokenizer.prototype.isEnd = function () {
76
+ return this._pos >= this._maxPos;
77
+ };
78
+ return Tokenizer;
79
+ }());
80
+ /**
81
+ * Values
82
+ */
83
+ var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
84
+ var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
85
+ var glTFAnimationPaths = ["translation", "rotation", "scale"];
86
+ var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
87
+ /**
88
+ * Parse
89
+ * @param parsedBuffers
90
+ * @param gltfRuntime
91
+ */
92
+ var parseBuffers = function (parsedBuffers, gltfRuntime) {
93
+ for (var buf in parsedBuffers) {
94
+ var parsedBuffer = parsedBuffers[buf];
95
+ gltfRuntime.buffers[buf] = parsedBuffer;
96
+ gltfRuntime.buffersCount++;
97
+ }
98
+ };
99
+ var parseShaders = function (parsedShaders, gltfRuntime) {
100
+ for (var sha in parsedShaders) {
101
+ var parsedShader = parsedShaders[sha];
102
+ gltfRuntime.shaders[sha] = parsedShader;
103
+ gltfRuntime.shaderscount++;
104
+ }
105
+ };
106
+ var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
107
+ for (var object in parsedObjects) {
108
+ var parsedObject = parsedObjects[object];
109
+ gltfRuntime[runtimeProperty][object] = parsedObject;
110
+ }
111
+ };
112
+ /**
113
+ * Utils
114
+ * @param buffer
115
+ */
116
+ var normalizeUVs = function (buffer) {
117
+ if (!buffer) {
118
+ return;
119
+ }
120
+ for (var i = 0; i < buffer.length / 2; i++) {
121
+ buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
122
+ }
123
+ };
124
+ var getAttribute = function (attributeParameter) {
125
+ if (attributeParameter.semantic === "NORMAL") {
126
+ return "normal";
127
+ }
128
+ else if (attributeParameter.semantic === "POSITION") {
129
+ return "position";
130
+ }
131
+ else if (attributeParameter.semantic === "JOINT") {
132
+ return "matricesIndices";
133
+ }
134
+ else if (attributeParameter.semantic === "WEIGHT") {
135
+ return "matricesWeights";
136
+ }
137
+ else if (attributeParameter.semantic === "COLOR") {
138
+ return "color";
139
+ }
140
+ else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
141
+ var channel = Number(attributeParameter.semantic.split("_")[1]);
142
+ return "uv" + (channel === 0 ? "" : channel + 1);
143
+ }
144
+ return null;
145
+ };
146
+ /**
147
+ * Loads and creates animations
148
+ * @param gltfRuntime
149
+ */
150
+ var loadAnimations = function (gltfRuntime) {
151
+ for (var anim in gltfRuntime.animations) {
152
+ var animation = gltfRuntime.animations[anim];
153
+ if (!animation.channels || !animation.samplers) {
154
+ continue;
155
+ }
156
+ var lastAnimation = null;
157
+ for (var i = 0; i < animation.channels.length; i++) {
158
+ // Get parameters and load buffers
159
+ var channel = animation.channels[i];
160
+ var sampler = animation.samplers[channel.sampler];
161
+ if (!sampler) {
162
+ continue;
163
+ }
164
+ var inputData = null;
165
+ var outputData = null;
166
+ if (animation.parameters) {
167
+ inputData = animation.parameters[sampler.input];
168
+ outputData = animation.parameters[sampler.output];
169
+ }
170
+ else {
171
+ inputData = sampler.input;
172
+ outputData = sampler.output;
173
+ }
174
+ var bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
175
+ var bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
176
+ var targetId = channel.target.id;
177
+ var targetNode = gltfRuntime.scene.getNodeById(targetId);
178
+ if (targetNode === null) {
179
+ targetNode = gltfRuntime.scene.getNodeByName(targetId);
180
+ }
181
+ if (targetNode === null) {
182
+ Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetId + " to attach to");
183
+ continue;
184
+ }
185
+ var isBone = targetNode instanceof Bone;
186
+ // Get target path (position, rotation or scaling)
187
+ var targetPath = channel.target.path;
188
+ var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
189
+ if (targetPathIndex !== -1) {
190
+ targetPath = babylonAnimationPaths[targetPathIndex];
191
+ }
192
+ // Determine animation type
193
+ var animationType = Animation.ANIMATIONTYPE_MATRIX;
194
+ if (!isBone) {
195
+ if (targetPath === "rotationQuaternion") {
196
+ animationType = Animation.ANIMATIONTYPE_QUATERNION;
197
+ targetNode.rotationQuaternion = new Quaternion();
198
+ }
199
+ else {
200
+ animationType = Animation.ANIMATIONTYPE_VECTOR3;
201
+ }
202
+ }
203
+ // Create animation and key frames
204
+ var babylonAnimation = null;
205
+ var keys = [];
206
+ var arrayOffset = 0;
207
+ var modifyKey = false;
208
+ if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
209
+ babylonAnimation = lastAnimation;
210
+ modifyKey = true;
211
+ }
212
+ if (!modifyKey) {
213
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
214
+ babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
215
+ gltfRuntime.scene._blockEntityCollection = false;
216
+ }
217
+ // For each frame
218
+ for (var j = 0; j < bufferInput.length; j++) {
219
+ var value = null;
220
+ if (targetPath === "rotationQuaternion") {
221
+ // VEC4
222
+ value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
223
+ arrayOffset += 4;
224
+ }
225
+ else {
226
+ // Position and scaling are VEC3
227
+ value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
228
+ arrayOffset += 3;
229
+ }
230
+ if (isBone) {
231
+ var bone = targetNode;
232
+ var translation = Vector3.Zero();
233
+ var rotationQuaternion = new Quaternion();
234
+ var scaling = Vector3.Zero();
235
+ // Warning on decompose
236
+ var mat = bone.getBaseMatrix();
237
+ if (modifyKey && lastAnimation) {
238
+ mat = lastAnimation.getKeys()[j].value;
239
+ }
240
+ mat.decompose(scaling, rotationQuaternion, translation);
241
+ if (targetPath === "position") {
242
+ translation = value;
243
+ }
244
+ else if (targetPath === "rotationQuaternion") {
245
+ rotationQuaternion = value;
246
+ }
247
+ else {
248
+ scaling = value;
249
+ }
250
+ value = Matrix.Compose(scaling, rotationQuaternion, translation);
251
+ }
252
+ if (!modifyKey) {
253
+ keys.push({
254
+ frame: bufferInput[j],
255
+ value: value,
256
+ });
257
+ }
258
+ else if (lastAnimation) {
259
+ lastAnimation.getKeys()[j].value = value;
260
+ }
261
+ }
262
+ // Finish
263
+ if (!modifyKey && babylonAnimation) {
264
+ babylonAnimation.setKeys(keys);
265
+ targetNode.animations.push(babylonAnimation);
266
+ }
267
+ lastAnimation = babylonAnimation;
268
+ gltfRuntime.scene.stopAnimation(targetNode);
269
+ gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
270
+ }
271
+ }
272
+ };
273
+ /**
274
+ * Returns the bones transformation matrix
275
+ * @param node
276
+ */
277
+ var configureBoneTransformation = function (node) {
278
+ var mat = null;
279
+ if (node.translation || node.rotation || node.scale) {
280
+ var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
281
+ var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
282
+ var position = Vector3.FromArray(node.translation || [0, 0, 0]);
283
+ mat = Matrix.Compose(scale, rotation, position);
284
+ }
285
+ else {
286
+ mat = Matrix.FromArray(node.matrix);
287
+ }
288
+ return mat;
289
+ };
290
+ /**
291
+ * Returns the parent bone
292
+ * @param gltfRuntime
293
+ * @param skins
294
+ * @param jointName
295
+ * @param newSkeleton
296
+ */
297
+ var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
298
+ // Try to find
299
+ for (var i = 0; i < newSkeleton.bones.length; i++) {
300
+ if (newSkeleton.bones[i].name === jointName) {
301
+ return newSkeleton.bones[i];
302
+ }
303
+ }
304
+ // Not found, search in gltf nodes
305
+ var nodes = gltfRuntime.nodes;
306
+ for (var nde in nodes) {
307
+ var node = nodes[nde];
308
+ if (!node.jointName) {
309
+ continue;
310
+ }
311
+ var children = node.children;
312
+ for (var i = 0; i < children.length; i++) {
313
+ var child = gltfRuntime.nodes[children[i]];
314
+ if (!child.jointName) {
315
+ continue;
316
+ }
317
+ if (child.jointName === jointName) {
318
+ var mat = configureBoneTransformation(node);
319
+ var bone = new Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
320
+ bone.id = nde;
321
+ return bone;
322
+ }
323
+ }
324
+ }
325
+ return null;
326
+ };
327
+ /**
328
+ * Returns the appropriate root node
329
+ * @param nodesToRoot
330
+ * @param id
331
+ */
332
+ var getNodeToRoot = function (nodesToRoot, id) {
333
+ for (var i = 0; i < nodesToRoot.length; i++) {
334
+ var nodeToRoot = nodesToRoot[i];
335
+ for (var j = 0; j < nodeToRoot.node.children.length; j++) {
336
+ var child = nodeToRoot.node.children[j];
337
+ if (child === id) {
338
+ return nodeToRoot.bone;
339
+ }
340
+ }
341
+ }
342
+ return null;
343
+ };
344
+ /**
345
+ * Returns the node with the joint name
346
+ * @param gltfRuntime
347
+ * @param jointName
348
+ */
349
+ var getJointNode = function (gltfRuntime, jointName) {
350
+ var nodes = gltfRuntime.nodes;
351
+ var node = nodes[jointName];
352
+ if (node) {
353
+ return {
354
+ node: node,
355
+ id: jointName,
356
+ };
357
+ }
358
+ for (var nde in nodes) {
359
+ node = nodes[nde];
360
+ if (node.jointName === jointName) {
361
+ return {
362
+ node: node,
363
+ id: nde,
364
+ };
365
+ }
366
+ }
367
+ return null;
368
+ };
369
+ /**
370
+ * Checks if a nodes is in joints
371
+ * @param skins
372
+ * @param id
373
+ */
374
+ var nodeIsInJoints = function (skins, id) {
375
+ for (var i = 0; i < skins.jointNames.length; i++) {
376
+ if (skins.jointNames[i] === id) {
377
+ return true;
378
+ }
379
+ }
380
+ return false;
381
+ };
382
+ /**
383
+ * Fills the nodes to root for bones and builds hierarchy
384
+ * @param gltfRuntime
385
+ * @param newSkeleton
386
+ * @param skins
387
+ * @param nodesToRoot
388
+ */
389
+ var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
390
+ // Creates nodes for root
391
+ for (var nde in gltfRuntime.nodes) {
392
+ var node = gltfRuntime.nodes[nde];
393
+ var id = nde;
394
+ if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
395
+ continue;
396
+ }
397
+ // Create node to root bone
398
+ var mat = configureBoneTransformation(node);
399
+ var bone = new Bone(node.name || "", newSkeleton, null, mat);
400
+ bone.id = id;
401
+ nodesToRoot.push({ bone: bone, node: node, id: id });
402
+ }
403
+ // Parenting
404
+ for (var i = 0; i < nodesToRoot.length; i++) {
405
+ var nodeToRoot = nodesToRoot[i];
406
+ var children = nodeToRoot.node.children;
407
+ for (var j = 0; j < children.length; j++) {
408
+ var child = null;
409
+ for (var k = 0; k < nodesToRoot.length; k++) {
410
+ if (nodesToRoot[k].id === children[j]) {
411
+ child = nodesToRoot[k];
412
+ break;
413
+ }
414
+ }
415
+ if (child) {
416
+ child.bone._parent = nodeToRoot.bone;
417
+ nodeToRoot.bone.children.push(child.bone);
418
+ }
419
+ }
420
+ }
421
+ };
422
+ /**
423
+ * Imports a skeleton
424
+ * @param gltfRuntime
425
+ * @param skins
426
+ * @param mesh
427
+ * @param newSkeleton
428
+ */
429
+ var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton) {
430
+ if (!newSkeleton) {
431
+ newSkeleton = new Skeleton(skins.name || "", "", gltfRuntime.scene);
432
+ }
433
+ if (!skins.babylonSkeleton) {
434
+ return newSkeleton;
435
+ }
436
+ // Find the root bones
437
+ var nodesToRoot = [];
438
+ var nodesToRootToAdd = [];
439
+ getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
440
+ newSkeleton.bones = [];
441
+ // Joints
442
+ for (var i = 0; i < skins.jointNames.length; i++) {
443
+ var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
444
+ if (!jointNode) {
445
+ continue;
446
+ }
447
+ var node = jointNode.node;
448
+ if (!node) {
449
+ Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
450
+ continue;
451
+ }
452
+ var id = jointNode.id;
453
+ // Optimize, if the bone already exists...
454
+ var existingBone = gltfRuntime.scene.getBoneById(id);
455
+ if (existingBone) {
456
+ newSkeleton.bones.push(existingBone);
457
+ continue;
458
+ }
459
+ // Search for parent bone
460
+ var foundBone = false;
461
+ var parentBone = null;
462
+ for (var j = 0; j < i; j++) {
463
+ var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
464
+ if (!jointNode_1) {
465
+ continue;
466
+ }
467
+ var joint = jointNode_1.node;
468
+ if (!joint) {
469
+ Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
470
+ continue;
471
+ }
472
+ var children = joint.children;
473
+ if (!children) {
474
+ continue;
475
+ }
476
+ foundBone = false;
477
+ for (var k = 0; k < children.length; k++) {
478
+ if (children[k] === id) {
479
+ parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
480
+ foundBone = true;
481
+ break;
482
+ }
483
+ }
484
+ if (foundBone) {
485
+ break;
486
+ }
487
+ }
488
+ // Create bone
489
+ var mat = configureBoneTransformation(node);
490
+ if (!parentBone && nodesToRoot.length > 0) {
491
+ parentBone = getNodeToRoot(nodesToRoot, id);
492
+ if (parentBone) {
493
+ if (nodesToRootToAdd.indexOf(parentBone) === -1) {
494
+ nodesToRootToAdd.push(parentBone);
495
+ }
496
+ }
497
+ }
498
+ var bone = new Bone(node.jointName || "", newSkeleton, parentBone, mat);
499
+ bone.id = id;
500
+ }
501
+ // Polish
502
+ var bones = newSkeleton.bones;
503
+ newSkeleton.bones = [];
504
+ for (var i = 0; i < skins.jointNames.length; i++) {
505
+ var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
506
+ if (!jointNode) {
507
+ continue;
508
+ }
509
+ for (var j = 0; j < bones.length; j++) {
510
+ if (bones[j].id === jointNode.id) {
511
+ newSkeleton.bones.push(bones[j]);
512
+ break;
513
+ }
514
+ }
515
+ }
516
+ newSkeleton.prepare();
517
+ // Finish
518
+ for (var i = 0; i < nodesToRootToAdd.length; i++) {
519
+ newSkeleton.bones.push(nodesToRootToAdd[i]);
520
+ }
521
+ return newSkeleton;
522
+ };
523
+ /**
524
+ * Imports a mesh and its geometries
525
+ * @param gltfRuntime
526
+ * @param node
527
+ * @param meshes
528
+ * @param id
529
+ * @param newMesh
530
+ */
531
+ var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
532
+ if (!newMesh) {
533
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
534
+ newMesh = new Mesh(node.name || "", gltfRuntime.scene);
535
+ newMesh._parentContainer = gltfRuntime.assetContainer;
536
+ gltfRuntime.scene._blockEntityCollection = false;
537
+ newMesh.id = id;
538
+ }
539
+ if (!node.babylonNode) {
540
+ return newMesh;
541
+ }
542
+ var subMaterials = [];
543
+ var vertexData = null;
544
+ var verticesStarts = new Array();
545
+ var verticesCounts = new Array();
546
+ var indexStarts = new Array();
547
+ var indexCounts = new Array();
548
+ for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
549
+ var meshId = meshes[meshIndex];
550
+ var mesh = gltfRuntime.meshes[meshId];
551
+ if (!mesh) {
552
+ continue;
553
+ }
554
+ // Positions, normals and UVs
555
+ for (var i = 0; i < mesh.primitives.length; i++) {
556
+ // Temporary vertex data
557
+ var tempVertexData = new VertexData();
558
+ var primitive = mesh.primitives[i];
559
+ if (primitive.mode !== 4) {
560
+ // continue;
561
+ }
562
+ var attributes = primitive.attributes;
563
+ var accessor = null;
564
+ var buffer = null;
565
+ // Set positions, normal and uvs
566
+ for (var semantic in attributes) {
567
+ // Link accessor and buffer view
568
+ accessor = gltfRuntime.accessors[attributes[semantic]];
569
+ buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
570
+ if (semantic === "NORMAL") {
571
+ tempVertexData.normals = new Float32Array(buffer.length);
572
+ tempVertexData.normals.set(buffer);
573
+ }
574
+ else if (semantic === "POSITION") {
575
+ if (GLTFFileLoader.HomogeneousCoordinates) {
576
+ tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
577
+ for (var j = 0; j < buffer.length; j += 4) {
578
+ tempVertexData.positions[j] = buffer[j];
579
+ tempVertexData.positions[j + 1] = buffer[j + 1];
580
+ tempVertexData.positions[j + 2] = buffer[j + 2];
581
+ }
582
+ }
583
+ else {
584
+ tempVertexData.positions = new Float32Array(buffer.length);
585
+ tempVertexData.positions.set(buffer);
586
+ }
587
+ verticesCounts.push(tempVertexData.positions.length);
588
+ }
589
+ else if (semantic.indexOf("TEXCOORD_") !== -1) {
590
+ var channel = Number(semantic.split("_")[1]);
591
+ var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : channel + 1);
592
+ var uvs = new Float32Array(buffer.length);
593
+ uvs.set(buffer);
594
+ normalizeUVs(uvs);
595
+ tempVertexData.set(uvs, uvKind);
596
+ }
597
+ else if (semantic === "JOINT") {
598
+ tempVertexData.matricesIndices = new Float32Array(buffer.length);
599
+ tempVertexData.matricesIndices.set(buffer);
600
+ }
601
+ else if (semantic === "WEIGHT") {
602
+ tempVertexData.matricesWeights = new Float32Array(buffer.length);
603
+ tempVertexData.matricesWeights.set(buffer);
604
+ }
605
+ else if (semantic === "COLOR") {
606
+ tempVertexData.colors = new Float32Array(buffer.length);
607
+ tempVertexData.colors.set(buffer);
608
+ }
609
+ }
610
+ // Indices
611
+ accessor = gltfRuntime.accessors[primitive.indices];
612
+ if (accessor) {
613
+ buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
614
+ tempVertexData.indices = new Int32Array(buffer.length);
615
+ tempVertexData.indices.set(buffer);
616
+ indexCounts.push(tempVertexData.indices.length);
617
+ }
618
+ else {
619
+ // Set indices on the fly
620
+ var indices = [];
621
+ for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
622
+ indices.push(j);
623
+ }
624
+ tempVertexData.indices = new Int32Array(indices);
625
+ indexCounts.push(tempVertexData.indices.length);
626
+ }
627
+ if (!vertexData) {
628
+ vertexData = tempVertexData;
629
+ }
630
+ else {
631
+ vertexData.merge(tempVertexData);
632
+ }
633
+ // Sub material
634
+ var material_1 = gltfRuntime.scene.getMaterialById(primitive.material);
635
+ subMaterials.push(material_1 === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
636
+ // Update vertices start and index start
637
+ verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
638
+ indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
639
+ }
640
+ }
641
+ var material;
642
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
643
+ if (subMaterials.length > 1) {
644
+ material = new MultiMaterial("multimat" + id, gltfRuntime.scene);
645
+ material.subMaterials = subMaterials;
646
+ }
647
+ else {
648
+ material = new StandardMaterial("multimat" + id, gltfRuntime.scene);
649
+ }
650
+ if (subMaterials.length === 1) {
651
+ material = subMaterials[0];
652
+ }
653
+ material._parentContainer = gltfRuntime.assetContainer;
654
+ if (!newMesh.material) {
655
+ newMesh.material = material;
656
+ }
657
+ // Apply geometry
658
+ new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
659
+ newMesh.computeWorldMatrix(true);
660
+ gltfRuntime.scene._blockEntityCollection = false;
661
+ // Apply submeshes
662
+ newMesh.subMeshes = [];
663
+ var index = 0;
664
+ for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
665
+ var meshId = meshes[meshIndex];
666
+ var mesh = gltfRuntime.meshes[meshId];
667
+ if (!mesh) {
668
+ continue;
669
+ }
670
+ for (var i = 0; i < mesh.primitives.length; i++) {
671
+ if (mesh.primitives[i].mode !== 4) {
672
+ //continue;
673
+ }
674
+ SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
675
+ index++;
676
+ }
677
+ }
678
+ // Finish
679
+ return newMesh;
680
+ };
681
+ /**
682
+ * Configure node transformation from position, rotation and scaling
683
+ * @param newNode
684
+ * @param position
685
+ * @param rotation
686
+ * @param scaling
687
+ */
688
+ var configureNode = function (newNode, position, rotation, scaling) {
689
+ if (newNode.position) {
690
+ newNode.position = position;
691
+ }
692
+ if (newNode.rotationQuaternion || newNode.rotation) {
693
+ newNode.rotationQuaternion = rotation;
694
+ }
695
+ if (newNode.scaling) {
696
+ newNode.scaling = scaling;
697
+ }
698
+ };
699
+ /**
700
+ * Configures node from transformation matrix
701
+ * @param newNode
702
+ * @param node
703
+ */
704
+ var configureNodeFromMatrix = function (newNode, node) {
705
+ if (node.matrix) {
706
+ var position = new Vector3(0, 0, 0);
707
+ var rotation = new Quaternion();
708
+ var scaling = new Vector3(0, 0, 0);
709
+ var mat = Matrix.FromArray(node.matrix);
710
+ mat.decompose(scaling, rotation, position);
711
+ configureNode(newNode, position, rotation, scaling);
712
+ }
713
+ else if (node.translation && node.rotation && node.scale) {
714
+ configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
715
+ }
716
+ newNode.computeWorldMatrix(true);
717
+ };
718
+ /**
719
+ * Imports a node
720
+ * @param gltfRuntime
721
+ * @param node
722
+ * @param id
723
+ */
724
+ var importNode = function (gltfRuntime, node, id) {
725
+ var lastNode = null;
726
+ if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
727
+ if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
728
+ return null;
729
+ }
730
+ }
731
+ // Meshes
732
+ if (node.skin) {
733
+ if (node.meshes) {
734
+ var skin = gltfRuntime.skins[node.skin];
735
+ var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
736
+ newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin);
737
+ if (newMesh.skeleton === null) {
738
+ newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);
739
+ if (!skin.babylonSkeleton) {
740
+ skin.babylonSkeleton = newMesh.skeleton;
741
+ }
742
+ }
743
+ lastNode = newMesh;
744
+ }
745
+ }
746
+ else if (node.meshes) {
747
+ /**
748
+ * Improve meshes property
749
+ */
750
+ var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
751
+ lastNode = newMesh;
752
+ }
753
+ // Lights
754
+ else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
755
+ var light = gltfRuntime.lights[node.light];
756
+ if (light) {
757
+ if (light.type === "ambient") {
758
+ var ambienLight = light[light.type];
759
+ var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
760
+ hemiLight.name = node.name || "";
761
+ if (ambienLight.color) {
762
+ hemiLight.diffuse = Color3.FromArray(ambienLight.color);
763
+ }
764
+ lastNode = hemiLight;
765
+ }
766
+ else if (light.type === "directional") {
767
+ var directionalLight = light[light.type];
768
+ var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
769
+ dirLight.name = node.name || "";
770
+ if (directionalLight.color) {
771
+ dirLight.diffuse = Color3.FromArray(directionalLight.color);
772
+ }
773
+ lastNode = dirLight;
774
+ }
775
+ else if (light.type === "point") {
776
+ var pointLight = light[light.type];
777
+ var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
778
+ ptLight.name = node.name || "";
779
+ if (pointLight.color) {
780
+ ptLight.diffuse = Color3.FromArray(pointLight.color);
781
+ }
782
+ lastNode = ptLight;
783
+ }
784
+ else if (light.type === "spot") {
785
+ var spotLight = light[light.type];
786
+ var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
787
+ spLight.name = node.name || "";
788
+ if (spotLight.color) {
789
+ spLight.diffuse = Color3.FromArray(spotLight.color);
790
+ }
791
+ if (spotLight.fallOfAngle) {
792
+ spLight.angle = spotLight.fallOfAngle;
793
+ }
794
+ if (spotLight.fallOffExponent) {
795
+ spLight.exponent = spotLight.fallOffExponent;
796
+ }
797
+ lastNode = spLight;
798
+ }
799
+ }
800
+ }
801
+ // Cameras
802
+ else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
803
+ var camera = gltfRuntime.cameras[node.camera];
804
+ if (camera) {
805
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
806
+ if (camera.type === "orthographic") {
807
+ var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
808
+ orthoCamera.name = node.name || "";
809
+ orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
810
+ orthoCamera.attachControl();
811
+ lastNode = orthoCamera;
812
+ orthoCamera._parentContainer = gltfRuntime.assetContainer;
813
+ }
814
+ else if (camera.type === "perspective") {
815
+ var perspectiveCamera = camera[camera.type];
816
+ var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
817
+ persCamera.name = node.name || "";
818
+ persCamera.attachControl();
819
+ if (!perspectiveCamera.aspectRatio) {
820
+ perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
821
+ }
822
+ if (perspectiveCamera.znear && perspectiveCamera.zfar) {
823
+ persCamera.maxZ = perspectiveCamera.zfar;
824
+ persCamera.minZ = perspectiveCamera.znear;
825
+ }
826
+ lastNode = persCamera;
827
+ persCamera._parentContainer = gltfRuntime.assetContainer;
828
+ }
829
+ gltfRuntime.scene._blockEntityCollection = false;
830
+ }
831
+ }
832
+ // Empty node
833
+ if (!node.jointName) {
834
+ if (node.babylonNode) {
835
+ return node.babylonNode;
836
+ }
837
+ else if (lastNode === null) {
838
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
839
+ var dummy = new Mesh(node.name || "", gltfRuntime.scene);
840
+ dummy._parentContainer = gltfRuntime.assetContainer;
841
+ gltfRuntime.scene._blockEntityCollection = false;
842
+ node.babylonNode = dummy;
843
+ lastNode = dummy;
844
+ }
845
+ }
846
+ if (lastNode !== null) {
847
+ if (node.matrix && lastNode instanceof Mesh) {
848
+ configureNodeFromMatrix(lastNode, node);
849
+ }
850
+ else {
851
+ var translation = node.translation || [0, 0, 0];
852
+ var rotation = node.rotation || [0, 0, 0, 1];
853
+ var scale = node.scale || [1, 1, 1];
854
+ configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
855
+ }
856
+ lastNode.updateCache(true);
857
+ node.babylonNode = lastNode;
858
+ }
859
+ return lastNode;
860
+ };
861
+ /**
862
+ * Traverses nodes and creates them
863
+ * @param gltfRuntime
864
+ * @param id
865
+ * @param parent
866
+ * @param meshIncluded
867
+ */
868
+ var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
869
+ if (meshIncluded === void 0) { meshIncluded = false; }
870
+ var node = gltfRuntime.nodes[id];
871
+ var newNode = null;
872
+ if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
873
+ if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
874
+ meshIncluded = true;
875
+ }
876
+ else {
877
+ meshIncluded = false;
878
+ }
879
+ }
880
+ else {
881
+ meshIncluded = true;
882
+ }
883
+ if (!node.jointName && meshIncluded) {
884
+ newNode = importNode(gltfRuntime, node, id);
885
+ if (newNode !== null) {
886
+ newNode.id = id;
887
+ newNode.parent = parent;
888
+ }
889
+ }
890
+ if (node.children) {
891
+ for (var i = 0; i < node.children.length; i++) {
892
+ traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
893
+ }
894
+ }
895
+ };
896
+ /**
897
+ * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
898
+ * @param gltfRuntime
899
+ */
900
+ var postLoad = function (gltfRuntime) {
901
+ // Nodes
902
+ var currentScene = gltfRuntime.currentScene;
903
+ if (currentScene) {
904
+ for (var i = 0; i < currentScene.nodes.length; i++) {
905
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
906
+ }
907
+ }
908
+ else {
909
+ for (var thing in gltfRuntime.scenes) {
910
+ currentScene = gltfRuntime.scenes[thing];
911
+ for (var i = 0; i < currentScene.nodes.length; i++) {
912
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
913
+ }
914
+ }
915
+ }
916
+ // Set animations
917
+ loadAnimations(gltfRuntime);
918
+ for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
919
+ var skeleton = gltfRuntime.scene.skeletons[i];
920
+ gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
921
+ }
922
+ };
923
+ /**
924
+ * onBind shaderrs callback to set uniforms and matrices
925
+ * @param mesh
926
+ * @param gltfRuntime
927
+ * @param unTreatedUniforms
928
+ * @param shaderMaterial
929
+ * @param technique
930
+ * @param material
931
+ * @param onSuccess
932
+ */
933
+ var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
934
+ var materialValues = material.values || technique.parameters;
935
+ for (var unif in unTreatedUniforms) {
936
+ var uniform = unTreatedUniforms[unif];
937
+ var type = uniform.type;
938
+ if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
939
+ if (uniform.semantic && !uniform.source && !uniform.node) {
940
+ GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
941
+ }
942
+ else if (uniform.semantic && (uniform.source || uniform.node)) {
943
+ var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
944
+ if (source === null) {
945
+ source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || "");
946
+ }
947
+ if (source === null) {
948
+ continue;
949
+ }
950
+ GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
951
+ }
952
+ }
953
+ else {
954
+ var value = materialValues[technique.uniforms[unif]];
955
+ if (!value) {
956
+ continue;
957
+ }
958
+ if (type === EParameterType.SAMPLER_2D) {
959
+ var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
960
+ if (texture === null || texture === undefined) {
961
+ continue;
962
+ }
963
+ shaderMaterial.getEffect().setTexture(unif, texture);
964
+ }
965
+ else {
966
+ GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
967
+ }
968
+ }
969
+ }
970
+ onSuccess(shaderMaterial);
971
+ };
972
+ /**
973
+ * Prepare uniforms to send the only one time
974
+ * Loads the appropriate textures
975
+ * @param gltfRuntime
976
+ * @param shaderMaterial
977
+ * @param technique
978
+ * @param material
979
+ */
980
+ var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
981
+ var materialValues = material.values || technique.parameters;
982
+ var techniqueUniforms = technique.uniforms;
983
+ var _loop_1 = function (unif) {
984
+ var uniform = unTreatedUniforms[unif];
985
+ var type = uniform.type;
986
+ var value = materialValues[techniqueUniforms[unif]];
987
+ if (value === undefined) {
988
+ // In case the value is the same for all materials
989
+ value = uniform.value;
990
+ }
991
+ if (!value) {
992
+ return "continue";
993
+ }
994
+ var onLoadTexture = function (uniformName) {
995
+ return function (texture) {
996
+ if (uniform.value && uniformName) {
997
+ // Static uniform
998
+ shaderMaterial.setTexture(uniformName, texture);
999
+ delete unTreatedUniforms[uniformName];
1000
+ }
1001
+ };
1002
+ };
1003
+ // Texture (sampler2D)
1004
+ if (type === EParameterType.SAMPLER_2D) {
1005
+ GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
1006
+ }
1007
+ // Others
1008
+ else {
1009
+ if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
1010
+ // Static uniform
1011
+ delete unTreatedUniforms[unif];
1012
+ }
1013
+ }
1014
+ };
1015
+ /**
1016
+ * Prepare values here (not matrices)
1017
+ */
1018
+ for (var unif in unTreatedUniforms) {
1019
+ _loop_1(unif);
1020
+ }
1021
+ };
1022
+ /**
1023
+ * Shader compilation failed
1024
+ * @param program
1025
+ * @param shaderMaterial
1026
+ * @param onError
1027
+ */
1028
+ var onShaderCompileError = function (program, shaderMaterial, onError) {
1029
+ return function (effect, error) {
1030
+ shaderMaterial.dispose(true);
1031
+ onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
1032
+ };
1033
+ };
1034
+ /**
1035
+ * Shader compilation success
1036
+ * @param gltfRuntime
1037
+ * @param shaderMaterial
1038
+ * @param technique
1039
+ * @param material
1040
+ * @param unTreatedUniforms
1041
+ * @param onSuccess
1042
+ */
1043
+ var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
1044
+ return function (_) {
1045
+ prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
1046
+ shaderMaterial.onBind = function (mesh) {
1047
+ onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
1048
+ };
1049
+ };
1050
+ };
1051
+ /**
1052
+ * Returns the appropriate uniform if already handled by babylon
1053
+ * @param tokenizer
1054
+ * @param technique
1055
+ */
1056
+ var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
1057
+ for (var unif in technique.uniforms) {
1058
+ var uniform = technique.uniforms[unif];
1059
+ var uniformParameter = technique.parameters[uniform];
1060
+ if (tokenizer.currentIdentifier === unif) {
1061
+ if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
1062
+ var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
1063
+ if (transformIndex !== -1) {
1064
+ delete unTreatedUniforms[unif];
1065
+ return babylonTransforms[transformIndex];
1066
+ }
1067
+ }
1068
+ }
1069
+ }
1070
+ return tokenizer.currentIdentifier;
1071
+ };
1072
+ /**
1073
+ * All shaders loaded. Create materials one by one
1074
+ * @param gltfRuntime
1075
+ */
1076
+ var importMaterials = function (gltfRuntime) {
1077
+ // Create materials
1078
+ for (var mat in gltfRuntime.materials) {
1079
+ GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function () { }, function () { });
1080
+ }
1081
+ };
1082
+ /**
1083
+ * Implementation of the base glTF spec
1084
+ * @hidden
1085
+ */
1086
+ var GLTFLoaderBase = /** @class */ (function () {
1087
+ function GLTFLoaderBase() {
1088
+ }
1089
+ GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
1090
+ var gltfRuntime = {
1091
+ extensions: {},
1092
+ accessors: {},
1093
+ buffers: {},
1094
+ bufferViews: {},
1095
+ meshes: {},
1096
+ lights: {},
1097
+ cameras: {},
1098
+ nodes: {},
1099
+ images: {},
1100
+ textures: {},
1101
+ shaders: {},
1102
+ programs: {},
1103
+ samplers: {},
1104
+ techniques: {},
1105
+ materials: {},
1106
+ animations: {},
1107
+ skins: {},
1108
+ extensionsUsed: [],
1109
+ scenes: {},
1110
+ buffersCount: 0,
1111
+ shaderscount: 0,
1112
+ scene: scene,
1113
+ rootUrl: rootUrl,
1114
+ loadedBufferCount: 0,
1115
+ loadedBufferViews: {},
1116
+ loadedShaderCount: 0,
1117
+ importOnlyMeshes: false,
1118
+ dummyNodes: [],
1119
+ assetContainer: null,
1120
+ };
1121
+ // Parse
1122
+ if (parsedData.extensions) {
1123
+ parseObject(parsedData.extensions, "extensions", gltfRuntime);
1124
+ }
1125
+ if (parsedData.extensionsUsed) {
1126
+ parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
1127
+ }
1128
+ if (parsedData.buffers) {
1129
+ parseBuffers(parsedData.buffers, gltfRuntime);
1130
+ }
1131
+ if (parsedData.bufferViews) {
1132
+ parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
1133
+ }
1134
+ if (parsedData.accessors) {
1135
+ parseObject(parsedData.accessors, "accessors", gltfRuntime);
1136
+ }
1137
+ if (parsedData.meshes) {
1138
+ parseObject(parsedData.meshes, "meshes", gltfRuntime);
1139
+ }
1140
+ if (parsedData.lights) {
1141
+ parseObject(parsedData.lights, "lights", gltfRuntime);
1142
+ }
1143
+ if (parsedData.cameras) {
1144
+ parseObject(parsedData.cameras, "cameras", gltfRuntime);
1145
+ }
1146
+ if (parsedData.nodes) {
1147
+ parseObject(parsedData.nodes, "nodes", gltfRuntime);
1148
+ }
1149
+ if (parsedData.images) {
1150
+ parseObject(parsedData.images, "images", gltfRuntime);
1151
+ }
1152
+ if (parsedData.textures) {
1153
+ parseObject(parsedData.textures, "textures", gltfRuntime);
1154
+ }
1155
+ if (parsedData.shaders) {
1156
+ parseShaders(parsedData.shaders, gltfRuntime);
1157
+ }
1158
+ if (parsedData.programs) {
1159
+ parseObject(parsedData.programs, "programs", gltfRuntime);
1160
+ }
1161
+ if (parsedData.samplers) {
1162
+ parseObject(parsedData.samplers, "samplers", gltfRuntime);
1163
+ }
1164
+ if (parsedData.techniques) {
1165
+ parseObject(parsedData.techniques, "techniques", gltfRuntime);
1166
+ }
1167
+ if (parsedData.materials) {
1168
+ parseObject(parsedData.materials, "materials", gltfRuntime);
1169
+ }
1170
+ if (parsedData.animations) {
1171
+ parseObject(parsedData.animations, "animations", gltfRuntime);
1172
+ }
1173
+ if (parsedData.skins) {
1174
+ parseObject(parsedData.skins, "skins", gltfRuntime);
1175
+ }
1176
+ if (parsedData.scenes) {
1177
+ gltfRuntime.scenes = parsedData.scenes;
1178
+ }
1179
+ if (parsedData.scene && parsedData.scenes) {
1180
+ gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
1181
+ }
1182
+ return gltfRuntime;
1183
+ };
1184
+ GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1185
+ var buffer = gltfRuntime.buffers[id];
1186
+ if (Tools.IsBase64(buffer.uri)) {
1187
+ setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))); });
1188
+ }
1189
+ else {
1190
+ Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
1191
+ if (request) {
1192
+ onError(request.status + " " + request.statusText);
1193
+ }
1194
+ });
1195
+ }
1196
+ };
1197
+ GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1198
+ var texture = gltfRuntime.textures[id];
1199
+ if (!texture || !texture.source) {
1200
+ onError("");
1201
+ return;
1202
+ }
1203
+ if (texture.babylonTexture) {
1204
+ onSuccess(null);
1205
+ return;
1206
+ }
1207
+ var source = gltfRuntime.images[texture.source];
1208
+ if (Tools.IsBase64(source.uri)) {
1209
+ setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))); });
1210
+ }
1211
+ else {
1212
+ Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
1213
+ if (request) {
1214
+ onError(request.status + " " + request.statusText);
1215
+ }
1216
+ });
1217
+ }
1218
+ };
1219
+ GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess) {
1220
+ var texture = gltfRuntime.textures[id];
1221
+ if (texture.babylonTexture) {
1222
+ onSuccess(texture.babylonTexture);
1223
+ return;
1224
+ }
1225
+ var sampler = gltfRuntime.samplers[texture.sampler];
1226
+ var createMipMaps = sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST ||
1227
+ sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR ||
1228
+ sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST ||
1229
+ sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR;
1230
+ var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
1231
+ var blob = buffer == null ? new Blob() : new Blob([buffer]);
1232
+ var blobURL = URL.createObjectURL(blob);
1233
+ var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
1234
+ var newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
1235
+ if (sampler.wrapS !== undefined) {
1236
+ newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
1237
+ }
1238
+ if (sampler.wrapT !== undefined) {
1239
+ newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
1240
+ }
1241
+ newTexture.name = id;
1242
+ texture.babylonTexture = newTexture;
1243
+ onSuccess(newTexture);
1244
+ };
1245
+ GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1246
+ var shader = gltfRuntime.shaders[id];
1247
+ if (Tools.IsBase64(shader.uri)) {
1248
+ var shaderString = atob(shader.uri.split(",")[1]);
1249
+ if (onSuccess) {
1250
+ onSuccess(shaderString);
1251
+ }
1252
+ }
1253
+ else {
1254
+ Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
1255
+ if (request && onError) {
1256
+ onError(request.status + " " + request.statusText);
1257
+ }
1258
+ });
1259
+ }
1260
+ };
1261
+ GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1262
+ var material = gltfRuntime.materials[id];
1263
+ if (!material.technique) {
1264
+ if (onError) {
1265
+ onError("No technique found.");
1266
+ }
1267
+ return;
1268
+ }
1269
+ var technique = gltfRuntime.techniques[material.technique];
1270
+ if (!technique) {
1271
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
1272
+ var defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
1273
+ defaultMaterial._parentContainer = gltfRuntime.assetContainer;
1274
+ gltfRuntime.scene._blockEntityCollection = false;
1275
+ defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
1276
+ defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1277
+ onSuccess(defaultMaterial);
1278
+ return;
1279
+ }
1280
+ var program = gltfRuntime.programs[technique.program];
1281
+ var states = technique.states;
1282
+ var vertexShader = Effect.ShadersStore[program.vertexShader + "VertexShader"];
1283
+ var pixelShader = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
1284
+ var newVertexShader = "";
1285
+ var newPixelShader = "";
1286
+ var vertexTokenizer = new Tokenizer(vertexShader);
1287
+ var pixelTokenizer = new Tokenizer(pixelShader);
1288
+ var unTreatedUniforms = {};
1289
+ var uniforms = [];
1290
+ var attributes = [];
1291
+ var samplers = [];
1292
+ // Fill uniform, sampler2D and attributes
1293
+ for (var unif in technique.uniforms) {
1294
+ var uniform = technique.uniforms[unif];
1295
+ var uniformParameter = technique.parameters[uniform];
1296
+ unTreatedUniforms[unif] = uniformParameter;
1297
+ if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
1298
+ var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
1299
+ if (transformIndex !== -1) {
1300
+ uniforms.push(babylonTransforms[transformIndex]);
1301
+ delete unTreatedUniforms[unif];
1302
+ }
1303
+ else {
1304
+ uniforms.push(unif);
1305
+ }
1306
+ }
1307
+ else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
1308
+ samplers.push(unif);
1309
+ }
1310
+ else {
1311
+ uniforms.push(unif);
1312
+ }
1313
+ }
1314
+ for (var attr in technique.attributes) {
1315
+ var attribute = technique.attributes[attr];
1316
+ var attributeParameter = technique.parameters[attribute];
1317
+ if (attributeParameter.semantic) {
1318
+ var name_1 = getAttribute(attributeParameter);
1319
+ if (name_1) {
1320
+ attributes.push(name_1);
1321
+ }
1322
+ }
1323
+ }
1324
+ // Configure vertex shader
1325
+ while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
1326
+ var tokenType = vertexTokenizer.currentToken;
1327
+ if (tokenType !== ETokenType.IDENTIFIER) {
1328
+ newVertexShader += vertexTokenizer.currentString;
1329
+ continue;
1330
+ }
1331
+ var foundAttribute = false;
1332
+ for (var attr in technique.attributes) {
1333
+ var attribute = technique.attributes[attr];
1334
+ var attributeParameter = technique.parameters[attribute];
1335
+ if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
1336
+ newVertexShader += getAttribute(attributeParameter);
1337
+ foundAttribute = true;
1338
+ break;
1339
+ }
1340
+ }
1341
+ if (foundAttribute) {
1342
+ continue;
1343
+ }
1344
+ newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
1345
+ }
1346
+ // Configure pixel shader
1347
+ while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
1348
+ var tokenType = pixelTokenizer.currentToken;
1349
+ if (tokenType !== ETokenType.IDENTIFIER) {
1350
+ newPixelShader += pixelTokenizer.currentString;
1351
+ continue;
1352
+ }
1353
+ newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
1354
+ }
1355
+ // Create shader material
1356
+ var shaderPath = {
1357
+ vertex: program.vertexShader + id,
1358
+ fragment: program.fragmentShader + id,
1359
+ };
1360
+ var options = {
1361
+ attributes: attributes,
1362
+ uniforms: uniforms,
1363
+ samplers: samplers,
1364
+ needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1,
1365
+ };
1366
+ Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
1367
+ Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
1368
+ var shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
1369
+ shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
1370
+ shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
1371
+ shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1372
+ if (states && states.functions) {
1373
+ var functions = states.functions;
1374
+ if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
1375
+ shaderMaterial.backFaceCulling = false;
1376
+ }
1377
+ var blendFunc = functions.blendFuncSeparate;
1378
+ if (blendFunc) {
1379
+ if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1380
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA &&
1381
+ blendFunc[2] === EBlendingFunction.ONE &&
1382
+ blendFunc[3] === EBlendingFunction.ONE) {
1383
+ shaderMaterial.alphaMode = Constants.ALPHA_COMBINE;
1384
+ }
1385
+ else if (blendFunc[0] === EBlendingFunction.ONE &&
1386
+ blendFunc[1] === EBlendingFunction.ONE &&
1387
+ blendFunc[2] === EBlendingFunction.ZERO &&
1388
+ blendFunc[3] === EBlendingFunction.ONE) {
1389
+ shaderMaterial.alphaMode = Constants.ALPHA_ONEONE;
1390
+ }
1391
+ else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1392
+ blendFunc[1] === EBlendingFunction.ONE &&
1393
+ blendFunc[2] === EBlendingFunction.ZERO &&
1394
+ blendFunc[3] === EBlendingFunction.ONE) {
1395
+ shaderMaterial.alphaMode = Constants.ALPHA_ADD;
1396
+ }
1397
+ else if (blendFunc[0] === EBlendingFunction.ZERO &&
1398
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
1399
+ blendFunc[2] === EBlendingFunction.ONE &&
1400
+ blendFunc[3] === EBlendingFunction.ONE) {
1401
+ shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT;
1402
+ }
1403
+ else if (blendFunc[0] === EBlendingFunction.DST_COLOR &&
1404
+ blendFunc[1] === EBlendingFunction.ZERO &&
1405
+ blendFunc[2] === EBlendingFunction.ONE &&
1406
+ blendFunc[3] === EBlendingFunction.ONE) {
1407
+ shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY;
1408
+ }
1409
+ else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1410
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
1411
+ blendFunc[2] === EBlendingFunction.ONE &&
1412
+ blendFunc[3] === EBlendingFunction.ONE) {
1413
+ shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED;
1414
+ }
1415
+ }
1416
+ }
1417
+ };
1418
+ return GLTFLoaderBase;
1419
+ }());
1420
+ export { GLTFLoaderBase };
1421
+ /**
1422
+ * glTF V1 Loader
1423
+ * @hidden
1424
+ */
1425
+ var GLTFLoader = /** @class */ (function () {
1426
+ function GLTFLoader() {
1427
+ }
1428
+ GLTFLoader.RegisterExtension = function (extension) {
1429
+ if (GLTFLoader.Extensions[extension.name]) {
1430
+ Tools.Error('Tool with the same name "' + extension.name + '" already exists');
1431
+ return;
1432
+ }
1433
+ GLTFLoader.Extensions[extension.name] = extension;
1434
+ };
1435
+ GLTFLoader.prototype.dispose = function () {
1436
+ // do nothing
1437
+ };
1438
+ GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) {
1439
+ var _this = this;
1440
+ scene.useRightHandedSystem = true;
1441
+ GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1442
+ gltfRuntime.assetContainer = assetContainer;
1443
+ gltfRuntime.importOnlyMeshes = true;
1444
+ if (meshesNames === "") {
1445
+ gltfRuntime.importMeshesNames = [];
1446
+ }
1447
+ else if (typeof meshesNames === "string") {
1448
+ gltfRuntime.importMeshesNames = [meshesNames];
1449
+ }
1450
+ else if (meshesNames && !(meshesNames instanceof Array)) {
1451
+ gltfRuntime.importMeshesNames = [meshesNames];
1452
+ }
1453
+ else {
1454
+ gltfRuntime.importMeshesNames = [];
1455
+ Tools.Warn("Argument meshesNames must be of type string or string[]");
1456
+ }
1457
+ // Create nodes
1458
+ _this._createNodes(gltfRuntime);
1459
+ var meshes = new Array();
1460
+ var skeletons = new Array();
1461
+ // Fill arrays of meshes and skeletons
1462
+ for (var nde in gltfRuntime.nodes) {
1463
+ var node = gltfRuntime.nodes[nde];
1464
+ if (node.babylonNode instanceof AbstractMesh) {
1465
+ meshes.push(node.babylonNode);
1466
+ }
1467
+ }
1468
+ for (var skl in gltfRuntime.skins) {
1469
+ var skin = gltfRuntime.skins[skl];
1470
+ if (skin.babylonSkeleton instanceof Skeleton) {
1471
+ skeletons.push(skin.babylonSkeleton);
1472
+ }
1473
+ }
1474
+ // Load buffers, shaders, materials, etc.
1475
+ _this._loadBuffersAsync(gltfRuntime, function () {
1476
+ _this._loadShadersAsync(gltfRuntime, function () {
1477
+ importMaterials(gltfRuntime);
1478
+ postLoad(gltfRuntime);
1479
+ if (!GLTFFileLoader.IncrementalLoading && onSuccess) {
1480
+ onSuccess(meshes, skeletons);
1481
+ }
1482
+ });
1483
+ });
1484
+ if (GLTFFileLoader.IncrementalLoading && onSuccess) {
1485
+ onSuccess(meshes, skeletons);
1486
+ }
1487
+ }, onError);
1488
+ return true;
1489
+ };
1490
+ /**
1491
+ * Imports one or more meshes from a loaded gltf file and adds them to the scene
1492
+ * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
1493
+ * @param scene the scene the meshes should be added to
1494
+ * @param assetContainer defines the asset container to use (can be null)
1495
+ * @param data gltf data containing information of the meshes in a loaded file
1496
+ * @param rootUrl root url to load from
1497
+ * @param onProgress event that fires when loading progress has occured
1498
+ * @returns a promise containg the loaded meshes, particles, skeletons and animations
1499
+ */
1500
+ GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, assetContainer, data, rootUrl, onProgress) {
1501
+ var _this = this;
1502
+ return new Promise(function (resolve, reject) {
1503
+ _this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, function (meshes, skeletons) {
1504
+ resolve({
1505
+ meshes: meshes,
1506
+ particleSystems: [],
1507
+ skeletons: skeletons,
1508
+ animationGroups: [],
1509
+ lights: [],
1510
+ transformNodes: [],
1511
+ geometries: [],
1512
+ });
1513
+ }, onProgress, function (message) {
1514
+ reject(new Error(message));
1515
+ });
1516
+ });
1517
+ };
1518
+ GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
1519
+ var _this = this;
1520
+ scene.useRightHandedSystem = true;
1521
+ GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1522
+ // Load runtime extensios
1523
+ GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
1524
+ // Create nodes
1525
+ _this._createNodes(gltfRuntime);
1526
+ // Load buffers, shaders, materials, etc.
1527
+ _this._loadBuffersAsync(gltfRuntime, function () {
1528
+ _this._loadShadersAsync(gltfRuntime, function () {
1529
+ importMaterials(gltfRuntime);
1530
+ postLoad(gltfRuntime);
1531
+ if (!GLTFFileLoader.IncrementalLoading) {
1532
+ onSuccess();
1533
+ }
1534
+ });
1535
+ });
1536
+ if (GLTFFileLoader.IncrementalLoading) {
1537
+ onSuccess();
1538
+ }
1539
+ }, onError);
1540
+ }, onError);
1541
+ };
1542
+ /**
1543
+ * Imports all objects from a loaded gltf file and adds them to the scene
1544
+ * @param scene the scene the objects should be added to
1545
+ * @param data gltf data containing information of the meshes in a loaded file
1546
+ * @param rootUrl root url to load from
1547
+ * @param onProgress event that fires when loading progress has occured
1548
+ * @returns a promise which completes when objects have been loaded to the scene
1549
+ */
1550
+ GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
1551
+ var _this = this;
1552
+ return new Promise(function (resolve, reject) {
1553
+ _this._loadAsync(scene, data, rootUrl, function () {
1554
+ resolve();
1555
+ }, onProgress, function (message) {
1556
+ reject(new Error(message));
1557
+ });
1558
+ });
1559
+ };
1560
+ GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
1561
+ var hasShaders = false;
1562
+ var processShader = function (sha, shader) {
1563
+ GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
1564
+ if (shaderString instanceof ArrayBuffer) {
1565
+ return;
1566
+ }
1567
+ gltfRuntime.loadedShaderCount++;
1568
+ if (shaderString) {
1569
+ Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
1570
+ }
1571
+ if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
1572
+ onload();
1573
+ }
1574
+ }, function () {
1575
+ Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
1576
+ });
1577
+ };
1578
+ for (var sha in gltfRuntime.shaders) {
1579
+ hasShaders = true;
1580
+ var shader = gltfRuntime.shaders[sha];
1581
+ if (shader) {
1582
+ processShader.bind(this, sha, shader)();
1583
+ }
1584
+ else {
1585
+ Tools.Error("No shader named: " + sha);
1586
+ }
1587
+ }
1588
+ if (!hasShaders) {
1589
+ onload();
1590
+ }
1591
+ };
1592
+ GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad) {
1593
+ var hasBuffers = false;
1594
+ var processBuffer = function (buf, buffer) {
1595
+ GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
1596
+ gltfRuntime.loadedBufferCount++;
1597
+ if (bufferView) {
1598
+ if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
1599
+ Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
1600
+ }
1601
+ gltfRuntime.loadedBufferViews[buf] = bufferView;
1602
+ }
1603
+ if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
1604
+ onLoad();
1605
+ }
1606
+ }, function () {
1607
+ Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
1608
+ });
1609
+ };
1610
+ for (var buf in gltfRuntime.buffers) {
1611
+ hasBuffers = true;
1612
+ var buffer = gltfRuntime.buffers[buf];
1613
+ if (buffer) {
1614
+ processBuffer.bind(this, buf, buffer)();
1615
+ }
1616
+ else {
1617
+ Tools.Error("No buffer named: " + buf);
1618
+ }
1619
+ }
1620
+ if (!hasBuffers) {
1621
+ onLoad();
1622
+ }
1623
+ };
1624
+ GLTFLoader.prototype._createNodes = function (gltfRuntime) {
1625
+ var currentScene = gltfRuntime.currentScene;
1626
+ if (currentScene) {
1627
+ // Only one scene even if multiple scenes are defined
1628
+ for (var i = 0; i < currentScene.nodes.length; i++) {
1629
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1630
+ }
1631
+ }
1632
+ else {
1633
+ // Load all scenes
1634
+ for (var thing in gltfRuntime.scenes) {
1635
+ currentScene = gltfRuntime.scenes[thing];
1636
+ for (var i = 0; i < currentScene.nodes.length; i++) {
1637
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1638
+ }
1639
+ }
1640
+ }
1641
+ };
1642
+ GLTFLoader.Extensions = {};
1643
+ return GLTFLoader;
1644
+ }());
1645
+ export { GLTFLoader };
1646
+ /** @hidden */
1647
+ var GLTFLoaderExtension = /** @class */ (function () {
1648
+ function GLTFLoaderExtension(name) {
1649
+ this._name = name;
1650
+ }
1651
+ Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
1652
+ get: function () {
1653
+ return this._name;
1654
+ },
1655
+ enumerable: false,
1656
+ configurable: true
1657
+ });
1658
+ /**
1659
+ * Defines an override for loading the runtime
1660
+ * Return true to stop further extensions from loading the runtime
1661
+ * @param scene
1662
+ * @param data
1663
+ * @param rootUrl
1664
+ * @param onSuccess
1665
+ * @param onError
1666
+ */
1667
+ GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1668
+ return false;
1669
+ };
1670
+ /**
1671
+ * Defines an onverride for creating gltf runtime
1672
+ * Return true to stop further extensions from creating the runtime
1673
+ * @param gltfRuntime
1674
+ * @param onSuccess
1675
+ * @param onError
1676
+ */
1677
+ GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1678
+ return false;
1679
+ };
1680
+ /**
1681
+ * Defines an override for loading buffers
1682
+ * Return true to stop further extensions from loading this buffer
1683
+ * @param gltfRuntime
1684
+ * @param id
1685
+ * @param onSuccess
1686
+ * @param onError
1687
+ * @param onProgress
1688
+ */
1689
+ GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1690
+ return false;
1691
+ };
1692
+ /**
1693
+ * Defines an override for loading texture buffers
1694
+ * Return true to stop further extensions from loading this texture data
1695
+ * @param gltfRuntime
1696
+ * @param id
1697
+ * @param onSuccess
1698
+ * @param onError
1699
+ */
1700
+ GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1701
+ return false;
1702
+ };
1703
+ /**
1704
+ * Defines an override for creating textures
1705
+ * Return true to stop further extensions from loading this texture
1706
+ * @param gltfRuntime
1707
+ * @param id
1708
+ * @param buffer
1709
+ * @param onSuccess
1710
+ * @param onError
1711
+ */
1712
+ GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1713
+ return false;
1714
+ };
1715
+ /**
1716
+ * Defines an override for loading shader strings
1717
+ * Return true to stop further extensions from loading this shader data
1718
+ * @param gltfRuntime
1719
+ * @param id
1720
+ * @param onSuccess
1721
+ * @param onError
1722
+ */
1723
+ GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1724
+ return false;
1725
+ };
1726
+ /**
1727
+ * Defines an override for loading materials
1728
+ * Return true to stop further extensions from loading this material
1729
+ * @param gltfRuntime
1730
+ * @param id
1731
+ * @param onSuccess
1732
+ * @param onError
1733
+ */
1734
+ GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1735
+ return false;
1736
+ };
1737
+ // ---------
1738
+ // Utilities
1739
+ // ---------
1740
+ GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1741
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1742
+ return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
1743
+ }, function () {
1744
+ setTimeout(function () {
1745
+ if (!onSuccess) {
1746
+ return;
1747
+ }
1748
+ onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
1749
+ });
1750
+ });
1751
+ };
1752
+ GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1753
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1754
+ return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
1755
+ }, function () {
1756
+ setTimeout(function () {
1757
+ onSuccess();
1758
+ });
1759
+ });
1760
+ };
1761
+ GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1762
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1763
+ return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1764
+ }, function () {
1765
+ GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1766
+ });
1767
+ };
1768
+ GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
1769
+ GLTFLoaderExtension._LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
1770
+ if (buffer) {
1771
+ GLTFLoaderExtension._CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1772
+ }
1773
+ }, onError);
1774
+ };
1775
+ GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1776
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1777
+ return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1778
+ }, function () {
1779
+ GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1780
+ });
1781
+ };
1782
+ GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1783
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1784
+ return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1785
+ }, function () {
1786
+ GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1787
+ });
1788
+ };
1789
+ GLTFLoaderExtension._LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1790
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1791
+ return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1792
+ }, function () {
1793
+ GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1794
+ });
1795
+ };
1796
+ GLTFLoaderExtension._CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1797
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1798
+ return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1799
+ }, function () {
1800
+ GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess);
1801
+ });
1802
+ };
1803
+ GLTFLoaderExtension._ApplyExtensions = function (func, defaultFunc) {
1804
+ for (var extensionName in GLTFLoader.Extensions) {
1805
+ var loaderExtension = GLTFLoader.Extensions[extensionName];
1806
+ if (func(loaderExtension)) {
1807
+ return;
1808
+ }
1809
+ }
1810
+ defaultFunc();
1811
+ };
1812
+ return GLTFLoaderExtension;
1813
+ }());
1814
+ export { GLTFLoaderExtension };
1815
+ GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
1816
1816
  //# sourceMappingURL=glTFLoader.js.map