GLTFLoader.js 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679
  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. scope.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( scope.manager );
  48. loader.setPath( this.path );
  49. loader.setResponseType( 'arraybuffer' );
  50. loader.setRequestHeader( this.requestHeader );
  51. if ( scope.crossOrigin === 'use-credentials' ) {
  52. loader.setWithCredentials( true );
  53. }
  54. loader.load( url, function ( data ) {
  55. try {
  56. scope.parse( data, resourcePath, function ( gltf ) {
  57. onLoad( gltf );
  58. scope.manager.itemEnd( url );
  59. }, _onError );
  60. } catch ( e ) {
  61. _onError( e );
  62. }
  63. }, onProgress, _onError );
  64. },
  65. setDRACOLoader: function ( dracoLoader ) {
  66. this.dracoLoader = dracoLoader;
  67. return this;
  68. },
  69. setDDSLoader: function ( ddsLoader ) {
  70. this.ddsLoader = ddsLoader;
  71. return this;
  72. },
  73. setKTX2Loader: function ( ktx2Loader ) {
  74. this.ktx2Loader = ktx2Loader;
  75. return this;
  76. },
  77. register: function ( callback ) {
  78. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  79. this.pluginCallbacks.push( callback );
  80. }
  81. return this;
  82. },
  83. unregister: function ( callback ) {
  84. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  85. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  86. }
  87. return this;
  88. },
  89. parse: function ( data, path, onLoad, onError ) {
  90. var content;
  91. var extensions = {};
  92. var plugins = {};
  93. if ( typeof data === 'string' ) {
  94. content = data;
  95. } else {
  96. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  97. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  98. try {
  99. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  100. } catch ( error ) {
  101. if ( onError ) onError( error );
  102. return;
  103. }
  104. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  105. } else {
  106. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  107. }
  108. }
  109. var json = JSON.parse( content );
  110. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  111. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  112. return;
  113. }
  114. var parser = new GLTFParser( json, {
  115. path: path || this.resourcePath || '',
  116. crossOrigin: this.crossOrigin,
  117. manager: this.manager,
  118. ktx2Loader: this.ktx2Loader
  119. } );
  120. parser.fileLoader.setRequestHeader( this.requestHeader );
  121. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  122. var plugin = this.pluginCallbacks[ i ]( parser );
  123. plugins[ plugin.name ] = plugin;
  124. // Workaround to avoid determining as unknown extension
  125. // in addUnknownExtensionsToUserData().
  126. // Remove this workaround if we move all the existing
  127. // extension handlers to plugin system
  128. extensions[ plugin.name ] = true;
  129. }
  130. if ( json.extensionsUsed ) {
  131. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  132. var extensionName = json.extensionsUsed[ i ];
  133. var extensionsRequired = json.extensionsRequired || [];
  134. switch ( extensionName ) {
  135. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  136. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  137. break;
  138. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  139. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  140. break;
  141. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  142. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  143. break;
  144. case EXTENSIONS.MSFT_TEXTURE_DDS:
  145. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  146. break;
  147. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  148. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  149. break;
  150. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  151. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  152. break;
  153. default:
  154. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  155. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  156. }
  157. }
  158. }
  159. }
  160. parser.setExtensions( extensions );
  161. parser.setPlugins( plugins );
  162. parser.parse( onLoad, onError );
  163. }
  164. } );
  165. /* GLTFREGISTRY */
  166. function GLTFRegistry() {
  167. var objects = {};
  168. return {
  169. get: function ( key ) {
  170. return objects[ key ];
  171. },
  172. add: function ( key, object ) {
  173. objects[ key ] = object;
  174. },
  175. remove: function ( key ) {
  176. delete objects[ key ];
  177. },
  178. removeAll: function () {
  179. objects = {};
  180. }
  181. };
  182. }
  183. /*********************************/
  184. /********** EXTENSIONS ***********/
  185. /*********************************/
  186. var EXTENSIONS = {
  187. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  188. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  189. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  190. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  191. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  192. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  193. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  194. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  195. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  196. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  197. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  198. };
  199. /**
  200. * DDS Texture Extension
  201. *
  202. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  203. *
  204. */
  205. function GLTFTextureDDSExtension( ddsLoader ) {
  206. if ( ! ddsLoader ) {
  207. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  208. }
  209. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  210. this.ddsLoader = ddsLoader;
  211. }
  212. /**
  213. * Punctual Lights Extension
  214. *
  215. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  216. */
  217. function GLTFLightsExtension( parser ) {
  218. this.parser = parser;
  219. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  220. // Object3D instance caches
  221. this.cache = { refs: {}, uses: {} };
  222. }
  223. GLTFLightsExtension.prototype._markDefs = function () {
  224. var parser = this.parser;
  225. var nodeDefs = this.parser.json.nodes || [];
  226. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  227. var nodeDef = nodeDefs[ nodeIndex ];
  228. if ( nodeDef.extensions
  229. && nodeDef.extensions[ this.name ]
  230. && nodeDef.extensions[ this.name ].light !== undefined ) {
  231. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  232. }
  233. }
  234. };
  235. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  236. var parser = this.parser;
  237. var cacheKey = 'light:' + lightIndex;
  238. var dependency = parser.cache.get( cacheKey );
  239. if ( dependency ) return dependency;
  240. var json = parser.json;
  241. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  242. var lightDefs = extensions.lights || [];
  243. var lightDef = lightDefs[ lightIndex ];
  244. var lightNode;
  245. var color = new THREE.Color( 0xffffff );
  246. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  247. var range = lightDef.range !== undefined ? lightDef.range : 0;
  248. switch ( lightDef.type ) {
  249. case 'directional':
  250. lightNode = new THREE.DirectionalLight( color );
  251. lightNode.target.position.set( 0, 0, - 1 );
  252. lightNode.add( lightNode.target );
  253. break;
  254. case 'point':
  255. lightNode = new THREE.PointLight( color );
  256. lightNode.distance = range;
  257. break;
  258. case 'spot':
  259. lightNode = new THREE.SpotLight( color );
  260. lightNode.distance = range;
  261. // Handle spotlight properties.
  262. lightDef.spot = lightDef.spot || {};
  263. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  264. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  265. lightNode.angle = lightDef.spot.outerConeAngle;
  266. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  267. lightNode.target.position.set( 0, 0, - 1 );
  268. lightNode.add( lightNode.target );
  269. break;
  270. default:
  271. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  272. }
  273. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  274. // here, because node-level parsing will only override position if explicitly specified.
  275. lightNode.position.set( 0, 0, 0 );
  276. lightNode.decay = 2;
  277. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  278. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  279. dependency = Promise.resolve( lightNode );
  280. parser.cache.add( cacheKey, dependency );
  281. return dependency;
  282. };
  283. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  284. var self = this;
  285. var parser = this.parser;
  286. var json = parser.json;
  287. var nodeDef = json.nodes[ nodeIndex ];
  288. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  289. var lightIndex = lightDef.light;
  290. if ( lightIndex === undefined ) return null;
  291. return this._loadLight( lightIndex ).then( function ( light ) {
  292. return parser._getNodeRef( self.cache, lightIndex, light );
  293. } );
  294. };
  295. /**
  296. * Unlit Materials Extension
  297. *
  298. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  299. */
  300. function GLTFMaterialsUnlitExtension() {
  301. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  302. }
  303. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  304. return THREE.MeshBasicMaterial;
  305. };
  306. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  307. var pending = [];
  308. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  309. materialParams.opacity = 1.0;
  310. var metallicRoughness = materialDef.pbrMetallicRoughness;
  311. if ( metallicRoughness ) {
  312. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  313. var array = metallicRoughness.baseColorFactor;
  314. materialParams.color.fromArray( array );
  315. materialParams.opacity = array[ 3 ];
  316. }
  317. if ( metallicRoughness.baseColorTexture !== undefined ) {
  318. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  319. }
  320. }
  321. return Promise.all( pending );
  322. };
  323. /**
  324. * Clearcoat Materials Extension
  325. *
  326. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  327. */
  328. function GLTFMaterialsClearcoatExtension( parser ) {
  329. this.parser = parser;
  330. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  331. }
  332. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  333. var parser = this.parser;
  334. var materialDef = parser.json.materials[ materialIndex ];
  335. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  336. return THREE.MeshPhysicalMaterial;
  337. };
  338. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  339. var parser = this.parser;
  340. var materialDef = parser.json.materials[ materialIndex ];
  341. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  342. return Promise.resolve();
  343. }
  344. var pending = [];
  345. var extension = materialDef.extensions[ this.name ];
  346. if ( extension.clearcoatFactor !== undefined ) {
  347. materialParams.clearcoat = extension.clearcoatFactor;
  348. }
  349. if ( extension.clearcoatTexture !== undefined ) {
  350. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  351. }
  352. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  353. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  354. }
  355. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  356. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  357. }
  358. if ( extension.clearcoatNormalTexture !== undefined ) {
  359. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  360. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  361. var scale = extension.clearcoatNormalTexture.scale;
  362. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
  363. }
  364. }
  365. return Promise.all( pending );
  366. };
  367. /**
  368. * Transmission Materials Extension
  369. *
  370. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  371. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  372. */
  373. function GLTFMaterialsTransmissionExtension( parser ) {
  374. this.parser = parser;
  375. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  376. }
  377. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  378. var parser = this.parser;
  379. var materialDef = parser.json.materials[ materialIndex ];
  380. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  381. return THREE.MeshPhysicalMaterial;
  382. };
  383. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  384. var parser = this.parser;
  385. var materialDef = parser.json.materials[ materialIndex ];
  386. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  387. return Promise.resolve();
  388. }
  389. var pending = [];
  390. var extension = materialDef.extensions[ this.name ];
  391. if ( extension.transmissionFactor !== undefined ) {
  392. materialParams.transmission = extension.transmissionFactor;
  393. }
  394. if ( extension.transmissionTexture !== undefined ) {
  395. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  396. }
  397. return Promise.all( pending );
  398. };
  399. /**
  400. * BasisU Texture Extension
  401. *
  402. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  403. * (draft PR https://github.com/KhronosGroup/glTF/pull/1751)
  404. */
  405. function GLTFTextureBasisUExtension( parser ) {
  406. this.parser = parser;
  407. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  408. }
  409. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  410. var parser = this.parser;
  411. var json = parser.json;
  412. var textureDef = json.textures[ textureIndex ];
  413. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  414. return null;
  415. }
  416. var extension = textureDef.extensions[ this.name ];
  417. var source = json.images[ extension.source ];
  418. var loader = parser.options.ktx2Loader;
  419. if ( ! loader ) {
  420. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  421. }
  422. return parser.loadTextureImage( textureIndex, source, loader );
  423. };
  424. /* BINARY EXTENSION */
  425. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  426. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  427. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  428. function GLTFBinaryExtension( data ) {
  429. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  430. this.content = null;
  431. this.body = null;
  432. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  433. this.header = {
  434. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  435. version: headerView.getUint32( 4, true ),
  436. length: headerView.getUint32( 8, true )
  437. };
  438. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  439. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  440. } else if ( this.header.version < 2.0 ) {
  441. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  442. }
  443. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  444. var chunkIndex = 0;
  445. while ( chunkIndex < chunkView.byteLength ) {
  446. var chunkLength = chunkView.getUint32( chunkIndex, true );
  447. chunkIndex += 4;
  448. var chunkType = chunkView.getUint32( chunkIndex, true );
  449. chunkIndex += 4;
  450. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  451. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  452. this.content = THREE.LoaderUtils.decodeText( contentArray );
  453. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  454. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  455. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  456. }
  457. // Clients must ignore chunks with unknown types.
  458. chunkIndex += chunkLength;
  459. }
  460. if ( this.content === null ) {
  461. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  462. }
  463. }
  464. /**
  465. * DRACO Mesh Compression Extension
  466. *
  467. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  468. */
  469. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  470. if ( ! dracoLoader ) {
  471. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  472. }
  473. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  474. this.json = json;
  475. this.dracoLoader = dracoLoader;
  476. this.dracoLoader.preload();
  477. }
  478. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  479. var json = this.json;
  480. var dracoLoader = this.dracoLoader;
  481. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  482. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  483. var threeAttributeMap = {};
  484. var attributeNormalizedMap = {};
  485. var attributeTypeMap = {};
  486. for ( var attributeName in gltfAttributeMap ) {
  487. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  488. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  489. }
  490. for ( attributeName in primitive.attributes ) {
  491. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  492. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  493. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  494. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  495. attributeTypeMap[ threeAttributeName ] = componentType;
  496. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  497. }
  498. }
  499. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  500. return new Promise( function ( resolve ) {
  501. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  502. for ( var attributeName in geometry.attributes ) {
  503. var attribute = geometry.attributes[ attributeName ];
  504. var normalized = attributeNormalizedMap[ attributeName ];
  505. if ( normalized !== undefined ) attribute.normalized = normalized;
  506. }
  507. resolve( geometry );
  508. }, threeAttributeMap, attributeTypeMap );
  509. } );
  510. } );
  511. };
  512. /**
  513. * Texture Transform Extension
  514. *
  515. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  516. */
  517. function GLTFTextureTransformExtension() {
  518. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  519. }
  520. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  521. texture = texture.clone();
  522. if ( transform.offset !== undefined ) {
  523. texture.offset.fromArray( transform.offset );
  524. }
  525. if ( transform.rotation !== undefined ) {
  526. texture.rotation = transform.rotation;
  527. }
  528. if ( transform.scale !== undefined ) {
  529. texture.repeat.fromArray( transform.scale );
  530. }
  531. if ( transform.texCoord !== undefined ) {
  532. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  533. }
  534. texture.needsUpdate = true;
  535. return texture;
  536. };
  537. /**
  538. * Specular-Glossiness Extension
  539. *
  540. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  541. */
  542. /**
  543. * A sub class of THREE.StandardMaterial with some of the functionality
  544. * changed via the `onBeforeCompile` callback
  545. * @pailhead
  546. */
  547. function GLTFMeshStandardSGMaterial( params ) {
  548. THREE.MeshStandardMaterial.call( this );
  549. this.isGLTFSpecularGlossinessMaterial = true;
  550. //various chunks that need replacing
  551. var specularMapParsFragmentChunk = [
  552. '#ifdef USE_SPECULARMAP',
  553. ' uniform sampler2D specularMap;',
  554. '#endif'
  555. ].join( '\n' );
  556. var glossinessMapParsFragmentChunk = [
  557. '#ifdef USE_GLOSSINESSMAP',
  558. ' uniform sampler2D glossinessMap;',
  559. '#endif'
  560. ].join( '\n' );
  561. var specularMapFragmentChunk = [
  562. 'vec3 specularFactor = specular;',
  563. '#ifdef USE_SPECULARMAP',
  564. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  565. ' texelSpecular = sRGBToLinear( texelSpecular );',
  566. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  567. ' specularFactor *= texelSpecular.rgb;',
  568. '#endif'
  569. ].join( '\n' );
  570. var glossinessMapFragmentChunk = [
  571. 'float glossinessFactor = glossiness;',
  572. '#ifdef USE_GLOSSINESSMAP',
  573. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  574. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  575. ' glossinessFactor *= texelGlossiness.a;',
  576. '#endif'
  577. ].join( '\n' );
  578. var lightPhysicalFragmentChunk = [
  579. 'PhysicalMaterial material;',
  580. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  581. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  582. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  583. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  584. 'material.specularRoughness += geometryRoughness;',
  585. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  586. 'material.specularColor = specularFactor;',
  587. ].join( '\n' );
  588. var uniforms = {
  589. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  590. glossiness: { value: 1 },
  591. specularMap: { value: null },
  592. glossinessMap: { value: null }
  593. };
  594. this._extraUniforms = uniforms;
  595. this.onBeforeCompile = function ( shader ) {
  596. for ( var uniformName in uniforms ) {
  597. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  598. }
  599. shader.fragmentShader = shader.fragmentShader
  600. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  601. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  602. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  603. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  604. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  605. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  606. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  607. };
  608. Object.defineProperties( this, {
  609. specular: {
  610. get: function () {
  611. return uniforms.specular.value;
  612. },
  613. set: function ( v ) {
  614. uniforms.specular.value = v;
  615. }
  616. },
  617. specularMap: {
  618. get: function () {
  619. return uniforms.specularMap.value;
  620. },
  621. set: function ( v ) {
  622. uniforms.specularMap.value = v;
  623. if ( v ) {
  624. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  625. } else {
  626. delete this.defines.USE_SPECULARMAP;
  627. }
  628. }
  629. },
  630. glossiness: {
  631. get: function () {
  632. return uniforms.glossiness.value;
  633. },
  634. set: function ( v ) {
  635. uniforms.glossiness.value = v;
  636. }
  637. },
  638. glossinessMap: {
  639. get: function () {
  640. return uniforms.glossinessMap.value;
  641. },
  642. set: function ( v ) {
  643. uniforms.glossinessMap.value = v;
  644. if ( v ) {
  645. this.defines.USE_GLOSSINESSMAP = '';
  646. this.defines.USE_UV = '';
  647. } else {
  648. delete this.defines.USE_GLOSSINESSMAP;
  649. delete this.defines.USE_UV;
  650. }
  651. }
  652. }
  653. } );
  654. delete this.metalness;
  655. delete this.roughness;
  656. delete this.metalnessMap;
  657. delete this.roughnessMap;
  658. this.setValues( params );
  659. }
  660. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  661. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  662. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  663. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  664. this.specularMap = source.specularMap;
  665. this.specular.copy( source.specular );
  666. this.glossinessMap = source.glossinessMap;
  667. this.glossiness = source.glossiness;
  668. delete this.metalness;
  669. delete this.roughness;
  670. delete this.metalnessMap;
  671. delete this.roughnessMap;
  672. return this;
  673. };
  674. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  675. return {
  676. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  677. specularGlossinessParams: [
  678. 'color',
  679. 'map',
  680. 'lightMap',
  681. 'lightMapIntensity',
  682. 'aoMap',
  683. 'aoMapIntensity',
  684. 'emissive',
  685. 'emissiveIntensity',
  686. 'emissiveMap',
  687. 'bumpMap',
  688. 'bumpScale',
  689. 'normalMap',
  690. 'normalMapType',
  691. 'displacementMap',
  692. 'displacementScale',
  693. 'displacementBias',
  694. 'specularMap',
  695. 'specular',
  696. 'glossinessMap',
  697. 'glossiness',
  698. 'alphaMap',
  699. 'envMap',
  700. 'envMapIntensity',
  701. 'refractionRatio',
  702. ],
  703. getMaterialType: function () {
  704. return GLTFMeshStandardSGMaterial;
  705. },
  706. extendParams: function ( materialParams, materialDef, parser ) {
  707. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  708. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  709. materialParams.opacity = 1.0;
  710. var pending = [];
  711. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  712. var array = pbrSpecularGlossiness.diffuseFactor;
  713. materialParams.color.fromArray( array );
  714. materialParams.opacity = array[ 3 ];
  715. }
  716. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  717. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  718. }
  719. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  720. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  721. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  722. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  723. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  724. }
  725. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  726. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  727. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  728. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  729. }
  730. return Promise.all( pending );
  731. },
  732. createMaterial: function ( materialParams ) {
  733. var material = new GLTFMeshStandardSGMaterial( materialParams );
  734. material.fog = true;
  735. material.color = materialParams.color;
  736. material.map = materialParams.map === undefined ? null : materialParams.map;
  737. material.lightMap = null;
  738. material.lightMapIntensity = 1.0;
  739. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  740. material.aoMapIntensity = 1.0;
  741. material.emissive = materialParams.emissive;
  742. material.emissiveIntensity = 1.0;
  743. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  744. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  745. material.bumpScale = 1;
  746. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  747. material.normalMapType = THREE.TangentSpaceNormalMap;
  748. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  749. material.displacementMap = null;
  750. material.displacementScale = 1;
  751. material.displacementBias = 0;
  752. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  753. material.specular = materialParams.specular;
  754. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  755. material.glossiness = materialParams.glossiness;
  756. material.alphaMap = null;
  757. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  758. material.envMapIntensity = 1.0;
  759. material.refractionRatio = 0.98;
  760. return material;
  761. },
  762. };
  763. }
  764. /**
  765. * Mesh Quantization Extension
  766. *
  767. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  768. */
  769. function GLTFMeshQuantizationExtension() {
  770. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  771. }
  772. /*********************************/
  773. /********** INTERPOLATION ********/
  774. /*********************************/
  775. // Spline Interpolation
  776. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  777. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  778. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  779. }
  780. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  781. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  782. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  783. // Copies a sample value to the result buffer. See description of glTF
  784. // CUBICSPLINE values layout in interpolate_() function below.
  785. var result = this.resultBuffer,
  786. values = this.sampleValues,
  787. valueSize = this.valueSize,
  788. offset = index * valueSize * 3 + valueSize;
  789. for ( var i = 0; i !== valueSize; i ++ ) {
  790. result[ i ] = values[ offset + i ];
  791. }
  792. return result;
  793. };
  794. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  795. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  796. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  797. var result = this.resultBuffer;
  798. var values = this.sampleValues;
  799. var stride = this.valueSize;
  800. var stride2 = stride * 2;
  801. var stride3 = stride * 3;
  802. var td = t1 - t0;
  803. var p = ( t - t0 ) / td;
  804. var pp = p * p;
  805. var ppp = pp * p;
  806. var offset1 = i1 * stride3;
  807. var offset0 = offset1 - stride3;
  808. var s2 = - 2 * ppp + 3 * pp;
  809. var s3 = ppp - pp;
  810. var s0 = 1 - s2;
  811. var s1 = s3 - pp + p;
  812. // Layout of keyframe output values for CUBICSPLINE animations:
  813. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  814. for ( var i = 0; i !== stride; i ++ ) {
  815. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  816. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  817. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  818. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  819. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  820. }
  821. return result;
  822. };
  823. /*********************************/
  824. /********** INTERNALS ************/
  825. /*********************************/
  826. /* CONSTANTS */
  827. var WEBGL_CONSTANTS = {
  828. FLOAT: 5126,
  829. //FLOAT_MAT2: 35674,
  830. FLOAT_MAT3: 35675,
  831. FLOAT_MAT4: 35676,
  832. FLOAT_VEC2: 35664,
  833. FLOAT_VEC3: 35665,
  834. FLOAT_VEC4: 35666,
  835. LINEAR: 9729,
  836. REPEAT: 10497,
  837. SAMPLER_2D: 35678,
  838. POINTS: 0,
  839. LINES: 1,
  840. LINE_LOOP: 2,
  841. LINE_STRIP: 3,
  842. TRIANGLES: 4,
  843. TRIANGLE_STRIP: 5,
  844. TRIANGLE_FAN: 6,
  845. UNSIGNED_BYTE: 5121,
  846. UNSIGNED_SHORT: 5123
  847. };
  848. var WEBGL_COMPONENT_TYPES = {
  849. 5120: Int8Array,
  850. 5121: Uint8Array,
  851. 5122: Int16Array,
  852. 5123: Uint16Array,
  853. 5125: Uint32Array,
  854. 5126: Float32Array
  855. };
  856. var WEBGL_FILTERS = {
  857. 9728: THREE.NearestFilter,
  858. 9729: THREE.LinearFilter,
  859. 9984: THREE.NearestMipmapNearestFilter,
  860. 9985: THREE.LinearMipmapNearestFilter,
  861. 9986: THREE.NearestMipmapLinearFilter,
  862. 9987: THREE.LinearMipmapLinearFilter
  863. };
  864. var WEBGL_WRAPPINGS = {
  865. 33071: THREE.ClampToEdgeWrapping,
  866. 33648: THREE.MirroredRepeatWrapping,
  867. 10497: THREE.RepeatWrapping
  868. };
  869. var WEBGL_TYPE_SIZES = {
  870. 'SCALAR': 1,
  871. 'VEC2': 2,
  872. 'VEC3': 3,
  873. 'VEC4': 4,
  874. 'MAT2': 4,
  875. 'MAT3': 9,
  876. 'MAT4': 16
  877. };
  878. var ATTRIBUTES = {
  879. POSITION: 'position',
  880. NORMAL: 'normal',
  881. TANGENT: 'tangent',
  882. TEXCOORD_0: 'uv',
  883. TEXCOORD_1: 'uv2',
  884. COLOR_0: 'color',
  885. WEIGHTS_0: 'skinWeight',
  886. JOINTS_0: 'skinIndex',
  887. };
  888. var PATH_PROPERTIES = {
  889. scale: 'scale',
  890. translation: 'position',
  891. rotation: 'quaternion',
  892. weights: 'morphTargetInfluences'
  893. };
  894. var INTERPOLATION = {
  895. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  896. // keyframe track will be initialized with a default interpolation type, then modified.
  897. LINEAR: THREE.InterpolateLinear,
  898. STEP: THREE.InterpolateDiscrete
  899. };
  900. var ALPHA_MODES = {
  901. OPAQUE: 'OPAQUE',
  902. MASK: 'MASK',
  903. BLEND: 'BLEND'
  904. };
  905. /* UTILITY FUNCTIONS */
  906. function resolveURL( url, path ) {
  907. // Invalid URL
  908. if ( typeof url !== 'string' || url === '' ) return '';
  909. // Host Relative URL
  910. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  911. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  912. }
  913. // Absolute URL http://,https://,//
  914. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  915. // Data URI
  916. if ( /^data:.*,.*$/i.test( url ) ) return url;
  917. // Blob URL
  918. if ( /^blob:.*$/i.test( url ) ) return url;
  919. // Relative URL
  920. return path + url;
  921. }
  922. /**
  923. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  924. */
  925. function createDefaultMaterial( cache ) {
  926. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  927. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  928. color: 0xFFFFFF,
  929. emissive: 0x000000,
  930. metalness: 1,
  931. roughness: 1,
  932. transparent: false,
  933. depthTest: true,
  934. side: THREE.FrontSide
  935. } );
  936. }
  937. return cache[ 'DefaultMaterial' ];
  938. }
  939. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  940. // Add unknown glTF extensions to an object's userData.
  941. for ( var name in objectDef.extensions ) {
  942. if ( knownExtensions[ name ] === undefined ) {
  943. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  944. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  945. }
  946. }
  947. }
  948. /**
  949. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  950. * @param {GLTF.definition} gltfDef
  951. */
  952. function assignExtrasToUserData( object, gltfDef ) {
  953. if ( gltfDef.extras !== undefined ) {
  954. if ( typeof gltfDef.extras === 'object' ) {
  955. Object.assign( object.userData, gltfDef.extras );
  956. } else {
  957. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  958. }
  959. }
  960. }
  961. /**
  962. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  963. *
  964. * @param {THREE.BufferGeometry} geometry
  965. * @param {Array<GLTF.Target>} targets
  966. * @param {GLTFParser} parser
  967. * @return {Promise<THREE.BufferGeometry>}
  968. */
  969. function addMorphTargets( geometry, targets, parser ) {
  970. var hasMorphPosition = false;
  971. var hasMorphNormal = false;
  972. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  973. var target = targets[ i ];
  974. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  975. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  976. if ( hasMorphPosition && hasMorphNormal ) break;
  977. }
  978. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  979. var pendingPositionAccessors = [];
  980. var pendingNormalAccessors = [];
  981. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  982. var target = targets[ i ];
  983. if ( hasMorphPosition ) {
  984. var pendingAccessor = target.POSITION !== undefined
  985. ? parser.getDependency( 'accessor', target.POSITION )
  986. : geometry.attributes.position;
  987. pendingPositionAccessors.push( pendingAccessor );
  988. }
  989. if ( hasMorphNormal ) {
  990. var pendingAccessor = target.NORMAL !== undefined
  991. ? parser.getDependency( 'accessor', target.NORMAL )
  992. : geometry.attributes.normal;
  993. pendingNormalAccessors.push( pendingAccessor );
  994. }
  995. }
  996. return Promise.all( [
  997. Promise.all( pendingPositionAccessors ),
  998. Promise.all( pendingNormalAccessors )
  999. ] ).then( function ( accessors ) {
  1000. var morphPositions = accessors[ 0 ];
  1001. var morphNormals = accessors[ 1 ];
  1002. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  1003. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  1004. geometry.morphTargetsRelative = true;
  1005. return geometry;
  1006. } );
  1007. }
  1008. /**
  1009. * @param {THREE.Mesh} mesh
  1010. * @param {GLTF.Mesh} meshDef
  1011. */
  1012. function updateMorphTargets( mesh, meshDef ) {
  1013. mesh.updateMorphTargets();
  1014. if ( meshDef.weights !== undefined ) {
  1015. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  1016. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  1017. }
  1018. }
  1019. // .extras has user-defined data, so check that .extras.targetNames is an array.
  1020. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  1021. var targetNames = meshDef.extras.targetNames;
  1022. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  1023. mesh.morphTargetDictionary = {};
  1024. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  1025. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  1026. }
  1027. } else {
  1028. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  1029. }
  1030. }
  1031. }
  1032. function createPrimitiveKey( primitiveDef ) {
  1033. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  1034. var geometryKey;
  1035. if ( dracoExtension ) {
  1036. geometryKey = 'draco:' + dracoExtension.bufferView
  1037. + ':' + dracoExtension.indices
  1038. + ':' + createAttributesKey( dracoExtension.attributes );
  1039. } else {
  1040. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  1041. }
  1042. return geometryKey;
  1043. }
  1044. function createAttributesKey( attributes ) {
  1045. var attributesKey = '';
  1046. var keys = Object.keys( attributes ).sort();
  1047. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1048. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  1049. }
  1050. return attributesKey;
  1051. }
  1052. /* GLTF PARSER */
  1053. function GLTFParser( json, options ) {
  1054. this.json = json || {};
  1055. this.extensions = {};
  1056. this.plugins = {};
  1057. this.options = options || {};
  1058. // loader object cache
  1059. this.cache = new GLTFRegistry();
  1060. // associations between Three.js objects and glTF elements
  1061. this.associations = new Map();
  1062. // BufferGeometry caching
  1063. this.primitiveCache = {};
  1064. // Object3D instance caches
  1065. this.meshCache = { refs: {}, uses: {} };
  1066. this.cameraCache = { refs: {}, uses: {} };
  1067. this.lightCache = { refs: {}, uses: {} };
  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. /**
  1673. * @param {THREE.BufferGeometry} geometry
  1674. * @param {GLTF.Primitive} primitiveDef
  1675. * @param {GLTFParser} parser
  1676. */
  1677. function computeBounds( geometry, primitiveDef, parser ) {
  1678. var attributes = primitiveDef.attributes;
  1679. var box = new THREE.Box3();
  1680. if ( attributes.POSITION !== undefined ) {
  1681. var accessor = parser.json.accessors[ attributes.POSITION ];
  1682. var min = accessor.min;
  1683. var max = accessor.max;
  1684. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1685. if ( min !== undefined && max !== undefined ) {
  1686. box.set(
  1687. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  1688. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  1689. } else {
  1690. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1691. return;
  1692. }
  1693. } else {
  1694. return;
  1695. }
  1696. var targets = primitiveDef.targets;
  1697. if ( targets !== undefined ) {
  1698. var maxDisplacement = new THREE.Vector3();
  1699. var vector = new THREE.Vector3();
  1700. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1701. var target = targets[ i ];
  1702. if ( target.POSITION !== undefined ) {
  1703. var accessor = parser.json.accessors[ target.POSITION ];
  1704. var min = accessor.min;
  1705. var max = accessor.max;
  1706. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1707. if ( min !== undefined && max !== undefined ) {
  1708. // we need to get max of absolute components because target weight is [-1,1]
  1709. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  1710. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  1711. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  1712. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  1713. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  1714. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  1715. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  1716. maxDisplacement.max( vector );
  1717. } else {
  1718. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1719. }
  1720. }
  1721. }
  1722. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  1723. box.expandByVector( maxDisplacement );
  1724. }
  1725. geometry.boundingBox = box;
  1726. var sphere = new THREE.Sphere();
  1727. box.getCenter( sphere.center );
  1728. sphere.radius = box.min.distanceTo( box.max ) / 2;
  1729. geometry.boundingSphere = sphere;
  1730. }
  1731. /**
  1732. * @param {THREE.BufferGeometry} geometry
  1733. * @param {GLTF.Primitive} primitiveDef
  1734. * @param {GLTFParser} parser
  1735. * @return {Promise<THREE.BufferGeometry>}
  1736. */
  1737. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1738. var attributes = primitiveDef.attributes;
  1739. var pending = [];
  1740. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1741. return parser.getDependency( 'accessor', accessorIndex )
  1742. .then( function ( accessor ) {
  1743. geometry.setAttribute( attributeName, accessor );
  1744. } );
  1745. }
  1746. for ( var gltfAttributeName in attributes ) {
  1747. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1748. // Skip attributes already provided by e.g. Draco extension.
  1749. if ( threeAttributeName in geometry.attributes ) continue;
  1750. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1751. }
  1752. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1753. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1754. geometry.setIndex( accessor );
  1755. } );
  1756. pending.push( accessor );
  1757. }
  1758. assignExtrasToUserData( geometry, primitiveDef );
  1759. computeBounds( geometry, primitiveDef, parser );
  1760. return Promise.all( pending ).then( function () {
  1761. return primitiveDef.targets !== undefined
  1762. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1763. : geometry;
  1764. } );
  1765. }
  1766. /**
  1767. * @param {THREE.BufferGeometry} geometry
  1768. * @param {Number} drawMode
  1769. * @return {THREE.BufferGeometry}
  1770. */
  1771. function toTrianglesDrawMode( geometry, drawMode ) {
  1772. var index = geometry.getIndex();
  1773. // generate index if not present
  1774. if ( index === null ) {
  1775. var indices = [];
  1776. var position = geometry.getAttribute( 'position' );
  1777. if ( position !== undefined ) {
  1778. for ( var i = 0; i < position.count; i ++ ) {
  1779. indices.push( i );
  1780. }
  1781. geometry.setIndex( indices );
  1782. index = geometry.getIndex();
  1783. } else {
  1784. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  1785. return geometry;
  1786. }
  1787. }
  1788. //
  1789. var numberOfTriangles = index.count - 2;
  1790. var newIndices = [];
  1791. if ( drawMode === THREE.TriangleFanDrawMode ) {
  1792. // gl.TRIANGLE_FAN
  1793. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  1794. newIndices.push( index.getX( 0 ) );
  1795. newIndices.push( index.getX( i ) );
  1796. newIndices.push( index.getX( i + 1 ) );
  1797. }
  1798. } else {
  1799. // gl.TRIANGLE_STRIP
  1800. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  1801. if ( i % 2 === 0 ) {
  1802. newIndices.push( index.getX( i ) );
  1803. newIndices.push( index.getX( i + 1 ) );
  1804. newIndices.push( index.getX( i + 2 ) );
  1805. } else {
  1806. newIndices.push( index.getX( i + 2 ) );
  1807. newIndices.push( index.getX( i + 1 ) );
  1808. newIndices.push( index.getX( i ) );
  1809. }
  1810. }
  1811. }
  1812. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  1813. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  1814. }
  1815. // build final geometry
  1816. var newGeometry = geometry.clone();
  1817. newGeometry.setIndex( newIndices );
  1818. return newGeometry;
  1819. }
  1820. /**
  1821. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1822. *
  1823. * Creates BufferGeometries from primitives.
  1824. *
  1825. * @param {Array<GLTF.Primitive>} primitives
  1826. * @return {Promise<Array<THREE.BufferGeometry>>}
  1827. */
  1828. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1829. var parser = this;
  1830. var extensions = this.extensions;
  1831. var cache = this.primitiveCache;
  1832. function createDracoPrimitive( primitive ) {
  1833. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1834. .decodePrimitive( primitive, parser )
  1835. .then( function ( geometry ) {
  1836. return addPrimitiveAttributes( geometry, primitive, parser );
  1837. } );
  1838. }
  1839. var pending = [];
  1840. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1841. var primitive = primitives[ i ];
  1842. var cacheKey = createPrimitiveKey( primitive );
  1843. // See if we've already created this geometry
  1844. var cached = cache[ cacheKey ];
  1845. if ( cached ) {
  1846. // Use the cached geometry if it exists
  1847. pending.push( cached.promise );
  1848. } else {
  1849. var geometryPromise;
  1850. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1851. // Use DRACO geometry if available
  1852. geometryPromise = createDracoPrimitive( primitive );
  1853. } else {
  1854. // Otherwise create a new geometry
  1855. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1856. }
  1857. // Cache this geometry
  1858. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1859. pending.push( geometryPromise );
  1860. }
  1861. }
  1862. return Promise.all( pending );
  1863. };
  1864. /**
  1865. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1866. * @param {number} meshIndex
  1867. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1868. */
  1869. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1870. var parser = this;
  1871. var json = this.json;
  1872. var meshDef = json.meshes[ meshIndex ];
  1873. var primitives = meshDef.primitives;
  1874. var pending = [];
  1875. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1876. var material = primitives[ i ].material === undefined
  1877. ? createDefaultMaterial( this.cache )
  1878. : this.getDependency( 'material', primitives[ i ].material );
  1879. pending.push( material );
  1880. }
  1881. pending.push( parser.loadGeometries( primitives ) );
  1882. return Promise.all( pending ).then( function ( results ) {
  1883. var materials = results.slice( 0, results.length - 1 );
  1884. var geometries = results[ results.length - 1 ];
  1885. var meshes = [];
  1886. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1887. var geometry = geometries[ i ];
  1888. var primitive = primitives[ i ];
  1889. // 1. create Mesh
  1890. var mesh;
  1891. var material = materials[ i ];
  1892. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1893. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1894. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1895. primitive.mode === undefined ) {
  1896. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  1897. mesh = meshDef.isSkinnedMesh === true
  1898. ? new THREE.SkinnedMesh( geometry, material )
  1899. : new THREE.Mesh( geometry, material );
  1900. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  1901. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  1902. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  1903. mesh.normalizeSkinWeights();
  1904. }
  1905. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1906. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  1907. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1908. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  1909. }
  1910. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1911. mesh = new THREE.LineSegments( geometry, material );
  1912. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1913. mesh = new THREE.Line( geometry, material );
  1914. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1915. mesh = new THREE.LineLoop( geometry, material );
  1916. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1917. mesh = new THREE.Points( geometry, material );
  1918. } else {
  1919. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1920. }
  1921. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1922. updateMorphTargets( mesh, meshDef );
  1923. }
  1924. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1925. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1926. assignExtrasToUserData( mesh, meshDef );
  1927. parser.assignFinalMaterial( mesh );
  1928. meshes.push( mesh );
  1929. }
  1930. if ( meshes.length === 1 ) {
  1931. return meshes[ 0 ];
  1932. }
  1933. var group = new THREE.Group();
  1934. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1935. group.add( meshes[ i ] );
  1936. }
  1937. return group;
  1938. } );
  1939. };
  1940. /**
  1941. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1942. * @param {number} cameraIndex
  1943. * @return {Promise<THREE.Camera>}
  1944. */
  1945. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1946. var camera;
  1947. var cameraDef = this.json.cameras[ cameraIndex ];
  1948. var params = cameraDef[ cameraDef.type ];
  1949. if ( ! params ) {
  1950. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1951. return;
  1952. }
  1953. if ( cameraDef.type === 'perspective' ) {
  1954. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1955. } else if ( cameraDef.type === 'orthographic' ) {
  1956. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  1957. }
  1958. if ( cameraDef.name ) camera.name = cameraDef.name;
  1959. assignExtrasToUserData( camera, cameraDef );
  1960. return Promise.resolve( camera );
  1961. };
  1962. /**
  1963. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1964. * @param {number} skinIndex
  1965. * @return {Promise<Object>}
  1966. */
  1967. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1968. var skinDef = this.json.skins[ skinIndex ];
  1969. var skinEntry = { joints: skinDef.joints };
  1970. if ( skinDef.inverseBindMatrices === undefined ) {
  1971. return Promise.resolve( skinEntry );
  1972. }
  1973. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1974. skinEntry.inverseBindMatrices = accessor;
  1975. return skinEntry;
  1976. } );
  1977. };
  1978. /**
  1979. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1980. * @param {number} animationIndex
  1981. * @return {Promise<THREE.AnimationClip>}
  1982. */
  1983. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1984. var json = this.json;
  1985. var animationDef = json.animations[ animationIndex ];
  1986. var pendingNodes = [];
  1987. var pendingInputAccessors = [];
  1988. var pendingOutputAccessors = [];
  1989. var pendingSamplers = [];
  1990. var pendingTargets = [];
  1991. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1992. var channel = animationDef.channels[ i ];
  1993. var sampler = animationDef.samplers[ channel.sampler ];
  1994. var target = channel.target;
  1995. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1996. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1997. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1998. pendingNodes.push( this.getDependency( 'node', name ) );
  1999. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  2000. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  2001. pendingSamplers.push( sampler );
  2002. pendingTargets.push( target );
  2003. }
  2004. return Promise.all( [
  2005. Promise.all( pendingNodes ),
  2006. Promise.all( pendingInputAccessors ),
  2007. Promise.all( pendingOutputAccessors ),
  2008. Promise.all( pendingSamplers ),
  2009. Promise.all( pendingTargets )
  2010. ] ).then( function ( dependencies ) {
  2011. var nodes = dependencies[ 0 ];
  2012. var inputAccessors = dependencies[ 1 ];
  2013. var outputAccessors = dependencies[ 2 ];
  2014. var samplers = dependencies[ 3 ];
  2015. var targets = dependencies[ 4 ];
  2016. var tracks = [];
  2017. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  2018. var node = nodes[ i ];
  2019. var inputAccessor = inputAccessors[ i ];
  2020. var outputAccessor = outputAccessors[ i ];
  2021. var sampler = samplers[ i ];
  2022. var target = targets[ i ];
  2023. if ( node === undefined ) continue;
  2024. node.updateMatrix();
  2025. node.matrixAutoUpdate = true;
  2026. var TypedKeyframeTrack;
  2027. switch ( PATH_PROPERTIES[ target.path ] ) {
  2028. case PATH_PROPERTIES.weights:
  2029. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  2030. break;
  2031. case PATH_PROPERTIES.rotation:
  2032. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  2033. break;
  2034. case PATH_PROPERTIES.position:
  2035. case PATH_PROPERTIES.scale:
  2036. default:
  2037. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  2038. break;
  2039. }
  2040. var targetName = node.name ? node.name : node.uuid;
  2041. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  2042. var targetNames = [];
  2043. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  2044. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  2045. node.traverse( function ( object ) {
  2046. if ( object.isMesh === true && object.morphTargetInfluences ) {
  2047. targetNames.push( object.name ? object.name : object.uuid );
  2048. }
  2049. } );
  2050. } else {
  2051. targetNames.push( targetName );
  2052. }
  2053. var outputArray = outputAccessor.array;
  2054. if ( outputAccessor.normalized ) {
  2055. var scale;
  2056. if ( outputArray.constructor === Int8Array ) {
  2057. scale = 1 / 127;
  2058. } else if ( outputArray.constructor === Uint8Array ) {
  2059. scale = 1 / 255;
  2060. } else if ( outputArray.constructor == Int16Array ) {
  2061. scale = 1 / 32767;
  2062. } else if ( outputArray.constructor === Uint16Array ) {
  2063. scale = 1 / 65535;
  2064. } else {
  2065. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  2066. }
  2067. var scaled = new Float32Array( outputArray.length );
  2068. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  2069. scaled[ j ] = outputArray[ j ] * scale;
  2070. }
  2071. outputArray = scaled;
  2072. }
  2073. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  2074. var track = new TypedKeyframeTrack(
  2075. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  2076. inputAccessor.array,
  2077. outputArray,
  2078. interpolation
  2079. );
  2080. // Override interpolation with custom factory method.
  2081. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  2082. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  2083. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  2084. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  2085. // must be divided by three to get the interpolant's sampleSize argument.
  2086. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  2087. };
  2088. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  2089. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  2090. }
  2091. tracks.push( track );
  2092. }
  2093. }
  2094. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  2095. return new THREE.AnimationClip( name, undefined, tracks );
  2096. } );
  2097. };
  2098. /**
  2099. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  2100. * @param {number} nodeIndex
  2101. * @return {Promise<THREE.Object3D>}
  2102. */
  2103. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  2104. var json = this.json;
  2105. var extensions = this.extensions;
  2106. var parser = this;
  2107. var nodeDef = json.nodes[ nodeIndex ];
  2108. return ( function () {
  2109. var pending = [];
  2110. if ( nodeDef.mesh !== undefined ) {
  2111. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  2112. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  2113. // if weights are provided on the node, override weights on the mesh.
  2114. if ( nodeDef.weights !== undefined ) {
  2115. node.traverse( function ( o ) {
  2116. if ( ! o.isMesh ) return;
  2117. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  2118. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  2119. }
  2120. } );
  2121. }
  2122. return node;
  2123. } ) );
  2124. }
  2125. if ( nodeDef.camera !== undefined ) {
  2126. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  2127. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  2128. } ) );
  2129. }
  2130. parser._invokeAll( function ( ext ) {
  2131. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  2132. } ).forEach( function ( promise ) {
  2133. pending.push( promise );
  2134. } );
  2135. return Promise.all( pending );
  2136. }() ).then( function ( objects ) {
  2137. var node;
  2138. // .isBone isn't in glTF spec. See ._markDefs
  2139. if ( nodeDef.isBone === true ) {
  2140. node = new THREE.Bone();
  2141. } else if ( objects.length > 1 ) {
  2142. node = new THREE.Group();
  2143. } else if ( objects.length === 1 ) {
  2144. node = objects[ 0 ];
  2145. } else {
  2146. node = new THREE.Object3D();
  2147. }
  2148. if ( node !== objects[ 0 ] ) {
  2149. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  2150. node.add( objects[ i ] );
  2151. }
  2152. }
  2153. if ( nodeDef.name ) {
  2154. node.userData.name = nodeDef.name;
  2155. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  2156. }
  2157. assignExtrasToUserData( node, nodeDef );
  2158. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  2159. if ( nodeDef.matrix !== undefined ) {
  2160. var matrix = new THREE.Matrix4();
  2161. matrix.fromArray( nodeDef.matrix );
  2162. node.applyMatrix4( matrix );
  2163. } else {
  2164. if ( nodeDef.translation !== undefined ) {
  2165. node.position.fromArray( nodeDef.translation );
  2166. }
  2167. if ( nodeDef.rotation !== undefined ) {
  2168. node.quaternion.fromArray( nodeDef.rotation );
  2169. }
  2170. if ( nodeDef.scale !== undefined ) {
  2171. node.scale.fromArray( nodeDef.scale );
  2172. }
  2173. }
  2174. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  2175. return node;
  2176. } );
  2177. };
  2178. /**
  2179. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  2180. * @param {number} sceneIndex
  2181. * @return {Promise<THREE.Group>}
  2182. */
  2183. GLTFParser.prototype.loadScene = function () {
  2184. // scene node hierachy builder
  2185. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  2186. var nodeDef = json.nodes[ nodeId ];
  2187. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  2188. if ( nodeDef.skin === undefined ) return node;
  2189. // build skeleton here as well
  2190. var skinEntry;
  2191. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  2192. skinEntry = skin;
  2193. var pendingJoints = [];
  2194. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  2195. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  2196. }
  2197. return Promise.all( pendingJoints );
  2198. } ).then( function ( jointNodes ) {
  2199. node.traverse( function ( mesh ) {
  2200. if ( ! mesh.isMesh ) return;
  2201. var bones = [];
  2202. var boneInverses = [];
  2203. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  2204. var jointNode = jointNodes[ j ];
  2205. if ( jointNode ) {
  2206. bones.push( jointNode );
  2207. var mat = new THREE.Matrix4();
  2208. if ( skinEntry.inverseBindMatrices !== undefined ) {
  2209. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  2210. }
  2211. boneInverses.push( mat );
  2212. } else {
  2213. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  2214. }
  2215. }
  2216. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  2217. } );
  2218. return node;
  2219. } );
  2220. } ).then( function ( node ) {
  2221. // build node hierachy
  2222. parentObject.add( node );
  2223. var pending = [];
  2224. if ( nodeDef.children ) {
  2225. var children = nodeDef.children;
  2226. for ( var i = 0, il = children.length; i < il; i ++ ) {
  2227. var child = children[ i ];
  2228. pending.push( buildNodeHierachy( child, node, json, parser ) );
  2229. }
  2230. }
  2231. return Promise.all( pending );
  2232. } );
  2233. }
  2234. return function loadScene( sceneIndex ) {
  2235. var json = this.json;
  2236. var extensions = this.extensions;
  2237. var sceneDef = this.json.scenes[ sceneIndex ];
  2238. var parser = this;
  2239. // Loader returns Group, not Scene.
  2240. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  2241. var scene = new THREE.Group();
  2242. if ( sceneDef.name ) scene.name = sceneDef.name;
  2243. assignExtrasToUserData( scene, sceneDef );
  2244. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  2245. var nodeIds = sceneDef.nodes || [];
  2246. var pending = [];
  2247. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  2248. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  2249. }
  2250. return Promise.all( pending ).then( function () {
  2251. return scene;
  2252. } );
  2253. };
  2254. }();
  2255. return GLTFLoader;
  2256. } )();