GLTFLoader.js 90 KB

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