babylonjs.loaders.js 275 KB

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