GLTFLoader.js 80 KB

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