PageRenderTime 46ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/Demo/threejs-demo/带着canvas去流浪(14)-demo/public/GLTFLoader.js

https://github.com/dashnowords/blogs
JavaScript | 3348 lines | 1788 code | 1245 blank | 315 comment | 377 complexity | 85590b0508e8e2ad2a651fb9ca026456 MD5 | raw file
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. * @author Takahiro / https://github.com/takahirox
  6. * @author Don McCurdy / https://www.donmccurdy.com
  7. */
  8. THREE.GLTFLoader = ( function () {
  9. function GLTFLoader( manager ) {
  10. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11. this.dracoLoader = null;
  12. }
  13. GLTFLoader.prototype = {
  14. constructor: GLTFLoader,
  15. crossOrigin: 'anonymous',
  16. load: function ( url, onLoad, onProgress, onError ) {
  17. var scope = this;
  18. var resourcePath;
  19. if ( this.resourcePath !== undefined ) {
  20. resourcePath = this.resourcePath;
  21. } else if ( this.path !== undefined ) {
  22. resourcePath = this.path;
  23. } else {
  24. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  25. }
  26. // Tells the LoadingManager to track an extra item, which resolves after
  27. // the model is fully loaded. This means the count of items loaded will
  28. // be incorrect, but ensures manager.onLoad() does not fire early.
  29. scope.manager.itemStart( url );
  30. var _onError = function ( e ) {
  31. if ( onError ) {
  32. onError( e );
  33. } else {
  34. console.error( e );
  35. }
  36. scope.manager.itemEnd( url );
  37. scope.manager.itemError( url );
  38. };
  39. var loader = new THREE.FileLoader( scope.manager );
  40. loader.setPath( this.path );
  41. loader.setResponseType( 'arraybuffer' );
  42. loader.load( url, function ( data ) {
  43. try {
  44. scope.parse( data, resourcePath, function ( gltf ) {
  45. onLoad( gltf );
  46. scope.manager.itemEnd( url );
  47. }, _onError );
  48. } catch ( e ) {
  49. _onError( e );
  50. }
  51. }, onProgress, _onError );
  52. },
  53. setCrossOrigin: function ( value ) {
  54. this.crossOrigin = value;
  55. return this;
  56. },
  57. setPath: function ( value ) {
  58. this.path = value;
  59. return this;
  60. },
  61. setResourcePath: function ( value ) {
  62. this.resourcePath = value;
  63. return this;
  64. },
  65. setDRACOLoader: function ( dracoLoader ) {
  66. this.dracoLoader = dracoLoader;
  67. return this;
  68. },
  69. parse: function ( data, path, onLoad, onError ) {
  70. var content;
  71. var extensions = {};
  72. if ( typeof data === 'string' ) {
  73. content = data;
  74. } else {
  75. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  76. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  77. try {
  78. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  79. } catch ( error ) {
  80. if ( onError ) onError( error );
  81. return;
  82. }
  83. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  84. } else {
  85. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  86. }
  87. }
  88. var json = JSON.parse( content );
  89. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  90. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  91. return;
  92. }
  93. if ( json.extensionsUsed ) {
  94. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  95. var extensionName = json.extensionsUsed[ i ];
  96. var extensionsRequired = json.extensionsRequired || [];
  97. switch ( extensionName ) {
  98. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  99. extensions[ extensionName ] = new GLTFLightsExtension( json );
  100. break;
  101. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  102. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension( json );
  103. break;
  104. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  105. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension( json );
  106. break;
  107. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  108. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  109. break;
  110. case EXTENSIONS.MSFT_TEXTURE_DDS:
  111. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( json );
  112. break;
  113. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  114. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension( json );
  115. break;
  116. default:
  117. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  118. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  119. }
  120. }
  121. }
  122. }
  123. var parser = new GLTFParser( json, extensions, {
  124. path: path || this.resourcePath || '',
  125. crossOrigin: this.crossOrigin,
  126. manager: this.manager
  127. } );
  128. parser.parse( function ( scene, scenes, cameras, animations, json ) {
  129. var glTF = {
  130. scene: scene,
  131. scenes: scenes,
  132. cameras: cameras,
  133. animations: animations,
  134. asset: json.asset,
  135. parser: parser,
  136. userData: {}
  137. };
  138. addUnknownExtensionsToUserData( extensions, glTF, json );
  139. onLoad( glTF );
  140. }, onError );
  141. }
  142. };
  143. /* GLTFREGISTRY */
  144. function GLTFRegistry() {
  145. var objects = {};
  146. return {
  147. get: function ( key ) {
  148. return objects[ key ];
  149. },
  150. add: function ( key, object ) {
  151. objects[ key ] = object;
  152. },
  153. remove: function ( key ) {
  154. delete objects[ key ];
  155. },
  156. removeAll: function () {
  157. objects = {};
  158. }
  159. };
  160. }
  161. /*********************************/
  162. /********** EXTENSIONS ***********/
  163. /*********************************/
  164. var EXTENSIONS = {
  165. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  166. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  167. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  168. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  169. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  170. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  171. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  172. };
  173. /**
  174. * DDS Texture Extension
  175. *
  176. * Specification:
  177. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  178. *
  179. */
  180. function GLTFTextureDDSExtension() {
  181. if ( ! THREE.DDSLoader ) {
  182. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  183. }
  184. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  185. this.ddsLoader = new THREE.DDSLoader();
  186. }
  187. /**
  188. * Lights Extension
  189. *
  190. * Specification: PENDING
  191. */
  192. function GLTFLightsExtension( json ) {
  193. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  194. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  195. this.lightDefs = extension.lights || [];
  196. }
  197. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  198. var lightDef = this.lightDefs[ lightIndex ];
  199. var lightNode;
  200. var color = new THREE.Color( 0xffffff );
  201. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  202. var range = lightDef.range !== undefined ? lightDef.range : 0;
  203. switch ( lightDef.type ) {
  204. case 'directional':
  205. lightNode = new THREE.DirectionalLight( color );
  206. lightNode.target.position.set( 0, 0, -1 );
  207. lightNode.add( lightNode.target );
  208. break;
  209. case 'point':
  210. lightNode = new THREE.PointLight( color );
  211. lightNode.distance = range;
  212. break;
  213. case 'spot':
  214. lightNode = new THREE.SpotLight( color );
  215. lightNode.distance = range;
  216. // Handle spotlight properties.
  217. lightDef.spot = lightDef.spot || {};
  218. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  219. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  220. lightNode.angle = lightDef.spot.outerConeAngle;
  221. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  222. lightNode.target.position.set( 0, 0, -1 );
  223. lightNode.add( lightNode.target );
  224. break;
  225. default:
  226. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  227. }
  228. lightNode.decay = 2;
  229. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  230. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  231. return Promise.resolve( lightNode );
  232. };
  233. /**
  234. * Unlit Materials Extension (pending)
  235. *
  236. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  237. */
  238. function GLTFMaterialsUnlitExtension( json ) {
  239. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  240. }
  241. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function ( material ) {
  242. return THREE.MeshBasicMaterial;
  243. };
  244. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  245. var pending = [];
  246. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  247. materialParams.opacity = 1.0;
  248. var metallicRoughness = material.pbrMetallicRoughness;
  249. if ( metallicRoughness ) {
  250. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  251. var array = metallicRoughness.baseColorFactor;
  252. materialParams.color.fromArray( array );
  253. materialParams.opacity = array[ 3 ];
  254. }
  255. if ( metallicRoughness.baseColorTexture !== undefined ) {
  256. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  257. }
  258. }
  259. return Promise.all( pending );
  260. };
  261. /* BINARY EXTENSION */
  262. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  263. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  264. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  265. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  266. function GLTFBinaryExtension( data ) {
  267. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  268. this.content = null;
  269. this.body = null;
  270. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  271. this.header = {
  272. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  273. version: headerView.getUint32( 4, true ),
  274. length: headerView.getUint32( 8, true )
  275. };
  276. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  277. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  278. } else if ( this.header.version < 2.0 ) {
  279. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  280. }
  281. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  282. var chunkIndex = 0;
  283. while ( chunkIndex < chunkView.byteLength ) {
  284. var chunkLength = chunkView.getUint32( chunkIndex, true );
  285. chunkIndex += 4;
  286. var chunkType = chunkView.getUint32( chunkIndex, true );
  287. chunkIndex += 4;
  288. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  289. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  290. this.content = THREE.LoaderUtils.decodeText( contentArray );
  291. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  292. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  293. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  294. }
  295. // Clients must ignore chunks with unknown types.
  296. chunkIndex += chunkLength;
  297. }
  298. if ( this.content === null ) {
  299. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  300. }
  301. }
  302. /**
  303. * DRACO Mesh Compression Extension
  304. *
  305. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  306. */
  307. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  308. if ( ! dracoLoader ) {
  309. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  310. }
  311. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  312. this.json = json;
  313. this.dracoLoader = dracoLoader;
  314. }
  315. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  316. var json = this.json;
  317. var dracoLoader = this.dracoLoader;
  318. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  319. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  320. var threeAttributeMap = {};
  321. var attributeNormalizedMap = {};
  322. var attributeTypeMap = {};
  323. for ( var attributeName in gltfAttributeMap ) {
  324. if ( ! ( attributeName in ATTRIBUTES ) ) continue;
  325. threeAttributeMap[ ATTRIBUTES[ attributeName ] ] = gltfAttributeMap[ attributeName ];
  326. }
  327. for ( attributeName in primitive.attributes ) {
  328. if ( ATTRIBUTES[ attributeName ] !== undefined && gltfAttributeMap[ attributeName ] !== undefined ) {
  329. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  330. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  331. attributeTypeMap[ ATTRIBUTES[ attributeName ] ] = componentType;
  332. attributeNormalizedMap[ ATTRIBUTES[ attributeName ] ] = accessorDef.normalized === true;
  333. }
  334. }
  335. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  336. return new Promise( function ( resolve ) {
  337. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  338. for ( var attributeName in geometry.attributes ) {
  339. var attribute = geometry.attributes[ attributeName ];
  340. var normalized = attributeNormalizedMap[ attributeName ];
  341. if ( normalized !== undefined ) attribute.normalized = normalized;
  342. }
  343. resolve( geometry );
  344. }, threeAttributeMap, attributeTypeMap );
  345. } );
  346. } );
  347. };
  348. /**
  349. * Texture Transform Extension
  350. *
  351. * Specification:
  352. */
  353. function GLTFTextureTransformExtension( json ) {
  354. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  355. }
  356. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  357. texture = texture.clone();
  358. if ( transform.offset !== undefined ) {
  359. texture.offset.fromArray( transform.offset );
  360. }
  361. if ( transform.rotation !== undefined ) {
  362. texture.rotation = transform.rotation;
  363. }
  364. if ( transform.scale !== undefined ) {
  365. texture.repeat.fromArray( transform.scale );
  366. }
  367. if ( transform.texCoord !== undefined ) {
  368. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  369. }
  370. texture.needsUpdate = true;
  371. return texture;
  372. };
  373. /**
  374. * Specular-Glossiness Extension
  375. *
  376. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  377. */
  378. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  379. return {
  380. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  381. specularGlossinessParams: [
  382. 'color',
  383. 'map',
  384. 'lightMap',
  385. 'lightMapIntensity',
  386. 'aoMap',
  387. 'aoMapIntensity',
  388. 'emissive',
  389. 'emissiveIntensity',
  390. 'emissiveMap',
  391. 'bumpMap',
  392. 'bumpScale',
  393. 'normalMap',
  394. 'displacementMap',
  395. 'displacementScale',
  396. 'displacementBias',
  397. 'specularMap',
  398. 'specular',
  399. 'glossinessMap',
  400. 'glossiness',
  401. 'alphaMap',
  402. 'envMap',
  403. 'envMapIntensity',
  404. 'refractionRatio',
  405. ],
  406. getMaterialType: function () {
  407. return THREE.ShaderMaterial;
  408. },
  409. extendParams: function ( params, material, parser ) {
  410. var pbrSpecularGlossiness = material.extensions[ this.name ];
  411. var shader = THREE.ShaderLib[ 'standard' ];
  412. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  413. var specularMapParsFragmentChunk = [
  414. '#ifdef USE_SPECULARMAP',
  415. ' uniform sampler2D specularMap;',
  416. '#endif'
  417. ].join( '\n' );
  418. var glossinessMapParsFragmentChunk = [
  419. '#ifdef USE_GLOSSINESSMAP',
  420. ' uniform sampler2D glossinessMap;',
  421. '#endif'
  422. ].join( '\n' );
  423. var specularMapFragmentChunk = [
  424. 'vec3 specularFactor = specular;',
  425. '#ifdef USE_SPECULARMAP',
  426. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  427. ' texelSpecular = sRGBToLinear( texelSpecular );',
  428. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  429. ' specularFactor *= texelSpecular.rgb;',
  430. '#endif'
  431. ].join( '\n' );
  432. var glossinessMapFragmentChunk = [
  433. 'float glossinessFactor = glossiness;',
  434. '#ifdef USE_GLOSSINESSMAP',
  435. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  436. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  437. ' glossinessFactor *= texelGlossiness.a;',
  438. '#endif'
  439. ].join( '\n' );
  440. var lightPhysicalFragmentChunk = [
  441. 'PhysicalMaterial material;',
  442. 'material.diffuseColor = diffuseColor.rgb;',
  443. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  444. 'material.specularColor = specularFactor.rgb;',
  445. ].join( '\n' );
  446. var fragmentShader = shader.fragmentShader
  447. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  448. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  449. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  450. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  451. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  452. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  453. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  454. delete uniforms.roughness;
  455. delete uniforms.metalness;
  456. delete uniforms.roughnessMap;
  457. delete uniforms.metalnessMap;
  458. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  459. uniforms.glossiness = { value: 0.5 };
  460. uniforms.specularMap = { value: null };
  461. uniforms.glossinessMap = { value: null };
  462. params.vertexShader = shader.vertexShader;
  463. params.fragmentShader = fragmentShader;
  464. params.uniforms = uniforms;
  465. params.defines = { 'STANDARD': '' };
  466. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  467. params.opacity = 1.0;
  468. var pending = [];
  469. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  470. var array = pbrSpecularGlossiness.diffuseFactor;
  471. params.color.fromArray( array );
  472. params.opacity = array[ 3 ];
  473. }
  474. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  475. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  476. }
  477. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  478. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  479. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  480. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  481. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  482. }
  483. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  484. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  485. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossMapDef ) );
  486. pending.push( parser.assignTexture( params, 'specularMap', specGlossMapDef ) );
  487. }
  488. return Promise.all( pending );
  489. },
  490. createMaterial: function ( params ) {
  491. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  492. var material = new THREE.ShaderMaterial( {
  493. defines: params.defines,
  494. vertexShader: params.vertexShader,
  495. fragmentShader: params.fragmentShader,
  496. uniforms: params.uniforms,
  497. fog: true,
  498. lights: true,
  499. opacity: params.opacity,
  500. transparent: params.transparent
  501. } );
  502. material.isGLTFSpecularGlossinessMaterial = true;
  503. material.color = params.color;
  504. material.map = params.map === undefined ? null : params.map;
  505. material.lightMap = null;
  506. material.lightMapIntensity = 1.0;
  507. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  508. material.aoMapIntensity = 1.0;
  509. material.emissive = params.emissive;
  510. material.emissiveIntensity = 1.0;
  511. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  512. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  513. material.bumpScale = 1;
  514. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  515. if ( params.normalScale ) material.normalScale = params.normalScale;
  516. material.displacementMap = null;
  517. material.displacementScale = 1;
  518. material.displacementBias = 0;
  519. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  520. material.specular = params.specular;
  521. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  522. material.glossiness = params.glossiness;
  523. material.alphaMap = null;
  524. material.envMap = params.envMap === undefined ? null : params.envMap;
  525. material.envMapIntensity = 1.0;
  526. material.refractionRatio = 0.98;
  527. material.extensions.derivatives = true;
  528. return material;
  529. },
  530. /**
  531. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  532. * copy only properties it knows about or inherits, and misses many properties that would
  533. * normally be defined by MeshStandardMaterial.
  534. *
  535. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  536. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  537. * AND also updating `.onBeforeRender` on the parent mesh.
  538. *
  539. * @param {THREE.ShaderMaterial} source
  540. * @return {THREE.ShaderMaterial}
  541. */
  542. cloneMaterial: function ( source ) {
  543. var target = source.clone();
  544. target.isGLTFSpecularGlossinessMaterial = true;
  545. var params = this.specularGlossinessParams;
  546. for ( var i = 0, il = params.length; i < il; i ++ ) {
  547. target[ params[ i ] ] = source[ params[ i ] ];
  548. }
  549. return target;
  550. },
  551. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  552. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  553. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  554. return;
  555. }
  556. var uniforms = material.uniforms;
  557. var defines = material.defines;
  558. uniforms.opacity.value = material.opacity;
  559. uniforms.diffuse.value.copy( material.color );
  560. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  561. uniforms.map.value = material.map;
  562. uniforms.specularMap.value = material.specularMap;
  563. uniforms.alphaMap.value = material.alphaMap;
  564. uniforms.lightMap.value = material.lightMap;
  565. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  566. uniforms.aoMap.value = material.aoMap;
  567. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  568. // uv repeat and offset setting priorities
  569. // 1. color map
  570. // 2. specular map
  571. // 3. normal map
  572. // 4. bump map
  573. // 5. alpha map
  574. // 6. emissive map
  575. var uvScaleMap;
  576. if ( material.map ) {
  577. uvScaleMap = material.map;
  578. } else if ( material.specularMap ) {
  579. uvScaleMap = material.specularMap;
  580. } else if ( material.displacementMap ) {
  581. uvScaleMap = material.displacementMap;
  582. } else if ( material.normalMap ) {
  583. uvScaleMap = material.normalMap;
  584. } else if ( material.bumpMap ) {
  585. uvScaleMap = material.bumpMap;
  586. } else if ( material.glossinessMap ) {
  587. uvScaleMap = material.glossinessMap;
  588. } else if ( material.alphaMap ) {
  589. uvScaleMap = material.alphaMap;
  590. } else if ( material.emissiveMap ) {
  591. uvScaleMap = material.emissiveMap;
  592. }
  593. if ( uvScaleMap !== undefined ) {
  594. // backwards compatibility
  595. if ( uvScaleMap.isWebGLRenderTarget ) {
  596. uvScaleMap = uvScaleMap.texture;
  597. }
  598. if ( uvScaleMap.matrixAutoUpdate === true ) {
  599. uvScaleMap.updateMatrix();
  600. }
  601. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  602. }
  603. uniforms.envMap.value = material.envMap;
  604. uniforms.envMapIntensity.value = material.envMapIntensity;
  605. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  606. uniforms.refractionRatio.value = material.refractionRatio;
  607. uniforms.specular.value.copy( material.specular );
  608. uniforms.glossiness.value = material.glossiness;
  609. uniforms.glossinessMap.value = material.glossinessMap;
  610. uniforms.emissiveMap.value = material.emissiveMap;
  611. uniforms.bumpMap.value = material.bumpMap;
  612. uniforms.normalMap.value = material.normalMap;
  613. uniforms.displacementMap.value = material.displacementMap;
  614. uniforms.displacementScale.value = material.displacementScale;
  615. uniforms.displacementBias.value = material.displacementBias;
  616. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  617. defines.USE_GLOSSINESSMAP = '';
  618. // set USE_ROUGHNESSMAP to enable vUv
  619. defines.USE_ROUGHNESSMAP = '';
  620. }
  621. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  622. delete defines.USE_GLOSSINESSMAP;
  623. delete defines.USE_ROUGHNESSMAP;
  624. }
  625. }
  626. };
  627. }
  628. /*********************************/
  629. /********** INTERPOLATION ********/
  630. /*********************************/
  631. // Spline Interpolation
  632. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  633. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  634. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  635. }
  636. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  637. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  638. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  639. // Copies a sample value to the result buffer. See description of glTF
  640. // CUBICSPLINE values layout in interpolate_() function below.
  641. var result = this.resultBuffer,
  642. values = this.sampleValues,
  643. valueSize = this.valueSize,
  644. offset = index * valueSize * 3 + valueSize;
  645. for ( var i = 0; i !== valueSize; i ++ ) {
  646. result[ i ] = values[ offset + i ];
  647. }
  648. return result;
  649. };
  650. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  651. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  652. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  653. var result = this.resultBuffer;
  654. var values = this.sampleValues;
  655. var stride = this.valueSize;
  656. var stride2 = stride * 2;
  657. var stride3 = stride * 3;
  658. var td = t1 - t0;
  659. var p = ( t - t0 ) / td;
  660. var pp = p * p;
  661. var ppp = pp * p;
  662. var offset1 = i1 * stride3;
  663. var offset0 = offset1 - stride3;
  664. var s0 = 2 * ppp - 3 * pp + 1;
  665. var s1 = ppp - 2 * pp + p;
  666. var s2 = - 2 * ppp + 3 * pp;
  667. var s3 = ppp - pp;
  668. // Layout of keyframe output values for CUBICSPLINE animations:
  669. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  670. for ( var i = 0; i !== stride; i ++ ) {
  671. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  672. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  673. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  674. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  675. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  676. }
  677. return result;
  678. };
  679. /*********************************/
  680. /********** INTERNALS ************/
  681. /*********************************/
  682. /* CONSTANTS */
  683. var WEBGL_CONSTANTS = {
  684. FLOAT: 5126,
  685. //FLOAT_MAT2: 35674,
  686. FLOAT_MAT3: 35675,
  687. FLOAT_MAT4: 35676,
  688. FLOAT_VEC2: 35664,
  689. FLOAT_VEC3: 35665,
  690. FLOAT_VEC4: 35666,
  691. LINEAR: 9729,
  692. REPEAT: 10497,
  693. SAMPLER_2D: 35678,
  694. POINTS: 0,
  695. LINES: 1,
  696. LINE_LOOP: 2,
  697. LINE_STRIP: 3,
  698. TRIANGLES: 4,
  699. TRIANGLE_STRIP: 5,
  700. TRIANGLE_FAN: 6,
  701. UNSIGNED_BYTE: 5121,
  702. UNSIGNED_SHORT: 5123
  703. };
  704. var WEBGL_TYPE = {
  705. 5126: Number,
  706. //35674: THREE.Matrix2,
  707. 35675: THREE.Matrix3,
  708. 35676: THREE.Matrix4,
  709. 35664: THREE.Vector2,
  710. 35665: THREE.Vector3,
  711. 35666: THREE.Vector4,
  712. 35678: THREE.Texture
  713. };
  714. var WEBGL_COMPONENT_TYPES = {
  715. 5120: Int8Array,
  716. 5121: Uint8Array,
  717. 5122: Int16Array,
  718. 5123: Uint16Array,
  719. 5125: Uint32Array,
  720. 5126: Float32Array
  721. };
  722. var WEBGL_FILTERS = {
  723. 9728: THREE.NearestFilter,
  724. 9729: THREE.LinearFilter,
  725. 9984: THREE.NearestMipMapNearestFilter,
  726. 9985: THREE.LinearMipMapNearestFilter,
  727. 9986: THREE.NearestMipMapLinearFilter,
  728. 9987: THREE.LinearMipMapLinearFilter
  729. };
  730. var WEBGL_WRAPPINGS = {
  731. 33071: THREE.ClampToEdgeWrapping,
  732. 33648: THREE.MirroredRepeatWrapping,
  733. 10497: THREE.RepeatWrapping
  734. };
  735. var WEBGL_SIDES = {
  736. 1028: THREE.BackSide, // Culling front
  737. 1029: THREE.FrontSide // Culling back
  738. //1032: THREE.NoSide // Culling front and back, what to do?
  739. };
  740. var WEBGL_DEPTH_FUNCS = {
  741. 512: THREE.NeverDepth,
  742. 513: THREE.LessDepth,
  743. 514: THREE.EqualDepth,
  744. 515: THREE.LessEqualDepth,
  745. 516: THREE.GreaterEqualDepth,
  746. 517: THREE.NotEqualDepth,
  747. 518: THREE.GreaterEqualDepth,
  748. 519: THREE.AlwaysDepth
  749. };
  750. var WEBGL_BLEND_EQUATIONS = {
  751. 32774: THREE.AddEquation,
  752. 32778: THREE.SubtractEquation,
  753. 32779: THREE.ReverseSubtractEquation
  754. };
  755. var WEBGL_BLEND_FUNCS = {
  756. 0: THREE.ZeroFactor,
  757. 1: THREE.OneFactor,
  758. 768: THREE.SrcColorFactor,
  759. 769: THREE.OneMinusSrcColorFactor,
  760. 770: THREE.SrcAlphaFactor,
  761. 771: THREE.OneMinusSrcAlphaFactor,
  762. 772: THREE.DstAlphaFactor,
  763. 773: THREE.OneMinusDstAlphaFactor,
  764. 774: THREE.DstColorFactor,
  765. 775: THREE.OneMinusDstColorFactor,
  766. 776: THREE.SrcAlphaSaturateFactor
  767. // The followings are not supported by Three.js yet
  768. //32769: CONSTANT_COLOR,
  769. //32770: ONE_MINUS_CONSTANT_COLOR,
  770. //32771: CONSTANT_ALPHA,
  771. //32772: ONE_MINUS_CONSTANT_COLOR
  772. };
  773. var WEBGL_TYPE_SIZES = {
  774. 'SCALAR': 1,
  775. 'VEC2': 2,
  776. 'VEC3': 3,
  777. 'VEC4': 4,
  778. 'MAT2': 4,
  779. 'MAT3': 9,
  780. 'MAT4': 16
  781. };
  782. var ATTRIBUTES = {
  783. POSITION: 'position',
  784. NORMAL: 'normal',
  785. TEXCOORD_0: 'uv',
  786. TEXCOORD0: 'uv', // deprecated
  787. TEXCOORD: 'uv', // deprecated
  788. TEXCOORD_1: 'uv2',
  789. COLOR_0: 'color',
  790. COLOR0: 'color', // deprecated
  791. COLOR: 'color', // deprecated
  792. WEIGHTS_0: 'skinWeight',
  793. WEIGHT: 'skinWeight', // deprecated
  794. JOINTS_0: 'skinIndex',
  795. JOINT: 'skinIndex' // deprecated
  796. };
  797. var PATH_PROPERTIES = {
  798. scale: 'scale',
  799. translation: 'position',
  800. rotation: 'quaternion',
  801. weights: 'morphTargetInfluences'
  802. };
  803. var INTERPOLATION = {
  804. CUBICSPLINE: THREE.InterpolateSmooth, // We use custom interpolation GLTFCubicSplineInterpolation for CUBICSPLINE.
  805. // KeyframeTrack.optimize() can't handle glTF Cubic Spline output values layout,
  806. // using THREE.InterpolateSmooth for KeyframeTrack instantiation to prevent optimization.
  807. // See KeyframeTrack.optimize() for the detail.
  808. LINEAR: THREE.InterpolateLinear,
  809. STEP: THREE.InterpolateDiscrete
  810. };
  811. var STATES_ENABLES = {
  812. 2884: 'CULL_FACE',
  813. 2929: 'DEPTH_TEST',
  814. 3042: 'BLEND',
  815. 3089: 'SCISSOR_TEST',
  816. 32823: 'POLYGON_OFFSET_FILL',
  817. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  818. };
  819. var ALPHA_MODES = {
  820. OPAQUE: 'OPAQUE',
  821. MASK: 'MASK',
  822. BLEND: 'BLEND'
  823. };
  824. var MIME_TYPE_FORMATS = {
  825. 'image/png': THREE.RGBAFormat,
  826. 'image/jpeg': THREE.RGBFormat
  827. };
  828. /* UTILITY FUNCTIONS */
  829. function resolveURL( url, path ) {
  830. // Invalid URL
  831. if ( typeof url !== 'string' || url === '' ) return '';
  832. // Absolute URL http://,https://,//
  833. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  834. // Data URI
  835. if ( /^data:.*,.*$/i.test( url ) ) return url;
  836. // Blob URL
  837. if ( /^blob:.*$/i.test( url ) ) return url;
  838. // Relative URL
  839. return path + url;
  840. }
  841. /**
  842. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  843. */
  844. function createDefaultMaterial() {
  845. return new THREE.MeshStandardMaterial( {
  846. color: 0xFFFFFF,
  847. emissive: 0x000000,
  848. metalness: 1,
  849. roughness: 1,
  850. transparent: false,
  851. depthTest: true,
  852. side: THREE.FrontSide
  853. } );
  854. }
  855. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  856. // Add unknown glTF extensions to an object's userData.
  857. for ( var name in objectDef.extensions ) {
  858. if ( knownExtensions[ name ] === undefined ) {
  859. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  860. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  861. }
  862. }
  863. }
  864. /**
  865. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  866. * @param {GLTF.definition} gltfDef
  867. */
  868. function assignExtrasToUserData( object, gltfDef ) {
  869. if ( gltfDef.extras !== undefined ) {
  870. if ( typeof gltfDef.extras === 'object' ) {
  871. object.userData = gltfDef.extras;
  872. } else {
  873. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  874. }
  875. }
  876. }
  877. /**
  878. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  879. *
  880. * @param {THREE.BufferGeometry} geometry
  881. * @param {Array<GLTF.Target>} targets
  882. * @param {GLTFParser} parser
  883. * @return {Promise<THREE.BufferGeometry>}
  884. */
  885. function addMorphTargets( geometry, targets, parser ) {
  886. var hasMorphPosition = false;
  887. var hasMorphNormal = false;
  888. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  889. var target = targets[ i ];
  890. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  891. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  892. if ( hasMorphPosition && hasMorphNormal ) break;
  893. }
  894. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  895. var pendingPositionAccessors = [];
  896. var pendingNormalAccessors = [];
  897. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  898. var target = targets[ i ];
  899. if ( hasMorphPosition ) {
  900. var accessor = target.POSITION !== undefined
  901. ? parser.getDependency( 'accessor', target.POSITION )
  902. .then( function ( accessor ) {
  903. // Cloning not to pollute original accessor below
  904. return cloneBufferAttribute( accessor );
  905. } )
  906. : geometry.attributes.position;
  907. pendingPositionAccessors.push( accessor );
  908. }
  909. if ( hasMorphNormal ) {
  910. var accessor = target.NORMAL !== undefined
  911. ? parser.getDependency( 'accessor', target.NORMAL )
  912. .then( function ( accessor ) {
  913. return cloneBufferAttribute( accessor );
  914. } )
  915. : geometry.attributes.normal;
  916. pendingNormalAccessors.push( accessor );
  917. }
  918. }
  919. return Promise.all( [
  920. Promise.all( pendingPositionAccessors ),
  921. Promise.all( pendingNormalAccessors )
  922. ] ).then( function ( accessors ) {
  923. var morphPositions = accessors[ 0 ];
  924. var morphNormals = accessors[ 1 ];
  925. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  926. var target = targets[ i ];
  927. var attributeName = 'morphTarget' + i;
  928. if ( hasMorphPosition ) {
  929. // Three.js morph position is absolute value. The formula is
  930. // basePosition
  931. // + weight0 * ( morphPosition0 - basePosition )
  932. // + weight1 * ( morphPosition1 - basePosition )
  933. // ...
  934. // while the glTF one is relative
  935. // basePosition
  936. // + weight0 * glTFmorphPosition0
  937. // + weight1 * glTFmorphPosition1
  938. // ...
  939. // then we need to convert from relative to absolute here.
  940. if ( target.POSITION !== undefined ) {
  941. var positionAttribute = morphPositions[ i ];
  942. positionAttribute.name = attributeName;
  943. var position = geometry.attributes.position;
  944. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  945. positionAttribute.setXYZ(
  946. j,
  947. positionAttribute.getX( j ) + position.getX( j ),
  948. positionAttribute.getY( j ) + position.getY( j ),
  949. positionAttribute.getZ( j ) + position.getZ( j )
  950. );
  951. }
  952. }
  953. }
  954. if ( hasMorphNormal ) {
  955. // see target.POSITION's comment
  956. if ( target.NORMAL !== undefined ) {
  957. var normalAttribute = morphNormals[ i ];
  958. normalAttribute.name = attributeName;
  959. var normal = geometry.attributes.normal;
  960. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  961. normalAttribute.setXYZ(
  962. j,
  963. normalAttribute.getX( j ) + normal.getX( j ),
  964. normalAttribute.getY( j ) + normal.getY( j ),
  965. normalAttribute.getZ( j ) + normal.getZ( j )
  966. );
  967. }
  968. }
  969. }
  970. }
  971. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  972. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  973. return geometry;
  974. } );
  975. }
  976. /**
  977. * @param {THREE.Mesh} mesh
  978. * @param {GLTF.Mesh} meshDef
  979. */
  980. function updateMorphTargets( mesh, meshDef ) {
  981. mesh.updateMorphTargets();
  982. if ( meshDef.weights !== undefined ) {
  983. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  984. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  985. }
  986. }
  987. // .extras has user-defined data, so check that .extras.targetNames is an array.
  988. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  989. var targetNames = meshDef.extras.targetNames;
  990. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  991. mesh.morphTargetDictionary = {};
  992. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  993. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  994. }
  995. } else {
  996. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  997. }
  998. }
  999. }
  1000. function isPrimitiveEqual( a, b ) {
  1001. if ( a.indices !== b.indices ) {
  1002. return false;
  1003. }
  1004. return isObjectEqual( a.attributes, b.attributes );
  1005. }
  1006. function isObjectEqual( a, b ) {
  1007. if ( Object.keys( a ).length !== Object.keys( b ).length ) return false;
  1008. for ( var key in a ) {
  1009. if ( a[ key ] !== b[ key ] ) return false;
  1010. }
  1011. return true;
  1012. }
  1013. function isArrayEqual( a, b ) {
  1014. if ( a.length !== b.length ) return false;
  1015. for ( var i = 0, il = a.length; i < il; i ++ ) {
  1016. if ( a[ i ] !== b[ i ] ) return false;
  1017. }
  1018. return true;
  1019. }
  1020. function getCachedGeometry( cache, newPrimitive ) {
  1021. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  1022. var cached = cache[ i ];
  1023. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) return cached.promise;
  1024. }
  1025. return null;
  1026. }
  1027. function getCachedCombinedGeometry( cache, geometries ) {
  1028. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  1029. var cached = cache[ i ];
  1030. if ( isArrayEqual( geometries, cached.baseGeometries ) ) return cached.geometry;
  1031. }
  1032. return null;
  1033. }
  1034. function getCachedMultiPassGeometry( cache, geometry, primitives ) {
  1035. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  1036. var cached = cache[ i ];
  1037. if ( geometry === cached.baseGeometry && isArrayEqual( primitives, cached.primitives ) ) return cached.geometry;
  1038. }
  1039. return null;
  1040. }
  1041. function cloneBufferAttribute( attribute ) {
  1042. if ( attribute.isInterleavedBufferAttribute ) {
  1043. var count = attribute.count;
  1044. var itemSize = attribute.itemSize;
  1045. var array = attribute.array.slice( 0, count * itemSize );
  1046. for ( var i = 0; i < count; ++ i ) {
  1047. array[ i ] = attribute.getX( i );
  1048. if ( itemSize >= 2 ) array[ i + 1 ] = attribute.getY( i );
  1049. if ( itemSize >= 3 ) array[ i + 2 ] = attribute.getZ( i );
  1050. if ( itemSize >= 4 ) array[ i + 3 ] = attribute.getW( i );
  1051. }
  1052. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  1053. }
  1054. return attribute.clone();
  1055. }
  1056. /**
  1057. * Checks if we can build a single Mesh with MultiMaterial from multiple primitives.
  1058. * Returns true if all primitives use the same attributes/morphAttributes/mode
  1059. * and also have index. Otherwise returns false.
  1060. *
  1061. * @param {Array<GLTF.Primitive>} primitives
  1062. * @return {Boolean}
  1063. */
  1064. function isMultiPassGeometry( primitives ) {
  1065. if ( primitives.length < 2 ) return false;
  1066. var primitive0 = primitives[ 0 ];
  1067. var targets0 = primitive0.targets || [];
  1068. if ( primitive0.indices === undefined ) return false;
  1069. for ( var i = 1, il = primitives.length; i < il; i ++ ) {
  1070. var primitive = primitives[ i ];
  1071. if ( primitive0.mode !== primitive.mode ) return false;
  1072. if ( primitive.indices === undefined ) return false;
  1073. if ( ! isObjectEqual( primitive0.attributes, primitive.attributes ) ) return false;
  1074. var targets = primitive.targets || [];
  1075. if ( targets0.length !== targets.length ) return false;
  1076. for ( var j = 0, jl = targets0.length; j < jl; j ++ ) {
  1077. if ( ! isObjectEqual( targets0[ j ], targets[ j ] ) ) return false;
  1078. }
  1079. }
  1080. return true;
  1081. }
  1082. /* GLTF PARSER */
  1083. function GLTFParser( json, extensions, options ) {
  1084. this.json = json || {};
  1085. this.extensions = extensions || {};
  1086. this.options = options || {};
  1087. // loader object cache
  1088. this.cache = new GLTFRegistry();
  1089. // BufferGeometry caching
  1090. this.primitiveCache = [];
  1091. this.multiplePrimitivesCache = [];
  1092. this.multiPassGeometryCache = [];
  1093. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  1094. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  1095. this.fileLoader = new THREE.FileLoader( this.options.manager );
  1096. this.fileLoader.setResponseType( 'arraybuffer' );
  1097. }
  1098. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  1099. var json = this.json;
  1100. // Clear the loader cache
  1101. this.cache.removeAll();
  1102. // Mark the special nodes/meshes in json for efficient parse
  1103. this.markDefs();
  1104. // Fire the callback on complete
  1105. this.getMultiDependencies( [
  1106. 'scene',
  1107. 'animation',
  1108. 'camera'
  1109. ] ).then( function ( dependencies ) {
  1110. var scenes = dependencies.scenes || [];
  1111. var scene = scenes[ json.scene || 0 ];
  1112. var animations = dependencies.animations || [];
  1113. var cameras = dependencies.cameras || [];
  1114. onLoad( scene, scenes, cameras, animations, json );
  1115. } ).catch( onError );
  1116. };
  1117. /**
  1118. * Marks the special nodes/meshes in json for efficient parse.
  1119. */
  1120. GLTFParser.prototype.markDefs = function () {
  1121. var nodeDefs = this.json.nodes || [];
  1122. var skinDefs = this.json.skins || [];
  1123. var meshDefs = this.json.meshes || [];
  1124. var meshReferences = {};
  1125. var meshUses = {};
  1126. // Nothing in the node definition indicates whether it is a Bone or an
  1127. // Object3D. Use the skins' joint references to mark bones.
  1128. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1129. var joints = skinDefs[ skinIndex ].joints;
  1130. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  1131. nodeDefs[ joints[ i ] ].isBone = true;
  1132. }
  1133. }
  1134. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  1135. // avoid having more than one THREE.Mesh with the same name, count
  1136. // references and rename instances below.
  1137. //
  1138. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1139. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1140. var nodeDef = nodeDefs[ nodeIndex ];
  1141. if ( nodeDef.mesh !== undefined ) {
  1142. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  1143. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  1144. }
  1145. meshReferences[ nodeDef.mesh ] ++;
  1146. // Nothing in the mesh definition indicates whether it is
  1147. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1148. // to mark SkinnedMesh if node has skin.
  1149. if ( nodeDef.skin !== undefined ) {
  1150. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1151. }
  1152. }
  1153. }
  1154. this.json.meshReferences = meshReferences;
  1155. this.json.meshUses = meshUses;
  1156. };
  1157. /**
  1158. * Requests the specified dependency asynchronously, with caching.
  1159. * @param {string} type
  1160. * @param {number} index
  1161. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  1162. */
  1163. GLTFParser.prototype.getDependency = function ( type, index ) {
  1164. var cacheKey = type + ':' + index;
  1165. var dependency = this.cache.get( cacheKey );
  1166. if ( ! dependency ) {
  1167. switch ( type ) {
  1168. case 'scene':
  1169. dependency = this.loadScene( index );
  1170. break;
  1171. case 'node':
  1172. dependency = this.loadNode( index );
  1173. break;
  1174. case 'mesh':
  1175. dependency = this.loadMesh( index );
  1176. break;
  1177. case 'accessor':
  1178. dependency = this.loadAccessor( index );
  1179. break;
  1180. case 'bufferView':
  1181. dependency = this.loadBufferView( index );
  1182. break;
  1183. case 'buffer':
  1184. dependency = this.loadBuffer( index );
  1185. break;
  1186. case 'material':
  1187. dependency = this.loadMaterial( index );
  1188. break;
  1189. case 'texture':
  1190. dependency = this.loadTexture( index );
  1191. break;
  1192. case 'skin':
  1193. dependency = this.loadSkin( index );
  1194. break;
  1195. case 'animation':
  1196. dependency = this.loadAnimation( index );
  1197. break;
  1198. case 'camera':
  1199. dependency = this.loadCamera( index );
  1200. break;
  1201. case 'light':
  1202. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  1203. break
  1204. default:
  1205. throw new Error( 'Unknown type: ' + type );
  1206. }
  1207. this.cache.add( cacheKey, dependency );
  1208. }
  1209. return dependency;
  1210. };
  1211. /**
  1212. * Requests all dependencies of the specified type asynchronously, with caching.
  1213. * @param {string} type
  1214. * @return {Promise<Array<Object>>}
  1215. */
  1216. GLTFParser.prototype.getDependencies = function ( type ) {
  1217. var dependencies = this.cache.get( type );
  1218. if ( ! dependencies ) {
  1219. var parser = this;
  1220. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1221. dependencies = Promise.all( defs.map( function ( def, index ) {
  1222. return parser.getDependency( type, index );
  1223. } ) );
  1224. this.cache.add( type, dependencies );
  1225. }
  1226. return dependencies;
  1227. };
  1228. /**
  1229. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  1230. * @param {Array<string>} types
  1231. * @return {Promise<Object<Array<Object>>>}
  1232. */
  1233. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  1234. var results = {};
  1235. var pending = [];
  1236. for ( var i = 0, il = types.length; i < il; i ++ ) {
  1237. var type = types[ i ];
  1238. var value = this.getDependencies( type );
  1239. value = value.then( function ( key, value ) {
  1240. results[ key ] = value;
  1241. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  1242. pending.push( value );
  1243. }
  1244. return Promise.all( pending ).then( function () {
  1245. return results;
  1246. } );
  1247. };
  1248. /**
  1249. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1250. * @param {number} bufferIndex
  1251. * @return {Promise<ArrayBuffer>}
  1252. */
  1253. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1254. var bufferDef = this.json.buffers[ bufferIndex ];
  1255. var loader = this.fileLoader;
  1256. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1257. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1258. }
  1259. // If present, GLB container is required to be the first buffer.
  1260. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1261. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1262. }
  1263. var options = this.options;
  1264. return new Promise( function ( resolve, reject ) {
  1265. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1266. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1267. } );
  1268. } );
  1269. };
  1270. /**
  1271. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1272. * @param {number} bufferViewIndex
  1273. * @return {Promise<ArrayBuffer>}
  1274. */
  1275. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1276. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1277. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1278. var byteLength = bufferViewDef.byteLength || 0;
  1279. var byteOffset = bufferViewDef.byteOffset || 0;
  1280. return buffer.slice( byteOffset, byteOffset + byteLength );
  1281. } );
  1282. };
  1283. /**
  1284. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1285. * @param {number} accessorIndex
  1286. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1287. */
  1288. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1289. var parser = this;
  1290. var json = this.json;
  1291. var accessorDef = this.json.accessors[ accessorIndex ];
  1292. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1293. // Ignore empty accessors, which may be used to declare runtime
  1294. // information about attributes coming from another source (e.g. Draco
  1295. // compression extension).
  1296. return null;
  1297. }
  1298. var pendingBufferViews = [];
  1299. if ( accessorDef.bufferView !== undefined ) {
  1300. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1301. } else {
  1302. pendingBufferViews.push( null );
  1303. }
  1304. if ( accessorDef.sparse !== undefined ) {
  1305. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1306. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1307. }
  1308. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1309. var bufferView = bufferViews[ 0 ];
  1310. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1311. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1312. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1313. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1314. var itemBytes = elementBytes * itemSize;
  1315. var byteOffset = accessorDef.byteOffset || 0;
  1316. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1317. var normalized = accessorDef.normalized === true;
  1318. var array, bufferAttribute;
  1319. // The buffer is not interleaved if the stride is the item size in bytes.
  1320. if ( byteStride && byteStride !== itemBytes ) {
  1321. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  1322. var ib = parser.cache.get( ibCacheKey );
  1323. if ( ! ib ) {
  1324. // Use the full buffer if it's interleaved.
  1325. array = new TypedArray( bufferView );
  1326. // Integer parameters to IB/IBA are in array elements, not bytes.
  1327. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1328. parser.cache.add( ibCacheKey, ib );
  1329. }
  1330. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  1331. } else {
  1332. if ( bufferView === null ) {
  1333. array = new TypedArray( accessorDef.count * itemSize );
  1334. } else {
  1335. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1336. }
  1337. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1338. }
  1339. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1340. if ( accessorDef.sparse !== undefined ) {
  1341. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1342. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1343. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1344. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1345. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1346. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1347. if ( bufferView !== null ) {
  1348. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1349. bufferAttribute.setArray( bufferAttribute.array.slice() );
  1350. }
  1351. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1352. var index = sparseIndices[ i ];
  1353. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1354. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1355. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1356. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1357. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1358. }
  1359. }
  1360. return bufferAttribute;
  1361. } );
  1362. };
  1363. /**
  1364. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1365. * @param {number} textureIndex
  1366. * @return {Promise<THREE.Texture>}
  1367. */
  1368. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1369. var parser = this;
  1370. var json = this.json;
  1371. var options = this.options;
  1372. var textureLoader = this.textureLoader;
  1373. var URL = window.URL || window.webkitURL;
  1374. var textureDef = json.textures[ textureIndex ];
  1375. var textureExtensions = textureDef.extensions || {};
  1376. var source;
  1377. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1378. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1379. } else {
  1380. source = json.images[ textureDef.source ];
  1381. }
  1382. var sourceURI = source.uri;
  1383. var isObjectURL = false;
  1384. if ( source.bufferView !== undefined ) {
  1385. // Load binary image data from bufferView, if provided.
  1386. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1387. isObjectURL = true;
  1388. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1389. sourceURI = URL.createObjectURL( blob );
  1390. return sourceURI;
  1391. } );
  1392. }
  1393. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1394. // Load Texture resource.
  1395. var loader = THREE.Loader.Handlers.get( sourceURI );
  1396. if ( ! loader ) {
  1397. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1398. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1399. : textureLoader;
  1400. }
  1401. return new Promise( function ( resolve, reject ) {
  1402. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1403. } );
  1404. } ).then( function ( texture ) {
  1405. // Clean up resources and configure Texture.
  1406. if ( isObjectURL === true ) {
  1407. URL.revokeObjectURL( sourceURI );
  1408. }
  1409. texture.flipY = false;
  1410. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1411. // Ignore unknown mime types, like DDS files.
  1412. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  1413. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  1414. }
  1415. var samplers = json.samplers || {};
  1416. var sampler = samplers[ textureDef.sampler ] || {};
  1417. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1418. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1419. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1420. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1421. return texture;
  1422. } );
  1423. };
  1424. /**
  1425. * Asynchronously assigns a texture to the given material parameters.
  1426. * @param {Object} materialParams
  1427. * @param {string} mapName
  1428. * @param {Object} mapDef
  1429. * @return {Promise}
  1430. */
  1431. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  1432. var parser = this;
  1433. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  1434. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1435. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1436. if ( transform ) {
  1437. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1438. }
  1439. }
  1440. materialParams[ mapName ] = texture;
  1441. } );
  1442. };
  1443. /**
  1444. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1445. * @param {number} materialIndex
  1446. * @return {Promise<THREE.Material>}
  1447. */
  1448. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1449. var parser = this;
  1450. var json = this.json;
  1451. var extensions = this.extensions;
  1452. var materialDef = json.materials[ materialIndex ];
  1453. var materialType;
  1454. var materialParams = {};
  1455. var materialExtensions = materialDef.extensions || {};
  1456. var pending = [];
  1457. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1458. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1459. materialType = sgExtension.getMaterialType( materialDef );
  1460. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1461. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1462. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1463. materialType = kmuExtension.getMaterialType( materialDef );
  1464. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1465. } else {
  1466. // Specification:
  1467. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1468. materialType = THREE.MeshStandardMaterial;
  1469. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1470. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1471. materialParams.opacity = 1.0;
  1472. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1473. var array = metallicRoughness.baseColorFactor;
  1474. materialParams.color.fromArray( array );
  1475. materialParams.opacity = array[ 3 ];
  1476. }
  1477. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1478. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1479. }
  1480. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1481. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1482. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1483. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1484. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1485. }
  1486. }
  1487. if ( materialDef.doubleSided === true ) {
  1488. materialParams.side = THREE.DoubleSide;
  1489. }
  1490. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1491. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1492. materialParams.transparent = true;
  1493. } else {
  1494. materialParams.transparent = false;
  1495. if ( alphaMode === ALPHA_MODES.MASK ) {
  1496. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1497. }
  1498. }
  1499. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1500. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1501. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1502. if ( materialDef.normalTexture.scale !== undefined ) {
  1503. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1504. }
  1505. }
  1506. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1507. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1508. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1509. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1510. }
  1511. }
  1512. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1513. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1514. }
  1515. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1516. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1517. }
  1518. return Promise.all( pending ).then( function () {
  1519. var material;
  1520. if ( materialType === THREE.ShaderMaterial ) {
  1521. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1522. } else {
  1523. material = new materialType( materialParams );
  1524. }
  1525. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  1526. // Normal map textures use OpenGL conventions:
  1527. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1528. if ( material.normalScale ) {
  1529. material.normalScale.y = - material.normalScale.y;
  1530. }
  1531. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1532. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1533. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1534. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  1535. assignExtrasToUserData( material, materialDef );
  1536. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1537. return material;
  1538. } );
  1539. };
  1540. /**
  1541. * @param {THREE.BufferGeometry} geometry
  1542. * @param {GLTF.Primitive} primitiveDef
  1543. * @param {GLTFParser} parser
  1544. * @return {Promise<THREE.BufferGeometry>}
  1545. */
  1546. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1547. var attributes = primitiveDef.attributes;
  1548. var pending = [];
  1549. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1550. return parser.getDependency( 'accessor', accessorIndex )
  1551. .then( function ( accessor ) {
  1552. geometry.addAttribute( attributeName, accessor );
  1553. } );
  1554. }
  1555. for ( var gltfAttributeName in attributes ) {
  1556. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ];
  1557. if ( ! threeAttributeName ) continue;
  1558. // Skip attributes already provided by e.g. Draco extension.
  1559. if ( threeAttributeName in geometry.attributes ) continue;
  1560. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1561. }
  1562. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1563. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1564. geometry.setIndex( accessor );
  1565. } );
  1566. pending.push( accessor );
  1567. }
  1568. assignExtrasToUserData( geometry, primitiveDef );
  1569. return Promise.all( pending ).then( function () {
  1570. return primitiveDef.targets !== undefined
  1571. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1572. : geometry;
  1573. } );
  1574. }
  1575. /**
  1576. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1577. *
  1578. * Creates BufferGeometries from primitives.
  1579. * If we can build a single BufferGeometry with .groups from multiple primitives, returns one BufferGeometry.
  1580. * Otherwise, returns BufferGeometries without .groups as many as primitives.
  1581. *
  1582. * @param {Array<GLTF.Primitive>} primitives
  1583. * @return {Promise<Array<THREE.BufferGeometry>>}
  1584. */
  1585. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1586. var parser = this;
  1587. var extensions = this.extensions;
  1588. var cache = this.primitiveCache;
  1589. var isMultiPass = isMultiPassGeometry( primitives );
  1590. var originalPrimitives;
  1591. if ( isMultiPass ) {
  1592. originalPrimitives = primitives; // save original primitives and use later
  1593. // We build a single BufferGeometry with .groups from multiple primitives
  1594. // because all primitives share the same attributes/morph/mode and have indices.
  1595. primitives = [ primitives[ 0 ] ];
  1596. // Sets .groups and combined indices to a geometry later in this method.
  1597. }
  1598. var pending = [];
  1599. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1600. var primitive = primitives[ i ];
  1601. // See if we've already created this geometry
  1602. var cached = getCachedGeometry( cache, primitive );
  1603. if ( cached ) {
  1604. // Use the cached geometry if it exists
  1605. pending.push( cached );
  1606. } else {
  1607. var geometryPromise;
  1608. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1609. // Use DRACO geometry if available
  1610. geometryPromise = extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1611. .decodePrimitive( primitive, parser )
  1612. .then( function ( geometry ) {
  1613. return addPrimitiveAttributes( geometry, primitive, parser );
  1614. } );
  1615. } else {
  1616. // Otherwise create a new geometry
  1617. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1618. }
  1619. // Cache this geometry
  1620. cache.push( { primitive: primitive, promise: geometryPromise } );
  1621. pending.push( geometryPromise );
  1622. }
  1623. }
  1624. return Promise.all( pending ).then( function ( geometries ) {
  1625. if ( isMultiPass ) {
  1626. var baseGeometry = geometries[ 0 ];
  1627. // See if we've already created this combined geometry
  1628. var cache = parser.multiPassGeometryCache;
  1629. var cached = getCachedMultiPassGeometry( cache, baseGeometry, originalPrimitives );
  1630. if ( cached !== null ) return [ cached.geometry ];
  1631. // Cloning geometry because of index override.
  1632. // Attributes can be reused so cloning by myself here.
  1633. var geometry = new THREE.BufferGeometry();
  1634. geometry.name = baseGeometry.name;
  1635. geometry.userData = baseGeometry.userData;
  1636. for ( var key in baseGeometry.attributes ) geometry.addAttribute( key, baseGeometry.attributes[ key ] );
  1637. for ( var key in baseGeometry.morphAttributes ) geometry.morphAttributes[ key ] = baseGeometry.morphAttributes[ key ];
  1638. var pendingIndices = [];
  1639. for ( var i = 0, il = originalPrimitives.length; i < il; i ++ ) {
  1640. pendingIndices.push( parser.getDependency( 'accessor', originalPrimitives[ i ].indices ) );
  1641. }
  1642. return Promise.all( pendingIndices ).then( function ( accessors ) {
  1643. var indices = [];
  1644. var offset = 0;
  1645. for ( var i = 0, il = originalPrimitives.length; i < il; i ++ ) {
  1646. var accessor = accessors[ i ];
  1647. for ( var j = 0, jl = accessor.count; j < jl; j ++ ) indices.push( accessor.array[ j ] );
  1648. geometry.addGroup( offset, accessor.count, i );
  1649. offset += accessor.count;
  1650. }
  1651. geometry.setIndex( indices );
  1652. cache.push( { geometry: geometry, baseGeometry: baseGeometry, primitives: originalPrimitives } );
  1653. return [ geometry ];
  1654. } );
  1655. } else if ( geometries.length > 1 && THREE.BufferGeometryUtils !== undefined ) {
  1656. // Tries to merge geometries with BufferGeometryUtils if possible
  1657. for ( var i = 1, il = primitives.length; i < il; i ++ ) {
  1658. // can't merge if draw mode is different
  1659. if ( primitives[ 0 ].mode !== primitives[ i ].mode ) return geometries;
  1660. }
  1661. // See if we've already created this combined geometry
  1662. var cache = parser.multiplePrimitivesCache;
  1663. var cached = getCachedCombinedGeometry( cache, geometries );
  1664. if ( cached ) {
  1665. if ( cached.geometry !== null ) return [ cached.geometry ];
  1666. } else {
  1667. var geometry = THREE.BufferGeometryUtils.mergeBufferGeometries( geometries, true );
  1668. cache.push( { geometry: geometry, baseGeometries: geometries } );
  1669. if ( geometry !== null ) return [ geometry ];
  1670. }
  1671. }
  1672. return geometries;
  1673. } );
  1674. };
  1675. /**
  1676. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1677. * @param {number} meshIndex
  1678. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1679. */
  1680. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1681. var parser = this;
  1682. var json = this.json;
  1683. var extensions = this.extensions;
  1684. var meshDef = json.meshes[ meshIndex ];
  1685. var primitives = meshDef.primitives;
  1686. var pending = [];
  1687. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1688. var material = primitives[ i ].material === undefined
  1689. ? createDefaultMaterial()
  1690. : this.getDependency( 'material', primitives[ i ].material );
  1691. pending.push( material );
  1692. }
  1693. return Promise.all( pending ).then( function ( originalMaterials ) {
  1694. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  1695. var isMultiMaterial = geometries.length === 1 && geometries[ 0 ].groups.length > 0;
  1696. var meshes = [];
  1697. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1698. var geometry = geometries[ i ];
  1699. var primitive = primitives[ i ];
  1700. // 1. create Mesh
  1701. var mesh;
  1702. var material = isMultiMaterial ? originalMaterials : originalMaterials[ i ];
  1703. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1704. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1705. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1706. primitive.mode === undefined ) {
  1707. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  1708. mesh = meshDef.isSkinnedMesh === true
  1709. ? new THREE.SkinnedMesh( geometry, material )
  1710. : new THREE.Mesh( geometry, material );
  1711. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1712. mesh.drawMode = THREE.TriangleStripDrawMode;
  1713. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1714. mesh.drawMode = THREE.TriangleFanDrawMode;
  1715. }
  1716. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1717. mesh = new THREE.LineSegments( geometry, material );
  1718. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1719. mesh = new THREE.Line( geometry, material );
  1720. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1721. mesh = new THREE.LineLoop( geometry, material );
  1722. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1723. mesh = new THREE.Points( geometry, material );
  1724. } else {
  1725. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1726. }
  1727. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1728. updateMorphTargets( mesh, meshDef );
  1729. }
  1730. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1731. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1732. assignExtrasToUserData( mesh, meshDef );
  1733. meshes.push( mesh );
  1734. // 2. update Material depending on Mesh and BufferGeometry
  1735. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  1736. var useVertexColors = geometry.attributes.color !== undefined;
  1737. var useFlatShading = geometry.attributes.normal === undefined;
  1738. var useSkinning = mesh.isSkinnedMesh === true;
  1739. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1740. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1741. for ( var j = 0, jl = materials.length; j < jl; j ++ ) {
  1742. var material = materials[ j ];
  1743. if ( mesh.isPoints ) {
  1744. var cacheKey = 'PointsMaterial:' + material.uuid;
  1745. var pointsMaterial = parser.cache.get( cacheKey );
  1746. if ( ! pointsMaterial ) {
  1747. pointsMaterial = new THREE.PointsMaterial();
  1748. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1749. pointsMaterial.color.copy( material.color );
  1750. pointsMaterial.map = material.map;
  1751. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  1752. parser.cache.add( cacheKey, pointsMaterial );
  1753. }
  1754. material = pointsMaterial;
  1755. } else if ( mesh.isLine ) {
  1756. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1757. var lineMaterial = parser.cache.get( cacheKey );
  1758. if ( ! lineMaterial ) {
  1759. lineMaterial = new THREE.LineBasicMaterial();
  1760. THREE.Material.prototype.copy.call( lineMaterial, material );
  1761. lineMaterial.color.copy( material.color );
  1762. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  1763. parser.cache.add( cacheKey, lineMaterial );
  1764. }
  1765. material = lineMaterial;
  1766. }
  1767. // Clone the material if it will be modified
  1768. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1769. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1770. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1771. if ( useSkinning ) cacheKey += 'skinning:';
  1772. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1773. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1774. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1775. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1776. var cachedMaterial = parser.cache.get( cacheKey );
  1777. if ( ! cachedMaterial ) {
  1778. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  1779. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  1780. : material.clone();
  1781. if ( useSkinning ) cachedMaterial.skinning = true;
  1782. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  1783. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1784. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1785. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1786. parser.cache.add( cacheKey, cachedMaterial );
  1787. }
  1788. material = cachedMaterial;
  1789. }
  1790. materials[ j ] = material;
  1791. // workarounds for mesh and geometry
  1792. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1793. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1794. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1795. }
  1796. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1797. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  1798. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1799. }
  1800. }
  1801. mesh.material = isMultiMaterial ? materials : materials[ 0 ];
  1802. }
  1803. if ( meshes.length === 1 ) {
  1804. return meshes[ 0 ];
  1805. }
  1806. var group = new THREE.Group();
  1807. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1808. group.add( meshes[ i ] );
  1809. }
  1810. return group;
  1811. } );
  1812. } );
  1813. };
  1814. /**
  1815. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1816. * @param {number} cameraIndex
  1817. * @return {Promise<THREE.Camera>}
  1818. */
  1819. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1820. var camera;
  1821. var cameraDef = this.json.cameras[ cameraIndex ];
  1822. var params = cameraDef[ cameraDef.type ];
  1823. if ( ! params ) {
  1824. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1825. return;
  1826. }
  1827. if ( cameraDef.type === 'perspective' ) {
  1828. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1829. } else if ( cameraDef.type === 'orthographic' ) {
  1830. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1831. }
  1832. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1833. assignExtrasToUserData( camera, cameraDef );
  1834. return Promise.resolve( camera );
  1835. };
  1836. /**
  1837. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1838. * @param {number} skinIndex
  1839. * @return {Promise<Object>}
  1840. */
  1841. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1842. var skinDef = this.json.skins[ skinIndex ];
  1843. var skinEntry = { joints: skinDef.joints };
  1844. if ( skinDef.inverseBindMatrices === undefined ) {
  1845. return Promise.resolve( skinEntry );
  1846. }
  1847. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1848. skinEntry.inverseBindMatrices = accessor;
  1849. return skinEntry;
  1850. } );
  1851. };
  1852. /**
  1853. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1854. * @param {number} animationIndex
  1855. * @return {Promise<THREE.AnimationClip>}
  1856. */
  1857. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1858. var json = this.json;
  1859. var animationDef = json.animations[ animationIndex ];
  1860. var pendingNodes = [];
  1861. var pendingInputAccessors = [];
  1862. var pendingOutputAccessors = [];
  1863. var pendingSamplers = [];
  1864. var pendingTargets = [];
  1865. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1866. var channel = animationDef.channels[ i ];
  1867. var sampler = animationDef.samplers[ channel.sampler ];
  1868. var target = channel.target;
  1869. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1870. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1871. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1872. pendingNodes.push( this.getDependency( 'node', name ) );
  1873. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  1874. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  1875. pendingSamplers.push( sampler );
  1876. pendingTargets.push( target );
  1877. }
  1878. return Promise.all( [
  1879. Promise.all( pendingNodes ),
  1880. Promise.all( pendingInputAccessors ),
  1881. Promise.all( pendingOutputAccessors ),
  1882. Promise.all( pendingSamplers ),
  1883. Promise.all( pendingTargets )
  1884. ] ).then( function ( dependencies ) {
  1885. var nodes = dependencies[ 0 ];
  1886. var inputAccessors = dependencies[ 1 ];
  1887. var outputAccessors = dependencies[ 2 ];
  1888. var samplers = dependencies[ 3 ];
  1889. var targets = dependencies[ 4 ];
  1890. var tracks = [];
  1891. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  1892. var node = nodes[ i ];
  1893. var inputAccessor = inputAccessors[ i ];
  1894. var outputAccessor = outputAccessors[ i ];
  1895. var sampler = samplers[ i ];
  1896. var target = targets[ i ];
  1897. if ( node === undefined ) continue;
  1898. node.updateMatrix();
  1899. node.matrixAutoUpdate = true;
  1900. var TypedKeyframeTrack;
  1901. switch ( PATH_PROPERTIES[ target.path ] ) {
  1902. case PATH_PROPERTIES.weights:
  1903. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1904. break;
  1905. case PATH_PROPERTIES.rotation:
  1906. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1907. break;
  1908. case PATH_PROPERTIES.position:
  1909. case PATH_PROPERTIES.scale:
  1910. default:
  1911. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1912. break;
  1913. }
  1914. var targetName = node.name ? node.name : node.uuid;
  1915. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1916. var targetNames = [];
  1917. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1918. // node can be THREE.Group here but
  1919. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1920. // the property of a mesh object under group.
  1921. node.traverse( function ( object ) {
  1922. if ( object.isMesh === true && object.morphTargetInfluences ) {
  1923. targetNames.push( object.name ? object.name : object.uuid );
  1924. }
  1925. } );
  1926. } else {
  1927. targetNames.push( targetName );
  1928. }
  1929. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1930. // buffers before creating a truncated copy to keep. Because buffers may
  1931. // be reused by other tracks, make copies here.
  1932. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1933. var track = new TypedKeyframeTrack(
  1934. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1935. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1936. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1937. interpolation
  1938. );
  1939. // Here is the trick to enable custom interpolation.
  1940. // Overrides .createInterpolant in a factory method which creates custom interpolation.
  1941. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1942. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  1943. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1944. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1945. // must be divided by three to get the interpolant's sampleSize argument.
  1946. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1947. };
  1948. // Workaround, provide an alternate way to know if the interpolant type is cubis spline to track.
  1949. // track.getInterpolation() doesn't return valid value for custom interpolant.
  1950. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  1951. }
  1952. tracks.push( track );
  1953. }
  1954. }
  1955. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  1956. return new THREE.AnimationClip( name, undefined, tracks );
  1957. } );
  1958. };
  1959. /**
  1960. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1961. * @param {number} nodeIndex
  1962. * @return {Promise<THREE.Object3D>}
  1963. */
  1964. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1965. var json = this.json;
  1966. var extensions = this.extensions;
  1967. var parser = this;
  1968. var meshReferences = json.meshReferences;
  1969. var meshUses = json.meshUses;
  1970. var nodeDef = json.nodes[ nodeIndex ];
  1971. return new Promise( function ( resolve ) {
  1972. // .isBone isn't in glTF spec. See .markDefs
  1973. if ( nodeDef.isBone === true ) {
  1974. resolve( new THREE.Bone() );
  1975. } else if ( nodeDef.mesh !== undefined ) {
  1976. parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  1977. var node;
  1978. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1979. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  1980. node = mesh.clone();
  1981. node.name += '_instance_' + instanceNum;
  1982. // onBeforeRender copy for Specular-Glossiness
  1983. node.onBeforeRender = mesh.onBeforeRender;
  1984. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  1985. node.children[ i ].name += '_instance_' + instanceNum;
  1986. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  1987. }
  1988. } else {
  1989. node = mesh;
  1990. }
  1991. resolve( node );
  1992. } );
  1993. } else if ( nodeDef.camera !== undefined ) {
  1994. parser.getDependency( 'camera', nodeDef.camera ).then( resolve );
  1995. } else if ( nodeDef.extensions
  1996. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  1997. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  1998. parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ).then( resolve );
  1999. } else {
  2000. resolve( new THREE.Object3D() );
  2001. }
  2002. } ).then( function ( node ) {
  2003. if ( nodeDef.name !== undefined ) {
  2004. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  2005. }
  2006. assignExtrasToUserData( node, nodeDef );
  2007. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  2008. if ( nodeDef.matrix !== undefined ) {
  2009. var matrix = new THREE.Matrix4();
  2010. matrix.fromArray( nodeDef.matrix );
  2011. node.applyMatrix( matrix );
  2012. } else {
  2013. if ( nodeDef.translation !== undefined ) {
  2014. node.position.fromArray( nodeDef.translation );
  2015. }
  2016. if ( nodeDef.rotation !== undefined ) {
  2017. node.quaternion.fromArray( nodeDef.rotation );
  2018. }
  2019. if ( nodeDef.scale !== undefined ) {
  2020. node.scale.fromArray( nodeDef.scale );
  2021. }
  2022. }
  2023. return node;
  2024. } );
  2025. };
  2026. /**
  2027. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  2028. * @param {number} sceneIndex
  2029. * @return {Promise<THREE.Scene>}
  2030. */
  2031. GLTFParser.prototype.loadScene = function () {
  2032. // scene node hierachy builder
  2033. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  2034. var nodeDef = json.nodes[ nodeId ];
  2035. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  2036. if ( nodeDef.skin === undefined ) return node;
  2037. // build skeleton here as well
  2038. var skinEntry;
  2039. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  2040. skinEntry = skin;
  2041. var pendingJoints = [];
  2042. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  2043. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  2044. }
  2045. return Promise.all( pendingJoints );
  2046. } ).then( function ( jointNodes ) {
  2047. var meshes = node.isGroup === true ? node.children : [ node ];
  2048. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  2049. var mesh = meshes[ i ];
  2050. var bones = [];
  2051. var boneInverses = [];
  2052. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  2053. var jointNode = jointNodes[ j ];
  2054. if ( jointNode ) {
  2055. bones.push( jointNode );
  2056. var mat = new THREE.Matrix4();
  2057. if ( skinEntry.inverseBindMatrices !== undefined ) {
  2058. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  2059. }
  2060. boneInverses.push( mat );
  2061. } else {
  2062. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  2063. }
  2064. }
  2065. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  2066. };
  2067. return node;
  2068. } );
  2069. } ).then( function ( node ) {
  2070. // build node hierachy
  2071. parentObject.add( node );
  2072. var pending = [];
  2073. if ( nodeDef.children ) {
  2074. var children = nodeDef.children;
  2075. for ( var i = 0, il = children.length; i < il; i ++ ) {
  2076. var child = children[ i ];
  2077. pending.push( buildNodeHierachy( child, node, json, parser ) );
  2078. }
  2079. }
  2080. return Promise.all( pending );
  2081. } );
  2082. }
  2083. return function loadScene( sceneIndex ) {
  2084. var json = this.json;
  2085. var extensions = this.extensions;
  2086. var sceneDef = this.json.scenes[ sceneIndex ];
  2087. var parser = this;
  2088. var scene = new THREE.Scene();
  2089. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  2090. assignExtrasToUserData( scene, sceneDef );
  2091. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  2092. var nodeIds = sceneDef.nodes || [];
  2093. var pending = [];
  2094. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  2095. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  2096. }
  2097. return Promise.all( pending ).then( function () {
  2098. return scene;
  2099. } );
  2100. };
  2101. }();
  2102. return GLTFLoader;
  2103. } )();