GLTFLoader.js 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172
  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. /* UTILITY FUNCTIONS */
  720. function resolveURL( url, path ) {
  721. // Invalid URL
  722. if ( typeof url !== 'string' || url === '' ) return '';
  723. // Host Relative URL
  724. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  725. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  726. }
  727. // Absolute URL http://,https://,//
  728. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  729. // Data URI
  730. if ( /^data:.*,.*$/i.test( url ) ) return url;
  731. // Blob URL
  732. if ( /^blob:.*$/i.test( url ) ) return url;
  733. // Relative URL
  734. return path + url;
  735. }
  736. /**
  737. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  738. */
  739. function createDefaultMaterial( cache ) {
  740. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  741. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  742. color: 0xFFFFFF,
  743. emissive: 0x000000,
  744. metalness: 1,
  745. roughness: 1,
  746. transparent: false,
  747. depthTest: true,
  748. side: THREE.FrontSide
  749. } );
  750. }
  751. return cache[ 'DefaultMaterial' ];
  752. }
  753. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  754. // Add unknown glTF extensions to an object's userData.
  755. for ( var name in objectDef.extensions ) {
  756. if ( knownExtensions[ name ] === undefined ) {
  757. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  758. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  759. }
  760. }
  761. }
  762. /**
  763. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  764. * @param {GLTF.definition} gltfDef
  765. */
  766. function assignExtrasToUserData( object, gltfDef ) {
  767. if ( gltfDef.extras !== undefined ) {
  768. if ( typeof gltfDef.extras === 'object' ) {
  769. Object.assign( object.userData, gltfDef.extras );
  770. } else {
  771. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  772. }
  773. }
  774. }
  775. /**
  776. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  777. *
  778. * @param {THREE.BufferGeometry} geometry
  779. * @param {Array<GLTF.Target>} targets
  780. * @param {GLTFParser} parser
  781. * @return {Promise<THREE.BufferGeometry>}
  782. */
  783. function addMorphTargets( geometry, targets, parser ) {
  784. var hasMorphPosition = false;
  785. var hasMorphNormal = false;
  786. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  787. var target = targets[ i ];
  788. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  789. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  790. if ( hasMorphPosition && hasMorphNormal ) break;
  791. }
  792. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  793. var pendingPositionAccessors = [];
  794. var pendingNormalAccessors = [];
  795. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  796. var target = targets[ i ];
  797. if ( hasMorphPosition ) {
  798. var pendingAccessor = target.POSITION !== undefined
  799. ? parser.getDependency( 'accessor', target.POSITION )
  800. : geometry.attributes.position;
  801. pendingPositionAccessors.push( pendingAccessor );
  802. }
  803. if ( hasMorphNormal ) {
  804. var pendingAccessor = target.NORMAL !== undefined
  805. ? parser.getDependency( 'accessor', target.NORMAL )
  806. : geometry.attributes.normal;
  807. pendingNormalAccessors.push( pendingAccessor );
  808. }
  809. }
  810. return Promise.all( [
  811. Promise.all( pendingPositionAccessors ),
  812. Promise.all( pendingNormalAccessors )
  813. ] ).then( function ( accessors ) {
  814. var morphPositions = accessors[ 0 ];
  815. var morphNormals = accessors[ 1 ];
  816. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  817. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  818. geometry.morphTargetsRelative = true;
  819. return geometry;
  820. } );
  821. }
  822. /**
  823. * @param {THREE.Mesh} mesh
  824. * @param {GLTF.Mesh} meshDef
  825. */
  826. function updateMorphTargets( mesh, meshDef ) {
  827. mesh.updateMorphTargets();
  828. if ( meshDef.weights !== undefined ) {
  829. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  830. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  831. }
  832. }
  833. // .extras has user-defined data, so check that .extras.targetNames is an array.
  834. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  835. var targetNames = meshDef.extras.targetNames;
  836. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  837. mesh.morphTargetDictionary = {};
  838. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  839. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  840. }
  841. } else {
  842. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  843. }
  844. }
  845. }
  846. function createPrimitiveKey( primitiveDef ) {
  847. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  848. var geometryKey;
  849. if ( dracoExtension ) {
  850. geometryKey = 'draco:' + dracoExtension.bufferView
  851. + ':' + dracoExtension.indices
  852. + ':' + createAttributesKey( dracoExtension.attributes );
  853. } else {
  854. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  855. }
  856. return geometryKey;
  857. }
  858. function createAttributesKey( attributes ) {
  859. var attributesKey = '';
  860. var keys = Object.keys( attributes ).sort();
  861. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  862. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  863. }
  864. return attributesKey;
  865. }
  866. /* GLTF PARSER */
  867. function GLTFParser( json, extensions, options ) {
  868. this.json = json || {};
  869. this.extensions = extensions || {};
  870. this.options = options || {};
  871. // loader object cache
  872. this.cache = new GLTFRegistry();
  873. // BufferGeometry caching
  874. this.primitiveCache = {};
  875. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  876. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  877. this.fileLoader = new THREE.FileLoader( this.options.manager );
  878. this.fileLoader.setResponseType( 'arraybuffer' );
  879. if ( this.options.crossOrigin === 'use-credentials' ) {
  880. this.fileLoader.setWithCredentials( true );
  881. }
  882. }
  883. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  884. var parser = this;
  885. var json = this.json;
  886. var extensions = this.extensions;
  887. // Clear the loader cache
  888. this.cache.removeAll();
  889. // Mark the special nodes/meshes in json for efficient parse
  890. this.markDefs();
  891. Promise.all( [
  892. this.getDependencies( 'scene' ),
  893. this.getDependencies( 'animation' ),
  894. this.getDependencies( 'camera' ),
  895. ] ).then( function ( dependencies ) {
  896. var result = {
  897. scene: dependencies[ 0 ][ json.scene || 0 ],
  898. scenes: dependencies[ 0 ],
  899. animations: dependencies[ 1 ],
  900. cameras: dependencies[ 2 ],
  901. asset: json.asset,
  902. parser: parser,
  903. userData: {}
  904. };
  905. addUnknownExtensionsToUserData( extensions, result, json );
  906. assignExtrasToUserData( result, json );
  907. onLoad( result );
  908. } ).catch( onError );
  909. };
  910. /**
  911. * Marks the special nodes/meshes in json for efficient parse.
  912. */
  913. GLTFParser.prototype.markDefs = function () {
  914. var nodeDefs = this.json.nodes || [];
  915. var skinDefs = this.json.skins || [];
  916. var meshDefs = this.json.meshes || [];
  917. var meshReferences = {};
  918. var meshUses = {};
  919. // Nothing in the node definition indicates whether it is a Bone or an
  920. // Object3D. Use the skins' joint references to mark bones.
  921. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  922. var joints = skinDefs[ skinIndex ].joints;
  923. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  924. nodeDefs[ joints[ i ] ].isBone = true;
  925. }
  926. }
  927. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  928. // avoid having more than one THREE.Mesh with the same name, count
  929. // references and rename instances below.
  930. //
  931. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  932. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  933. var nodeDef = nodeDefs[ nodeIndex ];
  934. if ( nodeDef.mesh !== undefined ) {
  935. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  936. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  937. }
  938. meshReferences[ nodeDef.mesh ] ++;
  939. // Nothing in the mesh definition indicates whether it is
  940. // a SkinnedMesh or Mesh. Use the node's mesh reference
  941. // to mark SkinnedMesh if node has skin.
  942. if ( nodeDef.skin !== undefined ) {
  943. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  944. }
  945. }
  946. }
  947. this.json.meshReferences = meshReferences;
  948. this.json.meshUses = meshUses;
  949. };
  950. /**
  951. * Requests the specified dependency asynchronously, with caching.
  952. * @param {string} type
  953. * @param {number} index
  954. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  955. */
  956. GLTFParser.prototype.getDependency = function ( type, index ) {
  957. var cacheKey = type + ':' + index;
  958. var dependency = this.cache.get( cacheKey );
  959. if ( ! dependency ) {
  960. switch ( type ) {
  961. case 'scene':
  962. dependency = this.loadScene( index );
  963. break;
  964. case 'node':
  965. dependency = this.loadNode( index );
  966. break;
  967. case 'mesh':
  968. dependency = this.loadMesh( index );
  969. break;
  970. case 'accessor':
  971. dependency = this.loadAccessor( index );
  972. break;
  973. case 'bufferView':
  974. dependency = this.loadBufferView( index );
  975. break;
  976. case 'buffer':
  977. dependency = this.loadBuffer( index );
  978. break;
  979. case 'material':
  980. dependency = this.loadMaterial( index );
  981. break;
  982. case 'texture':
  983. dependency = this.loadTexture( index );
  984. break;
  985. case 'skin':
  986. dependency = this.loadSkin( index );
  987. break;
  988. case 'animation':
  989. dependency = this.loadAnimation( index );
  990. break;
  991. case 'camera':
  992. dependency = this.loadCamera( index );
  993. break;
  994. case 'light':
  995. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  996. break;
  997. default:
  998. throw new Error( 'Unknown type: ' + type );
  999. }
  1000. this.cache.add( cacheKey, dependency );
  1001. }
  1002. return dependency;
  1003. };
  1004. /**
  1005. * Requests all dependencies of the specified type asynchronously, with caching.
  1006. * @param {string} type
  1007. * @return {Promise<Array<Object>>}
  1008. */
  1009. GLTFParser.prototype.getDependencies = function ( type ) {
  1010. var dependencies = this.cache.get( type );
  1011. if ( ! dependencies ) {
  1012. var parser = this;
  1013. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1014. dependencies = Promise.all( defs.map( function ( def, index ) {
  1015. return parser.getDependency( type, index );
  1016. } ) );
  1017. this.cache.add( type, dependencies );
  1018. }
  1019. return dependencies;
  1020. };
  1021. /**
  1022. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1023. * @param {number} bufferIndex
  1024. * @return {Promise<ArrayBuffer>}
  1025. */
  1026. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1027. var bufferDef = this.json.buffers[ bufferIndex ];
  1028. var loader = this.fileLoader;
  1029. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1030. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1031. }
  1032. // If present, GLB container is required to be the first buffer.
  1033. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1034. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1035. }
  1036. var options = this.options;
  1037. return new Promise( function ( resolve, reject ) {
  1038. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1039. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1040. } );
  1041. } );
  1042. };
  1043. /**
  1044. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1045. * @param {number} bufferViewIndex
  1046. * @return {Promise<ArrayBuffer>}
  1047. */
  1048. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1049. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1050. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1051. var byteLength = bufferViewDef.byteLength || 0;
  1052. var byteOffset = bufferViewDef.byteOffset || 0;
  1053. return buffer.slice( byteOffset, byteOffset + byteLength );
  1054. } );
  1055. };
  1056. /**
  1057. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1058. * @param {number} accessorIndex
  1059. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1060. */
  1061. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1062. var parser = this;
  1063. var json = this.json;
  1064. var accessorDef = this.json.accessors[ accessorIndex ];
  1065. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1066. // Ignore empty accessors, which may be used to declare runtime
  1067. // information about attributes coming from another source (e.g. Draco
  1068. // compression extension).
  1069. return Promise.resolve( null );
  1070. }
  1071. var pendingBufferViews = [];
  1072. if ( accessorDef.bufferView !== undefined ) {
  1073. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1074. } else {
  1075. pendingBufferViews.push( null );
  1076. }
  1077. if ( accessorDef.sparse !== undefined ) {
  1078. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1079. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1080. }
  1081. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1082. var bufferView = bufferViews[ 0 ];
  1083. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1084. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1085. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1086. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1087. var itemBytes = elementBytes * itemSize;
  1088. var byteOffset = accessorDef.byteOffset || 0;
  1089. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1090. var normalized = accessorDef.normalized === true;
  1091. var array, bufferAttribute;
  1092. // The buffer is not interleaved if the stride is the item size in bytes.
  1093. if ( byteStride && byteStride !== itemBytes ) {
  1094. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  1095. // This makes sure that IBA.count reflects accessor.count properly
  1096. var ibSlice = Math.floor( byteOffset / byteStride );
  1097. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  1098. var ib = parser.cache.get( ibCacheKey );
  1099. if ( ! ib ) {
  1100. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  1101. // Integer parameters to IB/IBA are in array elements, not bytes.
  1102. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1103. parser.cache.add( ibCacheKey, ib );
  1104. }
  1105. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  1106. } else {
  1107. if ( bufferView === null ) {
  1108. array = new TypedArray( accessorDef.count * itemSize );
  1109. } else {
  1110. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1111. }
  1112. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1113. }
  1114. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1115. if ( accessorDef.sparse !== undefined ) {
  1116. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1117. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1118. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1119. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1120. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1121. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1122. if ( bufferView !== null ) {
  1123. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1124. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  1125. }
  1126. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1127. var index = sparseIndices[ i ];
  1128. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1129. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1130. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1131. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1132. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1133. }
  1134. }
  1135. return bufferAttribute;
  1136. } );
  1137. };
  1138. /**
  1139. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1140. * @param {number} textureIndex
  1141. * @return {Promise<THREE.Texture>}
  1142. */
  1143. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1144. var parser = this;
  1145. var json = this.json;
  1146. var options = this.options;
  1147. var textureLoader = this.textureLoader;
  1148. var URL = window.URL || window.webkitURL;
  1149. var textureDef = json.textures[ textureIndex ];
  1150. var textureExtensions = textureDef.extensions || {};
  1151. var source;
  1152. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1153. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1154. } else {
  1155. source = json.images[ textureDef.source ];
  1156. }
  1157. var sourceURI = source.uri;
  1158. var isObjectURL = false;
  1159. var hasAlpha = true;
  1160. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  1161. if ( source.bufferView !== undefined ) {
  1162. // Load binary image data from bufferView, if provided.
  1163. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1164. if ( source.mimeType === 'image/png' ) {
  1165. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  1166. hasAlpha = new DataView( bufferView, 25, 1 ).getUint8( 0, false ) === 6;
  1167. }
  1168. isObjectURL = true;
  1169. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1170. sourceURI = URL.createObjectURL( blob );
  1171. return sourceURI;
  1172. } );
  1173. }
  1174. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1175. // Load Texture resource.
  1176. var loader = options.manager.getHandler( sourceURI );
  1177. if ( ! loader ) {
  1178. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1179. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1180. : textureLoader;
  1181. }
  1182. return new Promise( function ( resolve, reject ) {
  1183. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1184. } );
  1185. } ).then( function ( texture ) {
  1186. // Clean up resources and configure Texture.
  1187. if ( isObjectURL === true ) {
  1188. URL.revokeObjectURL( sourceURI );
  1189. }
  1190. texture.flipY = false;
  1191. if ( textureDef.name ) texture.name = textureDef.name;
  1192. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  1193. if ( ! hasAlpha ) texture.format = THREE.RGBFormat;
  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. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  1214. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  1215. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  1216. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  1217. }
  1218. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1219. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1220. if ( transform ) {
  1221. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1222. }
  1223. }
  1224. materialParams[ mapName ] = texture;
  1225. } );
  1226. };
  1227. /**
  1228. * Assigns final material to a Mesh, Line, or Points instance. The instance
  1229. * already has a material (generated from the glTF material options alone)
  1230. * but reuse of the same glTF material may require multiple threejs materials
  1231. * to accomodate different primitive types, defines, etc. New materials will
  1232. * be created if necessary, and reused from a cache.
  1233. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  1234. */
  1235. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  1236. var geometry = mesh.geometry;
  1237. var material = mesh.material;
  1238. var useVertexTangents = geometry.attributes.tangent !== undefined;
  1239. var useVertexColors = geometry.attributes.color !== undefined;
  1240. var useFlatShading = geometry.attributes.normal === undefined;
  1241. var useSkinning = mesh.isSkinnedMesh === true;
  1242. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1243. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1244. if ( mesh.isPoints ) {
  1245. var cacheKey = 'PointsMaterial:' + material.uuid;
  1246. var pointsMaterial = this.cache.get( cacheKey );
  1247. if ( ! pointsMaterial ) {
  1248. pointsMaterial = new THREE.PointsMaterial();
  1249. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1250. pointsMaterial.color.copy( material.color );
  1251. pointsMaterial.map = material.map;
  1252. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  1253. this.cache.add( cacheKey, pointsMaterial );
  1254. }
  1255. material = pointsMaterial;
  1256. } else if ( mesh.isLine ) {
  1257. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1258. var lineMaterial = this.cache.get( cacheKey );
  1259. if ( ! lineMaterial ) {
  1260. lineMaterial = new THREE.LineBasicMaterial();
  1261. THREE.Material.prototype.copy.call( lineMaterial, material );
  1262. lineMaterial.color.copy( material.color );
  1263. this.cache.add( cacheKey, lineMaterial );
  1264. }
  1265. material = lineMaterial;
  1266. }
  1267. // Clone the material if it will be modified
  1268. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1269. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1270. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1271. if ( useSkinning ) cacheKey += 'skinning:';
  1272. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  1273. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1274. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1275. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1276. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1277. var cachedMaterial = this.cache.get( cacheKey );
  1278. if ( ! cachedMaterial ) {
  1279. cachedMaterial = material.clone();
  1280. if ( useSkinning ) cachedMaterial.skinning = true;
  1281. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  1282. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  1283. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1284. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1285. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1286. this.cache.add( cacheKey, cachedMaterial );
  1287. }
  1288. material = cachedMaterial;
  1289. }
  1290. // workarounds for mesh and geometry
  1291. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1292. geometry.setAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1293. }
  1294. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1295. if ( material.normalScale && ! useVertexTangents ) {
  1296. material.normalScale.y = - material.normalScale.y;
  1297. }
  1298. mesh.material = material;
  1299. };
  1300. /**
  1301. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1302. * @param {number} materialIndex
  1303. * @return {Promise<THREE.Material>}
  1304. */
  1305. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1306. var parser = this;
  1307. var json = this.json;
  1308. var extensions = this.extensions;
  1309. var materialDef = json.materials[ materialIndex ];
  1310. var materialType;
  1311. var materialParams = {};
  1312. var materialExtensions = materialDef.extensions || {};
  1313. var pending = [];
  1314. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1315. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1316. materialType = sgExtension.getMaterialType();
  1317. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1318. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1319. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1320. materialType = kmuExtension.getMaterialType();
  1321. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1322. } else {
  1323. // Specification:
  1324. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1325. materialType = THREE.MeshStandardMaterial;
  1326. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1327. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1328. materialParams.opacity = 1.0;
  1329. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1330. var array = metallicRoughness.baseColorFactor;
  1331. materialParams.color.fromArray( array );
  1332. materialParams.opacity = array[ 3 ];
  1333. }
  1334. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1335. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1336. }
  1337. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1338. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1339. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1340. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1341. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1342. }
  1343. }
  1344. if ( materialDef.doubleSided === true ) {
  1345. materialParams.side = THREE.DoubleSide;
  1346. }
  1347. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1348. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1349. materialParams.transparent = true;
  1350. // See: https://github.com/mrdoob/three.js/issues/17706
  1351. materialParams.depthWrite = false;
  1352. } else {
  1353. materialParams.transparent = false;
  1354. if ( alphaMode === ALPHA_MODES.MASK ) {
  1355. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1356. }
  1357. }
  1358. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1359. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1360. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1361. if ( materialDef.normalTexture.scale !== undefined ) {
  1362. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1363. }
  1364. }
  1365. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1366. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1367. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1368. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1369. }
  1370. }
  1371. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1372. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1373. }
  1374. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1375. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1376. }
  1377. return Promise.all( pending ).then( function () {
  1378. var material;
  1379. if ( materialType === GLTFMeshStandardSGMaterial ) {
  1380. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1381. } else {
  1382. material = new materialType( materialParams );
  1383. }
  1384. if ( materialDef.name ) material.name = materialDef.name;
  1385. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1386. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1387. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1388. assignExtrasToUserData( material, materialDef );
  1389. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1390. return material;
  1391. } );
  1392. };
  1393. /**
  1394. * @param {THREE.BufferGeometry} geometry
  1395. * @param {GLTF.Primitive} primitiveDef
  1396. * @param {GLTFParser} parser
  1397. */
  1398. function computeBounds( geometry, primitiveDef, parser ) {
  1399. var attributes = primitiveDef.attributes;
  1400. var box = new THREE.Box3();
  1401. if ( attributes.POSITION !== undefined ) {
  1402. var accessor = parser.json.accessors[ attributes.POSITION ];
  1403. var min = accessor.min;
  1404. var max = accessor.max;
  1405. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1406. if ( min !== undefined && max !== undefined ) {
  1407. box.set(
  1408. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  1409. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  1410. } else {
  1411. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1412. return;
  1413. }
  1414. } else {
  1415. return;
  1416. }
  1417. var targets = primitiveDef.targets;
  1418. if ( targets !== undefined ) {
  1419. var vector = new THREE.Vector3();
  1420. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1421. var target = targets[ i ];
  1422. if ( target.POSITION !== undefined ) {
  1423. var accessor = parser.json.accessors[ target.POSITION ];
  1424. var min = accessor.min;
  1425. var max = accessor.max;
  1426. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1427. if ( min !== undefined && max !== undefined ) {
  1428. // we need to get max of absolute components because target weight is [-1,1]
  1429. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  1430. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  1431. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  1432. box.expandByVector( vector );
  1433. } else {
  1434. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1435. }
  1436. }
  1437. }
  1438. }
  1439. geometry.boundingBox = box;
  1440. var sphere = new THREE.Sphere();
  1441. box.getCenter( sphere.center );
  1442. sphere.radius = box.min.distanceTo( box.max ) / 2;
  1443. geometry.boundingSphere = sphere;
  1444. }
  1445. /**
  1446. * @param {THREE.BufferGeometry} geometry
  1447. * @param {GLTF.Primitive} primitiveDef
  1448. * @param {GLTFParser} parser
  1449. * @return {Promise<THREE.BufferGeometry>}
  1450. */
  1451. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1452. var attributes = primitiveDef.attributes;
  1453. var pending = [];
  1454. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1455. return parser.getDependency( 'accessor', accessorIndex )
  1456. .then( function ( accessor ) {
  1457. geometry.setAttribute( attributeName, accessor );
  1458. } );
  1459. }
  1460. for ( var gltfAttributeName in attributes ) {
  1461. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1462. // Skip attributes already provided by e.g. Draco extension.
  1463. if ( threeAttributeName in geometry.attributes ) continue;
  1464. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1465. }
  1466. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1467. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1468. geometry.setIndex( accessor );
  1469. } );
  1470. pending.push( accessor );
  1471. }
  1472. assignExtrasToUserData( geometry, primitiveDef );
  1473. computeBounds( geometry, primitiveDef, parser );
  1474. return Promise.all( pending ).then( function () {
  1475. return primitiveDef.targets !== undefined
  1476. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1477. : geometry;
  1478. } );
  1479. }
  1480. /**
  1481. * @param {THREE.BufferGeometry} geometry
  1482. * @param {Number} drawMode
  1483. * @return {THREE.BufferGeometry}
  1484. */
  1485. function toTrianglesDrawMode( geometry, drawMode ) {
  1486. var index = geometry.getIndex();
  1487. // generate index if not present
  1488. if ( index === null ) {
  1489. var indices = [];
  1490. var position = geometry.getAttribute( 'position' );
  1491. if ( position !== undefined ) {
  1492. for ( var i = 0; i < position.count; i ++ ) {
  1493. indices.push( i );
  1494. }
  1495. geometry.setIndex( indices );
  1496. index = geometry.getIndex();
  1497. } else {
  1498. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  1499. return geometry;
  1500. }
  1501. }
  1502. //
  1503. var numberOfTriangles = index.count - 2;
  1504. var newIndices = [];
  1505. if ( drawMode === THREE.TriangleFanDrawMode ) {
  1506. // gl.TRIANGLE_FAN
  1507. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  1508. newIndices.push( index.getX( 0 ) );
  1509. newIndices.push( index.getX( i ) );
  1510. newIndices.push( index.getX( i + 1 ) );
  1511. }
  1512. } else {
  1513. // gl.TRIANGLE_STRIP
  1514. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  1515. if ( i % 2 === 0 ) {
  1516. newIndices.push( index.getX( i ) );
  1517. newIndices.push( index.getX( i + 1 ) );
  1518. newIndices.push( index.getX( i + 2 ) );
  1519. } else {
  1520. newIndices.push( index.getX( i + 2 ) );
  1521. newIndices.push( index.getX( i + 1 ) );
  1522. newIndices.push( index.getX( i ) );
  1523. }
  1524. }
  1525. }
  1526. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  1527. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  1528. }
  1529. // build final geometry
  1530. var newGeometry = geometry.clone();
  1531. newGeometry.setIndex( newIndices );
  1532. return newGeometry;
  1533. }
  1534. /**
  1535. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1536. *
  1537. * Creates BufferGeometries from primitives.
  1538. *
  1539. * @param {Array<GLTF.Primitive>} primitives
  1540. * @return {Promise<Array<THREE.BufferGeometry>>}
  1541. */
  1542. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1543. var parser = this;
  1544. var extensions = this.extensions;
  1545. var cache = this.primitiveCache;
  1546. function createDracoPrimitive( primitive ) {
  1547. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1548. .decodePrimitive( primitive, parser )
  1549. .then( function ( geometry ) {
  1550. return addPrimitiveAttributes( geometry, primitive, parser );
  1551. } );
  1552. }
  1553. var pending = [];
  1554. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1555. var primitive = primitives[ i ];
  1556. var cacheKey = createPrimitiveKey( primitive );
  1557. // See if we've already created this geometry
  1558. var cached = cache[ cacheKey ];
  1559. if ( cached ) {
  1560. // Use the cached geometry if it exists
  1561. pending.push( cached.promise );
  1562. } else {
  1563. var geometryPromise;
  1564. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1565. // Use DRACO geometry if available
  1566. geometryPromise = createDracoPrimitive( primitive );
  1567. } else {
  1568. // Otherwise create a new geometry
  1569. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1570. }
  1571. // Cache this geometry
  1572. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1573. pending.push( geometryPromise );
  1574. }
  1575. }
  1576. return Promise.all( pending );
  1577. };
  1578. /**
  1579. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1580. * @param {number} meshIndex
  1581. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1582. */
  1583. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1584. var parser = this;
  1585. var json = this.json;
  1586. var meshDef = json.meshes[ meshIndex ];
  1587. var primitives = meshDef.primitives;
  1588. var pending = [];
  1589. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1590. var material = primitives[ i ].material === undefined
  1591. ? createDefaultMaterial( this.cache )
  1592. : this.getDependency( 'material', primitives[ i ].material );
  1593. pending.push( material );
  1594. }
  1595. pending.push( parser.loadGeometries( primitives ) );
  1596. return Promise.all( pending ).then( function ( results ) {
  1597. var materials = results.slice( 0, results.length - 1 );
  1598. var geometries = results[ results.length - 1 ];
  1599. var meshes = [];
  1600. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1601. var geometry = geometries[ i ];
  1602. var primitive = primitives[ i ];
  1603. // 1. create Mesh
  1604. var mesh;
  1605. var material = materials[ i ];
  1606. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1607. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1608. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1609. primitive.mode === undefined ) {
  1610. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  1611. mesh = meshDef.isSkinnedMesh === true
  1612. ? new THREE.SkinnedMesh( geometry, material )
  1613. : new THREE.Mesh( geometry, material );
  1614. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  1615. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  1616. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  1617. mesh.normalizeSkinWeights();
  1618. }
  1619. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1620. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  1621. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1622. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  1623. }
  1624. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1625. mesh = new THREE.LineSegments( geometry, material );
  1626. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1627. mesh = new THREE.Line( geometry, material );
  1628. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1629. mesh = new THREE.LineLoop( geometry, material );
  1630. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1631. mesh = new THREE.Points( geometry, material );
  1632. } else {
  1633. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1634. }
  1635. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1636. updateMorphTargets( mesh, meshDef );
  1637. }
  1638. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1639. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1640. assignExtrasToUserData( mesh, meshDef );
  1641. parser.assignFinalMaterial( mesh );
  1642. meshes.push( mesh );
  1643. }
  1644. if ( meshes.length === 1 ) {
  1645. return meshes[ 0 ];
  1646. }
  1647. var group = new THREE.Group();
  1648. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1649. group.add( meshes[ i ] );
  1650. }
  1651. return group;
  1652. } );
  1653. };
  1654. /**
  1655. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1656. * @param {number} cameraIndex
  1657. * @return {Promise<THREE.Camera>}
  1658. */
  1659. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1660. var camera;
  1661. var cameraDef = this.json.cameras[ cameraIndex ];
  1662. var params = cameraDef[ cameraDef.type ];
  1663. if ( ! params ) {
  1664. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1665. return;
  1666. }
  1667. if ( cameraDef.type === 'perspective' ) {
  1668. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1669. } else if ( cameraDef.type === 'orthographic' ) {
  1670. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1671. }
  1672. if ( cameraDef.name ) camera.name = cameraDef.name;
  1673. assignExtrasToUserData( camera, cameraDef );
  1674. return Promise.resolve( camera );
  1675. };
  1676. /**
  1677. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1678. * @param {number} skinIndex
  1679. * @return {Promise<Object>}
  1680. */
  1681. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1682. var skinDef = this.json.skins[ skinIndex ];
  1683. var skinEntry = { joints: skinDef.joints };
  1684. if ( skinDef.inverseBindMatrices === undefined ) {
  1685. return Promise.resolve( skinEntry );
  1686. }
  1687. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1688. skinEntry.inverseBindMatrices = accessor;
  1689. return skinEntry;
  1690. } );
  1691. };
  1692. /**
  1693. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1694. * @param {number} animationIndex
  1695. * @return {Promise<THREE.AnimationClip>}
  1696. */
  1697. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1698. var json = this.json;
  1699. var animationDef = json.animations[ animationIndex ];
  1700. var pendingNodes = [];
  1701. var pendingInputAccessors = [];
  1702. var pendingOutputAccessors = [];
  1703. var pendingSamplers = [];
  1704. var pendingTargets = [];
  1705. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1706. var channel = animationDef.channels[ i ];
  1707. var sampler = animationDef.samplers[ channel.sampler ];
  1708. var target = channel.target;
  1709. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1710. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1711. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1712. pendingNodes.push( this.getDependency( 'node', name ) );
  1713. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  1714. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  1715. pendingSamplers.push( sampler );
  1716. pendingTargets.push( target );
  1717. }
  1718. return Promise.all( [
  1719. Promise.all( pendingNodes ),
  1720. Promise.all( pendingInputAccessors ),
  1721. Promise.all( pendingOutputAccessors ),
  1722. Promise.all( pendingSamplers ),
  1723. Promise.all( pendingTargets )
  1724. ] ).then( function ( dependencies ) {
  1725. var nodes = dependencies[ 0 ];
  1726. var inputAccessors = dependencies[ 1 ];
  1727. var outputAccessors = dependencies[ 2 ];
  1728. var samplers = dependencies[ 3 ];
  1729. var targets = dependencies[ 4 ];
  1730. var tracks = [];
  1731. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  1732. var node = nodes[ i ];
  1733. var inputAccessor = inputAccessors[ i ];
  1734. var outputAccessor = outputAccessors[ i ];
  1735. var sampler = samplers[ i ];
  1736. var target = targets[ i ];
  1737. if ( node === undefined ) continue;
  1738. node.updateMatrix();
  1739. node.matrixAutoUpdate = true;
  1740. var TypedKeyframeTrack;
  1741. switch ( PATH_PROPERTIES[ target.path ] ) {
  1742. case PATH_PROPERTIES.weights:
  1743. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1744. break;
  1745. case PATH_PROPERTIES.rotation:
  1746. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1747. break;
  1748. case PATH_PROPERTIES.position:
  1749. case PATH_PROPERTIES.scale:
  1750. default:
  1751. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1752. break;
  1753. }
  1754. var targetName = node.name ? node.name : node.uuid;
  1755. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1756. var targetNames = [];
  1757. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1758. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  1759. node.traverse( function ( object ) {
  1760. if ( object.isMesh === true && object.morphTargetInfluences ) {
  1761. targetNames.push( object.name ? object.name : object.uuid );
  1762. }
  1763. } );
  1764. } else {
  1765. targetNames.push( targetName );
  1766. }
  1767. var outputArray = outputAccessor.array;
  1768. if ( outputAccessor.normalized ) {
  1769. var scale;
  1770. if ( outputArray.constructor === Int8Array ) {
  1771. scale = 1 / 127;
  1772. } else if ( outputArray.constructor === Uint8Array ) {
  1773. scale = 1 / 255;
  1774. } else if ( outputArray.constructor == Int16Array ) {
  1775. scale = 1 / 32767;
  1776. } else if ( outputArray.constructor === Uint16Array ) {
  1777. scale = 1 / 65535;
  1778. } else {
  1779. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  1780. }
  1781. var scaled = new Float32Array( outputArray.length );
  1782. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  1783. scaled[ j ] = outputArray[ j ] * scale;
  1784. }
  1785. outputArray = scaled;
  1786. }
  1787. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1788. var track = new TypedKeyframeTrack(
  1789. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1790. inputAccessor.array,
  1791. outputArray,
  1792. interpolation
  1793. );
  1794. // Override interpolation with custom factory method.
  1795. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1796. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  1797. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1798. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1799. // must be divided by three to get the interpolant's sampleSize argument.
  1800. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1801. };
  1802. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  1803. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  1804. }
  1805. tracks.push( track );
  1806. }
  1807. }
  1808. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  1809. return new THREE.AnimationClip( name, undefined, tracks );
  1810. } );
  1811. };
  1812. /**
  1813. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1814. * @param {number} nodeIndex
  1815. * @return {Promise<THREE.Object3D>}
  1816. */
  1817. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1818. var json = this.json;
  1819. var extensions = this.extensions;
  1820. var parser = this;
  1821. var meshReferences = json.meshReferences;
  1822. var meshUses = json.meshUses;
  1823. var nodeDef = json.nodes[ nodeIndex ];
  1824. return ( function () {
  1825. var pending = [];
  1826. if ( nodeDef.mesh !== undefined ) {
  1827. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  1828. var node;
  1829. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1830. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  1831. node = mesh.clone();
  1832. node.name += '_instance_' + instanceNum;
  1833. } else {
  1834. node = mesh;
  1835. }
  1836. // if weights are provided on the node, override weights on the mesh.
  1837. if ( nodeDef.weights !== undefined ) {
  1838. node.traverse( function ( o ) {
  1839. if ( ! o.isMesh ) return;
  1840. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  1841. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  1842. }
  1843. } );
  1844. }
  1845. return node;
  1846. } ) );
  1847. }
  1848. if ( nodeDef.camera !== undefined ) {
  1849. pending.push( parser.getDependency( 'camera', nodeDef.camera ) );
  1850. }
  1851. if ( nodeDef.extensions
  1852. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  1853. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  1854. pending.push( parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ) );
  1855. }
  1856. return Promise.all( pending );
  1857. }() ).then( function ( objects ) {
  1858. var node;
  1859. // .isBone isn't in glTF spec. See .markDefs
  1860. if ( nodeDef.isBone === true ) {
  1861. node = new THREE.Bone();
  1862. } else if ( objects.length > 1 ) {
  1863. node = new THREE.Group();
  1864. } else if ( objects.length === 1 ) {
  1865. node = objects[ 0 ];
  1866. } else {
  1867. node = new THREE.Object3D();
  1868. }
  1869. if ( node !== objects[ 0 ] ) {
  1870. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  1871. node.add( objects[ i ] );
  1872. }
  1873. }
  1874. if ( nodeDef.name ) {
  1875. node.userData.name = nodeDef.name;
  1876. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1877. }
  1878. assignExtrasToUserData( node, nodeDef );
  1879. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  1880. if ( nodeDef.matrix !== undefined ) {
  1881. var matrix = new THREE.Matrix4();
  1882. matrix.fromArray( nodeDef.matrix );
  1883. node.applyMatrix4( matrix );
  1884. } else {
  1885. if ( nodeDef.translation !== undefined ) {
  1886. node.position.fromArray( nodeDef.translation );
  1887. }
  1888. if ( nodeDef.rotation !== undefined ) {
  1889. node.quaternion.fromArray( nodeDef.rotation );
  1890. }
  1891. if ( nodeDef.scale !== undefined ) {
  1892. node.scale.fromArray( nodeDef.scale );
  1893. }
  1894. }
  1895. return node;
  1896. } );
  1897. };
  1898. /**
  1899. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  1900. * @param {number} sceneIndex
  1901. * @return {Promise<THREE.Group>}
  1902. */
  1903. GLTFParser.prototype.loadScene = function () {
  1904. // scene node hierachy builder
  1905. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  1906. var nodeDef = json.nodes[ nodeId ];
  1907. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  1908. if ( nodeDef.skin === undefined ) return node;
  1909. // build skeleton here as well
  1910. var skinEntry;
  1911. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  1912. skinEntry = skin;
  1913. var pendingJoints = [];
  1914. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  1915. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  1916. }
  1917. return Promise.all( pendingJoints );
  1918. } ).then( function ( jointNodes ) {
  1919. node.traverse( function ( mesh ) {
  1920. if ( ! mesh.isMesh ) return;
  1921. var bones = [];
  1922. var boneInverses = [];
  1923. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  1924. var jointNode = jointNodes[ j ];
  1925. if ( jointNode ) {
  1926. bones.push( jointNode );
  1927. var mat = new THREE.Matrix4();
  1928. if ( skinEntry.inverseBindMatrices !== undefined ) {
  1929. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  1930. }
  1931. boneInverses.push( mat );
  1932. } else {
  1933. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  1934. }
  1935. }
  1936. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  1937. } );
  1938. return node;
  1939. } );
  1940. } ).then( function ( node ) {
  1941. // build node hierachy
  1942. parentObject.add( node );
  1943. var pending = [];
  1944. if ( nodeDef.children ) {
  1945. var children = nodeDef.children;
  1946. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1947. var child = children[ i ];
  1948. pending.push( buildNodeHierachy( child, node, json, parser ) );
  1949. }
  1950. }
  1951. return Promise.all( pending );
  1952. } );
  1953. }
  1954. return function loadScene( sceneIndex ) {
  1955. var json = this.json;
  1956. var extensions = this.extensions;
  1957. var sceneDef = this.json.scenes[ sceneIndex ];
  1958. var parser = this;
  1959. // Loader returns Group, not Scene.
  1960. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  1961. var scene = new THREE.Group();
  1962. if ( sceneDef.name ) scene.name = sceneDef.name;
  1963. assignExtrasToUserData( scene, sceneDef );
  1964. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  1965. var nodeIds = sceneDef.nodes || [];
  1966. var pending = [];
  1967. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  1968. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  1969. }
  1970. return Promise.all( pending ).then( function () {
  1971. return scene;
  1972. } );
  1973. };
  1974. }();
  1975. return GLTFLoader;
  1976. } )();