GLTFLoader.js 71 KB

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