GLTFLoader.js 81 KB

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