GLTFLoader.js 90 KB

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