GLTFLoader.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411
  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. /**
  780. * TODO(donmccurdy): Why is all this necessary, again?
  781. * @param {GLTF.Node} nodeDef
  782. * @param {THREE.Group} group
  783. * @param {Array<THREE.Object3D>} nodes
  784. * @param {Array<Object} skins
  785. */
  786. function deepCloneMeshGroup( group ) {
  787. // Clone group's children manually.
  788. var clonedGroup = group.clone( false );
  789. for ( var i = 0; i < group.children.length; i ++ ) {
  790. var child = group.children[ i ];
  791. var clonedChild;
  792. switch ( child.type ) {
  793. case 'LineSegments':
  794. clonedChild = new THREE.LineSegments( child.geometry, child.material );
  795. break;
  796. case 'LineLoop':
  797. clonedChild = new THREE.LineLoop( child.geometry, child.material );
  798. break;
  799. case 'Line':
  800. clonedChild = new THREE.Line( child.geometry, child.material );
  801. break;
  802. case 'Points':
  803. clonedChild = new THREE.Points( child.geometry, child.material );
  804. break;
  805. default:
  806. clonedChild = new THREE.Mesh( child.geometry, child.material );
  807. clonedChild.drawMode = child.drawMode;
  808. }
  809. clonedChild.morphTargetInfluences = child.morphTargetInfluences;
  810. clonedChild.userData = child.userData;
  811. clonedChild.name = child.name;
  812. clonedGroup.add( clonedChild );
  813. }
  814. return clonedGroup;
  815. }
  816. /* GLTF PARSER */
  817. function GLTFParser( json, extensions, options ) {
  818. this.json = json || {};
  819. this.extensions = extensions || {};
  820. this.options = options || {};
  821. // loader object cache
  822. this.cache = new GLTFRegistry();
  823. }
  824. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  825. var _dependencies = {};
  826. for ( var i = 0; i < dependencies.length; i ++ ) {
  827. var dependency = dependencies[ i ];
  828. var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  829. var cached = this.cache.get( dependency );
  830. if ( cached !== undefined ) {
  831. _dependencies[ dependency ] = cached;
  832. } else if ( this[ fnName ] ) {
  833. var fn = this[ fnName ]();
  834. this.cache.add( dependency, fn );
  835. _dependencies[ dependency ] = fn;
  836. }
  837. }
  838. return _each( _dependencies, function ( dependency ) {
  839. return dependency;
  840. } );
  841. };
  842. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  843. var json = this.json;
  844. // Clear the loader cache
  845. this.cache.removeAll();
  846. // Fire the callback on complete
  847. this._withDependencies( [
  848. 'scenes',
  849. 'cameras',
  850. 'animations'
  851. ] ).then( function ( dependencies ) {
  852. var scenes = [];
  853. for ( var i = 0; i < dependencies.scenes.length; i ++ ) {
  854. scenes.push( dependencies.scenes[ i ] );
  855. }
  856. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  857. var cameras = [];
  858. dependencies.cameras = dependencies.cameras || [];
  859. for ( var i = 0; i < dependencies.cameras.length; i ++ ) {
  860. var camera = dependencies.cameras[ i ];
  861. cameras.push( camera );
  862. }
  863. var animations = [];
  864. dependencies.animations = dependencies.animations || [];
  865. for ( var i = 0; i < dependencies.animations.length; i ++ ) {
  866. animations.push( dependencies.animations[ i ] );
  867. }
  868. onLoad( scene, scenes, cameras, animations );
  869. } ).catch( onError );
  870. };
  871. /**
  872. * Requests the specified dependency asynchronously, with caching.
  873. * @param {string} type
  874. * @param {number} index
  875. * @return {Promise<Object>}
  876. */
  877. GLTFParser.prototype.getDependency = function ( type, index ) {
  878. var cacheKey = type + ':' + index;
  879. var dependency = this.cache.get( cacheKey );
  880. if ( ! dependency ) {
  881. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  882. dependency = this[ fnName ]( index );
  883. this.cache.add( cacheKey, dependency );
  884. }
  885. return dependency;
  886. };
  887. /**
  888. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  889. * @param {number} bufferIndex
  890. * @return {Promise<ArrayBuffer>}
  891. */
  892. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  893. var bufferDef = this.json.buffers[ bufferIndex ];
  894. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  895. throw new Error( 'THREE.GLTFLoader: %s buffer type is not supported.', bufferDef.type );
  896. }
  897. // If present, GLB container is required to be the first buffer.
  898. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  899. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  900. }
  901. var options = this.options;
  902. return new Promise( function ( resolve ) {
  903. var loader = new THREE.FileLoader();
  904. loader.setResponseType( 'arraybuffer' );
  905. loader.load( resolveURL( bufferDef.uri, options.path ), resolve );
  906. } );
  907. };
  908. /**
  909. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  910. * @param {number} bufferViewIndex
  911. * @return {Promise<ArrayBuffer>}
  912. */
  913. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  914. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  915. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  916. var byteLength = bufferViewDef.byteLength || 0;
  917. var byteOffset = bufferViewDef.byteOffset || 0;
  918. return buffer.slice( byteOffset, byteOffset + byteLength );
  919. } );
  920. };
  921. GLTFParser.prototype.loadAccessors = function () {
  922. var parser = this;
  923. var json = this.json;
  924. return _each( json.accessors, function ( accessor ) {
  925. return parser.getDependency( 'bufferView', accessor.bufferView ).then( function ( bufferView ) {
  926. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  927. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  928. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  929. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  930. var itemBytes = elementBytes * itemSize;
  931. var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
  932. var array;
  933. // The buffer is not interleaved if the stride is the item size in bytes.
  934. if ( byteStride && byteStride !== itemBytes ) {
  935. // Use the full buffer if it's interleaved.
  936. array = new TypedArray( bufferView );
  937. // Integer parameters to IB/IBA are in array elements, not bytes.
  938. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  939. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  940. } else {
  941. array = new TypedArray( bufferView, accessor.byteOffset, accessor.count * itemSize );
  942. return new THREE.BufferAttribute( array, itemSize );
  943. }
  944. } );
  945. } );
  946. };
  947. /**
  948. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  949. * @param {number} textureIndex
  950. * @return {Promise<THREE.Texture>}
  951. */
  952. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  953. var parser = this;
  954. var json = this.json;
  955. var options = this.options;
  956. var URL = window.URL || window.webkitURL;
  957. var textureDef = json.textures[ textureIndex ];
  958. var source = json.images[ textureDef.source ];
  959. var sourceURI = source.uri;
  960. var isObjectURL = false;
  961. if ( source.bufferView !== undefined ) {
  962. // Load binary image data from bufferView, if provided.
  963. sourceURI = parser.getDependency( 'bufferView', source.bufferView )
  964. .then( function ( bufferView ) {
  965. isObjectURL = true;
  966. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  967. sourceURI = URL.createObjectURL( blob );
  968. return sourceURI;
  969. } );
  970. }
  971. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  972. // Load Texture resource.
  973. var textureLoader = THREE.Loader.Handlers.get( sourceURI ) || new THREE.TextureLoader();
  974. textureLoader.setCrossOrigin( options.crossOrigin );
  975. return new Promise( function ( resolve, reject ) {
  976. textureLoader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  977. } );
  978. } ).then( function ( texture ) {
  979. // Clean up resources and configure Texture.
  980. if ( isObjectURL === true ) {
  981. URL.revokeObjectURL( sourceURI );
  982. }
  983. texture.flipY = false;
  984. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  985. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  986. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  987. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  988. 'internalFormat will be forced to be the same value as format.' );
  989. }
  990. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  991. var samplers = json.samplers || {};
  992. var sampler = samplers[ textureDef.sampler ] || {};
  993. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  994. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  995. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  996. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  997. return texture;
  998. } );
  999. };
  1000. /**
  1001. * Asynchronously assigns a texture to the given material parameters.
  1002. * @param {Object} materialParams
  1003. * @param {string} textureName
  1004. * @param {number} textureIndex
  1005. * @return {Promise}
  1006. */
  1007. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  1008. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  1009. materialParams[ textureName ] = texture;
  1010. } );
  1011. };
  1012. /**
  1013. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1014. * @return {Promise<Array<THREE.Material>>}
  1015. */
  1016. GLTFParser.prototype.loadMaterials = function () {
  1017. var parser = this;
  1018. var json = this.json;
  1019. var extensions = this.extensions;
  1020. return _each( json.materials, function ( material ) {
  1021. var materialType;
  1022. var materialParams = {};
  1023. var materialExtensions = material.extensions || {};
  1024. var pending = [];
  1025. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  1026. var khcExtension = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  1027. materialType = khcExtension.getMaterialType( material );
  1028. pending.push( khcExtension.extendParams( materialParams, material, parser ) );
  1029. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1030. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1031. materialType = sgExtension.getMaterialType( material );
  1032. pending.push( sgExtension.extendParams( materialParams, material, parser ) );
  1033. } else if ( material.pbrMetallicRoughness !== undefined ) {
  1034. // Specification:
  1035. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1036. materialType = THREE.MeshStandardMaterial;
  1037. var metallicRoughness = material.pbrMetallicRoughness;
  1038. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1039. materialParams.opacity = 1.0;
  1040. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1041. var array = metallicRoughness.baseColorFactor;
  1042. materialParams.color.fromArray( array );
  1043. materialParams.opacity = array[ 3 ];
  1044. }
  1045. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1046. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  1047. }
  1048. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1049. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1050. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1051. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1052. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  1053. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  1054. }
  1055. } else {
  1056. materialType = THREE.MeshPhongMaterial;
  1057. }
  1058. if ( material.doubleSided === true ) {
  1059. materialParams.side = THREE.DoubleSide;
  1060. }
  1061. var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;
  1062. if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
  1063. materialParams.transparent = true;
  1064. if ( alphaMode === ALPHA_MODES.MASK ) {
  1065. materialParams.alphaTest = material.alphaCutoff || 0.5;
  1066. }
  1067. } else {
  1068. materialParams.transparent = false;
  1069. }
  1070. if ( material.normalTexture !== undefined ) {
  1071. pending.push( parser.assignTexture( materialParams, 'normalMap', material.normalTexture.index ) );
  1072. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1073. if ( material.normalTexture.scale !== undefined ) {
  1074. materialParams.normalScale.set( material.normalTexture.scale, material.normalTexture.scale );
  1075. }
  1076. }
  1077. if ( material.occlusionTexture !== undefined ) {
  1078. pending.push( parser.assignTexture( materialParams, 'aoMap', material.occlusionTexture.index ) );
  1079. if ( material.occlusionTexture.strength !== undefined ) {
  1080. materialParams.aoMapIntensity = material.occlusionTexture.strength;
  1081. }
  1082. }
  1083. if ( material.emissiveFactor !== undefined ) {
  1084. if ( materialType === THREE.MeshBasicMaterial ) {
  1085. materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
  1086. } else {
  1087. materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
  1088. }
  1089. }
  1090. if ( material.emissiveTexture !== undefined ) {
  1091. if ( materialType === THREE.MeshBasicMaterial ) {
  1092. pending.push( parser.assignTexture( materialParams, 'map', material.emissiveTexture.index ) );
  1093. } else {
  1094. pending.push( parser.assignTexture( materialParams, 'emissiveMap', material.emissiveTexture.index ) );
  1095. }
  1096. }
  1097. return Promise.all( pending ).then( function () {
  1098. var _material;
  1099. if ( materialType === THREE.ShaderMaterial ) {
  1100. _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1101. } else {
  1102. _material = new materialType( materialParams );
  1103. }
  1104. if ( material.name !== undefined ) _material.name = material.name;
  1105. // Normal map textures use OpenGL conventions:
  1106. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1107. if ( _material.normalScale ) {
  1108. _material.normalScale.x = - _material.normalScale.x;
  1109. }
  1110. // emissiveTexture and baseColorTexture use sRGB encoding.
  1111. if ( _material.map ) _material.map.encoding = THREE.sRGBEncoding;
  1112. if ( _material.emissiveMap ) _material.emissiveMap.encoding = THREE.sRGBEncoding;
  1113. if ( material.extras ) _material.userData = material.extras;
  1114. return _material;
  1115. } );
  1116. } );
  1117. };
  1118. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1119. return this._withDependencies( [
  1120. 'accessors',
  1121. ] ).then( function ( dependencies ) {
  1122. return _each( primitives, function ( primitive ) {
  1123. var geometry = new THREE.BufferGeometry();
  1124. var attributes = primitive.attributes;
  1125. for ( var attributeId in attributes ) {
  1126. var attributeEntry = attributes[ attributeId ];
  1127. if ( attributeEntry === undefined ) return;
  1128. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1129. switch ( attributeId ) {
  1130. case 'POSITION':
  1131. geometry.addAttribute( 'position', bufferAttribute );
  1132. break;
  1133. case 'NORMAL':
  1134. geometry.addAttribute( 'normal', bufferAttribute );
  1135. break;
  1136. case 'TEXCOORD_0':
  1137. case 'TEXCOORD0':
  1138. case 'TEXCOORD':
  1139. geometry.addAttribute( 'uv', bufferAttribute );
  1140. break;
  1141. case 'TEXCOORD_1':
  1142. geometry.addAttribute( 'uv2', bufferAttribute );
  1143. break;
  1144. case 'COLOR_0':
  1145. case 'COLOR0':
  1146. case 'COLOR':
  1147. geometry.addAttribute( 'color', bufferAttribute );
  1148. break;
  1149. case 'WEIGHTS_0':
  1150. case 'WEIGHT': // WEIGHT semantic deprecated.
  1151. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1152. break;
  1153. case 'JOINTS_0':
  1154. case 'JOINT': // JOINT semantic deprecated.
  1155. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1156. break;
  1157. }
  1158. }
  1159. if ( primitive.indices !== undefined ) {
  1160. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1161. }
  1162. return geometry;
  1163. } );
  1164. } );
  1165. };
  1166. /**
  1167. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1168. */
  1169. GLTFParser.prototype.loadMeshes = function () {
  1170. var scope = this;
  1171. var json = this.json;
  1172. return this._withDependencies( [
  1173. 'accessors',
  1174. 'materials'
  1175. ] ).then( function ( dependencies ) {
  1176. return _each( json.meshes, function ( meshDef ) {
  1177. var group = new THREE.Group();
  1178. if ( meshDef.name !== undefined ) group.name = meshDef.name;
  1179. if ( meshDef.extras ) group.userData = meshDef.extras;
  1180. var primitives = meshDef.primitives || [];
  1181. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  1182. for ( var i = 0; i < primitives.length; i ++ ) {
  1183. var primitive = primitives[ i ];
  1184. var geometry = geometries[ i ];
  1185. var material = primitive.material === undefined
  1186. ? createDefaultMaterial()
  1187. : dependencies.materials[ primitive.material ];
  1188. if ( material.aoMap
  1189. && geometry.attributes.uv2 === undefined
  1190. && geometry.attributes.uv !== undefined ) {
  1191. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1192. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1193. }
  1194. var useVertexColors = geometry.attributes.color !== undefined;
  1195. var useFlatShading = geometry.attributes.normal === undefined;
  1196. if ( useVertexColors || useFlatShading ) {
  1197. material = material.clone();
  1198. }
  1199. if ( useVertexColors ) {
  1200. material.vertexColors = THREE.VertexColors;
  1201. material.needsUpdate = true;
  1202. }
  1203. if ( useFlatShading ) {
  1204. material.flatShading = true;
  1205. }
  1206. var mesh;
  1207. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  1208. mesh = new THREE.Mesh( geometry, material );
  1209. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1210. mesh = new THREE.Mesh( geometry, material );
  1211. mesh.drawMode = THREE.TriangleStripDrawMode;
  1212. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1213. mesh = new THREE.Mesh( geometry, material );
  1214. mesh.drawMode = THREE.TriangleFanDrawMode;
  1215. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1216. mesh = new THREE.LineSegments( geometry, material );
  1217. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1218. mesh = new THREE.Line( geometry, material );
  1219. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1220. mesh = new THREE.LineLoop( geometry, material );
  1221. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1222. mesh = new THREE.Points( geometry, material );
  1223. } else {
  1224. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ', primitive.mode );
  1225. }
  1226. mesh.name = group.name + '_' + i;
  1227. if ( primitive.targets !== undefined ) {
  1228. addMorphTargets( mesh, meshDef, primitive, dependencies );
  1229. }
  1230. if ( primitive.extras ) mesh.userData = primitive.extras;
  1231. group.add( mesh );
  1232. }
  1233. return group;
  1234. } );
  1235. } );
  1236. } );
  1237. };
  1238. /**
  1239. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1240. */
  1241. GLTFParser.prototype.loadCameras = function () {
  1242. var json = this.json;
  1243. return _each( json.cameras, function ( camera ) {
  1244. var _camera;
  1245. var params = camera[ camera.type ];
  1246. if ( ! params ) {
  1247. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1248. return;
  1249. }
  1250. if ( camera.type === 'perspective' ) {
  1251. var aspectRatio = params.aspectRatio || 1;
  1252. var xfov = params.yfov * aspectRatio;
  1253. _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  1254. } else if ( camera.type === 'orthographic' ) {
  1255. _camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1256. }
  1257. if ( camera.name !== undefined ) _camera.name = camera.name;
  1258. if ( camera.extras ) _camera.userData = camera.extras;
  1259. return _camera;
  1260. } );
  1261. };
  1262. GLTFParser.prototype.loadSkins = function () {
  1263. var json = this.json;
  1264. return this._withDependencies( [
  1265. 'accessors'
  1266. ] ).then( function ( dependencies ) {
  1267. return _each( json.skins, function ( skin ) {
  1268. var _skin = {
  1269. joints: skin.joints,
  1270. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1271. };
  1272. return _skin;
  1273. } );
  1274. } );
  1275. };
  1276. GLTFParser.prototype.loadAnimations = function () {
  1277. var json = this.json;
  1278. return this._withDependencies( [
  1279. 'accessors',
  1280. 'nodes'
  1281. ] ).then( function ( dependencies ) {
  1282. return _each( json.animations, function ( animation, animationId ) {
  1283. var tracks = [];
  1284. for ( var i = 0; i < animation.channels.length; i ++ ) {
  1285. var channel = animation.channels[ i ];
  1286. var sampler = animation.samplers[ channel.sampler ];
  1287. if ( sampler ) {
  1288. var target = channel.target;
  1289. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1290. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1291. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1292. var inputAccessor = dependencies.accessors[ input ];
  1293. var outputAccessor = dependencies.accessors[ output ];
  1294. var node = dependencies.nodes[ name ];
  1295. if ( node ) {
  1296. node.updateMatrix();
  1297. node.matrixAutoUpdate = true;
  1298. var TypedKeyframeTrack;
  1299. switch ( PATH_PROPERTIES[ target.path ] ) {
  1300. case PATH_PROPERTIES.weights:
  1301. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1302. break;
  1303. case PATH_PROPERTIES.rotation:
  1304. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1305. break;
  1306. case PATH_PROPERTIES.position:
  1307. case PATH_PROPERTIES.scale:
  1308. default:
  1309. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1310. break;
  1311. }
  1312. var targetName = node.name ? node.name : node.uuid;
  1313. if ( sampler.interpolation === 'CATMULLROMSPLINE' ) {
  1314. console.warn( 'THREE.GLTFLoader: CATMULLROMSPLINE interpolation is not supported. Using CUBICSPLINE instead.' );
  1315. }
  1316. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1317. var targetNames = [];
  1318. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1319. // node should be THREE.Group here but
  1320. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1321. // the property of a mesh object under node.
  1322. // So finding targets here.
  1323. node.traverse( function ( object ) {
  1324. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1325. targetNames.push( object.name ? object.name : object.uuid );
  1326. }
  1327. } );
  1328. } else {
  1329. targetNames.push( targetName );
  1330. }
  1331. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1332. // buffers before creating a truncated copy to keep. Because buffers may
  1333. // be reused by other tracks, make copies here.
  1334. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1335. tracks.push( new TypedKeyframeTrack(
  1336. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1337. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1338. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1339. interpolation
  1340. ) );
  1341. }
  1342. }
  1343. }
  1344. }
  1345. var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
  1346. return new THREE.AnimationClip( name, undefined, tracks );
  1347. } );
  1348. } );
  1349. };
  1350. GLTFParser.prototype.loadNodes = function () {
  1351. var json = this.json;
  1352. var extensions = this.extensions;
  1353. var scope = this;
  1354. var nodes = json.nodes || [];
  1355. var skins = json.skins || [];
  1356. // Nothing in the node definition indicates whether it is a Bone or an
  1357. // Object3D. Use the skins' joint references to mark bones.
  1358. skins.forEach( function ( skin ) {
  1359. skin.joints.forEach( function ( id ) {
  1360. nodes[ id ].isBone = true;
  1361. } );
  1362. } );
  1363. return scope._withDependencies( [
  1364. 'meshes',
  1365. 'skins',
  1366. 'cameras'
  1367. ] ).then( function ( dependencies ) {
  1368. return _each( json.nodes, function ( nodeDef ) {
  1369. if ( nodeDef.isBone === true ) {
  1370. return new THREE.Bone();
  1371. } else if ( nodeDef.mesh !== undefined ) {
  1372. return deepCloneMeshGroup( dependencies.meshes[ nodeDef.mesh ] );
  1373. } else if ( nodeDef.camera !== undefined ) {
  1374. return dependencies.cameras[ nodeDef.camera ];
  1375. } else if ( nodeDef.extensions
  1376. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1377. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1378. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1379. return lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
  1380. } else {
  1381. return new THREE.Object3D();
  1382. }
  1383. } ).then( function ( __nodes ) {
  1384. return _each( __nodes, function ( node, nodeIndex ) {
  1385. var nodeDef = json.nodes[ nodeIndex ];
  1386. if ( nodeDef.name !== undefined ) {
  1387. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1388. }
  1389. if ( nodeDef.extras ) node.userData = nodeDef.extras;
  1390. if ( nodeDef.matrix !== undefined ) {
  1391. var matrix = new THREE.Matrix4();
  1392. matrix.fromArray( nodeDef.matrix );
  1393. node.applyMatrix( matrix );
  1394. } else {
  1395. if ( nodeDef.translation !== undefined ) {
  1396. node.position.fromArray( nodeDef.translation );
  1397. }
  1398. if ( nodeDef.rotation !== undefined ) {
  1399. node.quaternion.fromArray( nodeDef.rotation );
  1400. }
  1401. if ( nodeDef.scale !== undefined ) {
  1402. node.scale.fromArray( nodeDef.scale );
  1403. }
  1404. }
  1405. if ( nodeDef.skin !== undefined ) {
  1406. var skinnedMeshes = [];
  1407. for ( var i = 0; i < node.children.length; i ++ ) {
  1408. var skinEntry = dependencies.skins[ nodeDef.skin ];
  1409. // Replace Mesh with SkinnedMesh.
  1410. var geometry = node.children[ i ].geometry;
  1411. var material = node.children[ i ].material;
  1412. material.skinning = true;
  1413. var child = new THREE.SkinnedMesh( geometry, material );
  1414. child.morphTargetInfluences = node.children[ i ].morphTargetInfluences;
  1415. child.userData = node.children[ i ].userData;
  1416. child.name = node.children[ i ].name;
  1417. var bones = [];
  1418. var boneInverses = [];
  1419. for ( var j = 0, l = skinEntry.joints.length; j < l; j ++ ) {
  1420. var jointId = skinEntry.joints[ j ];
  1421. var jointNode = __nodes[ jointId ];
  1422. if ( jointNode ) {
  1423. bones.push( jointNode );
  1424. var m = skinEntry.inverseBindMatrices.array;
  1425. var mat = new THREE.Matrix4().fromArray( m, j * 16 );
  1426. boneInverses.push( mat );
  1427. } else {
  1428. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  1429. }
  1430. }
  1431. child.bind( new THREE.Skeleton( bones, boneInverses ), child.matrixWorld );
  1432. skinnedMeshes.push( child );
  1433. }
  1434. node.remove.apply( node, node.children );
  1435. node.add.apply( node, skinnedMeshes );
  1436. }
  1437. return node;
  1438. } );
  1439. } );
  1440. } );
  1441. };
  1442. GLTFParser.prototype.loadScenes = function () {
  1443. var json = this.json;
  1444. var extensions = this.extensions;
  1445. // scene node hierachy builder
  1446. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1447. var _node = allNodes[ nodeId ];
  1448. parentObject.add( _node );
  1449. var node = json.nodes[ nodeId ];
  1450. if ( node.children ) {
  1451. var children = node.children;
  1452. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1453. var child = children[ i ];
  1454. buildNodeHierachy( child, _node, allNodes );
  1455. }
  1456. }
  1457. }
  1458. return this._withDependencies( [
  1459. 'nodes'
  1460. ] ).then( function ( dependencies ) {
  1461. return _each( json.scenes, function ( scene ) {
  1462. var _scene = new THREE.Scene();
  1463. if ( scene.name !== undefined ) _scene.name = scene.name;
  1464. if ( scene.extras ) _scene.userData = scene.extras;
  1465. var nodes = scene.nodes || [];
  1466. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1467. var nodeId = nodes[ i ];
  1468. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1469. }
  1470. _scene.traverse( function ( child ) {
  1471. // for Specular-Glossiness.
  1472. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial ) {
  1473. child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1474. }
  1475. } );
  1476. // Ambient lighting, if present, is always attached to the scene root.
  1477. if ( scene.extensions
  1478. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1479. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1480. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1481. _scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1482. }
  1483. return _scene;
  1484. } );
  1485. } );
  1486. };
  1487. return GLTFLoader;
  1488. } )();