GLTFLoader.js 79 KB

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