GLTFLoader.js 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584
  1. console.warn( "THREE.GLTFLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  2. THREE.GLTFLoader = ( function () {
  3. function GLTFLoader( manager ) {
  4. THREE.Loader.call( this, manager );
  5. this.dracoLoader = null;
  6. this.ddsLoader = null;
  7. this.ktx2Loader = null;
  8. this.pluginCallbacks = [];
  9. this.register( function ( parser ) {
  10. return new GLTFMaterialsClearcoatExtension( parser );
  11. } );
  12. this.register( function ( parser ) {
  13. return new GLTFTextureBasisUExtension( parser );
  14. } );
  15. this.register( function ( parser ) {
  16. return new GLTFMaterialsTransmissionExtension( parser );
  17. } );
  18. }
  19. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  20. constructor: GLTFLoader,
  21. load: function ( url, onLoad, onProgress, onError ) {
  22. var scope = this;
  23. var resourcePath;
  24. if ( this.resourcePath !== '' ) {
  25. resourcePath = this.resourcePath;
  26. } else if ( this.path !== '' ) {
  27. resourcePath = this.path;
  28. } else {
  29. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  30. }
  31. // Tells the LoadingManager to track an extra item, which resolves after
  32. // the model is fully loaded. This means the count of items loaded will
  33. // be incorrect, but ensures manager.onLoad() does not fire early.
  34. scope.manager.itemStart( url );
  35. var _onError = function ( e ) {
  36. if ( onError ) {
  37. onError( e );
  38. } else {
  39. console.error( e );
  40. }
  41. scope.manager.itemError( url );
  42. scope.manager.itemEnd( url );
  43. };
  44. var loader = new THREE.FileLoader( scope.manager );
  45. loader.setPath( this.path );
  46. loader.setResponseType( 'arraybuffer' );
  47. loader.setRequestHeader( this.requestHeader );
  48. if ( scope.crossOrigin === 'use-credentials' ) {
  49. loader.setWithCredentials( true );
  50. }
  51. loader.load( url, function ( data ) {
  52. try {
  53. scope.parse( data, resourcePath, function ( gltf ) {
  54. onLoad( gltf );
  55. scope.manager.itemEnd( url );
  56. }, _onError );
  57. } catch ( e ) {
  58. _onError( e );
  59. }
  60. }, onProgress, _onError );
  61. },
  62. setDRACOLoader: function ( dracoLoader ) {
  63. this.dracoLoader = dracoLoader;
  64. return this;
  65. },
  66. setDDSLoader: function ( ddsLoader ) {
  67. this.ddsLoader = ddsLoader;
  68. return this;
  69. },
  70. setKTX2Loader: function ( ktx2Loader ) {
  71. this.ktx2Loader = ktx2Loader;
  72. return this;
  73. },
  74. register: function ( callback ) {
  75. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  76. this.pluginCallbacks.push( callback );
  77. }
  78. return this;
  79. },
  80. unregister: function ( callback ) {
  81. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  82. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  83. }
  84. return this;
  85. },
  86. parse: function ( data, path, onLoad, onError ) {
  87. var content;
  88. var extensions = {};
  89. var plugins = {};
  90. if ( typeof data === 'string' ) {
  91. content = data;
  92. } else {
  93. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  94. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  95. try {
  96. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  97. } catch ( error ) {
  98. if ( onError ) onError( error );
  99. return;
  100. }
  101. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  102. } else {
  103. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  104. }
  105. }
  106. var json = JSON.parse( content );
  107. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  108. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  109. return;
  110. }
  111. var parser = new GLTFParser( json, {
  112. path: path || this.resourcePath || '',
  113. crossOrigin: this.crossOrigin,
  114. manager: this.manager,
  115. ktx2Loader: this.ktx2Loader
  116. } );
  117. parser.fileLoader.setRequestHeader( this.requestHeader );
  118. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  119. var plugin = this.pluginCallbacks[ i ]( parser );
  120. plugins[ plugin.name ] = plugin;
  121. // Workaround to avoid determining as unknown extension
  122. // in addUnknownExtensionsToUserData().
  123. // Remove this workaround if we move all the existing
  124. // extension handlers to plugin system
  125. extensions[ plugin.name ] = true;
  126. }
  127. if ( json.extensionsUsed ) {
  128. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  129. var extensionName = json.extensionsUsed[ i ];
  130. var extensionsRequired = json.extensionsRequired || [];
  131. switch ( extensionName ) {
  132. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  133. extensions[ extensionName ] = new GLTFLightsExtension( json );
  134. break;
  135. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  136. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  137. break;
  138. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  139. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  140. break;
  141. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  142. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  143. break;
  144. case EXTENSIONS.MSFT_TEXTURE_DDS:
  145. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  146. break;
  147. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  148. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  149. break;
  150. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  151. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  152. break;
  153. default:
  154. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  155. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  156. }
  157. }
  158. }
  159. }
  160. parser.setExtensions( extensions );
  161. parser.setPlugins( plugins );
  162. parser.parse( onLoad, onError );
  163. }
  164. } );
  165. /* GLTFREGISTRY */
  166. function GLTFRegistry() {
  167. var objects = {};
  168. return {
  169. get: function ( key ) {
  170. return objects[ key ];
  171. },
  172. add: function ( key, object ) {
  173. objects[ key ] = object;
  174. },
  175. remove: function ( key ) {
  176. delete objects[ key ];
  177. },
  178. removeAll: function () {
  179. objects = {};
  180. }
  181. };
  182. }
  183. /*********************************/
  184. /********** EXTENSIONS ***********/
  185. /*********************************/
  186. var EXTENSIONS = {
  187. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  188. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  189. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  190. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  191. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  192. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  193. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  194. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  195. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  196. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  197. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  198. };
  199. /**
  200. * DDS Texture Extension
  201. *
  202. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  203. *
  204. */
  205. function GLTFTextureDDSExtension( ddsLoader ) {
  206. if ( ! ddsLoader ) {
  207. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  208. }
  209. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  210. this.ddsLoader = ddsLoader;
  211. }
  212. /**
  213. * Punctual Lights Extension
  214. *
  215. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  216. */
  217. function GLTFLightsExtension( json ) {
  218. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  219. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  220. this.lightDefs = extension.lights || [];
  221. }
  222. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  223. var lightDef = this.lightDefs[ lightIndex ];
  224. var lightNode;
  225. var color = new THREE.Color( 0xffffff );
  226. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  227. var range = lightDef.range !== undefined ? lightDef.range : 0;
  228. switch ( lightDef.type ) {
  229. case 'directional':
  230. lightNode = new THREE.DirectionalLight( color );
  231. lightNode.target.position.set( 0, 0, - 1 );
  232. lightNode.add( lightNode.target );
  233. break;
  234. case 'point':
  235. lightNode = new THREE.PointLight( color );
  236. lightNode.distance = range;
  237. break;
  238. case 'spot':
  239. lightNode = new THREE.SpotLight( color );
  240. lightNode.distance = range;
  241. // Handle spotlight properties.
  242. lightDef.spot = lightDef.spot || {};
  243. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  244. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  245. lightNode.angle = lightDef.spot.outerConeAngle;
  246. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  247. lightNode.target.position.set( 0, 0, - 1 );
  248. lightNode.add( lightNode.target );
  249. break;
  250. default:
  251. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  252. }
  253. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  254. // here, because node-level parsing will only override position if explicitly specified.
  255. lightNode.position.set( 0, 0, 0 );
  256. lightNode.decay = 2;
  257. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  258. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  259. return Promise.resolve( lightNode );
  260. };
  261. /**
  262. * Unlit Materials Extension
  263. *
  264. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  265. */
  266. function GLTFMaterialsUnlitExtension() {
  267. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  268. }
  269. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  270. return THREE.MeshBasicMaterial;
  271. };
  272. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  273. var pending = [];
  274. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  275. materialParams.opacity = 1.0;
  276. var metallicRoughness = materialDef.pbrMetallicRoughness;
  277. if ( metallicRoughness ) {
  278. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  279. var array = metallicRoughness.baseColorFactor;
  280. materialParams.color.fromArray( array );
  281. materialParams.opacity = array[ 3 ];
  282. }
  283. if ( metallicRoughness.baseColorTexture !== undefined ) {
  284. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  285. }
  286. }
  287. return Promise.all( pending );
  288. };
  289. /**
  290. * Clearcoat Materials Extension
  291. *
  292. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  293. */
  294. function GLTFMaterialsClearcoatExtension( parser ) {
  295. this.parser = parser;
  296. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  297. }
  298. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( /* materialIndex */ ) {
  299. return THREE.MeshPhysicalMaterial;
  300. };
  301. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  302. var parser = this.parser;
  303. var materialDef = parser.json.materials[ materialIndex ];
  304. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  305. return Promise.resolve();
  306. }
  307. var pending = [];
  308. var extension = materialDef.extensions[ this.name ];
  309. if ( extension.clearcoatFactor !== undefined ) {
  310. materialParams.clearcoat = extension.clearcoatFactor;
  311. }
  312. if ( extension.clearcoatTexture !== undefined ) {
  313. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  314. }
  315. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  316. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  317. }
  318. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  319. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  320. }
  321. if ( extension.clearcoatNormalTexture !== undefined ) {
  322. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  323. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  324. var scale = extension.clearcoatNormalTexture.scale;
  325. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
  326. }
  327. }
  328. return Promise.all( pending );
  329. };
  330. /**
  331. * Transmission Materials Extension
  332. *
  333. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  334. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  335. */
  336. function GLTFMaterialsTransmissionExtension( parser ) {
  337. this.parser = parser;
  338. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  339. }
  340. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( /* materialIndex */ ) {
  341. return THREE.MeshPhysicalMaterial;
  342. };
  343. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  344. var parser = this.parser;
  345. var materialDef = parser.json.materials[ materialIndex ];
  346. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  347. return Promise.resolve();
  348. }
  349. var pending = [];
  350. var extension = materialDef.extensions[ this.name ];
  351. if ( extension.transmissionFactor !== undefined ) {
  352. materialParams.transmission = extension.transmissionFactor;
  353. }
  354. if ( extension.transmissionTexture !== undefined ) {
  355. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  356. }
  357. return Promise.all( pending );
  358. };
  359. /**
  360. * BasisU Texture Extension
  361. *
  362. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  363. * (draft PR https://github.com/KhronosGroup/glTF/pull/1751)
  364. */
  365. function GLTFTextureBasisUExtension( parser ) {
  366. this.parser = parser;
  367. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  368. }
  369. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  370. var parser = this.parser;
  371. var json = parser.json;
  372. var textureDef = json.textures[ textureIndex ];
  373. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  374. return null;
  375. }
  376. var extension = textureDef.extensions[ this.name ];
  377. var source = json.images[ extension.source ];
  378. var loader = parser.options.ktx2Loader;
  379. if ( ! loader ) {
  380. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  381. }
  382. return parser.loadTextureImage( textureIndex, source, loader );
  383. };
  384. /* BINARY EXTENSION */
  385. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  386. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  387. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  388. function GLTFBinaryExtension( data ) {
  389. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  390. this.content = null;
  391. this.body = null;
  392. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  393. this.header = {
  394. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  395. version: headerView.getUint32( 4, true ),
  396. length: headerView.getUint32( 8, true )
  397. };
  398. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  399. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  400. } else if ( this.header.version < 2.0 ) {
  401. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  402. }
  403. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  404. var chunkIndex = 0;
  405. while ( chunkIndex < chunkView.byteLength ) {
  406. var chunkLength = chunkView.getUint32( chunkIndex, true );
  407. chunkIndex += 4;
  408. var chunkType = chunkView.getUint32( chunkIndex, true );
  409. chunkIndex += 4;
  410. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  411. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  412. this.content = THREE.LoaderUtils.decodeText( contentArray );
  413. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  414. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  415. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  416. }
  417. // Clients must ignore chunks with unknown types.
  418. chunkIndex += chunkLength;
  419. }
  420. if ( this.content === null ) {
  421. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  422. }
  423. }
  424. /**
  425. * DRACO Mesh Compression Extension
  426. *
  427. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  428. */
  429. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  430. if ( ! dracoLoader ) {
  431. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  432. }
  433. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  434. this.json = json;
  435. this.dracoLoader = dracoLoader;
  436. this.dracoLoader.preload();
  437. }
  438. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  439. var json = this.json;
  440. var dracoLoader = this.dracoLoader;
  441. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  442. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  443. var threeAttributeMap = {};
  444. var attributeNormalizedMap = {};
  445. var attributeTypeMap = {};
  446. for ( var attributeName in gltfAttributeMap ) {
  447. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  448. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  449. }
  450. for ( attributeName in primitive.attributes ) {
  451. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  452. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  453. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  454. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  455. attributeTypeMap[ threeAttributeName ] = componentType;
  456. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  457. }
  458. }
  459. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  460. return new Promise( function ( resolve ) {
  461. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  462. for ( var attributeName in geometry.attributes ) {
  463. var attribute = geometry.attributes[ attributeName ];
  464. var normalized = attributeNormalizedMap[ attributeName ];
  465. if ( normalized !== undefined ) attribute.normalized = normalized;
  466. }
  467. resolve( geometry );
  468. }, threeAttributeMap, attributeTypeMap );
  469. } );
  470. } );
  471. };
  472. /**
  473. * Texture Transform Extension
  474. *
  475. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  476. */
  477. function GLTFTextureTransformExtension() {
  478. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  479. }
  480. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  481. texture = texture.clone();
  482. if ( transform.offset !== undefined ) {
  483. texture.offset.fromArray( transform.offset );
  484. }
  485. if ( transform.rotation !== undefined ) {
  486. texture.rotation = transform.rotation;
  487. }
  488. if ( transform.scale !== undefined ) {
  489. texture.repeat.fromArray( transform.scale );
  490. }
  491. if ( transform.texCoord !== undefined ) {
  492. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  493. }
  494. texture.needsUpdate = true;
  495. return texture;
  496. };
  497. /**
  498. * Specular-Glossiness Extension
  499. *
  500. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  501. */
  502. /**
  503. * A sub class of THREE.StandardMaterial with some of the functionality
  504. * changed via the `onBeforeCompile` callback
  505. * @pailhead
  506. */
  507. function GLTFMeshStandardSGMaterial( params ) {
  508. THREE.MeshStandardMaterial.call( this );
  509. this.isGLTFSpecularGlossinessMaterial = true;
  510. //various chunks that need replacing
  511. var specularMapParsFragmentChunk = [
  512. '#ifdef USE_SPECULARMAP',
  513. ' uniform sampler2D specularMap;',
  514. '#endif'
  515. ].join( '\n' );
  516. var glossinessMapParsFragmentChunk = [
  517. '#ifdef USE_GLOSSINESSMAP',
  518. ' uniform sampler2D glossinessMap;',
  519. '#endif'
  520. ].join( '\n' );
  521. var specularMapFragmentChunk = [
  522. 'vec3 specularFactor = specular;',
  523. '#ifdef USE_SPECULARMAP',
  524. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  525. ' texelSpecular = sRGBToLinear( texelSpecular );',
  526. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  527. ' specularFactor *= texelSpecular.rgb;',
  528. '#endif'
  529. ].join( '\n' );
  530. var glossinessMapFragmentChunk = [
  531. 'float glossinessFactor = glossiness;',
  532. '#ifdef USE_GLOSSINESSMAP',
  533. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  534. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  535. ' glossinessFactor *= texelGlossiness.a;',
  536. '#endif'
  537. ].join( '\n' );
  538. var lightPhysicalFragmentChunk = [
  539. 'PhysicalMaterial material;',
  540. 'material.diffuseColor = diffuseColor.rgb;',
  541. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  542. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  543. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.',
  544. 'material.specularRoughness += geometryRoughness;',
  545. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  546. 'material.specularColor = specularFactor.rgb;',
  547. ].join( '\n' );
  548. var uniforms = {
  549. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  550. glossiness: { value: 1 },
  551. specularMap: { value: null },
  552. glossinessMap: { value: null }
  553. };
  554. this._extraUniforms = uniforms;
  555. // please see #14031 or #13198 for an alternate approach
  556. this.onBeforeCompile = function ( shader ) {
  557. for ( var uniformName in uniforms ) {
  558. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  559. }
  560. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float roughness;', 'uniform vec3 specular;' );
  561. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float metalness;', 'uniform float glossiness;' );
  562. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk );
  563. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk );
  564. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk );
  565. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk );
  566. shader.fragmentShader = shader.fragmentShader.replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  567. };
  568. /*eslint-disable*/
  569. Object.defineProperties(
  570. this,
  571. {
  572. specular: {
  573. get: function () { return uniforms.specular.value; },
  574. set: function ( v ) { uniforms.specular.value = v; }
  575. },
  576. specularMap: {
  577. get: function () { return uniforms.specularMap.value; },
  578. set: function ( v ) { uniforms.specularMap.value = v; }
  579. },
  580. glossiness: {
  581. get: function () { return uniforms.glossiness.value; },
  582. set: function ( v ) { uniforms.glossiness.value = v; }
  583. },
  584. glossinessMap: {
  585. get: function () { return uniforms.glossinessMap.value; },
  586. set: function ( v ) {
  587. uniforms.glossinessMap.value = v;
  588. //how about something like this - @pailhead
  589. if ( v ) {
  590. this.defines.USE_GLOSSINESSMAP = '';
  591. // set USE_ROUGHNESSMAP to enable vUv
  592. this.defines.USE_ROUGHNESSMAP = '';
  593. } else {
  594. delete this.defines.USE_ROUGHNESSMAP;
  595. delete this.defines.USE_GLOSSINESSMAP;
  596. }
  597. }
  598. }
  599. }
  600. );
  601. /*eslint-enable*/
  602. delete this.metalness;
  603. delete this.roughness;
  604. delete this.metalnessMap;
  605. delete this.roughnessMap;
  606. this.setValues( params );
  607. }
  608. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  609. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  610. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  611. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  612. this.specularMap = source.specularMap;
  613. this.specular.copy( source.specular );
  614. this.glossinessMap = source.glossinessMap;
  615. this.glossiness = source.glossiness;
  616. delete this.metalness;
  617. delete this.roughness;
  618. delete this.metalnessMap;
  619. delete this.roughnessMap;
  620. return this;
  621. };
  622. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  623. return {
  624. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  625. specularGlossinessParams: [
  626. 'color',
  627. 'map',
  628. 'lightMap',
  629. 'lightMapIntensity',
  630. 'aoMap',
  631. 'aoMapIntensity',
  632. 'emissive',
  633. 'emissiveIntensity',
  634. 'emissiveMap',
  635. 'bumpMap',
  636. 'bumpScale',
  637. 'normalMap',
  638. 'normalMapType',
  639. 'displacementMap',
  640. 'displacementScale',
  641. 'displacementBias',
  642. 'specularMap',
  643. 'specular',
  644. 'glossinessMap',
  645. 'glossiness',
  646. 'alphaMap',
  647. 'envMap',
  648. 'envMapIntensity',
  649. 'refractionRatio',
  650. ],
  651. getMaterialType: function () {
  652. return GLTFMeshStandardSGMaterial;
  653. },
  654. extendParams: function ( materialParams, materialDef, parser ) {
  655. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  656. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  657. materialParams.opacity = 1.0;
  658. var pending = [];
  659. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  660. var array = pbrSpecularGlossiness.diffuseFactor;
  661. materialParams.color.fromArray( array );
  662. materialParams.opacity = array[ 3 ];
  663. }
  664. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  665. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  666. }
  667. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  668. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  669. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  670. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  671. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  672. }
  673. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  674. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  675. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  676. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  677. }
  678. return Promise.all( pending );
  679. },
  680. createMaterial: function ( materialParams ) {
  681. var material = new GLTFMeshStandardSGMaterial( materialParams );
  682. material.fog = true;
  683. material.color = materialParams.color;
  684. material.map = materialParams.map === undefined ? null : materialParams.map;
  685. material.lightMap = null;
  686. material.lightMapIntensity = 1.0;
  687. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  688. material.aoMapIntensity = 1.0;
  689. material.emissive = materialParams.emissive;
  690. material.emissiveIntensity = 1.0;
  691. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  692. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  693. material.bumpScale = 1;
  694. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  695. material.normalMapType = THREE.TangentSpaceNormalMap;
  696. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  697. material.displacementMap = null;
  698. material.displacementScale = 1;
  699. material.displacementBias = 0;
  700. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  701. material.specular = materialParams.specular;
  702. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  703. material.glossiness = materialParams.glossiness;
  704. material.alphaMap = null;
  705. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  706. material.envMapIntensity = 1.0;
  707. material.refractionRatio = 0.98;
  708. return material;
  709. },
  710. };
  711. }
  712. /**
  713. * Mesh Quantization Extension
  714. *
  715. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  716. */
  717. function GLTFMeshQuantizationExtension() {
  718. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  719. }
  720. /*********************************/
  721. /********** INTERPOLATION ********/
  722. /*********************************/
  723. // Spline Interpolation
  724. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  725. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  726. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  727. }
  728. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  729. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  730. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  731. // Copies a sample value to the result buffer. See description of glTF
  732. // CUBICSPLINE values layout in interpolate_() function below.
  733. var result = this.resultBuffer,
  734. values = this.sampleValues,
  735. valueSize = this.valueSize,
  736. offset = index * valueSize * 3 + valueSize;
  737. for ( var i = 0; i !== valueSize; i ++ ) {
  738. result[ i ] = values[ offset + i ];
  739. }
  740. return result;
  741. };
  742. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  743. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  744. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  745. var result = this.resultBuffer;
  746. var values = this.sampleValues;
  747. var stride = this.valueSize;
  748. var stride2 = stride * 2;
  749. var stride3 = stride * 3;
  750. var td = t1 - t0;
  751. var p = ( t - t0 ) / td;
  752. var pp = p * p;
  753. var ppp = pp * p;
  754. var offset1 = i1 * stride3;
  755. var offset0 = offset1 - stride3;
  756. var s2 = - 2 * ppp + 3 * pp;
  757. var s3 = ppp - pp;
  758. var s0 = 1 - s2;
  759. var s1 = s3 - pp + p;
  760. // Layout of keyframe output values for CUBICSPLINE animations:
  761. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  762. for ( var i = 0; i !== stride; i ++ ) {
  763. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  764. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  765. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  766. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  767. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  768. }
  769. return result;
  770. };
  771. /*********************************/
  772. /********** INTERNALS ************/
  773. /*********************************/
  774. /* CONSTANTS */
  775. var WEBGL_CONSTANTS = {
  776. FLOAT: 5126,
  777. //FLOAT_MAT2: 35674,
  778. FLOAT_MAT3: 35675,
  779. FLOAT_MAT4: 35676,
  780. FLOAT_VEC2: 35664,
  781. FLOAT_VEC3: 35665,
  782. FLOAT_VEC4: 35666,
  783. LINEAR: 9729,
  784. REPEAT: 10497,
  785. SAMPLER_2D: 35678,
  786. POINTS: 0,
  787. LINES: 1,
  788. LINE_LOOP: 2,
  789. LINE_STRIP: 3,
  790. TRIANGLES: 4,
  791. TRIANGLE_STRIP: 5,
  792. TRIANGLE_FAN: 6,
  793. UNSIGNED_BYTE: 5121,
  794. UNSIGNED_SHORT: 5123
  795. };
  796. var WEBGL_COMPONENT_TYPES = {
  797. 5120: Int8Array,
  798. 5121: Uint8Array,
  799. 5122: Int16Array,
  800. 5123: Uint16Array,
  801. 5125: Uint32Array,
  802. 5126: Float32Array
  803. };
  804. var WEBGL_FILTERS = {
  805. 9728: THREE.NearestFilter,
  806. 9729: THREE.LinearFilter,
  807. 9984: THREE.NearestMipmapNearestFilter,
  808. 9985: THREE.LinearMipmapNearestFilter,
  809. 9986: THREE.NearestMipmapLinearFilter,
  810. 9987: THREE.LinearMipmapLinearFilter
  811. };
  812. var WEBGL_WRAPPINGS = {
  813. 33071: THREE.ClampToEdgeWrapping,
  814. 33648: THREE.MirroredRepeatWrapping,
  815. 10497: THREE.RepeatWrapping
  816. };
  817. var WEBGL_TYPE_SIZES = {
  818. 'SCALAR': 1,
  819. 'VEC2': 2,
  820. 'VEC3': 3,
  821. 'VEC4': 4,
  822. 'MAT2': 4,
  823. 'MAT3': 9,
  824. 'MAT4': 16
  825. };
  826. var ATTRIBUTES = {
  827. POSITION: 'position',
  828. NORMAL: 'normal',
  829. TANGENT: 'tangent',
  830. TEXCOORD_0: 'uv',
  831. TEXCOORD_1: 'uv2',
  832. COLOR_0: 'color',
  833. WEIGHTS_0: 'skinWeight',
  834. JOINTS_0: 'skinIndex',
  835. };
  836. var PATH_PROPERTIES = {
  837. scale: 'scale',
  838. translation: 'position',
  839. rotation: 'quaternion',
  840. weights: 'morphTargetInfluences'
  841. };
  842. var INTERPOLATION = {
  843. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  844. // keyframe track will be initialized with a default interpolation type, then modified.
  845. LINEAR: THREE.InterpolateLinear,
  846. STEP: THREE.InterpolateDiscrete
  847. };
  848. var ALPHA_MODES = {
  849. OPAQUE: 'OPAQUE',
  850. MASK: 'MASK',
  851. BLEND: 'BLEND'
  852. };
  853. /* UTILITY FUNCTIONS */
  854. function resolveURL( url, path ) {
  855. // Invalid URL
  856. if ( typeof url !== 'string' || url === '' ) return '';
  857. // Host Relative URL
  858. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  859. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  860. }
  861. // Absolute URL http://,https://,//
  862. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  863. // Data URI
  864. if ( /^data:.*,.*$/i.test( url ) ) return url;
  865. // Blob URL
  866. if ( /^blob:.*$/i.test( url ) ) return url;
  867. // Relative URL
  868. return path + url;
  869. }
  870. /**
  871. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  872. */
  873. function createDefaultMaterial( cache ) {
  874. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  875. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  876. color: 0xFFFFFF,
  877. emissive: 0x000000,
  878. metalness: 1,
  879. roughness: 1,
  880. transparent: false,
  881. depthTest: true,
  882. side: THREE.FrontSide
  883. } );
  884. }
  885. return cache[ 'DefaultMaterial' ];
  886. }
  887. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  888. // Add unknown glTF extensions to an object's userData.
  889. for ( var name in objectDef.extensions ) {
  890. if ( knownExtensions[ name ] === undefined ) {
  891. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  892. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  893. }
  894. }
  895. }
  896. /**
  897. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  898. * @param {GLTF.definition} gltfDef
  899. */
  900. function assignExtrasToUserData( object, gltfDef ) {
  901. if ( gltfDef.extras !== undefined ) {
  902. if ( typeof gltfDef.extras === 'object' ) {
  903. Object.assign( object.userData, gltfDef.extras );
  904. } else {
  905. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  906. }
  907. }
  908. }
  909. /**
  910. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  911. *
  912. * @param {THREE.BufferGeometry} geometry
  913. * @param {Array<GLTF.Target>} targets
  914. * @param {GLTFParser} parser
  915. * @return {Promise<THREE.BufferGeometry>}
  916. */
  917. function addMorphTargets( geometry, targets, parser ) {
  918. var hasMorphPosition = false;
  919. var hasMorphNormal = false;
  920. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  921. var target = targets[ i ];
  922. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  923. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  924. if ( hasMorphPosition && hasMorphNormal ) break;
  925. }
  926. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  927. var pendingPositionAccessors = [];
  928. var pendingNormalAccessors = [];
  929. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  930. var target = targets[ i ];
  931. if ( hasMorphPosition ) {
  932. var pendingAccessor = target.POSITION !== undefined
  933. ? parser.getDependency( 'accessor', target.POSITION )
  934. : geometry.attributes.position;
  935. pendingPositionAccessors.push( pendingAccessor );
  936. }
  937. if ( hasMorphNormal ) {
  938. var pendingAccessor = target.NORMAL !== undefined
  939. ? parser.getDependency( 'accessor', target.NORMAL )
  940. : geometry.attributes.normal;
  941. pendingNormalAccessors.push( pendingAccessor );
  942. }
  943. }
  944. return Promise.all( [
  945. Promise.all( pendingPositionAccessors ),
  946. Promise.all( pendingNormalAccessors )
  947. ] ).then( function ( accessors ) {
  948. var morphPositions = accessors[ 0 ];
  949. var morphNormals = accessors[ 1 ];
  950. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  951. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  952. geometry.morphTargetsRelative = true;
  953. return geometry;
  954. } );
  955. }
  956. /**
  957. * @param {THREE.Mesh} mesh
  958. * @param {GLTF.Mesh} meshDef
  959. */
  960. function updateMorphTargets( mesh, meshDef ) {
  961. mesh.updateMorphTargets();
  962. if ( meshDef.weights !== undefined ) {
  963. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  964. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  965. }
  966. }
  967. // .extras has user-defined data, so check that .extras.targetNames is an array.
  968. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  969. var targetNames = meshDef.extras.targetNames;
  970. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  971. mesh.morphTargetDictionary = {};
  972. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  973. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  974. }
  975. } else {
  976. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  977. }
  978. }
  979. }
  980. function createPrimitiveKey( primitiveDef ) {
  981. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  982. var geometryKey;
  983. if ( dracoExtension ) {
  984. geometryKey = 'draco:' + dracoExtension.bufferView
  985. + ':' + dracoExtension.indices
  986. + ':' + createAttributesKey( dracoExtension.attributes );
  987. } else {
  988. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  989. }
  990. return geometryKey;
  991. }
  992. function createAttributesKey( attributes ) {
  993. var attributesKey = '';
  994. var keys = Object.keys( attributes ).sort();
  995. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  996. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  997. }
  998. return attributesKey;
  999. }
  1000. /* GLTF PARSER */
  1001. function GLTFParser( json, options ) {
  1002. this.json = json || {};
  1003. this.extensions = {};
  1004. this.plugins = {};
  1005. this.options = options || {};
  1006. // loader object cache
  1007. this.cache = new GLTFRegistry();
  1008. // associations between Three.js objects and glTF elements
  1009. this.associations = new Map();
  1010. // BufferGeometry caching
  1011. this.primitiveCache = {};
  1012. // Object3D instance caches
  1013. this.meshCache = { refs: {}, uses: {} };
  1014. this.cameraCache = { refs: {}, uses: {} };
  1015. this.lightCache = { refs: {}, uses: {} };
  1016. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  1017. // expensive work of uploading a texture to the GPU off the main thread.
  1018. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  1019. this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
  1020. } else {
  1021. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  1022. }
  1023. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  1024. this.fileLoader = new THREE.FileLoader( this.options.manager );
  1025. this.fileLoader.setResponseType( 'arraybuffer' );
  1026. if ( this.options.crossOrigin === 'use-credentials' ) {
  1027. this.fileLoader.setWithCredentials( true );
  1028. }
  1029. }
  1030. GLTFParser.prototype.setExtensions = function ( extensions ) {
  1031. this.extensions = extensions;
  1032. };
  1033. GLTFParser.prototype.setPlugins = function ( plugins ) {
  1034. this.plugins = plugins;
  1035. };
  1036. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  1037. var parser = this;
  1038. var json = this.json;
  1039. var extensions = this.extensions;
  1040. // Clear the loader cache
  1041. this.cache.removeAll();
  1042. // Mark the special nodes/meshes in json for efficient parse
  1043. this._markDefs();
  1044. Promise.all( [
  1045. this.getDependencies( 'scene' ),
  1046. this.getDependencies( 'animation' ),
  1047. this.getDependencies( 'camera' ),
  1048. ] ).then( function ( dependencies ) {
  1049. var result = {
  1050. scene: dependencies[ 0 ][ json.scene || 0 ],
  1051. scenes: dependencies[ 0 ],
  1052. animations: dependencies[ 1 ],
  1053. cameras: dependencies[ 2 ],
  1054. asset: json.asset,
  1055. parser: parser,
  1056. userData: {}
  1057. };
  1058. addUnknownExtensionsToUserData( extensions, result, json );
  1059. assignExtrasToUserData( result, json );
  1060. onLoad( result );
  1061. } ).catch( onError );
  1062. };
  1063. /**
  1064. * Marks the special nodes/meshes in json for efficient parse.
  1065. */
  1066. GLTFParser.prototype._markDefs = function () {
  1067. var nodeDefs = this.json.nodes || [];
  1068. var skinDefs = this.json.skins || [];
  1069. var meshDefs = this.json.meshes || [];
  1070. // Nothing in the node definition indicates whether it is a Bone or an
  1071. // Object3D. Use the skins' joint references to mark bones.
  1072. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1073. var joints = skinDefs[ skinIndex ].joints;
  1074. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  1075. nodeDefs[ joints[ i ] ].isBone = true;
  1076. }
  1077. }
  1078. // Iterate over all nodes, marking references to shared resources,
  1079. // as well as skeleton joints.
  1080. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1081. var nodeDef = nodeDefs[ nodeIndex ];
  1082. if ( nodeDef.mesh !== undefined ) {
  1083. this._addNodeRef( this.meshCache, nodeDef.mesh );
  1084. // Nothing in the mesh definition indicates whether it is
  1085. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1086. // to mark SkinnedMesh if node has skin.
  1087. if ( nodeDef.skin !== undefined ) {
  1088. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1089. }
  1090. }
  1091. if ( nodeDef.camera !== undefined ) {
  1092. this._addNodeRef( this.cameraCache, nodeDef.camera );
  1093. }
  1094. if ( nodeDef.extensions
  1095. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  1096. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  1097. this._addNodeRef( this.lightCache, nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light );
  1098. }
  1099. }
  1100. };
  1101. /**
  1102. * Counts references to shared node / Object3D resources. These resources
  1103. * can be reused, or "instantiated", at multiple nodes in the scene
  1104. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  1105. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  1106. * Textures) can be reused directly and are not marked here.
  1107. *
  1108. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1109. */
  1110. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  1111. if ( index === undefined ) return;
  1112. if ( cache.refs[ index ] === undefined ) {
  1113. cache.refs[ index ] = cache.uses[ index ] = 0;
  1114. }
  1115. cache.refs[ index ] ++;
  1116. };
  1117. /** Returns a reference to a shared resource, cloning it if necessary. */
  1118. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  1119. if ( cache.refs[ index ] <= 1 ) return object;
  1120. var ref = object.clone();
  1121. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  1122. return ref;
  1123. };
  1124. GLTFParser.prototype._invokeOne = function ( func ) {
  1125. var extensions = Object.values( this.plugins );
  1126. extensions.push( this );
  1127. for ( var i = 0; i < extensions.length; i ++ ) {
  1128. var result = func( extensions[ i ] );
  1129. if ( result ) return result;
  1130. }
  1131. };
  1132. GLTFParser.prototype._invokeAll = function ( func ) {
  1133. var extensions = Object.values( this.plugins );
  1134. extensions.unshift( this );
  1135. var pending = [];
  1136. for ( var i = 0; i < extensions.length; i ++ ) {
  1137. pending.push( func( extensions[ i ] ) );
  1138. }
  1139. return Promise.all( pending );
  1140. };
  1141. /**
  1142. * Requests the specified dependency asynchronously, with caching.
  1143. * @param {string} type
  1144. * @param {number} index
  1145. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  1146. */
  1147. GLTFParser.prototype.getDependency = function ( type, index ) {
  1148. var cacheKey = type + ':' + index;
  1149. var dependency = this.cache.get( cacheKey );
  1150. if ( ! dependency ) {
  1151. switch ( type ) {
  1152. case 'scene':
  1153. dependency = this.loadScene( index );
  1154. break;
  1155. case 'node':
  1156. dependency = this.loadNode( index );
  1157. break;
  1158. case 'mesh':
  1159. dependency = this._invokeOne( function ( ext ) {
  1160. return ext.loadMesh && ext.loadMesh( index );
  1161. } );
  1162. break;
  1163. case 'accessor':
  1164. dependency = this.loadAccessor( index );
  1165. break;
  1166. case 'bufferView':
  1167. dependency = this._invokeOne( function ( ext ) {
  1168. return ext.loadBufferView && ext.loadBufferView( index );
  1169. } );
  1170. break;
  1171. case 'buffer':
  1172. dependency = this.loadBuffer( index );
  1173. break;
  1174. case 'material':
  1175. dependency = this._invokeOne( function ( ext ) {
  1176. return ext.loadMaterial && ext.loadMaterial( index );
  1177. } );
  1178. break;
  1179. case 'texture':
  1180. dependency = this._invokeOne( function ( ext ) {
  1181. return ext.loadTexture && ext.loadTexture( index );
  1182. } );
  1183. break;
  1184. case 'skin':
  1185. dependency = this.loadSkin( index );
  1186. break;
  1187. case 'animation':
  1188. dependency = this.loadAnimation( index );
  1189. break;
  1190. case 'camera':
  1191. dependency = this.loadCamera( index );
  1192. break;
  1193. case 'light':
  1194. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  1195. break;
  1196. default:
  1197. throw new Error( 'Unknown type: ' + type );
  1198. }
  1199. this.cache.add( cacheKey, dependency );
  1200. }
  1201. return dependency;
  1202. };
  1203. /**
  1204. * Requests all dependencies of the specified type asynchronously, with caching.
  1205. * @param {string} type
  1206. * @return {Promise<Array<Object>>}
  1207. */
  1208. GLTFParser.prototype.getDependencies = function ( type ) {
  1209. var dependencies = this.cache.get( type );
  1210. if ( ! dependencies ) {
  1211. var parser = this;
  1212. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1213. dependencies = Promise.all( defs.map( function ( def, index ) {
  1214. return parser.getDependency( type, index );
  1215. } ) );
  1216. this.cache.add( type, dependencies );
  1217. }
  1218. return dependencies;
  1219. };
  1220. /**
  1221. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1222. * @param {number} bufferIndex
  1223. * @return {Promise<ArrayBuffer>}
  1224. */
  1225. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1226. var bufferDef = this.json.buffers[ bufferIndex ];
  1227. var loader = this.fileLoader;
  1228. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1229. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1230. }
  1231. // If present, GLB container is required to be the first buffer.
  1232. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1233. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1234. }
  1235. var options = this.options;
  1236. return new Promise( function ( resolve, reject ) {
  1237. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1238. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1239. } );
  1240. } );
  1241. };
  1242. /**
  1243. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1244. * @param {number} bufferViewIndex
  1245. * @return {Promise<ArrayBuffer>}
  1246. */
  1247. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1248. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1249. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1250. var byteLength = bufferViewDef.byteLength || 0;
  1251. var byteOffset = bufferViewDef.byteOffset || 0;
  1252. return buffer.slice( byteOffset, byteOffset + byteLength );
  1253. } );
  1254. };
  1255. /**
  1256. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1257. * @param {number} accessorIndex
  1258. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1259. */
  1260. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1261. var parser = this;
  1262. var json = this.json;
  1263. var accessorDef = this.json.accessors[ accessorIndex ];
  1264. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1265. // Ignore empty accessors, which may be used to declare runtime
  1266. // information about attributes coming from another source (e.g. Draco
  1267. // compression extension).
  1268. return Promise.resolve( null );
  1269. }
  1270. var pendingBufferViews = [];
  1271. if ( accessorDef.bufferView !== undefined ) {
  1272. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1273. } else {
  1274. pendingBufferViews.push( null );
  1275. }
  1276. if ( accessorDef.sparse !== undefined ) {
  1277. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1278. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1279. }
  1280. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1281. var bufferView = bufferViews[ 0 ];
  1282. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1283. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1284. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1285. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1286. var itemBytes = elementBytes * itemSize;
  1287. var byteOffset = accessorDef.byteOffset || 0;
  1288. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1289. var normalized = accessorDef.normalized === true;
  1290. var array, bufferAttribute;
  1291. // The buffer is not interleaved if the stride is the item size in bytes.
  1292. if ( byteStride && byteStride !== itemBytes ) {
  1293. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  1294. // This makes sure that IBA.count reflects accessor.count properly
  1295. var ibSlice = Math.floor( byteOffset / byteStride );
  1296. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  1297. var ib = parser.cache.get( ibCacheKey );
  1298. if ( ! ib ) {
  1299. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  1300. // Integer parameters to IB/IBA are in array elements, not bytes.
  1301. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1302. parser.cache.add( ibCacheKey, ib );
  1303. }
  1304. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  1305. } else {
  1306. if ( bufferView === null ) {
  1307. array = new TypedArray( accessorDef.count * itemSize );
  1308. } else {
  1309. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1310. }
  1311. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1312. }
  1313. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1314. if ( accessorDef.sparse !== undefined ) {
  1315. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1316. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1317. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1318. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1319. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1320. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1321. if ( bufferView !== null ) {
  1322. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1323. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  1324. }
  1325. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1326. var index = sparseIndices[ i ];
  1327. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1328. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1329. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1330. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1331. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1332. }
  1333. }
  1334. return bufferAttribute;
  1335. } );
  1336. };
  1337. /**
  1338. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1339. * @param {number} textureIndex
  1340. * @return {Promise<THREE.Texture>}
  1341. */
  1342. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1343. var parser = this;
  1344. var json = this.json;
  1345. var options = this.options;
  1346. var textureDef = json.textures[ textureIndex ];
  1347. var textureExtensions = textureDef.extensions || {};
  1348. var source;
  1349. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1350. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1351. } else {
  1352. source = json.images[ textureDef.source ];
  1353. }
  1354. var loader;
  1355. if ( source.uri ) {
  1356. loader = options.manager.getHandler( source.uri );
  1357. }
  1358. if ( ! loader ) {
  1359. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1360. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1361. : this.textureLoader;
  1362. }
  1363. return this.loadTextureImage( textureIndex, source, loader );
  1364. };
  1365. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  1366. var parser = this;
  1367. var json = this.json;
  1368. var options = this.options;
  1369. var textureDef = json.textures[ textureIndex ];
  1370. var URL = self.URL || self.webkitURL;
  1371. var sourceURI = source.uri;
  1372. var isObjectURL = false;
  1373. var hasAlpha = true;
  1374. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  1375. if ( source.bufferView !== undefined ) {
  1376. // Load binary image data from bufferView, if provided.
  1377. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1378. if ( source.mimeType === 'image/png' ) {
  1379. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  1380. hasAlpha = new DataView( bufferView, 25, 1 ).getUint8( 0, false ) === 6;
  1381. }
  1382. isObjectURL = true;
  1383. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1384. sourceURI = URL.createObjectURL( blob );
  1385. return sourceURI;
  1386. } );
  1387. }
  1388. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1389. return new Promise( function ( resolve, reject ) {
  1390. var onLoad = resolve;
  1391. if ( loader.isImageBitmapLoader === true ) {
  1392. onLoad = function ( imageBitmap ) {
  1393. resolve( new THREE.CanvasTexture( imageBitmap ) );
  1394. };
  1395. }
  1396. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  1397. } );
  1398. } ).then( function ( texture ) {
  1399. // Clean up resources and configure Texture.
  1400. if ( isObjectURL === true ) {
  1401. URL.revokeObjectURL( sourceURI );
  1402. }
  1403. texture.flipY = false;
  1404. if ( textureDef.name ) texture.name = textureDef.name;
  1405. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  1406. if ( ! hasAlpha ) texture.format = THREE.RGBFormat;
  1407. var samplers = json.samplers || {};
  1408. var sampler = samplers[ textureDef.sampler ] || {};
  1409. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1410. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  1411. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1412. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1413. parser.associations.set( texture, {
  1414. type: 'textures',
  1415. index: textureIndex
  1416. } );
  1417. return texture;
  1418. } );
  1419. };
  1420. /**
  1421. * Asynchronously assigns a texture to the given material parameters.
  1422. * @param {Object} materialParams
  1423. * @param {string} mapName
  1424. * @param {Object} mapDef
  1425. * @return {Promise}
  1426. */
  1427. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  1428. var parser = this;
  1429. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  1430. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  1431. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  1432. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  1433. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  1434. }
  1435. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1436. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1437. if ( transform ) {
  1438. var gltfReference = parser.associations.get( texture );
  1439. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1440. parser.associations.set( texture, gltfReference );
  1441. }
  1442. }
  1443. materialParams[ mapName ] = texture;
  1444. } );
  1445. };
  1446. /**
  1447. * Assigns final material to a Mesh, Line, or Points instance. The instance
  1448. * already has a material (generated from the glTF material options alone)
  1449. * but reuse of the same glTF material may require multiple threejs materials
  1450. * to accomodate different primitive types, defines, etc. New materials will
  1451. * be created if necessary, and reused from a cache.
  1452. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  1453. */
  1454. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  1455. var geometry = mesh.geometry;
  1456. var material = mesh.material;
  1457. var useVertexTangents = geometry.attributes.tangent !== undefined;
  1458. var useVertexColors = geometry.attributes.color !== undefined;
  1459. var useFlatShading = geometry.attributes.normal === undefined;
  1460. var useSkinning = mesh.isSkinnedMesh === true;
  1461. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1462. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1463. if ( mesh.isPoints ) {
  1464. var cacheKey = 'PointsMaterial:' + material.uuid;
  1465. var pointsMaterial = this.cache.get( cacheKey );
  1466. if ( ! pointsMaterial ) {
  1467. pointsMaterial = new THREE.PointsMaterial();
  1468. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1469. pointsMaterial.color.copy( material.color );
  1470. pointsMaterial.map = material.map;
  1471. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  1472. this.cache.add( cacheKey, pointsMaterial );
  1473. }
  1474. material = pointsMaterial;
  1475. } else if ( mesh.isLine ) {
  1476. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1477. var lineMaterial = this.cache.get( cacheKey );
  1478. if ( ! lineMaterial ) {
  1479. lineMaterial = new THREE.LineBasicMaterial();
  1480. THREE.Material.prototype.copy.call( lineMaterial, material );
  1481. lineMaterial.color.copy( material.color );
  1482. this.cache.add( cacheKey, lineMaterial );
  1483. }
  1484. material = lineMaterial;
  1485. }
  1486. // Clone the material if it will be modified
  1487. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1488. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1489. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1490. if ( useSkinning ) cacheKey += 'skinning:';
  1491. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  1492. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1493. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1494. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1495. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1496. var cachedMaterial = this.cache.get( cacheKey );
  1497. if ( ! cachedMaterial ) {
  1498. cachedMaterial = material.clone();
  1499. if ( useSkinning ) cachedMaterial.skinning = true;
  1500. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  1501. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  1502. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1503. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1504. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1505. this.cache.add( cacheKey, cachedMaterial );
  1506. this.associations.set( cachedMaterial, this.associations.get( material ) );
  1507. }
  1508. material = cachedMaterial;
  1509. }
  1510. // workarounds for mesh and geometry
  1511. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1512. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  1513. }
  1514. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1515. if ( material.normalScale && ! useVertexTangents ) {
  1516. material.normalScale.y = - material.normalScale.y;
  1517. }
  1518. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  1519. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  1520. }
  1521. mesh.material = material;
  1522. };
  1523. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  1524. return THREE.MeshStandardMaterial;
  1525. };
  1526. /**
  1527. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1528. * @param {number} materialIndex
  1529. * @return {Promise<THREE.Material>}
  1530. */
  1531. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1532. var parser = this;
  1533. var json = this.json;
  1534. var extensions = this.extensions;
  1535. var materialDef = json.materials[ materialIndex ];
  1536. var materialType;
  1537. var materialParams = {};
  1538. var materialExtensions = materialDef.extensions || {};
  1539. var pending = [];
  1540. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1541. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1542. materialType = sgExtension.getMaterialType();
  1543. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1544. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1545. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1546. materialType = kmuExtension.getMaterialType();
  1547. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1548. } else {
  1549. // Specification:
  1550. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1551. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1552. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1553. materialParams.opacity = 1.0;
  1554. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1555. var array = metallicRoughness.baseColorFactor;
  1556. materialParams.color.fromArray( array );
  1557. materialParams.opacity = array[ 3 ];
  1558. }
  1559. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1560. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1561. }
  1562. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1563. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1564. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1565. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1566. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1567. }
  1568. materialType = this._invokeOne( function ( ext ) {
  1569. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  1570. } );
  1571. pending.push( this._invokeAll( function ( ext ) {
  1572. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  1573. } ) );
  1574. }
  1575. if ( materialDef.doubleSided === true ) {
  1576. materialParams.side = THREE.DoubleSide;
  1577. }
  1578. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1579. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1580. materialParams.transparent = true;
  1581. // See: https://github.com/mrdoob/three.js/issues/17706
  1582. materialParams.depthWrite = false;
  1583. } else {
  1584. materialParams.transparent = false;
  1585. if ( alphaMode === ALPHA_MODES.MASK ) {
  1586. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1587. }
  1588. }
  1589. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1590. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1591. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1592. if ( materialDef.normalTexture.scale !== undefined ) {
  1593. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1594. }
  1595. }
  1596. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1597. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1598. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1599. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1600. }
  1601. }
  1602. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1603. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1604. }
  1605. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1606. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1607. }
  1608. return Promise.all( pending ).then( function () {
  1609. var material;
  1610. if ( materialType === GLTFMeshStandardSGMaterial ) {
  1611. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1612. } else {
  1613. material = new materialType( materialParams );
  1614. }
  1615. if ( materialDef.name ) material.name = materialDef.name;
  1616. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1617. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1618. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1619. assignExtrasToUserData( material, materialDef );
  1620. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  1621. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1622. return material;
  1623. } );
  1624. };
  1625. /**
  1626. * @param {THREE.BufferGeometry} geometry
  1627. * @param {GLTF.Primitive} primitiveDef
  1628. * @param {GLTFParser} parser
  1629. */
  1630. function computeBounds( geometry, primitiveDef, parser ) {
  1631. var attributes = primitiveDef.attributes;
  1632. var box = new THREE.Box3();
  1633. if ( attributes.POSITION !== undefined ) {
  1634. var accessor = parser.json.accessors[ attributes.POSITION ];
  1635. var min = accessor.min;
  1636. var max = accessor.max;
  1637. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1638. if ( min !== undefined && max !== undefined ) {
  1639. box.set(
  1640. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  1641. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  1642. } else {
  1643. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1644. return;
  1645. }
  1646. } else {
  1647. return;
  1648. }
  1649. var targets = primitiveDef.targets;
  1650. if ( targets !== undefined ) {
  1651. var maxDisplacement = new THREE.Vector3();
  1652. var vector = new THREE.Vector3();
  1653. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1654. var target = targets[ i ];
  1655. if ( target.POSITION !== undefined ) {
  1656. var accessor = parser.json.accessors[ target.POSITION ];
  1657. var min = accessor.min;
  1658. var max = accessor.max;
  1659. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1660. if ( min !== undefined && max !== undefined ) {
  1661. // we need to get max of absolute components because target weight is [-1,1]
  1662. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  1663. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  1664. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  1665. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  1666. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  1667. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  1668. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  1669. maxDisplacement.max( vector );
  1670. } else {
  1671. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1672. }
  1673. }
  1674. }
  1675. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  1676. box.expandByVector( maxDisplacement );
  1677. }
  1678. geometry.boundingBox = box;
  1679. var sphere = new THREE.Sphere();
  1680. box.getCenter( sphere.center );
  1681. sphere.radius = box.min.distanceTo( box.max ) / 2;
  1682. geometry.boundingSphere = sphere;
  1683. }
  1684. /**
  1685. * @param {THREE.BufferGeometry} geometry
  1686. * @param {GLTF.Primitive} primitiveDef
  1687. * @param {GLTFParser} parser
  1688. * @return {Promise<THREE.BufferGeometry>}
  1689. */
  1690. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1691. var attributes = primitiveDef.attributes;
  1692. var pending = [];
  1693. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1694. return parser.getDependency( 'accessor', accessorIndex )
  1695. .then( function ( accessor ) {
  1696. geometry.setAttribute( attributeName, accessor );
  1697. } );
  1698. }
  1699. for ( var gltfAttributeName in attributes ) {
  1700. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1701. // Skip attributes already provided by e.g. Draco extension.
  1702. if ( threeAttributeName in geometry.attributes ) continue;
  1703. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1704. }
  1705. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1706. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1707. geometry.setIndex( accessor );
  1708. } );
  1709. pending.push( accessor );
  1710. }
  1711. assignExtrasToUserData( geometry, primitiveDef );
  1712. computeBounds( geometry, primitiveDef, parser );
  1713. return Promise.all( pending ).then( function () {
  1714. return primitiveDef.targets !== undefined
  1715. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1716. : geometry;
  1717. } );
  1718. }
  1719. /**
  1720. * @param {THREE.BufferGeometry} geometry
  1721. * @param {Number} drawMode
  1722. * @return {THREE.BufferGeometry}
  1723. */
  1724. function toTrianglesDrawMode( geometry, drawMode ) {
  1725. var index = geometry.getIndex();
  1726. // generate index if not present
  1727. if ( index === null ) {
  1728. var indices = [];
  1729. var position = geometry.getAttribute( 'position' );
  1730. if ( position !== undefined ) {
  1731. for ( var i = 0; i < position.count; i ++ ) {
  1732. indices.push( i );
  1733. }
  1734. geometry.setIndex( indices );
  1735. index = geometry.getIndex();
  1736. } else {
  1737. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  1738. return geometry;
  1739. }
  1740. }
  1741. //
  1742. var numberOfTriangles = index.count - 2;
  1743. var newIndices = [];
  1744. if ( drawMode === THREE.TriangleFanDrawMode ) {
  1745. // gl.TRIANGLE_FAN
  1746. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  1747. newIndices.push( index.getX( 0 ) );
  1748. newIndices.push( index.getX( i ) );
  1749. newIndices.push( index.getX( i + 1 ) );
  1750. }
  1751. } else {
  1752. // gl.TRIANGLE_STRIP
  1753. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  1754. if ( i % 2 === 0 ) {
  1755. newIndices.push( index.getX( i ) );
  1756. newIndices.push( index.getX( i + 1 ) );
  1757. newIndices.push( index.getX( i + 2 ) );
  1758. } else {
  1759. newIndices.push( index.getX( i + 2 ) );
  1760. newIndices.push( index.getX( i + 1 ) );
  1761. newIndices.push( index.getX( i ) );
  1762. }
  1763. }
  1764. }
  1765. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  1766. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  1767. }
  1768. // build final geometry
  1769. var newGeometry = geometry.clone();
  1770. newGeometry.setIndex( newIndices );
  1771. return newGeometry;
  1772. }
  1773. /**
  1774. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1775. *
  1776. * Creates BufferGeometries from primitives.
  1777. *
  1778. * @param {Array<GLTF.Primitive>} primitives
  1779. * @return {Promise<Array<THREE.BufferGeometry>>}
  1780. */
  1781. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1782. var parser = this;
  1783. var extensions = this.extensions;
  1784. var cache = this.primitiveCache;
  1785. function createDracoPrimitive( primitive ) {
  1786. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1787. .decodePrimitive( primitive, parser )
  1788. .then( function ( geometry ) {
  1789. return addPrimitiveAttributes( geometry, primitive, parser );
  1790. } );
  1791. }
  1792. var pending = [];
  1793. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1794. var primitive = primitives[ i ];
  1795. var cacheKey = createPrimitiveKey( primitive );
  1796. // See if we've already created this geometry
  1797. var cached = cache[ cacheKey ];
  1798. if ( cached ) {
  1799. // Use the cached geometry if it exists
  1800. pending.push( cached.promise );
  1801. } else {
  1802. var geometryPromise;
  1803. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1804. // Use DRACO geometry if available
  1805. geometryPromise = createDracoPrimitive( primitive );
  1806. } else {
  1807. // Otherwise create a new geometry
  1808. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1809. }
  1810. // Cache this geometry
  1811. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1812. pending.push( geometryPromise );
  1813. }
  1814. }
  1815. return Promise.all( pending );
  1816. };
  1817. /**
  1818. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1819. * @param {number} meshIndex
  1820. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1821. */
  1822. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1823. var parser = this;
  1824. var json = this.json;
  1825. var meshDef = json.meshes[ meshIndex ];
  1826. var primitives = meshDef.primitives;
  1827. var pending = [];
  1828. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1829. var material = primitives[ i ].material === undefined
  1830. ? createDefaultMaterial( this.cache )
  1831. : this.getDependency( 'material', primitives[ i ].material );
  1832. pending.push( material );
  1833. }
  1834. pending.push( parser.loadGeometries( primitives ) );
  1835. return Promise.all( pending ).then( function ( results ) {
  1836. var materials = results.slice( 0, results.length - 1 );
  1837. var geometries = results[ results.length - 1 ];
  1838. var meshes = [];
  1839. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1840. var geometry = geometries[ i ];
  1841. var primitive = primitives[ i ];
  1842. // 1. create Mesh
  1843. var mesh;
  1844. var material = materials[ i ];
  1845. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1846. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1847. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1848. primitive.mode === undefined ) {
  1849. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  1850. mesh = meshDef.isSkinnedMesh === true
  1851. ? new THREE.SkinnedMesh( geometry, material )
  1852. : new THREE.Mesh( geometry, material );
  1853. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  1854. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  1855. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  1856. mesh.normalizeSkinWeights();
  1857. }
  1858. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1859. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  1860. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1861. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  1862. }
  1863. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1864. mesh = new THREE.LineSegments( geometry, material );
  1865. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1866. mesh = new THREE.Line( geometry, material );
  1867. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1868. mesh = new THREE.LineLoop( geometry, material );
  1869. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1870. mesh = new THREE.Points( geometry, material );
  1871. } else {
  1872. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1873. }
  1874. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1875. updateMorphTargets( mesh, meshDef );
  1876. }
  1877. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1878. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1879. assignExtrasToUserData( mesh, meshDef );
  1880. parser.assignFinalMaterial( mesh );
  1881. meshes.push( mesh );
  1882. }
  1883. if ( meshes.length === 1 ) {
  1884. return meshes[ 0 ];
  1885. }
  1886. var group = new THREE.Group();
  1887. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1888. group.add( meshes[ i ] );
  1889. }
  1890. return group;
  1891. } );
  1892. };
  1893. /**
  1894. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1895. * @param {number} cameraIndex
  1896. * @return {Promise<THREE.Camera>}
  1897. */
  1898. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1899. var camera;
  1900. var cameraDef = this.json.cameras[ cameraIndex ];
  1901. var params = cameraDef[ cameraDef.type ];
  1902. if ( ! params ) {
  1903. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1904. return;
  1905. }
  1906. if ( cameraDef.type === 'perspective' ) {
  1907. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1908. } else if ( cameraDef.type === 'orthographic' ) {
  1909. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  1910. }
  1911. if ( cameraDef.name ) camera.name = cameraDef.name;
  1912. assignExtrasToUserData( camera, cameraDef );
  1913. return Promise.resolve( camera );
  1914. };
  1915. /**
  1916. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1917. * @param {number} skinIndex
  1918. * @return {Promise<Object>}
  1919. */
  1920. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1921. var skinDef = this.json.skins[ skinIndex ];
  1922. var skinEntry = { joints: skinDef.joints };
  1923. if ( skinDef.inverseBindMatrices === undefined ) {
  1924. return Promise.resolve( skinEntry );
  1925. }
  1926. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1927. skinEntry.inverseBindMatrices = accessor;
  1928. return skinEntry;
  1929. } );
  1930. };
  1931. /**
  1932. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1933. * @param {number} animationIndex
  1934. * @return {Promise<THREE.AnimationClip>}
  1935. */
  1936. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1937. var json = this.json;
  1938. var animationDef = json.animations[ animationIndex ];
  1939. var pendingNodes = [];
  1940. var pendingInputAccessors = [];
  1941. var pendingOutputAccessors = [];
  1942. var pendingSamplers = [];
  1943. var pendingTargets = [];
  1944. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1945. var channel = animationDef.channels[ i ];
  1946. var sampler = animationDef.samplers[ channel.sampler ];
  1947. var target = channel.target;
  1948. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1949. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1950. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1951. pendingNodes.push( this.getDependency( 'node', name ) );
  1952. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  1953. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  1954. pendingSamplers.push( sampler );
  1955. pendingTargets.push( target );
  1956. }
  1957. return Promise.all( [
  1958. Promise.all( pendingNodes ),
  1959. Promise.all( pendingInputAccessors ),
  1960. Promise.all( pendingOutputAccessors ),
  1961. Promise.all( pendingSamplers ),
  1962. Promise.all( pendingTargets )
  1963. ] ).then( function ( dependencies ) {
  1964. var nodes = dependencies[ 0 ];
  1965. var inputAccessors = dependencies[ 1 ];
  1966. var outputAccessors = dependencies[ 2 ];
  1967. var samplers = dependencies[ 3 ];
  1968. var targets = dependencies[ 4 ];
  1969. var tracks = [];
  1970. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  1971. var node = nodes[ i ];
  1972. var inputAccessor = inputAccessors[ i ];
  1973. var outputAccessor = outputAccessors[ i ];
  1974. var sampler = samplers[ i ];
  1975. var target = targets[ i ];
  1976. if ( node === undefined ) continue;
  1977. node.updateMatrix();
  1978. node.matrixAutoUpdate = true;
  1979. var TypedKeyframeTrack;
  1980. switch ( PATH_PROPERTIES[ target.path ] ) {
  1981. case PATH_PROPERTIES.weights:
  1982. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1983. break;
  1984. case PATH_PROPERTIES.rotation:
  1985. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1986. break;
  1987. case PATH_PROPERTIES.position:
  1988. case PATH_PROPERTIES.scale:
  1989. default:
  1990. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1991. break;
  1992. }
  1993. var targetName = node.name ? node.name : node.uuid;
  1994. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1995. var targetNames = [];
  1996. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1997. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  1998. node.traverse( function ( object ) {
  1999. if ( object.isMesh === true && object.morphTargetInfluences ) {
  2000. targetNames.push( object.name ? object.name : object.uuid );
  2001. }
  2002. } );
  2003. } else {
  2004. targetNames.push( targetName );
  2005. }
  2006. var outputArray = outputAccessor.array;
  2007. if ( outputAccessor.normalized ) {
  2008. var scale;
  2009. if ( outputArray.constructor === Int8Array ) {
  2010. scale = 1 / 127;
  2011. } else if ( outputArray.constructor === Uint8Array ) {
  2012. scale = 1 / 255;
  2013. } else if ( outputArray.constructor == Int16Array ) {
  2014. scale = 1 / 32767;
  2015. } else if ( outputArray.constructor === Uint16Array ) {
  2016. scale = 1 / 65535;
  2017. } else {
  2018. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  2019. }
  2020. var scaled = new Float32Array( outputArray.length );
  2021. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  2022. scaled[ j ] = outputArray[ j ] * scale;
  2023. }
  2024. outputArray = scaled;
  2025. }
  2026. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  2027. var track = new TypedKeyframeTrack(
  2028. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  2029. inputAccessor.array,
  2030. outputArray,
  2031. interpolation
  2032. );
  2033. // Override interpolation with custom factory method.
  2034. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  2035. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  2036. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  2037. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  2038. // must be divided by three to get the interpolant's sampleSize argument.
  2039. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  2040. };
  2041. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  2042. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  2043. }
  2044. tracks.push( track );
  2045. }
  2046. }
  2047. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  2048. return new THREE.AnimationClip( name, undefined, tracks );
  2049. } );
  2050. };
  2051. /**
  2052. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  2053. * @param {number} nodeIndex
  2054. * @return {Promise<THREE.Object3D>}
  2055. */
  2056. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  2057. var json = this.json;
  2058. var extensions = this.extensions;
  2059. var parser = this;
  2060. var nodeDef = json.nodes[ nodeIndex ];
  2061. return ( function () {
  2062. var pending = [];
  2063. if ( nodeDef.mesh !== undefined ) {
  2064. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  2065. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  2066. // if weights are provided on the node, override weights on the mesh.
  2067. if ( nodeDef.weights !== undefined ) {
  2068. node.traverse( function ( o ) {
  2069. if ( ! o.isMesh ) return;
  2070. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  2071. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  2072. }
  2073. } );
  2074. }
  2075. return node;
  2076. } ) );
  2077. }
  2078. if ( nodeDef.camera !== undefined ) {
  2079. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  2080. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  2081. } ) );
  2082. }
  2083. if ( nodeDef.extensions
  2084. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  2085. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  2086. var lightIndex = nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light;
  2087. pending.push( parser.getDependency( 'light', lightIndex ).then( function ( light ) {
  2088. return parser._getNodeRef( parser.lightCache, lightIndex, light );
  2089. } ) );
  2090. }
  2091. return Promise.all( pending );
  2092. }() ).then( function ( objects ) {
  2093. var node;
  2094. // .isBone isn't in glTF spec. See ._markDefs
  2095. if ( nodeDef.isBone === true ) {
  2096. node = new THREE.Bone();
  2097. } else if ( objects.length > 1 ) {
  2098. node = new THREE.Group();
  2099. } else if ( objects.length === 1 ) {
  2100. node = objects[ 0 ];
  2101. } else {
  2102. node = new THREE.Object3D();
  2103. }
  2104. if ( node !== objects[ 0 ] ) {
  2105. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  2106. node.add( objects[ i ] );
  2107. }
  2108. }
  2109. if ( nodeDef.name ) {
  2110. node.userData.name = nodeDef.name;
  2111. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  2112. }
  2113. assignExtrasToUserData( node, nodeDef );
  2114. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  2115. if ( nodeDef.matrix !== undefined ) {
  2116. var matrix = new THREE.Matrix4();
  2117. matrix.fromArray( nodeDef.matrix );
  2118. node.applyMatrix4( matrix );
  2119. } else {
  2120. if ( nodeDef.translation !== undefined ) {
  2121. node.position.fromArray( nodeDef.translation );
  2122. }
  2123. if ( nodeDef.rotation !== undefined ) {
  2124. node.quaternion.fromArray( nodeDef.rotation );
  2125. }
  2126. if ( nodeDef.scale !== undefined ) {
  2127. node.scale.fromArray( nodeDef.scale );
  2128. }
  2129. }
  2130. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  2131. return node;
  2132. } );
  2133. };
  2134. /**
  2135. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  2136. * @param {number} sceneIndex
  2137. * @return {Promise<THREE.Group>}
  2138. */
  2139. GLTFParser.prototype.loadScene = function () {
  2140. // scene node hierachy builder
  2141. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  2142. var nodeDef = json.nodes[ nodeId ];
  2143. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  2144. if ( nodeDef.skin === undefined ) return node;
  2145. // build skeleton here as well
  2146. var skinEntry;
  2147. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  2148. skinEntry = skin;
  2149. var pendingJoints = [];
  2150. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  2151. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  2152. }
  2153. return Promise.all( pendingJoints );
  2154. } ).then( function ( jointNodes ) {
  2155. node.traverse( function ( mesh ) {
  2156. if ( ! mesh.isMesh ) return;
  2157. var bones = [];
  2158. var boneInverses = [];
  2159. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  2160. var jointNode = jointNodes[ j ];
  2161. if ( jointNode ) {
  2162. bones.push( jointNode );
  2163. var mat = new THREE.Matrix4();
  2164. if ( skinEntry.inverseBindMatrices !== undefined ) {
  2165. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  2166. }
  2167. boneInverses.push( mat );
  2168. } else {
  2169. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  2170. }
  2171. }
  2172. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  2173. } );
  2174. return node;
  2175. } );
  2176. } ).then( function ( node ) {
  2177. // build node hierachy
  2178. parentObject.add( node );
  2179. var pending = [];
  2180. if ( nodeDef.children ) {
  2181. var children = nodeDef.children;
  2182. for ( var i = 0, il = children.length; i < il; i ++ ) {
  2183. var child = children[ i ];
  2184. pending.push( buildNodeHierachy( child, node, json, parser ) );
  2185. }
  2186. }
  2187. return Promise.all( pending );
  2188. } );
  2189. }
  2190. return function loadScene( sceneIndex ) {
  2191. var json = this.json;
  2192. var extensions = this.extensions;
  2193. var sceneDef = this.json.scenes[ sceneIndex ];
  2194. var parser = this;
  2195. // Loader returns Group, not Scene.
  2196. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  2197. var scene = new THREE.Group();
  2198. if ( sceneDef.name ) scene.name = sceneDef.name;
  2199. assignExtrasToUserData( scene, sceneDef );
  2200. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  2201. var nodeIds = sceneDef.nodes || [];
  2202. var pending = [];
  2203. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  2204. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  2205. }
  2206. return Promise.all( pending ).then( function () {
  2207. return scene;
  2208. } );
  2209. };
  2210. }();
  2211. return GLTFLoader;
  2212. } )();