GLTFLoader.js 73 KB

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