GLTFLoader.js 79 KB

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