GLTFLoader.js 79 KB

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