GLTFLoader.js 57 KB

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