@inweb/viewer-three 26.6.6 → 26.6.7

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