@ohuoy/easymap 1.0.19 → 1.0.21

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