2
0

GLTFLoader.js 65 KB

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