GLTFLoader.js 98 KB

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