GLTFLoader.js 101 KB

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