GLTFLoader.js 79 KB

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