itowns 2.44.3-next.9 → 2.45.0

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