2
0

GLTFLoader.js 93 KB

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