@2112-lab/central-plant 0.1.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 (54) hide show
  1. package/README.md +0 -0
  2. package/dist/bundle/index.js +14259 -0
  3. package/dist/cjs/_virtual/_rollupPluginBabelHelpers.js +353 -0
  4. package/dist/cjs/node_modules/three/examples/jsm/controls/OrbitControls.js +1292 -0
  5. package/dist/cjs/node_modules/three/examples/jsm/controls/TransformControls.js +1543 -0
  6. package/dist/cjs/node_modules/three/examples/jsm/loaders/GLTFLoader.js +4374 -0
  7. package/dist/cjs/node_modules/three/examples/jsm/loaders/RGBELoader.js +465 -0
  8. package/dist/cjs/node_modules/three/examples/jsm/utils/BufferGeometryUtils.js +117 -0
  9. package/dist/cjs/src/ConnectionManager.js +114 -0
  10. package/dist/cjs/src/Pathfinder.js +88 -0
  11. package/dist/cjs/src/animationManager.js +121 -0
  12. package/dist/cjs/src/componentManager.js +151 -0
  13. package/dist/cjs/src/debugLogger.js +176 -0
  14. package/dist/cjs/src/disposalManager.js +185 -0
  15. package/dist/cjs/src/environmentManager.js +1015 -0
  16. package/dist/cjs/src/hotReloadManager.js +252 -0
  17. package/dist/cjs/src/index.js +126 -0
  18. package/dist/cjs/src/keyboardControlsManager.js +206 -0
  19. package/dist/cjs/src/modelPreloader.js +360 -0
  20. package/dist/cjs/src/nameUtils.js +106 -0
  21. package/dist/cjs/src/pathfindingManager.js +321 -0
  22. package/dist/cjs/src/performanceMonitor.js +718 -0
  23. package/dist/cjs/src/sceneExportManager.js +292 -0
  24. package/dist/cjs/src/sceneInitializationManager.js +540 -0
  25. package/dist/cjs/src/sceneOperationsManager.js +560 -0
  26. package/dist/cjs/src/textureConfig.js +195 -0
  27. package/dist/cjs/src/transformControlsManager.js +851 -0
  28. package/dist/esm/_virtual/_rollupPluginBabelHelpers.js +328 -0
  29. package/dist/esm/node_modules/three/examples/jsm/controls/OrbitControls.js +1287 -0
  30. package/dist/esm/node_modules/three/examples/jsm/controls/TransformControls.js +1537 -0
  31. package/dist/esm/node_modules/three/examples/jsm/loaders/GLTFLoader.js +4370 -0
  32. package/dist/esm/node_modules/three/examples/jsm/loaders/RGBELoader.js +461 -0
  33. package/dist/esm/node_modules/three/examples/jsm/utils/BufferGeometryUtils.js +113 -0
  34. package/dist/esm/src/ConnectionManager.js +110 -0
  35. package/dist/esm/src/Pathfinder.js +84 -0
  36. package/dist/esm/src/animationManager.js +112 -0
  37. package/dist/esm/src/componentManager.js +123 -0
  38. package/dist/esm/src/debugLogger.js +167 -0
  39. package/dist/esm/src/disposalManager.js +155 -0
  40. package/dist/esm/src/environmentManager.js +989 -0
  41. package/dist/esm/src/hotReloadManager.js +244 -0
  42. package/dist/esm/src/index.js +117 -0
  43. package/dist/esm/src/keyboardControlsManager.js +196 -0
  44. package/dist/esm/src/modelPreloader.js +337 -0
  45. package/dist/esm/src/nameUtils.js +99 -0
  46. package/dist/esm/src/pathfindingManager.js +295 -0
  47. package/dist/esm/src/performanceMonitor.js +712 -0
  48. package/dist/esm/src/sceneExportManager.js +286 -0
  49. package/dist/esm/src/sceneInitializationManager.js +513 -0
  50. package/dist/esm/src/sceneOperationsManager.js +536 -0
  51. package/dist/esm/src/textureConfig.js +168 -0
  52. package/dist/esm/src/transformControlsManager.js +827 -0
  53. package/dist/index.d.ts +259 -0
  54. package/package.json +53 -0
@@ -0,0 +1,4374 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var THREE = require('three');
6
+ var BufferGeometryUtils = require('../utils/BufferGeometryUtils.js');
7
+
8
+ class GLTFLoader extends THREE.Loader {
9
+
10
+ constructor( manager ) {
11
+
12
+ super( manager );
13
+
14
+ this.dracoLoader = null;
15
+ this.ktx2Loader = null;
16
+ this.meshoptDecoder = null;
17
+
18
+ this.pluginCallbacks = [];
19
+
20
+ this.register( function ( parser ) {
21
+
22
+ return new GLTFMaterialsClearcoatExtension( parser );
23
+
24
+ } );
25
+
26
+ this.register( function ( parser ) {
27
+
28
+ return new GLTFTextureBasisUExtension( parser );
29
+
30
+ } );
31
+
32
+ this.register( function ( parser ) {
33
+
34
+ return new GLTFTextureWebPExtension( parser );
35
+
36
+ } );
37
+
38
+ this.register( function ( parser ) {
39
+
40
+ return new GLTFTextureAVIFExtension( parser );
41
+
42
+ } );
43
+
44
+ this.register( function ( parser ) {
45
+
46
+ return new GLTFMaterialsSheenExtension( parser );
47
+
48
+ } );
49
+
50
+ this.register( function ( parser ) {
51
+
52
+ return new GLTFMaterialsTransmissionExtension( parser );
53
+
54
+ } );
55
+
56
+ this.register( function ( parser ) {
57
+
58
+ return new GLTFMaterialsVolumeExtension( parser );
59
+
60
+ } );
61
+
62
+ this.register( function ( parser ) {
63
+
64
+ return new GLTFMaterialsIorExtension( parser );
65
+
66
+ } );
67
+
68
+ this.register( function ( parser ) {
69
+
70
+ return new GLTFMaterialsEmissiveStrengthExtension( parser );
71
+
72
+ } );
73
+
74
+ this.register( function ( parser ) {
75
+
76
+ return new GLTFMaterialsSpecularExtension( parser );
77
+
78
+ } );
79
+
80
+ this.register( function ( parser ) {
81
+
82
+ return new GLTFMaterialsIridescenceExtension( parser );
83
+
84
+ } );
85
+
86
+ this.register( function ( parser ) {
87
+
88
+ return new GLTFLightsExtension( parser );
89
+
90
+ } );
91
+
92
+ this.register( function ( parser ) {
93
+
94
+ return new GLTFMeshoptCompression( parser );
95
+
96
+ } );
97
+
98
+ this.register( function ( parser ) {
99
+
100
+ return new GLTFMeshGpuInstancing( parser );
101
+
102
+ } );
103
+
104
+ }
105
+
106
+ load( url, onLoad, onProgress, onError ) {
107
+
108
+ const scope = this;
109
+
110
+ let resourcePath;
111
+
112
+ if ( this.resourcePath !== '' ) {
113
+
114
+ resourcePath = this.resourcePath;
115
+
116
+ } else if ( this.path !== '' ) {
117
+
118
+ resourcePath = this.path;
119
+
120
+ } else {
121
+
122
+ resourcePath = THREE.LoaderUtils.extractUrlBase( url );
123
+
124
+ }
125
+
126
+ // Tells the LoadingManager to track an extra item, which resolves after
127
+ // the model is fully loaded. This means the count of items loaded will
128
+ // be incorrect, but ensures manager.onLoad() does not fire early.
129
+ this.manager.itemStart( url );
130
+
131
+ const _onError = function ( e ) {
132
+
133
+ if ( onError ) {
134
+
135
+ onError( e );
136
+
137
+ } else {
138
+
139
+ console.error( e );
140
+
141
+ }
142
+
143
+ scope.manager.itemError( url );
144
+ scope.manager.itemEnd( url );
145
+
146
+ };
147
+
148
+ const loader = new THREE.FileLoader( this.manager );
149
+
150
+ loader.setPath( this.path );
151
+ loader.setResponseType( 'arraybuffer' );
152
+ loader.setRequestHeader( this.requestHeader );
153
+ loader.setWithCredentials( this.withCredentials );
154
+
155
+ loader.load( url, function ( data ) {
156
+
157
+ try {
158
+
159
+ scope.parse( data, resourcePath, function ( gltf ) {
160
+
161
+ onLoad( gltf );
162
+
163
+ scope.manager.itemEnd( url );
164
+
165
+ }, _onError );
166
+
167
+ } catch ( e ) {
168
+
169
+ _onError( e );
170
+
171
+ }
172
+
173
+ }, onProgress, _onError );
174
+
175
+ }
176
+
177
+ setDRACOLoader( dracoLoader ) {
178
+
179
+ this.dracoLoader = dracoLoader;
180
+ return this;
181
+
182
+ }
183
+
184
+ setDDSLoader() {
185
+
186
+ throw new Error(
187
+
188
+ 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".'
189
+
190
+ );
191
+
192
+ }
193
+
194
+ setKTX2Loader( ktx2Loader ) {
195
+
196
+ this.ktx2Loader = ktx2Loader;
197
+ return this;
198
+
199
+ }
200
+
201
+ setMeshoptDecoder( meshoptDecoder ) {
202
+
203
+ this.meshoptDecoder = meshoptDecoder;
204
+ return this;
205
+
206
+ }
207
+
208
+ register( callback ) {
209
+
210
+ if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
211
+
212
+ this.pluginCallbacks.push( callback );
213
+
214
+ }
215
+
216
+ return this;
217
+
218
+ }
219
+
220
+ unregister( callback ) {
221
+
222
+ if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
223
+
224
+ this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
225
+
226
+ }
227
+
228
+ return this;
229
+
230
+ }
231
+
232
+ parse( data, path, onLoad, onError ) {
233
+
234
+ let json;
235
+ const extensions = {};
236
+ const plugins = {};
237
+ const textDecoder = new TextDecoder();
238
+
239
+ if ( typeof data === 'string' ) {
240
+
241
+ json = JSON.parse( data );
242
+
243
+ } else if ( data instanceof ArrayBuffer ) {
244
+
245
+ const magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) );
246
+
247
+ if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
248
+
249
+ try {
250
+
251
+ extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
252
+
253
+ } catch ( error ) {
254
+
255
+ if ( onError ) onError( error );
256
+ return;
257
+
258
+ }
259
+
260
+ json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );
261
+
262
+ } else {
263
+
264
+ json = JSON.parse( textDecoder.decode( data ) );
265
+
266
+ }
267
+
268
+ } else {
269
+
270
+ json = data;
271
+
272
+ }
273
+
274
+ if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
275
+
276
+ if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
277
+ return;
278
+
279
+ }
280
+
281
+ const parser = new GLTFParser( json, {
282
+
283
+ path: path || this.resourcePath || '',
284
+ crossOrigin: this.crossOrigin,
285
+ requestHeader: this.requestHeader,
286
+ manager: this.manager,
287
+ ktx2Loader: this.ktx2Loader,
288
+ meshoptDecoder: this.meshoptDecoder
289
+
290
+ } );
291
+
292
+ parser.fileLoader.setRequestHeader( this.requestHeader );
293
+
294
+ for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
295
+
296
+ const plugin = this.pluginCallbacks[ i ]( parser );
297
+ plugins[ plugin.name ] = plugin;
298
+
299
+ // Workaround to avoid determining as unknown extension
300
+ // in addUnknownExtensionsToUserData().
301
+ // Remove this workaround if we move all the existing
302
+ // extension handlers to plugin system
303
+ extensions[ plugin.name ] = true;
304
+
305
+ }
306
+
307
+ if ( json.extensionsUsed ) {
308
+
309
+ for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
310
+
311
+ const extensionName = json.extensionsUsed[ i ];
312
+ const extensionsRequired = json.extensionsRequired || [];
313
+
314
+ switch ( extensionName ) {
315
+
316
+ case EXTENSIONS.KHR_MATERIALS_UNLIT:
317
+ extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
318
+ break;
319
+
320
+ case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
321
+ extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
322
+ break;
323
+
324
+ case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
325
+ extensions[ extensionName ] = new GLTFTextureTransformExtension();
326
+ break;
327
+
328
+ case EXTENSIONS.KHR_MESH_QUANTIZATION:
329
+ extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
330
+ break;
331
+
332
+ default:
333
+
334
+ if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
335
+
336
+ console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
337
+
338
+ }
339
+
340
+ }
341
+
342
+ }
343
+
344
+ }
345
+
346
+ parser.setExtensions( extensions );
347
+ parser.setPlugins( plugins );
348
+ parser.parse( onLoad, onError );
349
+
350
+ }
351
+
352
+ parseAsync( data, path ) {
353
+
354
+ const scope = this;
355
+
356
+ return new Promise( function ( resolve, reject ) {
357
+
358
+ scope.parse( data, path, resolve, reject );
359
+
360
+ } );
361
+
362
+ }
363
+
364
+ }
365
+
366
+ /* GLTFREGISTRY */
367
+
368
+ function GLTFRegistry() {
369
+
370
+ let objects = {};
371
+
372
+ return {
373
+
374
+ get: function ( key ) {
375
+
376
+ return objects[ key ];
377
+
378
+ },
379
+
380
+ add: function ( key, object ) {
381
+
382
+ objects[ key ] = object;
383
+
384
+ },
385
+
386
+ remove: function ( key ) {
387
+
388
+ delete objects[ key ];
389
+
390
+ },
391
+
392
+ removeAll: function () {
393
+
394
+ objects = {};
395
+
396
+ }
397
+
398
+ };
399
+
400
+ }
401
+
402
+ /*********************************/
403
+ /********** EXTENSIONS ***********/
404
+ /*********************************/
405
+
406
+ const EXTENSIONS = {
407
+ KHR_BINARY_GLTF: 'KHR_binary_glTF',
408
+ KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
409
+ KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
410
+ KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
411
+ KHR_MATERIALS_IOR: 'KHR_materials_ior',
412
+ KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
413
+ KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
414
+ KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
415
+ KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
416
+ KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
417
+ KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
418
+ KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
419
+ KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
420
+ KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
421
+ KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
422
+ EXT_TEXTURE_WEBP: 'EXT_texture_webp',
423
+ EXT_TEXTURE_AVIF: 'EXT_texture_avif',
424
+ EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
425
+ EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
426
+ };
427
+
428
+ /**
429
+ * Punctual Lights Extension
430
+ *
431
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
432
+ */
433
+ class GLTFLightsExtension {
434
+
435
+ constructor( parser ) {
436
+
437
+ this.parser = parser;
438
+ this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
439
+
440
+ // Object3D instance caches
441
+ this.cache = { refs: {}, uses: {} };
442
+
443
+ }
444
+
445
+ _markDefs() {
446
+
447
+ const parser = this.parser;
448
+ const nodeDefs = this.parser.json.nodes || [];
449
+
450
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
451
+
452
+ const nodeDef = nodeDefs[ nodeIndex ];
453
+
454
+ if ( nodeDef.extensions
455
+ && nodeDef.extensions[ this.name ]
456
+ && nodeDef.extensions[ this.name ].light !== undefined ) {
457
+
458
+ parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
459
+
460
+ }
461
+
462
+ }
463
+
464
+ }
465
+
466
+ _loadLight( lightIndex ) {
467
+
468
+ const parser = this.parser;
469
+ const cacheKey = 'light:' + lightIndex;
470
+ let dependency = parser.cache.get( cacheKey );
471
+
472
+ if ( dependency ) return dependency;
473
+
474
+ const json = parser.json;
475
+ const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
476
+ const lightDefs = extensions.lights || [];
477
+ const lightDef = lightDefs[ lightIndex ];
478
+ let lightNode;
479
+
480
+ const color = new THREE.Color( 0xffffff );
481
+
482
+ if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
483
+
484
+ const range = lightDef.range !== undefined ? lightDef.range : 0;
485
+
486
+ switch ( lightDef.type ) {
487
+
488
+ case 'directional':
489
+ lightNode = new THREE.DirectionalLight( color );
490
+ lightNode.target.position.set( 0, 0, - 1 );
491
+ lightNode.add( lightNode.target );
492
+ break;
493
+
494
+ case 'point':
495
+ lightNode = new THREE.PointLight( color );
496
+ lightNode.distance = range;
497
+ break;
498
+
499
+ case 'spot':
500
+ lightNode = new THREE.SpotLight( color );
501
+ lightNode.distance = range;
502
+ // Handle spotlight properties.
503
+ lightDef.spot = lightDef.spot || {};
504
+ lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
505
+ lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
506
+ lightNode.angle = lightDef.spot.outerConeAngle;
507
+ lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
508
+ lightNode.target.position.set( 0, 0, - 1 );
509
+ lightNode.add( lightNode.target );
510
+ break;
511
+
512
+ default:
513
+ throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
514
+
515
+ }
516
+
517
+ // Some lights (e.g. spot) default to a position other than the origin. Reset the position
518
+ // here, because node-level parsing will only override position if explicitly specified.
519
+ lightNode.position.set( 0, 0, 0 );
520
+
521
+ lightNode.decay = 2;
522
+
523
+ assignExtrasToUserData( lightNode, lightDef );
524
+
525
+ if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
526
+
527
+ lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
528
+
529
+ dependency = Promise.resolve( lightNode );
530
+
531
+ parser.cache.add( cacheKey, dependency );
532
+
533
+ return dependency;
534
+
535
+ }
536
+
537
+ getDependency( type, index ) {
538
+
539
+ if ( type !== 'light' ) return;
540
+
541
+ return this._loadLight( index );
542
+
543
+ }
544
+
545
+ createNodeAttachment( nodeIndex ) {
546
+
547
+ const self = this;
548
+ const parser = this.parser;
549
+ const json = parser.json;
550
+ const nodeDef = json.nodes[ nodeIndex ];
551
+ const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
552
+ const lightIndex = lightDef.light;
553
+
554
+ if ( lightIndex === undefined ) return null;
555
+
556
+ return this._loadLight( lightIndex ).then( function ( light ) {
557
+
558
+ return parser._getNodeRef( self.cache, lightIndex, light );
559
+
560
+ } );
561
+
562
+ }
563
+
564
+ }
565
+
566
+ /**
567
+ * Unlit Materials Extension
568
+ *
569
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
570
+ */
571
+ class GLTFMaterialsUnlitExtension {
572
+
573
+ constructor() {
574
+
575
+ this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
576
+
577
+ }
578
+
579
+ getMaterialType() {
580
+
581
+ return THREE.MeshBasicMaterial;
582
+
583
+ }
584
+
585
+ extendParams( materialParams, materialDef, parser ) {
586
+
587
+ const pending = [];
588
+
589
+ materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
590
+ materialParams.opacity = 1.0;
591
+
592
+ const metallicRoughness = materialDef.pbrMetallicRoughness;
593
+
594
+ if ( metallicRoughness ) {
595
+
596
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
597
+
598
+ const array = metallicRoughness.baseColorFactor;
599
+
600
+ materialParams.color.fromArray( array );
601
+ materialParams.opacity = array[ 3 ];
602
+
603
+ }
604
+
605
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
606
+
607
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, THREE.sRGBEncoding ) );
608
+
609
+ }
610
+
611
+ }
612
+
613
+ return Promise.all( pending );
614
+
615
+ }
616
+
617
+ }
618
+
619
+ /**
620
+ * Materials Emissive Strength Extension
621
+ *
622
+ * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
623
+ */
624
+ class GLTFMaterialsEmissiveStrengthExtension {
625
+
626
+ constructor( parser ) {
627
+
628
+ this.parser = parser;
629
+ this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
630
+
631
+ }
632
+
633
+ extendMaterialParams( materialIndex, materialParams ) {
634
+
635
+ const parser = this.parser;
636
+ const materialDef = parser.json.materials[ materialIndex ];
637
+
638
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
639
+
640
+ return Promise.resolve();
641
+
642
+ }
643
+
644
+ const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength;
645
+
646
+ if ( emissiveStrength !== undefined ) {
647
+
648
+ materialParams.emissiveIntensity = emissiveStrength;
649
+
650
+ }
651
+
652
+ return Promise.resolve();
653
+
654
+ }
655
+
656
+ }
657
+
658
+ /**
659
+ * Clearcoat Materials Extension
660
+ *
661
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
662
+ */
663
+ class GLTFMaterialsClearcoatExtension {
664
+
665
+ constructor( parser ) {
666
+
667
+ this.parser = parser;
668
+ this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
669
+
670
+ }
671
+
672
+ getMaterialType( materialIndex ) {
673
+
674
+ const parser = this.parser;
675
+ const materialDef = parser.json.materials[ materialIndex ];
676
+
677
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
678
+
679
+ return THREE.MeshPhysicalMaterial;
680
+
681
+ }
682
+
683
+ extendMaterialParams( materialIndex, materialParams ) {
684
+
685
+ const parser = this.parser;
686
+ const materialDef = parser.json.materials[ materialIndex ];
687
+
688
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
689
+
690
+ return Promise.resolve();
691
+
692
+ }
693
+
694
+ const pending = [];
695
+
696
+ const extension = materialDef.extensions[ this.name ];
697
+
698
+ if ( extension.clearcoatFactor !== undefined ) {
699
+
700
+ materialParams.clearcoat = extension.clearcoatFactor;
701
+
702
+ }
703
+
704
+ if ( extension.clearcoatTexture !== undefined ) {
705
+
706
+ pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
707
+
708
+ }
709
+
710
+ if ( extension.clearcoatRoughnessFactor !== undefined ) {
711
+
712
+ materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
713
+
714
+ }
715
+
716
+ if ( extension.clearcoatRoughnessTexture !== undefined ) {
717
+
718
+ pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
719
+
720
+ }
721
+
722
+ if ( extension.clearcoatNormalTexture !== undefined ) {
723
+
724
+ pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
725
+
726
+ if ( extension.clearcoatNormalTexture.scale !== undefined ) {
727
+
728
+ const scale = extension.clearcoatNormalTexture.scale;
729
+
730
+ materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
731
+
732
+ }
733
+
734
+ }
735
+
736
+ return Promise.all( pending );
737
+
738
+ }
739
+
740
+ }
741
+
742
+ /**
743
+ * Iridescence Materials Extension
744
+ *
745
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
746
+ */
747
+ class GLTFMaterialsIridescenceExtension {
748
+
749
+ constructor( parser ) {
750
+
751
+ this.parser = parser;
752
+ this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
753
+
754
+ }
755
+
756
+ getMaterialType( materialIndex ) {
757
+
758
+ const parser = this.parser;
759
+ const materialDef = parser.json.materials[ materialIndex ];
760
+
761
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
762
+
763
+ return THREE.MeshPhysicalMaterial;
764
+
765
+ }
766
+
767
+ extendMaterialParams( materialIndex, materialParams ) {
768
+
769
+ const parser = this.parser;
770
+ const materialDef = parser.json.materials[ materialIndex ];
771
+
772
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
773
+
774
+ return Promise.resolve();
775
+
776
+ }
777
+
778
+ const pending = [];
779
+
780
+ const extension = materialDef.extensions[ this.name ];
781
+
782
+ if ( extension.iridescenceFactor !== undefined ) {
783
+
784
+ materialParams.iridescence = extension.iridescenceFactor;
785
+
786
+ }
787
+
788
+ if ( extension.iridescenceTexture !== undefined ) {
789
+
790
+ pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );
791
+
792
+ }
793
+
794
+ if ( extension.iridescenceIor !== undefined ) {
795
+
796
+ materialParams.iridescenceIOR = extension.iridescenceIor;
797
+
798
+ }
799
+
800
+ if ( materialParams.iridescenceThicknessRange === undefined ) {
801
+
802
+ materialParams.iridescenceThicknessRange = [ 100, 400 ];
803
+
804
+ }
805
+
806
+ if ( extension.iridescenceThicknessMinimum !== undefined ) {
807
+
808
+ materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum;
809
+
810
+ }
811
+
812
+ if ( extension.iridescenceThicknessMaximum !== undefined ) {
813
+
814
+ materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum;
815
+
816
+ }
817
+
818
+ if ( extension.iridescenceThicknessTexture !== undefined ) {
819
+
820
+ pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );
821
+
822
+ }
823
+
824
+ return Promise.all( pending );
825
+
826
+ }
827
+
828
+ }
829
+
830
+ /**
831
+ * Sheen Materials Extension
832
+ *
833
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
834
+ */
835
+ class GLTFMaterialsSheenExtension {
836
+
837
+ constructor( parser ) {
838
+
839
+ this.parser = parser;
840
+ this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
841
+
842
+ }
843
+
844
+ getMaterialType( materialIndex ) {
845
+
846
+ const parser = this.parser;
847
+ const materialDef = parser.json.materials[ materialIndex ];
848
+
849
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
850
+
851
+ return THREE.MeshPhysicalMaterial;
852
+
853
+ }
854
+
855
+ extendMaterialParams( materialIndex, materialParams ) {
856
+
857
+ const parser = this.parser;
858
+ const materialDef = parser.json.materials[ materialIndex ];
859
+
860
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
861
+
862
+ return Promise.resolve();
863
+
864
+ }
865
+
866
+ const pending = [];
867
+
868
+ materialParams.sheenColor = new THREE.Color( 0, 0, 0 );
869
+ materialParams.sheenRoughness = 0;
870
+ materialParams.sheen = 1;
871
+
872
+ const extension = materialDef.extensions[ this.name ];
873
+
874
+ if ( extension.sheenColorFactor !== undefined ) {
875
+
876
+ materialParams.sheenColor.fromArray( extension.sheenColorFactor );
877
+
878
+ }
879
+
880
+ if ( extension.sheenRoughnessFactor !== undefined ) {
881
+
882
+ materialParams.sheenRoughness = extension.sheenRoughnessFactor;
883
+
884
+ }
885
+
886
+ if ( extension.sheenColorTexture !== undefined ) {
887
+
888
+ pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, THREE.sRGBEncoding ) );
889
+
890
+ }
891
+
892
+ if ( extension.sheenRoughnessTexture !== undefined ) {
893
+
894
+ pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );
895
+
896
+ }
897
+
898
+ return Promise.all( pending );
899
+
900
+ }
901
+
902
+ }
903
+
904
+ /**
905
+ * Transmission Materials Extension
906
+ *
907
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
908
+ * Draft: https://github.com/KhronosGroup/glTF/pull/1698
909
+ */
910
+ class GLTFMaterialsTransmissionExtension {
911
+
912
+ constructor( parser ) {
913
+
914
+ this.parser = parser;
915
+ this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
916
+
917
+ }
918
+
919
+ getMaterialType( materialIndex ) {
920
+
921
+ const parser = this.parser;
922
+ const materialDef = parser.json.materials[ materialIndex ];
923
+
924
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
925
+
926
+ return THREE.MeshPhysicalMaterial;
927
+
928
+ }
929
+
930
+ extendMaterialParams( materialIndex, materialParams ) {
931
+
932
+ const parser = this.parser;
933
+ const materialDef = parser.json.materials[ materialIndex ];
934
+
935
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
936
+
937
+ return Promise.resolve();
938
+
939
+ }
940
+
941
+ const pending = [];
942
+
943
+ const extension = materialDef.extensions[ this.name ];
944
+
945
+ if ( extension.transmissionFactor !== undefined ) {
946
+
947
+ materialParams.transmission = extension.transmissionFactor;
948
+
949
+ }
950
+
951
+ if ( extension.transmissionTexture !== undefined ) {
952
+
953
+ pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
954
+
955
+ }
956
+
957
+ return Promise.all( pending );
958
+
959
+ }
960
+
961
+ }
962
+
963
+ /**
964
+ * Materials Volume Extension
965
+ *
966
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
967
+ */
968
+ class GLTFMaterialsVolumeExtension {
969
+
970
+ constructor( parser ) {
971
+
972
+ this.parser = parser;
973
+ this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
974
+
975
+ }
976
+
977
+ getMaterialType( materialIndex ) {
978
+
979
+ const parser = this.parser;
980
+ const materialDef = parser.json.materials[ materialIndex ];
981
+
982
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
983
+
984
+ return THREE.MeshPhysicalMaterial;
985
+
986
+ }
987
+
988
+ extendMaterialParams( materialIndex, materialParams ) {
989
+
990
+ const parser = this.parser;
991
+ const materialDef = parser.json.materials[ materialIndex ];
992
+
993
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
994
+
995
+ return Promise.resolve();
996
+
997
+ }
998
+
999
+ const pending = [];
1000
+
1001
+ const extension = materialDef.extensions[ this.name ];
1002
+
1003
+ materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
1004
+
1005
+ if ( extension.thicknessTexture !== undefined ) {
1006
+
1007
+ pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
1008
+
1009
+ }
1010
+
1011
+ materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
1012
+
1013
+ const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
1014
+ materialParams.attenuationColor = new THREE.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
1015
+
1016
+ return Promise.all( pending );
1017
+
1018
+ }
1019
+
1020
+ }
1021
+
1022
+ /**
1023
+ * Materials ior Extension
1024
+ *
1025
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
1026
+ */
1027
+ class GLTFMaterialsIorExtension {
1028
+
1029
+ constructor( parser ) {
1030
+
1031
+ this.parser = parser;
1032
+ this.name = EXTENSIONS.KHR_MATERIALS_IOR;
1033
+
1034
+ }
1035
+
1036
+ getMaterialType( materialIndex ) {
1037
+
1038
+ const parser = this.parser;
1039
+ const materialDef = parser.json.materials[ materialIndex ];
1040
+
1041
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1042
+
1043
+ return THREE.MeshPhysicalMaterial;
1044
+
1045
+ }
1046
+
1047
+ extendMaterialParams( materialIndex, materialParams ) {
1048
+
1049
+ const parser = this.parser;
1050
+ const materialDef = parser.json.materials[ materialIndex ];
1051
+
1052
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1053
+
1054
+ return Promise.resolve();
1055
+
1056
+ }
1057
+
1058
+ const extension = materialDef.extensions[ this.name ];
1059
+
1060
+ materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
1061
+
1062
+ return Promise.resolve();
1063
+
1064
+ }
1065
+
1066
+ }
1067
+
1068
+ /**
1069
+ * Materials specular Extension
1070
+ *
1071
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
1072
+ */
1073
+ class GLTFMaterialsSpecularExtension {
1074
+
1075
+ constructor( parser ) {
1076
+
1077
+ this.parser = parser;
1078
+ this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
1079
+
1080
+ }
1081
+
1082
+ getMaterialType( materialIndex ) {
1083
+
1084
+ const parser = this.parser;
1085
+ const materialDef = parser.json.materials[ materialIndex ];
1086
+
1087
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1088
+
1089
+ return THREE.MeshPhysicalMaterial;
1090
+
1091
+ }
1092
+
1093
+ extendMaterialParams( materialIndex, materialParams ) {
1094
+
1095
+ const parser = this.parser;
1096
+ const materialDef = parser.json.materials[ materialIndex ];
1097
+
1098
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1099
+
1100
+ return Promise.resolve();
1101
+
1102
+ }
1103
+
1104
+ const pending = [];
1105
+
1106
+ const extension = materialDef.extensions[ this.name ];
1107
+
1108
+ materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
1109
+
1110
+ if ( extension.specularTexture !== undefined ) {
1111
+
1112
+ pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
1113
+
1114
+ }
1115
+
1116
+ const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
1117
+ materialParams.specularColor = new THREE.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
1118
+
1119
+ if ( extension.specularColorTexture !== undefined ) {
1120
+
1121
+ pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, THREE.sRGBEncoding ) );
1122
+
1123
+ }
1124
+
1125
+ return Promise.all( pending );
1126
+
1127
+ }
1128
+
1129
+ }
1130
+
1131
+ /**
1132
+ * BasisU Texture Extension
1133
+ *
1134
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
1135
+ */
1136
+ class GLTFTextureBasisUExtension {
1137
+
1138
+ constructor( parser ) {
1139
+
1140
+ this.parser = parser;
1141
+ this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
1142
+
1143
+ }
1144
+
1145
+ loadTexture( textureIndex ) {
1146
+
1147
+ const parser = this.parser;
1148
+ const json = parser.json;
1149
+
1150
+ const textureDef = json.textures[ textureIndex ];
1151
+
1152
+ if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
1153
+
1154
+ return null;
1155
+
1156
+ }
1157
+
1158
+ const extension = textureDef.extensions[ this.name ];
1159
+ const loader = parser.options.ktx2Loader;
1160
+
1161
+ if ( ! loader ) {
1162
+
1163
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
1164
+
1165
+ throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
1166
+
1167
+ } else {
1168
+
1169
+ // Assumes that the extension is optional and that a fallback texture is present
1170
+ return null;
1171
+
1172
+ }
1173
+
1174
+ }
1175
+
1176
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
1177
+
1178
+ }
1179
+
1180
+ }
1181
+
1182
+ /**
1183
+ * WebP Texture Extension
1184
+ *
1185
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
1186
+ */
1187
+ class GLTFTextureWebPExtension {
1188
+
1189
+ constructor( parser ) {
1190
+
1191
+ this.parser = parser;
1192
+ this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
1193
+ this.isSupported = null;
1194
+
1195
+ }
1196
+
1197
+ loadTexture( textureIndex ) {
1198
+
1199
+ const name = this.name;
1200
+ const parser = this.parser;
1201
+ const json = parser.json;
1202
+
1203
+ const textureDef = json.textures[ textureIndex ];
1204
+
1205
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
1206
+
1207
+ return null;
1208
+
1209
+ }
1210
+
1211
+ const extension = textureDef.extensions[ name ];
1212
+ const source = json.images[ extension.source ];
1213
+
1214
+ let loader = parser.textureLoader;
1215
+ if ( source.uri ) {
1216
+
1217
+ const handler = parser.options.manager.getHandler( source.uri );
1218
+ if ( handler !== null ) loader = handler;
1219
+
1220
+ }
1221
+
1222
+ return this.detectSupport().then( function ( isSupported ) {
1223
+
1224
+ if ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader );
1225
+
1226
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
1227
+
1228
+ throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
1229
+
1230
+ }
1231
+
1232
+ // Fall back to PNG or JPEG.
1233
+ return parser.loadTexture( textureIndex );
1234
+
1235
+ } );
1236
+
1237
+ }
1238
+
1239
+ detectSupport() {
1240
+
1241
+ if ( ! this.isSupported ) {
1242
+
1243
+ this.isSupported = new Promise( function ( resolve ) {
1244
+
1245
+ const image = new Image();
1246
+
1247
+ // Lossy test image. Support for lossy images doesn't guarantee support for all
1248
+ // WebP images, unfortunately.
1249
+ image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
1250
+
1251
+ image.onload = image.onerror = function () {
1252
+
1253
+ resolve( image.height === 1 );
1254
+
1255
+ };
1256
+
1257
+ } );
1258
+
1259
+ }
1260
+
1261
+ return this.isSupported;
1262
+
1263
+ }
1264
+
1265
+ }
1266
+
1267
+ /**
1268
+ * AVIF Texture Extension
1269
+ *
1270
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif
1271
+ */
1272
+ class GLTFTextureAVIFExtension {
1273
+
1274
+ constructor( parser ) {
1275
+
1276
+ this.parser = parser;
1277
+ this.name = EXTENSIONS.EXT_TEXTURE_AVIF;
1278
+ this.isSupported = null;
1279
+
1280
+ }
1281
+
1282
+ loadTexture( textureIndex ) {
1283
+
1284
+ const name = this.name;
1285
+ const parser = this.parser;
1286
+ const json = parser.json;
1287
+
1288
+ const textureDef = json.textures[ textureIndex ];
1289
+
1290
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
1291
+
1292
+ return null;
1293
+
1294
+ }
1295
+
1296
+ const extension = textureDef.extensions[ name ];
1297
+ const source = json.images[ extension.source ];
1298
+
1299
+ let loader = parser.textureLoader;
1300
+ if ( source.uri ) {
1301
+
1302
+ const handler = parser.options.manager.getHandler( source.uri );
1303
+ if ( handler !== null ) loader = handler;
1304
+
1305
+ }
1306
+
1307
+ return this.detectSupport().then( function ( isSupported ) {
1308
+
1309
+ if ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader );
1310
+
1311
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
1312
+
1313
+ throw new Error( 'THREE.GLTFLoader: AVIF required by asset but unsupported.' );
1314
+
1315
+ }
1316
+
1317
+ // Fall back to PNG or JPEG.
1318
+ return parser.loadTexture( textureIndex );
1319
+
1320
+ } );
1321
+
1322
+ }
1323
+
1324
+ detectSupport() {
1325
+
1326
+ if ( ! this.isSupported ) {
1327
+
1328
+ this.isSupported = new Promise( function ( resolve ) {
1329
+
1330
+ const image = new Image();
1331
+
1332
+ // Lossy test image.
1333
+ image.src = 'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=';
1334
+ image.onload = image.onerror = function () {
1335
+
1336
+ resolve( image.height === 1 );
1337
+
1338
+ };
1339
+
1340
+ } );
1341
+
1342
+ }
1343
+
1344
+ return this.isSupported;
1345
+
1346
+ }
1347
+
1348
+ }
1349
+
1350
+ /**
1351
+ * meshopt BufferView Compression Extension
1352
+ *
1353
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
1354
+ */
1355
+ class GLTFMeshoptCompression {
1356
+
1357
+ constructor( parser ) {
1358
+
1359
+ this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
1360
+ this.parser = parser;
1361
+
1362
+ }
1363
+
1364
+ loadBufferView( index ) {
1365
+
1366
+ const json = this.parser.json;
1367
+ const bufferView = json.bufferViews[ index ];
1368
+
1369
+ if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
1370
+
1371
+ const extensionDef = bufferView.extensions[ this.name ];
1372
+
1373
+ const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
1374
+ const decoder = this.parser.options.meshoptDecoder;
1375
+
1376
+ if ( ! decoder || ! decoder.supported ) {
1377
+
1378
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
1379
+
1380
+ throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
1381
+
1382
+ } else {
1383
+
1384
+ // Assumes that the extension is optional and that fallback buffer data is present
1385
+ return null;
1386
+
1387
+ }
1388
+
1389
+ }
1390
+
1391
+ return buffer.then( function ( res ) {
1392
+
1393
+ const byteOffset = extensionDef.byteOffset || 0;
1394
+ const byteLength = extensionDef.byteLength || 0;
1395
+
1396
+ const count = extensionDef.count;
1397
+ const stride = extensionDef.byteStride;
1398
+
1399
+ const source = new Uint8Array( res, byteOffset, byteLength );
1400
+
1401
+ if ( decoder.decodeGltfBufferAsync ) {
1402
+
1403
+ return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {
1404
+
1405
+ return res.buffer;
1406
+
1407
+ } );
1408
+
1409
+ } else {
1410
+
1411
+ // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
1412
+ return decoder.ready.then( function () {
1413
+
1414
+ const result = new ArrayBuffer( count * stride );
1415
+ decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
1416
+ return result;
1417
+
1418
+ } );
1419
+
1420
+ }
1421
+
1422
+ } );
1423
+
1424
+ } else {
1425
+
1426
+ return null;
1427
+
1428
+ }
1429
+
1430
+ }
1431
+
1432
+ }
1433
+
1434
+ /**
1435
+ * GPU Instancing Extension
1436
+ *
1437
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
1438
+ *
1439
+ */
1440
+ class GLTFMeshGpuInstancing {
1441
+
1442
+ constructor( parser ) {
1443
+
1444
+ this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
1445
+ this.parser = parser;
1446
+
1447
+ }
1448
+
1449
+ createNodeMesh( nodeIndex ) {
1450
+
1451
+ const json = this.parser.json;
1452
+ const nodeDef = json.nodes[ nodeIndex ];
1453
+
1454
+ if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||
1455
+ nodeDef.mesh === undefined ) {
1456
+
1457
+ return null;
1458
+
1459
+ }
1460
+
1461
+ const meshDef = json.meshes[ nodeDef.mesh ];
1462
+
1463
+ // No Points or Lines + Instancing support yet
1464
+
1465
+ for ( const primitive of meshDef.primitives ) {
1466
+
1467
+ if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&
1468
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&
1469
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&
1470
+ primitive.mode !== undefined ) {
1471
+
1472
+ return null;
1473
+
1474
+ }
1475
+
1476
+ }
1477
+
1478
+ const extensionDef = nodeDef.extensions[ this.name ];
1479
+ const attributesDef = extensionDef.attributes;
1480
+
1481
+ // @TODO: Can we support InstancedMesh + SkinnedMesh?
1482
+
1483
+ const pending = [];
1484
+ const attributes = {};
1485
+
1486
+ for ( const key in attributesDef ) {
1487
+
1488
+ pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {
1489
+
1490
+ attributes[ key ] = accessor;
1491
+ return attributes[ key ];
1492
+
1493
+ } ) );
1494
+
1495
+ }
1496
+
1497
+ if ( pending.length < 1 ) {
1498
+
1499
+ return null;
1500
+
1501
+ }
1502
+
1503
+ pending.push( this.parser.createNodeMesh( nodeIndex ) );
1504
+
1505
+ return Promise.all( pending ).then( results => {
1506
+
1507
+ const nodeObject = results.pop();
1508
+ const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];
1509
+ const count = results[ 0 ].count; // All attribute counts should be same
1510
+ const instancedMeshes = [];
1511
+
1512
+ for ( const mesh of meshes ) {
1513
+
1514
+ // Temporal variables
1515
+ const m = new THREE.Matrix4();
1516
+ const p = new THREE.Vector3();
1517
+ const q = new THREE.Quaternion();
1518
+ const s = new THREE.Vector3( 1, 1, 1 );
1519
+
1520
+ const instancedMesh = new THREE.InstancedMesh( mesh.geometry, mesh.material, count );
1521
+
1522
+ for ( let i = 0; i < count; i ++ ) {
1523
+
1524
+ if ( attributes.TRANSLATION ) {
1525
+
1526
+ p.fromBufferAttribute( attributes.TRANSLATION, i );
1527
+
1528
+ }
1529
+
1530
+ if ( attributes.ROTATION ) {
1531
+
1532
+ q.fromBufferAttribute( attributes.ROTATION, i );
1533
+
1534
+ }
1535
+
1536
+ if ( attributes.SCALE ) {
1537
+
1538
+ s.fromBufferAttribute( attributes.SCALE, i );
1539
+
1540
+ }
1541
+
1542
+ instancedMesh.setMatrixAt( i, m.compose( p, q, s ) );
1543
+
1544
+ }
1545
+
1546
+ // Add instance attributes to the geometry, excluding TRS.
1547
+ for ( const attributeName in attributes ) {
1548
+
1549
+ if ( attributeName !== 'TRANSLATION' &&
1550
+ attributeName !== 'ROTATION' &&
1551
+ attributeName !== 'SCALE' ) {
1552
+
1553
+ mesh.geometry.setAttribute( attributeName, attributes[ attributeName ] );
1554
+
1555
+ }
1556
+
1557
+ }
1558
+
1559
+ // Just in case
1560
+ THREE.Object3D.prototype.copy.call( instancedMesh, mesh );
1561
+
1562
+ // https://github.com/mrdoob/three.js/issues/18334
1563
+ instancedMesh.frustumCulled = false;
1564
+ this.parser.assignFinalMaterial( instancedMesh );
1565
+
1566
+ instancedMeshes.push( instancedMesh );
1567
+
1568
+ }
1569
+
1570
+ if ( nodeObject.isGroup ) {
1571
+
1572
+ nodeObject.clear();
1573
+
1574
+ nodeObject.add( ... instancedMeshes );
1575
+
1576
+ return nodeObject;
1577
+
1578
+ }
1579
+
1580
+ return instancedMeshes[ 0 ];
1581
+
1582
+ } );
1583
+
1584
+ }
1585
+
1586
+ }
1587
+
1588
+ /* BINARY EXTENSION */
1589
+ const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
1590
+ const BINARY_EXTENSION_HEADER_LENGTH = 12;
1591
+ const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
1592
+
1593
+ class GLTFBinaryExtension {
1594
+
1595
+ constructor( data ) {
1596
+
1597
+ this.name = EXTENSIONS.KHR_BINARY_GLTF;
1598
+ this.content = null;
1599
+ this.body = null;
1600
+
1601
+ const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
1602
+ const textDecoder = new TextDecoder();
1603
+
1604
+ this.header = {
1605
+ magic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ),
1606
+ version: headerView.getUint32( 4, true ),
1607
+ length: headerView.getUint32( 8, true )
1608
+ };
1609
+
1610
+ if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
1611
+
1612
+ throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
1613
+
1614
+ } else if ( this.header.version < 2.0 ) {
1615
+
1616
+ throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
1617
+
1618
+ }
1619
+
1620
+ const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
1621
+ const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
1622
+ let chunkIndex = 0;
1623
+
1624
+ while ( chunkIndex < chunkContentsLength ) {
1625
+
1626
+ const chunkLength = chunkView.getUint32( chunkIndex, true );
1627
+ chunkIndex += 4;
1628
+
1629
+ const chunkType = chunkView.getUint32( chunkIndex, true );
1630
+ chunkIndex += 4;
1631
+
1632
+ if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
1633
+
1634
+ const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
1635
+ this.content = textDecoder.decode( contentArray );
1636
+
1637
+ } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
1638
+
1639
+ const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
1640
+ this.body = data.slice( byteOffset, byteOffset + chunkLength );
1641
+
1642
+ }
1643
+
1644
+ // Clients must ignore chunks with unknown types.
1645
+
1646
+ chunkIndex += chunkLength;
1647
+
1648
+ }
1649
+
1650
+ if ( this.content === null ) {
1651
+
1652
+ throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
1653
+
1654
+ }
1655
+
1656
+ }
1657
+
1658
+ }
1659
+
1660
+ /**
1661
+ * DRACO Mesh Compression Extension
1662
+ *
1663
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
1664
+ */
1665
+ class GLTFDracoMeshCompressionExtension {
1666
+
1667
+ constructor( json, dracoLoader ) {
1668
+
1669
+ if ( ! dracoLoader ) {
1670
+
1671
+ throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
1672
+
1673
+ }
1674
+
1675
+ this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
1676
+ this.json = json;
1677
+ this.dracoLoader = dracoLoader;
1678
+ this.dracoLoader.preload();
1679
+
1680
+ }
1681
+
1682
+ decodePrimitive( primitive, parser ) {
1683
+
1684
+ const json = this.json;
1685
+ const dracoLoader = this.dracoLoader;
1686
+ const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
1687
+ const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
1688
+ const threeAttributeMap = {};
1689
+ const attributeNormalizedMap = {};
1690
+ const attributeTypeMap = {};
1691
+
1692
+ for ( const attributeName in gltfAttributeMap ) {
1693
+
1694
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
1695
+
1696
+ threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
1697
+
1698
+ }
1699
+
1700
+ for ( const attributeName in primitive.attributes ) {
1701
+
1702
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
1703
+
1704
+ if ( gltfAttributeMap[ attributeName ] !== undefined ) {
1705
+
1706
+ const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
1707
+ const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
1708
+
1709
+ attributeTypeMap[ threeAttributeName ] = componentType.name;
1710
+ attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
1711
+
1712
+ }
1713
+
1714
+ }
1715
+
1716
+ return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
1717
+
1718
+ return new Promise( function ( resolve ) {
1719
+
1720
+ dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
1721
+
1722
+ for ( const attributeName in geometry.attributes ) {
1723
+
1724
+ const attribute = geometry.attributes[ attributeName ];
1725
+ const normalized = attributeNormalizedMap[ attributeName ];
1726
+
1727
+ if ( normalized !== undefined ) attribute.normalized = normalized;
1728
+
1729
+ }
1730
+
1731
+ resolve( geometry );
1732
+
1733
+ }, threeAttributeMap, attributeTypeMap );
1734
+
1735
+ } );
1736
+
1737
+ } );
1738
+
1739
+ }
1740
+
1741
+ }
1742
+
1743
+ /**
1744
+ * Texture Transform Extension
1745
+ *
1746
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
1747
+ */
1748
+ class GLTFTextureTransformExtension {
1749
+
1750
+ constructor() {
1751
+
1752
+ this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
1753
+
1754
+ }
1755
+
1756
+ extendTexture( texture, transform ) {
1757
+
1758
+ if ( transform.texCoord !== undefined ) {
1759
+
1760
+ console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
1761
+
1762
+ }
1763
+
1764
+ if ( transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined ) {
1765
+
1766
+ // See https://github.com/mrdoob/three.js/issues/21819.
1767
+ return texture;
1768
+
1769
+ }
1770
+
1771
+ texture = texture.clone();
1772
+
1773
+ if ( transform.offset !== undefined ) {
1774
+
1775
+ texture.offset.fromArray( transform.offset );
1776
+
1777
+ }
1778
+
1779
+ if ( transform.rotation !== undefined ) {
1780
+
1781
+ texture.rotation = transform.rotation;
1782
+
1783
+ }
1784
+
1785
+ if ( transform.scale !== undefined ) {
1786
+
1787
+ texture.repeat.fromArray( transform.scale );
1788
+
1789
+ }
1790
+
1791
+ texture.needsUpdate = true;
1792
+
1793
+ return texture;
1794
+
1795
+ }
1796
+
1797
+ }
1798
+
1799
+ /**
1800
+ * Mesh Quantization Extension
1801
+ *
1802
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
1803
+ */
1804
+ class GLTFMeshQuantizationExtension {
1805
+
1806
+ constructor() {
1807
+
1808
+ this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
1809
+
1810
+ }
1811
+
1812
+ }
1813
+
1814
+ /*********************************/
1815
+ /********** INTERPOLATION ********/
1816
+ /*********************************/
1817
+
1818
+ // Spline Interpolation
1819
+ // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
1820
+ class GLTFCubicSplineInterpolant extends THREE.Interpolant {
1821
+
1822
+ constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
1823
+
1824
+ super( parameterPositions, sampleValues, sampleSize, resultBuffer );
1825
+
1826
+ }
1827
+
1828
+ copySampleValue_( index ) {
1829
+
1830
+ // Copies a sample value to the result buffer. See description of glTF
1831
+ // CUBICSPLINE values layout in interpolate_() function below.
1832
+
1833
+ const result = this.resultBuffer,
1834
+ values = this.sampleValues,
1835
+ valueSize = this.valueSize,
1836
+ offset = index * valueSize * 3 + valueSize;
1837
+
1838
+ for ( let i = 0; i !== valueSize; i ++ ) {
1839
+
1840
+ result[ i ] = values[ offset + i ];
1841
+
1842
+ }
1843
+
1844
+ return result;
1845
+
1846
+ }
1847
+
1848
+ interpolate_( i1, t0, t, t1 ) {
1849
+
1850
+ const result = this.resultBuffer;
1851
+ const values = this.sampleValues;
1852
+ const stride = this.valueSize;
1853
+
1854
+ const stride2 = stride * 2;
1855
+ const stride3 = stride * 3;
1856
+
1857
+ const td = t1 - t0;
1858
+
1859
+ const p = ( t - t0 ) / td;
1860
+ const pp = p * p;
1861
+ const ppp = pp * p;
1862
+
1863
+ const offset1 = i1 * stride3;
1864
+ const offset0 = offset1 - stride3;
1865
+
1866
+ const s2 = - 2 * ppp + 3 * pp;
1867
+ const s3 = ppp - pp;
1868
+ const s0 = 1 - s2;
1869
+ const s1 = s3 - pp + p;
1870
+
1871
+ // Layout of keyframe output values for CUBICSPLINE animations:
1872
+ // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
1873
+ for ( let i = 0; i !== stride; i ++ ) {
1874
+
1875
+ const p0 = values[ offset0 + i + stride ]; // splineVertex_k
1876
+ const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
1877
+ const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
1878
+ const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
1879
+
1880
+ result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
1881
+
1882
+ }
1883
+
1884
+ return result;
1885
+
1886
+ }
1887
+
1888
+ }
1889
+
1890
+ const _q = new THREE.Quaternion();
1891
+
1892
+ class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
1893
+
1894
+ interpolate_( i1, t0, t, t1 ) {
1895
+
1896
+ const result = super.interpolate_( i1, t0, t, t1 );
1897
+
1898
+ _q.fromArray( result ).normalize().toArray( result );
1899
+
1900
+ return result;
1901
+
1902
+ }
1903
+
1904
+ }
1905
+
1906
+
1907
+ /*********************************/
1908
+ /********** INTERNALS ************/
1909
+ /*********************************/
1910
+
1911
+ /* CONSTANTS */
1912
+
1913
+ const WEBGL_CONSTANTS = {
1914
+ FLOAT: 5126,
1915
+ //FLOAT_MAT2: 35674,
1916
+ FLOAT_MAT3: 35675,
1917
+ FLOAT_MAT4: 35676,
1918
+ FLOAT_VEC2: 35664,
1919
+ FLOAT_VEC3: 35665,
1920
+ FLOAT_VEC4: 35666,
1921
+ LINEAR: 9729,
1922
+ REPEAT: 10497,
1923
+ SAMPLER_2D: 35678,
1924
+ POINTS: 0,
1925
+ LINES: 1,
1926
+ LINE_LOOP: 2,
1927
+ LINE_STRIP: 3,
1928
+ TRIANGLES: 4,
1929
+ TRIANGLE_STRIP: 5,
1930
+ TRIANGLE_FAN: 6,
1931
+ UNSIGNED_BYTE: 5121,
1932
+ UNSIGNED_SHORT: 5123
1933
+ };
1934
+
1935
+ const WEBGL_COMPONENT_TYPES = {
1936
+ 5120: Int8Array,
1937
+ 5121: Uint8Array,
1938
+ 5122: Int16Array,
1939
+ 5123: Uint16Array,
1940
+ 5125: Uint32Array,
1941
+ 5126: Float32Array
1942
+ };
1943
+
1944
+ const WEBGL_FILTERS = {
1945
+ 9728: THREE.NearestFilter,
1946
+ 9729: THREE.LinearFilter,
1947
+ 9984: THREE.NearestMipmapNearestFilter,
1948
+ 9985: THREE.LinearMipmapNearestFilter,
1949
+ 9986: THREE.NearestMipmapLinearFilter,
1950
+ 9987: THREE.LinearMipmapLinearFilter
1951
+ };
1952
+
1953
+ const WEBGL_WRAPPINGS = {
1954
+ 33071: THREE.ClampToEdgeWrapping,
1955
+ 33648: THREE.MirroredRepeatWrapping,
1956
+ 10497: THREE.RepeatWrapping
1957
+ };
1958
+
1959
+ const WEBGL_TYPE_SIZES = {
1960
+ 'SCALAR': 1,
1961
+ 'VEC2': 2,
1962
+ 'VEC3': 3,
1963
+ 'VEC4': 4,
1964
+ 'MAT2': 4,
1965
+ 'MAT3': 9,
1966
+ 'MAT4': 16
1967
+ };
1968
+
1969
+ const ATTRIBUTES = {
1970
+ POSITION: 'position',
1971
+ NORMAL: 'normal',
1972
+ TANGENT: 'tangent',
1973
+ TEXCOORD_0: 'uv',
1974
+ TEXCOORD_1: 'uv2',
1975
+ COLOR_0: 'color',
1976
+ WEIGHTS_0: 'skinWeight',
1977
+ JOINTS_0: 'skinIndex',
1978
+ };
1979
+
1980
+ const PATH_PROPERTIES = {
1981
+ scale: 'scale',
1982
+ translation: 'position',
1983
+ rotation: 'quaternion',
1984
+ weights: 'morphTargetInfluences'
1985
+ };
1986
+
1987
+ const INTERPOLATION = {
1988
+ CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
1989
+ // keyframe track will be initialized with a default interpolation type, then modified.
1990
+ LINEAR: THREE.InterpolateLinear,
1991
+ STEP: THREE.InterpolateDiscrete
1992
+ };
1993
+
1994
+ const ALPHA_MODES = {
1995
+ OPAQUE: 'OPAQUE',
1996
+ MASK: 'MASK',
1997
+ BLEND: 'BLEND'
1998
+ };
1999
+
2000
+ /**
2001
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
2002
+ */
2003
+ function createDefaultMaterial( cache ) {
2004
+
2005
+ if ( cache[ 'DefaultMaterial' ] === undefined ) {
2006
+
2007
+ cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
2008
+ color: 0xFFFFFF,
2009
+ emissive: 0x000000,
2010
+ metalness: 1,
2011
+ roughness: 1,
2012
+ transparent: false,
2013
+ depthTest: true,
2014
+ side: THREE.FrontSide
2015
+ } );
2016
+
2017
+ }
2018
+
2019
+ return cache[ 'DefaultMaterial' ];
2020
+
2021
+ }
2022
+
2023
+ function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
2024
+
2025
+ // Add unknown glTF extensions to an object's userData.
2026
+
2027
+ for ( const name in objectDef.extensions ) {
2028
+
2029
+ if ( knownExtensions[ name ] === undefined ) {
2030
+
2031
+ object.userData.gltfExtensions = object.userData.gltfExtensions || {};
2032
+ object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
2033
+
2034
+ }
2035
+
2036
+ }
2037
+
2038
+ }
2039
+
2040
+ /**
2041
+ * @param {Object3D|Material|BufferGeometry} object
2042
+ * @param {GLTF.definition} gltfDef
2043
+ */
2044
+ function assignExtrasToUserData( object, gltfDef ) {
2045
+
2046
+ if ( gltfDef.extras !== undefined ) {
2047
+
2048
+ if ( typeof gltfDef.extras === 'object' ) {
2049
+
2050
+ Object.assign( object.userData, gltfDef.extras );
2051
+
2052
+ } else {
2053
+
2054
+ console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
2055
+
2056
+ }
2057
+
2058
+ }
2059
+
2060
+ }
2061
+
2062
+ /**
2063
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
2064
+ *
2065
+ * @param {BufferGeometry} geometry
2066
+ * @param {Array<GLTF.Target>} targets
2067
+ * @param {GLTFParser} parser
2068
+ * @return {Promise<BufferGeometry>}
2069
+ */
2070
+ function addMorphTargets( geometry, targets, parser ) {
2071
+
2072
+ let hasMorphPosition = false;
2073
+ let hasMorphNormal = false;
2074
+ let hasMorphColor = false;
2075
+
2076
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
2077
+
2078
+ const target = targets[ i ];
2079
+
2080
+ if ( target.POSITION !== undefined ) hasMorphPosition = true;
2081
+ if ( target.NORMAL !== undefined ) hasMorphNormal = true;
2082
+ if ( target.COLOR_0 !== undefined ) hasMorphColor = true;
2083
+
2084
+ if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;
2085
+
2086
+ }
2087
+
2088
+ if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );
2089
+
2090
+ const pendingPositionAccessors = [];
2091
+ const pendingNormalAccessors = [];
2092
+ const pendingColorAccessors = [];
2093
+
2094
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
2095
+
2096
+ const target = targets[ i ];
2097
+
2098
+ if ( hasMorphPosition ) {
2099
+
2100
+ const pendingAccessor = target.POSITION !== undefined
2101
+ ? parser.getDependency( 'accessor', target.POSITION )
2102
+ : geometry.attributes.position;
2103
+
2104
+ pendingPositionAccessors.push( pendingAccessor );
2105
+
2106
+ }
2107
+
2108
+ if ( hasMorphNormal ) {
2109
+
2110
+ const pendingAccessor = target.NORMAL !== undefined
2111
+ ? parser.getDependency( 'accessor', target.NORMAL )
2112
+ : geometry.attributes.normal;
2113
+
2114
+ pendingNormalAccessors.push( pendingAccessor );
2115
+
2116
+ }
2117
+
2118
+ if ( hasMorphColor ) {
2119
+
2120
+ const pendingAccessor = target.COLOR_0 !== undefined
2121
+ ? parser.getDependency( 'accessor', target.COLOR_0 )
2122
+ : geometry.attributes.color;
2123
+
2124
+ pendingColorAccessors.push( pendingAccessor );
2125
+
2126
+ }
2127
+
2128
+ }
2129
+
2130
+ return Promise.all( [
2131
+ Promise.all( pendingPositionAccessors ),
2132
+ Promise.all( pendingNormalAccessors ),
2133
+ Promise.all( pendingColorAccessors )
2134
+ ] ).then( function ( accessors ) {
2135
+
2136
+ const morphPositions = accessors[ 0 ];
2137
+ const morphNormals = accessors[ 1 ];
2138
+ const morphColors = accessors[ 2 ];
2139
+
2140
+ if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
2141
+ if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
2142
+ if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;
2143
+ geometry.morphTargetsRelative = true;
2144
+
2145
+ return geometry;
2146
+
2147
+ } );
2148
+
2149
+ }
2150
+
2151
+ /**
2152
+ * @param {Mesh} mesh
2153
+ * @param {GLTF.Mesh} meshDef
2154
+ */
2155
+ function updateMorphTargets( mesh, meshDef ) {
2156
+
2157
+ mesh.updateMorphTargets();
2158
+
2159
+ if ( meshDef.weights !== undefined ) {
2160
+
2161
+ for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
2162
+
2163
+ mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
2164
+
2165
+ }
2166
+
2167
+ }
2168
+
2169
+ // .extras has user-defined data, so check that .extras.targetNames is an array.
2170
+ if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
2171
+
2172
+ const targetNames = meshDef.extras.targetNames;
2173
+
2174
+ if ( mesh.morphTargetInfluences.length === targetNames.length ) {
2175
+
2176
+ mesh.morphTargetDictionary = {};
2177
+
2178
+ for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
2179
+
2180
+ mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
2181
+
2182
+ }
2183
+
2184
+ } else {
2185
+
2186
+ console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
2187
+
2188
+ }
2189
+
2190
+ }
2191
+
2192
+ }
2193
+
2194
+ function createPrimitiveKey( primitiveDef ) {
2195
+
2196
+ const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
2197
+ let geometryKey;
2198
+
2199
+ if ( dracoExtension ) {
2200
+
2201
+ geometryKey = 'draco:' + dracoExtension.bufferView
2202
+ + ':' + dracoExtension.indices
2203
+ + ':' + createAttributesKey( dracoExtension.attributes );
2204
+
2205
+ } else {
2206
+
2207
+ geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
2208
+
2209
+ }
2210
+
2211
+ return geometryKey;
2212
+
2213
+ }
2214
+
2215
+ function createAttributesKey( attributes ) {
2216
+
2217
+ let attributesKey = '';
2218
+
2219
+ const keys = Object.keys( attributes ).sort();
2220
+
2221
+ for ( let i = 0, il = keys.length; i < il; i ++ ) {
2222
+
2223
+ attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
2224
+
2225
+ }
2226
+
2227
+ return attributesKey;
2228
+
2229
+ }
2230
+
2231
+ function getNormalizedComponentScale( constructor ) {
2232
+
2233
+ // Reference:
2234
+ // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
2235
+
2236
+ switch ( constructor ) {
2237
+
2238
+ case Int8Array:
2239
+ return 1 / 127;
2240
+
2241
+ case Uint8Array:
2242
+ return 1 / 255;
2243
+
2244
+ case Int16Array:
2245
+ return 1 / 32767;
2246
+
2247
+ case Uint16Array:
2248
+ return 1 / 65535;
2249
+
2250
+ default:
2251
+ throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
2252
+
2253
+ }
2254
+
2255
+ }
2256
+
2257
+ function getImageURIMimeType( uri ) {
2258
+
2259
+ if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg';
2260
+ if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp';
2261
+
2262
+ return 'image/png';
2263
+
2264
+ }
2265
+
2266
+ const _identityMatrix = new THREE.Matrix4();
2267
+
2268
+ /* GLTF PARSER */
2269
+
2270
+ class GLTFParser {
2271
+
2272
+ constructor( json = {}, options = {} ) {
2273
+
2274
+ this.json = json;
2275
+ this.extensions = {};
2276
+ this.plugins = {};
2277
+ this.options = options;
2278
+
2279
+ // loader object cache
2280
+ this.cache = new GLTFRegistry();
2281
+
2282
+ // associations between Three.js objects and glTF elements
2283
+ this.associations = new Map();
2284
+
2285
+ // BufferGeometry caching
2286
+ this.primitiveCache = {};
2287
+
2288
+ // Node cache
2289
+ this.nodeCache = {};
2290
+
2291
+ // Object3D instance caches
2292
+ this.meshCache = { refs: {}, uses: {} };
2293
+ this.cameraCache = { refs: {}, uses: {} };
2294
+ this.lightCache = { refs: {}, uses: {} };
2295
+
2296
+ this.sourceCache = {};
2297
+ this.textureCache = {};
2298
+
2299
+ // Track node names, to ensure no duplicates
2300
+ this.nodeNamesUsed = {};
2301
+
2302
+ // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
2303
+ // expensive work of uploading a texture to the GPU off the main thread.
2304
+
2305
+ let isSafari = false;
2306
+ let isFirefox = false;
2307
+ let firefoxVersion = - 1;
2308
+
2309
+ if ( typeof navigator !== 'undefined' ) {
2310
+
2311
+ isSafari = /^((?!chrome|android).)*safari/i.test( navigator.userAgent ) === true;
2312
+ isFirefox = navigator.userAgent.indexOf( 'Firefox' ) > - 1;
2313
+ firefoxVersion = isFirefox ? navigator.userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1;
2314
+
2315
+ }
2316
+
2317
+ if ( typeof createImageBitmap === 'undefined' || isSafari || ( isFirefox && firefoxVersion < 98 ) ) {
2318
+
2319
+ this.textureLoader = new THREE.TextureLoader( this.options.manager );
2320
+
2321
+ } else {
2322
+
2323
+ this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
2324
+
2325
+ }
2326
+
2327
+ this.textureLoader.setCrossOrigin( this.options.crossOrigin );
2328
+ this.textureLoader.setRequestHeader( this.options.requestHeader );
2329
+
2330
+ this.fileLoader = new THREE.FileLoader( this.options.manager );
2331
+ this.fileLoader.setResponseType( 'arraybuffer' );
2332
+
2333
+ if ( this.options.crossOrigin === 'use-credentials' ) {
2334
+
2335
+ this.fileLoader.setWithCredentials( true );
2336
+
2337
+ }
2338
+
2339
+ }
2340
+
2341
+ setExtensions( extensions ) {
2342
+
2343
+ this.extensions = extensions;
2344
+
2345
+ }
2346
+
2347
+ setPlugins( plugins ) {
2348
+
2349
+ this.plugins = plugins;
2350
+
2351
+ }
2352
+
2353
+ parse( onLoad, onError ) {
2354
+
2355
+ const parser = this;
2356
+ const json = this.json;
2357
+ const extensions = this.extensions;
2358
+
2359
+ // Clear the loader cache
2360
+ this.cache.removeAll();
2361
+ this.nodeCache = {};
2362
+
2363
+ // Mark the special nodes/meshes in json for efficient parse
2364
+ this._invokeAll( function ( ext ) {
2365
+
2366
+ return ext._markDefs && ext._markDefs();
2367
+
2368
+ } );
2369
+
2370
+ Promise.all( this._invokeAll( function ( ext ) {
2371
+
2372
+ return ext.beforeRoot && ext.beforeRoot();
2373
+
2374
+ } ) ).then( function () {
2375
+
2376
+ return Promise.all( [
2377
+
2378
+ parser.getDependencies( 'scene' ),
2379
+ parser.getDependencies( 'animation' ),
2380
+ parser.getDependencies( 'camera' ),
2381
+
2382
+ ] );
2383
+
2384
+ } ).then( function ( dependencies ) {
2385
+
2386
+ const result = {
2387
+ scene: dependencies[ 0 ][ json.scene || 0 ],
2388
+ scenes: dependencies[ 0 ],
2389
+ animations: dependencies[ 1 ],
2390
+ cameras: dependencies[ 2 ],
2391
+ asset: json.asset,
2392
+ parser: parser,
2393
+ userData: {}
2394
+ };
2395
+
2396
+ addUnknownExtensionsToUserData( extensions, result, json );
2397
+
2398
+ assignExtrasToUserData( result, json );
2399
+
2400
+ Promise.all( parser._invokeAll( function ( ext ) {
2401
+
2402
+ return ext.afterRoot && ext.afterRoot( result );
2403
+
2404
+ } ) ).then( function () {
2405
+
2406
+ onLoad( result );
2407
+
2408
+ } );
2409
+
2410
+ } ).catch( onError );
2411
+
2412
+ }
2413
+
2414
+ /**
2415
+ * Marks the special nodes/meshes in json for efficient parse.
2416
+ */
2417
+ _markDefs() {
2418
+
2419
+ const nodeDefs = this.json.nodes || [];
2420
+ const skinDefs = this.json.skins || [];
2421
+ const meshDefs = this.json.meshes || [];
2422
+
2423
+ // Nothing in the node definition indicates whether it is a Bone or an
2424
+ // Object3D. Use the skins' joint references to mark bones.
2425
+ for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
2426
+
2427
+ const joints = skinDefs[ skinIndex ].joints;
2428
+
2429
+ for ( let i = 0, il = joints.length; i < il; i ++ ) {
2430
+
2431
+ nodeDefs[ joints[ i ] ].isBone = true;
2432
+
2433
+ }
2434
+
2435
+ }
2436
+
2437
+ // Iterate over all nodes, marking references to shared resources,
2438
+ // as well as skeleton joints.
2439
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
2440
+
2441
+ const nodeDef = nodeDefs[ nodeIndex ];
2442
+
2443
+ if ( nodeDef.mesh !== undefined ) {
2444
+
2445
+ this._addNodeRef( this.meshCache, nodeDef.mesh );
2446
+
2447
+ // Nothing in the mesh definition indicates whether it is
2448
+ // a SkinnedMesh or Mesh. Use the node's mesh reference
2449
+ // to mark SkinnedMesh if node has skin.
2450
+ if ( nodeDef.skin !== undefined ) {
2451
+
2452
+ meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
2453
+
2454
+ }
2455
+
2456
+ }
2457
+
2458
+ if ( nodeDef.camera !== undefined ) {
2459
+
2460
+ this._addNodeRef( this.cameraCache, nodeDef.camera );
2461
+
2462
+ }
2463
+
2464
+ }
2465
+
2466
+ }
2467
+
2468
+ /**
2469
+ * Counts references to shared node / Object3D resources. These resources
2470
+ * can be reused, or "instantiated", at multiple nodes in the scene
2471
+ * hierarchy. Mesh, Camera, and Light instances are instantiated and must
2472
+ * be marked. Non-scenegraph resources (like Materials, Geometries, and
2473
+ * Textures) can be reused directly and are not marked here.
2474
+ *
2475
+ * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
2476
+ */
2477
+ _addNodeRef( cache, index ) {
2478
+
2479
+ if ( index === undefined ) return;
2480
+
2481
+ if ( cache.refs[ index ] === undefined ) {
2482
+
2483
+ cache.refs[ index ] = cache.uses[ index ] = 0;
2484
+
2485
+ }
2486
+
2487
+ cache.refs[ index ] ++;
2488
+
2489
+ }
2490
+
2491
+ /** Returns a reference to a shared resource, cloning it if necessary. */
2492
+ _getNodeRef( cache, index, object ) {
2493
+
2494
+ if ( cache.refs[ index ] <= 1 ) return object;
2495
+
2496
+ const ref = object.clone();
2497
+
2498
+ // Propagates mappings to the cloned object, prevents mappings on the
2499
+ // original object from being lost.
2500
+ const updateMappings = ( original, clone ) => {
2501
+
2502
+ const mappings = this.associations.get( original );
2503
+ if ( mappings != null ) {
2504
+
2505
+ this.associations.set( clone, mappings );
2506
+
2507
+ }
2508
+
2509
+ for ( const [ i, child ] of original.children.entries() ) {
2510
+
2511
+ updateMappings( child, clone.children[ i ] );
2512
+
2513
+ }
2514
+
2515
+ };
2516
+
2517
+ updateMappings( object, ref );
2518
+
2519
+ ref.name += '_instance_' + ( cache.uses[ index ] ++ );
2520
+
2521
+ return ref;
2522
+
2523
+ }
2524
+
2525
+ _invokeOne( func ) {
2526
+
2527
+ const extensions = Object.values( this.plugins );
2528
+ extensions.push( this );
2529
+
2530
+ for ( let i = 0; i < extensions.length; i ++ ) {
2531
+
2532
+ const result = func( extensions[ i ] );
2533
+
2534
+ if ( result ) return result;
2535
+
2536
+ }
2537
+
2538
+ return null;
2539
+
2540
+ }
2541
+
2542
+ _invokeAll( func ) {
2543
+
2544
+ const extensions = Object.values( this.plugins );
2545
+ extensions.unshift( this );
2546
+
2547
+ const pending = [];
2548
+
2549
+ for ( let i = 0; i < extensions.length; i ++ ) {
2550
+
2551
+ const result = func( extensions[ i ] );
2552
+
2553
+ if ( result ) pending.push( result );
2554
+
2555
+ }
2556
+
2557
+ return pending;
2558
+
2559
+ }
2560
+
2561
+ /**
2562
+ * Requests the specified dependency asynchronously, with caching.
2563
+ * @param {string} type
2564
+ * @param {number} index
2565
+ * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
2566
+ */
2567
+ getDependency( type, index ) {
2568
+
2569
+ const cacheKey = type + ':' + index;
2570
+ let dependency = this.cache.get( cacheKey );
2571
+
2572
+ if ( ! dependency ) {
2573
+
2574
+ switch ( type ) {
2575
+
2576
+ case 'scene':
2577
+ dependency = this.loadScene( index );
2578
+ break;
2579
+
2580
+ case 'node':
2581
+ dependency = this._invokeOne( function ( ext ) {
2582
+
2583
+ return ext.loadNode && ext.loadNode( index );
2584
+
2585
+ } );
2586
+ break;
2587
+
2588
+ case 'mesh':
2589
+ dependency = this._invokeOne( function ( ext ) {
2590
+
2591
+ return ext.loadMesh && ext.loadMesh( index );
2592
+
2593
+ } );
2594
+ break;
2595
+
2596
+ case 'accessor':
2597
+ dependency = this.loadAccessor( index );
2598
+ break;
2599
+
2600
+ case 'bufferView':
2601
+ dependency = this._invokeOne( function ( ext ) {
2602
+
2603
+ return ext.loadBufferView && ext.loadBufferView( index );
2604
+
2605
+ } );
2606
+ break;
2607
+
2608
+ case 'buffer':
2609
+ dependency = this.loadBuffer( index );
2610
+ break;
2611
+
2612
+ case 'material':
2613
+ dependency = this._invokeOne( function ( ext ) {
2614
+
2615
+ return ext.loadMaterial && ext.loadMaterial( index );
2616
+
2617
+ } );
2618
+ break;
2619
+
2620
+ case 'texture':
2621
+ dependency = this._invokeOne( function ( ext ) {
2622
+
2623
+ return ext.loadTexture && ext.loadTexture( index );
2624
+
2625
+ } );
2626
+ break;
2627
+
2628
+ case 'skin':
2629
+ dependency = this.loadSkin( index );
2630
+ break;
2631
+
2632
+ case 'animation':
2633
+ dependency = this._invokeOne( function ( ext ) {
2634
+
2635
+ return ext.loadAnimation && ext.loadAnimation( index );
2636
+
2637
+ } );
2638
+ break;
2639
+
2640
+ case 'camera':
2641
+ dependency = this.loadCamera( index );
2642
+ break;
2643
+
2644
+ default:
2645
+ dependency = this._invokeOne( function ( ext ) {
2646
+
2647
+ return ext != this && ext.getDependency && ext.getDependency( type, index );
2648
+
2649
+ } );
2650
+
2651
+ if ( ! dependency ) {
2652
+
2653
+ throw new Error( 'Unknown type: ' + type );
2654
+
2655
+ }
2656
+
2657
+ break;
2658
+
2659
+ }
2660
+
2661
+ this.cache.add( cacheKey, dependency );
2662
+
2663
+ }
2664
+
2665
+ return dependency;
2666
+
2667
+ }
2668
+
2669
+ /**
2670
+ * Requests all dependencies of the specified type asynchronously, with caching.
2671
+ * @param {string} type
2672
+ * @return {Promise<Array<Object>>}
2673
+ */
2674
+ getDependencies( type ) {
2675
+
2676
+ let dependencies = this.cache.get( type );
2677
+
2678
+ if ( ! dependencies ) {
2679
+
2680
+ const parser = this;
2681
+ const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
2682
+
2683
+ dependencies = Promise.all( defs.map( function ( def, index ) {
2684
+
2685
+ return parser.getDependency( type, index );
2686
+
2687
+ } ) );
2688
+
2689
+ this.cache.add( type, dependencies );
2690
+
2691
+ }
2692
+
2693
+ return dependencies;
2694
+
2695
+ }
2696
+
2697
+ /**
2698
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
2699
+ * @param {number} bufferIndex
2700
+ * @return {Promise<ArrayBuffer>}
2701
+ */
2702
+ loadBuffer( bufferIndex ) {
2703
+
2704
+ const bufferDef = this.json.buffers[ bufferIndex ];
2705
+ const loader = this.fileLoader;
2706
+
2707
+ if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
2708
+
2709
+ throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
2710
+
2711
+ }
2712
+
2713
+ // If present, GLB container is required to be the first buffer.
2714
+ if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
2715
+
2716
+ return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
2717
+
2718
+ }
2719
+
2720
+ const options = this.options;
2721
+
2722
+ return new Promise( function ( resolve, reject ) {
2723
+
2724
+ loader.load( THREE.LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
2725
+
2726
+ reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
2727
+
2728
+ } );
2729
+
2730
+ } );
2731
+
2732
+ }
2733
+
2734
+ /**
2735
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
2736
+ * @param {number} bufferViewIndex
2737
+ * @return {Promise<ArrayBuffer>}
2738
+ */
2739
+ loadBufferView( bufferViewIndex ) {
2740
+
2741
+ const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
2742
+
2743
+ return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
2744
+
2745
+ const byteLength = bufferViewDef.byteLength || 0;
2746
+ const byteOffset = bufferViewDef.byteOffset || 0;
2747
+ return buffer.slice( byteOffset, byteOffset + byteLength );
2748
+
2749
+ } );
2750
+
2751
+ }
2752
+
2753
+ /**
2754
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
2755
+ * @param {number} accessorIndex
2756
+ * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
2757
+ */
2758
+ loadAccessor( accessorIndex ) {
2759
+
2760
+ const parser = this;
2761
+ const json = this.json;
2762
+
2763
+ const accessorDef = this.json.accessors[ accessorIndex ];
2764
+
2765
+ if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
2766
+
2767
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
2768
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
2769
+ const normalized = accessorDef.normalized === true;
2770
+
2771
+ const array = new TypedArray( accessorDef.count * itemSize );
2772
+ return Promise.resolve( new THREE.BufferAttribute( array, itemSize, normalized ) );
2773
+
2774
+ }
2775
+
2776
+ const pendingBufferViews = [];
2777
+
2778
+ if ( accessorDef.bufferView !== undefined ) {
2779
+
2780
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
2781
+
2782
+ } else {
2783
+
2784
+ pendingBufferViews.push( null );
2785
+
2786
+ }
2787
+
2788
+ if ( accessorDef.sparse !== undefined ) {
2789
+
2790
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
2791
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
2792
+
2793
+ }
2794
+
2795
+ return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
2796
+
2797
+ const bufferView = bufferViews[ 0 ];
2798
+
2799
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
2800
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
2801
+
2802
+ // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
2803
+ const elementBytes = TypedArray.BYTES_PER_ELEMENT;
2804
+ const itemBytes = elementBytes * itemSize;
2805
+ const byteOffset = accessorDef.byteOffset || 0;
2806
+ const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
2807
+ const normalized = accessorDef.normalized === true;
2808
+ let array, bufferAttribute;
2809
+
2810
+ // The buffer is not interleaved if the stride is the item size in bytes.
2811
+ if ( byteStride && byteStride !== itemBytes ) {
2812
+
2813
+ // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
2814
+ // This makes sure that IBA.count reflects accessor.count properly
2815
+ const ibSlice = Math.floor( byteOffset / byteStride );
2816
+ const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
2817
+ let ib = parser.cache.get( ibCacheKey );
2818
+
2819
+ if ( ! ib ) {
2820
+
2821
+ array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
2822
+
2823
+ // Integer parameters to IB/IBA are in array elements, not bytes.
2824
+ ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
2825
+
2826
+ parser.cache.add( ibCacheKey, ib );
2827
+
2828
+ }
2829
+
2830
+ bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
2831
+
2832
+ } else {
2833
+
2834
+ if ( bufferView === null ) {
2835
+
2836
+ array = new TypedArray( accessorDef.count * itemSize );
2837
+
2838
+ } else {
2839
+
2840
+ array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
2841
+
2842
+ }
2843
+
2844
+ bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
2845
+
2846
+ }
2847
+
2848
+ // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
2849
+ if ( accessorDef.sparse !== undefined ) {
2850
+
2851
+ const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
2852
+ const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
2853
+
2854
+ const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
2855
+ const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
2856
+
2857
+ const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
2858
+ const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
2859
+
2860
+ if ( bufferView !== null ) {
2861
+
2862
+ // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
2863
+ bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
2864
+
2865
+ }
2866
+
2867
+ for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
2868
+
2869
+ const index = sparseIndices[ i ];
2870
+
2871
+ bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
2872
+ if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
2873
+ if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
2874
+ if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
2875
+ if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
2876
+
2877
+ }
2878
+
2879
+ }
2880
+
2881
+ return bufferAttribute;
2882
+
2883
+ } );
2884
+
2885
+ }
2886
+
2887
+ /**
2888
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
2889
+ * @param {number} textureIndex
2890
+ * @return {Promise<THREE.Texture|null>}
2891
+ */
2892
+ loadTexture( textureIndex ) {
2893
+
2894
+ const json = this.json;
2895
+ const options = this.options;
2896
+ const textureDef = json.textures[ textureIndex ];
2897
+ const sourceIndex = textureDef.source;
2898
+ const sourceDef = json.images[ sourceIndex ];
2899
+
2900
+ let loader = this.textureLoader;
2901
+
2902
+ if ( sourceDef.uri ) {
2903
+
2904
+ const handler = options.manager.getHandler( sourceDef.uri );
2905
+ if ( handler !== null ) loader = handler;
2906
+
2907
+ }
2908
+
2909
+ return this.loadTextureImage( textureIndex, sourceIndex, loader );
2910
+
2911
+ }
2912
+
2913
+ loadTextureImage( textureIndex, sourceIndex, loader ) {
2914
+
2915
+ const parser = this;
2916
+ const json = this.json;
2917
+
2918
+ const textureDef = json.textures[ textureIndex ];
2919
+ const sourceDef = json.images[ sourceIndex ];
2920
+
2921
+ const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;
2922
+
2923
+ if ( this.textureCache[ cacheKey ] ) {
2924
+
2925
+ // See https://github.com/mrdoob/three.js/issues/21559.
2926
+ return this.textureCache[ cacheKey ];
2927
+
2928
+ }
2929
+
2930
+ const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {
2931
+
2932
+ texture.flipY = false;
2933
+
2934
+ texture.name = textureDef.name || sourceDef.name || '';
2935
+
2936
+ const samplers = json.samplers || {};
2937
+ const sampler = samplers[ textureDef.sampler ] || {};
2938
+
2939
+ texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
2940
+ texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
2941
+ texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
2942
+ texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
2943
+
2944
+ parser.associations.set( texture, { textures: textureIndex } );
2945
+
2946
+ return texture;
2947
+
2948
+ } ).catch( function () {
2949
+
2950
+ return null;
2951
+
2952
+ } );
2953
+
2954
+ this.textureCache[ cacheKey ] = promise;
2955
+
2956
+ return promise;
2957
+
2958
+ }
2959
+
2960
+ loadImageSource( sourceIndex, loader ) {
2961
+
2962
+ const parser = this;
2963
+ const json = this.json;
2964
+ const options = this.options;
2965
+
2966
+ if ( this.sourceCache[ sourceIndex ] !== undefined ) {
2967
+
2968
+ return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );
2969
+
2970
+ }
2971
+
2972
+ const sourceDef = json.images[ sourceIndex ];
2973
+
2974
+ const URL = self.URL || self.webkitURL;
2975
+
2976
+ let sourceURI = sourceDef.uri || '';
2977
+ let isObjectURL = false;
2978
+
2979
+ if ( sourceDef.bufferView !== undefined ) {
2980
+
2981
+ // Load binary image data from bufferView, if provided.
2982
+
2983
+ sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {
2984
+
2985
+ isObjectURL = true;
2986
+ const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );
2987
+ sourceURI = URL.createObjectURL( blob );
2988
+ return sourceURI;
2989
+
2990
+ } );
2991
+
2992
+ } else if ( sourceDef.uri === undefined ) {
2993
+
2994
+ throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );
2995
+
2996
+ }
2997
+
2998
+ const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
2999
+
3000
+ return new Promise( function ( resolve, reject ) {
3001
+
3002
+ let onLoad = resolve;
3003
+
3004
+ if ( loader.isImageBitmapLoader === true ) {
3005
+
3006
+ onLoad = function ( imageBitmap ) {
3007
+
3008
+ const texture = new THREE.Texture( imageBitmap );
3009
+ texture.needsUpdate = true;
3010
+
3011
+ resolve( texture );
3012
+
3013
+ };
3014
+
3015
+ }
3016
+
3017
+ loader.load( THREE.LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
3018
+
3019
+ } );
3020
+
3021
+ } ).then( function ( texture ) {
3022
+
3023
+ // Clean up resources and configure Texture.
3024
+
3025
+ if ( isObjectURL === true ) {
3026
+
3027
+ URL.revokeObjectURL( sourceURI );
3028
+
3029
+ }
3030
+
3031
+ texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri );
3032
+
3033
+ return texture;
3034
+
3035
+ } ).catch( function ( error ) {
3036
+
3037
+ console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
3038
+ throw error;
3039
+
3040
+ } );
3041
+
3042
+ this.sourceCache[ sourceIndex ] = promise;
3043
+ return promise;
3044
+
3045
+ }
3046
+
3047
+ /**
3048
+ * Asynchronously assigns a texture to the given material parameters.
3049
+ * @param {Object} materialParams
3050
+ * @param {string} mapName
3051
+ * @param {Object} mapDef
3052
+ * @return {Promise<Texture>}
3053
+ */
3054
+ assignTexture( materialParams, mapName, mapDef, encoding ) {
3055
+
3056
+ const parser = this;
3057
+
3058
+ return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
3059
+
3060
+ if ( ! texture ) return null;
3061
+
3062
+ // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
3063
+ // However, we will copy UV set 0 to UV set 1 on demand for aoMap
3064
+ if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
3065
+
3066
+ console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
3067
+
3068
+ }
3069
+
3070
+ if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
3071
+
3072
+ const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
3073
+
3074
+ if ( transform ) {
3075
+
3076
+ const gltfReference = parser.associations.get( texture );
3077
+ texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
3078
+ parser.associations.set( texture, gltfReference );
3079
+
3080
+ }
3081
+
3082
+ }
3083
+
3084
+ if ( encoding !== undefined ) {
3085
+
3086
+ texture.encoding = encoding;
3087
+
3088
+ }
3089
+
3090
+ materialParams[ mapName ] = texture;
3091
+
3092
+ return texture;
3093
+
3094
+ } );
3095
+
3096
+ }
3097
+
3098
+ /**
3099
+ * Assigns final material to a Mesh, Line, or Points instance. The instance
3100
+ * already has a material (generated from the glTF material options alone)
3101
+ * but reuse of the same glTF material may require multiple threejs materials
3102
+ * to accommodate different primitive types, defines, etc. New materials will
3103
+ * be created if necessary, and reused from a cache.
3104
+ * @param {Object3D} mesh Mesh, Line, or Points instance.
3105
+ */
3106
+ assignFinalMaterial( mesh ) {
3107
+
3108
+ const geometry = mesh.geometry;
3109
+ let material = mesh.material;
3110
+
3111
+ const useDerivativeTangents = geometry.attributes.tangent === undefined;
3112
+ const useVertexColors = geometry.attributes.color !== undefined;
3113
+ const useFlatShading = geometry.attributes.normal === undefined;
3114
+
3115
+ if ( mesh.isPoints ) {
3116
+
3117
+ const cacheKey = 'PointsMaterial:' + material.uuid;
3118
+
3119
+ let pointsMaterial = this.cache.get( cacheKey );
3120
+
3121
+ if ( ! pointsMaterial ) {
3122
+
3123
+ pointsMaterial = new THREE.PointsMaterial();
3124
+ THREE.Material.prototype.copy.call( pointsMaterial, material );
3125
+ pointsMaterial.color.copy( material.color );
3126
+ pointsMaterial.map = material.map;
3127
+ pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
3128
+
3129
+ this.cache.add( cacheKey, pointsMaterial );
3130
+
3131
+ }
3132
+
3133
+ material = pointsMaterial;
3134
+
3135
+ } else if ( mesh.isLine ) {
3136
+
3137
+ const cacheKey = 'LineBasicMaterial:' + material.uuid;
3138
+
3139
+ let lineMaterial = this.cache.get( cacheKey );
3140
+
3141
+ if ( ! lineMaterial ) {
3142
+
3143
+ lineMaterial = new THREE.LineBasicMaterial();
3144
+ THREE.Material.prototype.copy.call( lineMaterial, material );
3145
+ lineMaterial.color.copy( material.color );
3146
+
3147
+ this.cache.add( cacheKey, lineMaterial );
3148
+
3149
+ }
3150
+
3151
+ material = lineMaterial;
3152
+
3153
+ }
3154
+
3155
+ // Clone the material if it will be modified
3156
+ if ( useDerivativeTangents || useVertexColors || useFlatShading ) {
3157
+
3158
+ let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
3159
+
3160
+ if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';
3161
+ if ( useVertexColors ) cacheKey += 'vertex-colors:';
3162
+ if ( useFlatShading ) cacheKey += 'flat-shading:';
3163
+
3164
+ let cachedMaterial = this.cache.get( cacheKey );
3165
+
3166
+ if ( ! cachedMaterial ) {
3167
+
3168
+ cachedMaterial = material.clone();
3169
+
3170
+ if ( useVertexColors ) cachedMaterial.vertexColors = true;
3171
+ if ( useFlatShading ) cachedMaterial.flatShading = true;
3172
+
3173
+ if ( useDerivativeTangents ) {
3174
+
3175
+ // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
3176
+ if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;
3177
+ if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;
3178
+
3179
+ }
3180
+
3181
+ this.cache.add( cacheKey, cachedMaterial );
3182
+
3183
+ this.associations.set( cachedMaterial, this.associations.get( material ) );
3184
+
3185
+ }
3186
+
3187
+ material = cachedMaterial;
3188
+
3189
+ }
3190
+
3191
+ // workarounds for mesh and geometry
3192
+
3193
+ if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
3194
+
3195
+ geometry.setAttribute( 'uv2', geometry.attributes.uv );
3196
+
3197
+ }
3198
+
3199
+ mesh.material = material;
3200
+
3201
+ }
3202
+
3203
+ getMaterialType( /* materialIndex */ ) {
3204
+
3205
+ return THREE.MeshStandardMaterial;
3206
+
3207
+ }
3208
+
3209
+ /**
3210
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
3211
+ * @param {number} materialIndex
3212
+ * @return {Promise<Material>}
3213
+ */
3214
+ loadMaterial( materialIndex ) {
3215
+
3216
+ const parser = this;
3217
+ const json = this.json;
3218
+ const extensions = this.extensions;
3219
+ const materialDef = json.materials[ materialIndex ];
3220
+
3221
+ let materialType;
3222
+ const materialParams = {};
3223
+ const materialExtensions = materialDef.extensions || {};
3224
+
3225
+ const pending = [];
3226
+
3227
+ if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
3228
+
3229
+ const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
3230
+ materialType = kmuExtension.getMaterialType();
3231
+ pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
3232
+
3233
+ } else {
3234
+
3235
+ // Specification:
3236
+ // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
3237
+
3238
+ const metallicRoughness = materialDef.pbrMetallicRoughness || {};
3239
+
3240
+ materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
3241
+ materialParams.opacity = 1.0;
3242
+
3243
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
3244
+
3245
+ const array = metallicRoughness.baseColorFactor;
3246
+
3247
+ materialParams.color.fromArray( array );
3248
+ materialParams.opacity = array[ 3 ];
3249
+
3250
+ }
3251
+
3252
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
3253
+
3254
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, THREE.sRGBEncoding ) );
3255
+
3256
+ }
3257
+
3258
+ materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
3259
+ materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
3260
+
3261
+ if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
3262
+
3263
+ pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
3264
+ pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
3265
+
3266
+ }
3267
+
3268
+ materialType = this._invokeOne( function ( ext ) {
3269
+
3270
+ return ext.getMaterialType && ext.getMaterialType( materialIndex );
3271
+
3272
+ } );
3273
+
3274
+ pending.push( Promise.all( this._invokeAll( function ( ext ) {
3275
+
3276
+ return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
3277
+
3278
+ } ) ) );
3279
+
3280
+ }
3281
+
3282
+ if ( materialDef.doubleSided === true ) {
3283
+
3284
+ materialParams.side = THREE.DoubleSide;
3285
+
3286
+ }
3287
+
3288
+ const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
3289
+
3290
+ if ( alphaMode === ALPHA_MODES.BLEND ) {
3291
+
3292
+ materialParams.transparent = true;
3293
+
3294
+ // See: https://github.com/mrdoob/three.js/issues/17706
3295
+ materialParams.depthWrite = false;
3296
+
3297
+ } else {
3298
+
3299
+ materialParams.transparent = false;
3300
+
3301
+ if ( alphaMode === ALPHA_MODES.MASK ) {
3302
+
3303
+ materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
3304
+
3305
+ }
3306
+
3307
+ }
3308
+
3309
+ if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3310
+
3311
+ pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
3312
+
3313
+ materialParams.normalScale = new THREE.Vector2( 1, 1 );
3314
+
3315
+ if ( materialDef.normalTexture.scale !== undefined ) {
3316
+
3317
+ const scale = materialDef.normalTexture.scale;
3318
+
3319
+ materialParams.normalScale.set( scale, scale );
3320
+
3321
+ }
3322
+
3323
+ }
3324
+
3325
+ if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3326
+
3327
+ pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
3328
+
3329
+ if ( materialDef.occlusionTexture.strength !== undefined ) {
3330
+
3331
+ materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
3332
+
3333
+ }
3334
+
3335
+ }
3336
+
3337
+ if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3338
+
3339
+ materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
3340
+
3341
+ }
3342
+
3343
+ if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3344
+
3345
+ pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, THREE.sRGBEncoding ) );
3346
+
3347
+ }
3348
+
3349
+ return Promise.all( pending ).then( function () {
3350
+
3351
+ const material = new materialType( materialParams );
3352
+
3353
+ if ( materialDef.name ) material.name = materialDef.name;
3354
+
3355
+ assignExtrasToUserData( material, materialDef );
3356
+
3357
+ parser.associations.set( material, { materials: materialIndex } );
3358
+
3359
+ if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
3360
+
3361
+ return material;
3362
+
3363
+ } );
3364
+
3365
+ }
3366
+
3367
+ /** When Object3D instances are targeted by animation, they need unique names. */
3368
+ createUniqueName( originalName ) {
3369
+
3370
+ const sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' );
3371
+
3372
+ let name = sanitizedName;
3373
+
3374
+ for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
3375
+
3376
+ name = sanitizedName + '_' + i;
3377
+
3378
+ }
3379
+
3380
+ this.nodeNamesUsed[ name ] = true;
3381
+
3382
+ return name;
3383
+
3384
+ }
3385
+
3386
+ /**
3387
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
3388
+ *
3389
+ * Creates BufferGeometries from primitives.
3390
+ *
3391
+ * @param {Array<GLTF.Primitive>} primitives
3392
+ * @return {Promise<Array<BufferGeometry>>}
3393
+ */
3394
+ loadGeometries( primitives ) {
3395
+
3396
+ const parser = this;
3397
+ const extensions = this.extensions;
3398
+ const cache = this.primitiveCache;
3399
+
3400
+ function createDracoPrimitive( primitive ) {
3401
+
3402
+ return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
3403
+ .decodePrimitive( primitive, parser )
3404
+ .then( function ( geometry ) {
3405
+
3406
+ return addPrimitiveAttributes( geometry, primitive, parser );
3407
+
3408
+ } );
3409
+
3410
+ }
3411
+
3412
+ const pending = [];
3413
+
3414
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
3415
+
3416
+ const primitive = primitives[ i ];
3417
+ const cacheKey = createPrimitiveKey( primitive );
3418
+
3419
+ // See if we've already created this geometry
3420
+ const cached = cache[ cacheKey ];
3421
+
3422
+ if ( cached ) {
3423
+
3424
+ // Use the cached geometry if it exists
3425
+ pending.push( cached.promise );
3426
+
3427
+ } else {
3428
+
3429
+ let geometryPromise;
3430
+
3431
+ if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
3432
+
3433
+ // Use DRACO geometry if available
3434
+ geometryPromise = createDracoPrimitive( primitive );
3435
+
3436
+ } else {
3437
+
3438
+ // Otherwise create a new geometry
3439
+ geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
3440
+
3441
+ }
3442
+
3443
+ // Cache this geometry
3444
+ cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
3445
+
3446
+ pending.push( geometryPromise );
3447
+
3448
+ }
3449
+
3450
+ }
3451
+
3452
+ return Promise.all( pending );
3453
+
3454
+ }
3455
+
3456
+ /**
3457
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
3458
+ * @param {number} meshIndex
3459
+ * @return {Promise<Group|Mesh|SkinnedMesh>}
3460
+ */
3461
+ loadMesh( meshIndex ) {
3462
+
3463
+ const parser = this;
3464
+ const json = this.json;
3465
+ const extensions = this.extensions;
3466
+
3467
+ const meshDef = json.meshes[ meshIndex ];
3468
+ const primitives = meshDef.primitives;
3469
+
3470
+ const pending = [];
3471
+
3472
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
3473
+
3474
+ const material = primitives[ i ].material === undefined
3475
+ ? createDefaultMaterial( this.cache )
3476
+ : this.getDependency( 'material', primitives[ i ].material );
3477
+
3478
+ pending.push( material );
3479
+
3480
+ }
3481
+
3482
+ pending.push( parser.loadGeometries( primitives ) );
3483
+
3484
+ return Promise.all( pending ).then( function ( results ) {
3485
+
3486
+ const materials = results.slice( 0, results.length - 1 );
3487
+ const geometries = results[ results.length - 1 ];
3488
+
3489
+ const meshes = [];
3490
+
3491
+ for ( let i = 0, il = geometries.length; i < il; i ++ ) {
3492
+
3493
+ const geometry = geometries[ i ];
3494
+ const primitive = primitives[ i ];
3495
+
3496
+ // 1. create Mesh
3497
+
3498
+ let mesh;
3499
+
3500
+ const material = materials[ i ];
3501
+
3502
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
3503
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
3504
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
3505
+ primitive.mode === undefined ) {
3506
+
3507
+ // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
3508
+ mesh = meshDef.isSkinnedMesh === true
3509
+ ? new THREE.SkinnedMesh( geometry, material )
3510
+ : new THREE.Mesh( geometry, material );
3511
+
3512
+ if ( mesh.isSkinnedMesh === true ) {
3513
+
3514
+ // normalize skin weights to fix malformed assets (see #15319)
3515
+ mesh.normalizeSkinWeights();
3516
+
3517
+ }
3518
+
3519
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
3520
+
3521
+ mesh.geometry = BufferGeometryUtils.toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
3522
+
3523
+ } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
3524
+
3525
+ mesh.geometry = BufferGeometryUtils.toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
3526
+
3527
+ }
3528
+
3529
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
3530
+
3531
+ mesh = new THREE.LineSegments( geometry, material );
3532
+
3533
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
3534
+
3535
+ mesh = new THREE.Line( geometry, material );
3536
+
3537
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
3538
+
3539
+ mesh = new THREE.LineLoop( geometry, material );
3540
+
3541
+ } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
3542
+
3543
+ mesh = new THREE.Points( geometry, material );
3544
+
3545
+ } else {
3546
+
3547
+ throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
3548
+
3549
+ }
3550
+
3551
+ if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
3552
+
3553
+ updateMorphTargets( mesh, meshDef );
3554
+
3555
+ }
3556
+
3557
+ mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
3558
+
3559
+ assignExtrasToUserData( mesh, meshDef );
3560
+
3561
+ if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
3562
+
3563
+ parser.assignFinalMaterial( mesh );
3564
+
3565
+ meshes.push( mesh );
3566
+
3567
+ }
3568
+
3569
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
3570
+
3571
+ parser.associations.set( meshes[ i ], {
3572
+ meshes: meshIndex,
3573
+ primitives: i
3574
+ } );
3575
+
3576
+ }
3577
+
3578
+ if ( meshes.length === 1 ) {
3579
+
3580
+ return meshes[ 0 ];
3581
+
3582
+ }
3583
+
3584
+ const group = new THREE.Group();
3585
+
3586
+ parser.associations.set( group, { meshes: meshIndex } );
3587
+
3588
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
3589
+
3590
+ group.add( meshes[ i ] );
3591
+
3592
+ }
3593
+
3594
+ return group;
3595
+
3596
+ } );
3597
+
3598
+ }
3599
+
3600
+ /**
3601
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
3602
+ * @param {number} cameraIndex
3603
+ * @return {Promise<THREE.Camera>}
3604
+ */
3605
+ loadCamera( cameraIndex ) {
3606
+
3607
+ let camera;
3608
+ const cameraDef = this.json.cameras[ cameraIndex ];
3609
+ const params = cameraDef[ cameraDef.type ];
3610
+
3611
+ if ( ! params ) {
3612
+
3613
+ console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
3614
+ return;
3615
+
3616
+ }
3617
+
3618
+ if ( cameraDef.type === 'perspective' ) {
3619
+
3620
+ camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
3621
+
3622
+ } else if ( cameraDef.type === 'orthographic' ) {
3623
+
3624
+ camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
3625
+
3626
+ }
3627
+
3628
+ if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
3629
+
3630
+ assignExtrasToUserData( camera, cameraDef );
3631
+
3632
+ return Promise.resolve( camera );
3633
+
3634
+ }
3635
+
3636
+ /**
3637
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
3638
+ * @param {number} skinIndex
3639
+ * @return {Promise<Skeleton>}
3640
+ */
3641
+ loadSkin( skinIndex ) {
3642
+
3643
+ const skinDef = this.json.skins[ skinIndex ];
3644
+
3645
+ const pending = [];
3646
+
3647
+ for ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) {
3648
+
3649
+ pending.push( this._loadNodeShallow( skinDef.joints[ i ] ) );
3650
+
3651
+ }
3652
+
3653
+ if ( skinDef.inverseBindMatrices !== undefined ) {
3654
+
3655
+ pending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) );
3656
+
3657
+ } else {
3658
+
3659
+ pending.push( null );
3660
+
3661
+ }
3662
+
3663
+ return Promise.all( pending ).then( function ( results ) {
3664
+
3665
+ const inverseBindMatrices = results.pop();
3666
+ const jointNodes = results;
3667
+
3668
+ // Note that bones (joint nodes) may or may not be in the
3669
+ // scene graph at this time.
3670
+
3671
+ const bones = [];
3672
+ const boneInverses = [];
3673
+
3674
+ for ( let i = 0, il = jointNodes.length; i < il; i ++ ) {
3675
+
3676
+ const jointNode = jointNodes[ i ];
3677
+
3678
+ if ( jointNode ) {
3679
+
3680
+ bones.push( jointNode );
3681
+
3682
+ const mat = new THREE.Matrix4();
3683
+
3684
+ if ( inverseBindMatrices !== null ) {
3685
+
3686
+ mat.fromArray( inverseBindMatrices.array, i * 16 );
3687
+
3688
+ }
3689
+
3690
+ boneInverses.push( mat );
3691
+
3692
+ } else {
3693
+
3694
+ console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[ i ] );
3695
+
3696
+ }
3697
+
3698
+ }
3699
+
3700
+ return new THREE.Skeleton( bones, boneInverses );
3701
+
3702
+ } );
3703
+
3704
+ }
3705
+
3706
+ /**
3707
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
3708
+ * @param {number} animationIndex
3709
+ * @return {Promise<AnimationClip>}
3710
+ */
3711
+ loadAnimation( animationIndex ) {
3712
+
3713
+ const json = this.json;
3714
+
3715
+ const animationDef = json.animations[ animationIndex ];
3716
+
3717
+ const pendingNodes = [];
3718
+ const pendingInputAccessors = [];
3719
+ const pendingOutputAccessors = [];
3720
+ const pendingSamplers = [];
3721
+ const pendingTargets = [];
3722
+
3723
+ for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
3724
+
3725
+ const channel = animationDef.channels[ i ];
3726
+ const sampler = animationDef.samplers[ channel.sampler ];
3727
+ const target = channel.target;
3728
+ const name = target.node;
3729
+ const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
3730
+ const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
3731
+
3732
+ pendingNodes.push( this.getDependency( 'node', name ) );
3733
+ pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
3734
+ pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
3735
+ pendingSamplers.push( sampler );
3736
+ pendingTargets.push( target );
3737
+
3738
+ }
3739
+
3740
+ return Promise.all( [
3741
+
3742
+ Promise.all( pendingNodes ),
3743
+ Promise.all( pendingInputAccessors ),
3744
+ Promise.all( pendingOutputAccessors ),
3745
+ Promise.all( pendingSamplers ),
3746
+ Promise.all( pendingTargets )
3747
+
3748
+ ] ).then( function ( dependencies ) {
3749
+
3750
+ const nodes = dependencies[ 0 ];
3751
+ const inputAccessors = dependencies[ 1 ];
3752
+ const outputAccessors = dependencies[ 2 ];
3753
+ const samplers = dependencies[ 3 ];
3754
+ const targets = dependencies[ 4 ];
3755
+
3756
+ const tracks = [];
3757
+
3758
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
3759
+
3760
+ const node = nodes[ i ];
3761
+ const inputAccessor = inputAccessors[ i ];
3762
+ const outputAccessor = outputAccessors[ i ];
3763
+ const sampler = samplers[ i ];
3764
+ const target = targets[ i ];
3765
+
3766
+ if ( node === undefined ) continue;
3767
+
3768
+ node.updateMatrix();
3769
+
3770
+ let TypedKeyframeTrack;
3771
+
3772
+ switch ( PATH_PROPERTIES[ target.path ] ) {
3773
+
3774
+ case PATH_PROPERTIES.weights:
3775
+
3776
+ TypedKeyframeTrack = THREE.NumberKeyframeTrack;
3777
+ break;
3778
+
3779
+ case PATH_PROPERTIES.rotation:
3780
+
3781
+ TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
3782
+ break;
3783
+
3784
+ case PATH_PROPERTIES.position:
3785
+ case PATH_PROPERTIES.scale:
3786
+ default:
3787
+
3788
+ TypedKeyframeTrack = THREE.VectorKeyframeTrack;
3789
+ break;
3790
+
3791
+ }
3792
+
3793
+ const targetName = node.name ? node.name : node.uuid;
3794
+
3795
+ const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
3796
+
3797
+ const targetNames = [];
3798
+
3799
+ if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
3800
+
3801
+ node.traverse( function ( object ) {
3802
+
3803
+ if ( object.morphTargetInfluences ) {
3804
+
3805
+ targetNames.push( object.name ? object.name : object.uuid );
3806
+
3807
+ }
3808
+
3809
+ } );
3810
+
3811
+ } else {
3812
+
3813
+ targetNames.push( targetName );
3814
+
3815
+ }
3816
+
3817
+ let outputArray = outputAccessor.array;
3818
+
3819
+ if ( outputAccessor.normalized ) {
3820
+
3821
+ const scale = getNormalizedComponentScale( outputArray.constructor );
3822
+ const scaled = new Float32Array( outputArray.length );
3823
+
3824
+ for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
3825
+
3826
+ scaled[ j ] = outputArray[ j ] * scale;
3827
+
3828
+ }
3829
+
3830
+ outputArray = scaled;
3831
+
3832
+ }
3833
+
3834
+ for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
3835
+
3836
+ const track = new TypedKeyframeTrack(
3837
+ targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
3838
+ inputAccessor.array,
3839
+ outputArray,
3840
+ interpolation
3841
+ );
3842
+
3843
+ // Override interpolation with custom factory method.
3844
+ if ( sampler.interpolation === 'CUBICSPLINE' ) {
3845
+
3846
+ track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
3847
+
3848
+ // A CUBICSPLINE keyframe in glTF has three output values for each input value,
3849
+ // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
3850
+ // must be divided by three to get the interpolant's sampleSize argument.
3851
+
3852
+ const interpolantType = ( this instanceof THREE.QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
3853
+
3854
+ return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
3855
+
3856
+ };
3857
+
3858
+ // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
3859
+ track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
3860
+
3861
+ }
3862
+
3863
+ tracks.push( track );
3864
+
3865
+ }
3866
+
3867
+ }
3868
+
3869
+ const name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
3870
+
3871
+ return new THREE.AnimationClip( name, undefined, tracks );
3872
+
3873
+ } );
3874
+
3875
+ }
3876
+
3877
+ createNodeMesh( nodeIndex ) {
3878
+
3879
+ const json = this.json;
3880
+ const parser = this;
3881
+ const nodeDef = json.nodes[ nodeIndex ];
3882
+
3883
+ if ( nodeDef.mesh === undefined ) return null;
3884
+
3885
+ return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
3886
+
3887
+ const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
3888
+
3889
+ // if weights are provided on the node, override weights on the mesh.
3890
+ if ( nodeDef.weights !== undefined ) {
3891
+
3892
+ node.traverse( function ( o ) {
3893
+
3894
+ if ( ! o.isMesh ) return;
3895
+
3896
+ for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
3897
+
3898
+ o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
3899
+
3900
+ }
3901
+
3902
+ } );
3903
+
3904
+ }
3905
+
3906
+ return node;
3907
+
3908
+ } );
3909
+
3910
+ }
3911
+
3912
+ /**
3913
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
3914
+ * @param {number} nodeIndex
3915
+ * @return {Promise<Object3D>}
3916
+ */
3917
+ loadNode( nodeIndex ) {
3918
+
3919
+ const json = this.json;
3920
+ const parser = this;
3921
+
3922
+ const nodeDef = json.nodes[ nodeIndex ];
3923
+
3924
+ const nodePending = parser._loadNodeShallow( nodeIndex );
3925
+
3926
+ const childPending = [];
3927
+ const childrenDef = nodeDef.children || [];
3928
+
3929
+ for ( let i = 0, il = childrenDef.length; i < il; i ++ ) {
3930
+
3931
+ childPending.push( parser.getDependency( 'node', childrenDef[ i ] ) );
3932
+
3933
+ }
3934
+
3935
+ const skeletonPending = nodeDef.skin === undefined
3936
+ ? Promise.resolve( null )
3937
+ : parser.getDependency( 'skin', nodeDef.skin );
3938
+
3939
+ return Promise.all( [
3940
+ nodePending,
3941
+ Promise.all( childPending ),
3942
+ skeletonPending
3943
+ ] ).then( function ( results ) {
3944
+
3945
+ const node = results[ 0 ];
3946
+ const children = results[ 1 ];
3947
+ const skeleton = results[ 2 ];
3948
+
3949
+ if ( skeleton !== null ) {
3950
+
3951
+ // This full traverse should be fine because
3952
+ // child glTF nodes have not been added to this node yet.
3953
+ node.traverse( function ( mesh ) {
3954
+
3955
+ if ( ! mesh.isSkinnedMesh ) return;
3956
+
3957
+ mesh.bind( skeleton, _identityMatrix );
3958
+
3959
+ } );
3960
+
3961
+ }
3962
+
3963
+ for ( let i = 0, il = children.length; i < il; i ++ ) {
3964
+
3965
+ node.add( children[ i ] );
3966
+
3967
+ }
3968
+
3969
+ return node;
3970
+
3971
+ } );
3972
+
3973
+ }
3974
+
3975
+ // ._loadNodeShallow() parses a single node.
3976
+ // skin and child nodes are created and added in .loadNode() (no '_' prefix).
3977
+ _loadNodeShallow( nodeIndex ) {
3978
+
3979
+ const json = this.json;
3980
+ const extensions = this.extensions;
3981
+ const parser = this;
3982
+
3983
+ // This method is called from .loadNode() and .loadSkin().
3984
+ // Cache a node to avoid duplication.
3985
+
3986
+ if ( this.nodeCache[ nodeIndex ] !== undefined ) {
3987
+
3988
+ return this.nodeCache[ nodeIndex ];
3989
+
3990
+ }
3991
+
3992
+ const nodeDef = json.nodes[ nodeIndex ];
3993
+
3994
+ // reserve node's name before its dependencies, so the root has the intended name.
3995
+ const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
3996
+
3997
+ const pending = [];
3998
+
3999
+ const meshPromise = parser._invokeOne( function ( ext ) {
4000
+
4001
+ return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
4002
+
4003
+ } );
4004
+
4005
+ if ( meshPromise ) {
4006
+
4007
+ pending.push( meshPromise );
4008
+
4009
+ }
4010
+
4011
+ if ( nodeDef.camera !== undefined ) {
4012
+
4013
+ pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
4014
+
4015
+ return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
4016
+
4017
+ } ) );
4018
+
4019
+ }
4020
+
4021
+ parser._invokeAll( function ( ext ) {
4022
+
4023
+ return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
4024
+
4025
+ } ).forEach( function ( promise ) {
4026
+
4027
+ pending.push( promise );
4028
+
4029
+ } );
4030
+
4031
+ this.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) {
4032
+
4033
+ let node;
4034
+
4035
+ // .isBone isn't in glTF spec. See ._markDefs
4036
+ if ( nodeDef.isBone === true ) {
4037
+
4038
+ node = new THREE.Bone();
4039
+
4040
+ } else if ( objects.length > 1 ) {
4041
+
4042
+ node = new THREE.Group();
4043
+
4044
+ } else if ( objects.length === 1 ) {
4045
+
4046
+ node = objects[ 0 ];
4047
+
4048
+ } else {
4049
+
4050
+ node = new THREE.Object3D();
4051
+
4052
+ }
4053
+
4054
+ if ( node !== objects[ 0 ] ) {
4055
+
4056
+ for ( let i = 0, il = objects.length; i < il; i ++ ) {
4057
+
4058
+ node.add( objects[ i ] );
4059
+
4060
+ }
4061
+
4062
+ }
4063
+
4064
+ if ( nodeDef.name ) {
4065
+
4066
+ node.userData.name = nodeDef.name;
4067
+ node.name = nodeName;
4068
+
4069
+ }
4070
+
4071
+ assignExtrasToUserData( node, nodeDef );
4072
+
4073
+ if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
4074
+
4075
+ if ( nodeDef.matrix !== undefined ) {
4076
+
4077
+ const matrix = new THREE.Matrix4();
4078
+ matrix.fromArray( nodeDef.matrix );
4079
+ node.applyMatrix4( matrix );
4080
+
4081
+ } else {
4082
+
4083
+ if ( nodeDef.translation !== undefined ) {
4084
+
4085
+ node.position.fromArray( nodeDef.translation );
4086
+
4087
+ }
4088
+
4089
+ if ( nodeDef.rotation !== undefined ) {
4090
+
4091
+ node.quaternion.fromArray( nodeDef.rotation );
4092
+
4093
+ }
4094
+
4095
+ if ( nodeDef.scale !== undefined ) {
4096
+
4097
+ node.scale.fromArray( nodeDef.scale );
4098
+
4099
+ }
4100
+
4101
+ }
4102
+
4103
+ if ( ! parser.associations.has( node ) ) {
4104
+
4105
+ parser.associations.set( node, {} );
4106
+
4107
+ }
4108
+
4109
+ parser.associations.get( node ).nodes = nodeIndex;
4110
+
4111
+ return node;
4112
+
4113
+ } );
4114
+
4115
+ return this.nodeCache[ nodeIndex ];
4116
+
4117
+ }
4118
+
4119
+ /**
4120
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
4121
+ * @param {number} sceneIndex
4122
+ * @return {Promise<Group>}
4123
+ */
4124
+ loadScene( sceneIndex ) {
4125
+
4126
+ const extensions = this.extensions;
4127
+ const sceneDef = this.json.scenes[ sceneIndex ];
4128
+ const parser = this;
4129
+
4130
+ // Loader returns Group, not Scene.
4131
+ // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
4132
+ const scene = new THREE.Group();
4133
+ if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
4134
+
4135
+ assignExtrasToUserData( scene, sceneDef );
4136
+
4137
+ if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
4138
+
4139
+ const nodeIds = sceneDef.nodes || [];
4140
+
4141
+ const pending = [];
4142
+
4143
+ for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
4144
+
4145
+ pending.push( parser.getDependency( 'node', nodeIds[ i ] ) );
4146
+
4147
+ }
4148
+
4149
+ return Promise.all( pending ).then( function ( nodes ) {
4150
+
4151
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
4152
+
4153
+ scene.add( nodes[ i ] );
4154
+
4155
+ }
4156
+
4157
+ // Removes dangling associations, associations that reference a node that
4158
+ // didn't make it into the scene.
4159
+ const reduceAssociations = ( node ) => {
4160
+
4161
+ const reducedAssociations = new Map();
4162
+
4163
+ for ( const [ key, value ] of parser.associations ) {
4164
+
4165
+ if ( key instanceof THREE.Material || key instanceof THREE.Texture ) {
4166
+
4167
+ reducedAssociations.set( key, value );
4168
+
4169
+ }
4170
+
4171
+ }
4172
+
4173
+ node.traverse( ( node ) => {
4174
+
4175
+ const mappings = parser.associations.get( node );
4176
+
4177
+ if ( mappings != null ) {
4178
+
4179
+ reducedAssociations.set( node, mappings );
4180
+
4181
+ }
4182
+
4183
+ } );
4184
+
4185
+ return reducedAssociations;
4186
+
4187
+ };
4188
+
4189
+ parser.associations = reduceAssociations( scene );
4190
+
4191
+ return scene;
4192
+
4193
+ } );
4194
+
4195
+ }
4196
+
4197
+ }
4198
+
4199
+ /**
4200
+ * @param {BufferGeometry} geometry
4201
+ * @param {GLTF.Primitive} primitiveDef
4202
+ * @param {GLTFParser} parser
4203
+ */
4204
+ function computeBounds( geometry, primitiveDef, parser ) {
4205
+
4206
+ const attributes = primitiveDef.attributes;
4207
+
4208
+ const box = new THREE.Box3();
4209
+
4210
+ if ( attributes.POSITION !== undefined ) {
4211
+
4212
+ const accessor = parser.json.accessors[ attributes.POSITION ];
4213
+
4214
+ const min = accessor.min;
4215
+ const max = accessor.max;
4216
+
4217
+ // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
4218
+
4219
+ if ( min !== undefined && max !== undefined ) {
4220
+
4221
+ box.set(
4222
+ new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
4223
+ new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )
4224
+ );
4225
+
4226
+ if ( accessor.normalized ) {
4227
+
4228
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
4229
+ box.min.multiplyScalar( boxScale );
4230
+ box.max.multiplyScalar( boxScale );
4231
+
4232
+ }
4233
+
4234
+ } else {
4235
+
4236
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
4237
+
4238
+ return;
4239
+
4240
+ }
4241
+
4242
+ } else {
4243
+
4244
+ return;
4245
+
4246
+ }
4247
+
4248
+ const targets = primitiveDef.targets;
4249
+
4250
+ if ( targets !== undefined ) {
4251
+
4252
+ const maxDisplacement = new THREE.Vector3();
4253
+ const vector = new THREE.Vector3();
4254
+
4255
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
4256
+
4257
+ const target = targets[ i ];
4258
+
4259
+ if ( target.POSITION !== undefined ) {
4260
+
4261
+ const accessor = parser.json.accessors[ target.POSITION ];
4262
+ const min = accessor.min;
4263
+ const max = accessor.max;
4264
+
4265
+ // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
4266
+
4267
+ if ( min !== undefined && max !== undefined ) {
4268
+
4269
+ // we need to get max of absolute components because target weight is [-1,1]
4270
+ vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
4271
+ vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
4272
+ vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
4273
+
4274
+
4275
+ if ( accessor.normalized ) {
4276
+
4277
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
4278
+ vector.multiplyScalar( boxScale );
4279
+
4280
+ }
4281
+
4282
+ // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
4283
+ // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
4284
+ // are used to implement key-frame animations and as such only two are active at a time - this results in very large
4285
+ // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
4286
+ maxDisplacement.max( vector );
4287
+
4288
+ } else {
4289
+
4290
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
4291
+
4292
+ }
4293
+
4294
+ }
4295
+
4296
+ }
4297
+
4298
+ // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
4299
+ box.expandByVector( maxDisplacement );
4300
+
4301
+ }
4302
+
4303
+ geometry.boundingBox = box;
4304
+
4305
+ const sphere = new THREE.Sphere();
4306
+
4307
+ box.getCenter( sphere.center );
4308
+ sphere.radius = box.min.distanceTo( box.max ) / 2;
4309
+
4310
+ geometry.boundingSphere = sphere;
4311
+
4312
+ }
4313
+
4314
+ /**
4315
+ * @param {BufferGeometry} geometry
4316
+ * @param {GLTF.Primitive} primitiveDef
4317
+ * @param {GLTFParser} parser
4318
+ * @return {Promise<BufferGeometry>}
4319
+ */
4320
+ function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
4321
+
4322
+ const attributes = primitiveDef.attributes;
4323
+
4324
+ const pending = [];
4325
+
4326
+ function assignAttributeAccessor( accessorIndex, attributeName ) {
4327
+
4328
+ return parser.getDependency( 'accessor', accessorIndex )
4329
+ .then( function ( accessor ) {
4330
+
4331
+ geometry.setAttribute( attributeName, accessor );
4332
+
4333
+ } );
4334
+
4335
+ }
4336
+
4337
+ for ( const gltfAttributeName in attributes ) {
4338
+
4339
+ const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
4340
+
4341
+ // Skip attributes already provided by e.g. Draco extension.
4342
+ if ( threeAttributeName in geometry.attributes ) continue;
4343
+
4344
+ pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
4345
+
4346
+ }
4347
+
4348
+ if ( primitiveDef.indices !== undefined && ! geometry.index ) {
4349
+
4350
+ const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
4351
+
4352
+ geometry.setIndex( accessor );
4353
+
4354
+ } );
4355
+
4356
+ pending.push( accessor );
4357
+
4358
+ }
4359
+
4360
+ assignExtrasToUserData( geometry, primitiveDef );
4361
+
4362
+ computeBounds( geometry, primitiveDef, parser );
4363
+
4364
+ return Promise.all( pending ).then( function () {
4365
+
4366
+ return primitiveDef.targets !== undefined
4367
+ ? addMorphTargets( geometry, primitiveDef.targets, parser )
4368
+ : geometry;
4369
+
4370
+ } );
4371
+
4372
+ }
4373
+
4374
+ exports.GLTFLoader = GLTFLoader;