2
0

GLTFLoader.js 59 KB

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