GLTFLoader.js 104 KB

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