GLTFLoader.js 79 KB

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