babylon.glTFFileLoader.js 236 KB

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