GLTFLoader.js 56 KB

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