GLTFLoader.js 112 KB

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