GLTFLoader.js 90 KB

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