GLTFLoader.js 78 KB

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