GLTFLoader.js 82 KB

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