GLTFLoader.js 93 KB

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