GLTFLoader.js 80 KB

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