GLTFLoader.js 83 KB

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