Основа Маджонга | Mahjong's base
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

3662 lignes
89KB

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