GLTFLoader.js 72 KB

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