GLTFLoader.js 72 KB

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