GLTFLoader.js 71 KB

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