GLTFLoader.js 87 KB

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