GLTFLoader.js 80 KB

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