/examples/lib/GLTFLoader.module.js

https://github.com/Mugen87/yuka · JavaScript · 3186 lines · 1695 code · 1202 blank · 289 comment · 365 complexity · c913f90dcacf068f68b414d2658a67f1 MD5 · raw file

Large files are truncated click here to view the full file

  1. import * as THREE from './three.module.js';
  2. /**
  3. * @author Rich Tibbett / https://github.com/richtr
  4. * @author mrdoob / http://mrdoob.com/
  5. * @author Tony Parisi / http://www.tonyparisi.com/
  6. * @author Takahiro / https://github.com/takahirox
  7. * @author Don McCurdy / https://www.donmccurdy.com
  8. */
  9. function GLTFLoader( manager ) {
  10. THREE.Loader.call( this, manager );
  11. this.dracoLoader = null;
  12. this.ddsLoader = null;
  13. }
  14. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  15. constructor: GLTFLoader,
  16. load: function ( url, onLoad, onProgress, onError ) {
  17. var scope = this;
  18. var resourcePath;
  19. if ( this.resourcePath !== '' ) {
  20. resourcePath = this.resourcePath;
  21. } else if ( this.path !== '' ) {
  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.itemError( url );
  37. scope.manager.itemEnd( url );
  38. };
  39. var loader = new THREE.FileLoader( scope.manager );
  40. loader.setPath( this.path );
  41. loader.setResponseType( 'arraybuffer' );
  42. if ( scope.crossOrigin === 'use-credentials' ) {
  43. loader.setWithCredentials( true );
  44. }
  45. loader.load( url, function ( data ) {
  46. try {
  47. scope.parse( data, resourcePath, function ( gltf ) {
  48. onLoad( gltf );
  49. scope.manager.itemEnd( url );
  50. }, _onError );
  51. } catch ( e ) {
  52. _onError( e );
  53. }
  54. }, onProgress, _onError );
  55. },
  56. setDRACOLoader: function ( dracoLoader ) {
  57. this.dracoLoader = dracoLoader;
  58. return this;
  59. },
  60. setDDSLoader: function ( ddsLoader ) {
  61. this.ddsLoader = ddsLoader;
  62. return this;
  63. },
  64. parse: function ( data, path, onLoad, onError ) {
  65. var content;
  66. var extensions = {};
  67. if ( typeof data === 'string' ) {
  68. content = data;
  69. } else {
  70. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  71. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  72. try {
  73. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  74. } catch ( error ) {
  75. if ( onError ) onError( error );
  76. return;
  77. }
  78. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  79. } else {
  80. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  81. }
  82. }
  83. var json = JSON.parse( content );
  84. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  85. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  86. return;
  87. }
  88. if ( json.extensionsUsed ) {
  89. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  90. var extensionName = json.extensionsUsed[ i ];
  91. var extensionsRequired = json.extensionsRequired || [];
  92. switch ( extensionName ) {
  93. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  94. extensions[ extensionName ] = new GLTFLightsExtension( json );
  95. break;
  96. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  97. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  98. break;
  99. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  100. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  101. break;
  102. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  103. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  104. break;
  105. case EXTENSIONS.MSFT_TEXTURE_DDS:
  106. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( this.ddsLoader );
  107. break;
  108. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  109. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension();
  110. break;
  111. default:
  112. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  113. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  114. }
  115. }
  116. }
  117. }
  118. var parser = new GLTFParser( json, extensions, {
  119. path: path || this.resourcePath || '',
  120. crossOrigin: this.crossOrigin,
  121. manager: this.manager
  122. } );
  123. parser.parse( onLoad, onError );
  124. }
  125. } );
  126. /* GLTFREGISTRY */
  127. function GLTFRegistry() {
  128. var objects = {};
  129. return {
  130. get: function ( key ) {
  131. return objects[ key ];
  132. },
  133. add: function ( key, object ) {
  134. objects[ key ] = object;
  135. },
  136. remove: function ( key ) {
  137. delete objects[ key ];
  138. },
  139. removeAll: function () {
  140. objects = {};
  141. }
  142. };
  143. }
  144. /*********************************/
  145. /********** EXTENSIONS ***********/
  146. /*********************************/
  147. var EXTENSIONS = {
  148. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  149. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  150. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  151. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  152. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  153. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  154. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  155. };
  156. /**
  157. * DDS Texture Extension
  158. *
  159. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  160. *
  161. */
  162. function GLTFTextureDDSExtension( ddsLoader ) {
  163. if ( ! ddsLoader ) {
  164. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  165. }
  166. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  167. this.ddsLoader = ddsLoader;
  168. }
  169. /**
  170. * Punctual Lights Extension
  171. *
  172. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  173. */
  174. function GLTFLightsExtension( json ) {
  175. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  176. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  177. this.lightDefs = extension.lights || [];
  178. }
  179. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  180. var lightDef = this.lightDefs[ lightIndex ];
  181. var lightNode;
  182. var color = new THREE.Color( 0xffffff );
  183. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  184. var range = lightDef.range !== undefined ? lightDef.range : 0;
  185. switch ( lightDef.type ) {
  186. case 'directional':
  187. lightNode = new THREE.DirectionalLight( color );
  188. lightNode.target.position.set( 0, 0, - 1 );
  189. lightNode.add( lightNode.target );
  190. break;
  191. case 'point':
  192. lightNode = new THREE.PointLight( color );
  193. lightNode.distance = range;
  194. break;
  195. case 'spot':
  196. lightNode = new THREE.SpotLight( color );
  197. lightNode.distance = range;
  198. // Handle spotlight properties.
  199. lightDef.spot = lightDef.spot || {};
  200. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  201. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  202. lightNode.angle = lightDef.spot.outerConeAngle;
  203. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  204. lightNode.target.position.set( 0, 0, - 1 );
  205. lightNode.add( lightNode.target );
  206. break;
  207. default:
  208. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  209. }
  210. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  211. // here, because node-level parsing will only override position if explicitly specified.
  212. lightNode.position.set( 0, 0, 0 );
  213. lightNode.decay = 2;
  214. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  215. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  216. return Promise.resolve( lightNode );
  217. };
  218. /**
  219. * Unlit Materials Extension
  220. *
  221. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  222. */
  223. function GLTFMaterialsUnlitExtension() {
  224. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  225. }
  226. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  227. return THREE.MeshBasicMaterial;
  228. };
  229. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  230. var pending = [];
  231. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  232. materialParams.opacity = 1.0;
  233. var metallicRoughness = materialDef.pbrMetallicRoughness;
  234. if ( metallicRoughness ) {
  235. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  236. var array = metallicRoughness.baseColorFactor;
  237. materialParams.color.fromArray( array );
  238. materialParams.opacity = array[ 3 ];
  239. }
  240. if ( metallicRoughness.baseColorTexture !== undefined ) {
  241. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  242. }
  243. }
  244. return Promise.all( pending );
  245. };
  246. /* BINARY EXTENSION */
  247. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  248. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  249. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  250. function GLTFBinaryExtension( data ) {
  251. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  252. this.content = null;
  253. this.body = null;
  254. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  255. this.header = {
  256. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  257. version: headerView.getUint32( 4, true ),
  258. length: headerView.getUint32( 8, true )
  259. };
  260. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  261. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  262. } else if ( this.header.version < 2.0 ) {
  263. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  264. }
  265. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  266. var chunkIndex = 0;
  267. while ( chunkIndex < chunkView.byteLength ) {
  268. var chunkLength = chunkView.getUint32( chunkIndex, true );
  269. chunkIndex += 4;
  270. var chunkType = chunkView.getUint32( chunkIndex, true );
  271. chunkIndex += 4;
  272. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  273. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  274. this.content = THREE.LoaderUtils.decodeText( contentArray );
  275. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  276. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  277. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  278. }
  279. // Clients must ignore chunks with unknown types.
  280. chunkIndex += chunkLength;
  281. }
  282. if ( this.content === null ) {
  283. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  284. }
  285. }
  286. /**
  287. * DRACO Mesh Compression Extension
  288. *
  289. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  290. */
  291. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  292. if ( ! dracoLoader ) {
  293. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  294. }
  295. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  296. this.json = json;
  297. this.dracoLoader = dracoLoader;
  298. }
  299. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  300. var json = this.json;
  301. var dracoLoader = this.dracoLoader;
  302. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  303. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  304. var threeAttributeMap = {};
  305. var attributeNormalizedMap = {};
  306. var attributeTypeMap = {};
  307. for ( var attributeName in gltfAttributeMap ) {
  308. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  309. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  310. }
  311. for ( attributeName in primitive.attributes ) {
  312. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  313. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  314. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  315. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  316. attributeTypeMap[ threeAttributeName ] = componentType;
  317. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  318. }
  319. }
  320. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  321. return new Promise( function ( resolve ) {
  322. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  323. for ( var attributeName in geometry.attributes ) {
  324. var attribute = geometry.attributes[ attributeName ];
  325. var normalized = attributeNormalizedMap[ attributeName ];
  326. if ( normalized !== undefined ) attribute.normalized = normalized;
  327. }
  328. resolve( geometry );
  329. }, threeAttributeMap, attributeTypeMap );
  330. } );
  331. } );
  332. };
  333. /**
  334. * Texture Transform Extension
  335. *
  336. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  337. */
  338. function GLTFTextureTransformExtension() {
  339. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  340. }
  341. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  342. texture = texture.clone();
  343. if ( transform.offset !== undefined ) {
  344. texture.offset.fromArray( transform.offset );
  345. }
  346. if ( transform.rotation !== undefined ) {
  347. texture.rotation = transform.rotation;
  348. }
  349. if ( transform.scale !== undefined ) {
  350. texture.repeat.fromArray( transform.scale );
  351. }
  352. if ( transform.texCoord !== undefined ) {
  353. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  354. }
  355. texture.needsUpdate = true;
  356. return texture;
  357. };
  358. /**
  359. * Specular-Glossiness Extension
  360. *
  361. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  362. */
  363. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  364. return {
  365. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  366. specularGlossinessParams: [
  367. 'color',
  368. 'map',
  369. 'lightMap',
  370. 'lightMapIntensity',
  371. 'aoMap',
  372. 'aoMapIntensity',
  373. 'emissive',
  374. 'emissiveIntensity',
  375. 'emissiveMap',
  376. 'bumpMap',
  377. 'bumpScale',
  378. 'normalMap',
  379. 'displacementMap',
  380. 'displacementScale',
  381. 'displacementBias',
  382. 'specularMap',
  383. 'specular',
  384. 'glossinessMap',
  385. 'glossiness',
  386. 'alphaMap',
  387. 'envMap',
  388. 'envMapIntensity',
  389. 'refractionRatio',
  390. ],
  391. getMaterialType: function () {
  392. return THREE.ShaderMaterial;
  393. },
  394. extendParams: function ( materialParams, materialDef, parser ) {
  395. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  396. var shader = THREE.ShaderLib[ 'standard' ];
  397. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  398. var specularMapParsFragmentChunk = [
  399. '#ifdef USE_SPECULARMAP',
  400. ' uniform sampler2D specularMap;',
  401. '#endif'
  402. ].join( '\n' );
  403. var glossinessMapParsFragmentChunk = [
  404. '#ifdef USE_GLOSSINESSMAP',
  405. ' uniform sampler2D glossinessMap;',
  406. '#endif'
  407. ].join( '\n' );
  408. var specularMapFragmentChunk = [
  409. 'vec3 specularFactor = specular;',
  410. '#ifdef USE_SPECULARMAP',
  411. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  412. ' texelSpecular = sRGBToLinear( texelSpecular );',
  413. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  414. ' specularFactor *= texelSpecular.rgb;',
  415. '#endif'
  416. ].join( '\n' );
  417. var glossinessMapFragmentChunk = [
  418. 'float glossinessFactor = glossiness;',
  419. '#ifdef USE_GLOSSINESSMAP',
  420. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  421. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  422. ' glossinessFactor *= texelGlossiness.a;',
  423. '#endif'
  424. ].join( '\n' );
  425. var lightPhysicalFragmentChunk = [
  426. 'PhysicalMaterial material;',
  427. 'material.diffuseColor = diffuseColor.rgb;',
  428. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  429. 'material.specularColor = specularFactor.rgb;',
  430. ].join( '\n' );
  431. var fragmentShader = shader.fragmentShader
  432. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  433. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  434. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  435. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  436. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  437. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  438. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  439. delete uniforms.roughness;
  440. delete uniforms.metalness;
  441. delete uniforms.roughnessMap;
  442. delete uniforms.metalnessMap;
  443. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  444. uniforms.glossiness = { value: 0.5 };
  445. uniforms.specularMap = { value: null };
  446. uniforms.glossinessMap = { value: null };
  447. materialParams.vertexShader = shader.vertexShader;
  448. materialParams.fragmentShader = fragmentShader;
  449. materialParams.uniforms = uniforms;
  450. materialParams.defines = { 'STANDARD': '' };
  451. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  452. materialParams.opacity = 1.0;
  453. var pending = [];
  454. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  455. var array = pbrSpecularGlossiness.diffuseFactor;
  456. materialParams.color.fromArray( array );
  457. materialParams.opacity = array[ 3 ];
  458. }
  459. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  460. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  461. }
  462. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  463. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  464. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  465. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  466. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  467. }
  468. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  469. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  470. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  471. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  472. }
  473. return Promise.all( pending );
  474. },
  475. createMaterial: function ( params ) {
  476. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  477. var material = new THREE.ShaderMaterial( {
  478. defines: params.defines,
  479. vertexShader: params.vertexShader,
  480. fragmentShader: params.fragmentShader,
  481. uniforms: params.uniforms,
  482. fog: true,
  483. lights: true,
  484. opacity: params.opacity,
  485. transparent: params.transparent
  486. } );
  487. material.isGLTFSpecularGlossinessMaterial = true;
  488. material.color = params.color;
  489. material.map = params.map === undefined ? null : params.map;
  490. material.lightMap = null;
  491. material.lightMapIntensity = 1.0;
  492. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  493. material.aoMapIntensity = 1.0;
  494. material.emissive = params.emissive;
  495. material.emissiveIntensity = 1.0;
  496. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  497. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  498. material.bumpScale = 1;
  499. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  500. if ( params.normalScale ) material.normalScale = params.normalScale;
  501. material.displacementMap = null;
  502. material.displacementScale = 1;
  503. material.displacementBias = 0;
  504. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  505. material.specular = params.specular;
  506. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  507. material.glossiness = params.glossiness;
  508. material.alphaMap = null;
  509. material.envMap = params.envMap === undefined ? null : params.envMap;
  510. material.envMapIntensity = 1.0;
  511. material.refractionRatio = 0.98;
  512. material.extensions.derivatives = true;
  513. return material;
  514. },
  515. /**
  516. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  517. * copy only properties it knows about or inherits, and misses many properties that would
  518. * normally be defined by MeshStandardMaterial.
  519. *
  520. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  521. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  522. * AND also updating `.onBeforeRender` on the parent mesh.
  523. *
  524. * @param {THREE.ShaderMaterial} source
  525. * @return {THREE.ShaderMaterial}
  526. */
  527. cloneMaterial: function ( source ) {
  528. var target = source.clone();
  529. target.isGLTFSpecularGlossinessMaterial = true;
  530. var params = this.specularGlossinessParams;
  531. for ( var i = 0, il = params.length; i < il; i ++ ) {
  532. var value = source[ params[ i ] ];
  533. target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value;
  534. }
  535. return target;
  536. },
  537. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  538. refreshUniforms: function ( renderer, scene, camera, geometry, material ) {
  539. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  540. return;
  541. }
  542. var uniforms = material.uniforms;
  543. var defines = material.defines;
  544. uniforms.opacity.value = material.opacity;
  545. uniforms.diffuse.value.copy( material.color );
  546. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  547. uniforms.map.value = material.map;
  548. uniforms.specularMap.value = material.specularMap;
  549. uniforms.alphaMap.value = material.alphaMap;
  550. uniforms.lightMap.value = material.lightMap;
  551. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  552. uniforms.aoMap.value = material.aoMap;
  553. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  554. // uv repeat and offset setting priorities
  555. // 1. color map
  556. // 2. specular map
  557. // 3. normal map
  558. // 4. bump map
  559. // 5. alpha map
  560. // 6. emissive map
  561. var uvScaleMap;
  562. if ( material.map ) {
  563. uvScaleMap = material.map;
  564. } else if ( material.specularMap ) {
  565. uvScaleMap = material.specularMap;
  566. } else if ( material.displacementMap ) {
  567. uvScaleMap = material.displacementMap;
  568. } else if ( material.normalMap ) {
  569. uvScaleMap = material.normalMap;
  570. } else if ( material.bumpMap ) {
  571. uvScaleMap = material.bumpMap;
  572. } else if ( material.glossinessMap ) {
  573. uvScaleMap = material.glossinessMap;
  574. } else if ( material.alphaMap ) {
  575. uvScaleMap = material.alphaMap;
  576. } else if ( material.emissiveMap ) {
  577. uvScaleMap = material.emissiveMap;
  578. }
  579. if ( uvScaleMap !== undefined ) {
  580. // backwards compatibility
  581. if ( uvScaleMap.isWebGLRenderTarget ) {
  582. uvScaleMap = uvScaleMap.texture;
  583. }
  584. if ( uvScaleMap.matrixAutoUpdate === true ) {
  585. uvScaleMap.updateMatrix();
  586. }
  587. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  588. }
  589. if ( material.envMap ) {
  590. uniforms.envMap.value = material.envMap;
  591. uniforms.envMapIntensity.value = material.envMapIntensity;
  592. // don't flip CubeTexture envMaps, flip everything else:
  593. // WebGLRenderTargetCube will be flipped for backwards compatibility
  594. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  595. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  596. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  597. uniforms.reflectivity.value = material.reflectivity;
  598. uniforms.refractionRatio.value = material.refractionRatio;
  599. uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel;
  600. }
  601. uniforms.specular.value.copy( material.specular );
  602. uniforms.glossiness.value = material.glossiness;
  603. uniforms.glossinessMap.value = material.glossinessMap;
  604. uniforms.emissiveMap.value = material.emissiveMap;
  605. uniforms.bumpMap.value = material.bumpMap;
  606. uniforms.normalMap.value = material.normalMap;
  607. uniforms.displacementMap.value = material.displacementMap;
  608. uniforms.displacementScale.value = material.displacementScale;
  609. uniforms.displacementBias.value = material.displacementBias;
  610. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  611. defines.USE_GLOSSINESSMAP = '';
  612. // set USE_ROUGHNESSMAP to enable vUv
  613. defines.USE_ROUGHNESSMAP = '';
  614. }
  615. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  616. delete defines.USE_GLOSSINESSMAP;
  617. delete defines.USE_ROUGHNESSMAP;
  618. }
  619. }
  620. };
  621. }
  622. /*********************************/
  623. /********** INTERPOLATION ********/
  624. /*********************************/
  625. // Spline Interpolation
  626. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  627. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  628. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  629. }
  630. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  631. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  632. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  633. // Copies a sample value to the result buffer. See description of glTF
  634. // CUBICSPLINE values layout in interpolate_() function below.
  635. var result = this.resultBuffer,
  636. values = this.sampleValues,
  637. valueSize = this.valueSize,
  638. offset = index * valueSize * 3 + valueSize;
  639. for ( var i = 0; i !== valueSize; i ++ ) {
  640. result[ i ] = values[ offset + i ];
  641. }
  642. return result;
  643. };
  644. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  645. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  646. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  647. var result = this.resultBuffer;
  648. var values = this.sampleValues;
  649. var stride = this.valueSize;
  650. var stride2 = stride * 2;
  651. var stride3 = stride * 3;
  652. var td = t1 - t0;
  653. var p = ( t - t0 ) / td;
  654. var pp = p * p;
  655. var ppp = pp * p;
  656. var offset1 = i1 * stride3;
  657. var offset0 = offset1 - stride3;
  658. var s2 = - 2 * ppp + 3 * pp;
  659. var s3 = ppp - pp;
  660. var s0 = 1 - s2;
  661. var s1 = s3 - pp + p;
  662. // Layout of keyframe output values for CUBICSPLINE animations:
  663. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  664. for ( var i = 0; i !== stride; i ++ ) {
  665. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  666. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  667. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  668. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  669. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  670. }
  671. return result;
  672. };
  673. /*********************************/
  674. /********** INTERNALS ************/
  675. /*********************************/
  676. /* CONSTANTS */
  677. var WEBGL_CONSTANTS = {
  678. FLOAT: 5126,
  679. //FLOAT_MAT2: 35674,
  680. FLOAT_MAT3: 35675,
  681. FLOAT_MAT4: 35676,
  682. FLOAT_VEC2: 35664,
  683. FLOAT_VEC3: 35665,
  684. FLOAT_VEC4: 35666,
  685. LINEAR: 9729,
  686. REPEAT: 10497,
  687. SAMPLER_2D: 35678,
  688. POINTS: 0,
  689. LINES: 1,
  690. LINE_LOOP: 2,
  691. LINE_STRIP: 3,
  692. TRIANGLES: 4,
  693. TRIANGLE_STRIP: 5,
  694. TRIANGLE_FAN: 6,
  695. UNSIGNED_BYTE: 5121,
  696. UNSIGNED_SHORT: 5123
  697. };
  698. var WEBGL_COMPONENT_TYPES = {
  699. 5120: Int8Array,
  700. 5121: Uint8Array,
  701. 5122: Int16Array,
  702. 5123: Uint16Array,
  703. 5125: Uint32Array,
  704. 5126: Float32Array
  705. };
  706. var WEBGL_FILTERS = {
  707. 9728: THREE.NearestFilter,
  708. 9729: THREE.LinearFilter,
  709. 9984: THREE.NearestMipmapNearestFilter,
  710. 9985: THREE.LinearMipmapNearestFilter,
  711. 9986: THREE.NearestMipmapLinearFilter,
  712. 9987: THREE.LinearMipmapLinearFilter
  713. };
  714. var WEBGL_WRAPPINGS = {
  715. 33071: THREE.ClampToEdgeWrapping,
  716. 33648: THREE.MirroredRepeatWrapping,
  717. 10497: THREE.RepeatWrapping
  718. };
  719. var WEBGL_TYPE_SIZES = {
  720. 'SCALAR': 1,
  721. 'VEC2': 2,
  722. 'VEC3': 3,
  723. 'VEC4': 4,
  724. 'MAT2': 4,
  725. 'MAT3': 9,
  726. 'MAT4': 16
  727. };
  728. var ATTRIBUTES = {
  729. POSITION: 'position',
  730. NORMAL: 'normal',
  731. TANGENT: 'tangent',
  732. TEXCOORD_0: 'uv',
  733. TEXCOORD_1: 'uv2',
  734. COLOR_0: 'color',
  735. WEIGHTS_0: 'skinWeight',
  736. JOINTS_0: 'skinIndex',
  737. };
  738. var PATH_PROPERTIES = {
  739. scale: 'scale',
  740. translation: 'position',
  741. rotation: 'quaternion',
  742. weights: 'morphTargetInfluences'
  743. };
  744. var INTERPOLATION = {
  745. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  746. // keyframe track will be initialized with a default interpolation type, then modified.
  747. LINEAR: THREE.InterpolateLinear,
  748. STEP: THREE.InterpolateDiscrete
  749. };
  750. var ALPHA_MODES = {
  751. OPAQUE: 'OPAQUE',
  752. MASK: 'MASK',
  753. BLEND: 'BLEND'
  754. };
  755. var MIME_TYPE_FORMATS = {
  756. 'image/png': THREE.RGBAFormat,
  757. 'image/jpeg': THREE.RGBFormat
  758. };
  759. /* UTILITY FUNCTIONS */
  760. function resolveURL( url, path ) {
  761. // Invalid URL
  762. if ( typeof url !== 'string' || url === '' ) return '';
  763. // Host Relative URL
  764. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  765. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  766. }
  767. // Absolute URL http://,https://,//
  768. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  769. // Data URI
  770. if ( /^data:.*,.*$/i.test( url ) ) return url;
  771. // Blob URL
  772. if ( /^blob:.*$/i.test( url ) ) return url;
  773. // Relative URL
  774. return path + url;
  775. }
  776. var defaultMaterial;
  777. /**
  778. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  779. */
  780. function createDefaultMaterial() {
  781. defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( {
  782. color: 0xFFFFFF,
  783. emissive: 0x000000,
  784. metalness: 1,
  785. roughness: 1,
  786. transparent: false,
  787. depthTest: true,
  788. side: THREE.FrontSide
  789. } );
  790. return defaultMaterial;
  791. }
  792. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  793. // Add unknown glTF extensions to an object's userData.
  794. for ( var name in objectDef.extensions ) {
  795. if ( knownExtensions[ name ] === undefined ) {
  796. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  797. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  798. }
  799. }
  800. }
  801. /**
  802. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  803. * @param {GLTF.definition} gltfDef
  804. */
  805. function assignExtrasToUserData( object, gltfDef ) {
  806. if ( gltfDef.extras !== undefined ) {
  807. if ( typeof gltfDef.extras === 'object' ) {
  808. Object.assign( object.userData, gltfDef.extras );
  809. } else {
  810. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  811. }
  812. }
  813. }
  814. /**
  815. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  816. *
  817. * @param {THREE.BufferGeometry} geometry
  818. * @param {Array<GLTF.Target>} targets
  819. * @param {GLTFParser} parser
  820. * @return {Promise<THREE.BufferGeometry>}
  821. */
  822. function addMorphTargets( geometry, targets, parser ) {
  823. var hasMorphPosition = false;
  824. var hasMorphNormal = false;
  825. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  826. var target = targets[ i ];
  827. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  828. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  829. if ( hasMorphPosition && hasMorphNormal ) break;
  830. }
  831. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  832. var pendingPositionAccessors = [];
  833. var pendingNormalAccessors = [];
  834. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  835. var target = targets[ i ];
  836. if ( hasMorphPosition ) {
  837. var pendingAccessor = target.POSITION !== undefined
  838. ? parser.getDependency( 'accessor', target.POSITION )
  839. : geometry.attributes.position;
  840. pendingPositionAccessors.push( pendingAccessor );
  841. }
  842. if ( hasMorphNormal ) {
  843. var pendingAccessor = target.NORMAL !== undefined
  844. ? parser.getDependency( 'accessor', target.NORMAL )
  845. : geometry.attributes.normal;
  846. pendingNormalAccessors.push( pendingAccessor );
  847. }
  848. }
  849. return Promise.all( [
  850. Promise.all( pendingPositionAccessors ),
  851. Promise.all( pendingNormalAccessors )
  852. ] ).then( function ( accessors ) {
  853. var morphPositions = accessors[ 0 ];
  854. var morphNormals = accessors[ 1 ];
  855. // Clone morph target accessors before modifying them.
  856. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) {
  857. if ( geometry.attributes.position === morphPositions[ i ] ) continue;
  858. morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] );
  859. }
  860. for ( var i = 0, il = morphNormals.length; i < il; i ++ ) {
  861. if ( geometry.attributes.normal === morphNormals[ i ] ) continue;
  862. morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] );
  863. }
  864. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  865. var target = targets[ i ];
  866. var attributeName = 'morphTarget' + i;
  867. if ( hasMorphPosition ) {
  868. // Three.js morph position is absolute value. The formula is
  869. // basePosition
  870. // + weight0 * ( morphPosition0 - basePosition )
  871. // + weight1 * ( morphPosition1 - basePosition )
  872. // ...
  873. // while the glTF one is relative
  874. // basePosition
  875. // + weight0 * glTFmorphPosition0
  876. // + weight1 * glTFmorphPosition1
  877. // ...
  878. // then we need to convert from relative to absolute here.
  879. if ( target.POSITION !== undefined ) {
  880. var positionAttribute = morphPositions[ i ];
  881. positionAttribute.name = attributeName;
  882. var position = geometry.attributes.position;
  883. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  884. positionAttribute.setXYZ(
  885. j,
  886. positionAttribute.getX( j ) + position.getX( j ),
  887. positionAttribute.getY( j ) + position.getY( j ),
  888. positionAttribute.getZ( j ) + position.getZ( j )
  889. );
  890. }
  891. }
  892. }
  893. if ( hasMorphNormal ) {
  894. // see target.POSITION's comment
  895. if ( target.NORMAL !== undefined ) {
  896. var normalAttribute = morphNormals[ i ];
  897. normalAttribute.name = attributeName;
  898. var normal = geometry.attributes.normal;
  899. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  900. normalAttribute.setXYZ(
  901. j,
  902. normalAttribute.getX( j ) + normal.getX( j ),
  903. normalAttribute.getY( j ) + normal.getY( j ),
  904. normalAttribute.getZ( j ) + normal.getZ( j )
  905. );
  906. }
  907. }
  908. }
  909. }
  910. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  911. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  912. return geometry;
  913. } );
  914. }
  915. /**
  916. * @param {THREE.Mesh} mesh
  917. * @param {GLTF.Mesh} meshDef
  918. */
  919. function updateMorphTargets( mesh, meshDef ) {
  920. mesh.updateMorphTargets();
  921. if ( meshDef.weights !== undefined ) {
  922. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  923. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  924. }
  925. }
  926. // .extras has user-defined data, so check that .extras.targetNames is an array.
  927. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  928. var targetNames = meshDef.extras.targetNames;
  929. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  930. mesh.morphTargetDictionary = {};
  931. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  932. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  933. }
  934. } else {
  935. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  936. }
  937. }
  938. }
  939. function createPrimitiveKey( primitiveDef ) {
  940. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  941. var geometryKey;
  942. if ( dracoExtension ) {
  943. geometryKey = 'draco:' + dracoExtension.bufferView
  944. + ':' + dracoExtension.indices
  945. + ':' + createAttributesKey( dracoExtension.attributes );
  946. } else {
  947. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  948. }
  949. return geometryKey;
  950. }
  951. function createAttributesKey( attributes ) {
  952. var attributesKey = '';
  953. var keys = Object.keys( attributes ).sort();
  954. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  955. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  956. }
  957. return attributesKey;
  958. }
  959. function cloneBufferAttribute( attribute ) {
  960. if ( attribute.isInterleavedBufferAttribute ) {
  961. var count = attribute.count;
  962. var itemSize = attribute.itemSize;
  963. var array = attribute.array.slice( 0, count * itemSize );
  964. for ( var i = 0, j = 0; i < count; ++ i ) {
  965. array[ j ++ ] = attribute.getX( i );
  966. if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i );
  967. if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i );
  968. if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i );
  969. }
  970. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  971. }
  972. return attribute.clone();
  973. }
  974. /* GLTF PARSER */
  975. function GLTFParser( json, extensions, options ) {
  976. this.json = json || {};
  977. this.extensions = extensions || {};
  978. this.options = options || {};
  979. // loader object cache
  980. this.cache = new GLTFRegistry();
  981. // BufferGeometry caching
  982. this.primitiveCache = {};
  983. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  984. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  985. this.fileLoader = new THREE.FileLoader( this.options.manager );
  986. this.fileLoader.setResponseType( 'arraybuffer' );
  987. if ( this.options.crossOrigin === 'use-credentials' ) {
  988. this.fileLoader.setWithCredentials( true );
  989. }
  990. }
  991. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  992. var parser = this;
  993. var json = this.json;
  994. var extensions = this.extensions;
  995. // Clear the loader cache
  996. this.cache.removeAll();
  997. // Mark the special nodes/meshes in json for efficient parse
  998. this.markDefs();
  999. Promise.all( [
  1000. this.getDependencies( 'scene' ),
  1001. this.getDependencies( 'animation' ),
  1002. this.getDependencies( 'camera' ),
  1003. ] ).then( function ( dependencies ) {
  1004. var result = {
  1005. scene: dependencies[ 0 ][ json.scene || 0 ],
  1006. scenes: dependencies[ 0 ],
  1007. animations: dependencies[ 1 ],
  1008. cameras: dependencies[ 2 ],
  1009. asset: json.asset,
  1010. parser: parser,
  1011. userData: {}
  1012. };
  1013. addUnknownExtensionsToUserData( extensions, result, json );
  1014. assignExtrasToUserData( result, json );
  1015. onLoad( result );
  1016. } ).catch( onError );
  1017. };
  1018. /**
  1019. * Marks the special nodes/meshes in json for efficient parse.
  1020. */
  1021. GLTFParser.prototype.markDefs = function () {
  1022. var nodeDefs = this.json.nodes || [];
  1023. var skinDefs = this.json.skins || [];
  1024. var meshDefs = this.json.meshes || [];
  1025. var meshReferences = {};
  1026. var meshUses = {};
  1027. // Nothing in the node definition indicates whether it is a Bone or an
  1028. // Object3D. Use the skins' joint references to mark bones.
  1029. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1030. var joints = skinDefs[ skinIndex ].joints;
  1031. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  1032. nodeDefs[ joints[ i ] ].isBone = true;
  1033. }
  1034. }
  1035. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  1036. // avoid having more than one THREE.Mesh with the same name, count
  1037. // references and rename instances below.
  1038. //
  1039. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1040. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1041. var nodeDef = nodeDefs[ nodeIndex ];
  1042. if ( nodeDef.mesh !== undefined ) {
  1043. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  1044. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  1045. }
  1046. meshReferences[ nodeDef.mesh ] ++;
  1047. // Nothing in the mesh definition indicates whether it is
  1048. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1049. // to mark SkinnedMesh if node has skin.
  1050. if ( nodeDef.skin !== undefined ) {
  1051. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1052. }
  1053. }
  1054. }
  1055. this.json.meshReferences = meshReferences;
  1056. this.json.meshUses = meshUses;
  1057. };
  1058. /**
  1059. * Requests the specified dependency asynchronously, with caching.
  1060. * @param {string} type
  1061. * @param {number} index
  1062. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  1063. */
  1064. GLTFParser.prototype.getDependency = function ( type, index ) {
  1065. var cacheKey = type + ':' + index;
  1066. var dependency = this.cache.get( cacheKey );
  1067. if ( ! dependency ) {
  1068. switch ( type ) {
  1069. case 'scene':
  1070. dependency = this.loadScene( index );
  1071. break;
  1072. case 'node':
  1073. dependency = this.loadNode( index );
  1074. break;
  1075. case 'mesh':
  1076. dependency = this.loadMesh( index );
  1077. break;
  1078. case 'accessor':
  1079. dependency = this.loadAccessor( index );
  1080. break;
  1081. case 'bufferView':
  1082. dependency = this.loadBufferView( index );
  1083. break;
  1084. case 'buffer':
  1085. dependency = this.loadBuffer( index );
  1086. break;
  1087. case 'material':
  1088. dependency = this.loadMaterial( index );
  1089. break;
  1090. case 'texture':
  1091. dependency = this.loadTexture( index );
  1092. break;
  1093. case 'skin':
  1094. dependency = this.loadSkin( index );
  1095. break;
  1096. case 'animation':
  1097. dependency = this.loadAnimation( index );
  1098. break;
  1099. case 'camera':
  1100. dependency = this.loadCamera( index );
  1101. break;
  1102. case 'light':
  1103. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  1104. break;
  1105. default:
  1106. throw new Error( 'Unknown type: ' + type );
  1107. }
  1108. this.cache.add( cacheKey, dependency );
  1109. }
  1110. return dependency;
  1111. };
  1112. /**
  1113. * Requests all dependencies of the specified type asynchronously, with caching.
  1114. * @param {string} type
  1115. * @return {Promise<Array<Object>>}
  1116. */
  1117. GLTFParser.prototype.getDependencies = function ( type ) {
  1118. var dependencies = this.cache.get( type );
  1119. if ( ! dependencies ) {
  1120. var parser = this;
  1121. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1122. dependencies = Promise.all( defs.map( function ( def, index ) {
  1123. return parser.getDependency( type, index );
  1124. } ) );
  1125. this.cache.add( type, dependencies );
  1126. }
  1127. return dependencies;
  1128. };
  1129. /**
  1130. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1131. * @param {number} bufferIndex
  1132. * @return {Promise<ArrayBuffer>}
  1133. */
  1134. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1135. var bufferDef = this.json.buffers[ bufferIndex ];
  1136. var loader = this.fileLoader;
  1137. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1138. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1139. }
  1140. // If present, GLB container is required to be the first buffer.
  1141. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1142. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1143. }
  1144. var options = this.options;
  1145. return new Promise( function ( resolve, reject ) {
  1146. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1147. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1148. } );
  1149. } );
  1150. };
  1151. /**
  1152. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1153. * @param {number} bufferViewIndex
  1154. * @return {Promise<ArrayBuffer>}
  1155. */
  1156. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1157. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1158. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1159. var byteLength = bufferViewDef.byteLength || 0;
  1160. var byteOffset = bufferViewDef.byteOffset || 0;
  1161. return buffer.slice( byteOffset, byteOffset + byteLength );
  1162. } );
  1163. };
  1164. /**
  1165. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1166. * @param {number} accessorIndex
  1167. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1168. */
  1169. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1170. var parser = this;
  1171. var json = this.json;
  1172. var accessorDef = this.json.accessors[ accessorIndex ];
  1173. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1174. // Ignore empty accessors, which may be used to declare runtime
  1175. // information about attributes coming from another source (e.g. Draco
  1176. // compression extension).
  1177. return Promise.resolve( null );
  1178. }
  1179. var pendingBufferViews = [];
  1180. if ( accessorDef.bufferView !== undefined ) {
  1181. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1182. } else {
  1183. pendingBufferViews.push( null );
  1184. }
  1185. if ( accessorDef.sparse !== undefined ) {
  1186. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1187. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1188. }
  1189. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1190. var bufferView = bufferViews[ 0 ];
  1191. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1192. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1193. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1194. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1195. var itemBytes = elementBytes * itemSize;
  1196. var byteOffset = accessorDef.byteOffset || 0;
  1197. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1198. var normalized = accessorDef.normalized === true;
  1199. var array, bufferAttribute;
  1200. // The buffer is not interleaved if the stride is the item size in bytes.
  1201. if ( byteStride && byteStride !== itemBytes ) {
  1202. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  1203. // This makes sure that IBA.count reflects accessor.count properly
  1204. var ibSlice = Math.floor( byteOffset / byteStride );
  1205. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  1206. var ib = parser.cache.get( ibCacheKey );
  1207. if ( ! ib ) {
  1208. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  1209. // Integer parameters to IB/IBA are in array elements, not bytes.
  1210. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1211. parser.cache.add( ibCacheKey, ib );
  1212. }
  1213. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  1214. } else {
  1215. if ( bufferView === null ) {
  1216. array = new TypedArray( accessorDef.count * itemSize );
  1217. } else {
  1218. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1219. }
  1220. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1221. }
  1222. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1223. if ( accessorDef.sparse !== undefined ) {
  1224. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1225. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1226. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1227. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1228. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1229. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1230. if ( bufferView !== null ) {
  1231. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1232. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  1233. }
  1234. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1235. var index = sparseIndices[ i ];
  1236. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1237. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1238. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1239. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1240. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1241. }
  1242. }
  1243. return bufferAttribute;
  1244. } );
  1245. };
  1246. /**
  1247. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1248. * @param {number} textureIndex
  1249. * @return {Promise<THREE.Texture>}
  1250. */
  1251. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1252. var parser = this;
  1253. var json = this.json;
  1254. var options = this.options;
  1255. var textureLoader = this.textureLoader;
  1256. var URL = window.URL || window.webkitURL;
  1257. var textureDef = json.textures[ textureIndex ];
  1258. var textureExtensions = textureDef.extensions || {};
  1259. var source;
  1260. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1261. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1262. } else {
  1263. source = json.images[ textureDef.source ];
  1264. }
  1265. var sourceURI = source.uri;
  1266. var isObjectURL = false;
  1267. if ( source.bufferView !== undefined ) {
  1268. // Load binary image data from bufferView, if provided.
  1269. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1270. isObjectURL = true;
  1271. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1272. sourceURI = URL.createObjectURL( blob );
  1273. return sourceURI;
  1274. } );
  1275. }
  1276. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1277. // Load Texture resource.
  1278. var loader = options.manager.getHandler( sourceURI );
  1279. if ( ! loader ) {
  1280. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1281. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1282. : textureLoader;
  1283. }
  1284. return new Promise(