GLTFLoader.js 79 KB

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