GLTFLoader.js 54.9 KB
Newer Older
D
Don McCurdy 已提交
1 2 3 4 5 6 7 8
/**
 * @author Rich Tibbett / https://github.com/richtr
 * @author mrdoob / http://mrdoob.com/
 * @author Tony Parisi / http://www.tonyparisi.com/
 * @author Takahiro / https://github.com/takahirox
 * @author Don McCurdy / https://www.donmccurdy.com
 */

9
THREE.GLTFLoader = ( function () {
D
Don McCurdy 已提交
10

11
	function GLTFLoader( manager ) {
D
Don McCurdy 已提交
12 13 14 15 16

		this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;

	}

17
	GLTFLoader.prototype = {
D
Don McCurdy 已提交
18

19
		constructor: GLTFLoader,
D
Don McCurdy 已提交
20

21 22
		crossOrigin: 'Anonymous',

D
Don McCurdy 已提交
23 24 25 26
		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

M
Mugen87 已提交
27
			var path = this.path && ( typeof this.path === 'string' ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
D
Don McCurdy 已提交
28 29 30 31 32 33 34

			var loader = new THREE.FileLoader( scope.manager );

			loader.setResponseType( 'arraybuffer' );

			loader.load( url, function ( data ) {

35 36 37 38 39 40
				try {

					scope.parse( data, path, onLoad, onError );

				} catch ( e ) {

41 42 43 44 45 46
					if ( onError !== undefined ) {

						// For SyntaxError or TypeError, return a generic failure message.
						onError( e.constructor === Error ? e : new Error( 'THREE.GLTFLoader: Unable to parse model.' ) );

					}
47 48

				}
D
Don McCurdy 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

			}, onProgress, onError );

		},

		setCrossOrigin: function ( value ) {

			this.crossOrigin = value;

		},

		setPath: function ( value ) {

			this.path = value;

		},

66
		parse: function ( data, path, onLoad, onError ) {
D
Don McCurdy 已提交
67 68 69 70 71 72

			var content;
			var extensions = {};

			var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );

73
			if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
D
Don McCurdy 已提交
74 75 76 77 78 79 80 81 82 83 84 85

				extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
				content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;

			} else {

				content = convertUint8ArrayToString( new Uint8Array( data ) );

			}

			var json = JSON.parse( content );

86
			if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
87

88
				onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
89 90 91 92
				return;

			}

93
			if ( json.extensionsUsed ) {
D
Don McCurdy 已提交
94

M
Mugen87 已提交
95
				if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
96 97 98 99 100

					extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );

				}

M
Mugen87 已提交
101
				if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
102 103 104 105 106

					extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );

				}

M
Mugen87 已提交
107
				if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
108 109 110 111

					extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();

				}
D
Don McCurdy 已提交
112 113 114

			}

115
			console.time( 'GLTFLoader' );
D
Don McCurdy 已提交
116 117 118 119 120 121 122 123 124 125

			var parser = new GLTFParser( json, extensions, {

				path: path || this.path,
				crossOrigin: this.crossOrigin

			} );

			parser.parse( function ( scene, scenes, cameras, animations ) {

126
				console.timeEnd( 'GLTFLoader' );
D
Don McCurdy 已提交
127 128

				var glTF = {
M
Mugen87 已提交
129 130 131 132
					scene: scene,
					scenes: scenes,
					cameras: cameras,
					animations: animations
D
Don McCurdy 已提交
133 134
				};

135
				onLoad( glTF );
D
Don McCurdy 已提交
136

137
			}, onError );
D
Don McCurdy 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

		}

	};

	/* GLTFREGISTRY */

	function GLTFRegistry() {

		var objects = {};

		return	{

			get: function ( key ) {

				return objects[ key ];

			},

			add: function ( key, object ) {

				objects[ key ] = object;

			},

			remove: function ( key ) {

				delete objects[ key ];

			},

			removeAll: function () {

				objects = {};

			}

		};

	}

	/*********************************/
	/********** EXTENSIONS ***********/
	/*********************************/

	var EXTENSIONS = {
		KHR_BINARY_GLTF: 'KHR_binary_glTF',
185
		KHR_LIGHTS: 'KHR_lights',
186
		KHR_MATERIALS_COMMON: 'KHR_materials_common',
187
		KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness'
D
Don McCurdy 已提交
188 189
	};

190 191 192 193 194 195
	/**
	 * Lights Extension
	 *
	 * Specification: PENDING
	 */
	function GLTFLightsExtension( json ) {
D
Don McCurdy 已提交
196

197
		this.name = EXTENSIONS.KHR_LIGHTS;
D
Don McCurdy 已提交
198 199 200

		this.lights = {};

201
		var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
D
Don McCurdy 已提交
202 203 204 205 206 207 208
		var lights = extension.lights || {};

		for ( var lightId in lights ) {

			var light = lights[ lightId ];
			var lightNode;

209
			var color = new THREE.Color().fromArray( light.color );
D
Don McCurdy 已提交
210 211 212

			switch ( light.type ) {

213
				case 'directional':
D
Don McCurdy 已提交
214 215 216 217
					lightNode = new THREE.DirectionalLight( color );
					lightNode.position.set( 0, 0, 1 );
					break;

218
				case 'point':
D
Don McCurdy 已提交
219 220 221
					lightNode = new THREE.PointLight( color );
					break;

222
				case 'spot':
D
Don McCurdy 已提交
223 224 225 226
					lightNode = new THREE.SpotLight( color );
					lightNode.position.set( 0, 0, 1 );
					break;

227
				case 'ambient':
D
Don McCurdy 已提交
228 229 230 231 232 233 234
					lightNode = new THREE.AmbientLight( color );
					break;

			}

			if ( lightNode ) {

235 236 237 238 239 240 241 242 243 244 245 246 247 248
				if ( light.constantAttenuation !== undefined ) {

					lightNode.intensity = light.constantAttenuation;

				}

				if ( light.linearAttenuation !== undefined ) {

					lightNode.distance = 1 / light.linearAttenuation;

				}

				if ( light.quadraticAttenuation !== undefined ) {

249
					lightNode.decay = light.quadraticAttenuation;
250 251 252 253 254 255 256 257 258 259 260

				}

				if ( light.fallOffAngle !== undefined ) {

					lightNode.angle = light.fallOffAngle;

				}

				if ( light.fallOffExponent !== undefined ) {

261
					console.warn( 'THREE.GLTFLoader:: light.fallOffExponent not currently supported.' );
262 263 264

				}

265
				lightNode.name = light.name || ( 'light_' + lightId );
D
Don McCurdy 已提交
266 267 268 269 270 271 272 273
				this.lights[ lightId ] = lightNode;

			}

		}

	}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
	/**
	 * Common Materials Extension
	 *
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common
	 */
	function GLTFMaterialsCommonExtension( json ) {

		this.name = EXTENSIONS.KHR_MATERIALS_COMMON;

	}

	GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) {

		var khrMaterial = material.extensions[ this.name ];

		switch ( khrMaterial.type ) {

			case 'commonBlinn' :
			case 'commonPhong' :
				return THREE.MeshPhongMaterial;

			case 'commonLambert' :
				return THREE.MeshLambertMaterial;

			case 'commonConstant' :
			default :
				return THREE.MeshBasicMaterial;

		}

	};

306
	GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, parser ) {
307 308 309

		var khrMaterial = material.extensions[ this.name ];

310 311
		var pending = [];

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
		var keys = [];

		// TODO: Currently ignored: 'ambientFactor', 'ambientTexture'
		switch ( khrMaterial.type ) {

			case 'commonBlinn' :
			case 'commonPhong' :
				keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' );
				break;

			case 'commonLambert' :
				keys.push( 'diffuseFactor', 'diffuseTexture' );
				break;

			case 'commonConstant' :
			default :
				break;

		}

		var materialValues = {};

M
Mugen87 已提交
334
		keys.forEach( function ( v ) {
335 336 337 338 339 340 341 342

			if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ];

		} );

		if ( materialValues.diffuseFactor !== undefined ) {

			materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor );
343
			materialParams.opacity = materialValues.diffuseFactor[ 3 ];
344 345 346 347 348

		}

		if ( materialValues.diffuseTexture !== undefined ) {

349
			pending.push( parser.assignTexture( materialParams, 'map', materialValues.diffuseTexture.index ) );
350 351 352 353 354 355 356 357 358 359 360

		}

		if ( materialValues.specularFactor !== undefined ) {

			materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor );

		}

		if ( materialValues.specularTexture !== undefined ) {

361
			pending.push( parser.assignTexture( materialParams, 'specularMap', materialValues.specularTexture.index ) );
362 363 364 365 366 367 368 369 370

		}

		if ( materialValues.shininessFactor !== undefined ) {

			materialParams.shininess = materialValues.shininessFactor;

		}

371 372
		return Promise.all( pending );

373 374
	};

D
Don McCurdy 已提交
375 376 377
	/* BINARY EXTENSION */

	var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
378 379 380
	var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
	var BINARY_EXTENSION_HEADER_LENGTH = 12;
	var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
D
Don McCurdy 已提交
381 382 383 384

	function GLTFBinaryExtension( data ) {

		this.name = EXTENSIONS.KHR_BINARY_GLTF;
385 386
		this.content = null;
		this.body = null;
D
Don McCurdy 已提交
387 388 389

		var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );

390
		this.header = {
D
Don McCurdy 已提交
391 392
			magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
			version: headerView.getUint32( 4, true ),
393
			length: headerView.getUint32( 8, true )
D
Don McCurdy 已提交
394 395
		};

396
		if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
D
Don McCurdy 已提交
397

398
			throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
D
Don McCurdy 已提交
399

400
		} else if ( this.header.version < 2.0 ) {
D
Don McCurdy 已提交
401

402
			throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use GLTFLoader instead.' );
D
Don McCurdy 已提交
403 404 405

		}

406 407
		var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
		var chunkIndex = 0;
D
Don McCurdy 已提交
408

409
		while ( chunkIndex < chunkView.byteLength ) {
D
Don McCurdy 已提交
410

411 412
			var chunkLength = chunkView.getUint32( chunkIndex, true );
			chunkIndex += 4;
D
Don McCurdy 已提交
413

414 415
			var chunkType = chunkView.getUint32( chunkIndex, true );
			chunkIndex += 4;
D
Don McCurdy 已提交
416

417
			if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
D
Don McCurdy 已提交
418

419 420
				var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
				this.content = convertUint8ArrayToString( contentArray );
D
Don McCurdy 已提交
421

422
			} else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
D
Don McCurdy 已提交
423

424 425
				var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
				this.body = data.slice( byteOffset, byteOffset + chunkLength );
D
Don McCurdy 已提交
426

427
			}
D
Don McCurdy 已提交
428

429
			// Clients must ignore chunks with unknown types.
D
Don McCurdy 已提交
430

431 432 433 434 435 436
			chunkIndex += chunkLength;

		}

		if ( this.content === null ) {

437
			throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
438 439 440 441

		}

	}
D
Don McCurdy 已提交
442

443 444 445 446 447
	/**
	 * Specular-Glossiness Extension
	 *
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
	 */
448 449 450 451
	function GLTFMaterialsPbrSpecularGlossinessExtension() {

		return {

452 453 454 455 456 457 458 459
			name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,

			getMaterialType: function () {

				return THREE.ShaderMaterial;

			},

460
			extendParams: function ( params, material, parser ) {
461

462
				var pbrSpecularGlossiness = material.extensions[ this.name ];
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

				var shader = THREE.ShaderLib[ 'standard' ];

				var uniforms = THREE.UniformsUtils.clone( shader.uniforms );

				var specularMapParsFragmentChunk = [
					'#ifdef USE_SPECULARMAP',
					'	uniform sampler2D specularMap;',
					'#endif'
				].join( '\n' );

				var glossinessMapParsFragmentChunk = [
					'#ifdef USE_GLOSSINESSMAP',
					'	uniform sampler2D glossinessMap;',
					'#endif'
				].join( '\n' );

				var specularMapFragmentChunk = [
					'vec3 specularFactor = specular;',
					'#ifdef USE_SPECULARMAP',
					'	vec4 texelSpecular = texture2D( specularMap, vUv );',
					'	// reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
					'	specularFactor *= texelSpecular.rgb;',
					'#endif'
				].join( '\n' );

				var glossinessMapFragmentChunk = [
					'float glossinessFactor = glossiness;',
					'#ifdef USE_GLOSSINESSMAP',
					'	vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
					'	// reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
					'	glossinessFactor *= texelGlossiness.a;',
					'#endif'
				].join( '\n' );

				var lightPhysicalFragmentChunk = [
					'PhysicalMaterial material;',
					'material.diffuseColor = diffuseColor.rgb;',
					'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
					'material.specularColor = specularFactor.rgb;',
				].join( '\n' );

				var fragmentShader = shader.fragmentShader
M
Mugen87 已提交
506 507 508 509 510 511 512 513
					.replace( '#include <specularmap_fragment>', '' )
					.replace( 'uniform float roughness;', 'uniform vec3 specular;' )
					.replace( 'uniform float metalness;', 'uniform float glossiness;' )
					.replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
					.replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
					.replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
					.replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
					.replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

				delete uniforms.roughness;
				delete uniforms.metalness;
				delete uniforms.roughnessMap;
				delete uniforms.metalnessMap;

				uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
				uniforms.glossiness = { value: 0.5 };
				uniforms.specularMap = { value: null };
				uniforms.glossinessMap = { value: null };

				params.vertexShader = shader.vertexShader;
				params.fragmentShader = fragmentShader;
				params.uniforms = uniforms;
				params.defines = { 'STANDARD': '' };

				params.color = new THREE.Color( 1.0, 1.0, 1.0 );
				params.opacity = 1.0;

533 534
				var pending = [];

535 536 537 538 539 540 541 542 543 544 545
				if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {

					var array = pbrSpecularGlossiness.diffuseFactor;

					params.color.fromArray( array );
					params.opacity = array[ 3 ];

				}

				if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {

546
					pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
547 548 549

				}

550
				params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
551 552 553 554 555 556 557 558 559 560 561
				params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
				params.specular = new THREE.Color( 1.0, 1.0, 1.0 );

				if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {

					params.specular.fromArray( pbrSpecularGlossiness.specularFactor );

				}

				if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {

562 563 564
					var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
					pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
					pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
565 566 567

				}

568 569
				return Promise.all( pending );

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
			},

			createMaterial: function ( params ) {

				// setup material properties based on MeshStandardMaterial for Specular-Glossiness

				var material = new THREE.ShaderMaterial( {
					defines: params.defines,
					vertexShader: params.vertexShader,
					fragmentShader: params.fragmentShader,
					uniforms: params.uniforms,
					fog: true,
					lights: true,
					opacity: params.opacity,
					transparent: params.transparent
				} );

587 588
				material.isGLTFSpecularGlossinessMaterial = true;

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
				material.color = params.color;

				material.map = params.map === undefined ? null : params.map;

				material.lightMap = null;
				material.lightMapIntensity = 1.0;

				material.aoMap = params.aoMap === undefined ? null : params.aoMap;
				material.aoMapIntensity = 1.0;

				material.emissive = params.emissive;
				material.emissiveIntensity = 1.0;
				material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;

				material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
				material.bumpScale = 1;

				material.normalMap = params.normalMap === undefined ? null : params.normalMap;
607
				if ( params.normalScale ) material.normalScale = params.normalScale;
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

				material.displacementMap = null;
				material.displacementScale = 1;
				material.displacementBias = 0;

				material.specularMap = params.specularMap === undefined ? null : params.specularMap;
				material.specular = params.specular;

				material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
				material.glossiness = params.glossiness;

				material.alphaMap = null;

				material.envMap = params.envMap === undefined ? null : params.envMap;
				material.envMapIntensity = 1.0;

				material.refractionRatio = 0.98;

				material.extensions.derivatives = true;

				return material;

			},

			// Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
			refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {

				var uniforms = material.uniforms;
				var defines = material.defines;

				uniforms.opacity.value = material.opacity;

				uniforms.diffuse.value.copy( material.color );
				uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );

				uniforms.map.value = material.map;
				uniforms.specularMap.value = material.specularMap;
				uniforms.alphaMap.value = material.alphaMap;

				uniforms.lightMap.value = material.lightMap;
				uniforms.lightMapIntensity.value = material.lightMapIntensity;

				uniforms.aoMap.value = material.aoMap;
				uniforms.aoMapIntensity.value = material.aoMapIntensity;

				// uv repeat and offset setting priorities
				// 1. color map
				// 2. specular map
				// 3. normal map
				// 4. bump map
				// 5. alpha map
				// 6. emissive map

				var uvScaleMap;

				if ( material.map ) {

					uvScaleMap = material.map;

				} else if ( material.specularMap ) {

					uvScaleMap = material.specularMap;

				} else if ( material.displacementMap ) {

					uvScaleMap = material.displacementMap;

				} else if ( material.normalMap ) {

					uvScaleMap = material.normalMap;

				} else if ( material.bumpMap ) {

					uvScaleMap = material.bumpMap;

				} else if ( material.glossinessMap ) {

					uvScaleMap = material.glossinessMap;

				} else if ( material.alphaMap ) {

					uvScaleMap = material.alphaMap;

				} else if ( material.emissiveMap ) {

					uvScaleMap = material.emissiveMap;

				}

				if ( uvScaleMap !== undefined ) {

					// backwards compatibility
					if ( uvScaleMap.isWebGLRenderTarget ) {

						uvScaleMap = uvScaleMap.texture;

					}

706
					if ( uvScaleMap.matrixAutoUpdate === true ) {
707

708 709 710 711 712 713 714 715 716 717
						var offset = uvScaleMap.offset;
						var repeat = uvScaleMap.repeat;
						var rotation = uvScaleMap.rotation;
						var center = uvScaleMap.center;

						uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );

					}

					uniforms.uvTransform.value.copy( uvScaleMap.matrix );
718 719 720 721 722

				}

				uniforms.envMap.value = material.envMap;
				uniforms.envMapIntensity.value = material.envMapIntensity;
M
Mugen87 已提交
723
				uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

				uniforms.refractionRatio.value = material.refractionRatio;

				uniforms.specular.value.copy( material.specular );
				uniforms.glossiness.value = material.glossiness;

				uniforms.glossinessMap.value = material.glossinessMap;

				uniforms.emissiveMap.value = material.emissiveMap;
				uniforms.bumpMap.value = material.bumpMap;
				uniforms.normalMap.value = material.normalMap;

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

				if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {

					defines.USE_GLOSSINESSMAP = '';
					// set USE_ROUGHNESSMAP to enable vUv
744
					defines.USE_ROUGHNESSMAP = '';
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

				}

				if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {

					delete defines.USE_GLOSSINESSMAP;
					delete defines.USE_ROUGHNESSMAP;

				}

			}

		};

	}

D
Don McCurdy 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	/*********************************/
	/********** INTERNALS ************/
	/*********************************/

	/* CONSTANTS */

	var WEBGL_CONSTANTS = {
		FLOAT: 5126,
		//FLOAT_MAT2: 35674,
		FLOAT_MAT3: 35675,
		FLOAT_MAT4: 35676,
		FLOAT_VEC2: 35664,
		FLOAT_VEC3: 35665,
		FLOAT_VEC4: 35666,
		LINEAR: 9729,
		REPEAT: 10497,
		SAMPLER_2D: 35678,
778
		POINTS: 0,
D
Don McCurdy 已提交
779
		LINES: 1,
780 781 782 783 784
		LINE_LOOP: 2,
		LINE_STRIP: 3,
		TRIANGLES: 4,
		TRIANGLE_STRIP: 5,
		TRIANGLE_FAN: 6,
D
Don McCurdy 已提交
785
		UNSIGNED_BYTE: 5121,
786
		UNSIGNED_SHORT: 5123
D
Don McCurdy 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
	};

	var WEBGL_TYPE = {
		5126: Number,
		//35674: THREE.Matrix2,
		35675: THREE.Matrix3,
		35676: THREE.Matrix4,
		35664: THREE.Vector2,
		35665: THREE.Vector3,
		35666: THREE.Vector4,
		35678: THREE.Texture
	};

	var WEBGL_COMPONENT_TYPES = {
		5120: Int8Array,
		5121: Uint8Array,
		5122: Int16Array,
		5123: Uint16Array,
		5125: Uint32Array,
		5126: Float32Array
	};

	var WEBGL_FILTERS = {
		9728: THREE.NearestFilter,
		9729: THREE.LinearFilter,
		9984: THREE.NearestMipMapNearestFilter,
		9985: THREE.LinearMipMapNearestFilter,
		9986: THREE.NearestMipMapLinearFilter,
		9987: THREE.LinearMipMapLinearFilter
	};

	var WEBGL_WRAPPINGS = {
		33071: THREE.ClampToEdgeWrapping,
		33648: THREE.MirroredRepeatWrapping,
		10497: THREE.RepeatWrapping
	};

	var WEBGL_TEXTURE_FORMATS = {
		6406: THREE.AlphaFormat,
		6407: THREE.RGBFormat,
		6408: THREE.RGBAFormat,
		6409: THREE.LuminanceFormat,
		6410: THREE.LuminanceAlphaFormat
	};

	var WEBGL_TEXTURE_DATATYPES = {
		5121: THREE.UnsignedByteType,
		32819: THREE.UnsignedShort4444Type,
		32820: THREE.UnsignedShort5551Type,
		33635: THREE.UnsignedShort565Type
	};

	var WEBGL_SIDES = {
M
Mugen87 已提交
840 841
		1028: THREE.BackSide, // Culling front
		1029: THREE.FrontSide // Culling back
D
Don McCurdy 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
		//1032: THREE.NoSide   // Culling front and back, what to do?
	};

	var WEBGL_DEPTH_FUNCS = {
		512: THREE.NeverDepth,
		513: THREE.LessDepth,
		514: THREE.EqualDepth,
		515: THREE.LessEqualDepth,
		516: THREE.GreaterEqualDepth,
		517: THREE.NotEqualDepth,
		518: THREE.GreaterEqualDepth,
		519: THREE.AlwaysDepth
	};

	var WEBGL_BLEND_EQUATIONS = {
		32774: THREE.AddEquation,
		32778: THREE.SubtractEquation,
		32779: THREE.ReverseSubtractEquation
	};

	var WEBGL_BLEND_FUNCS = {
		0: THREE.ZeroFactor,
		1: THREE.OneFactor,
		768: THREE.SrcColorFactor,
		769: THREE.OneMinusSrcColorFactor,
		770: THREE.SrcAlphaFactor,
		771: THREE.OneMinusSrcAlphaFactor,
		772: THREE.DstAlphaFactor,
		773: THREE.OneMinusDstAlphaFactor,
		774: THREE.DstColorFactor,
		775: THREE.OneMinusDstColorFactor,
		776: THREE.SrcAlphaSaturateFactor
		// The followings are not supported by Three.js yet
		//32769: CONSTANT_COLOR,
		//32770: ONE_MINUS_CONSTANT_COLOR,
		//32771: CONSTANT_ALPHA,
		//32772: ONE_MINUS_CONSTANT_COLOR
	};

	var WEBGL_TYPE_SIZES = {
		'SCALAR': 1,
		'VEC2': 2,
		'VEC3': 3,
		'VEC4': 4,
		'MAT2': 4,
		'MAT3': 9,
		'MAT4': 16
	};

	var PATH_PROPERTIES = {
		scale: 'scale',
		translation: 'position',
T
Takahiro 已提交
894 895
		rotation: 'quaternion',
		weights: 'morphTargetInfluences'
D
Don McCurdy 已提交
896 897 898
	};

	var INTERPOLATION = {
899 900
		CATMULLROMSPLINE: THREE.InterpolateSmooth,
		CUBICSPLINE: THREE.InterpolateSmooth,
D
Don McCurdy 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913
		LINEAR: THREE.InterpolateLinear,
		STEP: THREE.InterpolateDiscrete
	};

	var STATES_ENABLES = {
		2884: 'CULL_FACE',
		2929: 'DEPTH_TEST',
		3042: 'BLEND',
		3089: 'SCISSOR_TEST',
		32823: 'POLYGON_OFFSET_FILL',
		32926: 'SAMPLE_ALPHA_TO_COVERAGE'
	};

914 915 916 917 918 919
	var ALPHA_MODES = {
		OPAQUE: 'OPAQUE',
		MASK: 'MASK',
		BLEND: 'BLEND'
	};

D
Don McCurdy 已提交
920 921 922 923
	/* UTILITY FUNCTIONS */

	function _each( object, callback, thisObj ) {

M
Mugen87 已提交
924 925
		if ( ! object ) {

D
Don McCurdy 已提交
926
			return Promise.resolve();
M
Mugen87 已提交
927

D
Don McCurdy 已提交
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
		}

		var results;
		var fns = [];

		if ( Object.prototype.toString.call( object ) === '[object Array]' ) {

			results = [];

			var length = object.length;

			for ( var idx = 0; idx < length; idx ++ ) {

				var value = callback.call( thisObj || this, object[ idx ], idx );

				if ( value ) {

					fns.push( value );

					if ( value instanceof Promise ) {

M
Mugen87 已提交
949
						value.then( function ( key, value ) {
D
Don McCurdy 已提交
950

951
							results[ key ] = value;
D
Don McCurdy 已提交
952

M
Mugen87 已提交
953
						}.bind( this, idx ) );
D
Don McCurdy 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980

					} else {

						results[ idx ] = value;

					}

				}

			}

		} else {

			results = {};

			for ( var key in object ) {

				if ( object.hasOwnProperty( key ) ) {

					var value = callback.call( thisObj || this, object[ key ], key );

					if ( value ) {

						fns.push( value );

						if ( value instanceof Promise ) {

M
Mugen87 已提交
981
							value.then( function ( key, value ) {
D
Don McCurdy 已提交
982 983 984

								results[ key ] = value;

M
Mugen87 已提交
985
							}.bind( this, key ) );
D
Don McCurdy 已提交
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000

						} else {

							results[ key ] = value;

						}

					}

				}

			}

		}

M
Mugen87 已提交
1001
		return Promise.all( fns ).then( function () {
D
Don McCurdy 已提交
1002 1003 1004

			return results;

M
Mugen87 已提交
1005
		} );
D
Don McCurdy 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014

	}

	function resolveURL( url, path ) {

		// Invalid URL
		if ( typeof url !== 'string' || url === '' )
			return '';

0
06wj 已提交
1015 1016
		// Absolute URL http://,https://,//
		if ( /^(https?:)?\/\//i.test( url ) ) {
D
Don McCurdy 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

			return url;

		}

		// Data URI
		if ( /^data:.*,.*$/i.test( url ) ) {

			return url;

		}

1029 1030 1031 1032 1033 1034 1035
		// Blob URL
		if ( /^blob:.*$/i.test( url ) ) {

			return url;

		}

D
Don McCurdy 已提交
1036 1037 1038 1039 1040 1041 1042
		// Relative URL
		return ( path || '' ) + url;

	}

	function convertUint8ArrayToString( array ) {

1043 1044 1045 1046 1047 1048 1049 1050 1051
		if ( window.TextDecoder !== undefined ) {

			return new TextDecoder().decode( array );

		}

		// Avoid the String.fromCharCode.apply(null, array) shortcut, which
		// throws a "maximum call stack size exceeded" error for large arrays.

D
Don McCurdy 已提交
1052 1053
		var s = '';

1054
		for ( var i = 0, il = array.length; i < il; i ++ ) {
D
Don McCurdy 已提交
1055 1056 1057 1058 1059 1060 1061 1062 1063

			s += String.fromCharCode( array[ i ] );

		}

		return s;

	}

1064 1065 1066
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
	 */
D
Don McCurdy 已提交
1067 1068
	function createDefaultMaterial() {

1069 1070 1071 1072 1073
		return new THREE.MeshStandardMaterial( {
			color: 0xFFFFFF,
			emissive: 0x000000,
			metalness: 1,
			roughness: 1,
D
Don McCurdy 已提交
1074 1075 1076 1077 1078 1079 1080
			transparent: false,
			depthTest: true,
			side: THREE.FrontSide
		} );

	}

D
Don McCurdy 已提交
1081 1082 1083 1084 1085 1086 1087
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
	 * @param {THREE.Mesh} mesh
	 * @param {GLTF.Mesh} meshDef
	 * @param {GLTF.Primitive} primitiveDef
	 * @param {Object} dependencies
	 */
M
Mugen87 已提交
1088
	function addMorphTargets( mesh, meshDef, primitiveDef, dependencies ) {
D
Don McCurdy 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

		var geometry = mesh.geometry;
		var material = mesh.material;

		var targets = primitiveDef.targets;
		var morphAttributes = geometry.morphAttributes;

		morphAttributes.position = [];
		morphAttributes.normal = [];

		material.morphTargets = true;

		for ( var i = 0, il = targets.length; i < il; i ++ ) {

			var target = targets[ i ];
			var attributeName = 'morphTarget' + i;

			var positionAttribute, normalAttribute;

			if ( target.POSITION !== undefined ) {

				// Three.js morph formula is
				//   position
				//     + weight0 * ( morphTarget0 - position )
				//     + weight1 * ( morphTarget1 - position )
				//     ...
				// while the glTF one is
				//   position
				//     + weight0 * morphTarget0
				//     + weight1 * morphTarget1
				//     ...
				// then adding position to morphTarget.
				// So morphTarget value will depend on mesh's position, then cloning attribute
				// for the case if attribute is shared among two or more meshes.

				positionAttribute = dependencies.accessors[ target.POSITION ].clone();
				var position = geometry.attributes.position;

				for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {

					positionAttribute.setXYZ(
						j,
						positionAttribute.getX( j ) + position.getX( j ),
						positionAttribute.getY( j ) + position.getY( j ),
						positionAttribute.getZ( j ) + position.getZ( j )
					);

				}

			} else {

				// Copying the original position not to affect the final position.
				// See the formula above.
				positionAttribute = geometry.attributes.position.clone();

			}

			if ( target.NORMAL !== undefined ) {

				material.morphNormals = true;

				// see target.POSITION's comment

				normalAttribute = dependencies.accessors[ target.NORMAL ].clone();
				var normal = geometry.attributes.normal;

				for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {

					normalAttribute.setXYZ(
						j,
						normalAttribute.getX( j ) + normal.getX( j ),
						normalAttribute.getY( j ) + normal.getY( j ),
						normalAttribute.getZ( j ) + normal.getZ( j )
					);

				}

			} else {

				normalAttribute = geometry.attributes.normal.clone();

			}

			if ( target.TANGENT !== undefined ) {

				// TODO: implement

			}

			positionAttribute.name = attributeName;
			normalAttribute.name = attributeName;

			morphAttributes.position.push( positionAttribute );
			morphAttributes.normal.push( normalAttribute );

		}

		mesh.updateMorphTargets();

		if ( meshDef.weights !== undefined ) {

			for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {

				mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];

			}

		}

	}

D
Don McCurdy 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	/* GLTF PARSER */

	function GLTFParser( json, extensions, options ) {

		this.json = json || {};
		this.extensions = extensions || {};
		this.options = options || {};

		// loader object cache
		this.cache = new GLTFRegistry();

	}

	GLTFParser.prototype._withDependencies = function ( dependencies ) {

		var _dependencies = {};

		for ( var i = 0; i < dependencies.length; i ++ ) {

			var dependency = dependencies[ i ];
M
Mugen87 已提交
1220
			var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
D
Don McCurdy 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246

			var cached = this.cache.get( dependency );

			if ( cached !== undefined ) {

				_dependencies[ dependency ] = cached;

			} else if ( this[ fnName ] ) {

				var fn = this[ fnName ]();
				this.cache.add( dependency, fn );

				_dependencies[ dependency ] = fn;

			}

		}

		return _each( _dependencies, function ( dependency ) {

			return dependency;

		} );

	};

1247
	GLTFParser.prototype.parse = function ( onLoad, onError ) {
D
Don McCurdy 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256

		var json = this.json;

		// Clear the loader cache
		this.cache.removeAll();

		// Fire the callback on complete
		this._withDependencies( [

M
Mugen87 已提交
1257 1258 1259
			'scenes',
			'cameras',
			'animations'
D
Don McCurdy 已提交
1260 1261 1262 1263 1264

		] ).then( function ( dependencies ) {

			var scenes = [];

1265
			for ( var i = 0; i < dependencies.scenes.length; i ++ ) {
D
Don McCurdy 已提交
1266

1267
				scenes.push( dependencies.scenes[ i ] );
D
Don McCurdy 已提交
1268 1269 1270

			}

1271 1272
			var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];

D
Don McCurdy 已提交
1273 1274
			var cameras = [];

1275 1276 1277
			dependencies.cameras = dependencies.cameras || [];

			for ( var i = 0; i < dependencies.cameras.length; i ++ ) {
D
Don McCurdy 已提交
1278

1279
				var camera = dependencies.cameras[ i ];
D
Don McCurdy 已提交
1280 1281 1282 1283 1284 1285
				cameras.push( camera );

			}

			var animations = [];

1286
			dependencies.animations = dependencies.animations || [];
D
Don McCurdy 已提交
1287

1288 1289 1290
			for ( var i = 0; i < dependencies.animations.length; i ++ ) {

				animations.push( dependencies.animations[ i ] );
D
Don McCurdy 已提交
1291 1292 1293

			}

1294
			onLoad( scene, scenes, cameras, animations );
D
Don McCurdy 已提交
1295

1296
		} ).catch( onError );
D
Don McCurdy 已提交
1297 1298 1299

	};

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
	/**
	 * Requests the specified dependency asynchronously, with caching.
	 * @param {string} type
	 * @param {number} index
	 * @return {Promise<Object>}
	 */
	GLTFParser.prototype.getDependency = function ( type, index ) {

		var cacheKey = type + ':' + index;
		var dependency = this.cache.get( cacheKey );

M
Mugen87 已提交
1311
		if ( ! dependency ) {
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322

			var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
			dependency = this[ fnName ]( index );
			this.cache.add( cacheKey, dependency );

		}

		return dependency;

	};

1323 1324 1325 1326 1327 1328
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
	 * @param {number} bufferIndex
	 * @return {Promise<ArrayBuffer>}
	 */
	GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
D
Don McCurdy 已提交
1329

1330
		var bufferDef = this.json.buffers[ bufferIndex ];
D
Don McCurdy 已提交
1331

1332
		if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
D
Don McCurdy 已提交
1333

1334
			throw new Error( 'THREE.GLTFLoader: %s buffer type is not supported.', bufferDef.type );
D
Don McCurdy 已提交
1335

1336
		}
D
Don McCurdy 已提交
1337

1338 1339
		// If present, GLB container is required to be the first buffer.
		if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
D
Don McCurdy 已提交
1340

1341
			return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
D
Don McCurdy 已提交
1342

1343
		}
D
Don McCurdy 已提交
1344

1345
		var options = this.options;
D
Don McCurdy 已提交
1346

1347
		return new Promise( function ( resolve ) {
D
Don McCurdy 已提交
1348

1349 1350
			var loader = new THREE.FileLoader();
			loader.setResponseType( 'arraybuffer' );
M
Mugen87 已提交
1351
			loader.load( resolveURL( bufferDef.uri, options.path ), resolve );
D
Don McCurdy 已提交
1352 1353 1354 1355 1356

		} );

	};

1357 1358 1359 1360 1361 1362 1363
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
	 * @param {number} bufferViewIndex
	 * @return {Promise<ArrayBuffer>}
	 */
	GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {

1364
		var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
1365

1366
		return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
1367

1368 1369 1370
			var byteLength = bufferViewDef.byteLength || 0;
			var byteOffset = bufferViewDef.byteOffset || 0;
			return buffer.slice( byteOffset, byteOffset + byteLength );
D
Don McCurdy 已提交
1371 1372 1373 1374 1375 1376 1377

		} );

	};

	GLTFParser.prototype.loadAccessors = function () {

1378
		var parser = this;
D
Don McCurdy 已提交
1379 1380
		var json = this.json;

1381
		return _each( json.accessors, function ( accessor ) {
D
Don McCurdy 已提交
1382

1383
			return parser.getDependency( 'bufferView', accessor.bufferView ).then( function ( bufferView ) {
D
Don McCurdy 已提交
1384 1385 1386 1387 1388 1389 1390

				var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
				var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];

				// For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
				var elementBytes = TypedArray.BYTES_PER_ELEMENT;
				var itemBytes = elementBytes * itemSize;
D
Don McCurdy 已提交
1391
				var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
1392 1393
				var array;

D
Don McCurdy 已提交
1394
				// The buffer is not interleaved if the stride is the item size in bytes.
1395
				if ( byteStride && byteStride !== itemBytes ) {
D
Don McCurdy 已提交
1396 1397

					// Use the full buffer if it's interleaved.
1398
					array = new TypedArray( bufferView );
D
Don McCurdy 已提交
1399 1400

					// Integer parameters to IB/IBA are in array elements, not bytes.
1401
					var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
D
Don McCurdy 已提交
1402 1403 1404 1405 1406

					return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );

				} else {

1407
					array = new TypedArray( bufferView, accessor.byteOffset, accessor.count * itemSize );
D
Don McCurdy 已提交
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418

					return new THREE.BufferAttribute( array, itemSize );

				}

			} );

		} );

	};

1419 1420 1421 1422 1423 1424 1425 1426
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
	 * @param {number} textureIndex
	 * @return {Promise<THREE.Texture>}
	 */
	GLTFParser.prototype.loadTexture = function ( textureIndex ) {

		var parser = this;
D
Don McCurdy 已提交
1427 1428 1429
		var json = this.json;
		var options = this.options;

1430
		var URL = window.URL || window.webkitURL;
D
Don McCurdy 已提交
1431

1432
		var textureDef = json.textures[ textureIndex ];
1433 1434 1435
		var source = json.images[ textureDef.source ];
		var sourceURI = source.uri;
		var isObjectURL = false;
D
Don McCurdy 已提交
1436

1437
		if ( source.bufferView !== undefined ) {
D
Don McCurdy 已提交
1438

1439
			// Load binary image data from bufferView, if provided.
D
Don McCurdy 已提交
1440

1441
			sourceURI = parser.getDependency( 'bufferView', source.bufferView )
1442
				.then( function ( bufferView ) {
D
Don McCurdy 已提交
1443

1444 1445 1446 1447
					isObjectURL = true;
					var blob = new Blob( [ bufferView ], { type: source.mimeType } );
					sourceURI = URL.createObjectURL( blob );
					return sourceURI;
D
Don McCurdy 已提交
1448

1449
				} );
D
Don McCurdy 已提交
1450

1451
		}
D
Don McCurdy 已提交
1452

1453
		return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
D
Don McCurdy 已提交
1454

1455
			// Load Texture resource.
D
Don McCurdy 已提交
1456

1457 1458
			var textureLoader = THREE.Loader.Handlers.get( sourceURI ) || new THREE.TextureLoader();
			textureLoader.setCrossOrigin( options.crossOrigin );
D
Don McCurdy 已提交
1459

1460
			return new Promise( function ( resolve, reject ) {
D
Don McCurdy 已提交
1461

1462
				textureLoader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
D
Don McCurdy 已提交
1463

1464
			} );
D
Don McCurdy 已提交
1465

1466
		} ).then( function ( texture ) {
D
Don McCurdy 已提交
1467

1468
			// Clean up resources and configure Texture.
D
Don McCurdy 已提交
1469

1470
			if ( isObjectURL === true ) {
D
Don McCurdy 已提交
1471

1472
				URL.revokeObjectURL( sourceURI );
D
Don McCurdy 已提交
1473

1474
			}
D
Don McCurdy 已提交
1475

1476
			texture.flipY = false;
D
Don McCurdy 已提交
1477

1478
			if ( textureDef.name !== undefined ) texture.name = textureDef.name;
D
Don McCurdy 已提交
1479

1480
			texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
D
Don McCurdy 已提交
1481

1482
			if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
D
Don McCurdy 已提交
1483

1484
				console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
1485
											'internalFormat will be forced to be the same value as format.' );
D
Don McCurdy 已提交
1486

1487
			}
D
Don McCurdy 已提交
1488

1489
			texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
D
Don McCurdy 已提交
1490

1491 1492
			var samplers = json.samplers || {};
			var sampler = samplers[ textureDef.sampler ] || {};
D
Don McCurdy 已提交
1493

1494 1495 1496 1497
			texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
			texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
			texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
			texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
D
Don McCurdy 已提交
1498

1499
			return texture;
D
Don McCurdy 已提交
1500

1501
		} );
D
Don McCurdy 已提交
1502

1503
	};
D
Don McCurdy 已提交
1504

1505 1506 1507 1508 1509 1510 1511 1512
	/**
	 * Asynchronously assigns a texture to the given material parameters.
	 * @param {Object} materialParams
	 * @param {string} textureName
	 * @param {number} textureIndex
	 * @return {Promise}
	 */
	GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
D
Don McCurdy 已提交
1513

1514 1515 1516
		return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {

			materialParams[ textureName ] = texture;
D
Don McCurdy 已提交
1517 1518 1519 1520 1521

		} );

	};

1522 1523 1524 1525
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
	 * @return {Promise<Array<THREE.Material>>}
	 */
D
Don McCurdy 已提交
1526 1527
	GLTFParser.prototype.loadMaterials = function () {

1528
		var parser = this;
D
Don McCurdy 已提交
1529
		var json = this.json;
1530
		var extensions = this.extensions;
D
Don McCurdy 已提交
1531

1532
		return _each( json.materials, function ( material ) {
D
Don McCurdy 已提交
1533

1534 1535 1536
			var materialType;
			var materialParams = {};
			var materialExtensions = material.extensions || {};
D
Don McCurdy 已提交
1537

1538
			var pending = [];
1539

1540
			if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
1541

1542 1543 1544
				var khcExtension = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
				materialType = khcExtension.getMaterialType( material );
				pending.push( khcExtension.extendParams( materialParams, material, parser ) );
1545

1546
			} else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
1547

1548 1549 1550
				var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
				materialType = sgExtension.getMaterialType( material );
				pending.push( sgExtension.extendParams( materialParams, material, parser ) );
1551

1552
			} else if ( material.pbrMetallicRoughness !== undefined ) {
1553

1554 1555
				// Specification:
				// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
1556

1557
				materialType = THREE.MeshStandardMaterial;
1558

1559
				var metallicRoughness = material.pbrMetallicRoughness;
1560

1561 1562
				materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
				materialParams.opacity = 1.0;
1563

1564
				if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
1565

1566
					var array = metallicRoughness.baseColorFactor;
1567

1568 1569
					materialParams.color.fromArray( array );
					materialParams.opacity = array[ 3 ];
1570

1571
				}
1572

1573
				if ( metallicRoughness.baseColorTexture !== undefined ) {
1574

1575
					pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
1576

1577
				}
1578

1579 1580
				materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
				materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
1581

1582
				if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
1583

1584 1585 1586
					var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
					pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
					pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
1587

1588
				}
D
Don McCurdy 已提交
1589

1590
			} else {
D
Don McCurdy 已提交
1591

1592
				materialType = THREE.MeshPhongMaterial;
D
Don McCurdy 已提交
1593

1594
			}
D
Don McCurdy 已提交
1595

1596
			if ( material.doubleSided === true ) {
D
Don McCurdy 已提交
1597

1598
				materialParams.side = THREE.DoubleSide;
D
Don McCurdy 已提交
1599

1600
			}
1601

1602
			var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;
D
Don McCurdy 已提交
1603

1604
			if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
D
Don McCurdy 已提交
1605

1606
				materialParams.transparent = true;
D
Don McCurdy 已提交
1607

1608 1609 1610 1611 1612
				if ( alphaMode === ALPHA_MODES.MASK ) {

				  materialParams.alphaTest = material.alphaCutoff || 0.5;

				}
1613

1614
			} else {
D
Don McCurdy 已提交
1615

1616
				materialParams.transparent = false;
D
Don McCurdy 已提交
1617

1618
			}
D
Don McCurdy 已提交
1619

1620
			if ( material.normalTexture !== undefined ) {
D
Don McCurdy 已提交
1621

1622
				pending.push( parser.assignTexture( materialParams, 'normalMap', material.normalTexture.index ) );
D
Don McCurdy 已提交
1623

1624 1625
				materialParams.normalScale = new THREE.Vector2( 1, 1 );

1626
				if ( material.normalTexture.scale !== undefined ) {
1627

1628
					materialParams.normalScale.set( material.normalTexture.scale, material.normalTexture.scale );
1629 1630

				}
M
Mugen87 已提交
1631

1632
			}
D
Don McCurdy 已提交
1633

1634
			if ( material.occlusionTexture !== undefined ) {
D
Don McCurdy 已提交
1635

1636
				pending.push( parser.assignTexture( materialParams, 'aoMap', material.occlusionTexture.index ) );
D
Don McCurdy 已提交
1637

D
Don McCurdy 已提交
1638 1639 1640 1641 1642 1643
				if ( material.occlusionTexture.strength !== undefined ) {

					materialParams.aoMapIntensity = material.occlusionTexture.strength;

				}

1644
			}
D
Don McCurdy 已提交
1645

1646
			if ( material.emissiveFactor !== undefined ) {
D
Don McCurdy 已提交
1647

1648
				if ( materialType === THREE.MeshBasicMaterial ) {
D
Don McCurdy 已提交
1649

1650
					materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
D
Don McCurdy 已提交
1651

1652
				} else {
D
Don McCurdy 已提交
1653

1654
					materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
D
Don McCurdy 已提交
1655

1656 1657
				}

1658
			}
D
Don McCurdy 已提交
1659

1660
			if ( material.emissiveTexture !== undefined ) {
D
Don McCurdy 已提交
1661

1662
				if ( materialType === THREE.MeshBasicMaterial ) {
D
Don McCurdy 已提交
1663

1664
					pending.push( parser.assignTexture( materialParams, 'map', material.emissiveTexture.index ) );
D
Don McCurdy 已提交
1665

1666
				} else {
D
Don McCurdy 已提交
1667

1668
					pending.push( parser.assignTexture( materialParams, 'emissiveMap', material.emissiveTexture.index ) );
D
Don McCurdy 已提交
1669 1670 1671

				}

1672 1673 1674 1675
			}

			return Promise.all( pending ).then( function () {

1676 1677 1678 1679
				var _material;

				if ( materialType === THREE.ShaderMaterial ) {

1680
					_material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
1681 1682 1683 1684 1685 1686 1687

				} else {

					_material = new materialType( materialParams );

				}

D
Don McCurdy 已提交
1688 1689
				if ( material.name !== undefined ) _material.name = material.name;

1690 1691
				// Normal map textures use OpenGL conventions:
				// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
1692 1693 1694 1695 1696
				if ( _material.normalScale ) {

					_material.normalScale.x = - _material.normalScale.x;

				}
1697

1698 1699 1700 1701
				// emissiveTexture and baseColorTexture use sRGB encoding.
				if ( _material.map ) _material.map.encoding = THREE.sRGBEncoding;
				if ( _material.emissiveMap ) _material.emissiveMap.encoding = THREE.sRGBEncoding;

1702
				if ( material.extras ) _material.userData = material.extras;
1703

D
Don McCurdy 已提交
1704 1705 1706 1707 1708 1709 1710 1711
				return _material;

			} );

		} );

	};

D
Don McCurdy 已提交
1712
	GLTFParser.prototype.loadGeometries = function ( primitives ) {
D
Don McCurdy 已提交
1713 1714 1715

		return this._withDependencies( [

M
Mugen87 已提交
1716
			'accessors',
D
Don McCurdy 已提交
1717 1718 1719

		] ).then( function ( dependencies ) {

D
Don McCurdy 已提交
1720
			return _each( primitives, function ( primitive ) {
D
Don McCurdy 已提交
1721

D
Don McCurdy 已提交
1722
				var geometry = new THREE.BufferGeometry();
D
Don McCurdy 已提交
1723

D
Don McCurdy 已提交
1724
				var attributes = primitive.attributes;
D
Don McCurdy 已提交
1725

D
Don McCurdy 已提交
1726
				for ( var attributeId in attributes ) {
D
Don McCurdy 已提交
1727

D
Don McCurdy 已提交
1728
					var attributeEntry = attributes[ attributeId ];
D
Don McCurdy 已提交
1729

D
Don McCurdy 已提交
1730
					if ( attributeEntry === undefined ) return;
D
Don McCurdy 已提交
1731

D
Don McCurdy 已提交
1732
					var bufferAttribute = dependencies.accessors[ attributeEntry ];
D
Don McCurdy 已提交
1733

D
Don McCurdy 已提交
1734
					switch ( attributeId ) {
1735

D
Don McCurdy 已提交
1736
						case 'POSITION':
D
Don McCurdy 已提交
1737

D
Don McCurdy 已提交
1738 1739
							geometry.addAttribute( 'position', bufferAttribute );
							break;
D
Don McCurdy 已提交
1740

D
Don McCurdy 已提交
1741
						case 'NORMAL':
D
Don McCurdy 已提交
1742

D
Don McCurdy 已提交
1743 1744
							geometry.addAttribute( 'normal', bufferAttribute );
							break;
D
Don McCurdy 已提交
1745

D
Don McCurdy 已提交
1746 1747 1748
						case 'TEXCOORD_0':
						case 'TEXCOORD0':
						case 'TEXCOORD':
D
Don McCurdy 已提交
1749

D
Don McCurdy 已提交
1750 1751
							geometry.addAttribute( 'uv', bufferAttribute );
							break;
D
Don McCurdy 已提交
1752

D
Don McCurdy 已提交
1753
						case 'TEXCOORD_1':
D
Don McCurdy 已提交
1754

D
Don McCurdy 已提交
1755 1756
							geometry.addAttribute( 'uv2', bufferAttribute );
							break;
D
Don McCurdy 已提交
1757

D
Don McCurdy 已提交
1758 1759 1760
						case 'COLOR_0':
						case 'COLOR0':
						case 'COLOR':
D
Don McCurdy 已提交
1761

D
Don McCurdy 已提交
1762 1763
							geometry.addAttribute( 'color', bufferAttribute );
							break;
1764

D
Don McCurdy 已提交
1765 1766
						case 'WEIGHTS_0':
						case 'WEIGHT': // WEIGHT semantic deprecated.
D
Don McCurdy 已提交
1767

D
Don McCurdy 已提交
1768 1769
							geometry.addAttribute( 'skinWeight', bufferAttribute );
							break;
1770

D
Don McCurdy 已提交
1771 1772
						case 'JOINTS_0':
						case 'JOINT': // JOINT semantic deprecated.
D
Don McCurdy 已提交
1773

D
Don McCurdy 已提交
1774 1775
							geometry.addAttribute( 'skinIndex', bufferAttribute );
							break;
1776

D
Don McCurdy 已提交
1777
					}
D
Don McCurdy 已提交
1778

D
Don McCurdy 已提交
1779
				}
1780

D
Don McCurdy 已提交
1781
				if ( primitive.indices !== undefined ) {
S
Steven Vergenz 已提交
1782

D
Don McCurdy 已提交
1783
					geometry.setIndex( dependencies.accessors[ primitive.indices ] );
1784

D
Don McCurdy 已提交
1785
				}
D
Don McCurdy 已提交
1786

D
Don McCurdy 已提交
1787
				return geometry;
1788

D
Don McCurdy 已提交
1789
			} );
D
Don McCurdy 已提交
1790

D
Don McCurdy 已提交
1791
		} );
1792

D
Don McCurdy 已提交
1793
	};
D
Don McCurdy 已提交
1794

D
Don McCurdy 已提交
1795 1796 1797 1798
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
	 */
	GLTFParser.prototype.loadMeshes = function () {
D
Don McCurdy 已提交
1799

D
Don McCurdy 已提交
1800 1801
		var scope = this;
		var json = this.json;
D
Don McCurdy 已提交
1802

D
Don McCurdy 已提交
1803
		return this._withDependencies( [
D
Don McCurdy 已提交
1804

D
Daniel Hritzkiv 已提交
1805
			'accessors',
D
Don McCurdy 已提交
1806
			'materials'
D
Don McCurdy 已提交
1807

D
Don McCurdy 已提交
1808 1809
		] ).then( function ( dependencies ) {

1810
			return _each( json.meshes, function ( meshDef, meshIndex ) {
D
Don McCurdy 已提交
1811 1812 1813 1814 1815 1816 1817

				var group = new THREE.Group();

				var primitives = meshDef.primitives || [];

				return scope.loadGeometries( primitives ).then( function ( geometries ) {

1818
					for ( var i = 0; i < primitives.length; i ++ ) {
D
Don McCurdy 已提交
1819

1820 1821
						var primitive = primitives[ i ];
						var geometry = geometries[ i ];
D
Don McCurdy 已提交
1822 1823 1824 1825

						var material = primitive.material === undefined
							? createDefaultMaterial()
							: dependencies.materials[ primitive.material ];
D
Don McCurdy 已提交
1826

1827
						if ( material.aoMap
1828 1829 1830
								&& geometry.attributes.uv2 === undefined
								&& geometry.attributes.uv !== undefined ) {

1831
							console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
1832 1833 1834 1835
							geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );

						}

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
						var useVertexColors = geometry.attributes.color !== undefined;
						var useFlatShading = geometry.attributes.normal === undefined;

						if ( useVertexColors || useFlatShading ) {

							material = material.clone();

						}

						if ( useVertexColors ) {
D
Don McCurdy 已提交
1846 1847 1848 1849 1850 1851

							material.vertexColors = THREE.VertexColors;
							material.needsUpdate = true;

						}

1852
						if ( useFlatShading ) {
1853

1854
							material.flatShading = true;
1855 1856 1857

						}

D
Don McCurdy 已提交
1858
						var mesh;
T
Takahiro 已提交
1859

D
Don McCurdy 已提交
1860
						if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
T
Takahiro 已提交
1861

D
Don McCurdy 已提交
1862
							mesh = new THREE.Mesh( geometry, material );
T
Takahiro 已提交
1863

1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
						} else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {

							mesh = new THREE.Mesh( geometry, material );
							mesh.drawMode = THREE.TriangleStripDrawMode;

						} else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {

							mesh = new THREE.Mesh( geometry, material );
							mesh.drawMode = THREE.TriangleFanDrawMode;

D
Don McCurdy 已提交
1874
						} else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
T
Takahiro 已提交
1875

D
Don McCurdy 已提交
1876
							mesh = new THREE.LineSegments( geometry, material );
1877

1878 1879 1880 1881 1882 1883 1884 1885
						} else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {

							mesh = new THREE.Line( geometry, material );

						} else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {

							mesh = new THREE.LineLoop( geometry, material );

1886 1887 1888 1889
						} else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {

							mesh = new THREE.Points( geometry, material );

D
Don McCurdy 已提交
1890
						} else {
T
Takahiro 已提交
1891

1892
							throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ', primitive.mode );
T
Takahiro 已提交
1893 1894 1895

						}

1896 1897
						mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
						mesh.name += i > 0 ? ( '_' + i ) : '';
D
Don McCurdy 已提交
1898

D
Don McCurdy 已提交
1899
						if ( primitive.targets !== undefined ) {
D
Don McCurdy 已提交
1900

D
Don McCurdy 已提交
1901
							addMorphTargets( mesh, meshDef, primitive, dependencies );
D
Don McCurdy 已提交
1902 1903 1904

						}

D
Don McCurdy 已提交
1905
						if ( primitive.extras ) mesh.userData = primitive.extras;
D
Don McCurdy 已提交
1906

D
Don McCurdy 已提交
1907
						group.add( mesh );
D
Don McCurdy 已提交
1908 1909 1910

					}

D
Don McCurdy 已提交
1911
					return group;
D
Don McCurdy 已提交
1912

D
Don McCurdy 已提交
1913
				} );
D
Don McCurdy 已提交
1914 1915 1916 1917 1918 1919 1920

			} );

		} );

	};

1921 1922 1923
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
	 */
D
Don McCurdy 已提交
1924 1925 1926 1927 1928 1929
	GLTFParser.prototype.loadCameras = function () {

		var json = this.json;

		return _each( json.cameras, function ( camera ) {

1930
			var _camera;
D
Don McCurdy 已提交
1931

1932
			var params = camera[ camera.type ];
D
Don McCurdy 已提交
1933

M
Mugen87 已提交
1934
			if ( ! params ) {
D
Don McCurdy 已提交
1935

1936
				console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
1937
				return;
D
Don McCurdy 已提交
1938

1939
			}
D
Don McCurdy 已提交
1940

1941
			if ( camera.type === 'perspective' ) {
D
Don McCurdy 已提交
1942

1943 1944
				var aspectRatio = params.aspectRatio || 1;
				var xfov = params.yfov * aspectRatio;
D
Don McCurdy 已提交
1945

1946
				_camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
D
Don McCurdy 已提交
1947

1948
			} else if ( camera.type === 'orthographic' ) {
D
Don McCurdy 已提交
1949

M
Mugen87 已提交
1950
				_camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
D
Don McCurdy 已提交
1951 1952 1953

			}

1954 1955 1956 1957 1958
			if ( camera.name !== undefined ) _camera.name = camera.name;
			if ( camera.extras ) _camera.userData = camera.extras;

			return _camera;

D
Don McCurdy 已提交
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
		} );

	};

	GLTFParser.prototype.loadSkins = function () {

		var json = this.json;

		return this._withDependencies( [

M
Mugen87 已提交
1969
			'accessors'
D
Don McCurdy 已提交
1970 1971 1972 1973 1974 1975

		] ).then( function ( dependencies ) {

			return _each( json.skins, function ( skin ) {

				var _skin = {
D
Don McCurdy 已提交
1976
					joints: skin.joints,
D
Don McCurdy 已提交
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
					inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
				};

				return _skin;

			} );

		} );

	};

	GLTFParser.prototype.loadAnimations = function () {

		var json = this.json;

		return this._withDependencies( [

M
Mugen87 已提交
1994 1995
			'accessors',
			'nodes'
D
Don McCurdy 已提交
1996 1997 1998 1999 2000 2001 2002

		] ).then( function ( dependencies ) {

			return _each( json.animations, function ( animation, animationId ) {

				var tracks = [];

2003
				for ( var i = 0; i < animation.channels.length; i ++ ) {
D
Don McCurdy 已提交
2004

2005
					var channel = animation.channels[ i ];
D
Don McCurdy 已提交
2006 2007 2008 2009 2010
					var sampler = animation.samplers[ channel.sampler ];

					if ( sampler ) {

						var target = channel.target;
2011
						var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
D
Don McCurdy 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
						var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
						var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;

						var inputAccessor = dependencies.accessors[ input ];
						var outputAccessor = dependencies.accessors[ output ];

						var node = dependencies.nodes[ name ];

						if ( node ) {

							node.updateMatrix();
							node.matrixAutoUpdate = true;

T
Takahiro 已提交
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
							var TypedKeyframeTrack;

							switch ( PATH_PROPERTIES[ target.path ] ) {

								case PATH_PROPERTIES.weights:

									TypedKeyframeTrack = THREE.NumberKeyframeTrack;
									break;

								case PATH_PROPERTIES.rotation:

									TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
									break;

								case PATH_PROPERTIES.position:
								case PATH_PROPERTIES.scale:
								default:

									TypedKeyframeTrack = THREE.VectorKeyframeTrack;
									break;

							}
D
Don McCurdy 已提交
2047 2048

							var targetName = node.name ? node.name : node.uuid;
2049 2050 2051

							if ( sampler.interpolation === 'CATMULLROMSPLINE' ) {

2052
								console.warn( 'THREE.GLTFLoader: CATMULLROMSPLINE interpolation is not supported. Using CUBICSPLINE instead.' );
2053 2054 2055

							}

D
Don McCurdy 已提交
2056 2057
							var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;

T
Takahiro 已提交
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
							var targetNames = [];

							if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {

								// node should be THREE.Group here but
								// PATH_PROPERTIES.weights(morphTargetInfluences) should be
								// the property of a mesh object under node.
								// So finding targets here.

								node.traverse( function ( object ) {

									if ( object.isMesh === true && object.material.morphTargets === true ) {

										targetNames.push( object.name ? object.name : object.uuid );

									}

								} );

							} else {

								targetNames.push( targetName );

							}

D
Don McCurdy 已提交
2083 2084 2085
							// KeyframeTrack.optimize() will modify given 'times' and 'values'
							// buffers before creating a truncated copy to keep. Because buffers may
							// be reused by other tracks, make copies here.
2086
							for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
T
Takahiro 已提交
2087 2088

								tracks.push( new TypedKeyframeTrack(
2089
									targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
T
Takahiro 已提交
2090 2091 2092 2093 2094 2095
									THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
									THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
									interpolation
								) );

							}
D
Don McCurdy 已提交
2096 2097 2098 2099 2100 2101 2102

						}

					}

				}

M
Mugen87 已提交
2103
				var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
D
Don McCurdy 已提交
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118

				return new THREE.AnimationClip( name, undefined, tracks );

			} );

		} );

	};

	GLTFParser.prototype.loadNodes = function () {

		var json = this.json;
		var extensions = this.extensions;
		var scope = this;

D
Don McCurdy 已提交
2119
		var nodes = json.nodes || [];
2120
		var skins = json.skins || [];
D
Don McCurdy 已提交
2121

D
Don McCurdy 已提交
2122
		// Nothing in the node definition indicates whether it is a Bone or an
2123 2124
		// Object3D. Use the skins' joint references to mark bones.
		skins.forEach( function ( skin ) {
D
Don McCurdy 已提交
2125

2126
			skin.joints.forEach( function ( id ) {
D
Don McCurdy 已提交
2127

2128
				nodes[ id ].isBone = true;
D
Don McCurdy 已提交
2129

2130
			} );
D
Don McCurdy 已提交
2131

D
Don McCurdy 已提交
2132 2133
		} );

2134
		return scope._withDependencies( [
D
Don McCurdy 已提交
2135

2136 2137 2138
			'meshes',
			'skins',
			'cameras'
D
Don McCurdy 已提交
2139

2140
		] ).then( function ( dependencies ) {
D
Don McCurdy 已提交
2141

2142
			return _each( json.nodes, function ( nodeDef ) {
D
Don McCurdy 已提交
2143

2144
				if ( nodeDef.isBone === true ) {
D
Don McCurdy 已提交
2145

2146
					return new THREE.Bone();
D
Don McCurdy 已提交
2147

2148
				} else if ( nodeDef.mesh !== undefined ) {
D
Don McCurdy 已提交
2149

2150
					return dependencies.meshes[ nodeDef.mesh ].clone();
D
Don McCurdy 已提交
2151

2152
				} else if ( nodeDef.camera !== undefined ) {
D
Don McCurdy 已提交
2153

2154
					return dependencies.cameras[ nodeDef.camera ];
D
Don McCurdy 已提交
2155

2156 2157 2158
				} else if ( nodeDef.extensions
								 && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
								 && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
D
Don McCurdy 已提交
2159

2160 2161
					var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
					return lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
D
Don McCurdy 已提交
2162

2163
				} else {
D
Don McCurdy 已提交
2164

2165
					return new THREE.Object3D();
D
Don McCurdy 已提交
2166 2167 2168

				}

2169
			} ).then( function ( __nodes ) {
2170

2171
				return _each( __nodes, function ( node, nodeIndex ) {
D
Don McCurdy 已提交
2172

2173
					var nodeDef = json.nodes[ nodeIndex ];
D
Don McCurdy 已提交
2174

2175
					if ( nodeDef.name !== undefined ) {
D
Don McCurdy 已提交
2176

2177
						node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
D
Don McCurdy 已提交
2178

2179
					}
D
Don McCurdy 已提交
2180

2181
					if ( nodeDef.extras ) node.userData = nodeDef.extras;
D
Don McCurdy 已提交
2182

2183
					if ( nodeDef.matrix !== undefined ) {
D
Don McCurdy 已提交
2184

2185 2186 2187
						var matrix = new THREE.Matrix4();
						matrix.fromArray( nodeDef.matrix );
						node.applyMatrix( matrix );
D
Don McCurdy 已提交
2188

2189
					} else {
D
Don McCurdy 已提交
2190

2191
						if ( nodeDef.translation !== undefined ) {
D
Don McCurdy 已提交
2192

2193
							node.position.fromArray( nodeDef.translation );
D
Don McCurdy 已提交
2194

2195
						}
2196

2197
						if ( nodeDef.rotation !== undefined ) {
D
Don McCurdy 已提交
2198

2199
							node.quaternion.fromArray( nodeDef.rotation );
D
Don McCurdy 已提交
2200

2201
						}
D
Don McCurdy 已提交
2202

2203
						if ( nodeDef.scale !== undefined ) {
D
Don McCurdy 已提交
2204

2205
							node.scale.fromArray( nodeDef.scale );
D
Don McCurdy 已提交
2206

2207
						}
D
Don McCurdy 已提交
2208

2209
					}
D
Don McCurdy 已提交
2210

2211
					if ( nodeDef.skin !== undefined ) {
D
Don McCurdy 已提交
2212

2213
						var skinnedMeshes = [];
D
Don McCurdy 已提交
2214

2215
						for ( var i = 0; i < node.children.length; i ++ ) {
D
Don McCurdy 已提交
2216

2217
							var skinEntry = dependencies.skins[ nodeDef.skin ];
D
Don McCurdy 已提交
2218

2219 2220 2221 2222
							// Replace Mesh with SkinnedMesh.
							var geometry = node.children[ i ].geometry;
							var material = node.children[ i ].material;
							material.skinning = true;
D
Don McCurdy 已提交
2223

2224 2225 2226 2227
							var child = new THREE.SkinnedMesh( geometry, material );
							child.morphTargetInfluences = node.children[ i ].morphTargetInfluences;
							child.userData = node.children[ i ].userData;
							child.name = node.children[ i ].name;
D
Don McCurdy 已提交
2228

2229 2230
							var bones = [];
							var boneInverses = [];
D
Don McCurdy 已提交
2231

2232
							for ( var j = 0, l = skinEntry.joints.length; j < l; j ++ ) {
D
Don McCurdy 已提交
2233

2234 2235
								var jointId = skinEntry.joints[ j ];
								var jointNode = __nodes[ jointId ];
D
Don McCurdy 已提交
2236

2237
								if ( jointNode ) {
D
Don McCurdy 已提交
2238

2239
									bones.push( jointNode );
D
Don McCurdy 已提交
2240

2241 2242 2243
									var m = skinEntry.inverseBindMatrices.array;
									var mat = new THREE.Matrix4().fromArray( m, j * 16 );
									boneInverses.push( mat );
D
Don McCurdy 已提交
2244

2245
								} else {
D
Don McCurdy 已提交
2246

2247
									console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
D
Don McCurdy 已提交
2248 2249 2250 2251

								}

							}
T
Takahiro 已提交
2252

2253
							child.bind( new THREE.Skeleton( bones, boneInverses ), child.matrixWorld );
T
Takahiro 已提交
2254

2255
							skinnedMeshes.push( child );
2256

2257
						}
D
Don McCurdy 已提交
2258

2259 2260
						node.remove.apply( node, node.children );
						node.add.apply( node, skinnedMeshes );
D
Don McCurdy 已提交
2261 2262 2263

					}

2264
					return node;
D
Don McCurdy 已提交
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276

				} );

			} );

		} );

	};

	GLTFParser.prototype.loadScenes = function () {

		var json = this.json;
2277
		var extensions = this.extensions;
D
Don McCurdy 已提交
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304

		// scene node hierachy builder

		function buildNodeHierachy( nodeId, parentObject, allNodes ) {

			var _node = allNodes[ nodeId ];
			parentObject.add( _node );

			var node = json.nodes[ nodeId ];

			if ( node.children ) {

				var children = node.children;

				for ( var i = 0, l = children.length; i < l; i ++ ) {

					var child = children[ i ];
					buildNodeHierachy( child, _node, allNodes );

				}

			}

		}

		return this._withDependencies( [

M
Mugen87 已提交
2305
			'nodes'
D
Don McCurdy 已提交
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326

		] ).then( function ( dependencies ) {

			return _each( json.scenes, function ( scene ) {

				var _scene = new THREE.Scene();
				if ( scene.name !== undefined ) _scene.name = scene.name;

				if ( scene.extras ) _scene.userData = scene.extras;

				var nodes = scene.nodes || [];

				for ( var i = 0, l = nodes.length; i < l; i ++ ) {

					var nodeId = nodes[ i ];
					buildNodeHierachy( nodeId, _scene, dependencies.nodes );

				}

				_scene.traverse( function ( child ) {

2327
					// for Specular-Glossiness.
2328
					if ( child.material && child.material.isGLTFSpecularGlossinessMaterial ) {
2329

2330
						child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
2331 2332 2333

					}

D
Don McCurdy 已提交
2334 2335
				} );

2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
				// Ambient lighting, if present, is always attached to the scene root.
				if ( scene.extensions
							 && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
							 && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {

					var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
					_scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );

				}

D
Don McCurdy 已提交
2346 2347 2348 2349 2350 2351 2352 2353
				return _scene;

			} );

		} );

	};

2354
	return GLTFLoader;
D
Don McCurdy 已提交
2355 2356

} )();