2
0

GLTFLoader.js 62 KB

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