GLTFLoader.js 86 KB

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