GLTFLoader.js 71 KB

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