2
0

GLTFLoader.js 80 KB

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