GLTFLoader.js 77 KB

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