2
0

GLTFLoader.js 81 KB

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