babylon.glTFFileLoader.js 240 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. /**
  7. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  8. */
  9. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  10. /**
  11. * Sets the useRightHandedSystem flag on the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  14. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  15. var GLTFLoaderAnimationStartMode;
  16. (function (GLTFLoaderAnimationStartMode) {
  17. /**
  18. * No animation will start.
  19. */
  20. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  21. /**
  22. * The first animation will start.
  23. */
  24. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  25. /**
  26. * All animations will start.
  27. */
  28. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  29. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  30. var GLTFLoaderState;
  31. (function (GLTFLoaderState) {
  32. /**
  33. * The asset is loading.
  34. */
  35. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  36. /**
  37. * The asset is ready for rendering.
  38. */
  39. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  40. /**
  41. * The asset is completely loaded.
  42. */
  43. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  44. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  45. var GLTFFileLoader = /** @class */ (function () {
  46. function GLTFFileLoader() {
  47. // #region Common options
  48. /**
  49. * Raised when the asset has been parsed.
  50. * The data.json property stores the glTF JSON.
  51. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  52. */
  53. this.onParsedObservable = new BABYLON.Observable();
  54. // #endregion
  55. // #region V2 options
  56. /**
  57. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  58. */
  59. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  60. /**
  61. * The animation start mode (NONE, FIRST, ALL).
  62. */
  63. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  64. /**
  65. * Set to true to compile materials before raising the success callback.
  66. */
  67. this.compileMaterials = false;
  68. /**
  69. * Set to true to also compile materials with clip planes.
  70. */
  71. this.useClipPlane = false;
  72. /**
  73. * Set to true to compile shadow generators before raising the success callback.
  74. */
  75. this.compileShadowGenerators = false;
  76. /**
  77. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  78. */
  79. this.onMeshLoadedObservable = new BABYLON.Observable();
  80. /**
  81. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  82. */
  83. this.onTextureLoadedObservable = new BABYLON.Observable();
  84. /**
  85. * Raised when the loader creates a material after parsing the glTF properties of the material.
  86. */
  87. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88. /**
  89. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  90. * For assets with LODs, raised when all of the LODs are complete.
  91. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  92. */
  93. this.onCompleteObservable = new BABYLON.Observable();
  94. /**
  95. * Raised after the loader is disposed.
  96. */
  97. this.onDisposeObservable = new BABYLON.Observable();
  98. /**
  99. * Raised after a loader extension is created.
  100. * Set additional options for a loader extension in this event.
  101. */
  102. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103. // #endregion
  104. this._loader = null;
  105. this.name = "gltf";
  106. this.extensions = {
  107. ".gltf": { isBinary: false },
  108. ".glb": { isBinary: true }
  109. };
  110. }
  111. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  112. set: function (callback) {
  113. if (this._onParsedObserver) {
  114. this.onParsedObservable.remove(this._onParsedObserver);
  115. }
  116. this._onParsedObserver = this.onParsedObservable.add(callback);
  117. },
  118. enumerable: true,
  119. configurable: true
  120. });
  121. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  122. set: function (callback) {
  123. if (this._onMeshLoadedObserver) {
  124. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  125. }
  126. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  127. },
  128. enumerable: true,
  129. configurable: true
  130. });
  131. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  132. set: function (callback) {
  133. if (this._onTextureLoadedObserver) {
  134. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  135. }
  136. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  137. },
  138. enumerable: true,
  139. configurable: true
  140. });
  141. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  142. set: function (callback) {
  143. if (this._onMaterialLoadedObserver) {
  144. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  145. }
  146. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  147. },
  148. enumerable: true,
  149. configurable: true
  150. });
  151. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  152. set: function (callback) {
  153. if (this._onCompleteObserver) {
  154. this.onCompleteObservable.remove(this._onCompleteObserver);
  155. }
  156. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  157. },
  158. enumerable: true,
  159. configurable: true
  160. });
  161. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  162. set: function (callback) {
  163. if (this._onDisposeObserver) {
  164. this.onDisposeObservable.remove(this._onDisposeObserver);
  165. }
  166. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  172. set: function (callback) {
  173. if (this._onExtensionLoadedObserver) {
  174. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  175. }
  176. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  177. },
  178. enumerable: true,
  179. configurable: true
  180. });
  181. /**
  182. * Returns a promise that resolves when the asset is completely loaded.
  183. * @returns A promise that resolves when the asset is completely loaded.
  184. */
  185. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  186. var _this = this;
  187. return new Promise(function (resolve) {
  188. _this.onCompleteObservable.add(function () {
  189. resolve();
  190. }, undefined, undefined, undefined, true);
  191. });
  192. };
  193. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  194. /**
  195. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  196. */
  197. get: function () {
  198. return this._loader ? this._loader.state : null;
  199. },
  200. enumerable: true,
  201. configurable: true
  202. });
  203. /**
  204. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  205. */
  206. GLTFFileLoader.prototype.dispose = function () {
  207. if (this._loader) {
  208. this._loader.dispose();
  209. this._loader = null;
  210. }
  211. this.onMeshLoadedObservable.clear();
  212. this.onTextureLoadedObservable.clear();
  213. this.onMaterialLoadedObservable.clear();
  214. this.onDisposeObservable.notifyObservers(this);
  215. this.onDisposeObservable.clear();
  216. };
  217. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  218. var _this = this;
  219. return Promise.resolve().then(function () {
  220. var loaderData = _this._parse(data);
  221. _this._loader = _this._getLoader(loaderData);
  222. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  223. });
  224. };
  225. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  226. var _this = this;
  227. return Promise.resolve().then(function () {
  228. var loaderData = _this._parse(data);
  229. _this._loader = _this._getLoader(loaderData);
  230. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  231. });
  232. };
  233. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  234. var _this = this;
  235. return Promise.resolve().then(function () {
  236. var loaderData = _this._parse(data);
  237. _this._loader = _this._getLoader(loaderData);
  238. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  239. var container = new BABYLON.AssetContainer(scene);
  240. Array.prototype.push.apply(container.meshes, result.meshes);
  241. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  242. Array.prototype.push.apply(container.skeletons, result.skeletons);
  243. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  244. container.removeAllFromScene();
  245. return container;
  246. });
  247. });
  248. };
  249. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  250. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  251. };
  252. GLTFFileLoader.prototype.createPlugin = function () {
  253. return new GLTFFileLoader();
  254. };
  255. GLTFFileLoader.prototype._parse = function (data) {
  256. var parsedData;
  257. if (data instanceof ArrayBuffer) {
  258. parsedData = GLTFFileLoader._parseBinary(data);
  259. }
  260. else {
  261. parsedData = {
  262. json: JSON.parse(data),
  263. bin: null
  264. };
  265. }
  266. this.onParsedObservable.notifyObservers(parsedData);
  267. this.onParsedObservable.clear();
  268. return parsedData;
  269. };
  270. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  271. var _this = this;
  272. var loaderVersion = { major: 2, minor: 0 };
  273. var asset = loaderData.json.asset || {};
  274. var version = GLTFFileLoader._parseVersion(asset.version);
  275. if (!version) {
  276. throw new Error("Invalid version: " + asset.version);
  277. }
  278. if (asset.minVersion !== undefined) {
  279. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  280. if (!minVersion) {
  281. throw new Error("Invalid minimum version: " + asset.minVersion);
  282. }
  283. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  284. throw new Error("Incompatible minimum version: " + asset.minVersion);
  285. }
  286. }
  287. var createLoaders = {
  288. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  289. 2: GLTFFileLoader.CreateGLTFLoaderV2
  290. };
  291. var createLoader = createLoaders[version.major];
  292. if (!createLoader) {
  293. throw new Error("Unsupported version: " + asset.version);
  294. }
  295. var loader = createLoader();
  296. loader.coordinateSystemMode = this.coordinateSystemMode;
  297. loader.animationStartMode = this.animationStartMode;
  298. loader.compileMaterials = this.compileMaterials;
  299. loader.useClipPlane = this.useClipPlane;
  300. loader.compileShadowGenerators = this.compileShadowGenerators;
  301. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  302. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  303. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  304. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  305. loader.onCompleteObservable.add(function () {
  306. _this.onMeshLoadedObservable.clear();
  307. _this.onTextureLoadedObservable.clear();
  308. _this.onMaterialLoadedObservable.clear();
  309. _this.onCompleteObservable.notifyObservers(_this);
  310. _this.onCompleteObservable.clear();
  311. });
  312. return loader;
  313. };
  314. GLTFFileLoader._parseBinary = function (data) {
  315. var Binary = {
  316. Magic: 0x46546C67
  317. };
  318. var binaryReader = new BinaryReader(data);
  319. var magic = binaryReader.readUint32();
  320. if (magic !== Binary.Magic) {
  321. throw new Error("Unexpected magic: " + magic);
  322. }
  323. var version = binaryReader.readUint32();
  324. switch (version) {
  325. case 1: return GLTFFileLoader._parseV1(binaryReader);
  326. case 2: return GLTFFileLoader._parseV2(binaryReader);
  327. }
  328. throw new Error("Unsupported version: " + version);
  329. };
  330. GLTFFileLoader._parseV1 = function (binaryReader) {
  331. var ContentFormat = {
  332. JSON: 0
  333. };
  334. var length = binaryReader.readUint32();
  335. if (length != binaryReader.getLength()) {
  336. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  337. }
  338. var contentLength = binaryReader.readUint32();
  339. var contentFormat = binaryReader.readUint32();
  340. var content;
  341. switch (contentFormat) {
  342. case ContentFormat.JSON: {
  343. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  344. break;
  345. }
  346. default: {
  347. throw new Error("Unexpected content format: " + contentFormat);
  348. }
  349. }
  350. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  351. var body = binaryReader.readUint8Array(bytesRemaining);
  352. return {
  353. json: content,
  354. bin: body
  355. };
  356. };
  357. GLTFFileLoader._parseV2 = function (binaryReader) {
  358. var ChunkFormat = {
  359. JSON: 0x4E4F534A,
  360. BIN: 0x004E4942
  361. };
  362. var length = binaryReader.readUint32();
  363. if (length !== binaryReader.getLength()) {
  364. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  365. }
  366. // JSON chunk
  367. var chunkLength = binaryReader.readUint32();
  368. var chunkFormat = binaryReader.readUint32();
  369. if (chunkFormat !== ChunkFormat.JSON) {
  370. throw new Error("First chunk format is not JSON");
  371. }
  372. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  373. // Look for BIN chunk
  374. var bin = null;
  375. while (binaryReader.getPosition() < binaryReader.getLength()) {
  376. var chunkLength_1 = binaryReader.readUint32();
  377. var chunkFormat_1 = binaryReader.readUint32();
  378. switch (chunkFormat_1) {
  379. case ChunkFormat.JSON: {
  380. throw new Error("Unexpected JSON chunk");
  381. }
  382. case ChunkFormat.BIN: {
  383. bin = binaryReader.readUint8Array(chunkLength_1);
  384. break;
  385. }
  386. default: {
  387. // ignore unrecognized chunkFormat
  388. binaryReader.skipBytes(chunkLength_1);
  389. break;
  390. }
  391. }
  392. }
  393. return {
  394. json: json,
  395. bin: bin
  396. };
  397. };
  398. GLTFFileLoader._parseVersion = function (version) {
  399. if (version === "1.0" || version === "1.0.1") {
  400. return {
  401. major: 1,
  402. minor: 0
  403. };
  404. }
  405. var match = (version + "").match(/^(\d+)\.(\d+)/);
  406. if (!match) {
  407. return null;
  408. }
  409. return {
  410. major: parseInt(match[1]),
  411. minor: parseInt(match[2])
  412. };
  413. };
  414. GLTFFileLoader._compareVersion = function (a, b) {
  415. if (a.major > b.major)
  416. return 1;
  417. if (a.major < b.major)
  418. return -1;
  419. if (a.minor > b.minor)
  420. return 1;
  421. if (a.minor < b.minor)
  422. return -1;
  423. return 0;
  424. };
  425. GLTFFileLoader._decodeBufferToText = function (buffer) {
  426. var result = "";
  427. var length = buffer.byteLength;
  428. for (var i = 0; i < length; i++) {
  429. result += String.fromCharCode(buffer[i]);
  430. }
  431. return result;
  432. };
  433. // #endregion
  434. // #region V1 options
  435. GLTFFileLoader.IncrementalLoading = true;
  436. GLTFFileLoader.HomogeneousCoordinates = false;
  437. return GLTFFileLoader;
  438. }());
  439. BABYLON.GLTFFileLoader = GLTFFileLoader;
  440. var BinaryReader = /** @class */ (function () {
  441. function BinaryReader(arrayBuffer) {
  442. this._arrayBuffer = arrayBuffer;
  443. this._dataView = new DataView(arrayBuffer);
  444. this._byteOffset = 0;
  445. }
  446. BinaryReader.prototype.getPosition = function () {
  447. return this._byteOffset;
  448. };
  449. BinaryReader.prototype.getLength = function () {
  450. return this._arrayBuffer.byteLength;
  451. };
  452. BinaryReader.prototype.readUint32 = function () {
  453. var value = this._dataView.getUint32(this._byteOffset, true);
  454. this._byteOffset += 4;
  455. return value;
  456. };
  457. BinaryReader.prototype.readUint8Array = function (length) {
  458. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  459. this._byteOffset += length;
  460. return value;
  461. };
  462. BinaryReader.prototype.skipBytes = function (length) {
  463. this._byteOffset += length;
  464. };
  465. return BinaryReader;
  466. }());
  467. if (BABYLON.SceneLoader) {
  468. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  469. }
  470. })(BABYLON || (BABYLON = {}));
  471. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  472. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  473. var BABYLON;
  474. (function (BABYLON) {
  475. var GLTF1;
  476. (function (GLTF1) {
  477. /**
  478. * Enums
  479. */
  480. var EComponentType;
  481. (function (EComponentType) {
  482. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  483. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  484. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  485. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  486. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  487. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  488. var EShaderType;
  489. (function (EShaderType) {
  490. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  491. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  492. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  493. var EParameterType;
  494. (function (EParameterType) {
  495. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  496. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  497. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  498. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  499. EParameterType[EParameterType["INT"] = 5124] = "INT";
  500. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  501. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  502. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  503. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  504. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  505. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  506. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  507. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  508. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  509. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  510. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  511. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  512. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  513. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  514. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  515. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  516. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  517. var ETextureWrapMode;
  518. (function (ETextureWrapMode) {
  519. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  520. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  521. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  522. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  523. var ETextureFilterType;
  524. (function (ETextureFilterType) {
  525. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  526. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  527. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  528. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  529. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  530. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  531. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  532. var ETextureFormat;
  533. (function (ETextureFormat) {
  534. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  535. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  536. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  537. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  538. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  539. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  540. var ECullingType;
  541. (function (ECullingType) {
  542. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  543. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  544. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  545. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  546. var EBlendingFunction;
  547. (function (EBlendingFunction) {
  548. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  549. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  550. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  551. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  552. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  553. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  554. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  555. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  556. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  557. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  558. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  559. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  560. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  561. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  562. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  563. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  564. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  565. })(BABYLON || (BABYLON = {}));
  566. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  567. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  568. var BABYLON;
  569. (function (BABYLON) {
  570. var GLTF1;
  571. (function (GLTF1) {
  572. /**
  573. * Tokenizer. Used for shaders compatibility
  574. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  575. */
  576. var ETokenType;
  577. (function (ETokenType) {
  578. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  579. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  580. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  581. })(ETokenType || (ETokenType = {}));
  582. var Tokenizer = /** @class */ (function () {
  583. function Tokenizer(toParse) {
  584. this._pos = 0;
  585. this.currentToken = ETokenType.UNKNOWN;
  586. this.currentIdentifier = "";
  587. this.currentString = "";
  588. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  589. this._toParse = toParse;
  590. this._maxPos = toParse.length;
  591. }
  592. Tokenizer.prototype.getNextToken = function () {
  593. if (this.isEnd())
  594. return ETokenType.END_OF_INPUT;
  595. this.currentString = this.read();
  596. this.currentToken = ETokenType.UNKNOWN;
  597. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  598. this.currentToken = ETokenType.IDENTIFIER;
  599. this.currentIdentifier = this.currentString;
  600. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  601. this.currentIdentifier += this.currentString;
  602. this.forward();
  603. }
  604. }
  605. return this.currentToken;
  606. };
  607. Tokenizer.prototype.peek = function () {
  608. return this._toParse[this._pos];
  609. };
  610. Tokenizer.prototype.read = function () {
  611. return this._toParse[this._pos++];
  612. };
  613. Tokenizer.prototype.forward = function () {
  614. this._pos++;
  615. };
  616. Tokenizer.prototype.isEnd = function () {
  617. return this._pos >= this._maxPos;
  618. };
  619. return Tokenizer;
  620. }());
  621. /**
  622. * Values
  623. */
  624. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  625. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  626. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  627. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  628. /**
  629. * Parse
  630. */
  631. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  632. for (var buf in parsedBuffers) {
  633. var parsedBuffer = parsedBuffers[buf];
  634. gltfRuntime.buffers[buf] = parsedBuffer;
  635. gltfRuntime.buffersCount++;
  636. }
  637. };
  638. var parseShaders = function (parsedShaders, gltfRuntime) {
  639. for (var sha in parsedShaders) {
  640. var parsedShader = parsedShaders[sha];
  641. gltfRuntime.shaders[sha] = parsedShader;
  642. gltfRuntime.shaderscount++;
  643. }
  644. };
  645. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  646. for (var object in parsedObjects) {
  647. var parsedObject = parsedObjects[object];
  648. gltfRuntime[runtimeProperty][object] = parsedObject;
  649. }
  650. };
  651. /**
  652. * Utils
  653. */
  654. var normalizeUVs = function (buffer) {
  655. if (!buffer) {
  656. return;
  657. }
  658. for (var i = 0; i < buffer.length / 2; i++) {
  659. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  660. }
  661. };
  662. var getAttribute = function (attributeParameter) {
  663. if (attributeParameter.semantic === "NORMAL") {
  664. return "normal";
  665. }
  666. else if (attributeParameter.semantic === "POSITION") {
  667. return "position";
  668. }
  669. else if (attributeParameter.semantic === "JOINT") {
  670. return "matricesIndices";
  671. }
  672. else if (attributeParameter.semantic === "WEIGHT") {
  673. return "matricesWeights";
  674. }
  675. else if (attributeParameter.semantic === "COLOR") {
  676. return "color";
  677. }
  678. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  679. var channel = Number(attributeParameter.semantic.split("_")[1]);
  680. return "uv" + (channel === 0 ? "" : channel + 1);
  681. }
  682. return null;
  683. };
  684. /**
  685. * Loads and creates animations
  686. */
  687. var loadAnimations = function (gltfRuntime) {
  688. for (var anim in gltfRuntime.animations) {
  689. var animation = gltfRuntime.animations[anim];
  690. if (!animation.channels || !animation.samplers) {
  691. continue;
  692. }
  693. var lastAnimation = null;
  694. for (var i = 0; i < animation.channels.length; i++) {
  695. // Get parameters and load buffers
  696. var channel = animation.channels[i];
  697. var sampler = animation.samplers[channel.sampler];
  698. if (!sampler) {
  699. continue;
  700. }
  701. var inputData = null;
  702. var outputData = null;
  703. if (animation.parameters) {
  704. inputData = animation.parameters[sampler.input];
  705. outputData = animation.parameters[sampler.output];
  706. }
  707. else {
  708. inputData = sampler.input;
  709. outputData = sampler.output;
  710. }
  711. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  712. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  713. var targetID = channel.target.id;
  714. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  715. if (targetNode === null) {
  716. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  717. }
  718. if (targetNode === null) {
  719. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  720. continue;
  721. }
  722. var isBone = targetNode instanceof BABYLON.Bone;
  723. // Get target path (position, rotation or scaling)
  724. var targetPath = channel.target.path;
  725. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  726. if (targetPathIndex !== -1) {
  727. targetPath = babylonAnimationPaths[targetPathIndex];
  728. }
  729. // Determine animation type
  730. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  731. if (!isBone) {
  732. if (targetPath === "rotationQuaternion") {
  733. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  734. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  735. }
  736. else {
  737. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  738. }
  739. }
  740. // Create animation and key frames
  741. var babylonAnimation = null;
  742. var keys = [];
  743. var arrayOffset = 0;
  744. var modifyKey = false;
  745. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  746. babylonAnimation = lastAnimation;
  747. modifyKey = true;
  748. }
  749. if (!modifyKey) {
  750. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  751. }
  752. // For each frame
  753. for (var j = 0; j < bufferInput.length; j++) {
  754. var value = null;
  755. if (targetPath === "rotationQuaternion") { // VEC4
  756. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  757. arrayOffset += 4;
  758. }
  759. else { // Position and scaling are VEC3
  760. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  761. arrayOffset += 3;
  762. }
  763. if (isBone) {
  764. var bone = targetNode;
  765. var translation = BABYLON.Vector3.Zero();
  766. var rotationQuaternion = new BABYLON.Quaternion();
  767. var scaling = BABYLON.Vector3.Zero();
  768. // Warning on decompose
  769. var mat = bone.getBaseMatrix();
  770. if (modifyKey && lastAnimation) {
  771. mat = lastAnimation.getKeys()[j].value;
  772. }
  773. mat.decompose(scaling, rotationQuaternion, translation);
  774. if (targetPath === "position") {
  775. translation = value;
  776. }
  777. else if (targetPath === "rotationQuaternion") {
  778. rotationQuaternion = value;
  779. }
  780. else {
  781. scaling = value;
  782. }
  783. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  784. }
  785. if (!modifyKey) {
  786. keys.push({
  787. frame: bufferInput[j],
  788. value: value
  789. });
  790. }
  791. else if (lastAnimation) {
  792. lastAnimation.getKeys()[j].value = value;
  793. }
  794. }
  795. // Finish
  796. if (!modifyKey && babylonAnimation) {
  797. babylonAnimation.setKeys(keys);
  798. targetNode.animations.push(babylonAnimation);
  799. }
  800. lastAnimation = babylonAnimation;
  801. gltfRuntime.scene.stopAnimation(targetNode);
  802. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  803. }
  804. }
  805. };
  806. /**
  807. * Returns the bones transformation matrix
  808. */
  809. var configureBoneTransformation = function (node) {
  810. var mat = null;
  811. if (node.translation || node.rotation || node.scale) {
  812. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  813. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  814. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  815. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  816. }
  817. else {
  818. mat = BABYLON.Matrix.FromArray(node.matrix);
  819. }
  820. return mat;
  821. };
  822. /**
  823. * Returns the parent bone
  824. */
  825. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  826. // Try to find
  827. for (var i = 0; i < newSkeleton.bones.length; i++) {
  828. if (newSkeleton.bones[i].name === jointName) {
  829. return newSkeleton.bones[i];
  830. }
  831. }
  832. // Not found, search in gltf nodes
  833. var nodes = gltfRuntime.nodes;
  834. for (var nde in nodes) {
  835. var node = nodes[nde];
  836. if (!node.jointName) {
  837. continue;
  838. }
  839. var children = node.children;
  840. for (var i = 0; i < children.length; i++) {
  841. var child = gltfRuntime.nodes[children[i]];
  842. if (!child.jointName) {
  843. continue;
  844. }
  845. if (child.jointName === jointName) {
  846. var mat = configureBoneTransformation(node);
  847. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  848. bone.id = nde;
  849. return bone;
  850. }
  851. }
  852. }
  853. return null;
  854. };
  855. /**
  856. * Returns the appropriate root node
  857. */
  858. var getNodeToRoot = function (nodesToRoot, id) {
  859. for (var i = 0; i < nodesToRoot.length; i++) {
  860. var nodeToRoot = nodesToRoot[i];
  861. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  862. var child = nodeToRoot.node.children[j];
  863. if (child === id) {
  864. return nodeToRoot.bone;
  865. }
  866. }
  867. }
  868. return null;
  869. };
  870. /**
  871. * Returns the node with the joint name
  872. */
  873. var getJointNode = function (gltfRuntime, jointName) {
  874. var nodes = gltfRuntime.nodes;
  875. var node = nodes[jointName];
  876. if (node) {
  877. return {
  878. node: node,
  879. id: jointName
  880. };
  881. }
  882. for (var nde in nodes) {
  883. node = nodes[nde];
  884. if (node.jointName === jointName) {
  885. return {
  886. node: node,
  887. id: nde
  888. };
  889. }
  890. }
  891. return null;
  892. };
  893. /**
  894. * Checks if a nodes is in joints
  895. */
  896. var nodeIsInJoints = function (skins, id) {
  897. for (var i = 0; i < skins.jointNames.length; i++) {
  898. if (skins.jointNames[i] === id) {
  899. return true;
  900. }
  901. }
  902. return false;
  903. };
  904. /**
  905. * Fills the nodes to root for bones and builds hierarchy
  906. */
  907. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  908. // Creates nodes for root
  909. for (var nde in gltfRuntime.nodes) {
  910. var node = gltfRuntime.nodes[nde];
  911. var id = nde;
  912. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  913. continue;
  914. }
  915. // Create node to root bone
  916. var mat = configureBoneTransformation(node);
  917. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  918. bone.id = id;
  919. nodesToRoot.push({ bone: bone, node: node, id: id });
  920. }
  921. // Parenting
  922. for (var i = 0; i < nodesToRoot.length; i++) {
  923. var nodeToRoot = nodesToRoot[i];
  924. var children = nodeToRoot.node.children;
  925. for (var j = 0; j < children.length; j++) {
  926. var child = null;
  927. for (var k = 0; k < nodesToRoot.length; k++) {
  928. if (nodesToRoot[k].id === children[j]) {
  929. child = nodesToRoot[k];
  930. break;
  931. }
  932. }
  933. if (child) {
  934. child.bone._parent = nodeToRoot.bone;
  935. nodeToRoot.bone.children.push(child.bone);
  936. }
  937. }
  938. }
  939. };
  940. /**
  941. * Imports a skeleton
  942. */
  943. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  944. if (!newSkeleton) {
  945. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  946. }
  947. if (!skins.babylonSkeleton) {
  948. return newSkeleton;
  949. }
  950. // Find the root bones
  951. var nodesToRoot = [];
  952. var nodesToRootToAdd = [];
  953. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  954. newSkeleton.bones = [];
  955. // Joints
  956. for (var i = 0; i < skins.jointNames.length; i++) {
  957. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  958. if (!jointNode) {
  959. continue;
  960. }
  961. var node = jointNode.node;
  962. if (!node) {
  963. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  964. continue;
  965. }
  966. var id = jointNode.id;
  967. // Optimize, if the bone already exists...
  968. var existingBone = gltfRuntime.scene.getBoneByID(id);
  969. if (existingBone) {
  970. newSkeleton.bones.push(existingBone);
  971. continue;
  972. }
  973. // Search for parent bone
  974. var foundBone = false;
  975. var parentBone = null;
  976. for (var j = 0; j < i; j++) {
  977. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  978. if (!jointNode_1) {
  979. continue;
  980. }
  981. var joint = jointNode_1.node;
  982. if (!joint) {
  983. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  984. continue;
  985. }
  986. var children = joint.children;
  987. if (!children) {
  988. continue;
  989. }
  990. foundBone = false;
  991. for (var k = 0; k < children.length; k++) {
  992. if (children[k] === id) {
  993. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  994. foundBone = true;
  995. break;
  996. }
  997. }
  998. if (foundBone) {
  999. break;
  1000. }
  1001. }
  1002. // Create bone
  1003. var mat = configureBoneTransformation(node);
  1004. if (!parentBone && nodesToRoot.length > 0) {
  1005. parentBone = getNodeToRoot(nodesToRoot, id);
  1006. if (parentBone) {
  1007. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1008. nodesToRootToAdd.push(parentBone);
  1009. }
  1010. }
  1011. }
  1012. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1013. bone.id = id;
  1014. }
  1015. // Polish
  1016. var bones = newSkeleton.bones;
  1017. newSkeleton.bones = [];
  1018. for (var i = 0; i < skins.jointNames.length; i++) {
  1019. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1020. if (!jointNode) {
  1021. continue;
  1022. }
  1023. for (var j = 0; j < bones.length; j++) {
  1024. if (bones[j].id === jointNode.id) {
  1025. newSkeleton.bones.push(bones[j]);
  1026. break;
  1027. }
  1028. }
  1029. }
  1030. newSkeleton.prepare();
  1031. // Finish
  1032. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1033. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1034. }
  1035. return newSkeleton;
  1036. };
  1037. /**
  1038. * Imports a mesh and its geometries
  1039. */
  1040. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1041. if (!newMesh) {
  1042. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1043. newMesh.id = id;
  1044. }
  1045. if (!node.babylonNode) {
  1046. return newMesh;
  1047. }
  1048. var subMaterials = [];
  1049. var vertexData = null;
  1050. var verticesStarts = new Array();
  1051. var verticesCounts = new Array();
  1052. var indexStarts = new Array();
  1053. var indexCounts = new Array();
  1054. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1055. var meshID = meshes[meshIndex];
  1056. var mesh = gltfRuntime.meshes[meshID];
  1057. if (!mesh) {
  1058. continue;
  1059. }
  1060. // Positions, normals and UVs
  1061. for (var i = 0; i < mesh.primitives.length; i++) {
  1062. // Temporary vertex data
  1063. var tempVertexData = new BABYLON.VertexData();
  1064. var primitive = mesh.primitives[i];
  1065. if (primitive.mode !== 4) {
  1066. // continue;
  1067. }
  1068. var attributes = primitive.attributes;
  1069. var accessor = null;
  1070. var buffer = null;
  1071. // Set positions, normal and uvs
  1072. for (var semantic in attributes) {
  1073. // Link accessor and buffer view
  1074. accessor = gltfRuntime.accessors[attributes[semantic]];
  1075. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1076. if (semantic === "NORMAL") {
  1077. tempVertexData.normals = new Float32Array(buffer.length);
  1078. tempVertexData.normals.set(buffer);
  1079. }
  1080. else if (semantic === "POSITION") {
  1081. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1082. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1083. for (var j = 0; j < buffer.length; j += 4) {
  1084. tempVertexData.positions[j] = buffer[j];
  1085. tempVertexData.positions[j + 1] = buffer[j + 1];
  1086. tempVertexData.positions[j + 2] = buffer[j + 2];
  1087. }
  1088. }
  1089. else {
  1090. tempVertexData.positions = new Float32Array(buffer.length);
  1091. tempVertexData.positions.set(buffer);
  1092. }
  1093. verticesCounts.push(tempVertexData.positions.length);
  1094. }
  1095. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1096. var channel = Number(semantic.split("_")[1]);
  1097. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1098. var uvs = new Float32Array(buffer.length);
  1099. uvs.set(buffer);
  1100. normalizeUVs(uvs);
  1101. tempVertexData.set(uvs, uvKind);
  1102. }
  1103. else if (semantic === "JOINT") {
  1104. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1105. tempVertexData.matricesIndices.set(buffer);
  1106. }
  1107. else if (semantic === "WEIGHT") {
  1108. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1109. tempVertexData.matricesWeights.set(buffer);
  1110. }
  1111. else if (semantic === "COLOR") {
  1112. tempVertexData.colors = new Float32Array(buffer.length);
  1113. tempVertexData.colors.set(buffer);
  1114. }
  1115. }
  1116. // Indices
  1117. accessor = gltfRuntime.accessors[primitive.indices];
  1118. if (accessor) {
  1119. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1120. tempVertexData.indices = new Int32Array(buffer.length);
  1121. tempVertexData.indices.set(buffer);
  1122. indexCounts.push(tempVertexData.indices.length);
  1123. }
  1124. else {
  1125. // Set indices on the fly
  1126. var indices = [];
  1127. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1128. indices.push(j);
  1129. }
  1130. tempVertexData.indices = new Int32Array(indices);
  1131. indexCounts.push(tempVertexData.indices.length);
  1132. }
  1133. if (!vertexData) {
  1134. vertexData = tempVertexData;
  1135. }
  1136. else {
  1137. vertexData.merge(tempVertexData);
  1138. }
  1139. // Sub material
  1140. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1141. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1142. // Update vertices start and index start
  1143. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1144. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1145. }
  1146. }
  1147. var material;
  1148. if (subMaterials.length > 1) {
  1149. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1150. material.subMaterials = subMaterials;
  1151. }
  1152. else {
  1153. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1154. }
  1155. if (subMaterials.length === 1) {
  1156. material = subMaterials[0];
  1157. }
  1158. if (!newMesh.material) {
  1159. newMesh.material = material;
  1160. }
  1161. // Apply geometry
  1162. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1163. newMesh.computeWorldMatrix(true);
  1164. // Apply submeshes
  1165. newMesh.subMeshes = [];
  1166. var index = 0;
  1167. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1168. var meshID = meshes[meshIndex];
  1169. var mesh = gltfRuntime.meshes[meshID];
  1170. if (!mesh) {
  1171. continue;
  1172. }
  1173. for (var i = 0; i < mesh.primitives.length; i++) {
  1174. if (mesh.primitives[i].mode !== 4) {
  1175. //continue;
  1176. }
  1177. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1178. index++;
  1179. }
  1180. }
  1181. // Finish
  1182. return newMesh;
  1183. };
  1184. /**
  1185. * Configure node transformation from position, rotation and scaling
  1186. */
  1187. var configureNode = function (newNode, position, rotation, scaling) {
  1188. if (newNode.position) {
  1189. newNode.position = position;
  1190. }
  1191. if (newNode.rotationQuaternion || newNode.rotation) {
  1192. newNode.rotationQuaternion = rotation;
  1193. }
  1194. if (newNode.scaling) {
  1195. newNode.scaling = scaling;
  1196. }
  1197. };
  1198. /**
  1199. * Configures node from transformation matrix
  1200. */
  1201. var configureNodeFromMatrix = function (newNode, node, parent) {
  1202. if (node.matrix) {
  1203. var position = new BABYLON.Vector3(0, 0, 0);
  1204. var rotation = new BABYLON.Quaternion();
  1205. var scaling = new BABYLON.Vector3(0, 0, 0);
  1206. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1207. mat.decompose(scaling, rotation, position);
  1208. configureNode(newNode, position, rotation, scaling);
  1209. }
  1210. else if (node.translation && node.rotation && node.scale) {
  1211. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1212. }
  1213. newNode.computeWorldMatrix(true);
  1214. };
  1215. /**
  1216. * Imports a node
  1217. */
  1218. var importNode = function (gltfRuntime, node, id, parent) {
  1219. var lastNode = null;
  1220. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1221. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1222. return null;
  1223. }
  1224. }
  1225. // Meshes
  1226. if (node.skin) {
  1227. if (node.meshes) {
  1228. var skin = gltfRuntime.skins[node.skin];
  1229. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1230. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1231. if (newMesh.skeleton === null) {
  1232. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1233. if (!skin.babylonSkeleton) {
  1234. skin.babylonSkeleton = newMesh.skeleton;
  1235. }
  1236. }
  1237. lastNode = newMesh;
  1238. }
  1239. }
  1240. else if (node.meshes) {
  1241. /**
  1242. * Improve meshes property
  1243. */
  1244. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1245. lastNode = newMesh;
  1246. }
  1247. // Lights
  1248. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1249. var light = gltfRuntime.lights[node.light];
  1250. if (light) {
  1251. if (light.type === "ambient") {
  1252. var ambienLight = light[light.type];
  1253. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1254. hemiLight.name = node.name || "";
  1255. if (ambienLight.color) {
  1256. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1257. }
  1258. lastNode = hemiLight;
  1259. }
  1260. else if (light.type === "directional") {
  1261. var directionalLight = light[light.type];
  1262. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1263. dirLight.name = node.name || "";
  1264. if (directionalLight.color) {
  1265. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1266. }
  1267. lastNode = dirLight;
  1268. }
  1269. else if (light.type === "point") {
  1270. var pointLight = light[light.type];
  1271. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1272. ptLight.name = node.name || "";
  1273. if (pointLight.color) {
  1274. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1275. }
  1276. lastNode = ptLight;
  1277. }
  1278. else if (light.type === "spot") {
  1279. var spotLight = light[light.type];
  1280. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1281. spLight.name = node.name || "";
  1282. if (spotLight.color) {
  1283. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1284. }
  1285. if (spotLight.fallOfAngle) {
  1286. spLight.angle = spotLight.fallOfAngle;
  1287. }
  1288. if (spotLight.fallOffExponent) {
  1289. spLight.exponent = spotLight.fallOffExponent;
  1290. }
  1291. lastNode = spLight;
  1292. }
  1293. }
  1294. }
  1295. // Cameras
  1296. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1297. var camera = gltfRuntime.cameras[node.camera];
  1298. if (camera) {
  1299. if (camera.type === "orthographic") {
  1300. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1301. orthoCamera.name = node.name || "";
  1302. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1303. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1304. lastNode = orthoCamera;
  1305. }
  1306. else if (camera.type === "perspective") {
  1307. var perspectiveCamera = camera[camera.type];
  1308. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1309. persCamera.name = node.name || "";
  1310. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1311. if (!perspectiveCamera.aspectRatio) {
  1312. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1313. }
  1314. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1315. persCamera.maxZ = perspectiveCamera.zfar;
  1316. persCamera.minZ = perspectiveCamera.znear;
  1317. }
  1318. lastNode = persCamera;
  1319. }
  1320. }
  1321. }
  1322. // Empty node
  1323. if (!node.jointName) {
  1324. if (node.babylonNode) {
  1325. return node.babylonNode;
  1326. }
  1327. else if (lastNode === null) {
  1328. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1329. node.babylonNode = dummy;
  1330. lastNode = dummy;
  1331. }
  1332. }
  1333. if (lastNode !== null) {
  1334. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1335. configureNodeFromMatrix(lastNode, node, parent);
  1336. }
  1337. else {
  1338. var translation = node.translation || [0, 0, 0];
  1339. var rotation = node.rotation || [0, 0, 0, 1];
  1340. var scale = node.scale || [1, 1, 1];
  1341. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1342. }
  1343. lastNode.updateCache(true);
  1344. node.babylonNode = lastNode;
  1345. }
  1346. return lastNode;
  1347. };
  1348. /**
  1349. * Traverses nodes and creates them
  1350. */
  1351. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1352. if (meshIncluded === void 0) { meshIncluded = false; }
  1353. var node = gltfRuntime.nodes[id];
  1354. var newNode = null;
  1355. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1356. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1357. meshIncluded = true;
  1358. }
  1359. else {
  1360. meshIncluded = false;
  1361. }
  1362. }
  1363. else {
  1364. meshIncluded = true;
  1365. }
  1366. if (!node.jointName && meshIncluded) {
  1367. newNode = importNode(gltfRuntime, node, id, parent);
  1368. if (newNode !== null) {
  1369. newNode.id = id;
  1370. newNode.parent = parent;
  1371. }
  1372. }
  1373. if (node.children) {
  1374. for (var i = 0; i < node.children.length; i++) {
  1375. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1376. }
  1377. }
  1378. };
  1379. /**
  1380. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1381. */
  1382. var postLoad = function (gltfRuntime) {
  1383. // Nodes
  1384. var currentScene = gltfRuntime.currentScene;
  1385. if (currentScene) {
  1386. for (var i = 0; i < currentScene.nodes.length; i++) {
  1387. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1388. }
  1389. }
  1390. else {
  1391. for (var thing in gltfRuntime.scenes) {
  1392. currentScene = gltfRuntime.scenes[thing];
  1393. for (var i = 0; i < currentScene.nodes.length; i++) {
  1394. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1395. }
  1396. }
  1397. }
  1398. // Set animations
  1399. loadAnimations(gltfRuntime);
  1400. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1401. var skeleton = gltfRuntime.scene.skeletons[i];
  1402. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1403. }
  1404. };
  1405. /**
  1406. * onBind shaderrs callback to set uniforms and matrices
  1407. */
  1408. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1409. var materialValues = material.values || technique.parameters;
  1410. for (var unif in unTreatedUniforms) {
  1411. var uniform = unTreatedUniforms[unif];
  1412. var type = uniform.type;
  1413. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1414. if (uniform.semantic && !uniform.source && !uniform.node) {
  1415. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1416. }
  1417. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1418. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1419. if (source === null) {
  1420. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1421. }
  1422. if (source === null) {
  1423. continue;
  1424. }
  1425. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1426. }
  1427. }
  1428. else {
  1429. var value = materialValues[technique.uniforms[unif]];
  1430. if (!value) {
  1431. continue;
  1432. }
  1433. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1434. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1435. if (texture === null || texture === undefined) {
  1436. continue;
  1437. }
  1438. shaderMaterial.getEffect().setTexture(unif, texture);
  1439. }
  1440. else {
  1441. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1442. }
  1443. }
  1444. }
  1445. onSuccess(shaderMaterial);
  1446. };
  1447. /**
  1448. * Prepare uniforms to send the only one time
  1449. * Loads the appropriate textures
  1450. */
  1451. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1452. var materialValues = material.values || technique.parameters;
  1453. var techniqueUniforms = technique.uniforms;
  1454. /**
  1455. * Prepare values here (not matrices)
  1456. */
  1457. for (var unif in unTreatedUniforms) {
  1458. var uniform = unTreatedUniforms[unif];
  1459. var type = uniform.type;
  1460. var value = materialValues[techniqueUniforms[unif]];
  1461. if (value === undefined) {
  1462. // In case the value is the same for all materials
  1463. value = uniform.value;
  1464. }
  1465. if (!value) {
  1466. continue;
  1467. }
  1468. var onLoadTexture = function (uniformName) {
  1469. return function (texture) {
  1470. if (uniform.value && uniformName) {
  1471. // Static uniform
  1472. shaderMaterial.setTexture(uniformName, texture);
  1473. delete unTreatedUniforms[uniformName];
  1474. }
  1475. };
  1476. };
  1477. // Texture (sampler2D)
  1478. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1479. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1480. }
  1481. // Others
  1482. else {
  1483. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1484. // Static uniform
  1485. delete unTreatedUniforms[unif];
  1486. }
  1487. }
  1488. }
  1489. };
  1490. /**
  1491. * Shader compilation failed
  1492. */
  1493. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1494. return function (effect, error) {
  1495. shaderMaterial.dispose(true);
  1496. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1497. };
  1498. };
  1499. /**
  1500. * Shader compilation success
  1501. */
  1502. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1503. return function (_) {
  1504. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1505. shaderMaterial.onBind = function (mesh) {
  1506. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1507. };
  1508. };
  1509. };
  1510. /**
  1511. * Returns the appropriate uniform if already handled by babylon
  1512. */
  1513. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1514. for (var unif in technique.uniforms) {
  1515. var uniform = technique.uniforms[unif];
  1516. var uniformParameter = technique.parameters[uniform];
  1517. if (tokenizer.currentIdentifier === unif) {
  1518. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1519. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1520. if (transformIndex !== -1) {
  1521. delete unTreatedUniforms[unif];
  1522. return babylonTransforms[transformIndex];
  1523. }
  1524. }
  1525. }
  1526. }
  1527. return tokenizer.currentIdentifier;
  1528. };
  1529. /**
  1530. * All shaders loaded. Create materials one by one
  1531. */
  1532. var importMaterials = function (gltfRuntime) {
  1533. // Create materials
  1534. for (var mat in gltfRuntime.materials) {
  1535. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1536. }
  1537. };
  1538. /**
  1539. * Implementation of the base glTF spec
  1540. */
  1541. var GLTFLoaderBase = /** @class */ (function () {
  1542. function GLTFLoaderBase() {
  1543. }
  1544. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1545. var gltfRuntime = {
  1546. extensions: {},
  1547. accessors: {},
  1548. buffers: {},
  1549. bufferViews: {},
  1550. meshes: {},
  1551. lights: {},
  1552. cameras: {},
  1553. nodes: {},
  1554. images: {},
  1555. textures: {},
  1556. shaders: {},
  1557. programs: {},
  1558. samplers: {},
  1559. techniques: {},
  1560. materials: {},
  1561. animations: {},
  1562. skins: {},
  1563. extensionsUsed: [],
  1564. scenes: {},
  1565. buffersCount: 0,
  1566. shaderscount: 0,
  1567. scene: scene,
  1568. rootUrl: rootUrl,
  1569. loadedBufferCount: 0,
  1570. loadedBufferViews: {},
  1571. loadedShaderCount: 0,
  1572. importOnlyMeshes: false,
  1573. dummyNodes: []
  1574. };
  1575. // Parse
  1576. if (parsedData.extensions) {
  1577. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1578. }
  1579. if (parsedData.extensionsUsed) {
  1580. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1581. }
  1582. if (parsedData.buffers) {
  1583. parseBuffers(parsedData.buffers, gltfRuntime);
  1584. }
  1585. if (parsedData.bufferViews) {
  1586. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1587. }
  1588. if (parsedData.accessors) {
  1589. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1590. }
  1591. if (parsedData.meshes) {
  1592. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1593. }
  1594. if (parsedData.lights) {
  1595. parseObject(parsedData.lights, "lights", gltfRuntime);
  1596. }
  1597. if (parsedData.cameras) {
  1598. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1599. }
  1600. if (parsedData.nodes) {
  1601. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1602. }
  1603. if (parsedData.images) {
  1604. parseObject(parsedData.images, "images", gltfRuntime);
  1605. }
  1606. if (parsedData.textures) {
  1607. parseObject(parsedData.textures, "textures", gltfRuntime);
  1608. }
  1609. if (parsedData.shaders) {
  1610. parseShaders(parsedData.shaders, gltfRuntime);
  1611. }
  1612. if (parsedData.programs) {
  1613. parseObject(parsedData.programs, "programs", gltfRuntime);
  1614. }
  1615. if (parsedData.samplers) {
  1616. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1617. }
  1618. if (parsedData.techniques) {
  1619. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1620. }
  1621. if (parsedData.materials) {
  1622. parseObject(parsedData.materials, "materials", gltfRuntime);
  1623. }
  1624. if (parsedData.animations) {
  1625. parseObject(parsedData.animations, "animations", gltfRuntime);
  1626. }
  1627. if (parsedData.skins) {
  1628. parseObject(parsedData.skins, "skins", gltfRuntime);
  1629. }
  1630. if (parsedData.scenes) {
  1631. gltfRuntime.scenes = parsedData.scenes;
  1632. }
  1633. if (parsedData.scene && parsedData.scenes) {
  1634. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1635. }
  1636. return gltfRuntime;
  1637. };
  1638. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1639. var buffer = gltfRuntime.buffers[id];
  1640. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1641. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1642. }
  1643. else {
  1644. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1645. if (request) {
  1646. onError(request.status + " " + request.statusText);
  1647. }
  1648. });
  1649. }
  1650. };
  1651. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1652. var texture = gltfRuntime.textures[id];
  1653. if (!texture || !texture.source) {
  1654. onError("");
  1655. return;
  1656. }
  1657. if (texture.babylonTexture) {
  1658. onSuccess(null);
  1659. return;
  1660. }
  1661. var source = gltfRuntime.images[texture.source];
  1662. if (BABYLON.Tools.IsBase64(source.uri)) {
  1663. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1664. }
  1665. else {
  1666. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1667. if (request) {
  1668. onError(request.status + " " + request.statusText);
  1669. }
  1670. });
  1671. }
  1672. };
  1673. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1674. var texture = gltfRuntime.textures[id];
  1675. if (texture.babylonTexture) {
  1676. onSuccess(texture.babylonTexture);
  1677. return;
  1678. }
  1679. var sampler = gltfRuntime.samplers[texture.sampler];
  1680. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1681. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1682. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1683. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1684. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1685. var blob = new Blob([buffer]);
  1686. var blobURL = URL.createObjectURL(blob);
  1687. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1688. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1689. if (sampler.wrapS !== undefined) {
  1690. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1691. }
  1692. if (sampler.wrapT !== undefined) {
  1693. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1694. }
  1695. newTexture.name = id;
  1696. texture.babylonTexture = newTexture;
  1697. onSuccess(newTexture);
  1698. };
  1699. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1700. var shader = gltfRuntime.shaders[id];
  1701. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1702. var shaderString = atob(shader.uri.split(",")[1]);
  1703. if (onSuccess) {
  1704. onSuccess(shaderString);
  1705. }
  1706. }
  1707. else {
  1708. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1709. if (request && onError) {
  1710. onError(request.status + " " + request.statusText);
  1711. }
  1712. });
  1713. }
  1714. };
  1715. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1716. var material = gltfRuntime.materials[id];
  1717. if (!material.technique) {
  1718. if (onError) {
  1719. onError("No technique found.");
  1720. }
  1721. return;
  1722. }
  1723. var technique = gltfRuntime.techniques[material.technique];
  1724. if (!technique) {
  1725. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1726. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1727. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1728. onSuccess(defaultMaterial);
  1729. return;
  1730. }
  1731. var program = gltfRuntime.programs[technique.program];
  1732. var states = technique.states;
  1733. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1734. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1735. var newVertexShader = "";
  1736. var newPixelShader = "";
  1737. var vertexTokenizer = new Tokenizer(vertexShader);
  1738. var pixelTokenizer = new Tokenizer(pixelShader);
  1739. var unTreatedUniforms = {};
  1740. var uniforms = [];
  1741. var attributes = [];
  1742. var samplers = [];
  1743. // Fill uniform, sampler2D and attributes
  1744. for (var unif in technique.uniforms) {
  1745. var uniform = technique.uniforms[unif];
  1746. var uniformParameter = technique.parameters[uniform];
  1747. unTreatedUniforms[unif] = uniformParameter;
  1748. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1749. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1750. if (transformIndex !== -1) {
  1751. uniforms.push(babylonTransforms[transformIndex]);
  1752. delete unTreatedUniforms[unif];
  1753. }
  1754. else {
  1755. uniforms.push(unif);
  1756. }
  1757. }
  1758. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1759. samplers.push(unif);
  1760. }
  1761. else {
  1762. uniforms.push(unif);
  1763. }
  1764. }
  1765. for (var attr in technique.attributes) {
  1766. var attribute = technique.attributes[attr];
  1767. var attributeParameter = technique.parameters[attribute];
  1768. if (attributeParameter.semantic) {
  1769. attributes.push(getAttribute(attributeParameter));
  1770. }
  1771. }
  1772. // Configure vertex shader
  1773. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1774. var tokenType = vertexTokenizer.currentToken;
  1775. if (tokenType !== ETokenType.IDENTIFIER) {
  1776. newVertexShader += vertexTokenizer.currentString;
  1777. continue;
  1778. }
  1779. var foundAttribute = false;
  1780. for (var attr in technique.attributes) {
  1781. var attribute = technique.attributes[attr];
  1782. var attributeParameter = technique.parameters[attribute];
  1783. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1784. newVertexShader += getAttribute(attributeParameter);
  1785. foundAttribute = true;
  1786. break;
  1787. }
  1788. }
  1789. if (foundAttribute) {
  1790. continue;
  1791. }
  1792. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1793. }
  1794. // Configure pixel shader
  1795. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1796. var tokenType = pixelTokenizer.currentToken;
  1797. if (tokenType !== ETokenType.IDENTIFIER) {
  1798. newPixelShader += pixelTokenizer.currentString;
  1799. continue;
  1800. }
  1801. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1802. }
  1803. // Create shader material
  1804. var shaderPath = {
  1805. vertex: program.vertexShader + id,
  1806. fragment: program.fragmentShader + id
  1807. };
  1808. var options = {
  1809. attributes: attributes,
  1810. uniforms: uniforms,
  1811. samplers: samplers,
  1812. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1813. };
  1814. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1815. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1816. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1817. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1818. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1819. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1820. if (states && states.functions) {
  1821. var functions = states.functions;
  1822. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1823. shaderMaterial.backFaceCulling = false;
  1824. }
  1825. var blendFunc = functions.blendFuncSeparate;
  1826. if (blendFunc) {
  1827. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1828. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1829. }
  1830. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1831. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1832. }
  1833. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1834. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1835. }
  1836. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1837. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1838. }
  1839. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1840. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1841. }
  1842. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1843. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1844. }
  1845. }
  1846. }
  1847. };
  1848. return GLTFLoaderBase;
  1849. }());
  1850. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1851. /**
  1852. * glTF V1 Loader
  1853. */
  1854. var GLTFLoader = /** @class */ (function () {
  1855. function GLTFLoader() {
  1856. // #region Stubs for IGLTFLoader interface
  1857. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1858. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1859. this.compileMaterials = false;
  1860. this.useClipPlane = false;
  1861. this.compileShadowGenerators = false;
  1862. this.onDisposeObservable = new BABYLON.Observable();
  1863. this.onMeshLoadedObservable = new BABYLON.Observable();
  1864. this.onTextureLoadedObservable = new BABYLON.Observable();
  1865. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1866. this.onCompleteObservable = new BABYLON.Observable();
  1867. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1868. this.state = null;
  1869. }
  1870. GLTFLoader.RegisterExtension = function (extension) {
  1871. if (GLTFLoader.Extensions[extension.name]) {
  1872. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1873. return;
  1874. }
  1875. GLTFLoader.Extensions[extension.name] = extension;
  1876. };
  1877. GLTFLoader.prototype.dispose = function () { };
  1878. // #endregion
  1879. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1880. var _this = this;
  1881. scene.useRightHandedSystem = true;
  1882. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1883. gltfRuntime.importOnlyMeshes = true;
  1884. if (meshesNames === "") {
  1885. gltfRuntime.importMeshesNames = [];
  1886. }
  1887. else if (typeof meshesNames === "string") {
  1888. gltfRuntime.importMeshesNames = [meshesNames];
  1889. }
  1890. else if (meshesNames && !(meshesNames instanceof Array)) {
  1891. gltfRuntime.importMeshesNames = [meshesNames];
  1892. }
  1893. else {
  1894. gltfRuntime.importMeshesNames = [];
  1895. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1896. }
  1897. // Create nodes
  1898. _this._createNodes(gltfRuntime);
  1899. var meshes = new Array();
  1900. var skeletons = new Array();
  1901. // Fill arrays of meshes and skeletons
  1902. for (var nde in gltfRuntime.nodes) {
  1903. var node = gltfRuntime.nodes[nde];
  1904. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1905. meshes.push(node.babylonNode);
  1906. }
  1907. }
  1908. for (var skl in gltfRuntime.skins) {
  1909. var skin = gltfRuntime.skins[skl];
  1910. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1911. skeletons.push(skin.babylonSkeleton);
  1912. }
  1913. }
  1914. // Load buffers, shaders, materials, etc.
  1915. _this._loadBuffersAsync(gltfRuntime, function () {
  1916. _this._loadShadersAsync(gltfRuntime, function () {
  1917. importMaterials(gltfRuntime);
  1918. postLoad(gltfRuntime);
  1919. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1920. onSuccess(meshes, skeletons);
  1921. }
  1922. });
  1923. }, onProgress);
  1924. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1925. onSuccess(meshes, skeletons);
  1926. }
  1927. }, onError);
  1928. return true;
  1929. };
  1930. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1931. var _this = this;
  1932. return new Promise(function (resolve, reject) {
  1933. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  1934. resolve({
  1935. meshes: meshes,
  1936. particleSystems: [],
  1937. skeletons: skeletons,
  1938. animationGroups: []
  1939. });
  1940. }, onProgress, function (message) {
  1941. reject(new Error(message));
  1942. });
  1943. });
  1944. };
  1945. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1946. var _this = this;
  1947. scene.useRightHandedSystem = true;
  1948. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1949. // Load runtime extensios
  1950. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1951. // Create nodes
  1952. _this._createNodes(gltfRuntime);
  1953. // Load buffers, shaders, materials, etc.
  1954. _this._loadBuffersAsync(gltfRuntime, function () {
  1955. _this._loadShadersAsync(gltfRuntime, function () {
  1956. importMaterials(gltfRuntime);
  1957. postLoad(gltfRuntime);
  1958. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1959. onSuccess();
  1960. }
  1961. });
  1962. });
  1963. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1964. onSuccess();
  1965. }
  1966. }, onError);
  1967. }, onError);
  1968. };
  1969. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1970. var _this = this;
  1971. return new Promise(function (resolve, reject) {
  1972. _this._loadAsync(scene, data, rootUrl, function () {
  1973. resolve();
  1974. }, onProgress, function (message) {
  1975. reject(new Error(message));
  1976. });
  1977. });
  1978. };
  1979. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1980. var hasShaders = false;
  1981. var processShader = function (sha, shader) {
  1982. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1983. if (shaderString instanceof ArrayBuffer) {
  1984. return;
  1985. }
  1986. gltfRuntime.loadedShaderCount++;
  1987. if (shaderString) {
  1988. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1989. }
  1990. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1991. onload();
  1992. }
  1993. }, function () {
  1994. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1995. });
  1996. };
  1997. for (var sha in gltfRuntime.shaders) {
  1998. hasShaders = true;
  1999. var shader = gltfRuntime.shaders[sha];
  2000. if (shader) {
  2001. processShader.bind(this, sha, shader)();
  2002. }
  2003. else {
  2004. BABYLON.Tools.Error("No shader named: " + sha);
  2005. }
  2006. }
  2007. if (!hasShaders) {
  2008. onload();
  2009. }
  2010. };
  2011. ;
  2012. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2013. var hasBuffers = false;
  2014. var processBuffer = function (buf, buffer) {
  2015. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2016. gltfRuntime.loadedBufferCount++;
  2017. if (bufferView) {
  2018. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2019. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2020. }
  2021. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2022. }
  2023. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2024. onLoad();
  2025. }
  2026. }, function () {
  2027. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2028. });
  2029. };
  2030. for (var buf in gltfRuntime.buffers) {
  2031. hasBuffers = true;
  2032. var buffer = gltfRuntime.buffers[buf];
  2033. if (buffer) {
  2034. processBuffer.bind(this, buf, buffer)();
  2035. }
  2036. else {
  2037. BABYLON.Tools.Error("No buffer named: " + buf);
  2038. }
  2039. }
  2040. if (!hasBuffers) {
  2041. onLoad();
  2042. }
  2043. };
  2044. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2045. var currentScene = gltfRuntime.currentScene;
  2046. if (currentScene) {
  2047. // Only one scene even if multiple scenes are defined
  2048. for (var i = 0; i < currentScene.nodes.length; i++) {
  2049. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2050. }
  2051. }
  2052. else {
  2053. // Load all scenes
  2054. for (var thing in gltfRuntime.scenes) {
  2055. currentScene = gltfRuntime.scenes[thing];
  2056. for (var i = 0; i < currentScene.nodes.length; i++) {
  2057. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2058. }
  2059. }
  2060. }
  2061. };
  2062. GLTFLoader.Extensions = {};
  2063. return GLTFLoader;
  2064. }());
  2065. GLTF1.GLTFLoader = GLTFLoader;
  2066. ;
  2067. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2068. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2069. })(BABYLON || (BABYLON = {}));
  2070. //# sourceMappingURL=babylon.glTFLoader.js.map
  2071. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2072. var BABYLON;
  2073. (function (BABYLON) {
  2074. var GLTF1;
  2075. (function (GLTF1) {
  2076. /**
  2077. * Utils functions for GLTF
  2078. */
  2079. var GLTFUtils = /** @class */ (function () {
  2080. function GLTFUtils() {
  2081. }
  2082. /**
  2083. * Sets the given "parameter" matrix
  2084. * @param scene: the {BABYLON.Scene} object
  2085. * @param source: the source node where to pick the matrix
  2086. * @param parameter: the GLTF technique parameter
  2087. * @param uniformName: the name of the shader's uniform
  2088. * @param shaderMaterial: the shader material
  2089. */
  2090. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2091. var mat = null;
  2092. if (parameter.semantic === "MODEL") {
  2093. mat = source.getWorldMatrix();
  2094. }
  2095. else if (parameter.semantic === "PROJECTION") {
  2096. mat = scene.getProjectionMatrix();
  2097. }
  2098. else if (parameter.semantic === "VIEW") {
  2099. mat = scene.getViewMatrix();
  2100. }
  2101. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2102. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2103. }
  2104. else if (parameter.semantic === "MODELVIEW") {
  2105. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2106. }
  2107. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2108. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2109. }
  2110. else if (parameter.semantic === "MODELINVERSE") {
  2111. mat = source.getWorldMatrix().invert();
  2112. }
  2113. else if (parameter.semantic === "VIEWINVERSE") {
  2114. mat = scene.getViewMatrix().invert();
  2115. }
  2116. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2117. mat = scene.getProjectionMatrix().invert();
  2118. }
  2119. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2120. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2121. }
  2122. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2123. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2124. }
  2125. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2126. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2127. }
  2128. else {
  2129. debugger;
  2130. }
  2131. if (mat) {
  2132. switch (parameter.type) {
  2133. case GLTF1.EParameterType.FLOAT_MAT2:
  2134. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2135. break;
  2136. case GLTF1.EParameterType.FLOAT_MAT3:
  2137. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2138. break;
  2139. case GLTF1.EParameterType.FLOAT_MAT4:
  2140. shaderMaterial.setMatrix(uniformName, mat);
  2141. break;
  2142. default: break;
  2143. }
  2144. }
  2145. };
  2146. /**
  2147. * Sets the given "parameter" matrix
  2148. * @param shaderMaterial: the shader material
  2149. * @param uniform: the name of the shader's uniform
  2150. * @param value: the value of the uniform
  2151. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2152. */
  2153. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2154. switch (type) {
  2155. case GLTF1.EParameterType.FLOAT:
  2156. shaderMaterial.setFloat(uniform, value);
  2157. return true;
  2158. case GLTF1.EParameterType.FLOAT_VEC2:
  2159. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2160. return true;
  2161. case GLTF1.EParameterType.FLOAT_VEC3:
  2162. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2163. return true;
  2164. case GLTF1.EParameterType.FLOAT_VEC4:
  2165. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2166. return true;
  2167. default: return false;
  2168. }
  2169. };
  2170. /**
  2171. * Returns the wrap mode of the texture
  2172. * @param mode: the mode value
  2173. */
  2174. GLTFUtils.GetWrapMode = function (mode) {
  2175. switch (mode) {
  2176. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2177. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2178. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2179. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2180. }
  2181. };
  2182. /**
  2183. * Returns the byte stride giving an accessor
  2184. * @param accessor: the GLTF accessor objet
  2185. */
  2186. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2187. // Needs this function since "byteStride" isn't requiered in glTF format
  2188. var type = accessor.type;
  2189. switch (type) {
  2190. case "VEC2": return 2;
  2191. case "VEC3": return 3;
  2192. case "VEC4": return 4;
  2193. case "MAT2": return 4;
  2194. case "MAT3": return 9;
  2195. case "MAT4": return 16;
  2196. default: return 1;
  2197. }
  2198. };
  2199. /**
  2200. * Returns the texture filter mode giving a mode value
  2201. * @param mode: the filter mode value
  2202. */
  2203. GLTFUtils.GetTextureFilterMode = function (mode) {
  2204. switch (mode) {
  2205. case GLTF1.ETextureFilterType.LINEAR:
  2206. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2207. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2208. case GLTF1.ETextureFilterType.NEAREST:
  2209. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2210. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2211. }
  2212. };
  2213. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2214. var byteOffset = bufferView.byteOffset + byteOffset;
  2215. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2216. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2217. throw new Error("Buffer access is out of range");
  2218. }
  2219. var buffer = loadedBufferView.buffer;
  2220. byteOffset += loadedBufferView.byteOffset;
  2221. switch (componentType) {
  2222. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2223. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2224. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2225. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2226. default: return new Float32Array(buffer, byteOffset, byteLength);
  2227. }
  2228. };
  2229. /**
  2230. * Returns a buffer from its accessor
  2231. * @param gltfRuntime: the GLTF runtime
  2232. * @param accessor: the GLTF accessor
  2233. */
  2234. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2235. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2236. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2237. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2238. };
  2239. /**
  2240. * Decodes a buffer view into a string
  2241. * @param view: the buffer view
  2242. */
  2243. GLTFUtils.DecodeBufferToText = function (view) {
  2244. var result = "";
  2245. var length = view.byteLength;
  2246. for (var i = 0; i < length; ++i) {
  2247. result += String.fromCharCode(view[i]);
  2248. }
  2249. return result;
  2250. };
  2251. /**
  2252. * Returns the default material of gltf. Related to
  2253. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2254. * @param scene: the Babylon.js scene
  2255. */
  2256. GLTFUtils.GetDefaultMaterial = function (scene) {
  2257. if (!GLTFUtils._DefaultMaterial) {
  2258. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2259. "precision highp float;",
  2260. "",
  2261. "uniform mat4 worldView;",
  2262. "uniform mat4 projection;",
  2263. "",
  2264. "attribute vec3 position;",
  2265. "",
  2266. "void main(void)",
  2267. "{",
  2268. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2269. "}"
  2270. ].join("\n");
  2271. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2272. "precision highp float;",
  2273. "",
  2274. "uniform vec4 u_emission;",
  2275. "",
  2276. "void main(void)",
  2277. "{",
  2278. " gl_FragColor = u_emission;",
  2279. "}"
  2280. ].join("\n");
  2281. var shaderPath = {
  2282. vertex: "GLTFDefaultMaterial",
  2283. fragment: "GLTFDefaultMaterial"
  2284. };
  2285. var options = {
  2286. attributes: ["position"],
  2287. uniforms: ["worldView", "projection", "u_emission"],
  2288. samplers: new Array(),
  2289. needAlphaBlending: false
  2290. };
  2291. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2292. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2293. }
  2294. return GLTFUtils._DefaultMaterial;
  2295. };
  2296. // The GLTF default material
  2297. GLTFUtils._DefaultMaterial = null;
  2298. return GLTFUtils;
  2299. }());
  2300. GLTF1.GLTFUtils = GLTFUtils;
  2301. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2302. })(BABYLON || (BABYLON = {}));
  2303. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2304. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2305. var BABYLON;
  2306. (function (BABYLON) {
  2307. var GLTF1;
  2308. (function (GLTF1) {
  2309. var GLTFLoaderExtension = /** @class */ (function () {
  2310. function GLTFLoaderExtension(name) {
  2311. this._name = name;
  2312. }
  2313. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2314. get: function () {
  2315. return this._name;
  2316. },
  2317. enumerable: true,
  2318. configurable: true
  2319. });
  2320. /**
  2321. * Defines an override for loading the runtime
  2322. * Return true to stop further extensions from loading the runtime
  2323. */
  2324. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2325. return false;
  2326. };
  2327. /**
  2328. * Defines an onverride for creating gltf runtime
  2329. * Return true to stop further extensions from creating the runtime
  2330. */
  2331. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2332. return false;
  2333. };
  2334. /**
  2335. * Defines an override for loading buffers
  2336. * Return true to stop further extensions from loading this buffer
  2337. */
  2338. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2339. return false;
  2340. };
  2341. /**
  2342. * Defines an override for loading texture buffers
  2343. * Return true to stop further extensions from loading this texture data
  2344. */
  2345. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2346. return false;
  2347. };
  2348. /**
  2349. * Defines an override for creating textures
  2350. * Return true to stop further extensions from loading this texture
  2351. */
  2352. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2353. return false;
  2354. };
  2355. /**
  2356. * Defines an override for loading shader strings
  2357. * Return true to stop further extensions from loading this shader data
  2358. */
  2359. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2360. return false;
  2361. };
  2362. /**
  2363. * Defines an override for loading materials
  2364. * Return true to stop further extensions from loading this material
  2365. */
  2366. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2367. return false;
  2368. };
  2369. // ---------
  2370. // Utilities
  2371. // ---------
  2372. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2373. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2374. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2375. }, function () {
  2376. setTimeout(function () {
  2377. if (!onSuccess) {
  2378. return;
  2379. }
  2380. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2381. });
  2382. });
  2383. };
  2384. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2385. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2386. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2387. }, function () {
  2388. setTimeout(function () {
  2389. onSuccess();
  2390. });
  2391. });
  2392. };
  2393. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2394. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2395. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2396. }, function () {
  2397. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2398. });
  2399. };
  2400. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2401. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2402. if (buffer) {
  2403. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2404. }
  2405. }, onError);
  2406. };
  2407. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2408. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2409. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2410. }, function () {
  2411. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2412. });
  2413. };
  2414. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2415. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2416. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2417. }, function () {
  2418. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2419. });
  2420. };
  2421. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2422. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2423. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2424. }, function () {
  2425. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2426. });
  2427. };
  2428. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2429. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2430. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2431. }, function () {
  2432. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2433. });
  2434. };
  2435. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2436. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2437. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2438. if (func(loaderExtension)) {
  2439. return;
  2440. }
  2441. }
  2442. defaultFunc();
  2443. };
  2444. return GLTFLoaderExtension;
  2445. }());
  2446. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2447. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2448. })(BABYLON || (BABYLON = {}));
  2449. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2450. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2451. var __extends = (this && this.__extends) || (function () {
  2452. var extendStatics = Object.setPrototypeOf ||
  2453. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2454. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2455. return function (d, b) {
  2456. extendStatics(d, b);
  2457. function __() { this.constructor = d; }
  2458. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2459. };
  2460. })();
  2461. var BABYLON;
  2462. (function (BABYLON) {
  2463. var GLTF1;
  2464. (function (GLTF1) {
  2465. var BinaryExtensionBufferName = "binary_glTF";
  2466. ;
  2467. ;
  2468. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2469. __extends(GLTFBinaryExtension, _super);
  2470. function GLTFBinaryExtension() {
  2471. return _super.call(this, "KHR_binary_glTF") || this;
  2472. }
  2473. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2474. var extensionsUsed = data.json.extensionsUsed;
  2475. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2476. return false;
  2477. }
  2478. this._bin = data.bin;
  2479. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2480. return true;
  2481. };
  2482. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2483. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2484. return false;
  2485. }
  2486. if (id !== BinaryExtensionBufferName) {
  2487. return false;
  2488. }
  2489. onSuccess(this._bin);
  2490. return true;
  2491. };
  2492. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2493. var texture = gltfRuntime.textures[id];
  2494. var source = gltfRuntime.images[texture.source];
  2495. if (!source.extensions || !(this.name in source.extensions)) {
  2496. return false;
  2497. }
  2498. var sourceExt = source.extensions[this.name];
  2499. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2500. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2501. onSuccess(buffer);
  2502. return true;
  2503. };
  2504. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2505. var shader = gltfRuntime.shaders[id];
  2506. if (!shader.extensions || !(this.name in shader.extensions)) {
  2507. return false;
  2508. }
  2509. var binaryExtensionShader = shader.extensions[this.name];
  2510. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2511. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2512. setTimeout(function () {
  2513. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2514. onSuccess(shaderString);
  2515. });
  2516. return true;
  2517. };
  2518. return GLTFBinaryExtension;
  2519. }(GLTF1.GLTFLoaderExtension));
  2520. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2521. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2522. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2523. })(BABYLON || (BABYLON = {}));
  2524. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2525. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2526. var __extends = (this && this.__extends) || (function () {
  2527. var extendStatics = Object.setPrototypeOf ||
  2528. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2529. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2530. return function (d, b) {
  2531. extendStatics(d, b);
  2532. function __() { this.constructor = d; }
  2533. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2534. };
  2535. })();
  2536. var BABYLON;
  2537. (function (BABYLON) {
  2538. var GLTF1;
  2539. (function (GLTF1) {
  2540. ;
  2541. ;
  2542. ;
  2543. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2544. __extends(GLTFMaterialsCommonExtension, _super);
  2545. function GLTFMaterialsCommonExtension() {
  2546. return _super.call(this, "KHR_materials_common") || this;
  2547. }
  2548. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2549. if (!gltfRuntime.extensions)
  2550. return false;
  2551. var extension = gltfRuntime.extensions[this.name];
  2552. if (!extension)
  2553. return false;
  2554. // Create lights
  2555. var lights = extension.lights;
  2556. if (lights) {
  2557. for (var thing in lights) {
  2558. var light = lights[thing];
  2559. switch (light.type) {
  2560. case "ambient":
  2561. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2562. var ambient = light.ambient;
  2563. if (ambient) {
  2564. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2565. }
  2566. break;
  2567. case "point":
  2568. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2569. var point = light.point;
  2570. if (point) {
  2571. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2572. }
  2573. break;
  2574. case "directional":
  2575. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2576. var directional = light.directional;
  2577. if (directional) {
  2578. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2579. }
  2580. break;
  2581. case "spot":
  2582. var spot = light.spot;
  2583. if (spot) {
  2584. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2585. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2586. }
  2587. break;
  2588. default:
  2589. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2590. break;
  2591. }
  2592. }
  2593. }
  2594. return false;
  2595. };
  2596. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2597. var material = gltfRuntime.materials[id];
  2598. if (!material || !material.extensions)
  2599. return false;
  2600. var extension = material.extensions[this.name];
  2601. if (!extension)
  2602. return false;
  2603. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2604. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2605. if (extension.technique === "CONSTANT") {
  2606. standardMaterial.disableLighting = true;
  2607. }
  2608. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2609. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2610. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2611. // Ambient
  2612. if (typeof extension.values.ambient === "string") {
  2613. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2614. }
  2615. else {
  2616. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2617. }
  2618. // Diffuse
  2619. if (typeof extension.values.diffuse === "string") {
  2620. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2621. }
  2622. else {
  2623. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2624. }
  2625. // Emission
  2626. if (typeof extension.values.emission === "string") {
  2627. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2628. }
  2629. else {
  2630. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2631. }
  2632. // Specular
  2633. if (typeof extension.values.specular === "string") {
  2634. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2635. }
  2636. else {
  2637. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2638. }
  2639. return true;
  2640. };
  2641. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2642. // Create buffer from texture url
  2643. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2644. // Create texture from buffer
  2645. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2646. }, onError);
  2647. };
  2648. return GLTFMaterialsCommonExtension;
  2649. }(GLTF1.GLTFLoaderExtension));
  2650. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2651. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2652. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2653. })(BABYLON || (BABYLON = {}));
  2654. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2655. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2656. var BABYLON;
  2657. (function (BABYLON) {
  2658. var GLTF2;
  2659. (function (GLTF2) {
  2660. var ArrayItem = /** @class */ (function () {
  2661. function ArrayItem() {
  2662. }
  2663. ArrayItem.Assign = function (values) {
  2664. if (values) {
  2665. for (var index = 0; index < values.length; index++) {
  2666. values[index]._index = index;
  2667. }
  2668. }
  2669. };
  2670. return ArrayItem;
  2671. }());
  2672. GLTF2.ArrayItem = ArrayItem;
  2673. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2674. })(BABYLON || (BABYLON = {}));
  2675. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  2676. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2677. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2678. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2679. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2680. var BABYLON;
  2681. (function (BABYLON) {
  2682. var GLTF2;
  2683. (function (GLTF2) {
  2684. var GLTFLoader = /** @class */ (function () {
  2685. function GLTFLoader() {
  2686. this._completePromises = new Array();
  2687. this._disposed = false;
  2688. this._state = null;
  2689. this._extensions = {};
  2690. this._defaultSampler = {};
  2691. this._defaultBabylonMaterials = {};
  2692. this._requests = new Array();
  2693. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2694. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2695. this.compileMaterials = false;
  2696. this.useClipPlane = false;
  2697. this.compileShadowGenerators = false;
  2698. this.onDisposeObservable = new BABYLON.Observable();
  2699. this.onMeshLoadedObservable = new BABYLON.Observable();
  2700. this.onTextureLoadedObservable = new BABYLON.Observable();
  2701. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2702. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2703. this.onCompleteObservable = new BABYLON.Observable();
  2704. }
  2705. GLTFLoader._Register = function (name, factory) {
  2706. if (GLTFLoader._Factories[name]) {
  2707. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  2708. return;
  2709. }
  2710. GLTFLoader._Factories[name] = factory;
  2711. // Keep the order of registration so that extensions registered first are called first.
  2712. GLTFLoader._Names.push(name);
  2713. };
  2714. Object.defineProperty(GLTFLoader.prototype, "state", {
  2715. get: function () {
  2716. return this._state;
  2717. },
  2718. enumerable: true,
  2719. configurable: true
  2720. });
  2721. GLTFLoader.prototype.dispose = function () {
  2722. if (this._disposed) {
  2723. return;
  2724. }
  2725. this._disposed = true;
  2726. this.onDisposeObservable.notifyObservers(this);
  2727. this.onDisposeObservable.clear();
  2728. this._clear();
  2729. };
  2730. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2731. var _this = this;
  2732. return Promise.resolve().then(function () {
  2733. var nodes = null;
  2734. if (meshesNames) {
  2735. var nodeMap_1 = {};
  2736. if (_this._gltf.nodes) {
  2737. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  2738. var node = _a[_i];
  2739. if (node.name) {
  2740. nodeMap_1[node.name] = node;
  2741. }
  2742. }
  2743. }
  2744. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  2745. nodes = names.map(function (name) {
  2746. var node = nodeMap_1[name];
  2747. if (!node) {
  2748. throw new Error("Failed to find node '" + name + "'");
  2749. }
  2750. return node;
  2751. });
  2752. }
  2753. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  2754. return {
  2755. meshes: _this._getMeshes(),
  2756. particleSystems: [],
  2757. skeletons: _this._getSkeletons(),
  2758. animationGroups: _this._getAnimationGroups()
  2759. };
  2760. });
  2761. });
  2762. };
  2763. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2764. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  2765. };
  2766. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  2767. var _this = this;
  2768. return Promise.resolve().then(function () {
  2769. _this._loadExtensions();
  2770. _this._babylonScene = scene;
  2771. _this._rootUrl = rootUrl;
  2772. _this._progressCallback = onProgress;
  2773. _this._state = BABYLON.GLTFLoaderState.LOADING;
  2774. _this._loadData(data);
  2775. _this._checkExtensions();
  2776. var promises = new Array();
  2777. if (nodes) {
  2778. promises.push(_this._loadNodesAsync(nodes));
  2779. }
  2780. else {
  2781. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  2782. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  2783. }
  2784. if (_this.compileMaterials) {
  2785. promises.push(_this._compileMaterialsAsync());
  2786. }
  2787. if (_this.compileShadowGenerators) {
  2788. promises.push(_this._compileShadowGeneratorsAsync());
  2789. }
  2790. var resultPromise = Promise.all(promises).then(function () {
  2791. _this._state = BABYLON.GLTFLoaderState.READY;
  2792. _this._startAnimations();
  2793. });
  2794. resultPromise.then(function () {
  2795. _this._rootBabylonMesh.setEnabled(true);
  2796. BABYLON.Tools.SetImmediate(function () {
  2797. if (!_this._disposed) {
  2798. Promise.all(_this._completePromises).then(function () {
  2799. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  2800. _this.onCompleteObservable.notifyObservers(_this);
  2801. _this.onCompleteObservable.clear();
  2802. _this._clear();
  2803. }).catch(function (error) {
  2804. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2805. _this._clear();
  2806. });
  2807. }
  2808. });
  2809. });
  2810. return resultPromise;
  2811. }).catch(function (error) {
  2812. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2813. _this._clear();
  2814. throw error;
  2815. });
  2816. };
  2817. GLTFLoader.prototype._loadExtensions = function () {
  2818. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2819. var name_1 = _a[_i];
  2820. var extension = GLTFLoader._Factories[name_1](this);
  2821. this._extensions[name_1] = extension;
  2822. this.onExtensionLoadedObservable.notifyObservers(extension);
  2823. }
  2824. this.onExtensionLoadedObservable.clear();
  2825. };
  2826. GLTFLoader.prototype._loadData = function (data) {
  2827. this._gltf = data.json;
  2828. this._setupData();
  2829. if (data.bin) {
  2830. var buffers = this._gltf.buffers;
  2831. if (buffers && buffers[0] && !buffers[0].uri) {
  2832. var binaryBuffer = buffers[0];
  2833. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  2834. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  2835. }
  2836. binaryBuffer._data = Promise.resolve(data.bin);
  2837. }
  2838. else {
  2839. BABYLON.Tools.Warn("Unexpected BIN chunk");
  2840. }
  2841. }
  2842. };
  2843. GLTFLoader.prototype._setupData = function () {
  2844. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  2845. GLTF2.ArrayItem.Assign(this._gltf.animations);
  2846. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  2847. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  2848. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  2849. GLTF2.ArrayItem.Assign(this._gltf.images);
  2850. GLTF2.ArrayItem.Assign(this._gltf.materials);
  2851. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  2852. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  2853. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  2854. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  2855. GLTF2.ArrayItem.Assign(this._gltf.skins);
  2856. GLTF2.ArrayItem.Assign(this._gltf.textures);
  2857. if (this._gltf.nodes) {
  2858. var nodeParents = {};
  2859. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  2860. var node = _a[_i];
  2861. if (node.children) {
  2862. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  2863. var index = _c[_b];
  2864. nodeParents[index] = node._index;
  2865. }
  2866. }
  2867. }
  2868. var rootNode = this._createRootNode();
  2869. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  2870. var node = _e[_d];
  2871. var parentIndex = nodeParents[node._index];
  2872. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  2873. }
  2874. }
  2875. };
  2876. GLTFLoader.prototype._checkExtensions = function () {
  2877. if (this._gltf.extensionsRequired) {
  2878. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  2879. var name_2 = _a[_i];
  2880. var extension = this._extensions[name_2];
  2881. if (!extension || !extension.enabled) {
  2882. throw new Error("Require extension " + name_2 + " is not available");
  2883. }
  2884. }
  2885. }
  2886. };
  2887. GLTFLoader.prototype._createRootNode = function () {
  2888. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  2889. this._rootBabylonMesh.setEnabled(false);
  2890. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  2891. switch (this.coordinateSystemMode) {
  2892. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  2893. if (!this._babylonScene.useRightHandedSystem) {
  2894. rootNode.rotation = [0, 1, 0, 0];
  2895. rootNode.scale = [1, 1, -1];
  2896. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  2897. }
  2898. break;
  2899. }
  2900. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  2901. this._babylonScene.useRightHandedSystem = true;
  2902. break;
  2903. }
  2904. default: {
  2905. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  2906. }
  2907. }
  2908. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  2909. return rootNode;
  2910. };
  2911. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  2912. var promises = new Array();
  2913. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  2914. var node = nodes_1[_i];
  2915. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2916. }
  2917. promises.push(this._loadAnimationsAsync());
  2918. return Promise.all(promises).then(function () { });
  2919. };
  2920. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  2921. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  2922. if (promise) {
  2923. return promise;
  2924. }
  2925. var promises = new Array();
  2926. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  2927. var index = _a[_i];
  2928. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  2929. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2930. }
  2931. promises.push(this._loadAnimationsAsync());
  2932. return Promise.all(promises).then(function () { });
  2933. };
  2934. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  2935. if (node._primitiveBabylonMeshes) {
  2936. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  2937. var babylonMesh = _a[_i];
  2938. callback(babylonMesh);
  2939. }
  2940. }
  2941. else {
  2942. callback(node._babylonMesh);
  2943. }
  2944. };
  2945. GLTFLoader.prototype._getMeshes = function () {
  2946. var meshes = new Array();
  2947. // Root mesh is always first.
  2948. meshes.push(this._rootBabylonMesh);
  2949. var nodes = this._gltf.nodes;
  2950. if (nodes) {
  2951. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  2952. var node = nodes_2[_i];
  2953. if (node._babylonMesh) {
  2954. meshes.push(node._babylonMesh);
  2955. }
  2956. if (node._primitiveBabylonMeshes) {
  2957. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  2958. var babylonMesh = _b[_a];
  2959. meshes.push(babylonMesh);
  2960. }
  2961. }
  2962. }
  2963. }
  2964. return meshes;
  2965. };
  2966. GLTFLoader.prototype._getSkeletons = function () {
  2967. var skeletons = new Array();
  2968. var skins = this._gltf.skins;
  2969. if (skins) {
  2970. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  2971. var skin = skins_1[_i];
  2972. if (skin._babylonSkeleton) {
  2973. skeletons.push(skin._babylonSkeleton);
  2974. }
  2975. }
  2976. }
  2977. return skeletons;
  2978. };
  2979. GLTFLoader.prototype._getAnimationGroups = function () {
  2980. var animationGroups = new Array();
  2981. var animations = this._gltf.animations;
  2982. if (animations) {
  2983. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  2984. var animation = animations_1[_i];
  2985. if (animation._babylonAnimationGroup) {
  2986. animationGroups.push(animation._babylonAnimationGroup);
  2987. }
  2988. }
  2989. }
  2990. return animationGroups;
  2991. };
  2992. GLTFLoader.prototype._startAnimations = function () {
  2993. switch (this.animationStartMode) {
  2994. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  2995. // do nothing
  2996. break;
  2997. }
  2998. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  2999. var babylonAnimationGroups = this._getAnimationGroups();
  3000. if (babylonAnimationGroups.length !== 0) {
  3001. babylonAnimationGroups[0].start(true);
  3002. }
  3003. break;
  3004. }
  3005. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  3006. var babylonAnimationGroups = this._getAnimationGroups();
  3007. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  3008. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  3009. babylonAnimationGroup.start(true);
  3010. }
  3011. break;
  3012. }
  3013. default: {
  3014. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  3015. return;
  3016. }
  3017. }
  3018. };
  3019. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  3020. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  3021. if (promise) {
  3022. return promise;
  3023. }
  3024. if (node._babylonMesh) {
  3025. throw new Error(context + ": Invalid recursive node hierarchy");
  3026. }
  3027. var promises = new Array();
  3028. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  3029. node._babylonMesh = babylonMesh;
  3030. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3031. node._babylonAnimationTargets.push(babylonMesh);
  3032. GLTFLoader._LoadTransform(node, babylonMesh);
  3033. if (node.mesh != undefined) {
  3034. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  3035. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  3036. }
  3037. if (node.children) {
  3038. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  3039. var index = _a[_i];
  3040. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  3041. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  3042. }
  3043. }
  3044. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3045. return Promise.all(promises).then(function () { });
  3046. };
  3047. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  3048. // TODO: instancing
  3049. var _this = this;
  3050. var promises = new Array();
  3051. var primitives = mesh.primitives;
  3052. if (!primitives || primitives.length === 0) {
  3053. throw new Error(context + ": Primitives are missing");
  3054. }
  3055. GLTF2.ArrayItem.Assign(primitives);
  3056. if (primitives.length === 1) {
  3057. var primitive = primitives[0];
  3058. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  3059. }
  3060. else {
  3061. node._primitiveBabylonMeshes = [];
  3062. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3063. var primitive = primitives_1[_i];
  3064. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  3065. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  3066. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  3067. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3068. }
  3069. }
  3070. if (node.skin != undefined) {
  3071. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  3072. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  3073. }
  3074. return Promise.all(promises).then(function () {
  3075. _this._forEachPrimitive(node, function (babylonMesh) {
  3076. babylonMesh._refreshBoundingInfo(true);
  3077. });
  3078. });
  3079. };
  3080. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  3081. var _this = this;
  3082. var promises = new Array();
  3083. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3084. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  3085. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  3086. babylonGeometry.applyToMesh(babylonMesh);
  3087. });
  3088. }));
  3089. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  3090. if (primitive.material == undefined) {
  3091. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  3092. }
  3093. else {
  3094. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  3095. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  3096. babylonMesh.material = babylonMaterial;
  3097. }));
  3098. }
  3099. return Promise.all(promises).then(function () { });
  3100. };
  3101. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3102. var _this = this;
  3103. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  3104. if (promise) {
  3105. return promise;
  3106. }
  3107. var attributes = primitive.attributes;
  3108. if (!attributes) {
  3109. throw new Error(context + ": Attributes are missing");
  3110. }
  3111. var promises = new Array();
  3112. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  3113. if (primitive.indices == undefined) {
  3114. babylonMesh.isUnIndexed = true;
  3115. }
  3116. else {
  3117. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3118. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3119. babylonGeometry.setIndices(data);
  3120. }));
  3121. }
  3122. var loadAttribute = function (attribute, kind, callback) {
  3123. if (attributes[attribute] == undefined) {
  3124. return;
  3125. }
  3126. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3127. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3128. babylonMesh._delayInfo.push(kind);
  3129. }
  3130. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3131. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  3132. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  3133. }));
  3134. if (callback) {
  3135. callback(accessor);
  3136. }
  3137. };
  3138. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3139. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3140. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3141. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3142. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3143. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3144. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3145. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  3146. if (accessor.type === "VEC4" /* VEC4 */) {
  3147. babylonMesh.hasVertexAlpha = true;
  3148. }
  3149. });
  3150. return Promise.all(promises).then(function () {
  3151. return babylonGeometry;
  3152. });
  3153. };
  3154. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3155. if (!primitive.targets) {
  3156. return;
  3157. }
  3158. if (node._numMorphTargets == undefined) {
  3159. node._numMorphTargets = primitive.targets.length;
  3160. }
  3161. else if (primitive.targets.length !== node._numMorphTargets) {
  3162. throw new Error(context + ": Primitives do not have the same number of targets");
  3163. }
  3164. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3165. for (var index = 0; index < primitive.targets.length; index++) {
  3166. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3167. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3168. // TODO: tell the target whether it has positions, normals, tangents
  3169. }
  3170. };
  3171. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  3172. if (!primitive.targets) {
  3173. return Promise.resolve();
  3174. }
  3175. var promises = new Array();
  3176. var morphTargetManager = babylonMesh.morphTargetManager;
  3177. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3178. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3179. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  3180. }
  3181. return Promise.all(promises).then(function () { });
  3182. };
  3183. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  3184. var _this = this;
  3185. var promises = new Array();
  3186. var loadAttribute = function (attribute, kind, setData) {
  3187. if (attributes[attribute] == undefined) {
  3188. return;
  3189. }
  3190. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  3191. if (!babylonVertexBuffer) {
  3192. return;
  3193. }
  3194. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3195. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3196. if (!(data instanceof Float32Array)) {
  3197. throw new Error(context + ": Morph target accessor must have float data");
  3198. }
  3199. setData(babylonVertexBuffer, data);
  3200. }));
  3201. };
  3202. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  3203. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3204. data[index] += value;
  3205. });
  3206. babylonMorphTarget.setPositions(data);
  3207. });
  3208. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  3209. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3210. data[index] += value;
  3211. });
  3212. babylonMorphTarget.setNormals(data);
  3213. });
  3214. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  3215. var dataIndex = 0;
  3216. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3217. // Tangent data for morph targets is stored as xyz delta.
  3218. // The vertexData.tangent is stored as xyzw.
  3219. // So we need to skip every fourth vertexData.tangent.
  3220. if (((index + 1) % 4) !== 0) {
  3221. data[dataIndex++] += value;
  3222. }
  3223. });
  3224. babylonMorphTarget.setTangents(data);
  3225. });
  3226. return Promise.all(promises).then(function () { });
  3227. };
  3228. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3229. var position = BABYLON.Vector3.Zero();
  3230. var rotation = BABYLON.Quaternion.Identity();
  3231. var scaling = BABYLON.Vector3.One();
  3232. if (node.matrix) {
  3233. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3234. matrix.decompose(scaling, rotation, position);
  3235. }
  3236. else {
  3237. if (node.translation)
  3238. position = BABYLON.Vector3.FromArray(node.translation);
  3239. if (node.rotation)
  3240. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3241. if (node.scale)
  3242. scaling = BABYLON.Vector3.FromArray(node.scale);
  3243. }
  3244. babylonNode.position = position;
  3245. babylonNode.rotationQuaternion = rotation;
  3246. babylonNode.scaling = scaling;
  3247. };
  3248. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  3249. var _this = this;
  3250. var assignSkeleton = function () {
  3251. _this._forEachPrimitive(node, function (babylonMesh) {
  3252. babylonMesh.skeleton = skin._babylonSkeleton;
  3253. });
  3254. // Ignore the TRS of skinned nodes.
  3255. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3256. node._babylonMesh.parent = _this._rootBabylonMesh;
  3257. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3258. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3259. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3260. };
  3261. if (skin._loaded) {
  3262. return skin._loaded.then(function () {
  3263. assignSkeleton();
  3264. });
  3265. }
  3266. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  3267. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3268. var skeletonId = "skeleton" + skin._index;
  3269. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  3270. skin._babylonSkeleton = babylonSkeleton;
  3271. _this._loadBones(context, skin, inverseBindMatricesData);
  3272. assignSkeleton();
  3273. }));
  3274. };
  3275. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3276. if (skin.inverseBindMatrices == undefined) {
  3277. return Promise.resolve(null);
  3278. }
  3279. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  3280. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3281. return data;
  3282. });
  3283. };
  3284. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3285. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3286. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3287. node._babylonAnimationTargets.push(babylonBone);
  3288. return babylonBone;
  3289. };
  3290. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  3291. var babylonBones = {};
  3292. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3293. var index = _a[_i];
  3294. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  3295. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  3296. }
  3297. };
  3298. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  3299. var babylonBone = babylonBones[node._index];
  3300. if (babylonBone) {
  3301. return babylonBone;
  3302. }
  3303. var boneIndex = skin.joints.indexOf(node._index);
  3304. var baseMatrix = BABYLON.Matrix.Identity();
  3305. if (inverseBindMatricesData && boneIndex !== -1) {
  3306. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  3307. baseMatrix.invertToRef(baseMatrix);
  3308. }
  3309. var babylonParentBone = null;
  3310. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  3311. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  3312. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3313. }
  3314. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3315. babylonBones[node._index] = babylonBone;
  3316. return babylonBone;
  3317. };
  3318. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3319. return node.matrix ?
  3320. BABYLON.Matrix.FromArray(node.matrix) :
  3321. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  3322. };
  3323. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3324. var animations = this._gltf.animations;
  3325. if (!animations) {
  3326. return Promise.resolve();
  3327. }
  3328. var promises = new Array();
  3329. for (var index = 0; index < animations.length; index++) {
  3330. var animation = animations[index];
  3331. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  3332. }
  3333. return Promise.all(promises).then(function () { });
  3334. };
  3335. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  3336. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  3337. animation._babylonAnimationGroup = babylonAnimationGroup;
  3338. var promises = new Array();
  3339. GLTF2.ArrayItem.Assign(animation.channels);
  3340. GLTF2.ArrayItem.Assign(animation.samplers);
  3341. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3342. var channel = _a[_i];
  3343. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  3344. }
  3345. return Promise.all(promises).then(function () {
  3346. babylonAnimationGroup.normalize();
  3347. });
  3348. };
  3349. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3350. var _this = this;
  3351. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  3352. if (!targetNode._babylonMesh) {
  3353. return Promise.resolve();
  3354. }
  3355. // Ignore animations targeting TRS of skinned nodes.
  3356. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3357. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  3358. return Promise.resolve();
  3359. }
  3360. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  3361. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3362. var targetPath;
  3363. var animationType;
  3364. switch (channel.target.path) {
  3365. case "translation" /* TRANSLATION */: {
  3366. targetPath = "position";
  3367. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3368. break;
  3369. }
  3370. case "rotation" /* ROTATION */: {
  3371. targetPath = "rotationQuaternion";
  3372. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3373. break;
  3374. }
  3375. case "scale" /* SCALE */: {
  3376. targetPath = "scaling";
  3377. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3378. break;
  3379. }
  3380. case "weights" /* WEIGHTS */: {
  3381. targetPath = "influence";
  3382. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3383. break;
  3384. }
  3385. default: {
  3386. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  3387. }
  3388. }
  3389. var outputBufferOffset = 0;
  3390. var getNextOutputValue;
  3391. switch (targetPath) {
  3392. case "position": {
  3393. getNextOutputValue = function () {
  3394. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3395. outputBufferOffset += 3;
  3396. return value;
  3397. };
  3398. break;
  3399. }
  3400. case "rotationQuaternion": {
  3401. getNextOutputValue = function () {
  3402. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3403. outputBufferOffset += 4;
  3404. return value;
  3405. };
  3406. break;
  3407. }
  3408. case "scaling": {
  3409. getNextOutputValue = function () {
  3410. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3411. outputBufferOffset += 3;
  3412. return value;
  3413. };
  3414. break;
  3415. }
  3416. case "influence": {
  3417. getNextOutputValue = function () {
  3418. var value = new Array(targetNode._numMorphTargets);
  3419. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3420. value[i] = data.output[outputBufferOffset++];
  3421. }
  3422. return value;
  3423. };
  3424. break;
  3425. }
  3426. }
  3427. var getNextKey;
  3428. switch (data.interpolation) {
  3429. case "STEP" /* STEP */: {
  3430. getNextKey = function (frameIndex) { return ({
  3431. frame: data.input[frameIndex],
  3432. value: getNextOutputValue(),
  3433. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3434. }); };
  3435. break;
  3436. }
  3437. case "LINEAR" /* LINEAR */: {
  3438. getNextKey = function (frameIndex) { return ({
  3439. frame: data.input[frameIndex],
  3440. value: getNextOutputValue()
  3441. }); };
  3442. break;
  3443. }
  3444. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3445. getNextKey = function (frameIndex) { return ({
  3446. frame: data.input[frameIndex],
  3447. inTangent: getNextOutputValue(),
  3448. value: getNextOutputValue(),
  3449. outTangent: getNextOutputValue()
  3450. }); };
  3451. break;
  3452. }
  3453. }
  3454. var keys = new Array(data.input.length);
  3455. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3456. keys[frameIndex] = getNextKey(frameIndex);
  3457. }
  3458. if (targetPath === "influence") {
  3459. var _loop_1 = function (targetIndex) {
  3460. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3461. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3462. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3463. frame: key.frame,
  3464. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3465. value: key.value[targetIndex],
  3466. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3467. }); }));
  3468. var morphTargets = new Array();
  3469. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  3470. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  3471. morphTarget.animations.push(babylonAnimation);
  3472. morphTargets.push(morphTarget);
  3473. });
  3474. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  3475. };
  3476. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3477. _loop_1(targetIndex);
  3478. }
  3479. }
  3480. else {
  3481. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3482. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3483. babylonAnimation.setKeys(keys);
  3484. if (targetNode._babylonAnimationTargets) {
  3485. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  3486. var babylonAnimationTarget = _a[_i];
  3487. babylonAnimationTarget.animations.push(babylonAnimation);
  3488. }
  3489. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  3490. }
  3491. }
  3492. });
  3493. };
  3494. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3495. if (sampler._data) {
  3496. return sampler._data;
  3497. }
  3498. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3499. switch (interpolation) {
  3500. case "STEP" /* STEP */:
  3501. case "LINEAR" /* LINEAR */:
  3502. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3503. break;
  3504. }
  3505. default: {
  3506. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  3507. }
  3508. }
  3509. var inputData;
  3510. var outputData;
  3511. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  3512. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  3513. sampler._data = Promise.all([
  3514. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  3515. inputData = data;
  3516. }),
  3517. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  3518. outputData = data;
  3519. })
  3520. ]).then(function () {
  3521. return {
  3522. input: inputData,
  3523. interpolation: interpolation,
  3524. output: outputData,
  3525. };
  3526. });
  3527. return sampler._data;
  3528. };
  3529. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  3530. if (buffer._data) {
  3531. return buffer._data;
  3532. }
  3533. if (!buffer.uri) {
  3534. throw new Error(context + ": Uri is missing");
  3535. }
  3536. buffer._data = this._loadUriAsync(context, buffer.uri);
  3537. return buffer._data;
  3538. };
  3539. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  3540. if (bufferView._data) {
  3541. return bufferView._data;
  3542. }
  3543. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  3544. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  3545. try {
  3546. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  3547. }
  3548. catch (e) {
  3549. throw new Error(context + ": " + e.message);
  3550. }
  3551. });
  3552. return bufferView._data;
  3553. };
  3554. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  3555. if (accessor.sparse) {
  3556. throw new Error(context + ": Sparse accessors are not currently supported");
  3557. }
  3558. if (accessor._data) {
  3559. return accessor._data;
  3560. }
  3561. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3562. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  3563. var buffer = data.buffer;
  3564. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  3565. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  3566. try {
  3567. switch (accessor.componentType) {
  3568. case 5120 /* BYTE */: {
  3569. return new Int8Array(buffer, byteOffset, length);
  3570. }
  3571. case 5121 /* UNSIGNED_BYTE */: {
  3572. return new Uint8Array(buffer, byteOffset, length);
  3573. }
  3574. case 5122 /* SHORT */: {
  3575. return new Int16Array(buffer, byteOffset, length);
  3576. }
  3577. case 5123 /* UNSIGNED_SHORT */: {
  3578. return new Uint16Array(buffer, byteOffset, length);
  3579. }
  3580. case 5125 /* UNSIGNED_INT */: {
  3581. return new Uint32Array(buffer, byteOffset, length);
  3582. }
  3583. case 5126 /* FLOAT */: {
  3584. return new Float32Array(buffer, byteOffset, length);
  3585. }
  3586. default: {
  3587. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  3588. }
  3589. }
  3590. }
  3591. catch (e) {
  3592. throw new Error(context + ": " + e);
  3593. }
  3594. });
  3595. return accessor._data;
  3596. };
  3597. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  3598. var _this = this;
  3599. if (bufferView._babylonBuffer) {
  3600. return bufferView._babylonBuffer;
  3601. }
  3602. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  3603. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  3604. });
  3605. return bufferView._babylonBuffer;
  3606. };
  3607. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  3608. var _this = this;
  3609. if (accessor.sparse) {
  3610. throw new Error(context + ": Sparse accessors are not currently supported");
  3611. }
  3612. if (accessor._babylonVertexBuffer) {
  3613. return accessor._babylonVertexBuffer;
  3614. }
  3615. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3616. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  3617. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  3618. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  3619. });
  3620. return accessor._babylonVertexBuffer;
  3621. };
  3622. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  3623. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  3624. if (!babylonMaterial) {
  3625. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  3626. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3627. babylonMaterial.metallic = 1;
  3628. babylonMaterial.roughness = 1;
  3629. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3630. }
  3631. return babylonMaterial;
  3632. };
  3633. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  3634. var promises = new Array();
  3635. // Ensure metallic workflow
  3636. babylonMaterial.metallic = 1;
  3637. babylonMaterial.roughness = 1;
  3638. var properties = material.pbrMetallicRoughness;
  3639. if (properties) {
  3640. if (properties.baseColorFactor) {
  3641. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3642. babylonMaterial.alpha = properties.baseColorFactor[3];
  3643. }
  3644. else {
  3645. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3646. }
  3647. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  3648. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  3649. if (properties.baseColorTexture) {
  3650. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3651. babylonMaterial.albedoTexture = texture;
  3652. }));
  3653. }
  3654. if (properties.metallicRoughnessTexture) {
  3655. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  3656. babylonMaterial.metallicTexture = texture;
  3657. }));
  3658. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3659. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3660. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3661. }
  3662. }
  3663. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  3664. return Promise.all(promises).then(function () { });
  3665. };
  3666. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  3667. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  3668. if (promise) {
  3669. return promise;
  3670. }
  3671. material._babylonData = material._babylonData || {};
  3672. var babylonData = material._babylonData[babylonDrawMode];
  3673. if (!babylonData) {
  3674. var promises = new Array();
  3675. var name_3 = material.name || "materialSG_" + material._index;
  3676. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  3677. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3678. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  3679. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3680. babylonData = {
  3681. material: babylonMaterial,
  3682. meshes: [],
  3683. loaded: Promise.all(promises).then(function () { })
  3684. };
  3685. material._babylonData[babylonDrawMode] = babylonData;
  3686. }
  3687. babylonData.meshes.push(babylonMesh);
  3688. assign(babylonData.material);
  3689. return babylonData.loaded;
  3690. };
  3691. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  3692. var babylonMaterial = new type(name, this._babylonScene);
  3693. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3694. babylonMaterial.fillMode = drawMode;
  3695. return babylonMaterial;
  3696. };
  3697. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  3698. var promises = new Array();
  3699. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3700. if (material.doubleSided) {
  3701. babylonMaterial.backFaceCulling = false;
  3702. babylonMaterial.twoSidedLighting = true;
  3703. }
  3704. if (material.normalTexture) {
  3705. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  3706. babylonMaterial.bumpTexture = texture;
  3707. }));
  3708. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  3709. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  3710. if (material.normalTexture.scale != undefined) {
  3711. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3712. }
  3713. }
  3714. if (material.occlusionTexture) {
  3715. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  3716. babylonMaterial.ambientTexture = texture;
  3717. }));
  3718. babylonMaterial.useAmbientInGrayScale = true;
  3719. if (material.occlusionTexture.strength != undefined) {
  3720. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3721. }
  3722. }
  3723. if (material.emissiveTexture) {
  3724. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  3725. babylonMaterial.emissiveTexture = texture;
  3726. }));
  3727. }
  3728. return Promise.all(promises).then(function () { });
  3729. };
  3730. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  3731. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  3732. switch (alphaMode) {
  3733. case "OPAQUE" /* OPAQUE */: {
  3734. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3735. break;
  3736. }
  3737. case "MASK" /* MASK */: {
  3738. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  3739. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  3740. if (babylonMaterial.albedoTexture) {
  3741. babylonMaterial.albedoTexture.hasAlpha = true;
  3742. }
  3743. break;
  3744. }
  3745. case "BLEND" /* BLEND */: {
  3746. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  3747. if (babylonMaterial.albedoTexture) {
  3748. babylonMaterial.albedoTexture.hasAlpha = true;
  3749. babylonMaterial.useAlphaFromAlbedoTexture = true;
  3750. }
  3751. break;
  3752. }
  3753. default: {
  3754. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  3755. }
  3756. }
  3757. };
  3758. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  3759. var _this = this;
  3760. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  3761. context = "#/textures/" + textureInfo.index;
  3762. var promises = new Array();
  3763. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  3764. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  3765. var deferred = new BABYLON.Deferred();
  3766. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  3767. if (!_this._disposed) {
  3768. deferred.resolve();
  3769. }
  3770. }, function (message, exception) {
  3771. if (!_this._disposed) {
  3772. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  3773. }
  3774. });
  3775. promises.push(deferred.promise);
  3776. babylonTexture.name = texture.name || "texture" + texture._index;
  3777. babylonTexture.wrapU = samplerData.wrapU;
  3778. babylonTexture.wrapV = samplerData.wrapV;
  3779. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  3780. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  3781. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  3782. babylonTexture.updateURL(objectURL);
  3783. }));
  3784. assign(babylonTexture);
  3785. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  3786. return Promise.all(promises).then(function () { });
  3787. };
  3788. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  3789. if (!sampler._data) {
  3790. sampler._data = {
  3791. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  3792. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  3793. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  3794. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  3795. };
  3796. }
  3797. ;
  3798. return sampler._data;
  3799. };
  3800. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  3801. if (image._objectURL) {
  3802. return image._objectURL;
  3803. }
  3804. var promise;
  3805. if (image.uri) {
  3806. promise = this._loadUriAsync(context, image.uri);
  3807. }
  3808. else {
  3809. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  3810. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  3811. }
  3812. image._objectURL = promise.then(function (data) {
  3813. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  3814. });
  3815. return image._objectURL;
  3816. };
  3817. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  3818. var _this = this;
  3819. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  3820. if (promise) {
  3821. return promise;
  3822. }
  3823. if (!GLTFLoader._ValidateUri(uri)) {
  3824. throw new Error(context + ": Uri '" + uri + "' is invalid");
  3825. }
  3826. if (BABYLON.Tools.IsBase64(uri)) {
  3827. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  3828. }
  3829. return new Promise(function (resolve, reject) {
  3830. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  3831. if (!_this._disposed) {
  3832. resolve(new Uint8Array(data));
  3833. }
  3834. }, function (event) {
  3835. if (!_this._disposed) {
  3836. try {
  3837. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  3838. request._lengthComputable = event.lengthComputable;
  3839. request._loaded = event.loaded;
  3840. request._total = event.total;
  3841. _this._onProgress();
  3842. }
  3843. }
  3844. catch (e) {
  3845. reject(e);
  3846. }
  3847. }
  3848. }, _this._babylonScene.database, true, function (request, exception) {
  3849. if (!_this._disposed) {
  3850. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  3851. }
  3852. });
  3853. _this._requests.push(request);
  3854. });
  3855. };
  3856. GLTFLoader.prototype._onProgress = function () {
  3857. if (!this._progressCallback) {
  3858. return;
  3859. }
  3860. var lengthComputable = true;
  3861. var loaded = 0;
  3862. var total = 0;
  3863. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3864. var request = _a[_i];
  3865. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  3866. return;
  3867. }
  3868. lengthComputable = lengthComputable && request._lengthComputable;
  3869. loaded += request._loaded;
  3870. total += request._total;
  3871. }
  3872. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  3873. };
  3874. GLTFLoader._GetProperty = function (context, array, index) {
  3875. if (!array || index == undefined || !array[index]) {
  3876. throw new Error(context + ": Failed to find index (" + index + ")");
  3877. }
  3878. return array[index];
  3879. };
  3880. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  3881. // Set defaults if undefined
  3882. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  3883. switch (mode) {
  3884. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3885. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3886. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3887. default:
  3888. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  3889. return BABYLON.Texture.WRAP_ADDRESSMODE;
  3890. }
  3891. };
  3892. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  3893. // Set defaults if undefined
  3894. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  3895. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  3896. if (magFilter === 9729 /* LINEAR */) {
  3897. switch (minFilter) {
  3898. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  3899. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  3900. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  3901. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  3902. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  3903. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3904. default:
  3905. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  3906. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3907. }
  3908. }
  3909. else {
  3910. if (magFilter !== 9728 /* NEAREST */) {
  3911. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  3912. }
  3913. switch (minFilter) {
  3914. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  3915. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  3916. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3917. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  3918. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  3919. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  3920. default:
  3921. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  3922. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3923. }
  3924. }
  3925. };
  3926. GLTFLoader._GetNumComponents = function (context, type) {
  3927. switch (type) {
  3928. case "SCALAR": return 1;
  3929. case "VEC2": return 2;
  3930. case "VEC3": return 3;
  3931. case "VEC4": return 4;
  3932. case "MAT2": return 4;
  3933. case "MAT3": return 9;
  3934. case "MAT4": return 16;
  3935. }
  3936. throw new Error(context + ": Invalid type (" + type + ")");
  3937. };
  3938. GLTFLoader._ValidateUri = function (uri) {
  3939. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  3940. };
  3941. GLTFLoader._GetDrawMode = function (context, mode) {
  3942. if (mode == undefined) {
  3943. mode = 4 /* TRIANGLES */;
  3944. }
  3945. switch (mode) {
  3946. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  3947. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  3948. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  3949. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  3950. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  3951. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  3952. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  3953. }
  3954. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  3955. };
  3956. GLTFLoader.prototype._compileMaterialsAsync = function () {
  3957. var promises = new Array();
  3958. if (this._gltf.materials) {
  3959. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  3960. var material = _a[_i];
  3961. if (material._babylonData) {
  3962. for (var babylonDrawMode in material._babylonData) {
  3963. var babylonData = material._babylonData[babylonDrawMode];
  3964. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  3965. var babylonMesh = _c[_b];
  3966. // Ensure nonUniformScaling is set if necessary.
  3967. babylonMesh.computeWorldMatrix(true);
  3968. var babylonMaterial = babylonData.material;
  3969. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  3970. if (this.useClipPlane) {
  3971. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  3972. }
  3973. }
  3974. }
  3975. }
  3976. }
  3977. }
  3978. return Promise.all(promises).then(function () { });
  3979. };
  3980. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  3981. var promises = new Array();
  3982. var lights = this._babylonScene.lights;
  3983. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  3984. var light = lights_1[_i];
  3985. var generator = light.getShadowGenerator();
  3986. if (generator) {
  3987. promises.push(generator.forceCompilationAsync());
  3988. }
  3989. }
  3990. return Promise.all(promises).then(function () { });
  3991. };
  3992. GLTFLoader.prototype._clear = function () {
  3993. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3994. var request = _a[_i];
  3995. request.abort();
  3996. }
  3997. this._requests.length = 0;
  3998. if (this._gltf && this._gltf.images) {
  3999. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  4000. var image = _c[_b];
  4001. if (image._objectURL) {
  4002. image._objectURL.then(function (value) {
  4003. URL.revokeObjectURL(value);
  4004. });
  4005. image._objectURL = undefined;
  4006. }
  4007. }
  4008. }
  4009. delete this._gltf;
  4010. delete this._babylonScene;
  4011. this._completePromises.length = 0;
  4012. for (var name_4 in this._extensions) {
  4013. this._extensions[name_4].dispose();
  4014. }
  4015. this._extensions = {};
  4016. delete this._rootBabylonMesh;
  4017. delete this._progressCallback;
  4018. this.onMeshLoadedObservable.clear();
  4019. this.onTextureLoadedObservable.clear();
  4020. this.onMaterialLoadedObservable.clear();
  4021. };
  4022. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  4023. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  4024. var name_5 = _a[_i];
  4025. var extension = this._extensions[name_5];
  4026. if (extension.enabled) {
  4027. var promise = actionAsync(extension);
  4028. if (promise) {
  4029. return promise;
  4030. }
  4031. }
  4032. }
  4033. return null;
  4034. };
  4035. GLTFLoader._Names = new Array();
  4036. GLTFLoader._Factories = {};
  4037. return GLTFLoader;
  4038. }());
  4039. GLTF2.GLTFLoader = GLTFLoader;
  4040. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  4041. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4042. })(BABYLON || (BABYLON = {}));
  4043. //# sourceMappingURL=babylon.glTFLoader.js.map
  4044. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  4045. var BABYLON;
  4046. (function (BABYLON) {
  4047. var GLTF2;
  4048. (function (GLTF2) {
  4049. var GLTFLoaderExtension = /** @class */ (function () {
  4050. function GLTFLoaderExtension(loader) {
  4051. this.enabled = true;
  4052. this._loader = loader;
  4053. }
  4054. GLTFLoaderExtension.prototype.dispose = function () {
  4055. delete this._loader;
  4056. };
  4057. // #region Overridable Methods
  4058. /** Override this method to modify the default behavior for loading scenes. */
  4059. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  4060. /** Override this method to modify the default behavior for loading nodes. */
  4061. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  4062. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  4063. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  4064. /** Override this method to modify the default behavior for loading materials. */
  4065. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  4066. /** Override this method to modify the default behavior for loading uris. */
  4067. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  4068. // #endregion
  4069. /** Helper method called by a loader extension to load an glTF extension. */
  4070. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  4071. if (!property.extensions) {
  4072. return null;
  4073. }
  4074. var extensions = property.extensions;
  4075. var extension = extensions[this.name];
  4076. if (!extension) {
  4077. return null;
  4078. }
  4079. // Clear out the extension before executing the action to avoid recursing into the same property.
  4080. delete extensions[this.name];
  4081. try {
  4082. return actionAsync(context + "/extensions/" + this.name, extension);
  4083. }
  4084. finally {
  4085. // Restore the extension after executing the action.
  4086. extensions[this.name] = extension;
  4087. }
  4088. };
  4089. /** Helper method called by the loader to allow extensions to override loading scenes. */
  4090. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  4091. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  4092. };
  4093. /** Helper method called by the loader to allow extensions to override loading nodes. */
  4094. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  4095. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  4096. };
  4097. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  4098. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  4099. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  4100. };
  4101. /** Helper method called by the loader to allow extensions to override loading materials. */
  4102. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  4103. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  4104. };
  4105. /** Helper method called by the loader to allow extensions to override loading uris. */
  4106. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4107. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4108. };
  4109. return GLTFLoaderExtension;
  4110. }());
  4111. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4112. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4113. })(BABYLON || (BABYLON = {}));
  4114. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4115. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4116. var __extends = (this && this.__extends) || (function () {
  4117. var extendStatics = Object.setPrototypeOf ||
  4118. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4119. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4120. return function (d, b) {
  4121. extendStatics(d, b);
  4122. function __() { this.constructor = d; }
  4123. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4124. };
  4125. })();
  4126. var BABYLON;
  4127. (function (BABYLON) {
  4128. var GLTF2;
  4129. (function (GLTF2) {
  4130. var Extensions;
  4131. (function (Extensions) {
  4132. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  4133. var NAME = "MSFT_lod";
  4134. var MSFT_lod = /** @class */ (function (_super) {
  4135. __extends(MSFT_lod, _super);
  4136. function MSFT_lod() {
  4137. var _this = _super !== null && _super.apply(this, arguments) || this;
  4138. _this.name = NAME;
  4139. /**
  4140. * Maximum number of LODs to load, starting from the lowest LOD.
  4141. */
  4142. _this.maxLODsToLoad = Number.MAX_VALUE;
  4143. _this._loadingNodeLOD = null;
  4144. _this._loadNodeSignals = {};
  4145. _this._loadingMaterialLOD = null;
  4146. _this._loadMaterialSignals = {};
  4147. return _this;
  4148. }
  4149. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  4150. var _this = this;
  4151. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  4152. var firstPromise;
  4153. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  4154. var _loop_1 = function (indexLOD) {
  4155. var nodeLOD = nodeLODs[indexLOD];
  4156. if (indexLOD !== 0) {
  4157. _this._loadingNodeLOD = nodeLOD;
  4158. if (!_this._loadNodeSignals[nodeLOD._index]) {
  4159. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  4160. }
  4161. }
  4162. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  4163. if (indexLOD !== 0) {
  4164. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4165. if (previousNodeLOD._babylonMesh) {
  4166. previousNodeLOD._babylonMesh.dispose(false, true);
  4167. delete previousNodeLOD._babylonMesh;
  4168. }
  4169. }
  4170. if (indexLOD !== nodeLODs.length - 1) {
  4171. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  4172. if (_this._loadNodeSignals[nodeIndex]) {
  4173. _this._loadNodeSignals[nodeIndex].resolve();
  4174. delete _this._loadNodeSignals[nodeIndex];
  4175. }
  4176. }
  4177. });
  4178. if (indexLOD === 0) {
  4179. firstPromise = promise;
  4180. }
  4181. else {
  4182. _this._loader._completePromises.push(promise);
  4183. _this._loadingNodeLOD = null;
  4184. }
  4185. };
  4186. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4187. _loop_1(indexLOD);
  4188. }
  4189. return firstPromise;
  4190. });
  4191. };
  4192. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4193. var _this = this;
  4194. // Don't load material LODs if already loading a node LOD.
  4195. if (this._loadingNodeLOD) {
  4196. return null;
  4197. }
  4198. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  4199. var firstPromise;
  4200. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  4201. var _loop_2 = function (indexLOD) {
  4202. var materialLOD = materialLODs[indexLOD];
  4203. if (indexLOD !== 0) {
  4204. _this._loadingMaterialLOD = materialLOD;
  4205. if (!_this._loadMaterialSignals[materialLOD._index]) {
  4206. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  4207. }
  4208. }
  4209. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  4210. if (indexLOD !== 0) {
  4211. var babylonDataLOD = materialLOD._babylonData;
  4212. assign(babylonDataLOD[babylonDrawMode].material);
  4213. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  4214. if (previousBabylonDataLOD[babylonDrawMode]) {
  4215. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  4216. delete previousBabylonDataLOD[babylonDrawMode];
  4217. }
  4218. }
  4219. if (indexLOD !== materialLODs.length - 1) {
  4220. var materialIndex = materialLODs[indexLOD + 1]._index;
  4221. if (_this._loadMaterialSignals[materialIndex]) {
  4222. _this._loadMaterialSignals[materialIndex].resolve();
  4223. delete _this._loadMaterialSignals[materialIndex];
  4224. }
  4225. }
  4226. });
  4227. if (indexLOD === 0) {
  4228. firstPromise = promise;
  4229. }
  4230. else {
  4231. _this._loader._completePromises.push(promise);
  4232. _this._loadingMaterialLOD = null;
  4233. }
  4234. };
  4235. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4236. _loop_2(indexLOD);
  4237. }
  4238. return firstPromise;
  4239. });
  4240. };
  4241. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4242. var _this = this;
  4243. // Defer the loading of uris if loading a material or node LOD.
  4244. if (this._loadingMaterialLOD) {
  4245. var index = this._loadingMaterialLOD._index;
  4246. return this._loadMaterialSignals[index].promise.then(function () {
  4247. return _this._loader._loadUriAsync(context, uri);
  4248. });
  4249. }
  4250. else if (this._loadingNodeLOD) {
  4251. var index = this._loadingNodeLOD._index;
  4252. return this._loadNodeSignals[index].promise.then(function () {
  4253. return _this._loader._loadUriAsync(context, uri);
  4254. });
  4255. }
  4256. return null;
  4257. };
  4258. /**
  4259. * Gets an array of LOD properties from lowest to highest.
  4260. */
  4261. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4262. if (this.maxLODsToLoad <= 0) {
  4263. throw new Error("maxLODsToLoad must be greater than zero");
  4264. }
  4265. var properties = new Array();
  4266. for (var i = ids.length - 1; i >= 0; i--) {
  4267. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  4268. if (properties.length === this.maxLODsToLoad) {
  4269. return properties;
  4270. }
  4271. }
  4272. properties.push(property);
  4273. return properties;
  4274. };
  4275. return MSFT_lod;
  4276. }(GLTF2.GLTFLoaderExtension));
  4277. Extensions.MSFT_lod = MSFT_lod;
  4278. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  4279. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4280. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4281. })(BABYLON || (BABYLON = {}));
  4282. //# sourceMappingURL=MSFT_lod.js.map
  4283. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4284. var __extends = (this && this.__extends) || (function () {
  4285. var extendStatics = Object.setPrototypeOf ||
  4286. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4287. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4288. return function (d, b) {
  4289. extendStatics(d, b);
  4290. function __() { this.constructor = d; }
  4291. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4292. };
  4293. })();
  4294. var BABYLON;
  4295. (function (BABYLON) {
  4296. var GLTF2;
  4297. (function (GLTF2) {
  4298. var Extensions;
  4299. (function (Extensions) {
  4300. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  4301. var NAME = "KHR_draco_mesh_compression";
  4302. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  4303. __extends(KHR_draco_mesh_compression, _super);
  4304. function KHR_draco_mesh_compression(loader) {
  4305. var _this = _super.call(this, loader) || this;
  4306. _this.name = NAME;
  4307. _this._dracoCompression = null;
  4308. // Disable extension if decoder is not available.
  4309. if (!BABYLON.DracoCompression.DecoderAvailable) {
  4310. _this.enabled = false;
  4311. }
  4312. return _this;
  4313. }
  4314. KHR_draco_mesh_compression.prototype.dispose = function () {
  4315. if (this._dracoCompression) {
  4316. this._dracoCompression.dispose();
  4317. }
  4318. _super.prototype.dispose.call(this);
  4319. };
  4320. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4321. var _this = this;
  4322. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  4323. if (primitive.mode != undefined) {
  4324. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  4325. primitive.mode !== 4 /* TRIANGLES */) {
  4326. throw new Error(context + ": Unsupported mode " + primitive.mode);
  4327. }
  4328. // TODO: handle triangle strips
  4329. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  4330. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  4331. }
  4332. }
  4333. var attributes = {};
  4334. var loadAttribute = function (name, kind) {
  4335. var uniqueId = extension.attributes[name];
  4336. if (uniqueId == undefined) {
  4337. return;
  4338. }
  4339. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4340. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4341. babylonMesh._delayInfo.push(kind);
  4342. }
  4343. attributes[kind] = uniqueId;
  4344. };
  4345. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4346. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4347. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4348. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4349. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4350. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4351. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4352. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  4353. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  4354. if (!bufferView._dracoBabylonGeometry) {
  4355. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  4356. if (!_this._dracoCompression) {
  4357. _this._dracoCompression = new BABYLON.DracoCompression();
  4358. }
  4359. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  4360. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  4361. babylonVertexData.applyToGeometry(babylonGeometry);
  4362. return babylonGeometry;
  4363. }).catch(function (error) {
  4364. throw new Error(context + ": " + error.message);
  4365. });
  4366. });
  4367. }
  4368. return bufferView._dracoBabylonGeometry;
  4369. });
  4370. };
  4371. return KHR_draco_mesh_compression;
  4372. }(GLTF2.GLTFLoaderExtension));
  4373. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  4374. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  4375. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4376. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4377. })(BABYLON || (BABYLON = {}));
  4378. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  4379. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4380. var __extends = (this && this.__extends) || (function () {
  4381. var extendStatics = Object.setPrototypeOf ||
  4382. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4383. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4384. return function (d, b) {
  4385. extendStatics(d, b);
  4386. function __() { this.constructor = d; }
  4387. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4388. };
  4389. })();
  4390. var BABYLON;
  4391. (function (BABYLON) {
  4392. var GLTF2;
  4393. (function (GLTF2) {
  4394. var Extensions;
  4395. (function (Extensions) {
  4396. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  4397. var NAME = "KHR_materials_pbrSpecularGlossiness";
  4398. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  4399. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  4400. function KHR_materials_pbrSpecularGlossiness() {
  4401. var _this = _super !== null && _super.apply(this, arguments) || this;
  4402. _this.name = NAME;
  4403. return _this;
  4404. }
  4405. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4406. var _this = this;
  4407. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  4408. material._babylonData = material._babylonData || {};
  4409. var babylonData = material._babylonData[babylonDrawMode];
  4410. if (!babylonData) {
  4411. var promises = new Array();
  4412. var name_1 = material.name || "materialSG_" + material._index;
  4413. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  4414. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4415. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  4416. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4417. babylonData = {
  4418. material: babylonMaterial,
  4419. meshes: [],
  4420. loaded: Promise.all(promises).then(function () { })
  4421. };
  4422. material._babylonData[babylonDrawMode] = babylonData;
  4423. }
  4424. babylonData.meshes.push(babylonMesh);
  4425. assign(babylonData.material);
  4426. return babylonData.loaded;
  4427. });
  4428. };
  4429. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  4430. var promises = new Array();
  4431. if (properties.diffuseFactor) {
  4432. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  4433. babylonMaterial.alpha = properties.diffuseFactor[3];
  4434. }
  4435. else {
  4436. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4437. }
  4438. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  4439. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4440. if (properties.diffuseTexture) {
  4441. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4442. babylonMaterial.albedoTexture = texture;
  4443. }));
  4444. }
  4445. if (properties.specularGlossinessTexture) {
  4446. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4447. babylonMaterial.reflectivityTexture = texture;
  4448. }));
  4449. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4450. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4451. }
  4452. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4453. return Promise.all(promises).then(function () { });
  4454. };
  4455. return KHR_materials_pbrSpecularGlossiness;
  4456. }(GLTF2.GLTFLoaderExtension));
  4457. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  4458. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  4459. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4460. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4461. })(BABYLON || (BABYLON = {}));
  4462. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4463. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4464. var __extends = (this && this.__extends) || (function () {
  4465. var extendStatics = Object.setPrototypeOf ||
  4466. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4467. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4468. return function (d, b) {
  4469. extendStatics(d, b);
  4470. function __() { this.constructor = d; }
  4471. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4472. };
  4473. })();
  4474. var BABYLON;
  4475. (function (BABYLON) {
  4476. var GLTF2;
  4477. (function (GLTF2) {
  4478. var Extensions;
  4479. (function (Extensions) {
  4480. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  4481. var NAME = "KHR_materials_unlit";
  4482. var KHR_materials_unlit = /** @class */ (function (_super) {
  4483. __extends(KHR_materials_unlit, _super);
  4484. function KHR_materials_unlit() {
  4485. var _this = _super !== null && _super.apply(this, arguments) || this;
  4486. _this.name = NAME;
  4487. return _this;
  4488. }
  4489. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4490. var _this = this;
  4491. return this._loadExtensionAsync(context, material, function () {
  4492. material._babylonData = material._babylonData || {};
  4493. var babylonData = material._babylonData[babylonDrawMode];
  4494. if (!babylonData) {
  4495. var name_1 = material.name || "materialUnlit_" + material._index;
  4496. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  4497. babylonMaterial.unlit = true;
  4498. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  4499. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4500. babylonData = {
  4501. material: babylonMaterial,
  4502. meshes: [],
  4503. loaded: promise
  4504. };
  4505. material._babylonData[babylonDrawMode] = babylonData;
  4506. }
  4507. babylonData.meshes.push(babylonMesh);
  4508. assign(babylonData.material);
  4509. return babylonData.loaded;
  4510. });
  4511. };
  4512. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  4513. var promises = new Array();
  4514. // Ensure metallic workflow
  4515. babylonMaterial.metallic = 1;
  4516. babylonMaterial.roughness = 1;
  4517. var properties = material.pbrMetallicRoughness;
  4518. if (properties) {
  4519. if (properties.baseColorFactor) {
  4520. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  4521. babylonMaterial.alpha = properties.baseColorFactor[3];
  4522. }
  4523. else {
  4524. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4525. }
  4526. if (properties.baseColorTexture) {
  4527. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4528. babylonMaterial.albedoTexture = texture;
  4529. }));
  4530. }
  4531. }
  4532. if (material.doubleSided) {
  4533. babylonMaterial.backFaceCulling = false;
  4534. babylonMaterial.twoSidedLighting = true;
  4535. }
  4536. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4537. return Promise.all(promises).then(function () { });
  4538. };
  4539. return KHR_materials_unlit;
  4540. }(GLTF2.GLTFLoaderExtension));
  4541. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  4542. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  4543. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4544. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4545. })(BABYLON || (BABYLON = {}));
  4546. //# sourceMappingURL=KHR_materials_unlit.js.map
  4547. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4548. var __extends = (this && this.__extends) || (function () {
  4549. var extendStatics = Object.setPrototypeOf ||
  4550. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4551. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4552. return function (d, b) {
  4553. extendStatics(d, b);
  4554. function __() { this.constructor = d; }
  4555. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4556. };
  4557. })();
  4558. var BABYLON;
  4559. (function (BABYLON) {
  4560. var GLTF2;
  4561. (function (GLTF2) {
  4562. var Extensions;
  4563. (function (Extensions) {
  4564. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  4565. var NAME = "KHR_lights";
  4566. var LightType;
  4567. (function (LightType) {
  4568. LightType["AMBIENT"] = "ambient";
  4569. LightType["DIRECTIONAL"] = "directional";
  4570. LightType["POINT"] = "point";
  4571. LightType["SPOT"] = "spot";
  4572. })(LightType || (LightType = {}));
  4573. var KHR_lights = /** @class */ (function (_super) {
  4574. __extends(KHR_lights, _super);
  4575. function KHR_lights() {
  4576. var _this = _super !== null && _super.apply(this, arguments) || this;
  4577. _this.name = NAME;
  4578. return _this;
  4579. }
  4580. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  4581. var _this = this;
  4582. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  4583. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  4584. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  4585. if (light.type !== LightType.AMBIENT) {
  4586. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  4587. }
  4588. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  4589. return promise;
  4590. });
  4591. };
  4592. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  4593. var _this = this;
  4594. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  4595. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  4596. var babylonLight;
  4597. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  4598. var name = node._babylonMesh.name;
  4599. switch (light.type) {
  4600. case LightType.AMBIENT: {
  4601. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  4602. }
  4603. case LightType.DIRECTIONAL: {
  4604. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  4605. break;
  4606. }
  4607. case LightType.POINT: {
  4608. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  4609. break;
  4610. }
  4611. case LightType.SPOT: {
  4612. var spotLight = light;
  4613. // TODO: support inner and outer cone angles
  4614. //const innerConeAngle = spotLight.innerConeAngle || 0;
  4615. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  4616. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  4617. break;
  4618. }
  4619. default: {
  4620. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  4621. }
  4622. }
  4623. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  4624. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  4625. babylonLight.parent = node._babylonMesh;
  4626. return promise;
  4627. });
  4628. };
  4629. Object.defineProperty(KHR_lights.prototype, "_lights", {
  4630. get: function () {
  4631. var extensions = this._loader._gltf.extensions;
  4632. if (!extensions || !extensions[this.name]) {
  4633. throw new Error("#/extensions: '" + this.name + "' not found");
  4634. }
  4635. var extension = extensions[this.name];
  4636. return extension.lights;
  4637. },
  4638. enumerable: true,
  4639. configurable: true
  4640. });
  4641. return KHR_lights;
  4642. }(GLTF2.GLTFLoaderExtension));
  4643. Extensions.KHR_lights = KHR_lights;
  4644. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  4645. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4646. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4647. })(BABYLON || (BABYLON = {}));
  4648. //# sourceMappingURL=KHR_lights.js.map