GLTFLoader.js 82 KB

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