GLTFLoader.js 101 KB

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