GLTFLoader.js 85 KB

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