GLTFLoader.js 77 KB

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