GLTFLoader.js 60 KB

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