GLTFLoader.js 89 KB

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