Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       140       150       160       1701import {2	AnimationClip,3	Bone,4	Box3,5	BufferAttribute,6	BufferGeometry,7	ClampToEdgeWrapping,8	Color,9	ColorManagement,10	DirectionalLight,11	DoubleSide,12	FileLoader,13	FrontSide,14	Group,15	ImageBitmapLoader,16	InstancedMesh,17	InterleavedBuffer,18	InterleavedBufferAttribute,19	Interpolant,20	InterpolateDiscrete,21	InterpolateLinear,22	Line,23	LineBasicMaterial,24	LineLoop,25	LineSegments,26	LinearFilter,27	LinearMipmapLinearFilter,28	LinearMipmapNearestFilter,29	LinearSRGBColorSpace,30	Loader,31	LoaderUtils,32	Material,33	MathUtils,34	Matrix4,35	Mesh,36	MeshBasicMaterial,37	MeshPhysicalMaterial,38	MeshStandardMaterial,39	MirroredRepeatWrapping,40	NearestFilter,41	NearestMipmapLinearFilter,42	NearestMipmapNearestFilter,43	NumberKeyframeTrack,44	Object3D,45	OrthographicCamera,46	PerspectiveCamera,47	PointLight,48	Points,49	PointsMaterial,50	PropertyBinding,51	Quaternion,52	QuaternionKeyframeTrack,53	RepeatWrapping,54	Skeleton,55	SkinnedMesh,56	Sphere,57	SpotLight,58	Texture,59	TextureLoader,60	TriangleFanDrawMode,61	TriangleStripDrawMode,62	Vector2,63	Vector3,64	VectorKeyframeTrack,65	SRGBColorSpace,66	InstancedBufferAttribute67} from 'three';68import { toTrianglesDrawMode } from '../utils/BufferGeometryUtils.js';69import { clone } from '../utils/SkeletonUtils.js';7071/**72 * A loader for the glTF 2.0 format.73 *74 * [glTF](https://www.khronos.org/gltf/) (GL Transmission Format) is an [open format specification]{@link https://github.com/KhronosGroup/glTF/tree/main/specification/2.0)75 * for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb)76 * format. External files store textures (.jpg, .png) and additional binary data (.bin). A glTF asset may deliver77 * one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights,78 * and/or cameras.79 *80 * `GLTFLoader` uses {@link ImageBitmapLoader} whenever possible. Be advised that image bitmaps are not81 * automatically GC-collected when they are no longer referenced, and they require special handling during82 * the disposal process.83 *84 * `GLTFLoader` supports the following glTF 2.0 extensions:85 * - KHR_draco_mesh_compression86 * - KHR_lights_punctual87 * - KHR_materials_anisotropy88 * - KHR_materials_clearcoat89 * - KHR_materials_diffuse_roughness90 * - KHR_materials_dispersion91 * - KHR_materials_emissive_strength92 * - KHR_materials_ior93 * - KHR_materials_specular94 * - KHR_materials_transmission95 * - KHR_materials_iridescence96 * - KHR_materials_unlit97 * - KHR_materials_volume98 * - KHR_mesh_quantization99 * - KHR_meshopt_compression100 * - KHR_texture_basisu101 * - KHR_texture_transform102 * - EXT_materials_bump103 * - EXT_meshopt_compression104 * - EXT_mesh_gpu_instancing105 * - EXT_texture_avif106 * - EXT_texture_webp107 *108 * The following glTF 2.0 extensions are supported by separately registered plugins:109 * - KHR_gaussian_splatting110 * - [KHR_materials_variants](https://github.com/takahirox/three-gltf-extensions)111 * - [MSFT_texture_dds](https://github.com/takahirox/three-gltf-extensions)112 * - [KHR_animation_pointer](https://github.com/needle-tools/three-animation-pointer)113 * - [NEEDLE_progressive](https://github.com/needle-tools/gltf-progressive)114 *115 * ```js116 * const loader = new GLTFLoader();117 *118 * // Optional: Provide a DRACOLoader instance to decode compressed mesh data119 * const dracoLoader = new DRACOLoader();120 * dracoLoader.setDecoderPath( '/examples/jsm/libs/draco/' );121 * loader.setDRACOLoader( dracoLoader );122 *123 * const gltf = await loader.loadAsync( 'models/gltf/duck/duck.gltf' );124 * scene.add( gltf.scene );125 * ```126 *127 * @augments Loader128 * @three_import import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';129 */130class GLTFLoader extends Loader {131132	/**133	 * Constructs a new glTF loader.134	 *135	 * @param {LoadingManager} [manager] - The loading manager.136	 */137	constructor( manager ) {138139		super( manager );140141		this.dracoLoader = null;142		this.ktx2Loader = null;143		this.meshoptDecoder = null;144145		this.pluginCallbacks = [];146147		this.register( function ( parser ) {148149			return new GLTFMaterialsClearcoatExtension( parser );150151		} );152153		this.register( function ( parser ) {154155			return new GLTFMaterialsDiffuseRoughnessExtension( parser );156157		} );158159		this.register( function ( parser ) {160161			return new GLTFMaterialsDispersionExtension( parser );162163		} );164165		this.register( function ( parser ) {166167			return new GLTFTextureBasisUExtension( parser );168169		} );170171		this.register( function ( parser ) {172173			return new GLTFTextureWebPExtension( parser );174175		} );176177		this.register( function ( parser ) {178179			return new GLTFTextureAVIFExtension( parser );180181		} );182183		this.register( function ( parser ) {184185			return new GLTFMaterialsSheenExtension( parser );186187		} );188189		this.register( function ( parser ) {190191			return new GLTFMaterialsTransmissionExtension( parser );192193		} );194195		this.register( function ( parser ) {196197			return new GLTFMaterialsVolumeExtension( parser );198199		} );200201		this.register( function ( parser ) {202203			return new GLTFMaterialsIorExtension( parser );204205		} );206207		this.register( function ( parser ) {208209			return new GLTFMaterialsEmissiveStrengthExtension( parser );210211		} );212213		this.register( function ( parser ) {214215			return new GLTFMaterialsSpecularExtension( parser );216217		} );218219		this.register( function ( parser ) {220221			return new GLTFMaterialsIridescenceExtension( parser );222223		} );224225		this.register( function ( parser ) {226227			return new GLTFMaterialsAnisotropyExtension( parser );228229		} );230231		this.register( function ( parser ) {232233			return new GLTFMaterialsBumpExtension( parser );234235		} );236237		this.register( function ( parser ) {238239			return new GLTFLightsExtension( parser );240241		} );242243		this.register( function ( parser ) {244245			return new GLTFMeshoptCompression( parser, EXTENSIONS.EXT_MESHOPT_COMPRESSION );246247		} );248249		this.register( function ( parser ) {250251			return new GLTFMeshoptCompression( parser, EXTENSIONS.KHR_MESHOPT_COMPRESSION );252253		} );254255		this.register( function ( parser ) {256257			return new GLTFMeshGpuInstancing( parser );258259		} );260261	}262263	/**264	 * Starts loading from the given URL and passes the loaded glTF asset265	 * to the `onLoad()` callback.266	 *267	 * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.268	 * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.269	 * @param {onProgressCallback} onProgress - Executed while the loading is in progress.270	 * @param {onErrorCallback} onError - Executed when errors occur.271	 */272	load( url, onLoad, onProgress, onError ) {273274		const scope = this;275276		let resourcePath;277278		if ( this.resourcePath !== '' ) {279280			resourcePath = this.resourcePath;281282		} else if ( this.path !== '' ) {283284			// If a base path is set, resources will be relative paths from that plus the relative path of the gltf file285			// Example  path = 'https://my-cnd-server.com/', url = 'assets/models/model.gltf'286			// resourcePath = 'https://my-cnd-server.com/assets/models/'287			// referenced resource 'model.bin' will be loaded from 'https://my-cnd-server.com/assets/models/model.bin'288			// referenced resource '../textures/texture.png' will be loaded from 'https://my-cnd-server.com/assets/textures/texture.png'289			const relativeUrl = LoaderUtils.extractUrlBase( url );290			resourcePath = LoaderUtils.resolveURL( relativeUrl, this.path );291292		} else {293294			resourcePath = LoaderUtils.extractUrlBase( url );295296		}297298		// Tells the LoadingManager to track an extra item, which resolves after299		// the model is fully loaded. This means the count of items loaded will300		// be incorrect, but ensures manager.onLoad() does not fire early.301		this.manager.itemStart( url );302303		const _onError = function ( e ) {304305			if ( onError ) {306307				onError( e );308309			} else {310311				console.error( e );312313			}314315			scope.manager.itemError( url );316			scope.manager.itemEnd( url );317318		};319320		const loader = new FileLoader( this.manager );321		loader.setPriority( this.priority );322		loader.setCache( this.cache );323324		loader.setPath( this.path );325		loader.setResponseType( 'arraybuffer' );326		loader.setRequestHeader( this.requestHeader );327		loader.setWithCredentials( this.withCredentials );328329		loader.load( url, function ( data ) {330331			try {332333				scope.parse( data, resourcePath, function ( gltf ) {334335					onLoad( gltf );336337					scope.manager.itemEnd( url );338339				}, _onError );340341			} catch ( e ) {342343				_onError( e );344345			}346347		}, onProgress, _onError );348349	}350351	/**352	 * Sets the given Draco loader to this loader. Required for decoding assets353	 * compressed with the `KHR_draco_mesh_compression` extension.354	 *355	 * @param {DRACOLoader} dracoLoader - The Draco loader to set.356	 * @return {GLTFLoader} A reference to this loader.357	 */358	setDRACOLoader( dracoLoader ) {359360		this.dracoLoader = dracoLoader;361		return this;362363	}364365	/**366	 * Sets the given KTX2 loader to this loader. Required for loading KTX2367	 * compressed textures.368	 *369	 * @param {KTX2Loader} ktx2Loader - The KTX2 loader to set.370	 * @return {GLTFLoader} A reference to this loader.371	 */372	setKTX2Loader( ktx2Loader ) {373374		this.ktx2Loader = ktx2Loader;375		return this;376377	}378379	/**380	 * Sets the given meshopt decoder. Required for decoding assets381	 * compressed with the `EXT_meshopt_compression` extension.382	 *383	 * @param {Object} meshoptDecoder - The meshopt decoder to set.384	 * @return {GLTFLoader} A reference to this loader.385	 */386	setMeshoptDecoder( meshoptDecoder ) {387388		this.meshoptDecoder = meshoptDecoder;389		return this;390391	}392393	/**394	 * Registers a plugin callback. This API is internally used to implement the various395	 * glTF extensions but can also used by third-party code to add additional logic396	 * to the loader.397	 *398	 * @param {function(parser:GLTFParser)} callback - The callback function to register.399	 * @return {GLTFLoader} A reference to this loader.400	 */401	register( callback ) {402403		if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {404405			this.pluginCallbacks.push( callback );406407		}408409		return this;410411	}412413	/**414	 * Unregisters a plugin callback.415	 *416	 * @param {Function} callback - The callback function to unregister.417	 * @return {GLTFLoader} A reference to this loader.418	 */419	unregister( callback ) {420421		if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {422423			this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );424425		}426427		return this;428429	}430431	/**432	 * Parses the given glTF data and returns the resulting group.433	 *434	 * @param {string|ArrayBuffer} data - The raw glTF data.435	 * @param {string} path - The URL base path.436	 * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.437	 * @param {onErrorCallback} onError - Executed when errors occur.438	 */439	parse( data, path, onLoad, onError ) {440441		let json;442		const extensions = {};443		const plugins = {};444		const textDecoder = new TextDecoder();445446		if ( typeof data === 'string' ) {447448			json = JSON.parse( data );449450		} else if ( data instanceof ArrayBuffer ) {451452			const magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) );453454			if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {455456				try {457458					extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );459460				} catch ( error ) {461462					if ( onError ) onError( error );463					return;464465				}466467				json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );468469			} else {470471				json = JSON.parse( textDecoder.decode( data ) );472473			}474475		} else {476477			json = data;478479		}480481		if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {482483			if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );484			return;485486		}487488		const parser = new GLTFParser( json, {489490			path: path || this.resourcePath || '',491			crossOrigin: this.crossOrigin,492			priority: this.priority,493			cache: this.cache,494			withCredentials: this.withCredentials,495			requestHeader: this.requestHeader,496			manager: this.manager,497			ktx2Loader: this.ktx2Loader,498			meshoptDecoder: this.meshoptDecoder499500		} );501502		parser.fileLoader.setRequestHeader( this.requestHeader );503504		for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {505506			const plugin = this.pluginCallbacks[ i ]( parser );507508			if ( ! plugin.name ) console.error( 'THREE.GLTFLoader: Invalid plugin found: missing name' );509510			plugins[ plugin.name ] = plugin;511512			// Workaround to avoid determining as unknown extension513			// in addUnknownExtensionsToUserData().514			// Remove this workaround if we move all the existing515			// extension handlers to plugin system516			extensions[ plugin.name ] = true;517518		}519520		if ( json.extensionsUsed ) {521522			for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {523524				const extensionName = json.extensionsUsed[ i ];525				const extensionsRequired = json.extensionsRequired || [];526527				switch ( extensionName ) {528529					case EXTENSIONS.KHR_MATERIALS_UNLIT:530						extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();531						break;532533					case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:534						extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );535						break;536537					case EXTENSIONS.KHR_TEXTURE_TRANSFORM:538						extensions[ extensionName ] = new GLTFTextureTransformExtension();539						break;540541					case EXTENSIONS.KHR_MESH_QUANTIZATION:542						extensions[ extensionName ] = new GLTFMeshQuantizationExtension();543						break;544545					default:546547						if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {548549							console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );550551						}552553				}554555			}556557		}558559		parser.setExtensions( extensions );560		parser.setPlugins( plugins );561		parser.parse( onLoad, onError );562563	}564565	/**566	 * Async version of {@link GLTFLoader#parse}.567	 *568	 * @async569	 * @param {string|ArrayBuffer} data - The raw glTF data.570	 * @param {string} path - The URL base path.571	 * @return {Promise<GLTFLoader~LoadObject>} A Promise that resolves with the loaded glTF when the parsing has been finished.572	 */573	parseAsync( data, path ) {574575		const scope = this;576577		return new Promise( function ( resolve, reject ) {578579			scope.parse( data, path, resolve, reject );580581		} );582583	}584585}586587/* GLTFREGISTRY */588589function GLTFRegistry() {590591	let objects = {};592593	return	{594595		get: function ( key ) {596597			return objects[ key ];598599		},600601		add: function ( key, object ) {602603			objects[ key ] = object;604605		},606607		remove: function ( key ) {608609			delete objects[ key ];610611		},612613		removeAll: function () {614615			objects = {};616617		}618619	};620621}622623/*********************************/624/********** EXTENSIONS ***********/625/*********************************/626627function getMaterialExtension( parser, materialIndex, extensionName ) {628629	const materialDef = parser.json.materials[ materialIndex ];630631	if ( materialDef.extensions && materialDef.extensions[ extensionName ] ) {632633		return materialDef.extensions[ extensionName ];634635	}636637	return null;638639}640641const EXTENSIONS = {642	KHR_BINARY_GLTF: 'KHR_binary_glTF',643	KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',644	KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',645	KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',646	KHR_MATERIALS_DIFFUSE_ROUGHNESS: 'KHR_materials_diffuse_roughness',647	KHR_MATERIALS_DISPERSION: 'KHR_materials_dispersion',648	KHR_MATERIALS_IOR: 'KHR_materials_ior',649	KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',650	KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',651	KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',652	KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',653	KHR_MATERIALS_ANISOTROPY: 'KHR_materials_anisotropy',654	KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',655	KHR_MATERIALS_VOLUME: 'KHR_materials_volume',656	KHR_TEXTURE_BASISU: 'KHR_texture_basisu',657	KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',658	KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',659	KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',660	EXT_MATERIALS_BUMP: 'EXT_materials_bump',661	EXT_TEXTURE_WEBP: 'EXT_texture_webp',662	EXT_TEXTURE_AVIF: 'EXT_texture_avif',663	EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',664	KHR_MESHOPT_COMPRESSION: 'KHR_meshopt_compression',665	EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'666};667668/**669 * Punctual Lights Extension670 *671 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual672 *673 * @private674 */675class GLTFLightsExtension {676677	constructor( parser ) {678679		this.parser = parser;680		this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;681682		// Object3D instance caches683		this.cache = { refs: {}, uses: {} };684685	}686687	_markDefs() {688689		const parser = this.parser;690		const nodeDefs = this.parser.json.nodes || [];691692		for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {693694			const nodeDef = nodeDefs[ nodeIndex ];695696			if ( nodeDef.extensions697					&& nodeDef.extensions[ this.name ]698					&& nodeDef.extensions[ this.name ].light !== undefined ) {699700				parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );701702			}703704		}705706	}707708	_loadLight( lightIndex ) {709710		const parser = this.parser;711		const cacheKey = 'light:' + lightIndex;712		let dependency = parser.cache.get( cacheKey );713714		if ( dependency ) return dependency;715716		const json = parser.json;717		const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};718		const lightDefs = extensions.lights || [];719		const lightDef = lightDefs[ lightIndex ];720		let lightNode;721722		const color = new Color( 0xffffff );723724		if ( lightDef.color !== undefined ) color.setRGB( lightDef.color[ 0 ], lightDef.color[ 1 ], lightDef.color[ 2 ], LinearSRGBColorSpace );725726		const range = lightDef.range !== undefined ? lightDef.range : 0;727728		switch ( lightDef.type ) {729730			case 'directional':731				lightNode = new DirectionalLight( color );732				lightNode.target.position.set( 0, 0, - 1 );733				lightNode.add( lightNode.target );734				break;735736			case 'point':737				lightNode = new PointLight( color );738				lightNode.distance = range;739				break;740741			case 'spot':742				lightNode = new SpotLight( color );743				lightNode.distance = range;744				// Handle spotlight properties.745				lightDef.spot = lightDef.spot || {};746				lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;747				lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;748				lightNode.angle = lightDef.spot.outerConeAngle;749				lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;750				lightNode.target.position.set( 0, 0, - 1 );751				lightNode.add( lightNode.target );752				break;753754			default:755				throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );756757		}758759		// Some lights (e.g. spot) default to a position other than the origin. Reset the position760		// here, because node-level parsing will only override position if explicitly specified.761		lightNode.position.set( 0, 0, 0 );762763		assignExtrasToUserData( lightNode, lightDef );764765		if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;766767		lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );768769		dependency = Promise.resolve( lightNode );770771		parser.cache.add( cacheKey, dependency );772773		return dependency;774775	}776777	getDependency( type, index ) {778779		if ( type !== 'light' ) return;780781		return this._loadLight( index );782783	}784785	createNodeAttachment( nodeIndex ) {786787		const self = this;788		const parser = this.parser;789		const json = parser.json;790		const nodeDef = json.nodes[ nodeIndex ];791		const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};792		const lightIndex = lightDef.light;793794		if ( lightIndex === undefined ) return null;795796		return this._loadLight( lightIndex ).then( function ( light ) {797798			return parser._getNodeRef( self.cache, lightIndex, light );799800		} );801802	}803804}805806/**807 * Unlit Materials Extension808 *809 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit810 *811 * @private812 */813class GLTFMaterialsUnlitExtension {814815	constructor() {816817		this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;818819	}820821	getMaterialType() {822823		return MeshBasicMaterial;824825	}826827	extendParams( materialParams, materialDef, parser ) {828829		const pending = [];830831		materialParams.color = new Color( 1.0, 1.0, 1.0 );832		materialParams.opacity = 1.0;833834		const metallicRoughness = materialDef.pbrMetallicRoughness;835836		if ( metallicRoughness ) {837838			if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {839840				const array = metallicRoughness.baseColorFactor;841842				materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace );843				materialParams.opacity = array[ 3 ];844845			}846847			if ( metallicRoughness.baseColorTexture !== undefined ) {848849				pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) );850851			}852853		}854855		return Promise.all( pending );856857	}858859}860861/**862 * Materials Emissive Strength Extension863 *864 * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md865 *866 * @private867 */868class GLTFMaterialsEmissiveStrengthExtension {869870	constructor( parser ) {871872		this.parser = parser;873		this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;874875	}876877	extendMaterialParams( materialIndex, materialParams ) {878879		const extension = getMaterialExtension( this.parser, materialIndex, this.name );880881		if ( extension === null ) return Promise.resolve();882883		if ( extension.emissiveStrength !== undefined ) {884885			materialParams.emissiveIntensity = extension.emissiveStrength;886887		}888889		return Promise.resolve();890891	}892893}894895/**896 * Clearcoat Materials Extension897 *898 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat899 *900 * @private901 */902class GLTFMaterialsClearcoatExtension {903904	constructor( parser ) {905906		this.parser = parser;907		this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;908909	}910911	getMaterialType( materialIndex ) {912913		const extension = getMaterialExtension( this.parser, materialIndex, this.name );914915		return extension !== null ? MeshPhysicalMaterial : null;916917	}918919	extendMaterialParams( materialIndex, materialParams ) {920921		const extension = getMaterialExtension( this.parser, materialIndex, this.name );922923		if ( extension === null ) return Promise.resolve();924925		const pending = [];926927		if ( extension.clearcoatFactor !== undefined ) {928929			materialParams.clearcoat = extension.clearcoatFactor;930931		}932933		if ( extension.clearcoatTexture !== undefined ) {934935			pending.push( this.parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );936937		}938939		if ( extension.clearcoatRoughnessFactor !== undefined ) {940941			materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;942943		}944945		if ( extension.clearcoatRoughnessTexture !== undefined ) {946947			pending.push( this.parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );948949		}950951		if ( extension.clearcoatNormalTexture !== undefined ) {952953			pending.push( this.parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );954955			if ( extension.clearcoatNormalTexture.scale !== undefined ) {956957				const scale = extension.clearcoatNormalTexture.scale;958959				materialParams.clearcoatNormalScale = new Vector2( scale, scale );960961			}962963		}964965		return Promise.all( pending );966967	}968969}970971/**972 * Diffuse Roughness Materials Extension973 *974 * Specification: https://github.com/MiiBond/glTF/tree/mbond/EXT_materials_diffuse_roughness/extensions/2.0/Khronos/KHR_materials_diffuse_roughness975 *976 * @private977 */978class GLTFMaterialsDiffuseRoughnessExtension {979980	constructor( parser ) {981982		this.parser = parser;983		this.name = EXTENSIONS.KHR_MATERIALS_DIFFUSE_ROUGHNESS;984985	}986987	getMaterialType( materialIndex ) {988989		const extension = getMaterialExtension( this.parser, materialIndex, this.name );990991		return extension !== null ? MeshPhysicalMaterial : null;992993	}994995	extendMaterialParams( materialIndex, materialParams ) {996997		const extension = getMaterialExtension( this.parser, materialIndex, this.name );998999		if ( extension === null ) return Promise.resolve();10001001		const pending = [];10021003		materialParams.diffuseRoughness = extension.diffuseRoughnessFactor !== undefined ? extension.diffuseRoughnessFactor : 0;10041005		if ( extension.diffuseRoughnessTexture !== undefined ) {10061007			pending.push( this.parser.assignTexture( materialParams, 'diffuseRoughnessMap', extension.diffuseRoughnessTexture ) );10081009		}10101011		return Promise.all( pending );10121013	}10141015}10161017/**1018 * Materials dispersion Extension1019 *1020 * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_dispersion1021 *1022 * @private1023 */1024class GLTFMaterialsDispersionExtension {10251026	constructor( parser ) {10271028		this.parser = parser;1029		this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION;10301031	}10321033	getMaterialType( materialIndex ) {10341035		const extension = getMaterialExtension( this.parser, materialIndex, this.name );10361037		return extension !== null ? MeshPhysicalMaterial : null;10381039	}10401041	extendMaterialParams( materialIndex, materialParams ) {10421043		const extension = getMaterialExtension( this.parser, materialIndex, this.name );10441045		if ( extension === null ) return Promise.resolve();10461047		materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0;10481049		return Promise.resolve();10501051	}10521053}10541055/**1056 * Iridescence Materials Extension1057 *1058 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence1059 *1060 * @private1061 */1062class GLTFMaterialsIridescenceExtension {10631064	constructor( parser ) {10651066		this.parser = parser;1067		this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;10681069	}10701071	getMaterialType( materialIndex ) {10721073		const extension = getMaterialExtension( this.parser, materialIndex, this.name );10741075		return extension !== null ? MeshPhysicalMaterial : null;10761077	}10781079	extendMaterialParams( materialIndex, materialParams ) {10801081		const extension = getMaterialExtension( this.parser, materialIndex, this.name );10821083		if ( extension === null ) return Promise.resolve();10841085		const pending = [];10861087		if ( extension.iridescenceFactor !== undefined ) {10881089			materialParams.iridescence = extension.iridescenceFactor;10901091		}10921093		if ( extension.iridescenceTexture !== undefined ) {10941095			pending.push( this.parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );10961097		}10981099		if ( extension.iridescenceIor !== undefined ) {11001101			materialParams.iridescenceIOR = extension.iridescenceIor;11021103		}11041105		if ( extension.iridescenceThicknessMinimum !== undefined ) {11061107			materialParams.iridescenceThicknessMinimum = extension.iridescenceThicknessMinimum;11081109		}11101111		if ( extension.iridescenceThicknessMaximum !== undefined ) {11121113			materialParams.iridescenceThicknessMaximum = extension.iridescenceThicknessMaximum;11141115		}11161117		if ( extension.iridescenceThicknessTexture !== undefined ) {11181119			pending.push( this.parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );11201121		}11221123		return Promise.all( pending );11241125	}11261127}11281129/**1130 * Sheen Materials Extension1131 *1132 * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen1133 *1134 * @private1135 */1136class GLTFMaterialsSheenExtension {11371138	constructor( parser ) {11391140		this.parser = parser;1141		this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;11421143	}11441145	getMaterialType( materialIndex ) {11461147		const extension = getMaterialExtension( this.parser, materialIndex, this.name );11481149		return extension !== null ? MeshPhysicalMaterial : null;11501151	}11521153	extendMaterialParams( materialIndex, materialParams ) {11541155		const extension = getMaterialExtension( this.parser, materialIndex, this.name );11561157		if ( extension === null ) return Promise.resolve();11581159		const pending = [];11601161		materialParams.sheenColor = new Color( 0, 0, 0 );1162		materialParams.sheenRoughness = 0;1163		materialParams.sheen = 1;11641165		if ( extension.sheenColorFactor !== undefined ) {11661167			const colorFactor = extension.sheenColorFactor;1168			materialParams.sheenColor.setRGB( colorFactor[ 0 ], colorFactor[ 1 ], colorFactor[ 2 ], LinearSRGBColorSpace );11691170		}11711172		if ( extension.sheenRoughnessFactor !== undefined ) {11731174			materialParams.sheenRoughness = extension.sheenRoughnessFactor;11751176		}11771178		if ( extension.sheenColorTexture !== undefined ) {11791180			pending.push( this.parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, SRGBColorSpace ) );11811182		}11831184		if ( extension.sheenRoughnessTexture !== undefined ) {11851186			pending.push( this.parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );11871188		}11891190		return Promise.all( pending );11911192	}11931194}11951196/**1197 * Transmission Materials Extension1198 *1199 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission1200 * Draft: https://github.com/KhronosGroup/glTF/pull/16981201 *1202 * @private1203 */1204class GLTFMaterialsTransmissionExtension {12051206	constructor( parser ) {12071208		this.parser = parser;1209		this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;12101211	}12121213	getMaterialType( materialIndex ) {12141215		const extension = getMaterialExtension( this.parser, materialIndex, this.name );12161217		return extension !== null ? MeshPhysicalMaterial : null;12181219	}12201221	extendMaterialParams( materialIndex, materialParams ) {12221223		const extension = getMaterialExtension( this.parser, materialIndex, this.name );12241225		if ( extension === null ) return Promise.resolve();12261227		const pending = [];12281229		if ( extension.transmissionFactor !== undefined ) {12301231			materialParams.transmission = extension.transmissionFactor;12321233		}12341235		if ( extension.transmissionTexture !== undefined ) {12361237			pending.push( this.parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );12381239		}12401241		return Promise.all( pending );12421243	}12441245}12461247/**1248 * Materials Volume Extension1249 *1250 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume1251 *1252 * @private1253 */1254class GLTFMaterialsVolumeExtension {12551256	constructor( parser ) {12571258		this.parser = parser;1259		this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;12601261	}12621263	getMaterialType( materialIndex ) {12641265		const extension = getMaterialExtension( this.parser, materialIndex, this.name );12661267		return extension !== null ? MeshPhysicalMaterial : null;12681269	}12701271	extendMaterialParams( materialIndex, materialParams ) {12721273		const extension = getMaterialExtension( this.parser, materialIndex, this.name );12741275		if ( extension === null ) return Promise.resolve();12761277		const pending = [];12781279		materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;12801281		if ( extension.thicknessTexture !== undefined ) {12821283			pending.push( this.parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );12841285		}12861287		materialParams.attenuationDistance = extension.attenuationDistance || Infinity;12881289		const colorArray = extension.attenuationColor || [ 1, 1, 1 ];1290		materialParams.attenuationColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace );12911292		return Promise.all( pending );12931294	}12951296}12971298/**1299 * Materials ior Extension1300 *1301 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior1302 *1303 * @private1304 */1305class GLTFMaterialsIorExtension {13061307	constructor( parser ) {13081309		this.parser = parser;1310		this.name = EXTENSIONS.KHR_MATERIALS_IOR;13111312	}13131314	getMaterialType( materialIndex ) {13151316		const extension = getMaterialExtension( this.parser, materialIndex, this.name );13171318		return extension !== null ? MeshPhysicalMaterial : null;13191320	}13211322	extendMaterialParams( materialIndex, materialParams ) {13231324		const extension = getMaterialExtension( this.parser, materialIndex, this.name );13251326		if ( extension === null ) return Promise.resolve();13271328		materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;13291330		if ( materialParams.ior === 0 ) materialParams.ior = 1000; // see #2616713311332		return Promise.resolve();13331334	}13351336}13371338/**1339 * Materials specular Extension1340 *1341 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular1342 *1343 * @private1344 */1345class GLTFMaterialsSpecularExtension {13461347	constructor( parser ) {13481349		this.parser = parser;1350		this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;13511352	}13531354	getMaterialType( materialIndex ) {13551356		const extension = getMaterialExtension( this.parser, materialIndex, this.name );13571358		return extension !== null ? MeshPhysicalMaterial : null;13591360	}13611362	extendMaterialParams( materialIndex, materialParams ) {13631364		const extension = getMaterialExtension( this.parser, materialIndex, this.name );13651366		if ( extension === null ) return Promise.resolve();13671368		const pending = [];13691370		materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;13711372		if ( extension.specularTexture !== undefined ) {13731374			pending.push( this.parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );13751376		}13771378		const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];1379		materialParams.specularColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace );13801381		if ( extension.specularColorTexture !== undefined ) {13821383			pending.push( this.parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, SRGBColorSpace ) );13841385		}13861387		return Promise.all( pending );13881389	}13901391}139213931394/**1395 * Materials bump Extension1396 *1397 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump1398 *1399 * @private1400 */1401class GLTFMaterialsBumpExtension {14021403	constructor( parser ) {14041405		this.parser = parser;1406		this.name = EXTENSIONS.EXT_MATERIALS_BUMP;14071408	}14091410	getMaterialType( materialIndex ) {14111412		const extension = getMaterialExtension( this.parser, materialIndex, this.name );14131414		return extension !== null ? MeshPhysicalMaterial : null;14151416	}14171418	extendMaterialParams( materialIndex, materialParams ) {14191420		const extension = getMaterialExtension( this.parser, materialIndex, this.name );14211422		if ( extension === null ) return Promise.resolve();14231424		const pending = [];14251426		materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1.0;14271428		if ( extension.bumpTexture !== undefined ) {14291430			pending.push( this.parser.assignTexture( materialParams, 'bumpMap', extension.bumpTexture ) );14311432		}14331434		return Promise.all( pending );14351436	}14371438}14391440/**1441 * Materials anisotropy Extension1442 *1443 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_anisotropy1444 *1445 * @private1446 */1447class GLTFMaterialsAnisotropyExtension {14481449	constructor( parser ) {14501451		this.parser = parser;1452		this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY;14531454	}14551456	getMaterialType( materialIndex ) {14571458		const extension = getMaterialExtension( this.parser, materialIndex, this.name );14591460		return extension !== null ? MeshPhysicalMaterial : null;14611462	}14631464	extendMaterialParams( materialIndex, materialParams ) {14651466		const extension = getMaterialExtension( this.parser, materialIndex, this.name );14671468		if ( extension === null ) return Promise.resolve();14691470		const pending = [];14711472		if ( extension.anisotropyStrength !== undefined ) {14731474			materialParams.anisotropy = extension.anisotropyStrength;14751476		}14771478		if ( extension.anisotropyRotation !== undefined ) {14791480			materialParams.anisotropyRotation = extension.anisotropyRotation;14811482		}14831484		if ( extension.anisotropyTexture !== undefined ) {14851486			pending.push( this.parser.assignTexture( materialParams, 'anisotropyMap', extension.anisotropyTexture ) );14871488		}14891490		return Promise.all( pending );14911492	}14931494}14951496/**1497 * BasisU Texture Extension1498 *1499 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu1500 *1501 * @private1502 */1503class GLTFTextureBasisUExtension {15041505	constructor( parser ) {15061507		this.parser = parser;1508		this.name = EXTENSIONS.KHR_TEXTURE_BASISU;15091510	}15111512	loadTexture( textureIndex ) {15131514		const parser = this.parser;1515		const json = parser.json;15161517		const textureDef = json.textures[ textureIndex ];15181519		if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {15201521			return null;15221523		}15241525		const extension = textureDef.extensions[ this.name ];1526		const loader = parser.options.ktx2Loader;15271528		if ( ! loader ) {15291530			if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {15311532				throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );15331534			} else {15351536				// Assumes that the extension is optional and that a fallback texture is present1537				return null;15381539			}15401541		}15421543		return parser.loadTextureImage( textureIndex, extension.source, loader );15441545	}15461547}15481549/**1550 * WebP Texture Extension1551 *1552 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp1553 *1554 * @private1555 */1556class GLTFTextureWebPExtension {15571558	constructor( parser ) {15591560		this.parser = parser;1561		this.name = EXTENSIONS.EXT_TEXTURE_WEBP;15621563	}15641565	loadTexture( textureIndex ) {15661567		const name = this.name;1568		const parser = this.parser;1569		const json = parser.json;15701571		const textureDef = json.textures[ textureIndex ];15721573		if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {15741575			return null;15761577		}15781579		const extension = textureDef.extensions[ name ];1580		const source = json.images[ extension.source ];15811582		let loader = parser.textureLoader;1583		if ( source.uri ) {15841585			const handler = parser.options.manager.getHandler( source.uri );1586			if ( handler !== null ) loader = handler;15871588		}15891590		return parser.loadTextureImage( textureIndex, extension.source, loader );15911592	}15931594}15951596/**1597 * AVIF Texture Extension1598 *1599 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif1600 *1601 * @private1602 */1603class GLTFTextureAVIFExtension {16041605	constructor( parser ) {16061607		this.parser = parser;1608		this.name = EXTENSIONS.EXT_TEXTURE_AVIF;16091610	}16111612	loadTexture( textureIndex ) {16131614		const name = this.name;1615		const parser = this.parser;1616		const json = parser.json;16171618		const textureDef = json.textures[ textureIndex ];16191620		if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {16211622			return null;16231624		}16251626		const extension = textureDef.extensions[ name ];1627		const source = json.images[ extension.source ];16281629		let loader = parser.textureLoader;1630		if ( source.uri ) {16311632			const handler = parser.options.manager.getHandler( source.uri );1633			if ( handler !== null ) loader = handler;16341635		}16361637		return parser.loadTextureImage( textureIndex, extension.source, loader );16381639	}16401641}16421643/**1644 * meshopt BufferView Compression Extension1645 *1646 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression1647 *1648 * @private1649 */1650class GLTFMeshoptCompression {16511652	constructor( parser, name ) {16531654		this.name = name;1655		this.parser = parser;16561657	}16581659	loadBufferView( index ) {16601661		const json = this.parser.json;1662		const bufferView = json.bufferViews[ index ];16631664		if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {16651666			const extensionDef = bufferView.extensions[ this.name ];16671668			const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );1669			const decoder = this.parser.options.meshoptDecoder;16701671			if ( ! decoder || ! decoder.supported ) {16721673				if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {16741675					throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );16761677				} else {16781679					// Assumes that the extension is optional and that fallback buffer data is present1680					return null;16811682				}16831684			}16851686			return buffer.then( function ( res ) {16871688				const byteOffset = extensionDef.byteOffset || 0;1689				const byteLength = extensionDef.byteLength || 0;16901691				const count = extensionDef.count;1692				const stride = extensionDef.byteStride;16931694				const source = new Uint8Array( res, byteOffset, byteLength );16951696				if ( decoder.decodeGltfBufferAsync ) {16971698					return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {16991700						return res.buffer;17011702					} );17031704				} else {17051706					// Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync1707					return decoder.ready.then( function () {17081709						const result = new ArrayBuffer( count * stride );1710						decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );1711						return result;17121713					} );17141715				}17161717			} );17181719		} else {17201721			return null;17221723		}17241725	}17261727}17281729/**1730 * GPU Instancing Extension1731 *1732 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing1733 *1734 * @private1735 */1736class GLTFMeshGpuInstancing {17371738	constructor( parser ) {17391740		this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;1741		this.parser = parser;17421743	}17441745	createNodeMesh( nodeIndex ) {17461747		const json = this.parser.json;1748		const nodeDef = json.nodes[ nodeIndex ];17491750		if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||1751			nodeDef.mesh === undefined ) {17521753			return null;17541755		}17561757		const meshDef = json.meshes[ nodeDef.mesh ];17581759		// No Points or Lines + Instancing support yet17601761		for ( const primitive of meshDef.primitives ) {17621763			if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&1764				 primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&1765				 primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&1766				 primitive.mode !== undefined ) {17671768				return null;17691770			}17711772		}17731774		const extensionDef = nodeDef.extensions[ this.name ];1775		const attributesDef = extensionDef.attributes;17761777		// @TODO: Can we support InstancedMesh + SkinnedMesh?17781779		const pending = [];1780		const attributes = {};17811782		for ( const key in attributesDef ) {17831784			pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {17851786				attributes[ key ] = accessor;1787				return attributes[ key ];17881789			} ) );17901791		}17921793		if ( pending.length < 1 ) {17941795			return null;17961797		}17981799		pending.push( this.parser.createNodeMesh( nodeIndex ) );18001801		return Promise.all( pending ).then( results => {18021803			const nodeObject = results.pop();1804			const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];1805			const count = results[ 0 ].count; // All attribute counts should be same1806			const instancedMeshes = [];18071808			for ( const mesh of meshes ) {18091810				// Temporal variables1811				const m = new Matrix4();1812				const p = new Vector3();1813				const q = new Quaternion();1814				const s = new Vector3( 1, 1, 1 );18151816				const instancedMesh = new InstancedMesh( mesh.geometry, mesh.material, count );18171818				for ( let i = 0; i < count; i ++ ) {18191820					if ( attributes.TRANSLATION ) {18211822						p.fromBufferAttribute( attributes.TRANSLATION, i );18231824					}18251826					if ( attributes.ROTATION ) {18271828						q.fromBufferAttribute( attributes.ROTATION, i );18291830					}18311832					if ( attributes.SCALE ) {18331834						s.fromBufferAttribute( attributes.SCALE, i );18351836					}18371838					instancedMesh.setMatrixAt( i, m.compose( p, q, s ) );18391840				}18411842				// Add instance attributes to the geometry, excluding TRS.18431844				let instanceGeometry = null;18451846				for ( const attributeName in attributes ) {18471848					if ( attributeName === '_COLOR_0' ) {18491850						const attr = attributes[ attributeName ];1851						instancedMesh.instanceColor = new InstancedBufferAttribute( attr.array, attr.itemSize, attr.normalized );18521853					} else if ( attributeName !== 'TRANSLATION' &&1854						 attributeName !== 'ROTATION' &&1855						 attributeName !== 'SCALE' ) {18561857						if ( instanceGeometry === null ) {18581859							// do a shallow clone of the goemetry so per-instance data are not shared18601861							const source = instancedMesh.geometry;1862							instanceGeometry = new BufferGeometry();1863							instanceGeometry.name = source.name;18641865							for ( const name in source.attributes ) instanceGeometry.setAttribute( name, source.attributes[ name ] );1866							for ( const name in source.morphAttributes ) instanceGeometry.morphAttributes[ name ] = source.morphAttributes[ name ];1867							if ( source.index !== null ) instanceGeometry.setIndex( source.index );18681869							instanceGeometry.morphTargetsRelative = source.morphTargetsRelative;18701871							for ( const group of source.groups ) instanceGeometry.addGroup( group.start, group.count, group.materialIndex );18721873							if ( source.boundingBox !== null ) instanceGeometry.boundingBox = source.boundingBox.clone();1874							if ( source.boundingSphere !== null ) instanceGeometry.boundingSphere = source.boundingSphere.clone();18751876							instanceGeometry.drawRange.start = source.drawRange.start;1877							instanceGeometry.drawRange.count = source.drawRange.count;18781879							instanceGeometry.userData = Object.assign( {}, source.userData );18801881							instancedMesh.geometry = instanceGeometry;18821883						}18841885						const attr = attributes[ attributeName ];1886						instanceGeometry.setAttribute( attributeName, new InstancedBufferAttribute( attr.array, attr.itemSize, attr.normalized ) );18871888					}18891890				}18911892				// Just in case1893				Object3D.prototype.copy.call( instancedMesh, mesh );18941895				this.parser.assignFinalMaterial( instancedMesh );18961897				instancedMeshes.push( instancedMesh );18981899			}19001901			if ( nodeObject.isGroup ) {19021903				nodeObject.clear();19041905				nodeObject.add( ... instancedMeshes );19061907				return nodeObject;19081909			}19101911			return instancedMeshes[ 0 ];19121913		} );19141915	}19161917}19181919/* BINARY EXTENSION */1920const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';1921const BINARY_EXTENSION_HEADER_LENGTH = 12;1922const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };19231924class GLTFBinaryExtension {19251926	constructor( data ) {19271928		this.name = EXTENSIONS.KHR_BINARY_GLTF;1929		this.content = null;1930		this.body = null;19311932		const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );1933		const textDecoder = new TextDecoder();19341935		this.header = {1936			magic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ),1937			version: headerView.getUint32( 4, true ),1938			length: headerView.getUint32( 8, true )1939		};19401941		if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {19421943			throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );19441945		} else if ( this.header.version < 2.0 ) {19461947			throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );19481949		}19501951		const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;1952		const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );1953		let chunkIndex = 0;19541955		while ( chunkIndex < chunkContentsLength ) {19561957			const chunkLength = chunkView.getUint32( chunkIndex, true );1958			chunkIndex += 4;19591960			const chunkType = chunkView.getUint32( chunkIndex, true );1961			chunkIndex += 4;19621963			if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {19641965				const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );1966				this.content = textDecoder.decode( contentArray );19671968			} else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {19691970				const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;1971				this.body = data.slice( byteOffset, byteOffset + chunkLength );19721973			}19741975			// Clients must ignore chunks with unknown types.19761977			chunkIndex += chunkLength;19781979		}19801981		if ( this.content === null ) {19821983			throw new Error( 'THREE.GLTFLoader: JSON content not found.' );19841985		}19861987	}19881989}19901991/**1992 * DRACO Mesh Compression Extension1993 *1994 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression1995 *1996 * @private1997 */1998class GLTFDracoMeshCompressionExtension {19992000	constructor( json, dracoLoader ) {20012002		if ( ! dracoLoader ) {20032004			throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );20052006		}20072008		this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;2009		this.json = json;2010		this.dracoLoader = dracoLoader;2011		this.dracoLoader.preload();20122013	}20142015	decodePrimitive( primitive, parser ) {20162017		const json = this.json;2018		const dracoLoader = this.dracoLoader;2019		const bufferViewIndex = primitive.extensions[ this.name ].bufferView;2020		const gltfAttributeMap = primitive.extensions[ this.name ].attributes;2021		const threeAttributeMap = {};2022		const attributeNormalizedMap = {};2023		const attributeTypeMap = {};20242025		for ( const attributeName in gltfAttributeMap ) {20262027			const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();20282029			threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];20302031		}20322033		for ( const attributeName in primitive.attributes ) {20342035			const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();20362037			if ( gltfAttributeMap[ attributeName ] !== undefined ) {20382039				const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];2040				const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];20412042				attributeTypeMap[ threeAttributeName ] = componentType.name;2043				attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;20442045			}20462047		}20482049		return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {20502051			return new Promise( function ( resolve, reject ) {20522053				dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {20542055					for ( const attributeName in geometry.attributes ) {20562057						const attribute = geometry.attributes[ attributeName ];2058						const normalized = attributeNormalizedMap[ attributeName ];20592060						if ( normalized !== undefined ) attribute.normalized = normalized;20612062					}20632064					resolve( geometry );20652066				}, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject );20672068			} );20692070		} );20712072	}20732074}20752076/**2077 * Texture Transform Extension2078 *2079 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform2080 *2081 * @private2082 */2083class GLTFTextureTransformExtension {20842085	constructor() {20862087		this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;20882089	}20902091	extendTexture( texture, transform ) {20922093		if ( ( transform.texCoord === undefined || transform.texCoord === texture.channel )2094			&& transform.offset === undefined2095			&& transform.rotation === undefined2096			&& transform.scale === undefined ) {20972098			// See https://github.com/mrdoob/three.js/issues/21819.2099			return texture;21002101		}21022103		texture = texture.clone();21042105		if ( transform.texCoord !== undefined ) {21062107			texture.channel = transform.texCoord;21082109		}21102111		if ( transform.offset !== undefined ) {21122113			texture.offset.fromArray( transform.offset );21142115		}21162117		if ( transform.rotation !== undefined ) {21182119			texture.rotation = transform.rotation;21202121		}21222123		if ( transform.scale !== undefined ) {21242125			texture.repeat.fromArray( transform.scale );21262127		}21282129		if ( transform.rotation !== undefined ) {21302131			// glTF's KHR_texture_transform order differs from three.js:2132			// glTF defines the UV transform as T * R * S2133			// three.js defines the UV transform as T * S * R2134			//2135			// To fix this, we need to override the matrix with the value computed per glTF spec2136			// We still set the other fields so that you can inspect/export the resulting object.21372138			const c = Math.cos( texture.rotation );2139			const s = Math.sin( texture.rotation );21402141			texture.matrix.set(2142				texture.repeat.x * c, texture.repeat.y * s, texture.offset.x,2143				- texture.repeat.x * s, texture.repeat.y * c, texture.offset.y,2144				0, 0, 12145			);2146			texture.matrixAutoUpdate = false;21472148		}21492150		texture.needsUpdate = true;21512152		return texture;21532154	}21552156}21572158/**2159 * Mesh Quantization Extension2160 *2161 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization2162 *2163 * @private2164 */2165class GLTFMeshQuantizationExtension {21662167	constructor() {21682169		this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;21702171	}21722173}21742175/*********************************/2176/********** INTERPOLATION ********/2177/*********************************/21782179// Spline Interpolation2180// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation2181class GLTFCubicSplineInterpolant extends Interpolant {21822183	constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {21842185		super( parameterPositions, sampleValues, sampleSize, resultBuffer );21862187	}21882189	copySampleValue_( index ) {21902191		// Copies a sample value to the result buffer. See description of glTF2192		// CUBICSPLINE values layout in interpolate_() function below.21932194		const result = this.resultBuffer,2195			values = this.sampleValues,2196			valueSize = this.valueSize,2197			offset = index * valueSize * 3 + valueSize;21982199		for ( let i = 0; i !== valueSize; i ++ ) {22002201			result[ i ] = values[ offset + i ];22022203		}22042205		return result;22062207	}22082209	interpolate_( i1, t0, t, t1 ) {22102211		const result = this.resultBuffer;2212		const values = this.sampleValues;2213		const stride = this.valueSize;22142215		const stride2 = stride * 2;2216		const stride3 = stride * 3;22172218		const td = t1 - t0;22192220		const p = ( t - t0 ) / td;2221		const pp = p * p;2222		const ppp = pp * p;22232224		const offset1 = i1 * stride3;2225		const offset0 = offset1 - stride3;22262227		const s2 = - 2 * ppp + 3 * pp;2228		const s3 = ppp - pp;2229		const s0 = 1 - s2;2230		const s1 = s3 - pp + p;22312232		// Layout of keyframe output values for CUBICSPLINE animations:2233		//   [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]2234		for ( let i = 0; i !== stride; i ++ ) {22352236			const p0 = values[ offset0 + i + stride ]; // splineVertex_k2237			const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)2238			const p1 = values[ offset1 + i + stride ]; // splineVertex_k+12239			const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)22402241			result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;22422243		}22442245		return result;22462247	}22482249}22502251const _quaternion = new Quaternion();22522253class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {22542255	interpolate_( i1, t0, t, t1 ) {22562257		const result = super.interpolate_( i1, t0, t, t1 );22582259		_quaternion.fromArray( result ).normalize().toArray( result );22602261		return result;22622263	}22642265}226622672268/*********************************/2269/********** INTERNALS ************/2270/*********************************/22712272/* CONSTANTS */22732274const WEBGL_CONSTANTS = {2275	FLOAT: 5126,2276	//FLOAT_MAT2: 35674,2277	FLOAT_MAT3: 35675,2278	FLOAT_MAT4: 35676,2279	FLOAT_VEC2: 35664,2280	FLOAT_VEC3: 35665,2281	FLOAT_VEC4: 35666,2282	LINEAR: 9729,2283	REPEAT: 10497,2284	SAMPLER_2D: 35678,2285	POINTS: 0,2286	LINES: 1,2287	LINE_LOOP: 2,2288	LINE_STRIP: 3,2289	TRIANGLES: 4,2290	TRIANGLE_STRIP: 5,2291	TRIANGLE_FAN: 6,2292	UNSIGNED_BYTE: 5121,2293	UNSIGNED_SHORT: 51232294};22952296const WEBGL_COMPONENT_TYPES = {2297	5120: Int8Array,2298	5121: Uint8Array,2299	5122: Int16Array,2300	5123: Uint16Array,2301	5125: Uint32Array,2302	5126: Float32Array2303};23042305const WEBGL_FILTERS = {2306	9728: NearestFilter,2307	9729: LinearFilter,2308	9984: NearestMipmapNearestFilter,2309	9985: LinearMipmapNearestFilter,2310	9986: NearestMipmapLinearFilter,2311	9987: LinearMipmapLinearFilter2312};23132314const WEBGL_WRAPPINGS = {2315	33071: ClampToEdgeWrapping,2316	33648: MirroredRepeatWrapping,2317	10497: RepeatWrapping2318};23192320const WEBGL_TYPE_SIZES = {2321	'SCALAR': 1,2322	'VEC2': 2,2323	'VEC3': 3,2324	'VEC4': 4,2325	'MAT2': 4,2326	'MAT3': 9,2327	'MAT4': 162328};23292330const ATTRIBUTES = {2331	POSITION: 'position',2332	NORMAL: 'normal',2333	TANGENT: 'tangent',2334	TEXCOORD_0: 'uv',2335	TEXCOORD_1: 'uv1',2336	TEXCOORD_2: 'uv2',2337	TEXCOORD_3: 'uv3',2338	COLOR_0: 'color',2339	WEIGHTS_0: 'skinWeight',2340	JOINTS_0: 'skinIndex',2341};23422343const PATH_PROPERTIES = {2344	scale: 'scale',2345	translation: 'position',2346	rotation: 'quaternion',2347	weights: 'morphTargetInfluences'2348};23492350const INTERPOLATION = {2351	CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each2352		                        // keyframe track will be initialized with a default interpolation type, then modified.2353	LINEAR: InterpolateLinear,2354	STEP: InterpolateDiscrete2355};23562357const ALPHA_MODES = {2358	OPAQUE: 'OPAQUE',2359	MASK: 'MASK',2360	BLEND: 'BLEND'2361};23622363/**2364 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material2365 *2366 * @private2367 * @param {Object<string, Material>} cache2368 * @return {Material}2369 */2370function createDefaultMaterial( cache ) {23712372	if ( cache[ 'DefaultMaterial' ] === undefined ) {23732374		cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( {2375			color: 0xFFFFFF,2376			emissive: 0x000000,2377			metalness: 1,2378			roughness: 1,2379			transparent: false,2380			depthTest: true,2381			side: FrontSide2382		} );23832384	}23852386	return cache[ 'DefaultMaterial' ];23872388}23892390function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {23912392	// Add unknown glTF extensions to an object's userData.23932394	for ( const name in objectDef.extensions ) {23952396		if ( knownExtensions[ name ] === undefined ) {23972398			object.userData.gltfExtensions = object.userData.gltfExtensions || {};2399			object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];24002401		}24022403	}24042405}24062407/**2408 *2409 * @private2410 * @param {Object3D|Material|BufferGeometry|Object|AnimationClip} object2411 * @param {GLTF.definition} gltfDef2412 */2413function assignExtrasToUserData( object, gltfDef ) {24142415	if ( gltfDef.extras !== undefined ) {24162417		if ( typeof gltfDef.extras === 'object' ) {24182419			Object.assign( object.userData, gltfDef.extras );24202421		} else {24222423			console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );24242425		}24262427	}24282429}24302431/**2432 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets2433 *2434 * @private2435 * @param {BufferGeometry} geometry2436 * @param {Array<GLTF.Target>} targets2437 * @param {GLTFParser} parser2438 * @return {Promise<BufferGeometry>}2439 */2440function addMorphTargets( geometry, targets, parser ) {24412442	let hasMorphPosition = false;2443	let hasMorphNormal = false;2444	let hasMorphColor = false;24452446	for ( let i = 0, il = targets.length; i < il; i ++ ) {24472448		const target = targets[ i ];24492450		if ( target.POSITION !== undefined ) hasMorphPosition = true;2451		if ( target.NORMAL !== undefined ) hasMorphNormal = true;2452		if ( target.COLOR_0 !== undefined ) hasMorphColor = true;24532454		if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;24552456	}24572458	if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );24592460	const pendingPositionAccessors = [];2461	const pendingNormalAccessors = [];2462	const pendingColorAccessors = [];24632464	for ( let i = 0, il = targets.length; i < il; i ++ ) {24652466		const target = targets[ i ];24672468		if ( hasMorphPosition ) {24692470			const pendingAccessor = target.POSITION !== undefined2471				? parser.getDependency( 'accessor', target.POSITION )2472				: geometry.attributes.position;24732474			pendingPositionAccessors.push( pendingAccessor );24752476		}24772478		if ( hasMorphNormal ) {24792480			const pendingAccessor = target.NORMAL !== undefined2481				? parser.getDependency( 'accessor', target.NORMAL )2482				: geometry.attributes.normal;24832484			pendingNormalAccessors.push( pendingAccessor );24852486		}24872488		if ( hasMorphColor ) {24892490			const pendingAccessor = target.COLOR_0 !== undefined2491				? parser.getDependency( 'accessor', target.COLOR_0 )2492				: geometry.attributes.color;24932494			pendingColorAccessors.push( pendingAccessor );24952496		}24972498	}24992500	return Promise.all( [2501		Promise.all( pendingPositionAccessors ),2502		Promise.all( pendingNormalAccessors ),2503		Promise.all( pendingColorAccessors )2504	] ).then( function ( accessors ) {25052506		const morphPositions = accessors[ 0 ];2507		const morphNormals = accessors[ 1 ];2508		const morphColors = accessors[ 2 ];25092510		if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;2511		if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;2512		if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;2513		geometry.morphTargetsRelative = true;25142515		return geometry;25162517	} );25182519}25202521/**2522 *2523 * @private2524 * @param {Mesh} mesh2525 * @param {GLTF.Mesh} meshDef2526 */2527function updateMorphTargets( mesh, meshDef ) {25282529	mesh.updateMorphTargets();25302531	if ( meshDef.weights !== undefined ) {25322533		for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {25342535			mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];25362537		}25382539	}25402541	// .extras has user-defined data, so check that .extras.targetNames is an array.2542	if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {25432544		const targetNames = meshDef.extras.targetNames;25452546		if ( mesh.morphTargetInfluences.length === targetNames.length ) {25472548			mesh.morphTargetDictionary = {};25492550			for ( let i = 0, il = targetNames.length; i < il; i ++ ) {25512552				mesh.morphTargetDictionary[ targetNames[ i ] ] = i;25532554			}25552556		} else {25572558			console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );25592560		}25612562	}25632564}25652566function createPrimitiveKey( primitiveDef ) {25672568	let geometryKey;25692570	const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];25712572	if ( dracoExtension ) {25732574		geometryKey = 'draco:' + dracoExtension.bufferView2575				+ ':' + dracoExtension.indices2576				+ ':' + createAttributesKey( dracoExtension.attributes );25772578	} else {25792580		geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;25812582	}25832584	if ( primitiveDef.targets !== undefined ) {25852586		for ( let i = 0, il = primitiveDef.targets.length; i < il; i ++ ) {25872588			geometryKey += ':' + createAttributesKey( primitiveDef.targets[ i ] );25892590		}25912592	}25932594	return geometryKey;25952596}25972598function createAttributesKey( attributes ) {25992600	let attributesKey = '';26012602	const keys = Object.keys( attributes ).sort();26032604	for ( let i = 0, il = keys.length; i < il; i ++ ) {26052606		attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';26072608	}26092610	return attributesKey;26112612}26132614function getNormalizedComponentScale( constructor ) {26152616	// Reference:2617	// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data26182619	switch ( constructor ) {26202621		case Int8Array:2622			return 1 / 127;26232624		case Uint8Array:2625			return 1 / 255;26262627		case Int16Array:2628			return 1 / 32767;26292630		case Uint16Array:2631			return 1 / 65535;26322633		default:2634			throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );26352636	}26372638}26392640function getImageURIMimeType( uri ) {26412642	if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg';2643	if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp';2644	if ( uri.search( /\.ktx2($|\?)/i ) > 0 || uri.search( /^data\:image\/ktx2/ ) === 0 ) return 'image/ktx2';26452646	return 'image/png';26472648}26492650const _identityMatrix = new Matrix4();26512652/* GLTF PARSER */26532654class GLTFParser {26552656	constructor( json = {}, options = {} ) {26572658		this.json = json;2659		this.extensions = {};2660		this.plugins = {};2661		this.options = options;26622663		// loader object cache2664		this.cache = new GLTFRegistry();26652666		// associations between Three.js objects and glTF elements2667		this.associations = new Map();26682669		// BufferGeometry caching2670		this.primitiveCache = {};26712672		// Node cache2673		this.nodeCache = {};26742675		// Object3D instance caches2676		this.meshCache = { refs: {}, uses: {} };2677		this.cameraCache = { refs: {}, uses: {} };2678		this.lightCache = { refs: {}, uses: {} };26792680		this.sourceCache = {};2681		this.textureCache = {};26822683		// Track node names, to ensure no duplicates2684		this.nodeNamesUsed = {};26852686		// Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the2687		// expensive work of uploading a texture to the GPU off the main thread.26882689		let isSafari = false;2690		let safariVersion = - 1;2691		let isFirefox = false;2692		let firefoxVersion = - 1;26932694		if ( typeof navigator !== 'undefined' && typeof navigator.userAgent !== 'undefined' ) {26952696			const userAgent = navigator.userAgent;26972698			isSafari = /^((?!chrome|android).)*safari/i.test( userAgent ) === true;2699			const safariMatch = userAgent.match( /Version\/(\d+)/ );2700			safariVersion = isSafari && safariMatch ? parseInt( safariMatch[ 1 ], 10 ) : - 1;27012702			isFirefox = userAgent.indexOf( 'Firefox' ) > - 1;2703			firefoxVersion = isFirefox ? userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1;27042705		}27062707		if ( typeof createImageBitmap === 'undefined' || ( isSafari && safariVersion < 17 ) || ( isFirefox && firefoxVersion < 98 ) ) {27082709			this.textureLoader = new TextureLoader( this.options.manager );2710			this.textureLoader.setPriority( this.options.priority );2711			this.textureLoader.setCache( this.options.cache );27122713		} else {27142715			this.textureLoader = new ImageBitmapLoader( this.options.manager );2716			this.textureLoader.setPriority( this.options.priority );2717			this.textureLoader.setCache( this.options.cache );27182719		}27202721		this.textureLoader.setCrossOrigin( this.options.crossOrigin );2722		this.textureLoader.setWithCredentials( this.options.withCredentials );2723		this.textureLoader.setRequestHeader( this.options.requestHeader );27242725		this.fileLoader = new FileLoader( this.options.manager );2726		this.fileLoader.setPriority( this.options.priority );2727		this.fileLoader.setCache( this.options.cache );2728		this.fileLoader.setResponseType( 'arraybuffer' );27292730		if ( this.options.withCredentials || this.options.crossOrigin === 'use-credentials' ) {27312732			this.fileLoader.setWithCredentials( true );27332734		}27352736	}27372738	setExtensions( extensions ) {27392740		this.extensions = extensions;27412742	}27432744	setPlugins( plugins ) {27452746		this.plugins = plugins;27472748	}27492750	parse( onLoad, onError ) {27512752		const parser = this;2753		const json = this.json;2754		const extensions = this.extensions;27552756		// Clear the loader cache2757		this.cache.removeAll();2758		this.nodeCache = {};27592760		// Mark the special nodes/meshes in json for efficient parse2761		this._invokeAll( function ( ext ) {27622763			return ext._markDefs && ext._markDefs();27642765		} );27662767		Promise.all( this._invokeAll( function ( ext ) {27682769			return ext.beforeRoot && ext.beforeRoot();27702771		} ) ).then( function () {27722773			return Promise.all( [27742775				parser.getDependencies( 'scene' ),2776				parser.getDependencies( 'animation' ),2777				parser.getDependencies( 'camera' ),27782779			] );27802781		} ).then( function ( dependencies ) {27822783			const result = {2784				scene: dependencies[ 0 ][ json.scene || 0 ],2785				scenes: dependencies[ 0 ],2786				animations: dependencies[ 1 ],2787				cameras: dependencies[ 2 ],2788				asset: json.asset,2789				parser: parser,2790				userData: {}2791			};27922793			addUnknownExtensionsToUserData( extensions, result, json );27942795			assignExtrasToUserData( result, json );27962797			return Promise.all( parser._invokeAll( function ( ext ) {27982799				return ext.afterRoot && ext.afterRoot( result );28002801			} ) ).then( function () {28022803				for ( const scene of result.scenes ) {28042805					scene.updateMatrixWorld();28062807				}28082809				onLoad( result );28102811			} );28122813		} ).catch( onError );28142815	}28162817	/**2818	 * Marks the special nodes/meshes in json for efficient parse.2819	 *2820	 * @private2821	 */2822	_markDefs() {28232824		const nodeDefs = this.json.nodes || [];2825		const skinDefs = this.json.skins || [];2826		const meshDefs = this.json.meshes || [];28272828		// Nothing in the node definition indicates whether it is a Bone or an2829		// Object3D. Use the skins' joint references to mark bones.2830		for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {28312832			const joints = skinDefs[ skinIndex ].joints;28332834			for ( let i = 0, il = joints.length; i < il; i ++ ) {28352836				nodeDefs[ joints[ i ] ].isBone = true;28372838			}28392840		}28412842		// Iterate over all nodes, marking references to shared resources,2843		// as well as skeleton joints.2844		for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {28452846			const nodeDef = nodeDefs[ nodeIndex ];28472848			if ( nodeDef.mesh !== undefined ) {28492850				this._addNodeRef( this.meshCache, nodeDef.mesh );28512852				// Nothing in the mesh definition indicates whether it is2853				// a SkinnedMesh or Mesh. Use the node's mesh reference2854				// to mark SkinnedMesh if node has skin.2855				if ( nodeDef.skin !== undefined ) {28562857					meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;28582859				}28602861			}28622863			if ( nodeDef.camera !== undefined ) {28642865				this._addNodeRef( this.cameraCache, nodeDef.camera );28662867			}28682869		}28702871	}28722873	/**2874	 * Counts references to shared node / Object3D resources. These resources2875	 * can be reused, or "instantiated", at multiple nodes in the scene2876	 * hierarchy. Mesh, Camera, and Light instances are instantiated and must2877	 * be marked. Non-scenegraph resources (like Materials, Geometries, and2878	 * Textures) can be reused directly and are not marked here.2879	 *2880	 * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.2881	 *2882	 * @private2883	 * @param {Object} cache2884	 * @param {Object3D} index2885	 */2886	_addNodeRef( cache, index ) {28872888		if ( index === undefined ) return;28892890		if ( cache.refs[ index ] === undefined ) {28912892			cache.refs[ index ] = cache.uses[ index ] = 0;28932894		}28952896		cache.refs[ index ] ++;28972898	}28992900	/**2901	 * Returns a reference to a shared resource, cloning it if necessary.2902	 *2903	 * @private2904	 * @param {Object} cache2905	 * @param {number} index2906	 * @param {Object} object2907	 * @return {Object}2908	 */2909	_getNodeRef( cache, index, object ) {29102911		if ( cache.refs[ index ] <= 1 ) return object;29122913		const ref = object.clone();29142915		// Propagates mappings to the cloned object, prevents mappings on the2916		// original object from being lost.2917		const updateMappings = ( original, clone ) => {29182919			const mappings = this.associations.get( original );2920			if ( mappings != null ) {29212922				this.associations.set( clone, mappings );29232924			}29252926			for ( const [ i, child ] of original.children.entries() ) {29272928				updateMappings( child, clone.children[ i ] );29292930			}29312932		};29332934		updateMappings( object, ref );29352936		ref.name += '_instance_' + ( cache.uses[ index ] ++ );29372938		return ref;29392940	}29412942	_invokeOne( func ) {29432944		const extensions = Object.values( this.plugins );2945		extensions.push( this );29462947		for ( let i = 0; i < extensions.length; i ++ ) {29482949			const result = func( extensions[ i ] );29502951			if ( result ) return result;29522953		}29542955		return null;29562957	}29582959	_invokeAll( func ) {29602961		const extensions = Object.values( this.plugins );2962		extensions.unshift( this );29632964		const pending = [];29652966		for ( let i = 0; i < extensions.length; i ++ ) {29672968			const result = func( extensions[ i ] );29692970			if ( result ) pending.push( result );29712972		}29732974		return pending;29752976	}29772978	/**2979	 * Requests the specified dependency asynchronously, with caching.2980	 *2981	 * @private2982	 * @param {string} type2983	 * @param {number} index2984	 * @return {Promise<Object3D|Material|Texture|AnimationClip|ArrayBuffer|Object>}2985	 */2986	getDependency( type, index ) {29872988		const cacheKey = type + ':' + index;2989		let dependency = this.cache.get( cacheKey );29902991		if ( ! dependency ) {29922993			switch ( type ) {29942995				case 'scene':2996					dependency = this.loadScene( index );2997					break;29982999				case 'node':3000					dependency = this._invokeOne( function ( ext ) {30013002						return ext.loadNode && ext.loadNode( index );30033004					} );3005					break;30063007				case 'mesh':3008					dependency = this._invokeOne( function ( ext ) {30093010						return ext.loadMesh && ext.loadMesh( index );30113012					} );3013					break;30143015				case 'accessor':3016					dependency = this.loadAccessor( index );3017					break;30183019				case 'bufferView':3020					dependency = this._invokeOne( function ( ext ) {30213022						return ext.loadBufferView && ext.loadBufferView( index );30233024					} );3025					break;30263027				case 'buffer':3028					dependency = this.loadBuffer( index );3029					break;30303031				case 'material':3032					dependency = this._invokeOne( function ( ext ) {30333034						return ext.loadMaterial && ext.loadMaterial( index );30353036					} );3037					break;30383039				case 'texture':3040					dependency = this._invokeOne( function ( ext ) {30413042						return ext.loadTexture && ext.loadTexture( index );30433044					} );3045					break;30463047				case 'skin':3048					dependency = this.loadSkin( index );3049					break;30503051				case 'animation':3052					dependency = this._invokeOne( function ( ext ) {30533054						return ext.loadAnimation && ext.loadAnimation( index );30553056					} );3057					break;30583059				case 'camera':3060					dependency = this.loadCamera( index );3061					break;30623063				default:3064					dependency = this._invokeOne( function ( ext ) {30653066						return ext != this && ext.getDependency && ext.getDependency( type, index );30673068					} );30693070					if ( ! dependency ) {30713072						throw new Error( 'Unknown type: ' + type );30733074					}30753076					break;30773078			}30793080			this.cache.add( cacheKey, dependency );30813082		}30833084		return dependency;30853086	}30873088	/**3089	 * Requests all dependencies of the specified type asynchronously, with caching.3090	 *3091	 * @private3092	 * @param {string} type3093	 * @return {Promise<Array<Object>>}3094	 */3095	getDependencies( type ) {30963097		let dependencies = this.cache.get( type );30983099		if ( ! dependencies ) {31003101			const parser = this;3102			const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];31033104			dependencies = Promise.all( defs.map( function ( def, index ) {31053106				return parser.getDependency( type, index );31073108			} ) );31093110			this.cache.add( type, dependencies );31113112		}31133114		return dependencies;31153116	}31173118	/**3119	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views3120	 *3121	 * @private3122	 * @param {number} bufferIndex3123	 * @return {Promise<ArrayBuffer>}3124	 */3125	loadBuffer( bufferIndex ) {31263127		const bufferDef = this.json.buffers[ bufferIndex ];3128		const loader = this.fileLoader;31293130		if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {31313132			throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );31333134		}31353136		// If present, GLB container is required to be the first buffer.3137		if ( bufferDef.uri === undefined && bufferIndex === 0 ) {31383139			return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );31403141		}31423143		const options = this.options;31443145		return new Promise( function ( resolve, reject ) {31463147			loader.load( LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {31483149				reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );31503151			} );31523153		} );31543155	}31563157	/**3158	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views3159	 *3160	 * @private3161	 * @param {number} bufferViewIndex3162	 * @return {Promise<ArrayBuffer>}3163	 */3164	loadBufferView( bufferViewIndex ) {31653166		const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];31673168		return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {31693170			const byteLength = bufferViewDef.byteLength || 0;3171			const byteOffset = bufferViewDef.byteOffset || 0;3172			return buffer.slice( byteOffset, byteOffset + byteLength );31733174		} );31753176	}31773178	/**3179	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors3180	 *3181	 * @private3182	 * @param {number} accessorIndex3183	 * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}3184	 */3185	loadAccessor( accessorIndex ) {31863187		const parser = this;3188		const json = this.json;31893190		const accessorDef = this.json.accessors[ accessorIndex ];31913192		if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {31933194			const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];3195			const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];3196			const normalized = accessorDef.normalized === true;31973198			const array = new TypedArray( accessorDef.count * itemSize );3199			return Promise.resolve( new BufferAttribute( array, itemSize, normalized ) );32003201		}32023203		const pendingBufferViews = [];32043205		if ( accessorDef.bufferView !== undefined ) {32063207			pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );32083209		} else {32103211			pendingBufferViews.push( null );32123213		}32143215		if ( accessorDef.sparse !== undefined ) {32163217			pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );3218			pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );32193220		}32213222		return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {32233224			const bufferView = bufferViews[ 0 ];32253226			const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];3227			const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];32283229			// For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.3230			const elementBytes = TypedArray.BYTES_PER_ELEMENT;3231			const itemBytes = elementBytes * itemSize;3232			const byteOffset = accessorDef.byteOffset || 0;3233			const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;3234			const normalized = accessorDef.normalized === true;3235			let array, bufferAttribute;32363237			// The buffer is not interleaved if the stride is the item size in bytes.3238			if ( byteStride && byteStride !== itemBytes ) {32393240				// Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer3241				// This makes sure that IBA.count reflects accessor.count properly3242				const ibSlice = Math.floor( byteOffset / byteStride );3243				const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;3244				let ib = parser.cache.get( ibCacheKey );32453246				if ( ! ib ) {32473248					array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );32493250					// Integer parameters to IB/IBA are in array elements, not bytes.3251					ib = new InterleavedBuffer( array, byteStride / elementBytes );32523253					parser.cache.add( ibCacheKey, ib );32543255				}32563257				bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );32583259			} else {32603261				if ( bufferView === null ) {32623263					array = new TypedArray( accessorDef.count * itemSize );32643265				} else {32663267					array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );32683269				}32703271				bufferAttribute = new BufferAttribute( array, itemSize, normalized );32723273			}32743275			// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors3276			if ( accessorDef.sparse !== undefined ) {32773278				const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;3279				const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];32803281				const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;3282				const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;32833284				const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );3285				const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );32863287				if ( bufferView !== null ) {32883289					// Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.3290					bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );32913292				}32933294				// Ignore normalized since we copy from sparse3295				bufferAttribute.normalized = false;32963297				for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {32983299					const index = sparseIndices[ i ];33003301					bufferAttribute.setX( index, sparseValues[ i * itemSize ] );3302					if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );3303					if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );3304					if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );3305					if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );33063307				}33083309				bufferAttribute.normalized = normalized;33103311			}33123313			return bufferAttribute;33143315		} );33163317	}33183319	/**3320	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures3321	 *3322	 * @private3323	 * @param {number} textureIndex3324	 * @return {Promise<?Texture>}3325	 */3326	loadTexture( textureIndex ) {33273328		const json = this.json;3329		const options = this.options;3330		const textureDef = json.textures[ textureIndex ];3331		const sourceIndex = textureDef.source;3332		const sourceDef = json.images[ sourceIndex ];33333334		let loader = this.textureLoader;33353336		if ( sourceDef.uri ) {33373338			const handler = options.manager.getHandler( sourceDef.uri );3339			if ( handler !== null ) loader = handler;33403341		}33423343		return this.loadTextureImage( textureIndex, sourceIndex, loader );33443345	}33463347	loadTextureImage( textureIndex, sourceIndex, loader ) {33483349		const parser = this;3350		const json = this.json;33513352		const textureDef = json.textures[ textureIndex ];3353		const sourceDef = json.images[ sourceIndex ];33543355		const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;33563357		if ( this.textureCache[ cacheKey ] ) {33583359			// See https://github.com/mrdoob/three.js/issues/21559.3360			return this.textureCache[ cacheKey ];33613362		}33633364		const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {33653366			texture.flipY = false;33673368			texture.name = textureDef.name || sourceDef.name || '';33693370			if ( texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith( 'data:image/' ) === false ) {33713372				texture.name = sourceDef.uri;33733374			}33753376			const samplers = json.samplers || {};3377			const sampler = samplers[ textureDef.sampler ] || {};33783379			texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;3380			texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;3381			texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;3382			texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;3383			texture.generateMipmaps = ! texture.isCompressedTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;33843385			parser.associations.set( texture, { textures: textureIndex } );33863387			return texture;33883389		} ).catch( function () {33903391			return null;33923393		} );33943395		this.textureCache[ cacheKey ] = promise;33963397		return promise;33983399	}34003401	loadImageSource( sourceIndex, loader ) {34023403		const parser = this;3404		const json = this.json;3405		const options = this.options;34063407		if ( this.sourceCache[ sourceIndex ] !== undefined ) {34083409			return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );34103411		}34123413		const sourceDef = json.images[ sourceIndex ];34143415		const URL = self.URL || self.webkitURL;34163417		let sourceURI = sourceDef.uri || '';3418		let isObjectURL = false;3419		let pending;34203421		if ( loader.isKTX2Loader === true && sourceDef.bufferView !== undefined ) {34223423			// KTX2Loader parses the binary image data from bufferView directly (see #35193).34243425			pending = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {34263427				return new Promise( function ( resolve, reject ) {34283429					loader.parse( bufferView, resolve, reject );34303431				} );34323433			} );34343435		} else {34363437			if ( sourceDef.bufferView !== undefined ) {34383439				// Load binary image data from bufferView, if provided.34403441				sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {34423443					isObjectURL = true;3444					const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );3445					sourceURI = URL.createObjectURL( blob );3446					return sourceURI;34473448				} );34493450			} else if ( sourceDef.uri === undefined ) {34513452				throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );34533454			}34553456			pending = Promise.resolve( sourceURI ).then( function ( sourceURI ) {34573458				return new Promise( function ( resolve, reject ) {34593460					let onLoad = resolve;34613462					if ( loader.isImageBitmapLoader === true ) {34633464						onLoad = function ( imageBitmap ) {34653466							const texture = new Texture( imageBitmap );3467							texture.needsUpdate = true;34683469							resolve( texture );34703471						};34723473					}34743475					loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );34763477				} );34783479			} );34803481		}34823483		const promise = pending.then( function ( texture ) {34843485			// Clean up resources and configure Texture.34863487			if ( isObjectURL === true ) {34883489				URL.revokeObjectURL( sourceURI );34903491			}34923493			assignExtrasToUserData( texture, sourceDef );34943495			texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri );34963497			return texture;34983499		} ).catch( function ( error ) {35003501			console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );3502			throw error;35033504		} );35053506		this.sourceCache[ sourceIndex ] = promise;3507		return promise;35083509	}35103511	/**3512	 * Asynchronously assigns a texture to the given material parameters.3513	 *3514	 * @private3515	 * @param {Object} materialParams3516	 * @param {string} mapName3517	 * @param {Object} mapDef3518	 * @param {string} [colorSpace]3519	 * @return {Promise<Texture>}3520	 */3521	assignTexture( materialParams, mapName, mapDef, colorSpace ) {35223523		const parser = this;35243525		return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {35263527			if ( ! texture ) return null;35283529			if ( mapDef.texCoord !== undefined && mapDef.texCoord > 0 ) {35303531				texture = texture.clone();3532				texture.channel = mapDef.texCoord;35333534			}35353536			if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {35373538				const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;35393540				if ( transform ) {35413542					const gltfReference = parser.associations.get( texture );3543					texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );3544					parser.associations.set( texture, gltfReference );35453546				}35473548			}35493550			if ( colorSpace !== undefined ) {35513552				texture.colorSpace = colorSpace;35533554			}35553556			materialParams[ mapName ] = texture;35573558			return texture;35593560		} );35613562	}35633564	/**3565	 * Assigns final material to a Mesh, Line, or Points instance. The instance3566	 * already has a material (generated from the glTF material options alone)3567	 * but reuse of the same glTF material may require multiple threejs materials3568	 * to accommodate different primitive types, defines, etc. New materials will3569	 * be created if necessary, and reused from a cache.3570	 *3571	 * @private3572	 * @param {Object3D} mesh Mesh, Line, or Points instance.3573	 */3574	assignFinalMaterial( mesh ) {35753576		const geometry = mesh.geometry;3577		let material = mesh.material;35783579		const useDerivativeTangents = geometry.attributes.tangent === undefined;3580		const useVertexColors = geometry.attributes.color !== undefined;3581		const useFlatShading = geometry.attributes.normal === undefined;35823583		if ( mesh.isPoints ) {35843585			const cacheKey = 'PointsMaterial:' + material.uuid;35863587			let pointsMaterial = this.cache.get( cacheKey );35883589			if ( ! pointsMaterial ) {35903591				pointsMaterial = new PointsMaterial();3592				Material.prototype.copy.call( pointsMaterial, material );3593				pointsMaterial.color.copy( material.color );3594				pointsMaterial.map = material.map;3595				pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px35963597				this.cache.add( cacheKey, pointsMaterial );35983599			}36003601			material = pointsMaterial;36023603		} else if ( mesh.isLine ) {36043605			const cacheKey = 'LineBasicMaterial:' + material.uuid;36063607			let lineMaterial = this.cache.get( cacheKey );36083609			if ( ! lineMaterial ) {36103611				lineMaterial = new LineBasicMaterial();3612				Material.prototype.copy.call( lineMaterial, material );3613				lineMaterial.color.copy( material.color );3614				lineMaterial.map = material.map;36153616				this.cache.add( cacheKey, lineMaterial );36173618			}36193620			material = lineMaterial;36213622		}36233624		// Clone the material if it will be modified3625		if ( useDerivativeTangents || useVertexColors || useFlatShading ) {36263627			let cacheKey = 'ClonedMaterial:' + material.uuid + ':';36283629			if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';3630			if ( useVertexColors ) cacheKey += 'vertex-colors:';3631			if ( useFlatShading ) cacheKey += 'flat-shading:';36323633			let cachedMaterial = this.cache.get( cacheKey );36343635			if ( ! cachedMaterial ) {36363637				cachedMaterial = material.clone();36383639				if ( useVertexColors ) cachedMaterial.vertexColors = true;3640				if ( useFlatShading ) cachedMaterial.flatShading = true;36413642				if ( useDerivativeTangents ) {36433644					// https://github.com/mrdoob/three.js/issues/11438#issuecomment-5070039953645					if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;3646					if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;36473648				}36493650				this.cache.add( cacheKey, cachedMaterial );36513652				this.associations.set( cachedMaterial, this.associations.get( material ) );36533654			}36553656			material = cachedMaterial;36573658		}36593660		mesh.material = material;36613662	}36633664	getMaterialType( /* materialIndex */ ) {36653666		return MeshStandardMaterial;36673668	}36693670	/**3671	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials3672	 *3673	 * @private3674	 * @param {number} materialIndex3675	 * @return {Promise<Material>}3676	 */3677	loadMaterial( materialIndex ) {36783679		const parser = this;3680		const json = this.json;3681		const extensions = this.extensions;3682		const materialDef = json.materials[ materialIndex ];36833684		let materialType;3685		const materialParams = {};3686		const materialExtensions = materialDef.extensions || {};36873688		const pending = [];36893690		if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {36913692			const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];3693			materialType = kmuExtension.getMaterialType();3694			pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );36953696		} else {36973698			// Specification:3699			// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material37003701			const metallicRoughness = materialDef.pbrMetallicRoughness || {};37023703			materialParams.color = new Color( 1.0, 1.0, 1.0 );3704			materialParams.opacity = 1.0;37053706			if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {37073708				const array = metallicRoughness.baseColorFactor;37093710				materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace );3711				materialParams.opacity = array[ 3 ];37123713			}37143715			if ( metallicRoughness.baseColorTexture !== undefined ) {37163717				pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) );37183719			}37203721			materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;3722			materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;37233724			if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {37253726				pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );3727				pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );37283729			}37303731			materialType = this._invokeOne( function ( ext ) {37323733				return ext.getMaterialType && ext.getMaterialType( materialIndex );37343735			} );37363737			pending.push( Promise.all( this._invokeAll( function ( ext ) {37383739				return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );37403741			} ) ) );37423743		}37443745		if ( materialDef.doubleSided === true ) {37463747			materialParams.side = DoubleSide;37483749		}37503751		const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;37523753		if ( alphaMode === ALPHA_MODES.BLEND ) {37543755			materialParams.transparent = true;37563757			// See: https://github.com/mrdoob/three.js/issues/177063758			materialParams.depthWrite = false;37593760		} else {37613762			materialParams.transparent = false;37633764			if ( alphaMode === ALPHA_MODES.MASK ) {37653766				materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;37673768			}37693770		}37713772		if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {37733774			pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );37753776			materialParams.normalScale = new Vector2( 1, 1 );37773778			if ( materialDef.normalTexture.scale !== undefined ) {37793780				const scale = materialDef.normalTexture.scale;37813782				materialParams.normalScale.set( scale, scale );37833784			}37853786		}37873788		if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {37893790			pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );37913792			if ( materialDef.occlusionTexture.strength !== undefined ) {37933794				materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;37953796			}37973798		}37993800		if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {38013802			const emissiveFactor = materialDef.emissiveFactor;3803			materialParams.emissive = new Color().setRGB( emissiveFactor[ 0 ], emissiveFactor[ 1 ], emissiveFactor[ 2 ], LinearSRGBColorSpace );38043805		}38063807		if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {38083809			pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, SRGBColorSpace ) );38103811		}38123813		return Promise.all( pending ).then( function () {38143815			const material = new materialType( materialParams );38163817			if ( materialDef.name ) material.name = materialDef.name;38183819			assignExtrasToUserData( material, materialDef );38203821			parser.associations.set( material, { materials: materialIndex } );38223823			if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );38243825			return material;38263827		} );38283829	}38303831	/**3832	 * When Object3D instances are targeted by animation, they need unique names.3833	 *3834	 * @private3835	 * @param {string} originalName3836	 * @return {string}3837	 */3838	createUniqueName( originalName ) {38393840		const sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' );38413842		if ( sanitizedName in this.nodeNamesUsed ) {38433844			return sanitizedName + '_' + ( ++ this.nodeNamesUsed[ sanitizedName ] );38453846		} else {38473848			this.nodeNamesUsed[ sanitizedName ] = 0;38493850			return sanitizedName;38513852		}38533854	}38553856	/**3857	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry3858	 *3859	 * Creates BufferGeometries from primitives.3860	 *3861	 * @private3862	 * @param {Array<GLTF.Primitive>} primitives3863	 * @return {Promise<Array<BufferGeometry>>}3864	 */3865	loadGeometries( primitives ) {38663867		const parser = this;3868		const extensions = this.extensions;3869		const cache = this.primitiveCache;38703871		function createDracoPrimitive( primitive ) {38723873			return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]3874				.decodePrimitive( primitive, parser )3875				.then( function ( geometry ) {38763877					return addPrimitiveAttributes( geometry, primitive, parser );38783879				} );38803881		}38823883		const pending = [];38843885		for ( let i = 0, il = primitives.length; i < il; i ++ ) {38863887			const primitive = primitives[ i ];3888			const cacheKey = createPrimitiveKey( primitive );38893890			// See if we've already created this geometry3891			const cached = cache[ cacheKey ];38923893			if ( cached ) {38943895				// Use the cached geometry if it exists3896				pending.push( cached.promise );38973898			} else {38993900				let geometryPromise;39013902				if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {39033904					// Use DRACO geometry if available3905					geometryPromise = createDracoPrimitive( primitive );39063907				} else {39083909					// Otherwise create a new geometry3910					geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );39113912				}39133914				// Convert strip/fan primitives to triangles39153916				if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {39173918					geometryPromise = geometryPromise.then( geometry => toTrianglesDrawMode( geometry, TriangleStripDrawMode ) );39193920				} else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {39213922					geometryPromise = geometryPromise.then( geometry => toTrianglesDrawMode( geometry, TriangleFanDrawMode ) );39233924				}39253926				// Cache this geometry3927				cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };39283929				pending.push( geometryPromise );39303931			}39323933		}39343935		return Promise.all( pending );39363937	}39383939	/**3940	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes3941	 *3942	 * @private3943	 * @param {number} meshIndex3944	 * @return {Promise<Group|Mesh|SkinnedMesh|Line|Points>}3945	 */3946	loadMesh( meshIndex ) {39473948		const parser = this;3949		const json = this.json;3950		const extensions = this.extensions;39513952		const meshDef = json.meshes[ meshIndex ];3953		const primitives = meshDef.primitives;39543955		const pending = [];39563957		for ( let i = 0, il = primitives.length; i < il; i ++ ) {39583959			const material = primitives[ i ].material === undefined3960				? createDefaultMaterial( this.cache )3961				: this.getDependency( 'material', primitives[ i ].material );39623963			pending.push( material );39643965		}39663967		pending.push( parser.loadGeometries( primitives ) );39683969		return Promise.all( pending ).then( async function ( results ) {39703971			const materials = results.slice( 0, results.length - 1 );3972			const geometries = results[ results.length - 1 ];39733974			const meshes = [];39753976			for ( let i = 0, il = geometries.length; i < il; i ++ ) {39773978				const geometry = geometries[ i ];3979				const primitive = primitives[ i ];39803981				// 1. create Mesh39823983				let mesh;39843985				const material = materials[ i ];39863987				if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||3988						primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||3989						primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||3990						primitive.mode === undefined ) {39913992					const needsSkinning = meshDef.isSkinnedMesh === true;3993					const hasSkinningAttributes = geometry.hasAttribute( 'skinIndex' ) && geometry.hasAttribute( 'skinWeight' );39943995					if ( needsSkinning && hasSkinningAttributes === false ) {39963997						console.warn( 'THREE.GLTFLoader: Missing skinIndex or skinWeight attributes. Skinning disabled.' );39983999					}40004001					// .isSkinnedMesh isn't in glTF spec. See ._markDefs()4002					mesh = ( needsSkinning && hasSkinningAttributes )4003						? new SkinnedMesh( geometry, material )4004						: new Mesh( geometry, material );40054006					if ( mesh.isSkinnedMesh === true ) {40074008						// normalize skin weights to fix malformed assets (see #15319)4009						mesh.normalizeSkinWeights();40104011					}40124013				} else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {40144015					mesh = new LineSegments( geometry, material );40164017				} else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {40184019					mesh = new Line( geometry, material );40204021				} else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {40224023					mesh = new LineLoop( geometry, material );40244025				} else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {40264027					mesh = new Points( geometry, material );40284029				} else {40304031					throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );40324033				}40344035				if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {40364037					updateMorphTargets( mesh, meshDef );40384039				}40404041				mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );40424043				assignExtrasToUserData( mesh, meshDef );40444045				if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );40464047				parser.assignFinalMaterial( mesh );40484049				meshes.push( mesh );40504051			}40524053			for ( let i = 0, il = meshes.length; i < il; i ++ ) {40544055				parser.associations.set( meshes[ i ], {4056					meshes: meshIndex,4057					primitives: i4058				} );40594060			}40614062			if ( meshes.length === 1 ) {40634064				if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, meshes[ 0 ], meshDef );40654066				return meshes[ 0 ];40674068			}40694070			const group = new Group();40714072			if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, group, meshDef );40734074			parser.associations.set( group, { meshes: meshIndex } );40754076			for ( let i = 0, il = meshes.length; i < il; i ++ ) {40774078				group.add( meshes[ i ] );40794080			}40814082			return group;40834084		} );40854086	}40874088	/**4089	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras4090	 *4091	 * @private4092	 * @param {number} cameraIndex4093	 * @return {Promise<Camera>|undefined}4094	 */4095	loadCamera( cameraIndex ) {40964097		let camera;4098		const cameraDef = this.json.cameras[ cameraIndex ];4099		const params = cameraDef[ cameraDef.type ];41004101		if ( ! params ) {41024103			console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );4104			return;41054106		}41074108		if ( cameraDef.type === 'perspective' ) {41094110			camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );41114112		} else if ( cameraDef.type === 'orthographic' ) {41134114			camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );41154116		}41174118		if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );41194120		assignExtrasToUserData( camera, cameraDef );41214122		return Promise.resolve( camera );41234124	}41254126	/**4127	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins4128	 *4129	 * @private4130	 * @param {number} skinIndex4131	 * @return {Promise<Skeleton>}4132	 */4133	loadSkin( skinIndex ) {41344135		const skinDef = this.json.skins[ skinIndex ];41364137		const pending = [];41384139		for ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) {41404141			pending.push( this._loadNodeShallow( skinDef.joints[ i ] ) );41424143		}41444145		if ( skinDef.inverseBindMatrices !== undefined ) {41464147			pending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) );41484149		} else {41504151			pending.push( null );41524153		}41544155		return Promise.all( pending ).then( function ( results ) {41564157			const inverseBindMatrices = results.pop();4158			const jointNodes = results;41594160			// Note that bones (joint nodes) may or may not be in the4161			// scene graph at this time.41624163			const bones = [];4164			const boneInverses = [];41654166			for ( let i = 0, il = jointNodes.length; i < il; i ++ ) {41674168				const jointNode = jointNodes[ i ];41694170				if ( jointNode ) {41714172					bones.push( jointNode );41734174					const mat = new Matrix4();41754176					if ( inverseBindMatrices !== null ) {41774178						mat.fromArray( inverseBindMatrices.array, i * 16 );41794180					}41814182					boneInverses.push( mat );41834184				} else {41854186					console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[ i ] );41874188				}41894190			}41914192			return new Skeleton( bones, boneInverses );41934194		} );41954196	}41974198	/**4199	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations4200	 *4201	 * @private4202	 * @param {number} animationIndex4203	 * @return {Promise<AnimationClip>}4204	 */4205	loadAnimation( animationIndex ) {42064207		const json = this.json;4208		const parser = this;42094210		const animationDef = json.animations[ animationIndex ];4211		const animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex;42124213		const pendingNodes = [];4214		const pendingInputAccessors = [];4215		const pendingOutputAccessors = [];4216		const pendingSamplers = [];4217		const pendingTargets = [];42184219		for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {42204221			const channel = animationDef.channels[ i ];4222			const sampler = animationDef.samplers[ channel.sampler ];4223			const target = channel.target;4224			const name = target.node;4225			const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;4226			const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;42274228			if ( target.node === undefined ) continue;42294230			pendingNodes.push( this.getDependency( 'node', name ) );4231			pendingInputAccessors.push( this.getDependency( 'accessor', input ) );4232			pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );4233			pendingSamplers.push( sampler );4234			pendingTargets.push( target );42354236		}42374238		return Promise.all( [42394240			Promise.all( pendingNodes ),4241			Promise.all( pendingInputAccessors ),4242			Promise.all( pendingOutputAccessors ),4243			Promise.all( pendingSamplers ),4244			Promise.all( pendingTargets )42454246		] ).then( function ( dependencies ) {42474248			const nodes = dependencies[ 0 ];4249			const inputAccessors = dependencies[ 1 ];4250			const outputAccessors = dependencies[ 2 ];4251			const samplers = dependencies[ 3 ];4252			const targets = dependencies[ 4 ];42534254			const tracks = [];42554256			for ( let i = 0, il = nodes.length; i < il; i ++ ) {42574258				const node = nodes[ i ];4259				const inputAccessor = inputAccessors[ i ];4260				const outputAccessor = outputAccessors[ i ];4261				const sampler = samplers[ i ];4262				const target = targets[ i ];42634264				if ( node === undefined ) continue;42654266				if ( node.updateMatrix ) {42674268					node.updateMatrix();42694270				}42714272				const createdTracks = parser._createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target );42734274				if ( createdTracks ) {42754276					for ( let k = 0; k < createdTracks.length; k ++ ) {42774278						tracks.push( createdTracks[ k ] );42794280					}42814282				}42834284			}42854286			const animation = new AnimationClip( animationName, undefined, tracks );42874288			assignExtrasToUserData( animation, animationDef );42894290			return animation;42914292		} );42934294	}42954296	createNodeMesh( nodeIndex ) {42974298		const json = this.json;4299		const parser = this;4300		const nodeDef = json.nodes[ nodeIndex ];43014302		if ( nodeDef.mesh === undefined ) return null;43034304		return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {43054306			const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );43074308			// if weights are provided on the node, override weights on the mesh.4309			if ( nodeDef.weights !== undefined ) {43104311				node.traverse( function ( o ) {43124313					if ( ! o.isMesh ) return;43144315					for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {43164317						o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];43184319					}43204321				} );43224323			}43244325			return node;43264327		} );43284329	}43304331	/**4332	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy4333	 *4334	 * @private4335	 * @param {number} nodeIndex4336	 * @return {Promise<Object3D>}4337	 */4338	loadNode( nodeIndex ) {43394340		const json = this.json;4341		const parser = this;43424343		const nodeDef = json.nodes[ nodeIndex ];43444345		const nodePending = parser._loadNodeShallow( nodeIndex );43464347		const childPending = [];4348		const childrenDef = nodeDef.children || [];43494350		for ( let i = 0, il = childrenDef.length; i < il; i ++ ) {43514352			childPending.push( parser.getDependency( 'node', childrenDef[ i ] ) );43534354		}43554356		const skeletonPending = nodeDef.skin === undefined4357			? Promise.resolve( null )4358			: parser.getDependency( 'skin', nodeDef.skin );43594360		return Promise.all( [4361			nodePending,4362			Promise.all( childPending ),4363			skeletonPending4364		] ).then( function ( results ) {43654366			const node = results[ 0 ];4367			const children = results[ 1 ];4368			const skeleton = results[ 2 ];43694370			if ( skeleton !== null ) {43714372				// This full traverse should be fine because4373				// child glTF nodes have not been added to this node yet.4374				node.traverse( function ( mesh ) {43754376					if ( ! mesh.isSkinnedMesh ) return;43774378					mesh.bind( skeleton, _identityMatrix );43794380				} );43814382			}43834384			for ( let i = 0, il = children.length; i < il; i ++ ) {43854386				node.add( children[ i ] );43874388			}43894390			// Reconstruct pivot from container pattern created by GLTFExporter4391			// The container has position+pivot, rotation, scale; child has -pivot offset and mesh4392			if ( node.userData.pivot !== undefined && children.length > 0 ) {43934394				const pivot = node.userData.pivot;4395				const pivotChild = children[ 0 ];43964397				// Set pivot on container and adjust transforms4398				node.pivot = new Vector3().fromArray( pivot );43994400				// Adjust container position: stored as position + pivot, so subtract pivot4401				node.position.x -= pivot[ 0 ];4402				node.position.y -= pivot[ 1 ];4403				node.position.z -= pivot[ 2 ];44044405				// Remove the child's -pivot offset since pivot now handles it4406				pivotChild.position.set( 0, 0, 0 );44074408				delete node.userData.pivot;44094410			}44114412			return node;44134414		} );44154416	}44174418	// ._loadNodeShallow() parses a single node.4419	// skin and child nodes are created and added in .loadNode() (no '_' prefix).4420	_loadNodeShallow( nodeIndex ) {44214422		const json = this.json;4423		const extensions = this.extensions;4424		const parser = this;44254426		// This method is called from .loadNode() and .loadSkin().4427		// Cache a node to avoid duplication.44284429		if ( this.nodeCache[ nodeIndex ] !== undefined ) {44304431			return this.nodeCache[ nodeIndex ];44324433		}44344435		const nodeDef = json.nodes[ nodeIndex ];44364437		// reserve node's name before its dependencies, so the root has the intended name.4438		const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';44394440		const pending = [];44414442		const meshPromise = parser._invokeOne( function ( ext ) {44434444			return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );44454446		} );44474448		if ( meshPromise ) {44494450			pending.push( meshPromise );44514452		}44534454		if ( nodeDef.camera !== undefined ) {44554456			pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {44574458				return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );44594460			} ) );44614462		}44634464		parser._invokeAll( function ( ext ) {44654466			return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );44674468		} ).forEach( function ( promise ) {44694470			pending.push( promise );44714472		} );44734474		this.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) {44754476			let node;44774478			// .isBone isn't in glTF spec. See ._markDefs4479			if ( nodeDef.isBone === true ) {44804481				node = new Bone();44824483			} else if ( objects.length > 1 ) {44844485				node = new Group();44864487			} else if ( objects.length === 1 ) {44884489				node = objects[ 0 ];44904491			} else {44924493				node = new Object3D();44944495			}44964497			if ( node !== objects[ 0 ] ) {44984499				for ( let i = 0, il = objects.length; i < il; i ++ ) {45004501					node.add( objects[ i ] );45024503				}45044505			}45064507			if ( nodeDef.name ) {45084509				node.userData.name = nodeDef.name;4510				node.name = nodeName;45114512			}45134514			assignExtrasToUserData( node, nodeDef );45154516			if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );45174518			if ( nodeDef.matrix !== undefined ) {45194520				const matrix = new Matrix4();4521				matrix.fromArray( nodeDef.matrix );4522				node.applyMatrix4( matrix );45234524			} else {45254526				if ( nodeDef.translation !== undefined ) {45274528					node.position.fromArray( nodeDef.translation );45294530				}45314532				if ( nodeDef.rotation !== undefined ) {45334534					node.quaternion.fromArray( nodeDef.rotation );45354536				}45374538				if ( nodeDef.scale !== undefined ) {45394540					node.scale.fromArray( nodeDef.scale );45414542				}45434544			}45454546			if ( ! parser.associations.has( node ) ) {45474548				parser.associations.set( node, {} );45494550			} else if ( nodeDef.mesh !== undefined && parser.meshCache.refs[ nodeDef.mesh ] > 1 ) {45514552				const mapping = parser.associations.get( node );4553				parser.associations.set( node, { ...mapping } );45544555			}45564557			parser.associations.get( node ).nodes = nodeIndex;45584559			return node;45604561		} );45624563		return this.nodeCache[ nodeIndex ];45644565	}45664567	/**4568	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes4569	 *4570	 * @private4571	 * @param {number} sceneIndex4572	 * @return {Promise<Group>}4573	 */4574	loadScene( sceneIndex ) {45754576		const extensions = this.extensions;4577		const sceneDef = this.json.scenes[ sceneIndex ];4578		const parser = this;45794580		// Loader returns Group, not Scene.4581		// See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-5789811724582		const scene = new Group();4583		if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );45844585		assignExtrasToUserData( scene, sceneDef );45864587		if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );45884589		const nodeIds = sceneDef.nodes || [];45904591		const pending = [];45924593		for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {45944595			pending.push( parser.getDependency( 'node', nodeIds[ i ] ) );45964597		}45984599		return Promise.all( pending ).then( function ( nodes ) {46004601			for ( let i = 0, il = nodes.length; i < il; i ++ ) {46024603				const node = nodes[ i ];46044605				// If the node already has a parent, it means it's being reused across multiple scenes.4606				// Clone it to avoid the second scene's add() removing it from the first scene.4607				// See: https://github.com/mrdoob/three.js/issues/279934608				if ( node.parent !== null ) {46094610					scene.add( clone( node ) );46114612				} else {46134614					scene.add( node );46154616				}46174618			}46194620			// Removes dangling associations, associations that reference a node that4621			// didn't make it into the scene.4622			const reduceAssociations = ( node ) => {46234624				const reducedAssociations = new Map();46254626				for ( const [ key, value ] of parser.associations ) {46274628					if ( key instanceof Material || key instanceof Texture ) {46294630						reducedAssociations.set( key, value );46314632					}46334634				}46354636				node.traverse( ( node ) => {46374638					const mappings = parser.associations.get( node );46394640					if ( mappings != null ) {46414642						reducedAssociations.set( node, mappings );46434644					}46454646				} );46474648				return reducedAssociations;46494650			};46514652			parser.associations = reduceAssociations( scene );46534654			return scene;46554656		} );46574658	}46594660	_createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target ) {46614662		const tracks = [];46634664		const targetName = node.name ? node.name : node.uuid;4665		const targetNames = [];46664667		function collectMorphTargets( object ) {46684669			if ( object.morphTargetInfluences ) {46704671				targetNames.push( object.name ? object.name : object.uuid );46724673			}46744675		}467646774678		if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {46794680			collectMorphTargets( node );46814682			// for multi-primitive meshes, the node is a Group containing the sub-meshes46834684			if ( node.isGroup ) {46854686				node.children.forEach( collectMorphTargets );46874688			}46894690		} else {46914692			targetNames.push( targetName );46934694		}46954696		let TypedKeyframeTrack;46974698		switch ( PATH_PROPERTIES[ target.path ] ) {46994700			case PATH_PROPERTIES.weights:47014702				TypedKeyframeTrack = NumberKeyframeTrack;4703				break;47044705			case PATH_PROPERTIES.rotation:47064707				TypedKeyframeTrack = QuaternionKeyframeTrack;4708				break;47094710			case PATH_PROPERTIES.translation:4711			case PATH_PROPERTIES.scale:47124713				TypedKeyframeTrack = VectorKeyframeTrack;4714				break;47154716			default:47174718				switch ( outputAccessor.itemSize ) {47194720					case 1:4721						TypedKeyframeTrack = NumberKeyframeTrack;4722						break;4723					case 2:4724					case 3:4725					default:4726						TypedKeyframeTrack = VectorKeyframeTrack;4727						break;47284729				}47304731				break;47324733		}47344735		const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;473647374738		const outputArray = this._getArrayFromAccessor( outputAccessor );47394740		for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {47414742			const track = new TypedKeyframeTrack(4743				targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],4744				inputAccessor.array,4745				outputArray,4746				interpolation4747			);47484749			// Override interpolation with custom factory method.4750			if ( sampler.interpolation === 'CUBICSPLINE' ) {47514752				this._createCubicSplineTrackInterpolant( track );47534754			}47554756			tracks.push( track );47574758		}47594760		return tracks;47614762	}47634764	_getArrayFromAccessor( accessor ) {47654766		let outputArray = accessor.array;47674768		if ( accessor.normalized ) {47694770			const scale = getNormalizedComponentScale( outputArray.constructor );4771			const scaled = new Float32Array( outputArray.length );47724773			for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {47744775				scaled[ j ] = outputArray[ j ] * scale;47764777			}47784779			outputArray = scaled;47804781		}47824783		return outputArray;47844785	}47864787	_createCubicSplineTrackInterpolant( track ) {47884789		track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {47904791			// A CUBICSPLINE keyframe in glTF has three output values for each input value,4792			// representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()4793			// must be divided by three to get the interpolant's sampleSize argument.47944795			const interpolantType = ( this instanceof QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;47964797			return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );47984799		};48004801		// Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.4802		track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;48034804	}48054806}48074808/**4809 *4810 * @private4811 * @param {BufferGeometry} geometry4812 * @param {GLTF.Primitive} primitiveDef4813 * @param {GLTFParser} parser4814 */4815function computeBounds( geometry, primitiveDef, parser ) {48164817	const attributes = primitiveDef.attributes;48184819	const box = new Box3();48204821	if ( attributes.POSITION !== undefined ) {48224823		const accessor = parser.json.accessors[ attributes.POSITION ];48244825		const min = accessor.min;4826		const max = accessor.max;48274828		// glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.48294830		if ( min !== undefined && max !== undefined ) {48314832			box.set(4833				new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),4834				new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )4835			);48364837			if ( accessor.normalized ) {48384839				const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );4840				box.min.multiplyScalar( boxScale );4841				box.max.multiplyScalar( boxScale );48424843			}48444845		} else {48464847			console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );48484849			return;48504851		}48524853	} else {48544855		return;48564857	}48584859	const targets = primitiveDef.targets;48604861	if ( targets !== undefined ) {48624863		const maxDisplacement = new Vector3();4864		const vector = new Vector3();48654866		for ( let i = 0, il = targets.length; i < il; i ++ ) {48674868			const target = targets[ i ];48694870			if ( target.POSITION !== undefined ) {48714872				const accessor = parser.json.accessors[ target.POSITION ];4873				const min = accessor.min;4874				const max = accessor.max;48754876				// glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.48774878				if ( min !== undefined && max !== undefined ) {48794880					// we need to get max of absolute components because target weight is [-1,1]4881					vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );4882					vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );4883					vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );488448854886					if ( accessor.normalized ) {48874888						const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );4889						vector.multiplyScalar( boxScale );48904891					}48924893					// Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative4894					// to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets4895					// are used to implement key-frame animations and as such only two are active at a time - this results in very large4896					// boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.4897					maxDisplacement.max( vector );48984899				} else {49004901					console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );49024903				}49044905			}49064907		}49084909		// As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.4910		box.expandByVector( maxDisplacement );49114912	}49134914	geometry.boundingBox = box;49154916	const sphere = new Sphere();49174918	box.getCenter( sphere.center );4919	sphere.radius = box.min.distanceTo( box.max ) / 2;49204921	geometry.boundingSphere = sphere;49224923}49244925/**4926 *4927 * @private4928 * @param {BufferGeometry} geometry4929 * @param {GLTF.Primitive} primitiveDef4930 * @param {GLTFParser} parser4931 * @return {Promise<BufferGeometry>}4932 */4933function addPrimitiveAttributes( geometry, primitiveDef, parser ) {49344935	const attributes = primitiveDef.attributes;49364937	const pending = [];49384939	function assignAttributeAccessor( accessorIndex, attributeName ) {49404941		return parser.getDependency( 'accessor', accessorIndex )4942			.then( function ( accessor ) {49434944				geometry.setAttribute( attributeName, accessor );49454946			} );49474948	}49494950	for ( const gltfAttributeName in attributes ) {49514952		const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();49534954		// Skip attributes already provided by e.g. Draco extension.4955		if ( threeAttributeName in geometry.attributes ) continue;49564957		pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );49584959	}49604961	if ( primitiveDef.indices !== undefined && ! geometry.index ) {49624963		const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {49644965			geometry.setIndex( accessor );49664967		} );49684969		pending.push( accessor );49704971	}49724973	if ( ColorManagement.workingColorSpace !== LinearSRGBColorSpace && 'COLOR_0' in attributes ) {49744975		console.warn( `THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.` );49764977	}49784979	assignExtrasToUserData( geometry, primitiveDef );49804981	computeBounds( geometry, primitiveDef, parser );49824983	return Promise.all( pending ).then( function () {49844985		return primitiveDef.targets !== undefined4986			? addMorphTargets( geometry, primitiveDef.targets, parser )4987			: geometry;49884989	} );49904991}49924993/**4994 * Loader result of `GLTFLoader`.4995 *4996 * @typedef {Object} GLTFLoader~LoadObject4997 * @property {Array<AnimationClip>} animations - An array of animation clips.4998 * @property {Object} asset - Meta data about the loaded asset.4999 * @property {Array<Camera>} cameras - An array of cameras.5000 * @property {GLTFParser} parser - A reference to the internal parser.5001 * @property {Group} scene - The default scene.5002 * @property {Array<Group>} scenes - glTF assets might define multiple scenes.5003 * @property {Object} userData - Additional data.5004 **/50055006export { GLTFLoader };