GLTFLoader.js 85 KB

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