babylonjs.loaders.js 281 KB

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