GLTFLoader.js 93 KB

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