GLTFLoader.js 61 KB

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