GLTFLoader.js 84 KB

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