GLTFLoader.js 79 KB

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