viral-viewer-2 6.2.8 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/dist/components/loader/viral-revit.loader.js +8 -3
  2. package/dist/components/loader/viral-revit.loader.js.map +1 -1
  3. package/dist/index.mjs +41153 -0
  4. package/package.json +1 -1
  5. package/dist/components/centralized-event-handler/viral-centralized-event-handler.d.ts +0 -7
  6. package/dist/components/centralized-event-handler/viral-centralized-event-handler.js +0 -47
  7. package/dist/components/centralized-event-handler/viral-centralized-event-handler.js.map +0 -1
  8. package/dist/components/compress/compress.processor.d.ts +0 -4
  9. package/dist/components/compress/compress.processor.js +0 -29
  10. package/dist/components/compress/compress.processor.js.map +0 -1
  11. package/dist/components/context-menu/viral-context-menu.d.ts +0 -17
  12. package/dist/components/context-menu/viral-context-menu.js +0 -74
  13. package/dist/components/context-menu/viral-context-menu.js.map +0 -1
  14. package/dist/components/keyboard/viral-keyboard.d.ts +0 -17
  15. package/dist/components/keyboard/viral-keyboard.js +0 -76
  16. package/dist/components/keyboard/viral-keyboard.js.map +0 -1
  17. package/dist/components/loader/viral-viewer-point-cloud.loader.d.ts +0 -16
  18. package/dist/components/loader/viral-viewer-point-cloud.loader.js +0 -33
  19. package/dist/components/loader/viral-viewer-point-cloud.loader.js.map +0 -1
  20. package/dist/components/loader/viral-viewer-revit.loader.d.ts +0 -13
  21. package/dist/components/loader/viral-viewer-revit.loader.js +0 -124
  22. package/dist/components/loader/viral-viewer-revit.loader.js.map +0 -1
  23. package/dist/components/mouse/viral-mouse.d.ts +0 -31
  24. package/dist/components/mouse/viral-mouse.js +0 -234
  25. package/dist/components/mouse/viral-mouse.js.map +0 -1
  26. package/dist/components/navigation-cube/components/cube-camera.d.ts +0 -15
  27. package/dist/components/navigation-cube/components/cube-camera.js +0 -74
  28. package/dist/components/navigation-cube/components/cube-camera.js.map +0 -1
  29. package/dist/components/navigation-cube/components/cube-renderer.d.ts +0 -9
  30. package/dist/components/navigation-cube/components/cube-renderer.js +0 -31
  31. package/dist/components/navigation-cube/components/cube-renderer.js.map +0 -1
  32. package/dist/components/navigation-cube/components/cube-scene.d.ts +0 -13
  33. package/dist/components/navigation-cube/components/cube-scene.js +0 -546
  34. package/dist/components/navigation-cube/components/cube-scene.js.map +0 -1
  35. package/dist/components/navigation-cube/components/cube.mouse.d.ts +0 -9
  36. package/dist/components/navigation-cube/components/cube.mouse.js +0 -109
  37. package/dist/components/navigation-cube/components/cube.mouse.js.map +0 -1
  38. package/dist/components/navigation-cube/viral-navigation-cube.d.ts +0 -16
  39. package/dist/components/navigation-cube/viral-navigation-cube.js +0 -50
  40. package/dist/components/navigation-cube/viral-navigation-cube.js.map +0 -1
  41. package/dist/components/post-processing/ambient-occlusion-effect.d.ts +0 -13
  42. package/dist/components/post-processing/ambient-occlusion-effect.js +0 -33
  43. package/dist/components/post-processing/ambient-occlusion-effect.js.map +0 -1
  44. package/dist/components/post-processing/bloom-effect.d.ts +0 -11
  45. package/dist/components/post-processing/bloom-effect.js +0 -29
  46. package/dist/components/post-processing/bloom-effect.js.map +0 -1
  47. package/dist/components/post-processing/outline-effect.d.ts +0 -13
  48. package/dist/components/post-processing/outline-effect.js +0 -33
  49. package/dist/components/post-processing/outline-effect.js.map +0 -1
  50. package/dist/components/spinner/viral-spinner.d.ts +0 -10
  51. package/dist/components/spinner/viral-spinner.js +0 -207
  52. package/dist/components/spinner/viral-spinner.js.map +0 -1
  53. package/dist/components/tools/tools/viral-tool-ambient-occlusion.d.ts +0 -7
  54. package/dist/components/tools/tools/viral-tool-ambient-occlusion.js +0 -16
  55. package/dist/components/tools/tools/viral-tool-ambient-occlusion.js.map +0 -1
  56. package/dist/components/tools/tools/viral-tool-dark-mode.d.ts +0 -7
  57. package/dist/components/tools/tools/viral-tool-dark-mode.js +0 -21
  58. package/dist/components/tools/tools/viral-tool-dark-mode.js.map +0 -1
  59. package/dist/components/tools/tools/viral-tool-elevation.d.ts +0 -11
  60. package/dist/components/tools/tools/viral-tool-elevation.js +0 -30
  61. package/dist/components/tools/tools/viral-tool-elevation.js.map +0 -1
  62. package/dist/components/tools/tools/viral-tool-measure.d.ts +0 -33
  63. package/dist/components/tools/tools/viral-tool-measure.js +0 -243
  64. package/dist/components/tools/tools/viral-tool-measure.js.map +0 -1
  65. package/dist/components/tools/tools/viral-tool-sunlight.d.ts +0 -7
  66. package/dist/components/tools/tools/viral-tool-sunlight.js +0 -46
  67. package/dist/components/tools/tools/viral-tool-sunlight.js.map +0 -1
  68. package/dist/components/tools/viral-tools.d.ts +0 -32
  69. package/dist/components/tools/viral-tools.js +0 -213
  70. package/dist/components/tools/viral-tools.js.map +0 -1
  71. package/dist/components/worker/load-model.d.ts +0 -126
  72. package/dist/components/worker/load-model.js +0 -1265
  73. package/dist/components/worker/load-model.js.map +0 -1
  74. package/dist/components/worker/test-worker-pool.d.ts +0 -6
  75. package/dist/components/worker/test-worker-pool.js +0 -21
  76. package/dist/components/worker/test-worker-pool.js.map +0 -1
  77. package/dist/components/worker/viral-viewer-4.worker.d.ts +0 -10
  78. package/dist/components/worker/viral-viewer-4.worker.js +0 -97
  79. package/dist/components/worker/viral-viewer-4.worker.js.map +0 -1
  80. package/dist/components/worker/viral-viewer.worker-pool.d.ts +0 -0
  81. package/dist/components/worker/viral-viewer.worker-pool.js +0 -61
  82. package/dist/components/worker/viral-viewer.worker-pool.js.map +0 -1
  83. package/dist/components/worker/worker-pool.d.ts +0 -21
  84. package/dist/components/worker/worker-pool.js +0 -47
  85. package/dist/components/worker/worker-pool.js.map +0 -1
  86. package/dist/components/worker/worker-thread.d.ts +0 -9
  87. package/dist/components/worker/worker-thread.js +0 -30
  88. package/dist/components/worker/worker-thread.js.map +0 -1
  89. package/dist/components/worker-script/load-model-worker-3.script.d.ts +0 -1
  90. package/dist/components/worker-script/load-model-worker-3.script.js +0 -34170
  91. package/dist/components/worker-script/load-model-worker-3.script.js.map +0 -1
  92. package/dist/components/worker-script/test-worker-pool.script.d.ts +0 -1
  93. package/dist/components/worker-script/test-worker-pool.script.js +0 -12
  94. package/dist/components/worker-script/test-worker-pool.script.js.map +0 -1
  95. package/dist/models/dictionary.model.d.ts +0 -10
  96. package/dist/models/dictionary.model.js +0 -42
  97. package/dist/models/dictionary.model.js.map +0 -1
  98. package/dist/threejs-addon/buffer-geometry-utils.d.ts +0 -64
  99. package/dist/threejs-addon/buffer-geometry-utils.js +0 -807
  100. package/dist/threejs-addon/buffer-geometry-utils.js.map +0 -1
  101. package/dist/threejs-addon/gltf-loader.d.ts +0 -17
  102. package/dist/threejs-addon/gltf-loader.js +0 -2796
  103. package/dist/threejs-addon/gltf-loader.js.map +0 -1
  104. package/dist/threejs-addon/post-processing/effect-composer.d.ts +0 -27
  105. package/dist/threejs-addon/post-processing/effect-composer.js +0 -134
  106. package/dist/threejs-addon/post-processing/effect-composer.js.map +0 -1
  107. package/dist/threejs-addon/post-processing/mask-pass.d.ts +0 -11
  108. package/dist/threejs-addon/post-processing/mask-pass.js +0 -69
  109. package/dist/threejs-addon/post-processing/mask-pass.js.map +0 -1
  110. package/dist/threejs-addon/post-processing/outline-pass.d.ts +0 -58
  111. package/dist/threejs-addon/post-processing/outline-pass.js +0 -484
  112. package/dist/threejs-addon/post-processing/outline-pass.js.map +0 -1
  113. package/dist/threejs-addon/post-processing/output-pass.d.ts +0 -11
  114. package/dist/threejs-addon/post-processing/output-pass.js +0 -61
  115. package/dist/threejs-addon/post-processing/output-pass.js.map +0 -1
  116. package/dist/threejs-addon/post-processing/pass.d.ts +0 -20
  117. package/dist/threejs-addon/post-processing/pass.js +0 -48
  118. package/dist/threejs-addon/post-processing/pass.js.map +0 -1
  119. package/dist/threejs-addon/post-processing/render-pass.d.ts +0 -13
  120. package/dist/threejs-addon/post-processing/render-pass.js +0 -50
  121. package/dist/threejs-addon/post-processing/render-pass.js.map +0 -1
  122. package/dist/threejs-addon/post-processing/sao-pass.d.ts +0 -62
  123. package/dist/threejs-addon/post-processing/sao-pass.js +0 -296
  124. package/dist/threejs-addon/post-processing/sao-pass.js.map +0 -1
  125. package/dist/threejs-addon/post-processing/shader-pass.d.ts +0 -11
  126. package/dist/threejs-addon/post-processing/shader-pass.js +0 -48
  127. package/dist/threejs-addon/post-processing/shader-pass.js.map +0 -1
  128. package/dist/threejs-addon/post-processing/unreal-bloom-pass.d.ts +0 -48
  129. package/dist/threejs-addon/post-processing/unreal-bloom-pass.js +0 -290
  130. package/dist/threejs-addon/post-processing/unreal-bloom-pass.js.map +0 -1
  131. package/dist/threejs-addon/shaders/copy-shader.d.ts +0 -13
  132. package/dist/threejs-addon/shaders/copy-shader.js +0 -39
  133. package/dist/threejs-addon/shaders/copy-shader.js.map +0 -1
  134. package/dist/threejs-addon/shaders/depth-limited-blur-shader.d.ts +0 -48
  135. package/dist/threejs-addon/shaders/depth-limited-blur-shader.js +0 -142
  136. package/dist/threejs-addon/shaders/depth-limited-blur-shader.js.map +0 -1
  137. package/dist/threejs-addon/shaders/luminosity-high-pass-shader.d.ts +0 -27
  138. package/dist/threejs-addon/shaders/luminosity-high-pass-shader.js +0 -56
  139. package/dist/threejs-addon/shaders/luminosity-high-pass-shader.js.map +0 -1
  140. package/dist/threejs-addon/shaders/output-shader.d.ts +0 -13
  141. package/dist/threejs-addon/shaders/output-shader.js +0 -72
  142. package/dist/threejs-addon/shaders/output-shader.js.map +0 -1
  143. package/dist/threejs-addon/shaders/sao-shader.d.ts +0 -71
  144. package/dist/threejs-addon/shaders/sao-shader.js +0 -180
  145. package/dist/threejs-addon/shaders/sao-shader.js.map +0 -1
  146. package/dist/threejs-addon/shaders/unpack-depth-rgba-shader.d.ts +0 -13
  147. package/dist/threejs-addon/shaders/unpack-depth-rgba-shader.js +0 -41
  148. package/dist/threejs-addon/shaders/unpack-depth-rgba-shader.js.map +0 -1
  149. package/dist/threejs-addon/simplify-modifier.d.ts +0 -4
  150. package/dist/threejs-addon/simplify-modifier.js +0 -325
  151. package/dist/threejs-addon/simplify-modifier.js.map +0 -1
  152. package/dist/threejs-addon/transform-control.d.ts +0 -74
  153. package/dist/threejs-addon/transform-control.js +0 -1033
  154. package/dist/threejs-addon/transform-control.js.map +0 -1
@@ -1,2796 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GLTFLoader = void 0;
4
- const three_1 = require("three");
5
- const buffer_geometry_utils_1 = require("./buffer-geometry-utils");
6
- class GLTFLoader extends three_1.Loader {
7
- constructor(manager) {
8
- super(manager);
9
- this.dracoLoader = null;
10
- this.ktx2Loader = null;
11
- this.meshoptDecoder = null;
12
- this.pluginCallbacks = [];
13
- this.register(function (parser) {
14
- return new GLTFMaterialsClearcoatExtension(parser);
15
- });
16
- this.register(function (parser) {
17
- return new GLTFTextureBasisUExtension(parser);
18
- });
19
- this.register(function (parser) {
20
- return new GLTFTextureWebPExtension(parser);
21
- });
22
- this.register(function (parser) {
23
- return new GLTFTextureAVIFExtension(parser);
24
- });
25
- this.register(function (parser) {
26
- return new GLTFMaterialsSheenExtension(parser);
27
- });
28
- this.register(function (parser) {
29
- return new GLTFMaterialsTransmissionExtension(parser);
30
- });
31
- this.register(function (parser) {
32
- return new GLTFMaterialsVolumeExtension(parser);
33
- });
34
- this.register(function (parser) {
35
- return new GLTFMaterialsIorExtension(parser);
36
- });
37
- this.register(function (parser) {
38
- return new GLTFMaterialsEmissiveStrengthExtension(parser);
39
- });
40
- this.register(function (parser) {
41
- return new GLTFMaterialsSpecularExtension(parser);
42
- });
43
- this.register(function (parser) {
44
- return new GLTFMaterialsIridescenceExtension(parser);
45
- });
46
- this.register(function (parser) {
47
- return new GLTFMaterialsAnisotropyExtension(parser);
48
- });
49
- this.register(function (parser) {
50
- return new GLTFLightsExtension(parser);
51
- });
52
- this.register(function (parser) {
53
- return new GLTFMeshoptCompression(parser);
54
- });
55
- this.register(function (parser) {
56
- return new GLTFMeshGpuInstancing(parser);
57
- });
58
- }
59
- load(url, onLoad, onProgress, onError) {
60
- const scope = this;
61
- let resourcePath;
62
- if (this.resourcePath !== '') {
63
- resourcePath = this.resourcePath;
64
- }
65
- else if (this.path !== '') {
66
- resourcePath = this.path;
67
- }
68
- else {
69
- resourcePath = three_1.LoaderUtils.extractUrlBase(url);
70
- }
71
- // Tells the LoadingManager to track an extra item, which resolves after
72
- // the model is fully loaded. This means the count of items loaded will
73
- // be incorrect, but ensures manager.onLoad() does not fire early.
74
- this.manager.itemStart(url);
75
- const _onError = function (e) {
76
- if (onError) {
77
- onError(e);
78
- }
79
- else {
80
- console.error(e);
81
- }
82
- scope.manager.itemError(url);
83
- scope.manager.itemEnd(url);
84
- };
85
- const loader = new three_1.FileLoader(this.manager);
86
- loader.setPath(this.path);
87
- loader.setResponseType('arraybuffer');
88
- loader.setRequestHeader(this.requestHeader);
89
- loader.setWithCredentials(this.withCredentials);
90
- loader.load(url, function (data) {
91
- try {
92
- scope.parse(data, resourcePath, function (gltf) {
93
- onLoad(gltf);
94
- scope.manager.itemEnd(url);
95
- }, _onError);
96
- }
97
- catch (e) {
98
- _onError(e);
99
- }
100
- }, onProgress, _onError);
101
- }
102
- setDRACOLoader(dracoLoader) {
103
- this.dracoLoader = dracoLoader;
104
- return this;
105
- }
106
- setDDSLoader() {
107
- throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".');
108
- }
109
- setKTX2Loader(ktx2Loader) {
110
- this.ktx2Loader = ktx2Loader;
111
- return this;
112
- }
113
- setMeshoptDecoder(meshoptDecoder) {
114
- this.meshoptDecoder = meshoptDecoder;
115
- return this;
116
- }
117
- register(callback) {
118
- if (this.pluginCallbacks.indexOf(callback) === -1) {
119
- this.pluginCallbacks.push(callback);
120
- }
121
- return this;
122
- }
123
- unregister(callback) {
124
- if (this.pluginCallbacks.indexOf(callback) !== -1) {
125
- this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1);
126
- }
127
- return this;
128
- }
129
- parse(data, path, onLoad, onError) {
130
- let json;
131
- const extensions = {};
132
- const plugins = {};
133
- const textDecoder = new TextDecoder();
134
- if (typeof data === 'string') {
135
- json = JSON.parse(data);
136
- }
137
- else if (data instanceof ArrayBuffer) {
138
- const magic = textDecoder.decode(new Uint8Array(data, 0, 4));
139
- if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
140
- try {
141
- extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
142
- }
143
- catch (error) {
144
- if (onError)
145
- onError(error);
146
- return;
147
- }
148
- json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content);
149
- }
150
- else {
151
- json = JSON.parse(textDecoder.decode(data));
152
- }
153
- }
154
- else {
155
- json = data;
156
- }
157
- if (json.asset === undefined || json.asset.version[0] < 2) {
158
- if (onError)
159
- onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
160
- return;
161
- }
162
- const parser = new GLTFParser(json, {
163
- path: path || this.resourcePath || '',
164
- crossOrigin: this.crossOrigin,
165
- requestHeader: this.requestHeader,
166
- manager: this.manager,
167
- ktx2Loader: this.ktx2Loader,
168
- meshoptDecoder: this.meshoptDecoder
169
- });
170
- parser.fileLoader.setRequestHeader(this.requestHeader);
171
- for (let i = 0; i < this.pluginCallbacks.length; i++) {
172
- const plugin = this.pluginCallbacks[i](parser);
173
- plugins[plugin.name] = plugin;
174
- // Workaround to avoid determining as unknown extension
175
- // in addUnknownExtensionsToUserData().
176
- // Remove this workaround if we move all the existing
177
- // extension handlers to plugin system
178
- extensions[plugin.name] = true;
179
- }
180
- if (json.extensionsUsed) {
181
- for (let i = 0; i < json.extensionsUsed.length; ++i) {
182
- const extensionName = json.extensionsUsed[i];
183
- const extensionsRequired = json.extensionsRequired || [];
184
- switch (extensionName) {
185
- case EXTENSIONS.KHR_MATERIALS_UNLIT:
186
- extensions[extensionName] = new GLTFMaterialsUnlitExtension();
187
- break;
188
- case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
189
- extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
190
- break;
191
- case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
192
- extensions[extensionName] = new GLTFTextureTransformExtension();
193
- break;
194
- case EXTENSIONS.KHR_MESH_QUANTIZATION:
195
- extensions[extensionName] = new GLTFMeshQuantizationExtension();
196
- break;
197
- default:
198
- if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) {
199
- console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
200
- }
201
- }
202
- }
203
- }
204
- parser.setExtensions(extensions);
205
- parser.setPlugins(plugins);
206
- parser.parse(onLoad, onError);
207
- }
208
- parseAsync(data, path) {
209
- const scope = this;
210
- return new Promise(function (resolve, reject) {
211
- scope.parse(data, path, resolve, reject);
212
- });
213
- }
214
- }
215
- exports.GLTFLoader = GLTFLoader;
216
- /* GLTFREGISTRY */
217
- function GLTFRegistry() {
218
- let objects = {};
219
- return {
220
- get: function (key) {
221
- return objects[key];
222
- },
223
- add: function (key, object) {
224
- objects[key] = object;
225
- },
226
- remove: function (key) {
227
- delete objects[key];
228
- },
229
- removeAll: function () {
230
- objects = {};
231
- }
232
- };
233
- }
234
- /*********************************/
235
- /********** EXTENSIONS ***********/
236
- /*********************************/
237
- const EXTENSIONS = {
238
- KHR_BINARY_GLTF: 'KHR_binary_glTF',
239
- KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
240
- KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
241
- KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
242
- KHR_MATERIALS_IOR: 'KHR_materials_ior',
243
- KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
244
- KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
245
- KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
246
- KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
247
- KHR_MATERIALS_ANISOTROPY: 'KHR_materials_anisotropy',
248
- KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
249
- KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
250
- KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
251
- KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
252
- KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
253
- KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
254
- EXT_TEXTURE_WEBP: 'EXT_texture_webp',
255
- EXT_TEXTURE_AVIF: 'EXT_texture_avif',
256
- EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
257
- EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
258
- };
259
- /**
260
- * Punctual Lights Extension
261
- *
262
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
263
- */
264
- class GLTFLightsExtension {
265
- constructor(parser) {
266
- this.parser = parser;
267
- this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
268
- // Object3D instance caches
269
- this.cache = { refs: {}, uses: {} };
270
- }
271
- _markDefs() {
272
- const parser = this.parser;
273
- const nodeDefs = this.parser.json.nodes || [];
274
- for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
275
- const nodeDef = nodeDefs[nodeIndex];
276
- if (nodeDef.extensions
277
- && nodeDef.extensions[this.name]
278
- && nodeDef.extensions[this.name].light !== undefined) {
279
- parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light);
280
- }
281
- }
282
- }
283
- _loadLight(lightIndex) {
284
- const parser = this.parser;
285
- const cacheKey = 'light:' + lightIndex;
286
- let dependency = parser.cache.get(cacheKey);
287
- if (dependency)
288
- return dependency;
289
- const json = parser.json;
290
- const extensions = (json.extensions && json.extensions[this.name]) || {};
291
- const lightDefs = extensions.lights || [];
292
- const lightDef = lightDefs[lightIndex];
293
- let lightNode;
294
- const color = new three_1.Color(0xffffff);
295
- if (lightDef.color !== undefined)
296
- color.setRGB(lightDef.color[0], lightDef.color[1], lightDef.color[2], three_1.LinearSRGBColorSpace);
297
- const range = lightDef.range !== undefined ? lightDef.range : 0;
298
- switch (lightDef.type) {
299
- case 'directional':
300
- lightNode = new three_1.DirectionalLight(color);
301
- lightNode.target.position.set(0, 0, -1);
302
- lightNode.add(lightNode.target);
303
- break;
304
- case 'point':
305
- lightNode = new three_1.PointLight(color);
306
- lightNode.distance = range;
307
- break;
308
- case 'spot':
309
- lightNode = new three_1.SpotLight(color);
310
- lightNode.distance = range;
311
- // Handle spotlight properties.
312
- lightDef.spot = lightDef.spot || {};
313
- lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
314
- lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
315
- lightNode.angle = lightDef.spot.outerConeAngle;
316
- lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
317
- lightNode.target.position.set(0, 0, -1);
318
- lightNode.add(lightNode.target);
319
- break;
320
- default:
321
- throw new Error('THREE.GLTFLoader: Unexpected light type: ' + lightDef.type);
322
- }
323
- // Some lights (e.g. spot) default to a position other than the origin. Reset the position
324
- // here, because node-level parsing will only override position if explicitly specified.
325
- lightNode.position.set(0, 0, 0);
326
- lightNode.decay = 2;
327
- assignExtrasToUserData(lightNode, lightDef);
328
- if (lightDef.intensity !== undefined)
329
- lightNode.intensity = lightDef.intensity;
330
- lightNode.name = parser.createUniqueName(lightDef.name || ('light_' + lightIndex));
331
- dependency = Promise.resolve(lightNode);
332
- parser.cache.add(cacheKey, dependency);
333
- return dependency;
334
- }
335
- getDependency(type, index) {
336
- if (type !== 'light')
337
- return;
338
- return this._loadLight(index);
339
- }
340
- createNodeAttachment(nodeIndex) {
341
- const self = this;
342
- const parser = this.parser;
343
- const json = parser.json;
344
- const nodeDef = json.nodes[nodeIndex];
345
- const lightDef = (nodeDef.extensions && nodeDef.extensions[this.name]) || {};
346
- const lightIndex = lightDef.light;
347
- if (lightIndex === undefined)
348
- return null;
349
- return this._loadLight(lightIndex).then(function (light) {
350
- return parser._getNodeRef(self.cache, lightIndex, light);
351
- });
352
- }
353
- }
354
- /**
355
- * Unlit Materials Extension
356
- *
357
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
358
- */
359
- class GLTFMaterialsUnlitExtension {
360
- constructor() {
361
- this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
362
- }
363
- getMaterialType() {
364
- return three_1.MeshBasicMaterial;
365
- }
366
- extendParams(materialParams, materialDef, parser) {
367
- const pending = [];
368
- materialParams.color = new three_1.Color(1.0, 1.0, 1.0);
369
- materialParams.opacity = 1.0;
370
- const metallicRoughness = materialDef.pbrMetallicRoughness;
371
- if (metallicRoughness) {
372
- if (Array.isArray(metallicRoughness.baseColorFactor)) {
373
- const array = metallicRoughness.baseColorFactor;
374
- materialParams.color.setRGB(array[0], array[1], array[2], three_1.LinearSRGBColorSpace);
375
- materialParams.opacity = array[3];
376
- }
377
- if (metallicRoughness.baseColorTexture !== undefined) {
378
- pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, three_1.SRGBColorSpace));
379
- }
380
- }
381
- return Promise.all(pending);
382
- }
383
- }
384
- /**
385
- * Materials Emissive Strength Extension
386
- *
387
- * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
388
- */
389
- class GLTFMaterialsEmissiveStrengthExtension {
390
- constructor(parser) {
391
- this.parser = parser;
392
- this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
393
- }
394
- extendMaterialParams(materialIndex, materialParams) {
395
- const parser = this.parser;
396
- const materialDef = parser.json.materials[materialIndex];
397
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
398
- return Promise.resolve();
399
- }
400
- const emissiveStrength = materialDef.extensions[this.name].emissiveStrength;
401
- if (emissiveStrength !== undefined) {
402
- materialParams.emissiveIntensity = emissiveStrength;
403
- }
404
- return Promise.resolve();
405
- }
406
- }
407
- /**
408
- * Clearcoat Materials Extension
409
- *
410
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
411
- */
412
- class GLTFMaterialsClearcoatExtension {
413
- constructor(parser) {
414
- this.parser = parser;
415
- this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
416
- }
417
- getMaterialType(materialIndex) {
418
- const parser = this.parser;
419
- const materialDef = parser.json.materials[materialIndex];
420
- if (!materialDef.extensions || !materialDef.extensions[this.name])
421
- return null;
422
- return three_1.MeshPhysicalMaterial;
423
- }
424
- extendMaterialParams(materialIndex, materialParams) {
425
- const parser = this.parser;
426
- const materialDef = parser.json.materials[materialIndex];
427
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
428
- return Promise.resolve();
429
- }
430
- const pending = [];
431
- const extension = materialDef.extensions[this.name];
432
- if (extension.clearcoatFactor !== undefined) {
433
- materialParams.clearcoat = extension.clearcoatFactor;
434
- }
435
- if (extension.clearcoatTexture !== undefined) {
436
- pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
437
- }
438
- if (extension.clearcoatRoughnessFactor !== undefined) {
439
- materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
440
- }
441
- if (extension.clearcoatRoughnessTexture !== undefined) {
442
- pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
443
- }
444
- if (extension.clearcoatNormalTexture !== undefined) {
445
- pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
446
- if (extension.clearcoatNormalTexture.scale !== undefined) {
447
- const scale = extension.clearcoatNormalTexture.scale;
448
- materialParams.clearcoatNormalScale = new three_1.Vector2(scale, scale);
449
- }
450
- }
451
- return Promise.all(pending);
452
- }
453
- }
454
- /**
455
- * Iridescence Materials Extension
456
- *
457
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
458
- */
459
- class GLTFMaterialsIridescenceExtension {
460
- constructor(parser) {
461
- this.parser = parser;
462
- this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
463
- }
464
- getMaterialType(materialIndex) {
465
- const parser = this.parser;
466
- const materialDef = parser.json.materials[materialIndex];
467
- if (!materialDef.extensions || !materialDef.extensions[this.name])
468
- return null;
469
- return three_1.MeshPhysicalMaterial;
470
- }
471
- extendMaterialParams(materialIndex, materialParams) {
472
- const parser = this.parser;
473
- const materialDef = parser.json.materials[materialIndex];
474
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
475
- return Promise.resolve();
476
- }
477
- const pending = [];
478
- const extension = materialDef.extensions[this.name];
479
- if (extension.iridescenceFactor !== undefined) {
480
- materialParams.iridescence = extension.iridescenceFactor;
481
- }
482
- if (extension.iridescenceTexture !== undefined) {
483
- pending.push(parser.assignTexture(materialParams, 'iridescenceMap', extension.iridescenceTexture));
484
- }
485
- if (extension.iridescenceIor !== undefined) {
486
- materialParams.iridescenceIOR = extension.iridescenceIor;
487
- }
488
- if (materialParams.iridescenceThicknessRange === undefined) {
489
- materialParams.iridescenceThicknessRange = [100, 400];
490
- }
491
- if (extension.iridescenceThicknessMinimum !== undefined) {
492
- materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum;
493
- }
494
- if (extension.iridescenceThicknessMaximum !== undefined) {
495
- materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum;
496
- }
497
- if (extension.iridescenceThicknessTexture !== undefined) {
498
- pending.push(parser.assignTexture(materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture));
499
- }
500
- return Promise.all(pending);
501
- }
502
- }
503
- /**
504
- * Sheen Materials Extension
505
- *
506
- * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
507
- */
508
- class GLTFMaterialsSheenExtension {
509
- constructor(parser) {
510
- this.parser = parser;
511
- this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
512
- }
513
- getMaterialType(materialIndex) {
514
- const parser = this.parser;
515
- const materialDef = parser.json.materials[materialIndex];
516
- if (!materialDef.extensions || !materialDef.extensions[this.name])
517
- return null;
518
- return three_1.MeshPhysicalMaterial;
519
- }
520
- extendMaterialParams(materialIndex, materialParams) {
521
- const parser = this.parser;
522
- const materialDef = parser.json.materials[materialIndex];
523
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
524
- return Promise.resolve();
525
- }
526
- const pending = [];
527
- materialParams.sheenColor = new three_1.Color(0, 0, 0);
528
- materialParams.sheenRoughness = 0;
529
- materialParams.sheen = 1;
530
- const extension = materialDef.extensions[this.name];
531
- if (extension.sheenColorFactor !== undefined) {
532
- const colorFactor = extension.sheenColorFactor;
533
- materialParams.sheenColor.setRGB(colorFactor[0], colorFactor[1], colorFactor[2], three_1.LinearSRGBColorSpace);
534
- }
535
- if (extension.sheenRoughnessFactor !== undefined) {
536
- materialParams.sheenRoughness = extension.sheenRoughnessFactor;
537
- }
538
- if (extension.sheenColorTexture !== undefined) {
539
- pending.push(parser.assignTexture(materialParams, 'sheenColorMap', extension.sheenColorTexture, three_1.SRGBColorSpace));
540
- }
541
- if (extension.sheenRoughnessTexture !== undefined) {
542
- pending.push(parser.assignTexture(materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture));
543
- }
544
- return Promise.all(pending);
545
- }
546
- }
547
- /**
548
- * Transmission Materials Extension
549
- *
550
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
551
- * Draft: https://github.com/KhronosGroup/glTF/pull/1698
552
- */
553
- class GLTFMaterialsTransmissionExtension {
554
- constructor(parser) {
555
- this.parser = parser;
556
- this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
557
- }
558
- getMaterialType(materialIndex) {
559
- const parser = this.parser;
560
- const materialDef = parser.json.materials[materialIndex];
561
- if (!materialDef.extensions || !materialDef.extensions[this.name])
562
- return null;
563
- return three_1.MeshPhysicalMaterial;
564
- }
565
- extendMaterialParams(materialIndex, materialParams) {
566
- const parser = this.parser;
567
- const materialDef = parser.json.materials[materialIndex];
568
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
569
- return Promise.resolve();
570
- }
571
- const pending = [];
572
- const extension = materialDef.extensions[this.name];
573
- if (extension.transmissionFactor !== undefined) {
574
- materialParams.transmission = extension.transmissionFactor;
575
- }
576
- if (extension.transmissionTexture !== undefined) {
577
- pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture));
578
- }
579
- return Promise.all(pending);
580
- }
581
- }
582
- /**
583
- * Materials Volume Extension
584
- *
585
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
586
- */
587
- class GLTFMaterialsVolumeExtension {
588
- constructor(parser) {
589
- this.parser = parser;
590
- this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
591
- }
592
- getMaterialType(materialIndex) {
593
- const parser = this.parser;
594
- const materialDef = parser.json.materials[materialIndex];
595
- if (!materialDef.extensions || !materialDef.extensions[this.name])
596
- return null;
597
- return three_1.MeshPhysicalMaterial;
598
- }
599
- extendMaterialParams(materialIndex, materialParams) {
600
- const parser = this.parser;
601
- const materialDef = parser.json.materials[materialIndex];
602
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
603
- return Promise.resolve();
604
- }
605
- const pending = [];
606
- const extension = materialDef.extensions[this.name];
607
- materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
608
- if (extension.thicknessTexture !== undefined) {
609
- pending.push(parser.assignTexture(materialParams, 'thicknessMap', extension.thicknessTexture));
610
- }
611
- materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
612
- const colorArray = extension.attenuationColor || [1, 1, 1];
613
- materialParams.attenuationColor = new three_1.Color().setRGB(colorArray[0], colorArray[1], colorArray[2], three_1.LinearSRGBColorSpace);
614
- return Promise.all(pending);
615
- }
616
- }
617
- /**
618
- * Materials ior Extension
619
- *
620
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
621
- */
622
- class GLTFMaterialsIorExtension {
623
- constructor(parser) {
624
- this.parser = parser;
625
- this.name = EXTENSIONS.KHR_MATERIALS_IOR;
626
- }
627
- getMaterialType(materialIndex) {
628
- const parser = this.parser;
629
- const materialDef = parser.json.materials[materialIndex];
630
- if (!materialDef.extensions || !materialDef.extensions[this.name])
631
- return null;
632
- return three_1.MeshPhysicalMaterial;
633
- }
634
- extendMaterialParams(materialIndex, materialParams) {
635
- const parser = this.parser;
636
- const materialDef = parser.json.materials[materialIndex];
637
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
638
- return Promise.resolve();
639
- }
640
- const extension = materialDef.extensions[this.name];
641
- materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
642
- return Promise.resolve();
643
- }
644
- }
645
- /**
646
- * Materials specular Extension
647
- *
648
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
649
- */
650
- class GLTFMaterialsSpecularExtension {
651
- constructor(parser) {
652
- this.parser = parser;
653
- this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
654
- }
655
- getMaterialType(materialIndex) {
656
- const parser = this.parser;
657
- const materialDef = parser.json.materials[materialIndex];
658
- if (!materialDef.extensions || !materialDef.extensions[this.name])
659
- return null;
660
- return three_1.MeshPhysicalMaterial;
661
- }
662
- extendMaterialParams(materialIndex, materialParams) {
663
- const parser = this.parser;
664
- const materialDef = parser.json.materials[materialIndex];
665
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
666
- return Promise.resolve();
667
- }
668
- const pending = [];
669
- const extension = materialDef.extensions[this.name];
670
- materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
671
- if (extension.specularTexture !== undefined) {
672
- pending.push(parser.assignTexture(materialParams, 'specularIntensityMap', extension.specularTexture));
673
- }
674
- const colorArray = extension.specularColorFactor || [1, 1, 1];
675
- materialParams.specularColor = new three_1.Color().setRGB(colorArray[0], colorArray[1], colorArray[2], three_1.LinearSRGBColorSpace);
676
- if (extension.specularColorTexture !== undefined) {
677
- pending.push(parser.assignTexture(materialParams, 'specularColorMap', extension.specularColorTexture, three_1.SRGBColorSpace));
678
- }
679
- return Promise.all(pending);
680
- }
681
- }
682
- /**
683
- * Materials anisotropy Extension
684
- *
685
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_anisotropy
686
- */
687
- class GLTFMaterialsAnisotropyExtension {
688
- constructor(parser) {
689
- this.parser = parser;
690
- this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY;
691
- }
692
- getMaterialType(materialIndex) {
693
- const parser = this.parser;
694
- const materialDef = parser.json.materials[materialIndex];
695
- if (!materialDef.extensions || !materialDef.extensions[this.name])
696
- return null;
697
- return three_1.MeshPhysicalMaterial;
698
- }
699
- extendMaterialParams(materialIndex, materialParams) {
700
- const parser = this.parser;
701
- const materialDef = parser.json.materials[materialIndex];
702
- if (!materialDef.extensions || !materialDef.extensions[this.name]) {
703
- return Promise.resolve();
704
- }
705
- const pending = [];
706
- const extension = materialDef.extensions[this.name];
707
- if (extension.anisotropyStrength !== undefined) {
708
- materialParams.anisotropy = extension.anisotropyStrength;
709
- }
710
- if (extension.anisotropyRotation !== undefined) {
711
- materialParams.anisotropyRotation = extension.anisotropyRotation;
712
- }
713
- if (extension.anisotropyTexture !== undefined) {
714
- pending.push(parser.assignTexture(materialParams, 'anisotropyMap', extension.anisotropyTexture));
715
- }
716
- return Promise.all(pending);
717
- }
718
- }
719
- /**
720
- * BasisU Texture Extension
721
- *
722
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
723
- */
724
- class GLTFTextureBasisUExtension {
725
- constructor(parser) {
726
- this.parser = parser;
727
- this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
728
- }
729
- loadTexture(textureIndex) {
730
- const parser = this.parser;
731
- const json = parser.json;
732
- const textureDef = json.textures[textureIndex];
733
- if (!textureDef.extensions || !textureDef.extensions[this.name]) {
734
- return null;
735
- }
736
- const extension = textureDef.extensions[this.name];
737
- const loader = parser.options.ktx2Loader;
738
- if (!loader) {
739
- if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
740
- throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures');
741
- }
742
- else {
743
- // Assumes that the extension is optional and that a fallback texture is present
744
- return null;
745
- }
746
- }
747
- return parser.loadTextureImage(textureIndex, extension.source, loader);
748
- }
749
- }
750
- /**
751
- * WebP Texture Extension
752
- *
753
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
754
- */
755
- class GLTFTextureWebPExtension {
756
- constructor(parser) {
757
- this.parser = parser;
758
- this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
759
- this.isSupported = null;
760
- }
761
- loadTexture(textureIndex) {
762
- const name = this.name;
763
- const parser = this.parser;
764
- const json = parser.json;
765
- const textureDef = json.textures[textureIndex];
766
- if (!textureDef.extensions || !textureDef.extensions[name]) {
767
- return null;
768
- }
769
- const extension = textureDef.extensions[name];
770
- const source = json.images[extension.source];
771
- let loader = parser.textureLoader;
772
- if (source.uri) {
773
- const handler = parser.options.manager.getHandler(source.uri);
774
- if (handler !== null)
775
- loader = handler;
776
- }
777
- return this.detectSupport().then(function (isSupported) {
778
- if (isSupported)
779
- return parser.loadTextureImage(textureIndex, extension.source, loader);
780
- if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) {
781
- throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.');
782
- }
783
- // Fall back to PNG or JPEG.
784
- return parser.loadTexture(textureIndex);
785
- });
786
- }
787
- detectSupport() {
788
- if (!this.isSupported) {
789
- this.isSupported = new Promise(function (resolve) {
790
- const image = new Image();
791
- // Lossy test image. Support for lossy images doesn't guarantee support for all
792
- // WebP images, unfortunately.
793
- image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
794
- image.onload = image.onerror = function () {
795
- resolve(image.height === 1);
796
- };
797
- });
798
- }
799
- return this.isSupported;
800
- }
801
- }
802
- /**
803
- * AVIF Texture Extension
804
- *
805
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif
806
- */
807
- class GLTFTextureAVIFExtension {
808
- constructor(parser) {
809
- this.parser = parser;
810
- this.name = EXTENSIONS.EXT_TEXTURE_AVIF;
811
- this.isSupported = null;
812
- }
813
- loadTexture(textureIndex) {
814
- const name = this.name;
815
- const parser = this.parser;
816
- const json = parser.json;
817
- const textureDef = json.textures[textureIndex];
818
- if (!textureDef.extensions || !textureDef.extensions[name]) {
819
- return null;
820
- }
821
- const extension = textureDef.extensions[name];
822
- const source = json.images[extension.source];
823
- let loader = parser.textureLoader;
824
- if (source.uri) {
825
- const handler = parser.options.manager.getHandler(source.uri);
826
- if (handler !== null)
827
- loader = handler;
828
- }
829
- return this.detectSupport().then(function (isSupported) {
830
- if (isSupported)
831
- return parser.loadTextureImage(textureIndex, extension.source, loader);
832
- if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) {
833
- throw new Error('THREE.GLTFLoader: AVIF required by asset but unsupported.');
834
- }
835
- // Fall back to PNG or JPEG.
836
- return parser.loadTexture(textureIndex);
837
- });
838
- }
839
- detectSupport() {
840
- if (!this.isSupported) {
841
- this.isSupported = new Promise(function (resolve) {
842
- const image = new Image();
843
- // Lossy test image.
844
- image.src = 'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=';
845
- image.onload = image.onerror = function () {
846
- resolve(image.height === 1);
847
- };
848
- });
849
- }
850
- return this.isSupported;
851
- }
852
- }
853
- /**
854
- * meshopt BufferView Compression Extension
855
- *
856
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
857
- */
858
- class GLTFMeshoptCompression {
859
- constructor(parser) {
860
- this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
861
- this.parser = parser;
862
- }
863
- loadBufferView(index) {
864
- const json = this.parser.json;
865
- const bufferView = json.bufferViews[index];
866
- if (bufferView.extensions && bufferView.extensions[this.name]) {
867
- const extensionDef = bufferView.extensions[this.name];
868
- const buffer = this.parser.getDependency('buffer', extensionDef.buffer);
869
- const decoder = this.parser.options.meshoptDecoder;
870
- if (!decoder || !decoder.supported) {
871
- if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
872
- throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files');
873
- }
874
- else {
875
- // Assumes that the extension is optional and that fallback buffer data is present
876
- return null;
877
- }
878
- }
879
- return buffer.then(function (res) {
880
- const byteOffset = extensionDef.byteOffset || 0;
881
- const byteLength = extensionDef.byteLength || 0;
882
- const count = extensionDef.count;
883
- const stride = extensionDef.byteStride;
884
- const source = new Uint8Array(res, byteOffset, byteLength);
885
- if (decoder.decodeGltfBufferAsync) {
886
- return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function (res) {
887
- return res.buffer;
888
- });
889
- }
890
- else {
891
- // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
892
- return decoder.ready.then(function () {
893
- const result = new ArrayBuffer(count * stride);
894
- decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter);
895
- return result;
896
- });
897
- }
898
- });
899
- }
900
- else {
901
- return null;
902
- }
903
- }
904
- }
905
- /**
906
- * GPU Instancing Extension
907
- *
908
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
909
- *
910
- */
911
- class GLTFMeshGpuInstancing {
912
- constructor(parser) {
913
- this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
914
- this.parser = parser;
915
- }
916
- createNodeMesh(nodeIndex) {
917
- const json = this.parser.json;
918
- const nodeDef = json.nodes[nodeIndex];
919
- if (!nodeDef.extensions || !nodeDef.extensions[this.name] ||
920
- nodeDef.mesh === undefined) {
921
- return null;
922
- }
923
- const meshDef = json.meshes[nodeDef.mesh];
924
- // No Points or Lines + Instancing support yet
925
- for (const primitive of meshDef.primitives) {
926
- if (primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&
927
- primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&
928
- primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&
929
- primitive.mode !== undefined) {
930
- return null;
931
- }
932
- }
933
- const extensionDef = nodeDef.extensions[this.name];
934
- const attributesDef = extensionDef.attributes;
935
- // @TODO: Can we support InstancedMesh + SkinnedMesh?
936
- const pending = [];
937
- const attributes = {};
938
- for (const key in attributesDef) {
939
- pending.push(this.parser.getDependency('accessor', attributesDef[key]).then(accessor => {
940
- attributes[key] = accessor;
941
- return attributes[key];
942
- }));
943
- }
944
- if (pending.length < 1) {
945
- return null;
946
- }
947
- pending.push(this.parser.createNodeMesh(nodeIndex));
948
- return Promise.all(pending).then(results => {
949
- const nodeObject = results.pop();
950
- const meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject];
951
- const count = results[0].count; // All attribute counts should be same
952
- const instancedMeshes = [];
953
- for (const mesh of meshes) {
954
- // Temporal variables
955
- const m = new three_1.Matrix4();
956
- const p = new three_1.Vector3();
957
- const q = new three_1.Quaternion();
958
- const s = new three_1.Vector3(1, 1, 1);
959
- const instancedMesh = new three_1.InstancedMesh(mesh.geometry, mesh.material, count);
960
- for (let i = 0; i < count; i++) {
961
- if (attributes.TRANSLATION) {
962
- p.fromBufferAttribute(attributes.TRANSLATION, i);
963
- }
964
- if (attributes.ROTATION) {
965
- q.fromBufferAttribute(attributes.ROTATION, i);
966
- }
967
- if (attributes.SCALE) {
968
- s.fromBufferAttribute(attributes.SCALE, i);
969
- }
970
- instancedMesh.setMatrixAt(i, m.compose(p, q, s));
971
- }
972
- // Add instance attributes to the geometry, excluding TRS.
973
- for (const attributeName in attributes) {
974
- if (attributeName !== 'TRANSLATION' &&
975
- attributeName !== 'ROTATION' &&
976
- attributeName !== 'SCALE') {
977
- mesh.geometry.setAttribute(attributeName, attributes[attributeName]);
978
- }
979
- }
980
- // Just in case
981
- three_1.Object3D.prototype.copy.call(instancedMesh, mesh);
982
- this.parser.assignFinalMaterial(instancedMesh);
983
- instancedMeshes.push(instancedMesh);
984
- }
985
- if (nodeObject.isGroup) {
986
- nodeObject.clear();
987
- nodeObject.add(...instancedMeshes);
988
- return nodeObject;
989
- }
990
- return instancedMeshes[0];
991
- });
992
- }
993
- }
994
- /* BINARY EXTENSION */
995
- const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
996
- const BINARY_EXTENSION_HEADER_LENGTH = 12;
997
- const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
998
- class GLTFBinaryExtension {
999
- constructor(data) {
1000
- this.name = EXTENSIONS.KHR_BINARY_GLTF;
1001
- this.content = null;
1002
- this.body = null;
1003
- const headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
1004
- const textDecoder = new TextDecoder();
1005
- this.header = {
1006
- magic: textDecoder.decode(new Uint8Array(data.slice(0, 4))),
1007
- version: headerView.getUint32(4, true),
1008
- length: headerView.getUint32(8, true)
1009
- };
1010
- if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
1011
- throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
1012
- }
1013
- else if (this.header.version < 2.0) {
1014
- throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
1015
- }
1016
- const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
1017
- const chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
1018
- let chunkIndex = 0;
1019
- while (chunkIndex < chunkContentsLength) {
1020
- const chunkLength = chunkView.getUint32(chunkIndex, true);
1021
- chunkIndex += 4;
1022
- const chunkType = chunkView.getUint32(chunkIndex, true);
1023
- chunkIndex += 4;
1024
- if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
1025
- const contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
1026
- this.content = textDecoder.decode(contentArray);
1027
- }
1028
- else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
1029
- const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
1030
- this.body = data.slice(byteOffset, byteOffset + chunkLength);
1031
- }
1032
- // Clients must ignore chunks with unknown types.
1033
- chunkIndex += chunkLength;
1034
- }
1035
- if (this.content === null) {
1036
- throw new Error('THREE.GLTFLoader: JSON content not found.');
1037
- }
1038
- }
1039
- }
1040
- /**
1041
- * DRACO Mesh Compression Extension
1042
- *
1043
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
1044
- */
1045
- class GLTFDracoMeshCompressionExtension {
1046
- constructor(json, dracoLoader) {
1047
- if (!dracoLoader) {
1048
- throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
1049
- }
1050
- this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
1051
- this.json = json;
1052
- this.dracoLoader = dracoLoader;
1053
- this.dracoLoader.preload();
1054
- }
1055
- decodePrimitive(primitive, parser) {
1056
- const json = this.json;
1057
- const dracoLoader = this.dracoLoader;
1058
- const bufferViewIndex = primitive.extensions[this.name].bufferView;
1059
- const gltfAttributeMap = primitive.extensions[this.name].attributes;
1060
- const threeAttributeMap = {};
1061
- const attributeNormalizedMap = {};
1062
- const attributeTypeMap = {};
1063
- for (const attributeName in gltfAttributeMap) {
1064
- const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
1065
- threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
1066
- }
1067
- for (const attributeName in primitive.attributes) {
1068
- const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
1069
- if (gltfAttributeMap[attributeName] !== undefined) {
1070
- const accessorDef = json.accessors[primitive.attributes[attributeName]];
1071
- const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
1072
- attributeTypeMap[threeAttributeName] = componentType.name;
1073
- attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
1074
- }
1075
- }
1076
- return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
1077
- return new Promise(function (resolve) {
1078
- dracoLoader.decodeDracoFile(bufferView, function (geometry) {
1079
- for (const attributeName in geometry.attributes) {
1080
- const attribute = geometry.attributes[attributeName];
1081
- const normalized = attributeNormalizedMap[attributeName];
1082
- if (normalized !== undefined)
1083
- attribute.normalized = normalized;
1084
- }
1085
- resolve(geometry);
1086
- }, threeAttributeMap, attributeTypeMap);
1087
- });
1088
- });
1089
- }
1090
- }
1091
- /**
1092
- * Texture Transform Extension
1093
- *
1094
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
1095
- */
1096
- class GLTFTextureTransformExtension {
1097
- constructor() {
1098
- this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
1099
- }
1100
- extendTexture(texture, transform) {
1101
- if ((transform.texCoord === undefined || transform.texCoord === texture.channel)
1102
- && transform.offset === undefined
1103
- && transform.rotation === undefined
1104
- && transform.scale === undefined) {
1105
- // See https://github.com/mrdoob/three.js/issues/21819.
1106
- return texture;
1107
- }
1108
- texture = texture.clone();
1109
- if (transform.texCoord !== undefined) {
1110
- texture.channel = transform.texCoord;
1111
- }
1112
- if (transform.offset !== undefined) {
1113
- texture.offset.fromArray(transform.offset);
1114
- }
1115
- if (transform.rotation !== undefined) {
1116
- texture.rotation = transform.rotation;
1117
- }
1118
- if (transform.scale !== undefined) {
1119
- texture.repeat.fromArray(transform.scale);
1120
- }
1121
- texture.needsUpdate = true;
1122
- return texture;
1123
- }
1124
- }
1125
- /**
1126
- * Mesh Quantization Extension
1127
- *
1128
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
1129
- */
1130
- class GLTFMeshQuantizationExtension {
1131
- constructor() {
1132
- this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
1133
- }
1134
- }
1135
- /*********************************/
1136
- /********** INTERPOLATION ********/
1137
- /*********************************/
1138
- // Spline Interpolation
1139
- // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
1140
- class GLTFCubicSplineInterpolant extends three_1.Interpolant {
1141
- constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
1142
- super(parameterPositions, sampleValues, sampleSize, resultBuffer);
1143
- }
1144
- copySampleValue_(index) {
1145
- // Copies a sample value to the result buffer. See description of glTF
1146
- // CUBICSPLINE values layout in interpolate_() function below.
1147
- const result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize;
1148
- for (let i = 0; i !== valueSize; i++) {
1149
- result[i] = values[offset + i];
1150
- }
1151
- return result;
1152
- }
1153
- interpolate_(i1, t0, t, t1) {
1154
- const result = this.resultBuffer;
1155
- const values = this.sampleValues;
1156
- const stride = this.valueSize;
1157
- const stride2 = stride * 2;
1158
- const stride3 = stride * 3;
1159
- const td = t1 - t0;
1160
- const p = (t - t0) / td;
1161
- const pp = p * p;
1162
- const ppp = pp * p;
1163
- const offset1 = i1 * stride3;
1164
- const offset0 = offset1 - stride3;
1165
- const s2 = -2 * ppp + 3 * pp;
1166
- const s3 = ppp - pp;
1167
- const s0 = 1 - s2;
1168
- const s1 = s3 - pp + p;
1169
- // Layout of keyframe output values for CUBICSPLINE animations:
1170
- // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
1171
- for (let i = 0; i !== stride; i++) {
1172
- const p0 = values[offset0 + i + stride]; // splineVertex_k
1173
- const m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
1174
- const p1 = values[offset1 + i + stride]; // splineVertex_k+1
1175
- const m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
1176
- result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
1177
- }
1178
- return result;
1179
- }
1180
- }
1181
- const _q = new three_1.Quaternion();
1182
- class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
1183
- interpolate_(i1, t0, t, t1) {
1184
- const result = super.interpolate_(i1, t0, t, t1);
1185
- _q.fromArray(result).normalize().toArray(result);
1186
- return result;
1187
- }
1188
- }
1189
- /*********************************/
1190
- /********** INTERNALS ************/
1191
- /*********************************/
1192
- /* CONSTANTS */
1193
- const WEBGL_CONSTANTS = {
1194
- FLOAT: 5126,
1195
- //FLOAT_MAT2: 35674,
1196
- FLOAT_MAT3: 35675,
1197
- FLOAT_MAT4: 35676,
1198
- FLOAT_VEC2: 35664,
1199
- FLOAT_VEC3: 35665,
1200
- FLOAT_VEC4: 35666,
1201
- LINEAR: 9729,
1202
- REPEAT: 10497,
1203
- SAMPLER_2D: 35678,
1204
- POINTS: 0,
1205
- LINES: 1,
1206
- LINE_LOOP: 2,
1207
- LINE_STRIP: 3,
1208
- TRIANGLES: 4,
1209
- TRIANGLE_STRIP: 5,
1210
- TRIANGLE_FAN: 6,
1211
- UNSIGNED_BYTE: 5121,
1212
- UNSIGNED_SHORT: 5123
1213
- };
1214
- const WEBGL_COMPONENT_TYPES = {
1215
- 5120: Int8Array,
1216
- 5121: Uint8Array,
1217
- 5122: Int16Array,
1218
- 5123: Uint16Array,
1219
- 5125: Uint32Array,
1220
- 5126: Float32Array
1221
- };
1222
- const WEBGL_FILTERS = {
1223
- 9728: three_1.NearestFilter,
1224
- 9729: three_1.LinearFilter,
1225
- 9984: three_1.NearestMipmapNearestFilter,
1226
- 9985: three_1.LinearMipmapNearestFilter,
1227
- 9986: three_1.NearestMipmapLinearFilter,
1228
- 9987: three_1.LinearMipmapLinearFilter
1229
- };
1230
- const WEBGL_WRAPPINGS = {
1231
- 33071: three_1.ClampToEdgeWrapping,
1232
- 33648: three_1.MirroredRepeatWrapping,
1233
- 10497: three_1.RepeatWrapping
1234
- };
1235
- const WEBGL_TYPE_SIZES = {
1236
- 'SCALAR': 1,
1237
- 'VEC2': 2,
1238
- 'VEC3': 3,
1239
- 'VEC4': 4,
1240
- 'MAT2': 4,
1241
- 'MAT3': 9,
1242
- 'MAT4': 16
1243
- };
1244
- const ATTRIBUTES = {
1245
- POSITION: 'position',
1246
- NORMAL: 'normal',
1247
- TANGENT: 'tangent',
1248
- TEXCOORD_0: 'uv',
1249
- TEXCOORD_1: 'uv1',
1250
- TEXCOORD_2: 'uv2',
1251
- TEXCOORD_3: 'uv3',
1252
- COLOR_0: 'color',
1253
- WEIGHTS_0: 'skinWeight',
1254
- JOINTS_0: 'skinIndex',
1255
- };
1256
- const PATH_PROPERTIES = {
1257
- scale: 'scale',
1258
- translation: 'position',
1259
- rotation: 'quaternion',
1260
- weights: 'morphTargetInfluences'
1261
- };
1262
- const INTERPOLATION = {
1263
- CUBICSPLINE: undefined,
1264
- // keyframe track will be initialized with a default interpolation type, then modified.
1265
- LINEAR: three_1.InterpolateLinear,
1266
- STEP: three_1.InterpolateDiscrete
1267
- };
1268
- const ALPHA_MODES = {
1269
- OPAQUE: 'OPAQUE',
1270
- MASK: 'MASK',
1271
- BLEND: 'BLEND'
1272
- };
1273
- /**
1274
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
1275
- */
1276
- function createDefaultMaterial(cache) {
1277
- if (cache['DefaultMaterial'] === undefined) {
1278
- cache['DefaultMaterial'] = new three_1.MeshStandardMaterial({
1279
- color: 0xFFFFFF,
1280
- emissive: 0x000000,
1281
- metalness: 1,
1282
- roughness: 1,
1283
- transparent: false,
1284
- depthTest: true,
1285
- side: three_1.FrontSide
1286
- });
1287
- }
1288
- return cache['DefaultMaterial'];
1289
- }
1290
- function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
1291
- // Add unknown glTF extensions to an object's userData.
1292
- for (const name in objectDef.extensions) {
1293
- if (knownExtensions[name] === undefined) {
1294
- object.userData.gltfExtensions = object.userData.gltfExtensions || {};
1295
- object.userData.gltfExtensions[name] = objectDef.extensions[name];
1296
- }
1297
- }
1298
- }
1299
- /**
1300
- * @param {Object3D|Material|BufferGeometry} object
1301
- * @param {GLTF.definition} gltfDef
1302
- */
1303
- function assignExtrasToUserData(object, gltfDef) {
1304
- if (gltfDef.extras !== undefined) {
1305
- if (typeof gltfDef.extras === 'object') {
1306
- Object.assign(object.userData, gltfDef.extras);
1307
- }
1308
- else {
1309
- console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
1310
- }
1311
- }
1312
- }
1313
- /**
1314
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
1315
- *
1316
- * @param {BufferGeometry} geometry
1317
- * @param {Array<GLTF.Target>} targets
1318
- * @param {GLTFParser} parser
1319
- * @return {Promise<BufferGeometry>}
1320
- */
1321
- function addMorphTargets(geometry, targets, parser) {
1322
- let hasMorphPosition = false;
1323
- let hasMorphNormal = false;
1324
- let hasMorphColor = false;
1325
- for (let i = 0, il = targets.length; i < il; i++) {
1326
- const target = targets[i];
1327
- if (target.POSITION !== undefined)
1328
- hasMorphPosition = true;
1329
- if (target.NORMAL !== undefined)
1330
- hasMorphNormal = true;
1331
- if (target.COLOR_0 !== undefined)
1332
- hasMorphColor = true;
1333
- if (hasMorphPosition && hasMorphNormal && hasMorphColor)
1334
- break;
1335
- }
1336
- if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor)
1337
- return Promise.resolve(geometry);
1338
- const pendingPositionAccessors = [];
1339
- const pendingNormalAccessors = [];
1340
- const pendingColorAccessors = [];
1341
- for (let i = 0, il = targets.length; i < il; i++) {
1342
- const target = targets[i];
1343
- if (hasMorphPosition) {
1344
- const pendingAccessor = target.POSITION !== undefined
1345
- ? parser.getDependency('accessor', target.POSITION)
1346
- : geometry.attributes.position;
1347
- pendingPositionAccessors.push(pendingAccessor);
1348
- }
1349
- if (hasMorphNormal) {
1350
- const pendingAccessor = target.NORMAL !== undefined
1351
- ? parser.getDependency('accessor', target.NORMAL)
1352
- : geometry.attributes.normal;
1353
- pendingNormalAccessors.push(pendingAccessor);
1354
- }
1355
- if (hasMorphColor) {
1356
- const pendingAccessor = target.COLOR_0 !== undefined
1357
- ? parser.getDependency('accessor', target.COLOR_0)
1358
- : geometry.attributes.color;
1359
- pendingColorAccessors.push(pendingAccessor);
1360
- }
1361
- }
1362
- return Promise.all([
1363
- Promise.all(pendingPositionAccessors),
1364
- Promise.all(pendingNormalAccessors),
1365
- Promise.all(pendingColorAccessors)
1366
- ]).then(function (accessors) {
1367
- const morphPositions = accessors[0];
1368
- const morphNormals = accessors[1];
1369
- const morphColors = accessors[2];
1370
- if (hasMorphPosition)
1371
- geometry.morphAttributes.position = morphPositions;
1372
- if (hasMorphNormal)
1373
- geometry.morphAttributes.normal = morphNormals;
1374
- if (hasMorphColor)
1375
- geometry.morphAttributes.color = morphColors;
1376
- geometry.morphTargetsRelative = true;
1377
- return geometry;
1378
- });
1379
- }
1380
- /**
1381
- * @param {Mesh} mesh
1382
- * @param {GLTF.Mesh} meshDef
1383
- */
1384
- function updateMorphTargets(mesh, meshDef) {
1385
- mesh.updateMorphTargets();
1386
- if (meshDef.weights !== undefined) {
1387
- for (let i = 0, il = meshDef.weights.length; i < il; i++) {
1388
- mesh.morphTargetInfluences[i] = meshDef.weights[i];
1389
- }
1390
- }
1391
- // .extras has user-defined data, so check that .extras.targetNames is an array.
1392
- if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
1393
- const targetNames = meshDef.extras.targetNames;
1394
- if (mesh.morphTargetInfluences.length === targetNames.length) {
1395
- mesh.morphTargetDictionary = {};
1396
- for (let i = 0, il = targetNames.length; i < il; i++) {
1397
- mesh.morphTargetDictionary[targetNames[i]] = i;
1398
- }
1399
- }
1400
- else {
1401
- console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
1402
- }
1403
- }
1404
- }
1405
- function createPrimitiveKey(primitiveDef) {
1406
- let geometryKey;
1407
- const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
1408
- if (dracoExtension) {
1409
- geometryKey = 'draco:' + dracoExtension.bufferView
1410
- + ':' + dracoExtension.indices
1411
- + ':' + createAttributesKey(dracoExtension.attributes);
1412
- }
1413
- else {
1414
- geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
1415
- }
1416
- if (primitiveDef.targets !== undefined) {
1417
- for (let i = 0, il = primitiveDef.targets.length; i < il; i++) {
1418
- geometryKey += ':' + createAttributesKey(primitiveDef.targets[i]);
1419
- }
1420
- }
1421
- return geometryKey;
1422
- }
1423
- function createAttributesKey(attributes) {
1424
- let attributesKey = '';
1425
- const keys = Object.keys(attributes).sort();
1426
- for (let i = 0, il = keys.length; i < il; i++) {
1427
- attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
1428
- }
1429
- return attributesKey;
1430
- }
1431
- function getNormalizedComponentScale(constructor) {
1432
- // Reference:
1433
- // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
1434
- switch (constructor) {
1435
- case Int8Array:
1436
- return 1 / 127;
1437
- case Uint8Array:
1438
- return 1 / 255;
1439
- case Int16Array:
1440
- return 1 / 32767;
1441
- case Uint16Array:
1442
- return 1 / 65535;
1443
- default:
1444
- throw new Error('THREE.GLTFLoader: Unsupported normalized accessor component type.');
1445
- }
1446
- }
1447
- function getImageURIMimeType(uri) {
1448
- if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0)
1449
- return 'image/jpeg';
1450
- if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0)
1451
- return 'image/webp';
1452
- return 'image/png';
1453
- }
1454
- const _identityMatrix = new three_1.Matrix4();
1455
- /* GLTF PARSER */
1456
- class GLTFParser {
1457
- constructor(json = {}, options = {}) {
1458
- this.json = json;
1459
- this.extensions = {};
1460
- this.plugins = {};
1461
- this.options = options;
1462
- // loader object cache
1463
- this.cache = new GLTFRegistry();
1464
- // associations between Three.js objects and glTF elements
1465
- this.associations = new Map();
1466
- // BufferGeometry caching
1467
- this.primitiveCache = {};
1468
- // Node cache
1469
- this.nodeCache = {};
1470
- // Object3D instance caches
1471
- this.meshCache = { refs: {}, uses: {} };
1472
- this.cameraCache = { refs: {}, uses: {} };
1473
- this.lightCache = { refs: {}, uses: {} };
1474
- this.sourceCache = {};
1475
- this.textureCache = {};
1476
- // Track node names, to ensure no duplicates
1477
- this.nodeNamesUsed = {};
1478
- // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
1479
- // expensive work of uploading a texture to the GPU off the main thread.
1480
- let isSafari = false;
1481
- let isFirefox = false;
1482
- let firefoxVersion = -1;
1483
- if (typeof navigator !== 'undefined') {
1484
- isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) === true;
1485
- isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
1486
- firefoxVersion = isFirefox ? navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1;
1487
- }
1488
- if (typeof createImageBitmap === 'undefined' || isSafari || (isFirefox && firefoxVersion < 98)) {
1489
- this.textureLoader = new three_1.TextureLoader(this.options.manager);
1490
- }
1491
- else {
1492
- this.textureLoader = new three_1.ImageBitmapLoader(this.options.manager);
1493
- }
1494
- this.textureLoader.setCrossOrigin(this.options.crossOrigin);
1495
- this.textureLoader.setRequestHeader(this.options.requestHeader);
1496
- this.fileLoader = new three_1.FileLoader(this.options.manager);
1497
- this.fileLoader.setResponseType('arraybuffer');
1498
- if (this.options.crossOrigin === 'use-credentials') {
1499
- this.fileLoader.setWithCredentials(true);
1500
- }
1501
- }
1502
- setExtensions(extensions) {
1503
- this.extensions = extensions;
1504
- }
1505
- setPlugins(plugins) {
1506
- this.plugins = plugins;
1507
- }
1508
- parse(onLoad, onError) {
1509
- const parser = this;
1510
- const json = this.json;
1511
- const extensions = this.extensions;
1512
- // Clear the loader cache
1513
- this.cache.removeAll();
1514
- this.nodeCache = {};
1515
- // Mark the special nodes/meshes in json for efficient parse
1516
- this._invokeAll(function (ext) {
1517
- return ext._markDefs && ext._markDefs();
1518
- });
1519
- Promise.all(this._invokeAll(function (ext) {
1520
- return ext.beforeRoot && ext.beforeRoot();
1521
- })).then(function () {
1522
- return Promise.all([
1523
- parser.getDependencies('scene'),
1524
- parser.getDependencies('animation'),
1525
- parser.getDependencies('camera'),
1526
- ]);
1527
- }).then(function (dependencies) {
1528
- const result = {
1529
- scene: dependencies[0][json.scene || 0],
1530
- scenes: dependencies[0],
1531
- animations: dependencies[1],
1532
- cameras: dependencies[2],
1533
- asset: json.asset,
1534
- parser: parser,
1535
- userData: {}
1536
- };
1537
- addUnknownExtensionsToUserData(extensions, result, json);
1538
- assignExtrasToUserData(result, json);
1539
- Promise.all(parser._invokeAll(function (ext) {
1540
- return ext.afterRoot && ext.afterRoot(result);
1541
- })).then(function () {
1542
- onLoad(result);
1543
- });
1544
- }).catch(onError);
1545
- }
1546
- /**
1547
- * Marks the special nodes/meshes in json for efficient parse.
1548
- */
1549
- _markDefs() {
1550
- const nodeDefs = this.json.nodes || [];
1551
- const skinDefs = this.json.skins || [];
1552
- const meshDefs = this.json.meshes || [];
1553
- // Nothing in the node definition indicates whether it is a Bone or an
1554
- // Object3D. Use the skins' joint references to mark bones.
1555
- for (let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
1556
- const joints = skinDefs[skinIndex].joints;
1557
- for (let i = 0, il = joints.length; i < il; i++) {
1558
- nodeDefs[joints[i]].isBone = true;
1559
- }
1560
- }
1561
- // Iterate over all nodes, marking references to shared resources,
1562
- // as well as skeleton joints.
1563
- for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
1564
- const nodeDef = nodeDefs[nodeIndex];
1565
- if (nodeDef.mesh !== undefined) {
1566
- this._addNodeRef(this.meshCache, nodeDef.mesh);
1567
- // Nothing in the mesh definition indicates whether it is
1568
- // a SkinnedMesh or Mesh. Use the node's mesh reference
1569
- // to mark SkinnedMesh if node has skin.
1570
- if (nodeDef.skin !== undefined) {
1571
- meshDefs[nodeDef.mesh].isSkinnedMesh = true;
1572
- }
1573
- }
1574
- if (nodeDef.camera !== undefined) {
1575
- this._addNodeRef(this.cameraCache, nodeDef.camera);
1576
- }
1577
- }
1578
- }
1579
- /**
1580
- * Counts references to shared node / Object3D resources. These resources
1581
- * can be reused, or "instantiated", at multiple nodes in the scene
1582
- * hierarchy. Mesh, Camera, and Light instances are instantiated and must
1583
- * be marked. Non-scenegraph resources (like Materials, Geometries, and
1584
- * Textures) can be reused directly and are not marked here.
1585
- *
1586
- * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
1587
- */
1588
- _addNodeRef(cache, index) {
1589
- if (index === undefined)
1590
- return;
1591
- if (cache.refs[index] === undefined) {
1592
- cache.refs[index] = cache.uses[index] = 0;
1593
- }
1594
- cache.refs[index]++;
1595
- }
1596
- /** Returns a reference to a shared resource, cloning it if necessary. */
1597
- _getNodeRef(cache, index, object) {
1598
- if (cache.refs[index] <= 1)
1599
- return object;
1600
- const ref = object.clone();
1601
- // Propagates mappings to the cloned object, prevents mappings on the
1602
- // original object from being lost.
1603
- const updateMappings = (original, clone) => {
1604
- const mappings = this.associations.get(original);
1605
- if (mappings != null) {
1606
- this.associations.set(clone, mappings);
1607
- }
1608
- for (const [i, child] of original.children.entries()) {
1609
- updateMappings(child, clone.children[i]);
1610
- }
1611
- };
1612
- updateMappings(object, ref);
1613
- ref.name += '_instance_' + (cache.uses[index]++);
1614
- return ref;
1615
- }
1616
- _invokeOne(func) {
1617
- const extensions = Object.values(this.plugins);
1618
- extensions.push(this);
1619
- for (let i = 0; i < extensions.length; i++) {
1620
- const result = func(extensions[i]);
1621
- if (result)
1622
- return result;
1623
- }
1624
- return null;
1625
- }
1626
- _invokeAll(func) {
1627
- const extensions = Object.values(this.plugins);
1628
- extensions.unshift(this);
1629
- const pending = [];
1630
- for (let i = 0; i < extensions.length; i++) {
1631
- const result = func(extensions[i]);
1632
- if (result)
1633
- pending.push(result);
1634
- }
1635
- return pending;
1636
- }
1637
- /**
1638
- * Requests the specified dependency asynchronously, with caching.
1639
- * @param {string} type
1640
- * @param {number} index
1641
- * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
1642
- */
1643
- getDependency(type, index) {
1644
- const cacheKey = type + ':' + index;
1645
- let dependency = this.cache.get(cacheKey);
1646
- if (!dependency) {
1647
- switch (type) {
1648
- case 'scene':
1649
- dependency = this.loadScene(index);
1650
- break;
1651
- case 'node':
1652
- dependency = this._invokeOne(function (ext) {
1653
- return ext.loadNode && ext.loadNode(index);
1654
- });
1655
- break;
1656
- case 'mesh':
1657
- dependency = this._invokeOne(function (ext) {
1658
- return ext.loadMesh && ext.loadMesh(index);
1659
- });
1660
- break;
1661
- case 'accessor':
1662
- dependency = this.loadAccessor(index);
1663
- break;
1664
- case 'bufferView':
1665
- dependency = this._invokeOne(function (ext) {
1666
- return ext.loadBufferView && ext.loadBufferView(index);
1667
- });
1668
- break;
1669
- case 'buffer':
1670
- dependency = this.loadBuffer(index);
1671
- break;
1672
- case 'material':
1673
- dependency = this._invokeOne(function (ext) {
1674
- return ext.loadMaterial && ext.loadMaterial(index);
1675
- });
1676
- break;
1677
- case 'texture':
1678
- dependency = this._invokeOne(function (ext) {
1679
- return ext.loadTexture && ext.loadTexture(index);
1680
- });
1681
- break;
1682
- case 'skin':
1683
- dependency = this.loadSkin(index);
1684
- break;
1685
- case 'animation':
1686
- dependency = this._invokeOne(function (ext) {
1687
- return ext.loadAnimation && ext.loadAnimation(index);
1688
- });
1689
- break;
1690
- case 'camera':
1691
- dependency = this.loadCamera(index);
1692
- break;
1693
- default:
1694
- dependency = this._invokeOne(function (ext) {
1695
- return ext != this && ext.getDependency && ext.getDependency(type, index);
1696
- });
1697
- if (!dependency) {
1698
- throw new Error('Unknown type: ' + type);
1699
- }
1700
- break;
1701
- }
1702
- this.cache.add(cacheKey, dependency);
1703
- }
1704
- return dependency;
1705
- }
1706
- /**
1707
- * Requests all dependencies of the specified type asynchronously, with caching.
1708
- * @param {string} type
1709
- * @return {Promise<Array<Object>>}
1710
- */
1711
- getDependencies(type) {
1712
- let dependencies = this.cache.get(type);
1713
- if (!dependencies) {
1714
- const parser = this;
1715
- const defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
1716
- dependencies = Promise.all(defs.map(function (def, index) {
1717
- return parser.getDependency(type, index);
1718
- }));
1719
- this.cache.add(type, dependencies);
1720
- }
1721
- return dependencies;
1722
- }
1723
- /**
1724
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
1725
- * @param {number} bufferIndex
1726
- * @return {Promise<ArrayBuffer>}
1727
- */
1728
- loadBuffer(bufferIndex) {
1729
- const bufferDef = this.json.buffers[bufferIndex];
1730
- const loader = this.fileLoader;
1731
- if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
1732
- throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
1733
- }
1734
- // If present, GLB container is required to be the first buffer.
1735
- if (bufferDef.uri === undefined && bufferIndex === 0) {
1736
- return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
1737
- }
1738
- const options = this.options;
1739
- return new Promise(function (resolve, reject) {
1740
- loader.load(three_1.LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
1741
- reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
1742
- });
1743
- });
1744
- }
1745
- /**
1746
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
1747
- * @param {number} bufferViewIndex
1748
- * @return {Promise<ArrayBuffer>}
1749
- */
1750
- loadBufferView(bufferViewIndex) {
1751
- const bufferViewDef = this.json.bufferViews[bufferViewIndex];
1752
- return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
1753
- const byteLength = bufferViewDef.byteLength || 0;
1754
- const byteOffset = bufferViewDef.byteOffset || 0;
1755
- return buffer.slice(byteOffset, byteOffset + byteLength);
1756
- });
1757
- }
1758
- /**
1759
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
1760
- * @param {number} accessorIndex
1761
- * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
1762
- */
1763
- loadAccessor(accessorIndex) {
1764
- const parser = this;
1765
- const json = this.json;
1766
- const accessorDef = this.json.accessors[accessorIndex];
1767
- if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
1768
- const itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
1769
- const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
1770
- const normalized = accessorDef.normalized === true;
1771
- const array = new TypedArray(accessorDef.count * itemSize);
1772
- return Promise.resolve(new three_1.BufferAttribute(array, itemSize, normalized));
1773
- }
1774
- const pendingBufferViews = [];
1775
- if (accessorDef.bufferView !== undefined) {
1776
- pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
1777
- }
1778
- else {
1779
- pendingBufferViews.push(null);
1780
- }
1781
- if (accessorDef.sparse !== undefined) {
1782
- pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
1783
- pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
1784
- }
1785
- return Promise.all(pendingBufferViews).then(function (bufferViews) {
1786
- const bufferView = bufferViews[0];
1787
- const itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
1788
- const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
1789
- // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
1790
- const elementBytes = TypedArray.BYTES_PER_ELEMENT;
1791
- const itemBytes = elementBytes * itemSize;
1792
- const byteOffset = accessorDef.byteOffset || 0;
1793
- const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
1794
- const normalized = accessorDef.normalized === true;
1795
- let array, bufferAttribute;
1796
- // The buffer is not interleaved if the stride is the item size in bytes.
1797
- if (byteStride && byteStride !== itemBytes) {
1798
- // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
1799
- // This makes sure that IBA.count reflects accessor.count properly
1800
- const ibSlice = Math.floor(byteOffset / byteStride);
1801
- const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
1802
- let ib = parser.cache.get(ibCacheKey);
1803
- if (!ib) {
1804
- array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes);
1805
- // Integer parameters to IB/IBA are in array elements, not bytes.
1806
- ib = new three_1.InterleavedBuffer(array, byteStride / elementBytes);
1807
- parser.cache.add(ibCacheKey, ib);
1808
- }
1809
- bufferAttribute = new three_1.InterleavedBufferAttribute(ib, itemSize, (byteOffset % byteStride) / elementBytes, normalized);
1810
- }
1811
- else {
1812
- if (bufferView === null) {
1813
- array = new TypedArray(accessorDef.count * itemSize);
1814
- }
1815
- else {
1816
- array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
1817
- }
1818
- bufferAttribute = new three_1.BufferAttribute(array, itemSize, normalized);
1819
- }
1820
- // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
1821
- if (accessorDef.sparse !== undefined) {
1822
- const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
1823
- const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
1824
- const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
1825
- const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
1826
- const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
1827
- const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
1828
- if (bufferView !== null) {
1829
- // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
1830
- bufferAttribute = new three_1.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
1831
- }
1832
- for (let i = 0, il = sparseIndices.length; i < il; i++) {
1833
- const index = sparseIndices[i];
1834
- bufferAttribute.setX(index, sparseValues[i * itemSize]);
1835
- if (itemSize >= 2)
1836
- bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
1837
- if (itemSize >= 3)
1838
- bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
1839
- if (itemSize >= 4)
1840
- bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
1841
- if (itemSize >= 5)
1842
- throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
1843
- }
1844
- }
1845
- return bufferAttribute;
1846
- });
1847
- }
1848
- /**
1849
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
1850
- * @param {number} textureIndex
1851
- * @return {Promise<THREE.Texture|null>}
1852
- */
1853
- loadTexture(textureIndex) {
1854
- const json = this.json;
1855
- const options = this.options;
1856
- const textureDef = json.textures[textureIndex];
1857
- const sourceIndex = textureDef.source;
1858
- const sourceDef = json.images[sourceIndex];
1859
- let loader = this.textureLoader;
1860
- if (sourceDef.uri) {
1861
- const handler = options.manager.getHandler(sourceDef.uri);
1862
- if (handler !== null)
1863
- loader = handler;
1864
- }
1865
- return this.loadTextureImage(textureIndex, sourceIndex, loader);
1866
- }
1867
- loadTextureImage(textureIndex, sourceIndex, loader) {
1868
- const parser = this;
1869
- const json = this.json;
1870
- const textureDef = json.textures[textureIndex];
1871
- const sourceDef = json.images[sourceIndex];
1872
- const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ':' + textureDef.sampler;
1873
- if (this.textureCache[cacheKey]) {
1874
- // See https://github.com/mrdoob/three.js/issues/21559.
1875
- return this.textureCache[cacheKey];
1876
- }
1877
- const promise = this.loadImageSource(sourceIndex, loader).then(function (texture) {
1878
- texture.flipY = false;
1879
- texture.name = textureDef.name || sourceDef.name || '';
1880
- if (texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith('data:image/') === false) {
1881
- texture.name = sourceDef.uri;
1882
- }
1883
- const samplers = json.samplers || {};
1884
- const sampler = samplers[textureDef.sampler] || {};
1885
- texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || three_1.LinearFilter;
1886
- texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || three_1.LinearMipmapLinearFilter;
1887
- texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || three_1.RepeatWrapping;
1888
- texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || three_1.RepeatWrapping;
1889
- parser.associations.set(texture, { textures: textureIndex });
1890
- return texture;
1891
- }).catch(function () {
1892
- return null;
1893
- });
1894
- this.textureCache[cacheKey] = promise;
1895
- return promise;
1896
- }
1897
- loadImageSource(sourceIndex, loader) {
1898
- const parser = this;
1899
- const json = this.json;
1900
- const options = this.options;
1901
- if (this.sourceCache[sourceIndex] !== undefined) {
1902
- return this.sourceCache[sourceIndex].then((texture) => texture.clone());
1903
- }
1904
- const sourceDef = json.images[sourceIndex];
1905
- const URL = self.URL || self.webkitURL;
1906
- let sourceURI = sourceDef.uri || '';
1907
- let isObjectURL = false;
1908
- if (sourceDef.bufferView !== undefined) {
1909
- // Load binary image data from bufferView, if provided.
1910
- sourceURI = parser.getDependency('bufferView', sourceDef.bufferView).then(function (bufferView) {
1911
- isObjectURL = true;
1912
- const blob = new Blob([bufferView], { type: sourceDef.mimeType });
1913
- sourceURI = URL.createObjectURL(blob);
1914
- return sourceURI;
1915
- });
1916
- }
1917
- else if (sourceDef.uri === undefined) {
1918
- throw new Error('THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView');
1919
- }
1920
- const promise = Promise.resolve(sourceURI).then(function (sourceURI) {
1921
- return new Promise(function (resolve, reject) {
1922
- let onLoad = resolve;
1923
- if (loader.isImageBitmapLoader === true) {
1924
- onLoad = function (imageBitmap) {
1925
- const texture = new three_1.Texture(imageBitmap);
1926
- texture.needsUpdate = true;
1927
- resolve(texture);
1928
- };
1929
- }
1930
- loader.load(three_1.LoaderUtils.resolveURL(sourceURI, options.path), onLoad, undefined, reject);
1931
- });
1932
- }).then(function (texture) {
1933
- // Clean up resources and configure Texture.
1934
- if (isObjectURL === true) {
1935
- URL.revokeObjectURL(sourceURI);
1936
- }
1937
- texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri);
1938
- return texture;
1939
- }).catch(function (error) {
1940
- console.error('THREE.GLTFLoader: Couldn\'t load texture', sourceURI);
1941
- throw error;
1942
- });
1943
- this.sourceCache[sourceIndex] = promise;
1944
- return promise;
1945
- }
1946
- /**
1947
- * Asynchronously assigns a texture to the given material parameters.
1948
- * @param {Object} materialParams
1949
- * @param {string} mapName
1950
- * @param {Object} mapDef
1951
- * @return {Promise<Texture>}
1952
- */
1953
- assignTexture(materialParams, mapName, mapDef, colorSpace) {
1954
- const parser = this;
1955
- return this.getDependency('texture', mapDef.index).then(function (texture) {
1956
- if (!texture)
1957
- return null;
1958
- if (mapDef.texCoord !== undefined && mapDef.texCoord > 0) {
1959
- texture = texture.clone();
1960
- texture.channel = mapDef.texCoord;
1961
- }
1962
- if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
1963
- const transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
1964
- if (transform) {
1965
- const gltfReference = parser.associations.get(texture);
1966
- texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
1967
- parser.associations.set(texture, gltfReference);
1968
- }
1969
- }
1970
- if (colorSpace !== undefined) {
1971
- texture.colorSpace = colorSpace;
1972
- }
1973
- materialParams[mapName] = texture;
1974
- return texture;
1975
- });
1976
- }
1977
- /**
1978
- * Assigns final material to a Mesh, Line, or Points instance. The instance
1979
- * already has a material (generated from the glTF material options alone)
1980
- * but reuse of the same glTF material may require multiple threejs materials
1981
- * to accommodate different primitive types, defines, etc. New materials will
1982
- * be created if necessary, and reused from a cache.
1983
- * @param {Object3D} mesh Mesh, Line, or Points instance.
1984
- */
1985
- assignFinalMaterial(mesh) {
1986
- const geometry = mesh.geometry;
1987
- let material = mesh.material;
1988
- const useDerivativeTangents = geometry.attributes.tangent === undefined;
1989
- const useVertexColors = geometry.attributes.color !== undefined;
1990
- const useFlatShading = geometry.attributes.normal === undefined;
1991
- if (mesh.isPoints) {
1992
- const cacheKey = 'PointsMaterial:' + material.uuid;
1993
- let pointsMaterial = this.cache.get(cacheKey);
1994
- if (!pointsMaterial) {
1995
- pointsMaterial = new three_1.PointsMaterial();
1996
- three_1.Material.prototype.copy.call(pointsMaterial, material);
1997
- pointsMaterial.color.copy(material.color);
1998
- pointsMaterial.map = material.map;
1999
- pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
2000
- this.cache.add(cacheKey, pointsMaterial);
2001
- }
2002
- material = pointsMaterial;
2003
- }
2004
- else if (mesh.isLine) {
2005
- const cacheKey = 'LineBasicMaterial:' + material.uuid;
2006
- let lineMaterial = this.cache.get(cacheKey);
2007
- if (!lineMaterial) {
2008
- lineMaterial = new three_1.LineBasicMaterial();
2009
- three_1.Material.prototype.copy.call(lineMaterial, material);
2010
- lineMaterial.color.copy(material.color);
2011
- lineMaterial.map = material.map;
2012
- this.cache.add(cacheKey, lineMaterial);
2013
- }
2014
- material = lineMaterial;
2015
- }
2016
- // Clone the material if it will be modified
2017
- if (useDerivativeTangents || useVertexColors || useFlatShading) {
2018
- let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
2019
- if (useDerivativeTangents)
2020
- cacheKey += 'derivative-tangents:';
2021
- if (useVertexColors)
2022
- cacheKey += 'vertex-colors:';
2023
- if (useFlatShading)
2024
- cacheKey += 'flat-shading:';
2025
- let cachedMaterial = this.cache.get(cacheKey);
2026
- if (!cachedMaterial) {
2027
- cachedMaterial = material.clone();
2028
- if (useVertexColors)
2029
- cachedMaterial.vertexColors = true;
2030
- if (useFlatShading)
2031
- cachedMaterial.flatShading = true;
2032
- if (useDerivativeTangents) {
2033
- // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
2034
- if (cachedMaterial.normalScale)
2035
- cachedMaterial.normalScale.y *= -1;
2036
- if (cachedMaterial.clearcoatNormalScale)
2037
- cachedMaterial.clearcoatNormalScale.y *= -1;
2038
- }
2039
- this.cache.add(cacheKey, cachedMaterial);
2040
- this.associations.set(cachedMaterial, this.associations.get(material));
2041
- }
2042
- material = cachedMaterial;
2043
- }
2044
- mesh.material = material;
2045
- }
2046
- getMaterialType( /* materialIndex */) {
2047
- return three_1.MeshStandardMaterial;
2048
- }
2049
- /**
2050
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
2051
- * @param {number} materialIndex
2052
- * @return {Promise<Material>}
2053
- */
2054
- loadMaterial(materialIndex) {
2055
- const parser = this;
2056
- const json = this.json;
2057
- const extensions = this.extensions;
2058
- const materialDef = json.materials[materialIndex];
2059
- let materialType;
2060
- const materialParams = {};
2061
- const materialExtensions = materialDef.extensions || {};
2062
- const pending = [];
2063
- if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
2064
- const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
2065
- materialType = kmuExtension.getMaterialType();
2066
- pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
2067
- }
2068
- else {
2069
- // Specification:
2070
- // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
2071
- const metallicRoughness = materialDef.pbrMetallicRoughness || {};
2072
- materialParams.color = new three_1.Color(1.0, 1.0, 1.0);
2073
- materialParams.opacity = 1.0;
2074
- if (Array.isArray(metallicRoughness.baseColorFactor)) {
2075
- const array = metallicRoughness.baseColorFactor;
2076
- materialParams.color.setRGB(array[0], array[1], array[2], three_1.LinearSRGBColorSpace);
2077
- materialParams.opacity = array[3];
2078
- }
2079
- if (metallicRoughness.baseColorTexture !== undefined) {
2080
- pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, three_1.SRGBColorSpace));
2081
- }
2082
- materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
2083
- materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
2084
- if (metallicRoughness.metallicRoughnessTexture !== undefined) {
2085
- pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
2086
- pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
2087
- }
2088
- materialType = this._invokeOne(function (ext) {
2089
- return ext.getMaterialType && ext.getMaterialType(materialIndex);
2090
- });
2091
- pending.push(Promise.all(this._invokeAll(function (ext) {
2092
- return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams);
2093
- })));
2094
- }
2095
- if (materialDef.doubleSided === true) {
2096
- materialParams.side = three_1.DoubleSide;
2097
- }
2098
- const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
2099
- if (alphaMode === ALPHA_MODES.BLEND) {
2100
- materialParams.transparent = true;
2101
- // See: https://github.com/mrdoob/three.js/issues/17706
2102
- materialParams.depthWrite = false;
2103
- }
2104
- else {
2105
- materialParams.transparent = false;
2106
- if (alphaMode === ALPHA_MODES.MASK) {
2107
- materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
2108
- }
2109
- }
2110
- if (materialDef.normalTexture !== undefined && materialType !== three_1.MeshBasicMaterial) {
2111
- pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
2112
- materialParams.normalScale = new three_1.Vector2(1, 1);
2113
- if (materialDef.normalTexture.scale !== undefined) {
2114
- const scale = materialDef.normalTexture.scale;
2115
- materialParams.normalScale.set(scale, scale);
2116
- }
2117
- }
2118
- if (materialDef.occlusionTexture !== undefined && materialType !== three_1.MeshBasicMaterial) {
2119
- pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
2120
- if (materialDef.occlusionTexture.strength !== undefined) {
2121
- materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
2122
- }
2123
- }
2124
- if (materialDef.emissiveFactor !== undefined && materialType !== three_1.MeshBasicMaterial) {
2125
- const emissiveFactor = materialDef.emissiveFactor;
2126
- materialParams.emissive = new three_1.Color().setRGB(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], three_1.LinearSRGBColorSpace);
2127
- }
2128
- if (materialDef.emissiveTexture !== undefined && materialType !== three_1.MeshBasicMaterial) {
2129
- pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture, three_1.SRGBColorSpace));
2130
- }
2131
- return Promise.all(pending).then(function () {
2132
- const material = new materialType(materialParams);
2133
- if (materialDef.name)
2134
- material.name = materialDef.name;
2135
- assignExtrasToUserData(material, materialDef);
2136
- parser.associations.set(material, { materials: materialIndex });
2137
- if (materialDef.extensions)
2138
- addUnknownExtensionsToUserData(extensions, material, materialDef);
2139
- return material;
2140
- });
2141
- }
2142
- /** When Object3D instances are targeted by animation, they need unique names. */
2143
- createUniqueName(originalName) {
2144
- const sanitizedName = three_1.PropertyBinding.sanitizeNodeName(originalName || '');
2145
- if (sanitizedName in this.nodeNamesUsed) {
2146
- return sanitizedName + '_' + (++this.nodeNamesUsed[sanitizedName]);
2147
- }
2148
- else {
2149
- this.nodeNamesUsed[sanitizedName] = 0;
2150
- return sanitizedName;
2151
- }
2152
- }
2153
- /**
2154
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
2155
- *
2156
- * Creates BufferGeometries from primitives.
2157
- *
2158
- * @param {Array<GLTF.Primitive>} primitives
2159
- * @return {Promise<Array<BufferGeometry>>}
2160
- */
2161
- loadGeometries(primitives) {
2162
- const parser = this;
2163
- const extensions = this.extensions;
2164
- const cache = this.primitiveCache;
2165
- function createDracoPrimitive(primitive) {
2166
- return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]
2167
- .decodePrimitive(primitive, parser)
2168
- .then(function (geometry) {
2169
- return addPrimitiveAttributes(geometry, primitive, parser);
2170
- });
2171
- }
2172
- const pending = [];
2173
- for (let i = 0, il = primitives.length; i < il; i++) {
2174
- const primitive = primitives[i];
2175
- const cacheKey = createPrimitiveKey(primitive);
2176
- // See if we've already created this geometry
2177
- const cached = cache[cacheKey];
2178
- if (cached) {
2179
- // Use the cached geometry if it exists
2180
- pending.push(cached.promise);
2181
- }
2182
- else {
2183
- let geometryPromise;
2184
- if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
2185
- // Use DRACO geometry if available
2186
- geometryPromise = createDracoPrimitive(primitive);
2187
- }
2188
- else {
2189
- // Otherwise create a new geometry
2190
- geometryPromise = addPrimitiveAttributes(new three_1.BufferGeometry(), primitive, parser);
2191
- }
2192
- // Cache this geometry
2193
- cache[cacheKey] = { primitive: primitive, promise: geometryPromise };
2194
- pending.push(geometryPromise);
2195
- }
2196
- }
2197
- return Promise.all(pending);
2198
- }
2199
- /**
2200
- * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
2201
- * @param {number} meshIndex
2202
- * @return {Promise<Group|Mesh|SkinnedMesh>}
2203
- */
2204
- loadMesh(meshIndex) {
2205
- const parser = this;
2206
- const json = this.json;
2207
- const extensions = this.extensions;
2208
- const meshDef = json.meshes[meshIndex];
2209
- const primitives = meshDef.primitives;
2210
- const pending = [];
2211
- for (let i = 0, il = primitives.length; i < il; i++) {
2212
- const material = primitives[i].material === undefined
2213
- ? createDefaultMaterial(this.cache)
2214
- : this.getDependency('material', primitives[i].material);
2215
- pending.push(material);
2216
- }
2217
- pending.push(parser.loadGeometries(primitives));
2218
- return Promise.all(pending).then(function (results) {
2219
- const materials = results.slice(0, results.length - 1);
2220
- const geometries = results[results.length - 1];
2221
- const meshes = [];
2222
- for (let i = 0, il = geometries.length; i < il; i++) {
2223
- const geometry = geometries[i];
2224
- const primitive = primitives[i];
2225
- // 1. create Mesh
2226
- let mesh;
2227
- const material = materials[i];
2228
- if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
2229
- primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
2230
- primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
2231
- primitive.mode === undefined) {
2232
- // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
2233
- mesh = meshDef.isSkinnedMesh === true
2234
- ? new three_1.SkinnedMesh(geometry, material)
2235
- : new three_1.Mesh(geometry, material);
2236
- if (mesh.isSkinnedMesh === true) {
2237
- // normalize skin weights to fix malformed assets (see #15319)
2238
- mesh.normalizeSkinWeights();
2239
- }
2240
- if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
2241
- mesh.geometry = (0, buffer_geometry_utils_1.toTrianglesDrawMode)(mesh.geometry, three_1.TriangleStripDrawMode);
2242
- }
2243
- else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
2244
- mesh.geometry = (0, buffer_geometry_utils_1.toTrianglesDrawMode)(mesh.geometry, three_1.TriangleFanDrawMode);
2245
- }
2246
- }
2247
- else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
2248
- mesh = new three_1.LineSegments(geometry, material);
2249
- }
2250
- else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
2251
- mesh = new three_1.Line(geometry, material);
2252
- }
2253
- else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
2254
- mesh = new three_1.LineLoop(geometry, material);
2255
- }
2256
- else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
2257
- mesh = new three_1.Points(geometry, material);
2258
- }
2259
- else {
2260
- throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
2261
- }
2262
- if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
2263
- updateMorphTargets(mesh, meshDef);
2264
- }
2265
- mesh.name = parser.createUniqueName(meshDef.name || ('mesh_' + meshIndex));
2266
- assignExtrasToUserData(mesh, meshDef);
2267
- if (primitive.extensions)
2268
- addUnknownExtensionsToUserData(extensions, mesh, primitive);
2269
- parser.assignFinalMaterial(mesh);
2270
- meshes.push(mesh);
2271
- }
2272
- for (let i = 0, il = meshes.length; i < il; i++) {
2273
- parser.associations.set(meshes[i], {
2274
- meshes: meshIndex,
2275
- primitives: i
2276
- });
2277
- }
2278
- if (meshes.length === 1) {
2279
- if (meshDef.extensions)
2280
- addUnknownExtensionsToUserData(extensions, meshes[0], meshDef);
2281
- return meshes[0];
2282
- }
2283
- const group = new three_1.Group();
2284
- if (meshDef.extensions)
2285
- addUnknownExtensionsToUserData(extensions, group, meshDef);
2286
- parser.associations.set(group, { meshes: meshIndex });
2287
- for (let i = 0, il = meshes.length; i < il; i++) {
2288
- group.add(meshes[i]);
2289
- }
2290
- return group;
2291
- });
2292
- }
2293
- /**
2294
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
2295
- * @param {number} cameraIndex
2296
- * @return {Promise<THREE.Camera>}
2297
- */
2298
- loadCamera(cameraIndex) {
2299
- let camera;
2300
- const cameraDef = this.json.cameras[cameraIndex];
2301
- const params = cameraDef[cameraDef.type];
2302
- if (!params) {
2303
- console.warn('THREE.GLTFLoader: Missing camera parameters.');
2304
- return;
2305
- }
2306
- if (cameraDef.type === 'perspective') {
2307
- camera = new three_1.PerspectiveCamera(three_1.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
2308
- }
2309
- else if (cameraDef.type === 'orthographic') {
2310
- camera = new three_1.OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar);
2311
- }
2312
- if (cameraDef.name)
2313
- camera.name = this.createUniqueName(cameraDef.name);
2314
- assignExtrasToUserData(camera, cameraDef);
2315
- return Promise.resolve(camera);
2316
- }
2317
- /**
2318
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
2319
- * @param {number} skinIndex
2320
- * @return {Promise<Skeleton>}
2321
- */
2322
- loadSkin(skinIndex) {
2323
- const skinDef = this.json.skins[skinIndex];
2324
- const pending = [];
2325
- for (let i = 0, il = skinDef.joints.length; i < il; i++) {
2326
- pending.push(this._loadNodeShallow(skinDef.joints[i]));
2327
- }
2328
- if (skinDef.inverseBindMatrices !== undefined) {
2329
- pending.push(this.getDependency('accessor', skinDef.inverseBindMatrices));
2330
- }
2331
- else {
2332
- pending.push(null);
2333
- }
2334
- return Promise.all(pending).then(function (results) {
2335
- const inverseBindMatrices = results.pop();
2336
- const jointNodes = results;
2337
- // Note that bones (joint nodes) may or may not be in the
2338
- // scene graph at this time.
2339
- const bones = [];
2340
- const boneInverses = [];
2341
- for (let i = 0, il = jointNodes.length; i < il; i++) {
2342
- const jointNode = jointNodes[i];
2343
- if (jointNode) {
2344
- bones.push(jointNode);
2345
- const mat = new three_1.Matrix4();
2346
- if (inverseBindMatrices !== null) {
2347
- mat.fromArray(inverseBindMatrices.array, i * 16);
2348
- }
2349
- boneInverses.push(mat);
2350
- }
2351
- else {
2352
- console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[i]);
2353
- }
2354
- }
2355
- return new three_1.Skeleton(bones, boneInverses);
2356
- });
2357
- }
2358
- /**
2359
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
2360
- * @param {number} animationIndex
2361
- * @return {Promise<AnimationClip>}
2362
- */
2363
- loadAnimation(animationIndex) {
2364
- const json = this.json;
2365
- const parser = this;
2366
- const animationDef = json.animations[animationIndex];
2367
- const animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
2368
- const pendingNodes = [];
2369
- const pendingInputAccessors = [];
2370
- const pendingOutputAccessors = [];
2371
- const pendingSamplers = [];
2372
- const pendingTargets = [];
2373
- for (let i = 0, il = animationDef.channels.length; i < il; i++) {
2374
- const channel = animationDef.channels[i];
2375
- const sampler = animationDef.samplers[channel.sampler];
2376
- const target = channel.target;
2377
- const name = target.node;
2378
- const input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
2379
- const output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
2380
- if (target.node === undefined)
2381
- continue;
2382
- pendingNodes.push(this.getDependency('node', name));
2383
- pendingInputAccessors.push(this.getDependency('accessor', input));
2384
- pendingOutputAccessors.push(this.getDependency('accessor', output));
2385
- pendingSamplers.push(sampler);
2386
- pendingTargets.push(target);
2387
- }
2388
- return Promise.all([
2389
- Promise.all(pendingNodes),
2390
- Promise.all(pendingInputAccessors),
2391
- Promise.all(pendingOutputAccessors),
2392
- Promise.all(pendingSamplers),
2393
- Promise.all(pendingTargets)
2394
- ]).then(function (dependencies) {
2395
- const nodes = dependencies[0];
2396
- const inputAccessors = dependencies[1];
2397
- const outputAccessors = dependencies[2];
2398
- const samplers = dependencies[3];
2399
- const targets = dependencies[4];
2400
- const tracks = [];
2401
- for (let i = 0, il = nodes.length; i < il; i++) {
2402
- const node = nodes[i];
2403
- const inputAccessor = inputAccessors[i];
2404
- const outputAccessor = outputAccessors[i];
2405
- const sampler = samplers[i];
2406
- const target = targets[i];
2407
- if (node === undefined)
2408
- continue;
2409
- if (node.updateMatrix) {
2410
- node.updateMatrix();
2411
- }
2412
- const createdTracks = parser._createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target);
2413
- if (createdTracks) {
2414
- for (let k = 0; k < createdTracks.length; k++) {
2415
- tracks.push(createdTracks[k]);
2416
- }
2417
- }
2418
- }
2419
- return new three_1.AnimationClip(animationName, undefined, tracks);
2420
- });
2421
- }
2422
- createNodeMesh(nodeIndex) {
2423
- const json = this.json;
2424
- const parser = this;
2425
- const nodeDef = json.nodes[nodeIndex];
2426
- if (nodeDef.mesh === undefined)
2427
- return null;
2428
- return parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
2429
- const node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh);
2430
- // if weights are provided on the node, override weights on the mesh.
2431
- if (nodeDef.weights !== undefined) {
2432
- node.traverse(function (o) {
2433
- if (!o.isMesh)
2434
- return;
2435
- for (let i = 0, il = nodeDef.weights.length; i < il; i++) {
2436
- o.morphTargetInfluences[i] = nodeDef.weights[i];
2437
- }
2438
- });
2439
- }
2440
- return node;
2441
- });
2442
- }
2443
- /**
2444
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
2445
- * @param {number} nodeIndex
2446
- * @return {Promise<Object3D>}
2447
- */
2448
- loadNode(nodeIndex) {
2449
- const json = this.json;
2450
- const parser = this;
2451
- const nodeDef = json.nodes[nodeIndex];
2452
- const nodePending = parser._loadNodeShallow(nodeIndex);
2453
- const childPending = [];
2454
- const childrenDef = nodeDef.children || [];
2455
- for (let i = 0, il = childrenDef.length; i < il; i++) {
2456
- childPending.push(parser.getDependency('node', childrenDef[i]));
2457
- }
2458
- const skeletonPending = nodeDef.skin === undefined
2459
- ? Promise.resolve(null)
2460
- : parser.getDependency('skin', nodeDef.skin);
2461
- return Promise.all([
2462
- nodePending,
2463
- Promise.all(childPending),
2464
- skeletonPending
2465
- ]).then(function (results) {
2466
- const node = results[0];
2467
- const children = results[1];
2468
- const skeleton = results[2];
2469
- if (skeleton !== null) {
2470
- // This full traverse should be fine because
2471
- // child glTF nodes have not been added to this node yet.
2472
- node.traverse(function (mesh) {
2473
- if (!mesh.isSkinnedMesh)
2474
- return;
2475
- mesh.bind(skeleton, _identityMatrix);
2476
- });
2477
- }
2478
- for (let i = 0, il = children.length; i < il; i++) {
2479
- node.add(children[i]);
2480
- }
2481
- return node;
2482
- });
2483
- }
2484
- // ._loadNodeShallow() parses a single node.
2485
- // skin and child nodes are created and added in .loadNode() (no '_' prefix).
2486
- _loadNodeShallow(nodeIndex) {
2487
- const json = this.json;
2488
- const extensions = this.extensions;
2489
- const parser = this;
2490
- // This method is called from .loadNode() and .loadSkin().
2491
- // Cache a node to avoid duplication.
2492
- if (this.nodeCache[nodeIndex] !== undefined) {
2493
- return this.nodeCache[nodeIndex];
2494
- }
2495
- const nodeDef = json.nodes[nodeIndex];
2496
- // reserve node's name before its dependencies, so the root has the intended name.
2497
- const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : '';
2498
- const pending = [];
2499
- const meshPromise = parser._invokeOne(function (ext) {
2500
- return ext.createNodeMesh && ext.createNodeMesh(nodeIndex);
2501
- });
2502
- if (meshPromise) {
2503
- pending.push(meshPromise);
2504
- }
2505
- if (nodeDef.camera !== undefined) {
2506
- pending.push(parser.getDependency('camera', nodeDef.camera).then(function (camera) {
2507
- return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera);
2508
- }));
2509
- }
2510
- parser._invokeAll(function (ext) {
2511
- return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex);
2512
- }).forEach(function (promise) {
2513
- pending.push(promise);
2514
- });
2515
- this.nodeCache[nodeIndex] = Promise.all(pending).then(function (objects) {
2516
- let node;
2517
- // .isBone isn't in glTF spec. See ._markDefs
2518
- if (nodeDef.isBone === true) {
2519
- node = new three_1.Bone();
2520
- }
2521
- else if (objects.length > 1) {
2522
- node = new three_1.Group();
2523
- }
2524
- else if (objects.length === 1) {
2525
- node = objects[0];
2526
- }
2527
- else {
2528
- node = new three_1.Object3D();
2529
- }
2530
- if (node !== objects[0]) {
2531
- for (let i = 0, il = objects.length; i < il; i++) {
2532
- node.add(objects[i]);
2533
- }
2534
- }
2535
- if (nodeDef.name) {
2536
- node.userData.name = nodeDef.name;
2537
- node.name = nodeName;
2538
- }
2539
- assignExtrasToUserData(node, nodeDef);
2540
- if (nodeDef.extensions)
2541
- addUnknownExtensionsToUserData(extensions, node, nodeDef);
2542
- if (nodeDef.matrix !== undefined) {
2543
- const matrix = new three_1.Matrix4();
2544
- matrix.fromArray(nodeDef.matrix);
2545
- node.applyMatrix4(matrix);
2546
- }
2547
- else {
2548
- if (nodeDef.translation !== undefined) {
2549
- node.position.fromArray(nodeDef.translation);
2550
- }
2551
- if (nodeDef.rotation !== undefined) {
2552
- node.quaternion.fromArray(nodeDef.rotation);
2553
- }
2554
- if (nodeDef.scale !== undefined) {
2555
- node.scale.fromArray(nodeDef.scale);
2556
- }
2557
- }
2558
- if (!parser.associations.has(node)) {
2559
- parser.associations.set(node, {});
2560
- }
2561
- parser.associations.get(node).nodes = nodeIndex;
2562
- return node;
2563
- });
2564
- return this.nodeCache[nodeIndex];
2565
- }
2566
- /**
2567
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
2568
- * @param {number} sceneIndex
2569
- * @return {Promise<Group>}
2570
- */
2571
- loadScene(sceneIndex) {
2572
- const extensions = this.extensions;
2573
- const sceneDef = this.json.scenes[sceneIndex];
2574
- const parser = this;
2575
- // Loader returns Group, not Scene.
2576
- // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
2577
- const scene = new three_1.Group();
2578
- if (sceneDef.name)
2579
- scene.name = parser.createUniqueName(sceneDef.name);
2580
- assignExtrasToUserData(scene, sceneDef);
2581
- if (sceneDef.extensions)
2582
- addUnknownExtensionsToUserData(extensions, scene, sceneDef);
2583
- const nodeIds = sceneDef.nodes || [];
2584
- const pending = [];
2585
- for (let i = 0, il = nodeIds.length; i < il; i++) {
2586
- pending.push(parser.getDependency('node', nodeIds[i]));
2587
- }
2588
- return Promise.all(pending).then(function (nodes) {
2589
- for (let i = 0, il = nodes.length; i < il; i++) {
2590
- scene.add(nodes[i]);
2591
- }
2592
- // Removes dangling associations, associations that reference a node that
2593
- // didn't make it into the scene.
2594
- const reduceAssociations = (node) => {
2595
- const reducedAssociations = new Map();
2596
- for (const [key, value] of parser.associations) {
2597
- if (key instanceof three_1.Material || key instanceof three_1.Texture) {
2598
- reducedAssociations.set(key, value);
2599
- }
2600
- }
2601
- node.traverse((node) => {
2602
- const mappings = parser.associations.get(node);
2603
- if (mappings != null) {
2604
- reducedAssociations.set(node, mappings);
2605
- }
2606
- });
2607
- return reducedAssociations;
2608
- };
2609
- parser.associations = reduceAssociations(scene);
2610
- return scene;
2611
- });
2612
- }
2613
- _createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target) {
2614
- const tracks = [];
2615
- const targetName = node.name ? node.name : node.uuid;
2616
- const targetNames = [];
2617
- if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
2618
- node.traverse(function (object) {
2619
- if (object.morphTargetInfluences) {
2620
- targetNames.push(object.name ? object.name : object.uuid);
2621
- }
2622
- });
2623
- }
2624
- else {
2625
- targetNames.push(targetName);
2626
- }
2627
- let TypedKeyframeTrack;
2628
- switch (PATH_PROPERTIES[target.path]) {
2629
- case PATH_PROPERTIES.weights:
2630
- TypedKeyframeTrack = three_1.NumberKeyframeTrack;
2631
- break;
2632
- case PATH_PROPERTIES.rotation:
2633
- TypedKeyframeTrack = three_1.QuaternionKeyframeTrack;
2634
- break;
2635
- case PATH_PROPERTIES.position:
2636
- case PATH_PROPERTIES.scale:
2637
- TypedKeyframeTrack = three_1.VectorKeyframeTrack;
2638
- break;
2639
- default:
2640
- switch (outputAccessor.itemSize) {
2641
- case 1:
2642
- TypedKeyframeTrack = three_1.NumberKeyframeTrack;
2643
- break;
2644
- case 2:
2645
- case 3:
2646
- default:
2647
- TypedKeyframeTrack = three_1.VectorKeyframeTrack;
2648
- break;
2649
- }
2650
- break;
2651
- }
2652
- const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : three_1.InterpolateLinear;
2653
- const outputArray = this._getArrayFromAccessor(outputAccessor);
2654
- for (let j = 0, jl = targetNames.length; j < jl; j++) {
2655
- const track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation);
2656
- // Override interpolation with custom factory method.
2657
- if (sampler.interpolation === 'CUBICSPLINE') {
2658
- this._createCubicSplineTrackInterpolant(track);
2659
- }
2660
- tracks.push(track);
2661
- }
2662
- return tracks;
2663
- }
2664
- _getArrayFromAccessor(accessor) {
2665
- let outputArray = accessor.array;
2666
- if (accessor.normalized) {
2667
- const scale = getNormalizedComponentScale(outputArray.constructor);
2668
- const scaled = new Float32Array(outputArray.length);
2669
- for (let j = 0, jl = outputArray.length; j < jl; j++) {
2670
- scaled[j] = outputArray[j] * scale;
2671
- }
2672
- outputArray = scaled;
2673
- }
2674
- return outputArray;
2675
- }
2676
- _createCubicSplineTrackInterpolant(track) {
2677
- track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
2678
- // A CUBICSPLINE keyframe in glTF has three output values for each input value,
2679
- // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
2680
- // must be divided by three to get the interpolant's sampleSize argument.
2681
- const interpolantType = (this instanceof three_1.QuaternionKeyframeTrack) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
2682
- return new interpolantType(this.times, this.values, this.getValueSize() / 3, result);
2683
- };
2684
- // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
2685
- track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
2686
- }
2687
- }
2688
- /**
2689
- * @param {BufferGeometry} geometry
2690
- * @param {GLTF.Primitive} primitiveDef
2691
- * @param {GLTFParser} parser
2692
- */
2693
- function computeBounds(geometry, primitiveDef, parser) {
2694
- const attributes = primitiveDef.attributes;
2695
- const box = new three_1.Box3();
2696
- if (attributes.POSITION !== undefined) {
2697
- const accessor = parser.json.accessors[attributes.POSITION];
2698
- const min = accessor.min;
2699
- const max = accessor.max;
2700
- // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
2701
- if (min !== undefined && max !== undefined) {
2702
- box.set(new three_1.Vector3(min[0], min[1], min[2]), new three_1.Vector3(max[0], max[1], max[2]));
2703
- if (accessor.normalized) {
2704
- const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]);
2705
- box.min.multiplyScalar(boxScale);
2706
- box.max.multiplyScalar(boxScale);
2707
- }
2708
- }
2709
- else {
2710
- console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
2711
- return;
2712
- }
2713
- }
2714
- else {
2715
- return;
2716
- }
2717
- const targets = primitiveDef.targets;
2718
- if (targets !== undefined) {
2719
- const maxDisplacement = new three_1.Vector3();
2720
- const vector = new three_1.Vector3();
2721
- for (let i = 0, il = targets.length; i < il; i++) {
2722
- const target = targets[i];
2723
- if (target.POSITION !== undefined) {
2724
- const accessor = parser.json.accessors[target.POSITION];
2725
- const min = accessor.min;
2726
- const max = accessor.max;
2727
- // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
2728
- if (min !== undefined && max !== undefined) {
2729
- // we need to get max of absolute components because target weight is [-1,1]
2730
- vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])));
2731
- vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])));
2732
- vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2])));
2733
- if (accessor.normalized) {
2734
- const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]);
2735
- vector.multiplyScalar(boxScale);
2736
- }
2737
- // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
2738
- // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
2739
- // are used to implement key-frame animations and as such only two are active at a time - this results in very large
2740
- // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
2741
- maxDisplacement.max(vector);
2742
- }
2743
- else {
2744
- console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
2745
- }
2746
- }
2747
- }
2748
- // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
2749
- box.expandByVector(maxDisplacement);
2750
- }
2751
- geometry.boundingBox = box;
2752
- const sphere = new three_1.Sphere();
2753
- box.getCenter(sphere.center);
2754
- sphere.radius = box.min.distanceTo(box.max) / 2;
2755
- geometry.boundingSphere = sphere;
2756
- }
2757
- /**
2758
- * @param {BufferGeometry} geometry
2759
- * @param {GLTF.Primitive} primitiveDef
2760
- * @param {GLTFParser} parser
2761
- * @return {Promise<BufferGeometry>}
2762
- */
2763
- function addPrimitiveAttributes(geometry, primitiveDef, parser) {
2764
- const attributes = primitiveDef.attributes;
2765
- const pending = [];
2766
- function assignAttributeAccessor(accessorIndex, attributeName) {
2767
- return parser.getDependency('accessor', accessorIndex)
2768
- .then(function (accessor) {
2769
- geometry.setAttribute(attributeName, accessor);
2770
- });
2771
- }
2772
- for (const gltfAttributeName in attributes) {
2773
- const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase();
2774
- // Skip attributes already provided by e.g. Draco extension.
2775
- if (threeAttributeName in geometry.attributes)
2776
- continue;
2777
- pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
2778
- }
2779
- if (primitiveDef.indices !== undefined && !geometry.index) {
2780
- const accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
2781
- geometry.setIndex(accessor);
2782
- });
2783
- pending.push(accessor);
2784
- }
2785
- if (three_1.ColorManagement.workingColorSpace !== three_1.LinearSRGBColorSpace && 'COLOR_0' in attributes) {
2786
- console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${three_1.ColorManagement.workingColorSpace}" not supported.`);
2787
- }
2788
- assignExtrasToUserData(geometry, primitiveDef);
2789
- computeBounds(geometry, primitiveDef, parser);
2790
- return Promise.all(pending).then(function () {
2791
- return primitiveDef.targets !== undefined
2792
- ? addMorphTargets(geometry, primitiveDef.targets, parser)
2793
- : geometry;
2794
- });
2795
- }
2796
- //# sourceMappingURL=gltf-loader.js.map