itowns 2.45.1-next.0 → 2.45.1-next.1

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