GLTFLoader.js 79 KB

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