GLTFLoader.js 85 KB

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