babylon.glTFFileLoader.js 237 KB

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