PageRenderTime 89ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full 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,

Large files files are truncated, but you can click here to view the full file