babylonjs.loaders.js 281 KB

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