GLTFLoader.js 70 KB

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