GLTFLoader.js 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639
  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.LoaderUtils.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. onError( e );
  26. } else {
  27. throw e;
  28. }
  29. }
  30. }, onProgress, onError );
  31. },
  32. setCrossOrigin: function ( value ) {
  33. this.crossOrigin = value;
  34. return this;
  35. },
  36. setPath: function ( value ) {
  37. this.path = value;
  38. return this;
  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 = THREE.LoaderUtils.decodeText( 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 = THREE.LoaderUtils.decodeText( 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. Use LegacyGLTFLoader instead.' ) );
  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. } );
  81. parser.parse( function ( scene, scenes, cameras, animations, asset ) {
  82. console.timeEnd( 'GLTFLoader' );
  83. var glTF = {
  84. scene: scene,
  85. scenes: scenes,
  86. cameras: cameras,
  87. animations: animations,
  88. asset: asset
  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: THREE.LoaderUtils.decodeText( 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 LegacyGLTFLoader 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 = THREE.LoaderUtils.decodeText( 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. ' texelSpecular = sRGBToLinear( texelSpecular );',
  328. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  329. ' specularFactor *= texelSpecular.rgb;',
  330. '#endif'
  331. ].join( '\n' );
  332. var glossinessMapFragmentChunk = [
  333. 'float glossinessFactor = glossiness;',
  334. '#ifdef USE_GLOSSINESSMAP',
  335. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  336. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  337. ' glossinessFactor *= texelGlossiness.a;',
  338. '#endif'
  339. ].join( '\n' );
  340. var lightPhysicalFragmentChunk = [
  341. 'PhysicalMaterial material;',
  342. 'material.diffuseColor = diffuseColor.rgb;',
  343. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  344. 'material.specularColor = specularFactor.rgb;',
  345. ].join( '\n' );
  346. var fragmentShader = shader.fragmentShader
  347. .replace( '#include <specularmap_fragment>', '' )
  348. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  349. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  350. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  351. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  352. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  353. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  354. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  355. delete uniforms.roughness;
  356. delete uniforms.metalness;
  357. delete uniforms.roughnessMap;
  358. delete uniforms.metalnessMap;
  359. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  360. uniforms.glossiness = { value: 0.5 };
  361. uniforms.specularMap = { value: null };
  362. uniforms.glossinessMap = { value: null };
  363. params.vertexShader = shader.vertexShader;
  364. params.fragmentShader = fragmentShader;
  365. params.uniforms = uniforms;
  366. params.defines = { 'STANDARD': '' };
  367. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  368. params.opacity = 1.0;
  369. var pending = [];
  370. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  371. var array = pbrSpecularGlossiness.diffuseFactor;
  372. params.color.fromArray( array );
  373. params.opacity = array[ 3 ];
  374. }
  375. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  376. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  377. }
  378. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  379. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  380. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  381. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  382. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  383. }
  384. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  385. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  386. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  387. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  388. }
  389. return Promise.all( pending );
  390. },
  391. createMaterial: function ( params ) {
  392. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  393. var material = new THREE.ShaderMaterial( {
  394. defines: params.defines,
  395. vertexShader: params.vertexShader,
  396. fragmentShader: params.fragmentShader,
  397. uniforms: params.uniforms,
  398. fog: true,
  399. lights: true,
  400. opacity: params.opacity,
  401. transparent: params.transparent
  402. } );
  403. material.isGLTFSpecularGlossinessMaterial = true;
  404. material.color = params.color;
  405. material.map = params.map === undefined ? null : params.map;
  406. material.lightMap = null;
  407. material.lightMapIntensity = 1.0;
  408. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  409. material.aoMapIntensity = 1.0;
  410. material.emissive = params.emissive;
  411. material.emissiveIntensity = 1.0;
  412. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  413. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  414. material.bumpScale = 1;
  415. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  416. if ( params.normalScale ) material.normalScale = params.normalScale;
  417. material.displacementMap = null;
  418. material.displacementScale = 1;
  419. material.displacementBias = 0;
  420. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  421. material.specular = params.specular;
  422. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  423. material.glossiness = params.glossiness;
  424. material.alphaMap = null;
  425. material.envMap = params.envMap === undefined ? null : params.envMap;
  426. material.envMapIntensity = 1.0;
  427. material.refractionRatio = 0.98;
  428. material.extensions.derivatives = true;
  429. return material;
  430. },
  431. /**
  432. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  433. * copy only properties it knows about or inherits, and misses many properties that would
  434. * normally be defined by MeshStandardMaterial.
  435. *
  436. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  437. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  438. * AND also updating `.onBeforeRender` on the parent mesh.
  439. *
  440. * @param {THREE.ShaderMaterial} source
  441. * @return {THREE.ShaderMaterial}
  442. */
  443. cloneMaterial: function ( source ) {
  444. var target = source.clone();
  445. target.isGLTFSpecularGlossinessMaterial = true;
  446. var params = this.specularGlossinessParams;
  447. for ( var i = 0, il = params.length; i < il; i ++ ) {
  448. target[ params[ i ] ] = source[ params[ i ] ];
  449. }
  450. return target;
  451. },
  452. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  453. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  454. var uniforms = material.uniforms;
  455. var defines = material.defines;
  456. uniforms.opacity.value = material.opacity;
  457. uniforms.diffuse.value.copy( material.color );
  458. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  459. uniforms.map.value = material.map;
  460. uniforms.specularMap.value = material.specularMap;
  461. uniforms.alphaMap.value = material.alphaMap;
  462. uniforms.lightMap.value = material.lightMap;
  463. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  464. uniforms.aoMap.value = material.aoMap;
  465. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  466. // uv repeat and offset setting priorities
  467. // 1. color map
  468. // 2. specular map
  469. // 3. normal map
  470. // 4. bump map
  471. // 5. alpha map
  472. // 6. emissive map
  473. var uvScaleMap;
  474. if ( material.map ) {
  475. uvScaleMap = material.map;
  476. } else if ( material.specularMap ) {
  477. uvScaleMap = material.specularMap;
  478. } else if ( material.displacementMap ) {
  479. uvScaleMap = material.displacementMap;
  480. } else if ( material.normalMap ) {
  481. uvScaleMap = material.normalMap;
  482. } else if ( material.bumpMap ) {
  483. uvScaleMap = material.bumpMap;
  484. } else if ( material.glossinessMap ) {
  485. uvScaleMap = material.glossinessMap;
  486. } else if ( material.alphaMap ) {
  487. uvScaleMap = material.alphaMap;
  488. } else if ( material.emissiveMap ) {
  489. uvScaleMap = material.emissiveMap;
  490. }
  491. if ( uvScaleMap !== undefined ) {
  492. // backwards compatibility
  493. if ( uvScaleMap.isWebGLRenderTarget ) {
  494. uvScaleMap = uvScaleMap.texture;
  495. }
  496. var offset;
  497. var repeat;
  498. if ( uvScaleMap.matrix !== undefined ) {
  499. // > r88.
  500. if ( uvScaleMap.matrixAutoUpdate === true ) {
  501. offset = uvScaleMap.offset;
  502. repeat = uvScaleMap.repeat;
  503. var rotation = uvScaleMap.rotation;
  504. var center = uvScaleMap.center;
  505. uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );
  506. }
  507. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  508. } else {
  509. // <= r87. Remove when reasonable.
  510. offset = uvScaleMap.offset;
  511. repeat = uvScaleMap.repeat;
  512. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  513. }
  514. }
  515. uniforms.envMap.value = material.envMap;
  516. uniforms.envMapIntensity.value = material.envMapIntensity;
  517. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  518. uniforms.refractionRatio.value = material.refractionRatio;
  519. uniforms.specular.value.copy( material.specular );
  520. uniforms.glossiness.value = material.glossiness;
  521. uniforms.glossinessMap.value = material.glossinessMap;
  522. uniforms.emissiveMap.value = material.emissiveMap;
  523. uniforms.bumpMap.value = material.bumpMap;
  524. uniforms.normalMap.value = material.normalMap;
  525. uniforms.displacementMap.value = material.displacementMap;
  526. uniforms.displacementScale.value = material.displacementScale;
  527. uniforms.displacementBias.value = material.displacementBias;
  528. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  529. defines.USE_GLOSSINESSMAP = '';
  530. // set USE_ROUGHNESSMAP to enable vUv
  531. defines.USE_ROUGHNESSMAP = '';
  532. }
  533. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  534. delete defines.USE_GLOSSINESSMAP;
  535. delete defines.USE_ROUGHNESSMAP;
  536. }
  537. }
  538. };
  539. }
  540. /*********************************/
  541. /********** INTERNALS ************/
  542. /*********************************/
  543. /* CONSTANTS */
  544. var WEBGL_CONSTANTS = {
  545. FLOAT: 5126,
  546. //FLOAT_MAT2: 35674,
  547. FLOAT_MAT3: 35675,
  548. FLOAT_MAT4: 35676,
  549. FLOAT_VEC2: 35664,
  550. FLOAT_VEC3: 35665,
  551. FLOAT_VEC4: 35666,
  552. LINEAR: 9729,
  553. REPEAT: 10497,
  554. SAMPLER_2D: 35678,
  555. POINTS: 0,
  556. LINES: 1,
  557. LINE_LOOP: 2,
  558. LINE_STRIP: 3,
  559. TRIANGLES: 4,
  560. TRIANGLE_STRIP: 5,
  561. TRIANGLE_FAN: 6,
  562. UNSIGNED_BYTE: 5121,
  563. UNSIGNED_SHORT: 5123
  564. };
  565. var WEBGL_TYPE = {
  566. 5126: Number,
  567. //35674: THREE.Matrix2,
  568. 35675: THREE.Matrix3,
  569. 35676: THREE.Matrix4,
  570. 35664: THREE.Vector2,
  571. 35665: THREE.Vector3,
  572. 35666: THREE.Vector4,
  573. 35678: THREE.Texture
  574. };
  575. var WEBGL_COMPONENT_TYPES = {
  576. 5120: Int8Array,
  577. 5121: Uint8Array,
  578. 5122: Int16Array,
  579. 5123: Uint16Array,
  580. 5125: Uint32Array,
  581. 5126: Float32Array
  582. };
  583. var WEBGL_FILTERS = {
  584. 9728: THREE.NearestFilter,
  585. 9729: THREE.LinearFilter,
  586. 9984: THREE.NearestMipMapNearestFilter,
  587. 9985: THREE.LinearMipMapNearestFilter,
  588. 9986: THREE.NearestMipMapLinearFilter,
  589. 9987: THREE.LinearMipMapLinearFilter
  590. };
  591. var WEBGL_WRAPPINGS = {
  592. 33071: THREE.ClampToEdgeWrapping,
  593. 33648: THREE.MirroredRepeatWrapping,
  594. 10497: THREE.RepeatWrapping
  595. };
  596. var WEBGL_TEXTURE_FORMATS = {
  597. 6406: THREE.AlphaFormat,
  598. 6407: THREE.RGBFormat,
  599. 6408: THREE.RGBAFormat,
  600. 6409: THREE.LuminanceFormat,
  601. 6410: THREE.LuminanceAlphaFormat
  602. };
  603. var WEBGL_TEXTURE_DATATYPES = {
  604. 5121: THREE.UnsignedByteType,
  605. 32819: THREE.UnsignedShort4444Type,
  606. 32820: THREE.UnsignedShort5551Type,
  607. 33635: THREE.UnsignedShort565Type
  608. };
  609. var WEBGL_SIDES = {
  610. 1028: THREE.BackSide, // Culling front
  611. 1029: THREE.FrontSide // Culling back
  612. //1032: THREE.NoSide // Culling front and back, what to do?
  613. };
  614. var WEBGL_DEPTH_FUNCS = {
  615. 512: THREE.NeverDepth,
  616. 513: THREE.LessDepth,
  617. 514: THREE.EqualDepth,
  618. 515: THREE.LessEqualDepth,
  619. 516: THREE.GreaterEqualDepth,
  620. 517: THREE.NotEqualDepth,
  621. 518: THREE.GreaterEqualDepth,
  622. 519: THREE.AlwaysDepth
  623. };
  624. var WEBGL_BLEND_EQUATIONS = {
  625. 32774: THREE.AddEquation,
  626. 32778: THREE.SubtractEquation,
  627. 32779: THREE.ReverseSubtractEquation
  628. };
  629. var WEBGL_BLEND_FUNCS = {
  630. 0: THREE.ZeroFactor,
  631. 1: THREE.OneFactor,
  632. 768: THREE.SrcColorFactor,
  633. 769: THREE.OneMinusSrcColorFactor,
  634. 770: THREE.SrcAlphaFactor,
  635. 771: THREE.OneMinusSrcAlphaFactor,
  636. 772: THREE.DstAlphaFactor,
  637. 773: THREE.OneMinusDstAlphaFactor,
  638. 774: THREE.DstColorFactor,
  639. 775: THREE.OneMinusDstColorFactor,
  640. 776: THREE.SrcAlphaSaturateFactor
  641. // The followings are not supported by Three.js yet
  642. //32769: CONSTANT_COLOR,
  643. //32770: ONE_MINUS_CONSTANT_COLOR,
  644. //32771: CONSTANT_ALPHA,
  645. //32772: ONE_MINUS_CONSTANT_COLOR
  646. };
  647. var WEBGL_TYPE_SIZES = {
  648. 'SCALAR': 1,
  649. 'VEC2': 2,
  650. 'VEC3': 3,
  651. 'VEC4': 4,
  652. 'MAT2': 4,
  653. 'MAT3': 9,
  654. 'MAT4': 16
  655. };
  656. var PATH_PROPERTIES = {
  657. scale: 'scale',
  658. translation: 'position',
  659. rotation: 'quaternion',
  660. weights: 'morphTargetInfluences'
  661. };
  662. var INTERPOLATION = {
  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 resolveURL( url, path ) {
  682. // Invalid URL
  683. if ( typeof url !== 'string' || url === '' ) return '';
  684. // Absolute URL http://,https://,//
  685. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  686. // Data URI
  687. if ( /^data:.*,.*$/i.test( url ) ) return url;
  688. // Blob URL
  689. if ( /^blob:.*$/i.test( url ) ) return url;
  690. // Relative URL
  691. return path + url;
  692. }
  693. /**
  694. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  695. */
  696. function createDefaultMaterial() {
  697. return new THREE.MeshStandardMaterial( {
  698. color: 0xFFFFFF,
  699. emissive: 0x000000,
  700. metalness: 1,
  701. roughness: 1,
  702. transparent: false,
  703. depthTest: true,
  704. side: THREE.FrontSide
  705. } );
  706. }
  707. /**
  708. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  709. *
  710. * TODO: Implement support for morph targets on TANGENT attribute.
  711. *
  712. * @param {THREE.Mesh} mesh
  713. * @param {GLTF.Mesh} meshDef
  714. * @param {GLTF.Primitive} primitiveDef
  715. * @param {Array<THREE.BufferAttribute>} accessors
  716. */
  717. function addMorphTargets( mesh, meshDef, primitiveDef, accessors ) {
  718. var geometry = mesh.geometry;
  719. var material = mesh.material;
  720. var targets = primitiveDef.targets;
  721. var morphAttributes = geometry.morphAttributes;
  722. morphAttributes.position = [];
  723. morphAttributes.normal = [];
  724. material.morphTargets = true;
  725. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  726. var target = targets[ i ];
  727. var attributeName = 'morphTarget' + i;
  728. var positionAttribute, normalAttribute;
  729. if ( target.POSITION !== undefined ) {
  730. // Three.js morph formula is
  731. // position
  732. // + weight0 * ( morphTarget0 - position )
  733. // + weight1 * ( morphTarget1 - position )
  734. // ...
  735. // while the glTF one is
  736. // position
  737. // + weight0 * morphTarget0
  738. // + weight1 * morphTarget1
  739. // ...
  740. // then adding position to morphTarget.
  741. // So morphTarget value will depend on mesh's position, then cloning attribute
  742. // for the case if attribute is shared among two or more meshes.
  743. positionAttribute = accessors[ target.POSITION ].clone();
  744. var position = geometry.attributes.position;
  745. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  746. positionAttribute.setXYZ(
  747. j,
  748. positionAttribute.getX( j ) + position.getX( j ),
  749. positionAttribute.getY( j ) + position.getY( j ),
  750. positionAttribute.getZ( j ) + position.getZ( j )
  751. );
  752. }
  753. } else if ( geometry.attributes.position ) {
  754. // Copying the original position not to affect the final position.
  755. // See the formula above.
  756. positionAttribute = geometry.attributes.position.clone();
  757. }
  758. if ( positionAttribute !== undefined ) {
  759. positionAttribute.name = attributeName;
  760. morphAttributes.position.push( positionAttribute );
  761. }
  762. if ( target.NORMAL !== undefined ) {
  763. material.morphNormals = true;
  764. // see target.POSITION's comment
  765. normalAttribute = accessors[ target.NORMAL ].clone();
  766. var normal = geometry.attributes.normal;
  767. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  768. normalAttribute.setXYZ(
  769. j,
  770. normalAttribute.getX( j ) + normal.getX( j ),
  771. normalAttribute.getY( j ) + normal.getY( j ),
  772. normalAttribute.getZ( j ) + normal.getZ( j )
  773. );
  774. }
  775. } else if ( geometry.attributes.normal !== undefined ) {
  776. normalAttribute = geometry.attributes.normal.clone();
  777. }
  778. if ( normalAttribute !== undefined ) {
  779. normalAttribute.name = attributeName;
  780. morphAttributes.normal.push( normalAttribute );
  781. }
  782. }
  783. mesh.updateMorphTargets();
  784. if ( meshDef.weights !== undefined ) {
  785. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  786. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  787. }
  788. }
  789. }
  790. function isPrimitiveEqual( a, b ) {
  791. if ( a.indices !== b.indices ) {
  792. return false;
  793. }
  794. var attribA = a.attributes || {};
  795. var attribB = b.attributes || {};
  796. var keysA = Object.keys( attribA );
  797. var keysB = Object.keys( attribB );
  798. if ( keysA.length !== keysB.length ) {
  799. return false;
  800. }
  801. for ( var i = 0, il = keysA.length; i < il; i ++ ) {
  802. var key = keysA[ i ];
  803. if ( attribA[ key ] !== attribB[ key ] ) {
  804. return false;
  805. }
  806. }
  807. return true;
  808. }
  809. function getCachedGeometry( cache, newPrimitive ) {
  810. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  811. var cached = cache[ i ];
  812. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) {
  813. return cached.geometry;
  814. }
  815. }
  816. return null;
  817. }
  818. /* GLTF PARSER */
  819. function GLTFParser( json, extensions, options ) {
  820. this.json = json || {};
  821. this.extensions = extensions || {};
  822. this.options = options || {};
  823. // loader object cache
  824. this.cache = new GLTFRegistry();
  825. // BufferGeometry caching
  826. this.primitiveCache = [];
  827. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  828. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  829. this.fileLoader = new THREE.FileLoader( this.options.manager );
  830. this.fileLoader.setResponseType( 'arraybuffer' );
  831. }
  832. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  833. var json = this.json;
  834. var parser = this;
  835. // Clear the loader cache
  836. this.cache.removeAll();
  837. // Mark the special nodes/meshes in json for efficient parse
  838. this.markDefs();
  839. // Fire the callback on complete
  840. this.getMultiDependencies( [
  841. 'scene',
  842. 'animation',
  843. 'camera'
  844. ] ).then( function ( dependencies ) {
  845. var scenes = dependencies.scenes || [];
  846. var scene = scenes[ json.scene || 0 ];
  847. var animations = dependencies.animations || [];
  848. var asset = json.asset;
  849. var cameras = dependencies.cameras || [];
  850. onLoad( scene, scenes, cameras, animations, asset );
  851. } ).catch( onError );
  852. };
  853. /**
  854. * Marks the special nodes/meshes in json for efficient parse.
  855. */
  856. GLTFParser.prototype.markDefs = function () {
  857. var nodeDefs = this.json.nodes || [];
  858. var skinDefs = this.json.skins || [];
  859. var meshDefs = this.json.meshes || [];
  860. var meshReferences = {};
  861. var meshUses = {};
  862. // Nothing in the node definition indicates whether it is a Bone or an
  863. // Object3D. Use the skins' joint references to mark bones.
  864. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  865. var joints = skinDefs[ skinIndex ].joints;
  866. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  867. nodeDefs[ joints[ i ] ].isBone = true;
  868. }
  869. }
  870. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  871. // avoid having more than one THREE.Mesh with the same name, count
  872. // references and rename instances below.
  873. //
  874. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  875. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  876. var nodeDef = nodeDefs[ nodeIndex ];
  877. if ( nodeDef.mesh !== undefined ) {
  878. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  879. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  880. }
  881. meshReferences[ nodeDef.mesh ] ++;
  882. // Nothing in the mesh definition indicates whether it is
  883. // a SkinnedMesh or Mesh. Use the node's mesh reference
  884. // to mark SkinnedMesh if node has skin.
  885. if ( nodeDef.skin !== undefined ) {
  886. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  887. }
  888. }
  889. }
  890. this.json.meshReferences = meshReferences;
  891. this.json.meshUses = meshUses;
  892. };
  893. /**
  894. * Requests the specified dependency asynchronously, with caching.
  895. * @param {string} type
  896. * @param {number} index
  897. * @return {Promise<Object>}
  898. */
  899. GLTFParser.prototype.getDependency = function ( type, index ) {
  900. var cacheKey = type + ':' + index;
  901. var dependency = this.cache.get( cacheKey );
  902. if ( ! dependency ) {
  903. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  904. dependency = this[ fnName ]( index );
  905. this.cache.add( cacheKey, dependency );
  906. }
  907. return dependency;
  908. };
  909. /**
  910. * Requests all dependencies of the specified type asynchronously, with caching.
  911. * @param {string} type
  912. * @return {Promise<Array<Object>>}
  913. */
  914. GLTFParser.prototype.getDependencies = function ( type ) {
  915. var dependencies = this.cache.get( type );
  916. if ( ! dependencies ) {
  917. var parser = this;
  918. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  919. dependencies = Promise.all( defs.map( function ( def, index ) {
  920. return parser.getDependency( type, index );
  921. } ) );
  922. this.cache.add( type, dependencies );
  923. }
  924. return dependencies;
  925. };
  926. /**
  927. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  928. * @param {Array<string>} types
  929. * @return {Promise<Object<Array<Object>>>}
  930. */
  931. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  932. var results = {};
  933. var pendings = [];
  934. for ( var i = 0, il = types.length; i < il; i ++ ) {
  935. var type = types[ i ];
  936. var value = this.getDependencies( type );
  937. value = value.then( function ( key, value ) {
  938. results[ key ] = value;
  939. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  940. pendings.push( value );
  941. }
  942. return Promise.all( pendings ).then( function () {
  943. return results;
  944. } );
  945. };
  946. /**
  947. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  948. * @param {number} bufferIndex
  949. * @return {Promise<ArrayBuffer>}
  950. */
  951. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  952. var bufferDef = this.json.buffers[ bufferIndex ];
  953. var loader = this.fileLoader;
  954. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  955. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  956. }
  957. // If present, GLB container is required to be the first buffer.
  958. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  959. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  960. }
  961. var options = this.options;
  962. return new Promise( function ( resolve, reject ) {
  963. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  964. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  965. } );
  966. } );
  967. };
  968. /**
  969. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  970. * @param {number} bufferViewIndex
  971. * @return {Promise<ArrayBuffer>}
  972. */
  973. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  974. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  975. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  976. var byteLength = bufferViewDef.byteLength || 0;
  977. var byteOffset = bufferViewDef.byteOffset || 0;
  978. return buffer.slice( byteOffset, byteOffset + byteLength );
  979. } );
  980. };
  981. /**
  982. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  983. * @param {number} accessorIndex
  984. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  985. */
  986. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  987. var json = this.json;
  988. var accessorDef = this.json.accessors[ accessorIndex ];
  989. var pendingBufferViews = [];
  990. if ( accessorDef.bufferView !== undefined ) {
  991. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  992. } else {
  993. pendingBufferViews.push( null );
  994. }
  995. if ( accessorDef.sparse !== undefined ) {
  996. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  997. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  998. }
  999. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1000. var bufferView = bufferViews[ 0 ];
  1001. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1002. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1003. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1004. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1005. var itemBytes = elementBytes * itemSize;
  1006. var byteOffset = accessorDef.byteOffset || 0;
  1007. var byteStride = json.bufferViews[ accessorDef.bufferView ].byteStride;
  1008. var normalized = accessorDef.normalized === true;
  1009. var array, bufferAttribute;
  1010. // The buffer is not interleaved if the stride is the item size in bytes.
  1011. if ( byteStride && byteStride !== itemBytes ) {
  1012. // Use the full buffer if it's interleaved.
  1013. array = new TypedArray( bufferView );
  1014. // Integer parameters to IB/IBA are in array elements, not bytes.
  1015. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1016. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  1017. } else {
  1018. if ( bufferView === null ) {
  1019. array = new TypedArray( accessorDef.count * itemSize );
  1020. } else {
  1021. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1022. }
  1023. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1024. }
  1025. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1026. if ( accessorDef.sparse !== undefined ) {
  1027. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1028. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1029. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1030. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1031. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1032. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1033. if ( bufferView !== null ) {
  1034. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1035. bufferAttribute.setArray( bufferAttribute.array.slice() );
  1036. }
  1037. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1038. var index = sparseIndices[ i ];
  1039. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1040. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1041. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1042. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1043. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1044. }
  1045. }
  1046. return bufferAttribute;
  1047. } );
  1048. };
  1049. /**
  1050. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1051. * @param {number} textureIndex
  1052. * @return {Promise<THREE.Texture>}
  1053. */
  1054. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1055. var parser = this;
  1056. var json = this.json;
  1057. var options = this.options;
  1058. var textureLoader = this.textureLoader;
  1059. var URL = window.URL || window.webkitURL;
  1060. var textureDef = json.textures[ textureIndex ];
  1061. var source = json.images[ textureDef.source ];
  1062. var sourceURI = source.uri;
  1063. var isObjectURL = false;
  1064. if ( source.bufferView !== undefined ) {
  1065. // Load binary image data from bufferView, if provided.
  1066. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1067. isObjectURL = true;
  1068. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1069. sourceURI = URL.createObjectURL( blob );
  1070. return sourceURI;
  1071. } );
  1072. }
  1073. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1074. // Load Texture resource.
  1075. var loader = THREE.Loader.Handlers.get( sourceURI ) || textureLoader;
  1076. return new Promise( function ( resolve, reject ) {
  1077. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1078. } );
  1079. } ).then( function ( texture ) {
  1080. // Clean up resources and configure Texture.
  1081. if ( isObjectURL === true ) {
  1082. URL.revokeObjectURL( sourceURI );
  1083. }
  1084. texture.flipY = false;
  1085. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1086. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  1087. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  1088. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  1089. 'internalFormat will be forced to be the same value as format.' );
  1090. }
  1091. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  1092. var samplers = json.samplers || {};
  1093. var sampler = samplers[ textureDef.sampler ] || {};
  1094. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1095. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1096. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1097. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1098. return texture;
  1099. } );
  1100. };
  1101. /**
  1102. * Asynchronously assigns a texture to the given material parameters.
  1103. * @param {Object} materialParams
  1104. * @param {string} textureName
  1105. * @param {number} textureIndex
  1106. * @return {Promise}
  1107. */
  1108. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  1109. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  1110. materialParams[ textureName ] = texture;
  1111. } );
  1112. };
  1113. /**
  1114. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1115. * @param {number} materialIndex
  1116. * @return {Promise<THREE.Material>}
  1117. */
  1118. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1119. var parser = this;
  1120. var json = this.json;
  1121. var extensions = this.extensions;
  1122. var materialDef = this.json.materials[ materialIndex ];
  1123. var materialType;
  1124. var materialParams = {};
  1125. var materialExtensions = materialDef.extensions || {};
  1126. var pending = [];
  1127. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  1128. var khcExtension = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  1129. materialType = khcExtension.getMaterialType( materialDef );
  1130. pending.push( khcExtension.extendParams( materialParams, materialDef, parser ) );
  1131. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1132. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1133. materialType = sgExtension.getMaterialType( materialDef );
  1134. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1135. } else if ( materialDef.pbrMetallicRoughness !== undefined ) {
  1136. // Specification:
  1137. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1138. materialType = THREE.MeshStandardMaterial;
  1139. var metallicRoughness = materialDef.pbrMetallicRoughness;
  1140. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1141. materialParams.opacity = 1.0;
  1142. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1143. var array = metallicRoughness.baseColorFactor;
  1144. materialParams.color.fromArray( array );
  1145. materialParams.opacity = array[ 3 ];
  1146. }
  1147. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1148. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  1149. }
  1150. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1151. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1152. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1153. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1154. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  1155. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  1156. }
  1157. } else {
  1158. materialType = THREE.MeshPhongMaterial;
  1159. }
  1160. if ( materialDef.doubleSided === true ) {
  1161. materialParams.side = THREE.DoubleSide;
  1162. }
  1163. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1164. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1165. materialParams.transparent = true;
  1166. } else {
  1167. materialParams.transparent = false;
  1168. if ( alphaMode === ALPHA_MODES.MASK ) {
  1169. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1170. }
  1171. }
  1172. if ( materialDef.normalTexture !== undefined ) {
  1173. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture.index ) );
  1174. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1175. if ( materialDef.normalTexture.scale !== undefined ) {
  1176. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1177. }
  1178. }
  1179. if ( materialDef.occlusionTexture !== undefined ) {
  1180. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture.index ) );
  1181. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1182. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1183. }
  1184. }
  1185. if ( materialDef.emissiveFactor !== undefined ) {
  1186. if ( materialType === THREE.MeshBasicMaterial ) {
  1187. materialParams.color = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1188. } else {
  1189. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1190. }
  1191. }
  1192. if ( materialDef.emissiveTexture !== undefined ) {
  1193. if ( materialType === THREE.MeshBasicMaterial ) {
  1194. pending.push( parser.assignTexture( materialParams, 'map', materialDef.emissiveTexture.index ) );
  1195. } else {
  1196. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture.index ) );
  1197. }
  1198. }
  1199. return Promise.all( pending ).then( function () {
  1200. var material;
  1201. if ( materialType === THREE.ShaderMaterial ) {
  1202. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1203. } else {
  1204. material = new materialType( materialParams );
  1205. }
  1206. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  1207. // Normal map textures use OpenGL conventions:
  1208. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1209. if ( material.normalScale ) {
  1210. material.normalScale.x = - material.normalScale.x;
  1211. }
  1212. // emissiveTexture and baseColorTexture use sRGB encoding.
  1213. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1214. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1215. if ( materialDef.extras ) material.userData = materialDef.extras;
  1216. return material;
  1217. } );
  1218. };
  1219. /**
  1220. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1221. * @param {Array<Object>} primitives
  1222. * @return {Promise<Array<THREE.BufferGeometry>>}
  1223. */
  1224. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1225. var cache = this.primitiveCache;
  1226. return this.getDependencies( 'accessor' ).then( function ( accessors ) {
  1227. var geometries = [];
  1228. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1229. var primitive = primitives[ i ];
  1230. // See if we've already created this geometry
  1231. var cached = getCachedGeometry( cache, primitive );
  1232. if ( cached ) {
  1233. // Use the cached geometry if it exists
  1234. geometries.push( cached );
  1235. } else {
  1236. // Otherwise create a new geometry
  1237. var geometry = new THREE.BufferGeometry();
  1238. var attributes = primitive.attributes;
  1239. for ( var attributeId in attributes ) {
  1240. var attributeEntry = attributes[ attributeId ];
  1241. var bufferAttribute = accessors[ attributeEntry ];
  1242. switch ( attributeId ) {
  1243. case 'POSITION':
  1244. geometry.addAttribute( 'position', bufferAttribute );
  1245. break;
  1246. case 'NORMAL':
  1247. geometry.addAttribute( 'normal', bufferAttribute );
  1248. break;
  1249. case 'TEXCOORD_0':
  1250. case 'TEXCOORD0':
  1251. case 'TEXCOORD':
  1252. geometry.addAttribute( 'uv', bufferAttribute );
  1253. break;
  1254. case 'TEXCOORD_1':
  1255. geometry.addAttribute( 'uv2', bufferAttribute );
  1256. break;
  1257. case 'COLOR_0':
  1258. case 'COLOR0':
  1259. case 'COLOR':
  1260. geometry.addAttribute( 'color', bufferAttribute );
  1261. break;
  1262. case 'WEIGHTS_0':
  1263. case 'WEIGHT': // WEIGHT semantic deprecated.
  1264. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1265. break;
  1266. case 'JOINTS_0':
  1267. case 'JOINT': // JOINT semantic deprecated.
  1268. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1269. break;
  1270. }
  1271. }
  1272. if ( primitive.indices !== undefined ) {
  1273. geometry.setIndex( accessors[ primitive.indices ] );
  1274. }
  1275. // Cache this geometry
  1276. cache.push( {
  1277. primitive: primitive,
  1278. geometry: geometry
  1279. } );
  1280. geometries.push( geometry );
  1281. }
  1282. }
  1283. return geometries;
  1284. } );
  1285. };
  1286. /**
  1287. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1288. * @param {number} meshIndex
  1289. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1290. */
  1291. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1292. var scope = this;
  1293. var json = this.json;
  1294. var extensions = this.extensions;
  1295. var meshDef = this.json.meshes[ meshIndex ];
  1296. return this.getMultiDependencies( [
  1297. 'accessor',
  1298. 'material'
  1299. ] ).then( function ( dependencies ) {
  1300. var group = new THREE.Group();
  1301. var primitives = meshDef.primitives;
  1302. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  1303. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1304. var primitive = primitives[ i ];
  1305. var geometry = geometries[ i ];
  1306. var material = primitive.material === undefined
  1307. ? createDefaultMaterial()
  1308. : dependencies.materials[ primitive.material ];
  1309. if ( material.aoMap
  1310. && geometry.attributes.uv2 === undefined
  1311. && geometry.attributes.uv !== undefined ) {
  1312. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1313. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1314. }
  1315. // If the material will be modified later on, clone it now.
  1316. var useVertexColors = geometry.attributes.color !== undefined;
  1317. var useFlatShading = geometry.attributes.normal === undefined;
  1318. var useSkinning = meshDef.isSkinnedMesh === true;
  1319. var useMorphTargets = primitive.targets !== undefined;
  1320. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1321. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1322. var specGlossExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1323. material = specGlossExtension.cloneMaterial( material );
  1324. } else {
  1325. material = material.clone();
  1326. }
  1327. }
  1328. if ( useVertexColors ) {
  1329. material.vertexColors = THREE.VertexColors;
  1330. material.needsUpdate = true;
  1331. }
  1332. if ( useFlatShading ) {
  1333. material.flatShading = true;
  1334. }
  1335. var mesh;
  1336. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1337. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1338. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1339. primitive.mode === undefined ) {
  1340. if ( useSkinning ) {
  1341. mesh = new THREE.SkinnedMesh( geometry, material );
  1342. material.skinning = true;
  1343. } else {
  1344. mesh = new THREE.Mesh( geometry, material );
  1345. }
  1346. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1347. mesh.drawMode = THREE.TriangleStripDrawMode;
  1348. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1349. mesh.drawMode = THREE.TriangleFanDrawMode;
  1350. }
  1351. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1352. mesh = new THREE.LineSegments( geometry, material );
  1353. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1354. mesh = new THREE.Line( geometry, material );
  1355. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1356. mesh = new THREE.LineLoop( geometry, material );
  1357. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1358. mesh = new THREE.Points( geometry, material );
  1359. } else {
  1360. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1361. }
  1362. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1363. if ( useMorphTargets ) {
  1364. addMorphTargets( mesh, meshDef, primitive, dependencies.accessors );
  1365. }
  1366. if ( meshDef.extras !== undefined ) mesh.userData = meshDef.extras;
  1367. if ( primitive.extras !== undefined ) mesh.geometry.userData = primitive.extras;
  1368. // for Specular-Glossiness.
  1369. if ( material.isGLTFSpecularGlossinessMaterial === true ) {
  1370. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1371. }
  1372. if ( primitives.length > 1 ) {
  1373. mesh.name += '_' + i;
  1374. group.add( mesh );
  1375. } else {
  1376. return mesh;
  1377. }
  1378. }
  1379. return group;
  1380. } );
  1381. } );
  1382. };
  1383. /**
  1384. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1385. * @param {number} cameraIndex
  1386. * @return {Promise<THREE.Camera>}
  1387. */
  1388. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1389. var camera;
  1390. var cameraDef = this.json.cameras[ cameraIndex ];
  1391. var params = cameraDef[ cameraDef.type ];
  1392. if ( ! params ) {
  1393. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1394. return;
  1395. }
  1396. if ( cameraDef.type === 'perspective' ) {
  1397. var aspectRatio = params.aspectRatio || 1;
  1398. var xfov = params.yfov * aspectRatio;
  1399. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  1400. } else if ( cameraDef.type === 'orthographic' ) {
  1401. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1402. }
  1403. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1404. if ( cameraDef.extras ) camera.userData = cameraDef.extras;
  1405. return Promise.resolve( camera );
  1406. };
  1407. /**
  1408. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1409. * @param {number} skinIndex
  1410. * @return {Promise<Object>}
  1411. */
  1412. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1413. var skinDef = this.json.skins[ skinIndex ];
  1414. var skinEntry = { joints: skinDef.joints };
  1415. if ( skinDef.inverseBindMatrices === undefined ) {
  1416. return Promise.resolve( skinEntry );
  1417. }
  1418. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1419. skinEntry.inverseBindMatrices = accessor;
  1420. return skinEntry;
  1421. } );
  1422. };
  1423. /**
  1424. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1425. * @param {number} animationIndex
  1426. * @return {Promise<THREE.AnimationClip>}
  1427. */
  1428. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1429. var json = this.json;
  1430. var animationDef = this.json.animations[ animationIndex ];
  1431. return this.getMultiDependencies( [
  1432. 'accessor',
  1433. 'node'
  1434. ] ).then( function ( dependencies ) {
  1435. var tracks = [];
  1436. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1437. var channel = animationDef.channels[ i ];
  1438. var sampler = animationDef.samplers[ channel.sampler ];
  1439. if ( sampler ) {
  1440. var target = channel.target;
  1441. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1442. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1443. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1444. var inputAccessor = dependencies.accessors[ input ];
  1445. var outputAccessor = dependencies.accessors[ output ];
  1446. var node = dependencies.nodes[ name ];
  1447. if ( node ) {
  1448. node.updateMatrix();
  1449. node.matrixAutoUpdate = true;
  1450. var TypedKeyframeTrack;
  1451. switch ( PATH_PROPERTIES[ target.path ] ) {
  1452. case PATH_PROPERTIES.weights:
  1453. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1454. break;
  1455. case PATH_PROPERTIES.rotation:
  1456. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1457. break;
  1458. case PATH_PROPERTIES.position:
  1459. case PATH_PROPERTIES.scale:
  1460. default:
  1461. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1462. break;
  1463. }
  1464. var targetName = node.name ? node.name : node.uuid;
  1465. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1466. var itemSize = outputAccessor.itemSize;
  1467. var TypedArray = outputAccessor.array.constructor;
  1468. var outputAccessorValues = new TypedArray( outputAccessor.count * itemSize / 3 );
  1469. // Layout of keyframe output values for CUBICSPLINE animations:
  1470. //
  1471. // [ inTangent1, splineVertex1, outTangent1, inTangent2, splineVertex2, ... ]
  1472. //
  1473. // THREE.KeyframeTrack infers tangents from the spline vertices when interpolating:
  1474. // those values are extracted below. This still guarantees smooth curves, but does
  1475. // throw away more precise information in the tangents. In the future, consider
  1476. // re-sampling at a higher framerate using the tangents provided.
  1477. //
  1478. // See: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  1479. for ( var j = 0, jl = outputAccessor.count; j < jl; j += 3 ) {
  1480. outputAccessorValues[ j * itemSize / 3 ] = outputAccessor.getX( j + 1 );
  1481. if ( itemSize > 1 ) outputAccessorValues[ j * itemSize / 3 + 1 ] = outputAccessor.getY( j + 1 );
  1482. if ( itemSize > 2 ) outputAccessorValues[ j * itemSize / 3 + 2 ] = outputAccessor.getZ( j + 1 );
  1483. if ( itemSize > 3 ) outputAccessorValues[ j * itemSize / 3 + 3 ] = outputAccessor.getW( j + 1 );
  1484. }
  1485. outputAccessor = new THREE.BufferAttribute( outputAccessorValues, itemSize / 3, outputAccessor.normalized );
  1486. }
  1487. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1488. var targetNames = [];
  1489. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1490. // node should be THREE.Group here but
  1491. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1492. // the property of a mesh object under node.
  1493. // So finding targets here.
  1494. node.traverse( function ( object ) {
  1495. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1496. targetNames.push( object.name ? object.name : object.uuid );
  1497. }
  1498. } );
  1499. } else {
  1500. targetNames.push( targetName );
  1501. }
  1502. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1503. // buffers before creating a truncated copy to keep. Because buffers may
  1504. // be reused by other tracks, make copies here.
  1505. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1506. tracks.push( new TypedKeyframeTrack(
  1507. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1508. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1509. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1510. interpolation
  1511. ) );
  1512. }
  1513. }
  1514. }
  1515. }
  1516. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  1517. return new THREE.AnimationClip( name, undefined, tracks );
  1518. } );
  1519. };
  1520. /**
  1521. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1522. * @param {number} nodeIndex
  1523. * @return {Promise<THREE.Object3D>}
  1524. */
  1525. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1526. var json = this.json;
  1527. var extensions = this.extensions;
  1528. var meshReferences = this.json.meshReferences;
  1529. var meshUses = this.json.meshUses;
  1530. var nodeDef = this.json.nodes[ nodeIndex ];
  1531. return this.getMultiDependencies( [
  1532. 'mesh',
  1533. 'skin',
  1534. 'camera'
  1535. ] ).then( function ( dependencies ) {
  1536. var node;
  1537. if ( nodeDef.isBone === true ) {
  1538. node = new THREE.Bone();
  1539. } else if ( nodeDef.mesh !== undefined ) {
  1540. var mesh = dependencies.meshes[ nodeDef.mesh ];
  1541. node = mesh.clone();
  1542. // for Specular-Glossiness
  1543. if ( mesh.isGroup === true ) {
  1544. for ( var i = 0, il = mesh.children.length; i < il; i ++ ) {
  1545. var child = mesh.children[ i ];
  1546. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial === true ) {
  1547. node.children[ i ].onBeforeRender = child.onBeforeRender;
  1548. }
  1549. }
  1550. } else {
  1551. if ( mesh.material && mesh.material.isGLTFSpecularGlossinessMaterial === true ) {
  1552. node.onBeforeRender = mesh.onBeforeRender;
  1553. }
  1554. }
  1555. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1556. node.name += '_instance_' + meshUses[ nodeDef.mesh ] ++;
  1557. }
  1558. } else if ( nodeDef.camera !== undefined ) {
  1559. node = dependencies.cameras[ nodeDef.camera ];
  1560. } else if ( nodeDef.extensions
  1561. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1562. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1563. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1564. node = lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
  1565. } else {
  1566. node = new THREE.Object3D();
  1567. }
  1568. if ( nodeDef.name !== undefined ) {
  1569. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1570. }
  1571. if ( nodeDef.extras ) node.userData = nodeDef.extras;
  1572. if ( nodeDef.matrix !== undefined ) {
  1573. var matrix = new THREE.Matrix4();
  1574. matrix.fromArray( nodeDef.matrix );
  1575. node.applyMatrix( matrix );
  1576. } else {
  1577. if ( nodeDef.translation !== undefined ) {
  1578. node.position.fromArray( nodeDef.translation );
  1579. }
  1580. if ( nodeDef.rotation !== undefined ) {
  1581. node.quaternion.fromArray( nodeDef.rotation );
  1582. }
  1583. if ( nodeDef.scale !== undefined ) {
  1584. node.scale.fromArray( nodeDef.scale );
  1585. }
  1586. }
  1587. return node;
  1588. } );
  1589. };
  1590. /**
  1591. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  1592. * @param {number} sceneIndex
  1593. * @return {Promise<THREE.Scene>}
  1594. */
  1595. GLTFParser.prototype.loadScene = function () {
  1596. // scene node hierachy builder
  1597. function buildNodeHierachy( nodeId, parentObject, json, allNodes, skins ) {
  1598. var node = allNodes[ nodeId ];
  1599. var nodeDef = json.nodes[ nodeId ];
  1600. // build skeleton here as well
  1601. if ( nodeDef.skin !== undefined ) {
  1602. var meshes = node.isGroup === true ? node.children : [ node ];
  1603. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1604. var mesh = meshes[ i ];
  1605. var skinEntry = skins[ nodeDef.skin ];
  1606. var bones = [];
  1607. var boneInverses = [];
  1608. for ( var j = 0, jl = skinEntry.joints.length; j < jl; j ++ ) {
  1609. var jointId = skinEntry.joints[ j ];
  1610. var jointNode = allNodes[ jointId ];
  1611. if ( jointNode ) {
  1612. bones.push( jointNode );
  1613. var mat = new THREE.Matrix4();
  1614. if ( skinEntry.inverseBindMatrices !== undefined ) {
  1615. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  1616. }
  1617. boneInverses.push( mat );
  1618. } else {
  1619. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  1620. }
  1621. }
  1622. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  1623. }
  1624. }
  1625. // build node hierachy
  1626. parentObject.add( node );
  1627. if ( nodeDef.children ) {
  1628. var children = nodeDef.children;
  1629. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1630. var child = children[ i ];
  1631. buildNodeHierachy( child, node, json, allNodes, skins );
  1632. }
  1633. }
  1634. }
  1635. return function loadScene( sceneIndex ) {
  1636. var json = this.json;
  1637. var extensions = this.extensions;
  1638. var sceneDef = this.json.scenes[ sceneIndex ];
  1639. return this.getMultiDependencies( [
  1640. 'node',
  1641. 'skin'
  1642. ] ).then( function ( dependencies ) {
  1643. var scene = new THREE.Scene();
  1644. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  1645. if ( sceneDef.extras ) scene.userData = sceneDef.extras;
  1646. var nodeIds = sceneDef.nodes || [];
  1647. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  1648. buildNodeHierachy( nodeIds[ i ], scene, json, dependencies.nodes, dependencies.skins );
  1649. }
  1650. // Ambient lighting, if present, is always attached to the scene root.
  1651. if ( sceneDef.extensions
  1652. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1653. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1654. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1655. scene.add( lights[ sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1656. }
  1657. return scene;
  1658. } );
  1659. };
  1660. }();
  1661. return GLTFLoader;
  1662. } )();