GLTFLoader.js 85 KB

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