GLTFLoader.js 114 KB

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