GLTFLoader.js 85 KB

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