GLTFLoader.js 69 KB

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