GLTFLoader.js 66 KB

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