GLTFLoader.js 100 KB

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