GLTFLoader.js 61 KB

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