GLTFLoader.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. * @author Takahiro / https://github.com/takahirox
  6. * @author Don McCurdy / https://www.donmccurdy.com
  7. */
  8. THREE.GLTFLoader = ( function () {
  9. function GLTFLoader( manager ) {
  10. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11. }
  12. GLTFLoader.prototype = {
  13. constructor: GLTFLoader,
  14. crossOrigin: 'Anonymous',
  15. load: function ( url, onLoad, onProgress, onError ) {
  16. var scope = this;
  17. var path = this.path !== undefined ? this.path : THREE.LoaderUtils.extractUrlBase( url );
  18. var loader = new THREE.FileLoader( scope.manager );
  19. loader.setResponseType( 'arraybuffer' );
  20. loader.load( url, function ( data ) {
  21. try {
  22. scope.parse( data, path, onLoad, onError );
  23. } catch ( e ) {
  24. if ( onError !== undefined ) {
  25. onError( e );
  26. } else {
  27. throw e;
  28. }
  29. }
  30. }, onProgress, onError );
  31. },
  32. setCrossOrigin: function ( value ) {
  33. this.crossOrigin = value;
  34. return this;
  35. },
  36. setPath: function ( value ) {
  37. this.path = value;
  38. return this;
  39. },
  40. parse: function ( data, path, onLoad, onError ) {
  41. var content;
  42. var extensions = {};
  43. if ( typeof data === 'string' ) {
  44. content = data;
  45. } else {
  46. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  47. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  48. try {
  49. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  50. } catch ( error ) {
  51. if ( onError ) onError( error );
  52. return;
  53. }
  54. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  55. } else {
  56. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  57. }
  58. }
  59. var json = JSON.parse( content );
  60. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  61. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  62. return;
  63. }
  64. if ( json.extensionsUsed ) {
  65. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
  66. extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );
  67. }
  68. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  69. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  70. }
  71. }
  72. console.time( 'GLTFLoader' );
  73. var parser = new GLTFParser( json, extensions, {
  74. path: path || this.path || '',
  75. crossOrigin: this.crossOrigin,
  76. manager: this.manager
  77. } );
  78. parser.parse( function ( scene, scenes, cameras, animations, asset ) {
  79. console.timeEnd( 'GLTFLoader' );
  80. var glTF = {
  81. scene: scene,
  82. scenes: scenes,
  83. cameras: cameras,
  84. animations: animations,
  85. asset: asset
  86. };
  87. onLoad( glTF );
  88. }, onError );
  89. }
  90. };
  91. /* GLTFREGISTRY */
  92. function GLTFRegistry() {
  93. var objects = {};
  94. return {
  95. get: function ( key ) {
  96. return objects[ key ];
  97. },
  98. add: function ( key, object ) {
  99. objects[ key ] = object;
  100. },
  101. remove: function ( key ) {
  102. delete objects[ key ];
  103. },
  104. removeAll: function () {
  105. objects = {};
  106. }
  107. };
  108. }
  109. /*********************************/
  110. /********** EXTENSIONS ***********/
  111. /*********************************/
  112. var EXTENSIONS = {
  113. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  114. KHR_LIGHTS: 'KHR_lights',
  115. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness'
  116. };
  117. /**
  118. * Lights Extension
  119. *
  120. * Specification: PENDING
  121. */
  122. function GLTFLightsExtension( json ) {
  123. this.name = EXTENSIONS.KHR_LIGHTS;
  124. this.lights = {};
  125. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
  126. var lights = extension.lights || {};
  127. for ( var lightId in lights ) {
  128. var light = lights[ lightId ];
  129. var lightNode;
  130. var color = new THREE.Color().fromArray( light.color );
  131. switch ( light.type ) {
  132. case 'directional':
  133. lightNode = new THREE.DirectionalLight( color );
  134. lightNode.position.set( 0, 0, 1 );
  135. break;
  136. case 'point':
  137. lightNode = new THREE.PointLight( color );
  138. break;
  139. case 'spot':
  140. lightNode = new THREE.SpotLight( color );
  141. lightNode.position.set( 0, 0, 1 );
  142. break;
  143. case 'ambient':
  144. lightNode = new THREE.AmbientLight( color );
  145. break;
  146. }
  147. if ( lightNode ) {
  148. if ( light.constantAttenuation !== undefined ) {
  149. lightNode.intensity = light.constantAttenuation;
  150. }
  151. if ( light.linearAttenuation !== undefined ) {
  152. lightNode.distance = 1 / light.linearAttenuation;
  153. }
  154. if ( light.quadraticAttenuation !== undefined ) {
  155. lightNode.decay = light.quadraticAttenuation;
  156. }
  157. if ( light.fallOffAngle !== undefined ) {
  158. lightNode.angle = light.fallOffAngle;
  159. }
  160. if ( light.fallOffExponent !== undefined ) {
  161. console.warn( 'THREE.GLTFLoader:: light.fallOffExponent not currently supported.' );
  162. }
  163. lightNode.name = light.name || ( 'light_' + lightId );
  164. this.lights[ lightId ] = lightNode;
  165. }
  166. }
  167. }
  168. /* BINARY EXTENSION */
  169. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  170. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  171. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  172. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  173. function GLTFBinaryExtension( data ) {
  174. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  175. this.content = null;
  176. this.body = null;
  177. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  178. this.header = {
  179. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  180. version: headerView.getUint32( 4, true ),
  181. length: headerView.getUint32( 8, true )
  182. };
  183. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  184. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  185. } else if ( this.header.version < 2.0 ) {
  186. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  187. }
  188. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  189. var chunkIndex = 0;
  190. while ( chunkIndex < chunkView.byteLength ) {
  191. var chunkLength = chunkView.getUint32( chunkIndex, true );
  192. chunkIndex += 4;
  193. var chunkType = chunkView.getUint32( chunkIndex, true );
  194. chunkIndex += 4;
  195. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  196. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  197. this.content = THREE.LoaderUtils.decodeText( contentArray );
  198. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  199. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  200. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  201. }
  202. // Clients must ignore chunks with unknown types.
  203. chunkIndex += chunkLength;
  204. }
  205. if ( this.content === null ) {
  206. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  207. }
  208. }
  209. /**
  210. * Specular-Glossiness Extension
  211. *
  212. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  213. */
  214. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  215. return {
  216. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  217. specularGlossinessParams: [
  218. 'color',
  219. 'map',
  220. 'lightMap',
  221. 'lightMapIntensity',
  222. 'aoMap',
  223. 'aoMapIntensity',
  224. 'emissive',
  225. 'emissiveIntensity',
  226. 'emissiveMap',
  227. 'bumpMap',
  228. 'bumpScale',
  229. 'normalMap',
  230. 'displacementMap',
  231. 'displacementScale',
  232. 'displacementBias',
  233. 'specularMap',
  234. 'specular',
  235. 'glossinessMap',
  236. 'glossiness',
  237. 'alphaMap',
  238. 'envMap',
  239. 'envMapIntensity',
  240. 'refractionRatio',
  241. ],
  242. getMaterialType: function () {
  243. return THREE.ShaderMaterial;
  244. },
  245. extendParams: function ( params, material, parser ) {
  246. var pbrSpecularGlossiness = material.extensions[ this.name ];
  247. var shader = THREE.ShaderLib[ 'standard' ];
  248. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  249. var specularMapParsFragmentChunk = [
  250. '#ifdef USE_SPECULARMAP',
  251. ' uniform sampler2D specularMap;',
  252. '#endif'
  253. ].join( '\n' );
  254. var glossinessMapParsFragmentChunk = [
  255. '#ifdef USE_GLOSSINESSMAP',
  256. ' uniform sampler2D glossinessMap;',
  257. '#endif'
  258. ].join( '\n' );
  259. var specularMapFragmentChunk = [
  260. 'vec3 specularFactor = specular;',
  261. '#ifdef USE_SPECULARMAP',
  262. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  263. ' texelSpecular = sRGBToLinear( texelSpecular );',
  264. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  265. ' specularFactor *= texelSpecular.rgb;',
  266. '#endif'
  267. ].join( '\n' );
  268. var glossinessMapFragmentChunk = [
  269. 'float glossinessFactor = glossiness;',
  270. '#ifdef USE_GLOSSINESSMAP',
  271. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  272. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  273. ' glossinessFactor *= texelGlossiness.a;',
  274. '#endif'
  275. ].join( '\n' );
  276. var lightPhysicalFragmentChunk = [
  277. 'PhysicalMaterial material;',
  278. 'material.diffuseColor = diffuseColor.rgb;',
  279. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  280. 'material.specularColor = specularFactor.rgb;',
  281. ].join( '\n' );
  282. var fragmentShader = shader.fragmentShader
  283. .replace( '#include <specularmap_fragment>', '' )
  284. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  285. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  286. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  287. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  288. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  289. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  290. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  291. delete uniforms.roughness;
  292. delete uniforms.metalness;
  293. delete uniforms.roughnessMap;
  294. delete uniforms.metalnessMap;
  295. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  296. uniforms.glossiness = { value: 0.5 };
  297. uniforms.specularMap = { value: null };
  298. uniforms.glossinessMap = { value: null };
  299. params.vertexShader = shader.vertexShader;
  300. params.fragmentShader = fragmentShader;
  301. params.uniforms = uniforms;
  302. params.defines = { 'STANDARD': '' };
  303. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  304. params.opacity = 1.0;
  305. var pending = [];
  306. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  307. var array = pbrSpecularGlossiness.diffuseFactor;
  308. params.color.fromArray( array );
  309. params.opacity = array[ 3 ];
  310. }
  311. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  312. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  313. }
  314. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  315. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  316. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  317. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  318. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  319. }
  320. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  321. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  322. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  323. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  324. }
  325. return Promise.all( pending );
  326. },
  327. createMaterial: function ( params ) {
  328. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  329. var material = new THREE.ShaderMaterial( {
  330. defines: params.defines,
  331. vertexShader: params.vertexShader,
  332. fragmentShader: params.fragmentShader,
  333. uniforms: params.uniforms,
  334. fog: true,
  335. lights: true,
  336. opacity: params.opacity,
  337. transparent: params.transparent
  338. } );
  339. material.isGLTFSpecularGlossinessMaterial = true;
  340. material.color = params.color;
  341. material.map = params.map === undefined ? null : params.map;
  342. material.lightMap = null;
  343. material.lightMapIntensity = 1.0;
  344. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  345. material.aoMapIntensity = 1.0;
  346. material.emissive = params.emissive;
  347. material.emissiveIntensity = 1.0;
  348. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  349. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  350. material.bumpScale = 1;
  351. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  352. if ( params.normalScale ) material.normalScale = params.normalScale;
  353. material.displacementMap = null;
  354. material.displacementScale = 1;
  355. material.displacementBias = 0;
  356. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  357. material.specular = params.specular;
  358. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  359. material.glossiness = params.glossiness;
  360. material.alphaMap = null;
  361. material.envMap = params.envMap === undefined ? null : params.envMap;
  362. material.envMapIntensity = 1.0;
  363. material.refractionRatio = 0.98;
  364. material.extensions.derivatives = true;
  365. return material;
  366. },
  367. /**
  368. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  369. * copy only properties it knows about or inherits, and misses many properties that would
  370. * normally be defined by MeshStandardMaterial.
  371. *
  372. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  373. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  374. * AND also updating `.onBeforeRender` on the parent mesh.
  375. *
  376. * @param {THREE.ShaderMaterial} source
  377. * @return {THREE.ShaderMaterial}
  378. */
  379. cloneMaterial: function ( source ) {
  380. var target = source.clone();
  381. target.isGLTFSpecularGlossinessMaterial = true;
  382. var params = this.specularGlossinessParams;
  383. for ( var i = 0, il = params.length; i < il; i ++ ) {
  384. target[ params[ i ] ] = source[ params[ i ] ];
  385. }
  386. return target;
  387. },
  388. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  389. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  390. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  391. return;
  392. }
  393. var uniforms = material.uniforms;
  394. var defines = material.defines;
  395. uniforms.opacity.value = material.opacity;
  396. uniforms.diffuse.value.copy( material.color );
  397. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  398. uniforms.map.value = material.map;
  399. uniforms.specularMap.value = material.specularMap;
  400. uniforms.alphaMap.value = material.alphaMap;
  401. uniforms.lightMap.value = material.lightMap;
  402. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  403. uniforms.aoMap.value = material.aoMap;
  404. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  405. // uv repeat and offset setting priorities
  406. // 1. color map
  407. // 2. specular map
  408. // 3. normal map
  409. // 4. bump map
  410. // 5. alpha map
  411. // 6. emissive map
  412. var uvScaleMap;
  413. if ( material.map ) {
  414. uvScaleMap = material.map;
  415. } else if ( material.specularMap ) {
  416. uvScaleMap = material.specularMap;
  417. } else if ( material.displacementMap ) {
  418. uvScaleMap = material.displacementMap;
  419. } else if ( material.normalMap ) {
  420. uvScaleMap = material.normalMap;
  421. } else if ( material.bumpMap ) {
  422. uvScaleMap = material.bumpMap;
  423. } else if ( material.glossinessMap ) {
  424. uvScaleMap = material.glossinessMap;
  425. } else if ( material.alphaMap ) {
  426. uvScaleMap = material.alphaMap;
  427. } else if ( material.emissiveMap ) {
  428. uvScaleMap = material.emissiveMap;
  429. }
  430. if ( uvScaleMap !== undefined ) {
  431. // backwards compatibility
  432. if ( uvScaleMap.isWebGLRenderTarget ) {
  433. uvScaleMap = uvScaleMap.texture;
  434. }
  435. var offset;
  436. var repeat;
  437. if ( uvScaleMap.matrix !== undefined ) {
  438. // > r88.
  439. if ( uvScaleMap.matrixAutoUpdate === true ) {
  440. offset = uvScaleMap.offset;
  441. repeat = uvScaleMap.repeat;
  442. var rotation = uvScaleMap.rotation;
  443. var center = uvScaleMap.center;
  444. uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );
  445. }
  446. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  447. } else {
  448. // <= r87. Remove when reasonable.
  449. offset = uvScaleMap.offset;
  450. repeat = uvScaleMap.repeat;
  451. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  452. }
  453. }
  454. uniforms.envMap.value = material.envMap;
  455. uniforms.envMapIntensity.value = material.envMapIntensity;
  456. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  457. uniforms.refractionRatio.value = material.refractionRatio;
  458. uniforms.specular.value.copy( material.specular );
  459. uniforms.glossiness.value = material.glossiness;
  460. uniforms.glossinessMap.value = material.glossinessMap;
  461. uniforms.emissiveMap.value = material.emissiveMap;
  462. uniforms.bumpMap.value = material.bumpMap;
  463. uniforms.normalMap.value = material.normalMap;
  464. uniforms.displacementMap.value = material.displacementMap;
  465. uniforms.displacementScale.value = material.displacementScale;
  466. uniforms.displacementBias.value = material.displacementBias;
  467. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  468. defines.USE_GLOSSINESSMAP = '';
  469. // set USE_ROUGHNESSMAP to enable vUv
  470. defines.USE_ROUGHNESSMAP = '';
  471. }
  472. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  473. delete defines.USE_GLOSSINESSMAP;
  474. delete defines.USE_ROUGHNESSMAP;
  475. }
  476. }
  477. };
  478. }
  479. /*********************************/
  480. /********** INTERPOLATION ********/
  481. /*********************************/
  482. // Spline Interpolation
  483. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  484. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  485. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  486. };
  487. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  488. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  489. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  490. var result = this.resultBuffer;
  491. var values = this.sampleValues;
  492. var stride = this.valueSize;
  493. var stride2 = stride * 2;
  494. var stride3 = stride * 3;
  495. var td = t1 - t0;
  496. var p = ( t - t0 ) / td;
  497. var pp = p * p;
  498. var ppp = pp * p;
  499. var offset1 = i1 * stride3;
  500. var offset0 = offset1 - stride3;
  501. var s0 = 2 * ppp - 3 * pp + 1;
  502. var s1 = ppp - 2 * pp + p;
  503. var s2 = - 2 * ppp + 3 * pp;
  504. var s3 = ppp - pp;
  505. // Layout of keyframe output values for CUBICSPLINE animations:
  506. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  507. for ( var i = 0; i !== stride; i ++ ) {
  508. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  509. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  510. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  511. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  512. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  513. }
  514. return result;
  515. };
  516. /*********************************/
  517. /********** INTERNALS ************/
  518. /*********************************/
  519. /* CONSTANTS */
  520. var WEBGL_CONSTANTS = {
  521. FLOAT: 5126,
  522. //FLOAT_MAT2: 35674,
  523. FLOAT_MAT3: 35675,
  524. FLOAT_MAT4: 35676,
  525. FLOAT_VEC2: 35664,
  526. FLOAT_VEC3: 35665,
  527. FLOAT_VEC4: 35666,
  528. LINEAR: 9729,
  529. REPEAT: 10497,
  530. SAMPLER_2D: 35678,
  531. POINTS: 0,
  532. LINES: 1,
  533. LINE_LOOP: 2,
  534. LINE_STRIP: 3,
  535. TRIANGLES: 4,
  536. TRIANGLE_STRIP: 5,
  537. TRIANGLE_FAN: 6,
  538. UNSIGNED_BYTE: 5121,
  539. UNSIGNED_SHORT: 5123
  540. };
  541. var WEBGL_TYPE = {
  542. 5126: Number,
  543. //35674: THREE.Matrix2,
  544. 35675: THREE.Matrix3,
  545. 35676: THREE.Matrix4,
  546. 35664: THREE.Vector2,
  547. 35665: THREE.Vector3,
  548. 35666: THREE.Vector4,
  549. 35678: THREE.Texture
  550. };
  551. var WEBGL_COMPONENT_TYPES = {
  552. 5120: Int8Array,
  553. 5121: Uint8Array,
  554. 5122: Int16Array,
  555. 5123: Uint16Array,
  556. 5125: Uint32Array,
  557. 5126: Float32Array
  558. };
  559. var WEBGL_FILTERS = {
  560. 9728: THREE.NearestFilter,
  561. 9729: THREE.LinearFilter,
  562. 9984: THREE.NearestMipMapNearestFilter,
  563. 9985: THREE.LinearMipMapNearestFilter,
  564. 9986: THREE.NearestMipMapLinearFilter,
  565. 9987: THREE.LinearMipMapLinearFilter
  566. };
  567. var WEBGL_WRAPPINGS = {
  568. 33071: THREE.ClampToEdgeWrapping,
  569. 33648: THREE.MirroredRepeatWrapping,
  570. 10497: THREE.RepeatWrapping
  571. };
  572. var WEBGL_TEXTURE_FORMATS = {
  573. 6406: THREE.AlphaFormat,
  574. 6407: THREE.RGBFormat,
  575. 6408: THREE.RGBAFormat,
  576. 6409: THREE.LuminanceFormat,
  577. 6410: THREE.LuminanceAlphaFormat
  578. };
  579. var WEBGL_TEXTURE_DATATYPES = {
  580. 5121: THREE.UnsignedByteType,
  581. 32819: THREE.UnsignedShort4444Type,
  582. 32820: THREE.UnsignedShort5551Type,
  583. 33635: THREE.UnsignedShort565Type
  584. };
  585. var WEBGL_SIDES = {
  586. 1028: THREE.BackSide, // Culling front
  587. 1029: THREE.FrontSide // Culling back
  588. //1032: THREE.NoSide // Culling front and back, what to do?
  589. };
  590. var WEBGL_DEPTH_FUNCS = {
  591. 512: THREE.NeverDepth,
  592. 513: THREE.LessDepth,
  593. 514: THREE.EqualDepth,
  594. 515: THREE.LessEqualDepth,
  595. 516: THREE.GreaterEqualDepth,
  596. 517: THREE.NotEqualDepth,
  597. 518: THREE.GreaterEqualDepth,
  598. 519: THREE.AlwaysDepth
  599. };
  600. var WEBGL_BLEND_EQUATIONS = {
  601. 32774: THREE.AddEquation,
  602. 32778: THREE.SubtractEquation,
  603. 32779: THREE.ReverseSubtractEquation
  604. };
  605. var WEBGL_BLEND_FUNCS = {
  606. 0: THREE.ZeroFactor,
  607. 1: THREE.OneFactor,
  608. 768: THREE.SrcColorFactor,
  609. 769: THREE.OneMinusSrcColorFactor,
  610. 770: THREE.SrcAlphaFactor,
  611. 771: THREE.OneMinusSrcAlphaFactor,
  612. 772: THREE.DstAlphaFactor,
  613. 773: THREE.OneMinusDstAlphaFactor,
  614. 774: THREE.DstColorFactor,
  615. 775: THREE.OneMinusDstColorFactor,
  616. 776: THREE.SrcAlphaSaturateFactor
  617. // The followings are not supported by Three.js yet
  618. //32769: CONSTANT_COLOR,
  619. //32770: ONE_MINUS_CONSTANT_COLOR,
  620. //32771: CONSTANT_ALPHA,
  621. //32772: ONE_MINUS_CONSTANT_COLOR
  622. };
  623. var WEBGL_TYPE_SIZES = {
  624. 'SCALAR': 1,
  625. 'VEC2': 2,
  626. 'VEC3': 3,
  627. 'VEC4': 4,
  628. 'MAT2': 4,
  629. 'MAT3': 9,
  630. 'MAT4': 16
  631. };
  632. var PATH_PROPERTIES = {
  633. scale: 'scale',
  634. translation: 'position',
  635. rotation: 'quaternion',
  636. weights: 'morphTargetInfluences'
  637. };
  638. var INTERPOLATION = {
  639. CUBICSPLINE: THREE.InterpolateSmooth, // We use custom interpolation GLTFCubicSplineInterpolation for CUBICSPLINE.
  640. // KeyframeTrack.optimize() can't handle glTF Cubic Spline output values layout,
  641. // using THREE.InterpolateSmooth for KeyframeTrack instantiation to prevent optimization.
  642. // See KeyframeTrack.optimize() for the detail.
  643. LINEAR: THREE.InterpolateLinear,
  644. STEP: THREE.InterpolateDiscrete
  645. };
  646. var STATES_ENABLES = {
  647. 2884: 'CULL_FACE',
  648. 2929: 'DEPTH_TEST',
  649. 3042: 'BLEND',
  650. 3089: 'SCISSOR_TEST',
  651. 32823: 'POLYGON_OFFSET_FILL',
  652. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  653. };
  654. var ALPHA_MODES = {
  655. OPAQUE: 'OPAQUE',
  656. MASK: 'MASK',
  657. BLEND: 'BLEND'
  658. };
  659. /* UTILITY FUNCTIONS */
  660. function resolveURL( url, path ) {
  661. // Invalid URL
  662. if ( typeof url !== 'string' || url === '' ) return '';
  663. // Absolute URL http://,https://,//
  664. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  665. // Data URI
  666. if ( /^data:.*,.*$/i.test( url ) ) return url;
  667. // Blob URL
  668. if ( /^blob:.*$/i.test( url ) ) return url;
  669. // Relative URL
  670. return path + url;
  671. }
  672. /**
  673. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  674. */
  675. function createDefaultMaterial() {
  676. return new THREE.MeshStandardMaterial( {
  677. color: 0xFFFFFF,
  678. emissive: 0x000000,
  679. metalness: 1,
  680. roughness: 1,
  681. transparent: false,
  682. depthTest: true,
  683. side: THREE.FrontSide
  684. } );
  685. }
  686. /**
  687. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  688. *
  689. * TODO: Implement support for morph targets on TANGENT attribute.
  690. *
  691. * @param {THREE.Mesh} mesh
  692. * @param {GLTF.Mesh} meshDef
  693. * @param {GLTF.Primitive} primitiveDef
  694. * @param {Array<THREE.BufferAttribute>} accessors
  695. */
  696. function addMorphTargets( mesh, meshDef, primitiveDef, accessors ) {
  697. var geometry = mesh.geometry;
  698. var material = mesh.material;
  699. var targets = primitiveDef.targets;
  700. var morphAttributes = geometry.morphAttributes;
  701. morphAttributes.position = [];
  702. morphAttributes.normal = [];
  703. material.morphTargets = true;
  704. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  705. var target = targets[ i ];
  706. var attributeName = 'morphTarget' + i;
  707. var positionAttribute, normalAttribute;
  708. if ( target.POSITION !== undefined ) {
  709. // Three.js morph formula is
  710. // position
  711. // + weight0 * ( morphTarget0 - position )
  712. // + weight1 * ( morphTarget1 - position )
  713. // ...
  714. // while the glTF one is
  715. // position
  716. // + weight0 * morphTarget0
  717. // + weight1 * morphTarget1
  718. // ...
  719. // then adding position to morphTarget.
  720. // So morphTarget value will depend on mesh's position, then cloning attribute
  721. // for the case if attribute is shared among two or more meshes.
  722. positionAttribute = cloneBufferAttribute( accessors[ target.POSITION ] );
  723. var position = geometry.attributes.position;
  724. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  725. positionAttribute.setXYZ(
  726. j,
  727. positionAttribute.getX( j ) + position.getX( j ),
  728. positionAttribute.getY( j ) + position.getY( j ),
  729. positionAttribute.getZ( j ) + position.getZ( j )
  730. );
  731. }
  732. } else if ( geometry.attributes.position ) {
  733. // Copying the original position not to affect the final position.
  734. // See the formula above.
  735. positionAttribute = cloneBufferAttribute( geometry.attributes.position );
  736. }
  737. if ( positionAttribute !== undefined ) {
  738. positionAttribute.name = attributeName;
  739. morphAttributes.position.push( positionAttribute );
  740. }
  741. if ( target.NORMAL !== undefined ) {
  742. material.morphNormals = true;
  743. // see target.POSITION's comment
  744. normalAttribute = cloneBufferAttribute( accessors[ target.NORMAL ] );
  745. var normal = geometry.attributes.normal;
  746. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  747. normalAttribute.setXYZ(
  748. j,
  749. normalAttribute.getX( j ) + normal.getX( j ),
  750. normalAttribute.getY( j ) + normal.getY( j ),
  751. normalAttribute.getZ( j ) + normal.getZ( j )
  752. );
  753. }
  754. } else if ( geometry.attributes.normal !== undefined ) {
  755. normalAttribute = cloneBufferAttribute( geometry.attributes.normal );
  756. }
  757. if ( normalAttribute !== undefined ) {
  758. normalAttribute.name = attributeName;
  759. morphAttributes.normal.push( normalAttribute );
  760. }
  761. }
  762. mesh.updateMorphTargets();
  763. if ( meshDef.weights !== undefined ) {
  764. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  765. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  766. }
  767. }
  768. }
  769. function isPrimitiveEqual( a, b ) {
  770. if ( a.indices !== b.indices ) {
  771. return false;
  772. }
  773. var attribA = a.attributes || {};
  774. var attribB = b.attributes || {};
  775. var keysA = Object.keys( attribA );
  776. var keysB = Object.keys( attribB );
  777. if ( keysA.length !== keysB.length ) {
  778. return false;
  779. }
  780. for ( var i = 0, il = keysA.length; i < il; i ++ ) {
  781. var key = keysA[ i ];
  782. if ( attribA[ key ] !== attribB[ key ] ) {
  783. return false;
  784. }
  785. }
  786. return true;
  787. }
  788. function getCachedGeometry( cache, newPrimitive ) {
  789. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  790. var cached = cache[ i ];
  791. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) {
  792. return cached.geometry;
  793. }
  794. }
  795. return null;
  796. }
  797. function cloneBufferAttribute( attribute ) {
  798. if ( attribute.isInterleavedBufferAttribute ) {
  799. var count = attribute.count;
  800. var itemSize = attribute.itemSize;
  801. var array = attribute.array.slice( 0, count * itemSize );
  802. for ( var i = 0; i < count; ++ i ) {
  803. array[ i ] = attribute.getX( i );
  804. if ( itemSize >= 2 ) array[ i + 1 ] = attribute.getY( i );
  805. if ( itemSize >= 3 ) array[ i + 2 ] = attribute.getZ( i );
  806. if ( itemSize >= 4 ) array[ i + 3 ] = attribute.getW( i );
  807. }
  808. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  809. }
  810. return attribute.clone();
  811. }
  812. /* GLTF PARSER */
  813. function GLTFParser( json, extensions, options ) {
  814. this.json = json || {};
  815. this.extensions = extensions || {};
  816. this.options = options || {};
  817. // loader object cache
  818. this.cache = new GLTFRegistry();
  819. // BufferGeometry caching
  820. this.primitiveCache = [];
  821. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  822. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  823. this.fileLoader = new THREE.FileLoader( this.options.manager );
  824. this.fileLoader.setResponseType( 'arraybuffer' );
  825. }
  826. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  827. var json = this.json;
  828. // Clear the loader cache
  829. this.cache.removeAll();
  830. // Mark the special nodes/meshes in json for efficient parse
  831. this.markDefs();
  832. // Fire the callback on complete
  833. this.getMultiDependencies( [
  834. 'scene',
  835. 'animation',
  836. 'camera'
  837. ] ).then( function ( dependencies ) {
  838. var scenes = dependencies.scenes || [];
  839. var scene = scenes[ json.scene || 0 ];
  840. var animations = dependencies.animations || [];
  841. var asset = json.asset;
  842. var cameras = dependencies.cameras || [];
  843. onLoad( scene, scenes, cameras, animations, asset );
  844. } ).catch( onError );
  845. };
  846. /**
  847. * Marks the special nodes/meshes in json for efficient parse.
  848. */
  849. GLTFParser.prototype.markDefs = function () {
  850. var nodeDefs = this.json.nodes || [];
  851. var skinDefs = this.json.skins || [];
  852. var meshDefs = this.json.meshes || [];
  853. var meshReferences = {};
  854. var meshUses = {};
  855. // Nothing in the node definition indicates whether it is a Bone or an
  856. // Object3D. Use the skins' joint references to mark bones.
  857. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  858. var joints = skinDefs[ skinIndex ].joints;
  859. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  860. nodeDefs[ joints[ i ] ].isBone = true;
  861. }
  862. }
  863. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  864. // avoid having more than one THREE.Mesh with the same name, count
  865. // references and rename instances below.
  866. //
  867. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  868. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  869. var nodeDef = nodeDefs[ nodeIndex ];
  870. if ( nodeDef.mesh !== undefined ) {
  871. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  872. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  873. }
  874. meshReferences[ nodeDef.mesh ] ++;
  875. // Nothing in the mesh definition indicates whether it is
  876. // a SkinnedMesh or Mesh. Use the node's mesh reference
  877. // to mark SkinnedMesh if node has skin.
  878. if ( nodeDef.skin !== undefined ) {
  879. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  880. }
  881. }
  882. }
  883. this.json.meshReferences = meshReferences;
  884. this.json.meshUses = meshUses;
  885. };
  886. /**
  887. * Requests the specified dependency asynchronously, with caching.
  888. * @param {string} type
  889. * @param {number} index
  890. * @return {Promise<Object>}
  891. */
  892. GLTFParser.prototype.getDependency = function ( type, index ) {
  893. var cacheKey = type + ':' + index;
  894. var dependency = this.cache.get( cacheKey );
  895. if ( ! dependency ) {
  896. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  897. dependency = this[ fnName ]( index );
  898. this.cache.add( cacheKey, dependency );
  899. }
  900. return dependency;
  901. };
  902. /**
  903. * Requests all dependencies of the specified type asynchronously, with caching.
  904. * @param {string} type
  905. * @return {Promise<Array<Object>>}
  906. */
  907. GLTFParser.prototype.getDependencies = function ( type ) {
  908. var dependencies = this.cache.get( type );
  909. if ( ! dependencies ) {
  910. var parser = this;
  911. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  912. dependencies = Promise.all( defs.map( function ( def, index ) {
  913. return parser.getDependency( type, index );
  914. } ) );
  915. this.cache.add( type, dependencies );
  916. }
  917. return dependencies;
  918. };
  919. /**
  920. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  921. * @param {Array<string>} types
  922. * @return {Promise<Object<Array<Object>>>}
  923. */
  924. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  925. var results = {};
  926. var pendings = [];
  927. for ( var i = 0, il = types.length; i < il; i ++ ) {
  928. var type = types[ i ];
  929. var value = this.getDependencies( type );
  930. value = value.then( function ( key, value ) {
  931. results[ key ] = value;
  932. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  933. pendings.push( value );
  934. }
  935. return Promise.all( pendings ).then( function () {
  936. return results;
  937. } );
  938. };
  939. /**
  940. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  941. * @param {number} bufferIndex
  942. * @return {Promise<ArrayBuffer>}
  943. */
  944. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  945. var bufferDef = this.json.buffers[ bufferIndex ];
  946. var loader = this.fileLoader;
  947. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  948. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  949. }
  950. // If present, GLB container is required to be the first buffer.
  951. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  952. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  953. }
  954. var options = this.options;
  955. return new Promise( function ( resolve, reject ) {
  956. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  957. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  958. } );
  959. } );
  960. };
  961. /**
  962. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  963. * @param {number} bufferViewIndex
  964. * @return {Promise<ArrayBuffer>}
  965. */
  966. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  967. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  968. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  969. var byteLength = bufferViewDef.byteLength || 0;
  970. var byteOffset = bufferViewDef.byteOffset || 0;
  971. return buffer.slice( byteOffset, byteOffset + byteLength );
  972. } );
  973. };
  974. /**
  975. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  976. * @param {number} accessorIndex
  977. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  978. */
  979. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  980. var parser = this;
  981. var json = this.json;
  982. var accessorDef = this.json.accessors[ accessorIndex ];
  983. var pendingBufferViews = [];
  984. if ( accessorDef.bufferView !== undefined ) {
  985. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  986. } else {
  987. pendingBufferViews.push( null );
  988. }
  989. if ( accessorDef.sparse !== undefined ) {
  990. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  991. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  992. }
  993. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  994. var bufferView = bufferViews[ 0 ];
  995. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  996. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  997. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  998. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  999. var itemBytes = elementBytes * itemSize;
  1000. var byteOffset = accessorDef.byteOffset || 0;
  1001. var byteStride = json.bufferViews[ accessorDef.bufferView ].byteStride;
  1002. var normalized = accessorDef.normalized === true;
  1003. var array, bufferAttribute;
  1004. // The buffer is not interleaved if the stride is the item size in bytes.
  1005. if ( byteStride && byteStride !== itemBytes ) {
  1006. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  1007. var ib = parser.cache.get( ibCacheKey );
  1008. if ( ! ib ) {
  1009. // Use the full buffer if it's interleaved.
  1010. array = new TypedArray( bufferView );
  1011. // Integer parameters to IB/IBA are in array elements, not bytes.
  1012. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1013. parser.cache.add( ibCacheKey, ib );
  1014. }
  1015. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  1016. } else {
  1017. if ( bufferView === null ) {
  1018. array = new TypedArray( accessorDef.count * itemSize );
  1019. } else {
  1020. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1021. }
  1022. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1023. }
  1024. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1025. if ( accessorDef.sparse !== undefined ) {
  1026. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1027. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1028. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1029. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1030. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1031. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1032. if ( bufferView !== null ) {
  1033. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1034. bufferAttribute.setArray( bufferAttribute.array.slice() );
  1035. }
  1036. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1037. var index = sparseIndices[ i ];
  1038. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1039. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1040. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1041. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1042. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1043. }
  1044. }
  1045. return bufferAttribute;
  1046. } );
  1047. };
  1048. /**
  1049. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1050. * @param {number} textureIndex
  1051. * @return {Promise<THREE.Texture>}
  1052. */
  1053. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1054. var parser = this;
  1055. var json = this.json;
  1056. var options = this.options;
  1057. var textureLoader = this.textureLoader;
  1058. var URL = window.URL || window.webkitURL;
  1059. var textureDef = json.textures[ textureIndex ];
  1060. var source = json.images[ textureDef.source ];
  1061. var sourceURI = source.uri;
  1062. var isObjectURL = false;
  1063. if ( source.bufferView !== undefined ) {
  1064. // Load binary image data from bufferView, if provided.
  1065. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1066. isObjectURL = true;
  1067. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1068. sourceURI = URL.createObjectURL( blob );
  1069. return sourceURI;
  1070. } );
  1071. }
  1072. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1073. // Load Texture resource.
  1074. var loader = THREE.Loader.Handlers.get( sourceURI ) || textureLoader;
  1075. return new Promise( function ( resolve, reject ) {
  1076. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1077. } );
  1078. } ).then( function ( texture ) {
  1079. // Clean up resources and configure Texture.
  1080. if ( isObjectURL === true ) {
  1081. URL.revokeObjectURL( sourceURI );
  1082. }
  1083. texture.flipY = false;
  1084. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1085. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  1086. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  1087. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  1088. 'internalFormat will be forced to be the same value as format.' );
  1089. }
  1090. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  1091. var samplers = json.samplers || {};
  1092. var sampler = samplers[ textureDef.sampler ] || {};
  1093. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1094. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1095. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1096. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1097. return texture;
  1098. } );
  1099. };
  1100. /**
  1101. * Asynchronously assigns a texture to the given material parameters.
  1102. * @param {Object} materialParams
  1103. * @param {string} textureName
  1104. * @param {number} textureIndex
  1105. * @return {Promise}
  1106. */
  1107. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  1108. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  1109. materialParams[ textureName ] = texture;
  1110. } );
  1111. };
  1112. /**
  1113. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1114. * @param {number} materialIndex
  1115. * @return {Promise<THREE.Material>}
  1116. */
  1117. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1118. var parser = this;
  1119. var json = this.json;
  1120. var extensions = this.extensions;
  1121. var materialDef = this.json.materials[ materialIndex ];
  1122. var materialType;
  1123. var materialParams = {};
  1124. var materialExtensions = materialDef.extensions || {};
  1125. var pending = [];
  1126. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1127. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1128. materialType = sgExtension.getMaterialType( materialDef );
  1129. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1130. } else if ( materialDef.pbrMetallicRoughness !== undefined ) {
  1131. // Specification:
  1132. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1133. materialType = THREE.MeshStandardMaterial;
  1134. var metallicRoughness = materialDef.pbrMetallicRoughness;
  1135. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1136. materialParams.opacity = 1.0;
  1137. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1138. var array = metallicRoughness.baseColorFactor;
  1139. materialParams.color.fromArray( array );
  1140. materialParams.opacity = array[ 3 ];
  1141. }
  1142. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1143. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  1144. }
  1145. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1146. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1147. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1148. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1149. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  1150. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  1151. }
  1152. } else {
  1153. materialType = THREE.MeshPhongMaterial;
  1154. }
  1155. if ( materialDef.doubleSided === true ) {
  1156. materialParams.side = THREE.DoubleSide;
  1157. }
  1158. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1159. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1160. materialParams.transparent = true;
  1161. } else {
  1162. materialParams.transparent = false;
  1163. if ( alphaMode === ALPHA_MODES.MASK ) {
  1164. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1165. }
  1166. }
  1167. if ( materialDef.normalTexture !== undefined ) {
  1168. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture.index ) );
  1169. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1170. if ( materialDef.normalTexture.scale !== undefined ) {
  1171. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1172. }
  1173. }
  1174. if ( materialDef.occlusionTexture !== undefined ) {
  1175. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture.index ) );
  1176. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1177. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1178. }
  1179. }
  1180. if ( materialDef.emissiveFactor !== undefined ) {
  1181. if ( materialType === THREE.MeshBasicMaterial ) {
  1182. materialParams.color = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1183. } else {
  1184. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1185. }
  1186. }
  1187. if ( materialDef.emissiveTexture !== undefined ) {
  1188. if ( materialType === THREE.MeshBasicMaterial ) {
  1189. pending.push( parser.assignTexture( materialParams, 'map', materialDef.emissiveTexture.index ) );
  1190. } else {
  1191. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture.index ) );
  1192. }
  1193. }
  1194. return Promise.all( pending ).then( function () {
  1195. var material;
  1196. if ( materialType === THREE.ShaderMaterial ) {
  1197. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1198. } else {
  1199. material = new materialType( materialParams );
  1200. }
  1201. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  1202. // Normal map textures use OpenGL conventions:
  1203. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1204. if ( material.normalScale ) {
  1205. material.normalScale.x = - material.normalScale.x;
  1206. }
  1207. // emissiveTexture and baseColorTexture use sRGB encoding.
  1208. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1209. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1210. if ( materialDef.extras ) material.userData = materialDef.extras;
  1211. return material;
  1212. } );
  1213. };
  1214. /**
  1215. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1216. * @param {Array<Object>} primitives
  1217. * @return {Promise<Array<THREE.BufferGeometry>>}
  1218. */
  1219. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1220. var cache = this.primitiveCache;
  1221. return this.getDependencies( 'accessor' ).then( function ( accessors ) {
  1222. var geometries = [];
  1223. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1224. var primitive = primitives[ i ];
  1225. // See if we've already created this geometry
  1226. var cached = getCachedGeometry( cache, primitive );
  1227. if ( cached ) {
  1228. // Use the cached geometry if it exists
  1229. geometries.push( cached );
  1230. } else {
  1231. // Otherwise create a new geometry
  1232. var geometry = new THREE.BufferGeometry();
  1233. var attributes = primitive.attributes;
  1234. for ( var attributeId in attributes ) {
  1235. var attributeEntry = attributes[ attributeId ];
  1236. var bufferAttribute = accessors[ attributeEntry ];
  1237. switch ( attributeId ) {
  1238. case 'POSITION':
  1239. geometry.addAttribute( 'position', bufferAttribute );
  1240. break;
  1241. case 'NORMAL':
  1242. geometry.addAttribute( 'normal', bufferAttribute );
  1243. break;
  1244. case 'TEXCOORD_0':
  1245. case 'TEXCOORD0':
  1246. case 'TEXCOORD':
  1247. geometry.addAttribute( 'uv', bufferAttribute );
  1248. break;
  1249. case 'TEXCOORD_1':
  1250. geometry.addAttribute( 'uv2', bufferAttribute );
  1251. break;
  1252. case 'COLOR_0':
  1253. case 'COLOR0':
  1254. case 'COLOR':
  1255. geometry.addAttribute( 'color', bufferAttribute );
  1256. break;
  1257. case 'WEIGHTS_0':
  1258. case 'WEIGHT': // WEIGHT semantic deprecated.
  1259. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1260. break;
  1261. case 'JOINTS_0':
  1262. case 'JOINT': // JOINT semantic deprecated.
  1263. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1264. break;
  1265. }
  1266. }
  1267. if ( primitive.indices !== undefined ) {
  1268. geometry.setIndex( accessors[ primitive.indices ] );
  1269. }
  1270. // Cache this geometry
  1271. cache.push( {
  1272. primitive: primitive,
  1273. geometry: geometry
  1274. } );
  1275. geometries.push( geometry );
  1276. }
  1277. }
  1278. return geometries;
  1279. } );
  1280. };
  1281. /**
  1282. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1283. * @param {number} meshIndex
  1284. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1285. */
  1286. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1287. var scope = this;
  1288. var json = this.json;
  1289. var extensions = this.extensions;
  1290. var meshDef = this.json.meshes[ meshIndex ];
  1291. return this.getMultiDependencies( [
  1292. 'accessor',
  1293. 'material'
  1294. ] ).then( function ( dependencies ) {
  1295. var group = new THREE.Group();
  1296. var primitives = meshDef.primitives;
  1297. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  1298. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1299. var primitive = primitives[ i ];
  1300. var geometry = geometries[ i ];
  1301. var material = primitive.material === undefined
  1302. ? createDefaultMaterial()
  1303. : dependencies.materials[ primitive.material ];
  1304. if ( material.aoMap
  1305. && geometry.attributes.uv2 === undefined
  1306. && geometry.attributes.uv !== undefined ) {
  1307. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1308. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1309. }
  1310. // If the material will be modified later on, clone it now.
  1311. var useVertexColors = geometry.attributes.color !== undefined;
  1312. var useFlatShading = geometry.attributes.normal === undefined;
  1313. var useSkinning = meshDef.isSkinnedMesh === true;
  1314. var useMorphTargets = primitive.targets !== undefined;
  1315. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1316. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1317. var specGlossExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1318. material = specGlossExtension.cloneMaterial( material );
  1319. } else {
  1320. material = material.clone();
  1321. }
  1322. }
  1323. if ( useVertexColors ) {
  1324. material.vertexColors = THREE.VertexColors;
  1325. material.needsUpdate = true;
  1326. }
  1327. if ( useFlatShading ) {
  1328. material.flatShading = true;
  1329. }
  1330. var mesh;
  1331. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1332. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1333. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1334. primitive.mode === undefined ) {
  1335. if ( useSkinning ) {
  1336. mesh = new THREE.SkinnedMesh( geometry, material );
  1337. material.skinning = true;
  1338. } else {
  1339. mesh = new THREE.Mesh( geometry, material );
  1340. }
  1341. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1342. mesh.drawMode = THREE.TriangleStripDrawMode;
  1343. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1344. mesh.drawMode = THREE.TriangleFanDrawMode;
  1345. }
  1346. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ||
  1347. primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ||
  1348. primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1349. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1350. var lineMaterial = scope.cache.get( cacheKey );
  1351. if ( ! lineMaterial ) {
  1352. lineMaterial = new THREE.LineBasicMaterial();
  1353. THREE.Material.prototype.copy.call( lineMaterial, material );
  1354. lineMaterial.color.copy( material.color );
  1355. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  1356. scope.cache.add( cacheKey, lineMaterial );
  1357. }
  1358. material = lineMaterial;
  1359. if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1360. mesh = new THREE.LineSegments( geometry, material );
  1361. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1362. mesh = new THREE.Line( geometry, material );
  1363. } else {
  1364. mesh = new THREE.LineLoop( geometry, material );
  1365. }
  1366. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1367. var cacheKey = 'PointsMaterial:' + material.uuid;
  1368. var pointsMaterial = scope.cache.get( cacheKey );
  1369. if ( ! pointsMaterial ) {
  1370. pointsMaterial = new THREE.PointsMaterial();
  1371. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1372. pointsMaterial.color.copy( material.color );
  1373. pointsMaterial.map = material.map;
  1374. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  1375. scope.cache.add( cacheKey, pointsMaterial );
  1376. }
  1377. material = pointsMaterial;
  1378. mesh = new THREE.Points( geometry, material );
  1379. } else {
  1380. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1381. }
  1382. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1383. if ( useMorphTargets ) {
  1384. addMorphTargets( mesh, meshDef, primitive, dependencies.accessors );
  1385. }
  1386. if ( meshDef.extras !== undefined ) mesh.userData = meshDef.extras;
  1387. if ( primitive.extras !== undefined ) mesh.geometry.userData = primitive.extras;
  1388. // for Specular-Glossiness.
  1389. if ( material.isGLTFSpecularGlossinessMaterial === true ) {
  1390. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1391. }
  1392. if ( primitives.length > 1 ) {
  1393. mesh.name += '_' + i;
  1394. group.add( mesh );
  1395. } else {
  1396. return mesh;
  1397. }
  1398. }
  1399. return group;
  1400. } );
  1401. } );
  1402. };
  1403. /**
  1404. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1405. * @param {number} cameraIndex
  1406. * @return {Promise<THREE.Camera>}
  1407. */
  1408. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1409. var camera;
  1410. var cameraDef = this.json.cameras[ cameraIndex ];
  1411. var params = cameraDef[ cameraDef.type ];
  1412. if ( ! params ) {
  1413. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1414. return;
  1415. }
  1416. if ( cameraDef.type === 'perspective' ) {
  1417. var aspectRatio = params.aspectRatio || 1;
  1418. var xfov = params.yfov * aspectRatio;
  1419. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  1420. } else if ( cameraDef.type === 'orthographic' ) {
  1421. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1422. }
  1423. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1424. if ( cameraDef.extras ) camera.userData = cameraDef.extras;
  1425. return Promise.resolve( camera );
  1426. };
  1427. /**
  1428. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1429. * @param {number} skinIndex
  1430. * @return {Promise<Object>}
  1431. */
  1432. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1433. var skinDef = this.json.skins[ skinIndex ];
  1434. var skinEntry = { joints: skinDef.joints };
  1435. if ( skinDef.inverseBindMatrices === undefined ) {
  1436. return Promise.resolve( skinEntry );
  1437. }
  1438. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1439. skinEntry.inverseBindMatrices = accessor;
  1440. return skinEntry;
  1441. } );
  1442. };
  1443. /**
  1444. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1445. * @param {number} animationIndex
  1446. * @return {Promise<THREE.AnimationClip>}
  1447. */
  1448. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1449. var json = this.json;
  1450. var animationDef = this.json.animations[ animationIndex ];
  1451. return this.getMultiDependencies( [
  1452. 'accessor',
  1453. 'node'
  1454. ] ).then( function ( dependencies ) {
  1455. var tracks = [];
  1456. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1457. var channel = animationDef.channels[ i ];
  1458. var sampler = animationDef.samplers[ channel.sampler ];
  1459. if ( sampler ) {
  1460. var target = channel.target;
  1461. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1462. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1463. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1464. var inputAccessor = dependencies.accessors[ input ];
  1465. var outputAccessor = dependencies.accessors[ output ];
  1466. var node = dependencies.nodes[ name ];
  1467. if ( node ) {
  1468. node.updateMatrix();
  1469. node.matrixAutoUpdate = true;
  1470. var TypedKeyframeTrack;
  1471. switch ( PATH_PROPERTIES[ target.path ] ) {
  1472. case PATH_PROPERTIES.weights:
  1473. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1474. break;
  1475. case PATH_PROPERTIES.rotation:
  1476. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1477. break;
  1478. case PATH_PROPERTIES.position:
  1479. case PATH_PROPERTIES.scale:
  1480. default:
  1481. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1482. break;
  1483. }
  1484. var targetName = node.name ? node.name : node.uuid;
  1485. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1486. var targetNames = [];
  1487. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1488. // node should be THREE.Group here but
  1489. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1490. // the property of a mesh object under node.
  1491. // So finding targets here.
  1492. node.traverse( function ( object ) {
  1493. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1494. targetNames.push( object.name ? object.name : object.uuid );
  1495. }
  1496. } );
  1497. } else {
  1498. targetNames.push( targetName );
  1499. }
  1500. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1501. // buffers before creating a truncated copy to keep. Because buffers may
  1502. // be reused by other tracks, make copies here.
  1503. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1504. var track = new TypedKeyframeTrack(
  1505. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1506. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1507. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1508. interpolation
  1509. );
  1510. // Here is the trick to enable custom interpolation.
  1511. // Overrides .createInterpolant in a factory method which creates custom interpolation.
  1512. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1513. track.createInterpolant = function ( result ) {
  1514. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1515. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1516. // must be divided by three to get the interpolant's sampleSize argument.
  1517. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1518. };
  1519. }
  1520. tracks.push( track );
  1521. }
  1522. }
  1523. }
  1524. }
  1525. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  1526. return new THREE.AnimationClip( name, undefined, tracks );
  1527. } );
  1528. };
  1529. /**
  1530. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1531. * @param {number} nodeIndex
  1532. * @return {Promise<THREE.Object3D>}
  1533. */
  1534. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1535. var json = this.json;
  1536. var extensions = this.extensions;
  1537. var meshReferences = this.json.meshReferences;
  1538. var meshUses = this.json.meshUses;
  1539. var nodeDef = this.json.nodes[ nodeIndex ];
  1540. return this.getMultiDependencies( [
  1541. 'mesh',
  1542. 'skin',
  1543. 'camera'
  1544. ] ).then( function ( dependencies ) {
  1545. var node;
  1546. if ( nodeDef.isBone === true ) {
  1547. node = new THREE.Bone();
  1548. } else if ( nodeDef.mesh !== undefined ) {
  1549. var mesh = dependencies.meshes[ nodeDef.mesh ];
  1550. node = mesh.clone();
  1551. // for Specular-Glossiness
  1552. if ( mesh.isGroup === true ) {
  1553. for ( var i = 0, il = mesh.children.length; i < il; i ++ ) {
  1554. var child = mesh.children[ i ];
  1555. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial === true ) {
  1556. node.children[ i ].onBeforeRender = child.onBeforeRender;
  1557. }
  1558. }
  1559. } else {
  1560. if ( mesh.material && mesh.material.isGLTFSpecularGlossinessMaterial === true ) {
  1561. node.onBeforeRender = mesh.onBeforeRender;
  1562. }
  1563. }
  1564. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1565. node.name += '_instance_' + meshUses[ nodeDef.mesh ] ++;
  1566. }
  1567. } else if ( nodeDef.camera !== undefined ) {
  1568. node = dependencies.cameras[ nodeDef.camera ];
  1569. } else if ( nodeDef.extensions
  1570. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1571. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1572. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1573. node = lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
  1574. } else {
  1575. node = new THREE.Object3D();
  1576. }
  1577. if ( nodeDef.name !== undefined ) {
  1578. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1579. }
  1580. if ( nodeDef.extras ) node.userData = nodeDef.extras;
  1581. if ( nodeDef.matrix !== undefined ) {
  1582. var matrix = new THREE.Matrix4();
  1583. matrix.fromArray( nodeDef.matrix );
  1584. node.applyMatrix( matrix );
  1585. } else {
  1586. if ( nodeDef.translation !== undefined ) {
  1587. node.position.fromArray( nodeDef.translation );
  1588. }
  1589. if ( nodeDef.rotation !== undefined ) {
  1590. node.quaternion.fromArray( nodeDef.rotation );
  1591. }
  1592. if ( nodeDef.scale !== undefined ) {
  1593. node.scale.fromArray( nodeDef.scale );
  1594. }
  1595. }
  1596. return node;
  1597. } );
  1598. };
  1599. /**
  1600. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  1601. * @param {number} sceneIndex
  1602. * @return {Promise<THREE.Scene>}
  1603. */
  1604. GLTFParser.prototype.loadScene = function () {
  1605. // scene node hierachy builder
  1606. function buildNodeHierachy( nodeId, parentObject, json, allNodes, skins ) {
  1607. var node = allNodes[ nodeId ];
  1608. var nodeDef = json.nodes[ nodeId ];
  1609. // build skeleton here as well
  1610. if ( nodeDef.skin !== undefined ) {
  1611. var meshes = node.isGroup === true ? node.children : [ node ];
  1612. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1613. var mesh = meshes[ i ];
  1614. var skinEntry = skins[ nodeDef.skin ];
  1615. var bones = [];
  1616. var boneInverses = [];
  1617. for ( var j = 0, jl = skinEntry.joints.length; j < jl; j ++ ) {
  1618. var jointId = skinEntry.joints[ j ];
  1619. var jointNode = allNodes[ jointId ];
  1620. if ( jointNode ) {
  1621. bones.push( jointNode );
  1622. var mat = new THREE.Matrix4();
  1623. if ( skinEntry.inverseBindMatrices !== undefined ) {
  1624. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  1625. }
  1626. boneInverses.push( mat );
  1627. } else {
  1628. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  1629. }
  1630. }
  1631. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  1632. }
  1633. }
  1634. // build node hierachy
  1635. parentObject.add( node );
  1636. if ( nodeDef.children ) {
  1637. var children = nodeDef.children;
  1638. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1639. var child = children[ i ];
  1640. buildNodeHierachy( child, node, json, allNodes, skins );
  1641. }
  1642. }
  1643. }
  1644. return function loadScene( sceneIndex ) {
  1645. var json = this.json;
  1646. var extensions = this.extensions;
  1647. var sceneDef = this.json.scenes[ sceneIndex ];
  1648. return this.getMultiDependencies( [
  1649. 'node',
  1650. 'skin'
  1651. ] ).then( function ( dependencies ) {
  1652. var scene = new THREE.Scene();
  1653. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  1654. if ( sceneDef.extras ) scene.userData = sceneDef.extras;
  1655. var nodeIds = sceneDef.nodes || [];
  1656. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  1657. buildNodeHierachy( nodeIds[ i ], scene, json, dependencies.nodes, dependencies.skins );
  1658. }
  1659. // Ambient lighting, if present, is always attached to the scene root.
  1660. if ( sceneDef.extensions
  1661. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1662. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1663. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1664. scene.add( lights[ sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1665. }
  1666. return scene;
  1667. } );
  1668. };
  1669. }();
  1670. return GLTFLoader;
  1671. } )();