GLTFLoader.js 80 KB

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