GLTFLoader.js 56 KB

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