GLTFLoader.js 70 KB

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