GLTFLoader.js 112 KB

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