GLTFLoader.js 80 KB

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