@babylonjs/loaders 9.22.2 → 9.24.0

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