babylonjs.loaders.js 334 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory(require("babylonjs"));
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-loaders", ["babylonjs"], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  8. else
  9. root["LOADERS"] = factory(root["BABYLON"]);
  10. })(window, function(__WEBPACK_EXTERNAL_MODULE_babylonjs__) {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ var ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ var getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = "./src/legacy.ts");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "../node_modules/webpack/buildin/global.js":
  99. /*!*************************************************!*\
  100. !*** ../node_modules/webpack/buildin/global.js ***!
  101. \*************************************************/
  102. /*! no static exports found */
  103. /***/ (function(module, exports) {
  104. var g;
  105. // This works in non-strict mode
  106. g = (function() {
  107. return this;
  108. })();
  109. try {
  110. // This works if eval is allowed (see CSP)
  111. g = g || Function("return this")() || (1, eval)("this");
  112. } catch (e) {
  113. // This works if the window reference is available
  114. if (typeof window === "object") g = window;
  115. }
  116. // g can still be undefined, but nothing to do about it...
  117. // We return undefined, instead of nothing here, so it's
  118. // easier to handle this case. if(!global) { ...}
  119. module.exports = g;
  120. /***/ }),
  121. /***/ "./src/OBJ/index.ts":
  122. /*!**************************!*\
  123. !*** ./src/OBJ/index.ts ***!
  124. \**************************/
  125. /*! no static exports found */
  126. /***/ (function(module, exports, __webpack_require__) {
  127. "use strict";
  128. function __export(m) {
  129. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  130. }
  131. Object.defineProperty(exports, "__esModule", { value: true });
  132. __export(__webpack_require__(/*! ./objFileLoader */ "./src/OBJ/objFileLoader.ts"));
  133. /***/ }),
  134. /***/ "./src/OBJ/objFileLoader.ts":
  135. /*!**********************************!*\
  136. !*** ./src/OBJ/objFileLoader.ts ***!
  137. \**********************************/
  138. /*! no static exports found */
  139. /***/ (function(module, exports, __webpack_require__) {
  140. "use strict";
  141. Object.defineProperty(exports, "__esModule", { value: true });
  142. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  143. /**
  144. * Class reading and parsing the MTL file bundled with the obj file.
  145. */
  146. var MTLFileLoader = /** @class */ (function () {
  147. function MTLFileLoader() {
  148. // All material loaded from the mtl will be set here
  149. this.materials = [];
  150. }
  151. /**
  152. * This function will read the mtl file and create each material described inside
  153. * This function could be improve by adding :
  154. * -some component missing (Ni, Tf...)
  155. * -including the specific options available
  156. *
  157. * @param scene
  158. * @param data
  159. * @param rootUrl
  160. */
  161. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  162. if (data instanceof ArrayBuffer) {
  163. return;
  164. }
  165. //Split the lines from the file
  166. var lines = data.split('\n');
  167. //Space char
  168. var delimiter_pattern = /\s+/;
  169. //Array with RGB colors
  170. var color;
  171. //New material
  172. var material = null;
  173. //Look at each line
  174. for (var i = 0; i < lines.length; i++) {
  175. var line = lines[i].trim();
  176. // Blank line or comment
  177. if (line.length === 0 || line.charAt(0) === '#') {
  178. continue;
  179. }
  180. //Get the first parameter (keyword)
  181. var pos = line.indexOf(' ');
  182. var key = (pos >= 0) ? line.substring(0, pos) : line;
  183. key = key.toLowerCase();
  184. //Get the data following the key
  185. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  186. //This mtl keyword will create the new material
  187. if (key === "newmtl") {
  188. //Check if it is the first material.
  189. // Materials specifications are described after this keyword.
  190. if (material) {
  191. //Add the previous material in the material array.
  192. this.materials.push(material);
  193. }
  194. //Create a new material.
  195. // value is the name of the material read in the mtl file
  196. material = new babylonjs_1.StandardMaterial(value, scene);
  197. }
  198. else if (key === "kd" && material) {
  199. // Diffuse color (color under white light) using RGB values
  200. //value = "r g b"
  201. color = value.split(delimiter_pattern, 3).map(parseFloat);
  202. //color = [r,g,b]
  203. //Set tghe color into the material
  204. material.diffuseColor = babylonjs_1.Color3.FromArray(color);
  205. }
  206. else if (key === "ka" && material) {
  207. // Ambient color (color under shadow) using RGB values
  208. //value = "r g b"
  209. color = value.split(delimiter_pattern, 3).map(parseFloat);
  210. //color = [r,g,b]
  211. //Set tghe color into the material
  212. material.ambientColor = babylonjs_1.Color3.FromArray(color);
  213. }
  214. else if (key === "ks" && material) {
  215. // Specular color (color when light is reflected from shiny surface) using RGB values
  216. //value = "r g b"
  217. color = value.split(delimiter_pattern, 3).map(parseFloat);
  218. //color = [r,g,b]
  219. //Set the color into the material
  220. material.specularColor = babylonjs_1.Color3.FromArray(color);
  221. }
  222. else if (key === "ke" && material) {
  223. // Emissive color using RGB values
  224. color = value.split(delimiter_pattern, 3).map(parseFloat);
  225. material.emissiveColor = babylonjs_1.Color3.FromArray(color);
  226. }
  227. else if (key === "ns" && material) {
  228. //value = "Integer"
  229. material.specularPower = parseFloat(value);
  230. }
  231. else if (key === "d" && material) {
  232. //d is dissolve for current material. It mean alpha for BABYLON
  233. material.alpha = parseFloat(value);
  234. //Texture
  235. //This part can be improved by adding the possible options of texture
  236. }
  237. else if (key === "map_ka" && material) {
  238. // ambient texture map with a loaded image
  239. //We must first get the folder of the image
  240. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  241. }
  242. else if (key === "map_kd" && material) {
  243. // Diffuse texture map with a loaded image
  244. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  245. }
  246. else if (key === "map_ks" && material) {
  247. // Specular texture map with a loaded image
  248. //We must first get the folder of the image
  249. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  250. }
  251. else if (key === "map_ns") {
  252. //Specular
  253. //Specular highlight component
  254. //We must first get the folder of the image
  255. //
  256. //Not supported by BABYLON
  257. //
  258. // continue;
  259. }
  260. else if (key === "map_bump" && material) {
  261. //The bump texture
  262. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  263. }
  264. else if (key === "map_d" && material) {
  265. // The dissolve of the material
  266. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  267. //Options for illumination
  268. }
  269. else if (key === "illum") {
  270. //Illumination
  271. if (value === "0") {
  272. //That mean Kd == Kd
  273. }
  274. else if (value === "1") {
  275. //Color on and Ambient on
  276. }
  277. else if (value === "2") {
  278. //Highlight on
  279. }
  280. else if (value === "3") {
  281. //Reflection on and Ray trace on
  282. }
  283. else if (value === "4") {
  284. //Transparency: Glass on, Reflection: Ray trace on
  285. }
  286. else if (value === "5") {
  287. //Reflection: Fresnel on and Ray trace on
  288. }
  289. else if (value === "6") {
  290. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  291. }
  292. else if (value === "7") {
  293. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  294. }
  295. else if (value === "8") {
  296. //Reflection on and Ray trace off
  297. }
  298. else if (value === "9") {
  299. //Transparency: Glass on, Reflection: Ray trace off
  300. }
  301. else if (value === "10") {
  302. //Casts shadows onto invisible surfaces
  303. }
  304. }
  305. else {
  306. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  307. }
  308. }
  309. //At the end of the file, add the last material
  310. if (material) {
  311. this.materials.push(material);
  312. }
  313. };
  314. /**
  315. * Gets the texture for the material.
  316. *
  317. * If the material is imported from input file,
  318. * We sanitize the url to ensure it takes the textre from aside the material.
  319. *
  320. * @param rootUrl The root url to load from
  321. * @param value The value stored in the mtl
  322. * @return The Texture
  323. */
  324. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  325. if (!value) {
  326. return null;
  327. }
  328. var url = rootUrl;
  329. // Load from input file.
  330. if (rootUrl === "file:") {
  331. var lastDelimiter = value.lastIndexOf("\\");
  332. if (lastDelimiter === -1) {
  333. lastDelimiter = value.lastIndexOf("/");
  334. }
  335. if (lastDelimiter > -1) {
  336. url += value.substr(lastDelimiter + 1);
  337. }
  338. else {
  339. url += value;
  340. }
  341. }
  342. // Not from input file.
  343. else {
  344. url += value;
  345. }
  346. return new babylonjs_1.Texture(url, scene);
  347. };
  348. return MTLFileLoader;
  349. }());
  350. exports.MTLFileLoader = MTLFileLoader;
  351. var OBJFileLoader = /** @class */ (function () {
  352. function OBJFileLoader() {
  353. this.name = "obj";
  354. this.extensions = ".obj";
  355. this.obj = /^o/;
  356. this.group = /^g/;
  357. this.mtllib = /^mtllib /;
  358. this.usemtl = /^usemtl /;
  359. this.smooth = /^s /;
  360. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  361. // vn float float float
  362. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  363. // vt float float
  364. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  365. // f vertex vertex vertex ...
  366. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  367. // f vertex/uvs vertex/uvs vertex/uvs ...
  368. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  369. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  370. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  371. // f vertex//normal vertex//normal vertex//normal ...
  372. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  373. // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...
  374. this.facePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;
  375. }
  376. /**
  377. * Calls synchronously the MTL file attached to this obj.
  378. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  379. * Without this function materials are not displayed in the first frame (but displayed after).
  380. * In consequence it is impossible to get material information in your HTML file
  381. *
  382. * @param url The URL of the MTL file
  383. * @param rootUrl
  384. * @param onSuccess Callback function to be called when the MTL file is loaded
  385. * @private
  386. */
  387. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  388. //The complete path to the mtl file
  389. var pathOfFile = babylonjs_1.Tools.BaseUrl + rootUrl + url;
  390. // Loads through the babylon tools to allow fileInput search.
  391. babylonjs_1.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  392. };
  393. /**
  394. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  395. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  396. * @param scene the scene the meshes should be added to
  397. * @param data the glTF data to load
  398. * @param rootUrl root url to load from
  399. * @param onProgress event that fires when loading progress has occured
  400. * @param fileName Defines the name of the file to load
  401. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  402. */
  403. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  404. //get the meshes from OBJ file
  405. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  406. return {
  407. meshes: meshes,
  408. particleSystems: [],
  409. skeletons: [],
  410. animationGroups: []
  411. };
  412. });
  413. };
  414. /**
  415. * Imports all objects from the loaded glTF data and adds them to the scene
  416. * @param scene the scene the objects should be added to
  417. * @param data the glTF data to load
  418. * @param rootUrl root url to load from
  419. * @param onProgress event that fires when loading progress has occured
  420. * @param fileName Defines the name of the file to load
  421. * @returns a promise which completes when objects have been loaded to the scene
  422. */
  423. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  424. //Get the 3D model
  425. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  426. // return void
  427. });
  428. };
  429. /**
  430. * Load into an asset container.
  431. * @param scene The scene to load into
  432. * @param data The data to import
  433. * @param rootUrl The root url for scene and resources
  434. * @param onProgress The callback when the load progresses
  435. * @param fileName Defines the name of the file to load
  436. * @returns The loaded asset container
  437. */
  438. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  439. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  440. var container = new babylonjs_1.AssetContainer(scene);
  441. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  442. container.removeAllFromScene();
  443. return container;
  444. });
  445. };
  446. /**
  447. * Read the OBJ file and create an Array of meshes.
  448. * Each mesh contains all information given by the OBJ and the MTL file.
  449. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  450. *
  451. * @param meshesNames
  452. * @param scene Scene The scene where are displayed the data
  453. * @param data String The content of the obj file
  454. * @param rootUrl String The path to the folder
  455. * @returns Array<AbstractMesh>
  456. * @private
  457. */
  458. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  459. var _this = this;
  460. var positions = []; //values for the positions of vertices
  461. var normals = []; //Values for the normals
  462. var uvs = []; //Values for the textures
  463. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  464. var handledMesh; //The current mesh of meshes array
  465. var indicesForBabylon = []; //The list of indices for VertexData
  466. var wrappedPositionForBabylon = []; //The list of position in vectors
  467. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  468. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  469. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  470. var curPositionInIndices = 0;
  471. var hasMeshes = false; //Meshes are defined in the file
  472. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  473. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  474. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  475. var triangles = []; //Indices from new triangles coming from polygons
  476. var materialNameFromObj = ""; //The name of the current material
  477. var fileToLoad = ""; //The name of the mtlFile to load
  478. var materialsFromMTLFile = new MTLFileLoader();
  479. var objMeshName = ""; //The name of the current obj mesh
  480. var increment = 1; //Id for meshes created by the multimaterial
  481. var isFirstMaterial = true;
  482. /**
  483. * Search for obj in the given array.
  484. * This function is called to check if a couple of data already exists in an array.
  485. *
  486. * If found, returns the index of the founded tuple index. Returns -1 if not found
  487. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  488. * @param obj Array<number>
  489. * @returns {boolean}
  490. */
  491. var isInArray = function (arr, obj) {
  492. if (!arr[obj[0]]) {
  493. arr[obj[0]] = { normals: [], idx: [] };
  494. }
  495. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  496. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  497. };
  498. var isInArrayUV = function (arr, obj) {
  499. if (!arr[obj[0]]) {
  500. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  501. }
  502. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  503. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  504. return arr[obj[0]].idx[idx];
  505. }
  506. return -1;
  507. };
  508. /**
  509. * This function set the data for each triangle.
  510. * Data are position, normals and uvs
  511. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  512. * If the tuple already exist, add only their indice
  513. *
  514. * @param indicePositionFromObj Integer The index in positions array
  515. * @param indiceUvsFromObj Integer The index in uvs array
  516. * @param indiceNormalFromObj Integer The index in normals array
  517. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  518. * @param textureVectorFromOBJ Vector3 The value of uvs
  519. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  520. */
  521. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  522. //Check if this tuple already exists in the list of tuples
  523. var _index;
  524. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  525. _index = isInArrayUV(tuplePosNorm, [
  526. indicePositionFromObj,
  527. indiceNormalFromObj,
  528. indiceUvsFromObj
  529. ]);
  530. }
  531. else {
  532. _index = isInArray(tuplePosNorm, [
  533. indicePositionFromObj,
  534. indiceNormalFromObj
  535. ]);
  536. }
  537. //If it not exists
  538. if (_index == -1) {
  539. //Add an new indice.
  540. //The array of indices is only an array with his length equal to the number of triangles - 1.
  541. //We add vertices data in this order
  542. indicesForBabylon.push(wrappedPositionForBabylon.length);
  543. //Push the position of vertice for Babylon
  544. //Each element is a Vector3(x,y,z)
  545. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  546. //Push the uvs for Babylon
  547. //Each element is a Vector3(u,v)
  548. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  549. //Push the normals for Babylon
  550. //Each element is a Vector3(x,y,z)
  551. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  552. //Add the tuple in the comparison list
  553. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  554. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  555. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  556. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  557. }
  558. }
  559. else {
  560. //The tuple already exists
  561. //Add the index of the already existing tuple
  562. //At this index we can get the value of position, normal and uvs of vertex
  563. indicesForBabylon.push(_index);
  564. }
  565. };
  566. /**
  567. * Transform Vector() object onto 3 digits in an array
  568. */
  569. var unwrapData = function () {
  570. //Every array has the same length
  571. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  572. //Push the x, y, z values of each element in the unwrapped array
  573. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  574. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  575. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  576. }
  577. // Reset arrays for the next new meshes
  578. wrappedPositionForBabylon = [];
  579. wrappedNormalsForBabylon = [];
  580. wrappedUvsForBabylon = [];
  581. tuplePosNorm = [];
  582. curPositionInIndices = 0;
  583. };
  584. /**
  585. * Create triangles from polygons by recursion
  586. * The best to understand how it works is to draw it in the same time you get the recursion.
  587. * It is important to notice that a triangle is a polygon
  588. * We get 5 patterns of face defined in OBJ File :
  589. * facePattern1 = ["1","2","3","4","5","6"]
  590. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  591. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  592. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  593. * facePattern5 = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-4/-4/-4","-5/-5/-5","-6/-6/-6"]
  594. * Each pattern is divided by the same method
  595. * @param face Array[String] The indices of elements
  596. * @param v Integer The variable to increment
  597. */
  598. var getTriangles = function (face, v) {
  599. //Work for each element of the array
  600. if (v + 1 < face.length) {
  601. //Add on the triangle variable the indexes to obtain triangles
  602. triangles.push(face[0], face[v], face[v + 1]);
  603. //Incrementation for recursion
  604. v += 1;
  605. //Recursion
  606. getTriangles(face, v);
  607. }
  608. //Result obtained after 2 iterations:
  609. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  610. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  611. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  612. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  613. //Pattern5 => triangle = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-1/-1/-1","-3/-3/-3","-4/-4/-4"];
  614. };
  615. /**
  616. * Create triangles and push the data for each polygon for the pattern 1
  617. * In this pattern we get vertice positions
  618. * @param face
  619. * @param v
  620. */
  621. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  622. //Get the indices of triangles for each polygon
  623. getTriangles(face, v);
  624. //For each element in the triangles array.
  625. //This var could contains 1 to an infinity of triangles
  626. for (var k = 0; k < triangles.length; k++) {
  627. // Set position indice
  628. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  629. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  630. positions[indicePositionFromObj], //Get the vectors data
  631. babylonjs_1.Vector2.Zero(), babylonjs_1.Vector3.Up() //Create default vectors
  632. );
  633. }
  634. //Reset variable for the next line
  635. triangles = [];
  636. };
  637. /**
  638. * Create triangles and push the data for each polygon for the pattern 2
  639. * In this pattern we get vertice positions and uvsu
  640. * @param face
  641. * @param v
  642. */
  643. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  644. //Get the indices of triangles for each polygon
  645. getTriangles(face, v);
  646. for (var k = 0; k < triangles.length; k++) {
  647. //triangle[k] = "1/1"
  648. //Split the data for getting position and uv
  649. var point = triangles[k].split("/"); // ["1", "1"]
  650. //Set position indice
  651. var indicePositionFromObj = parseInt(point[0]) - 1;
  652. //Set uv indice
  653. var indiceUvsFromObj = parseInt(point[1]) - 1;
  654. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  655. positions[indicePositionFromObj], //Get the values for each element
  656. uvs[indiceUvsFromObj], babylonjs_1.Vector3.Up() //Default value for normals
  657. );
  658. }
  659. //Reset variable for the next line
  660. triangles = [];
  661. };
  662. /**
  663. * Create triangles and push the data for each polygon for the pattern 3
  664. * In this pattern we get vertice positions, uvs and normals
  665. * @param face
  666. * @param v
  667. */
  668. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  669. //Get the indices of triangles for each polygon
  670. getTriangles(face, v);
  671. for (var k = 0; k < triangles.length; k++) {
  672. //triangle[k] = "1/1/1"
  673. //Split the data for getting position, uv, and normals
  674. var point = triangles[k].split("/"); // ["1", "1", "1"]
  675. // Set position indice
  676. var indicePositionFromObj = parseInt(point[0]) - 1;
  677. // Set uv indice
  678. var indiceUvsFromObj = parseInt(point[1]) - 1;
  679. // Set normal indice
  680. var indiceNormalFromObj = parseInt(point[2]) - 1;
  681. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  682. );
  683. }
  684. //Reset variable for the next line
  685. triangles = [];
  686. };
  687. /**
  688. * Create triangles and push the data for each polygon for the pattern 4
  689. * In this pattern we get vertice positions and normals
  690. * @param face
  691. * @param v
  692. */
  693. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  694. getTriangles(face, v);
  695. for (var k = 0; k < triangles.length; k++) {
  696. //triangle[k] = "1//1"
  697. //Split the data for getting position and normals
  698. var point = triangles[k].split("//"); // ["1", "1"]
  699. // We check indices, and normals
  700. var indicePositionFromObj = parseInt(point[0]) - 1;
  701. var indiceNormalFromObj = parseInt(point[1]) - 1;
  702. setData(indicePositionFromObj, 1, //Default value for uv
  703. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  704. babylonjs_1.Vector2.Zero(), normals[indiceNormalFromObj]);
  705. }
  706. //Reset variable for the next line
  707. triangles = [];
  708. };
  709. /**
  710. * Create triangles and push the data for each polygon for the pattern 3
  711. * In this pattern we get vertice positions, uvs and normals
  712. * @param face
  713. * @param v
  714. */
  715. var setDataForCurrentFaceWithPattern5 = function (face, v) {
  716. //Get the indices of triangles for each polygon
  717. getTriangles(face, v);
  718. for (var k = 0; k < triangles.length; k++) {
  719. //triangle[k] = "-1/-1/-1"
  720. //Split the data for getting position, uv, and normals
  721. var point = triangles[k].split("/"); // ["-1", "-1", "-1"]
  722. // Set position indice
  723. var indicePositionFromObj = positions.length + parseInt(point[0]);
  724. // Set uv indice
  725. var indiceUvsFromObj = uvs.length + parseInt(point[1]);
  726. // Set normal indice
  727. var indiceNormalFromObj = normals.length + parseInt(point[2]);
  728. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  729. );
  730. }
  731. //Reset variable for the next line
  732. triangles = [];
  733. };
  734. var addPreviousObjMesh = function () {
  735. //Check if it is not the first mesh. Otherwise we don't have data.
  736. if (meshesFromObj.length > 0) {
  737. //Get the previous mesh for applying the data about the faces
  738. //=> in obj file, faces definition append after the name of the mesh
  739. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  740. //Set the data into Array for the mesh
  741. unwrapData();
  742. // Reverse tab. Otherwise face are displayed in the wrong sens
  743. indicesForBabylon.reverse();
  744. //Set the information for the mesh
  745. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  746. handledMesh.indices = indicesForBabylon.slice();
  747. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  748. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  749. handledMesh.uvs = unwrappedUVForBabylon.slice();
  750. //Reset the array for the next mesh
  751. indicesForBabylon = [];
  752. unwrappedPositionsForBabylon = [];
  753. unwrappedNormalsForBabylon = [];
  754. unwrappedUVForBabylon = [];
  755. }
  756. };
  757. //Main function
  758. //Split the file into lines
  759. var lines = data.split('\n');
  760. //Look at each line
  761. for (var i = 0; i < lines.length; i++) {
  762. var line = lines[i].trim();
  763. var result;
  764. //Comment or newLine
  765. if (line.length === 0 || line.charAt(0) === '#') {
  766. continue;
  767. //Get information about one position possible for the vertices
  768. }
  769. else if ((result = this.vertexPattern.exec(line)) !== null) {
  770. //Create a Vector3 with the position x, y, z
  771. //Value of result:
  772. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  773. //Add the Vector in the list of positions
  774. positions.push(new babylonjs_1.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  775. }
  776. else if ((result = this.normalPattern.exec(line)) !== null) {
  777. //Create a Vector3 with the normals x, y, z
  778. //Value of result
  779. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  780. //Add the Vector in the list of normals
  781. normals.push(new babylonjs_1.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  782. }
  783. else if ((result = this.uvPattern.exec(line)) !== null) {
  784. //Create a Vector2 with the normals u, v
  785. //Value of result
  786. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  787. //Add the Vector in the list of uvs
  788. uvs.push(new babylonjs_1.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  789. //Identify patterns of faces
  790. //Face could be defined in different type of pattern
  791. }
  792. else if ((result = this.facePattern3.exec(line)) !== null) {
  793. //Value of result:
  794. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  795. //Set the data for this face
  796. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  797. 1);
  798. }
  799. else if ((result = this.facePattern4.exec(line)) !== null) {
  800. //Value of result:
  801. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  802. //Set the data for this face
  803. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  804. 1);
  805. }
  806. else if ((result = this.facePattern5.exec(line)) !== null) {
  807. //Value of result:
  808. //["f -1/-1/-1 -2/-2/-2 -3/-3/-3", "-1/-1/-1 -2/-2/-2 -3/-3/-3"...]
  809. //Set the data for this face
  810. setDataForCurrentFaceWithPattern5(result[1].trim().split(" "), // ["-1/-1/-1", "-2/-2/-2", "-3/-3/-3"]
  811. 1);
  812. }
  813. else if ((result = this.facePattern2.exec(line)) !== null) {
  814. //Value of result:
  815. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  816. //Set the data for this face
  817. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  818. 1);
  819. }
  820. else if ((result = this.facePattern1.exec(line)) !== null) {
  821. //Value of result
  822. //["f 1 2 3", "1 2 3"...]
  823. //Set the data for this face
  824. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  825. 1);
  826. //Define a mesh or an object
  827. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  828. }
  829. else if (this.group.test(line) || this.obj.test(line)) {
  830. //Create a new mesh corresponding to the name of the group.
  831. //Definition of the mesh
  832. var objMesh =
  833. //Set the name of the current obj mesh
  834. {
  835. name: line.substring(2).trim(),
  836. indices: undefined,
  837. positions: undefined,
  838. normals: undefined,
  839. uvs: undefined,
  840. materialName: ""
  841. };
  842. addPreviousObjMesh();
  843. //Push the last mesh created with only the name
  844. meshesFromObj.push(objMesh);
  845. //Set this variable to indicate that now meshesFromObj has objects defined inside
  846. hasMeshes = true;
  847. isFirstMaterial = true;
  848. increment = 1;
  849. //Keyword for applying a material
  850. }
  851. else if (this.usemtl.test(line)) {
  852. //Get the name of the material
  853. materialNameFromObj = line.substring(7).trim();
  854. //If this new material is in the same mesh
  855. if (!isFirstMaterial) {
  856. //Set the data for the previous mesh
  857. addPreviousObjMesh();
  858. //Create a new mesh
  859. var objMesh =
  860. //Set the name of the current obj mesh
  861. {
  862. name: objMeshName + "_mm" + increment.toString(),
  863. indices: undefined,
  864. positions: undefined,
  865. normals: undefined,
  866. uvs: undefined,
  867. materialName: materialNameFromObj
  868. };
  869. increment++;
  870. //If meshes are already defined
  871. meshesFromObj.push(objMesh);
  872. }
  873. //Set the material name if the previous line define a mesh
  874. if (hasMeshes && isFirstMaterial) {
  875. //Set the material name to the previous mesh (1 material per mesh)
  876. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  877. isFirstMaterial = false;
  878. }
  879. //Keyword for loading the mtl file
  880. }
  881. else if (this.mtllib.test(line)) {
  882. //Get the name of mtl file
  883. fileToLoad = line.substring(7).trim();
  884. //Apply smoothing
  885. }
  886. else if (this.smooth.test(line)) {
  887. // smooth shading => apply smoothing
  888. //Toda y I don't know it work with babylon and with obj.
  889. //With the obj file an integer is set
  890. }
  891. else {
  892. //If there is another possibility
  893. console.log("Unhandled expression at line : " + line);
  894. }
  895. }
  896. //At the end of the file, add the last mesh into the meshesFromObj array
  897. if (hasMeshes) {
  898. //Set the data for the last mesh
  899. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  900. //Reverse indices for displaying faces in the good sens
  901. indicesForBabylon.reverse();
  902. //Get the good array
  903. unwrapData();
  904. //Set array
  905. handledMesh.indices = indicesForBabylon;
  906. handledMesh.positions = unwrappedPositionsForBabylon;
  907. handledMesh.normals = unwrappedNormalsForBabylon;
  908. handledMesh.uvs = unwrappedUVForBabylon;
  909. }
  910. //If any o or g keyword found, create a mesj with a random id
  911. if (!hasMeshes) {
  912. // reverse tab of indices
  913. indicesForBabylon.reverse();
  914. //Get positions normals uvs
  915. unwrapData();
  916. //Set data for one mesh
  917. meshesFromObj.push({
  918. name: babylonjs_1.Geometry.RandomId(),
  919. indices: indicesForBabylon,
  920. positions: unwrappedPositionsForBabylon,
  921. normals: unwrappedNormalsForBabylon,
  922. uvs: unwrappedUVForBabylon,
  923. materialName: materialNameFromObj
  924. });
  925. }
  926. //Create a Mesh list
  927. var babylonMeshesArray = []; //The mesh for babylon
  928. var materialToUse = new Array();
  929. //Set data for each mesh
  930. for (var j = 0; j < meshesFromObj.length; j++) {
  931. //check meshesNames (stlFileLoader)
  932. if (meshesNames && meshesFromObj[j].name) {
  933. if (meshesNames instanceof Array) {
  934. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  935. continue;
  936. }
  937. }
  938. else {
  939. if (meshesFromObj[j].name !== meshesNames) {
  940. continue;
  941. }
  942. }
  943. }
  944. //Get the current mesh
  945. //Set the data with VertexBuffer for each mesh
  946. handledMesh = meshesFromObj[j];
  947. //Create a Mesh with the name of the obj mesh
  948. var babylonMesh = new babylonjs_1.Mesh(meshesFromObj[j].name, scene);
  949. //Push the name of the material to an array
  950. //This is indispensable for the importMesh function
  951. materialToUse.push(meshesFromObj[j].materialName);
  952. var vertexData = new babylonjs_1.VertexData(); //The container for the values
  953. //Set the data for the babylonMesh
  954. vertexData.positions = handledMesh.positions;
  955. vertexData.normals = handledMesh.normals;
  956. vertexData.uvs = handledMesh.uvs;
  957. vertexData.indices = handledMesh.indices;
  958. //Set the data from the VertexBuffer to the current Mesh
  959. vertexData.applyToMesh(babylonMesh);
  960. if (OBJFileLoader.INVERT_Y) {
  961. babylonMesh.scaling.y *= -1;
  962. }
  963. //Push the mesh into an array
  964. babylonMeshesArray.push(babylonMesh);
  965. }
  966. var mtlPromises = [];
  967. //load the materials
  968. //Check if we have a file to load
  969. if (fileToLoad !== "") {
  970. //Load the file synchronously
  971. mtlPromises.push(new Promise(function (resolve, reject) {
  972. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  973. try {
  974. //Create materials thanks MTLLoader function
  975. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  976. //Look at each material loaded in the mtl file
  977. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  978. //Three variables to get all meshes with the same material
  979. var startIndex = 0;
  980. var _indices = [];
  981. var _index;
  982. //The material from MTL file is used in the meshes loaded
  983. //Push the indice in an array
  984. //Check if the material is not used for another mesh
  985. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  986. _indices.push(_index);
  987. startIndex = _index + 1;
  988. }
  989. //If the material is not used dispose it
  990. if (_index == -1 && _indices.length == 0) {
  991. //If the material is not needed, remove it
  992. materialsFromMTLFile.materials[n].dispose();
  993. }
  994. else {
  995. for (var o = 0; o < _indices.length; o++) {
  996. //Apply the material to the Mesh for each mesh with the material
  997. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  998. }
  999. }
  1000. }
  1001. resolve();
  1002. }
  1003. catch (e) {
  1004. reject(e);
  1005. }
  1006. });
  1007. }));
  1008. }
  1009. //Return an array with all Mesh
  1010. return Promise.all(mtlPromises).then(function () {
  1011. return babylonMeshesArray;
  1012. });
  1013. };
  1014. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  1015. OBJFileLoader.INVERT_Y = false;
  1016. return OBJFileLoader;
  1017. }());
  1018. exports.OBJFileLoader = OBJFileLoader;
  1019. if (babylonjs_1.SceneLoader) {
  1020. //Add this loader into the register plugin
  1021. babylonjs_1.SceneLoader.RegisterPlugin(new OBJFileLoader());
  1022. }
  1023. /***/ }),
  1024. /***/ "./src/STL/index.ts":
  1025. /*!**************************!*\
  1026. !*** ./src/STL/index.ts ***!
  1027. \**************************/
  1028. /*! no static exports found */
  1029. /***/ (function(module, exports, __webpack_require__) {
  1030. "use strict";
  1031. function __export(m) {
  1032. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  1033. }
  1034. Object.defineProperty(exports, "__esModule", { value: true });
  1035. __export(__webpack_require__(/*! ./stlFileLoader */ "./src/STL/stlFileLoader.ts"));
  1036. /***/ }),
  1037. /***/ "./src/STL/stlFileLoader.ts":
  1038. /*!**********************************!*\
  1039. !*** ./src/STL/stlFileLoader.ts ***!
  1040. \**********************************/
  1041. /*! no static exports found */
  1042. /***/ (function(module, exports, __webpack_require__) {
  1043. "use strict";
  1044. Object.defineProperty(exports, "__esModule", { value: true });
  1045. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1046. var STLFileLoader = /** @class */ (function () {
  1047. function STLFileLoader() {
  1048. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  1049. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  1050. 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;
  1051. 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;
  1052. this.name = "stl";
  1053. // force data to come in as an ArrayBuffer
  1054. // we'll convert to string if it looks like it's an ASCII .stl
  1055. this.extensions = {
  1056. ".stl": { isBinary: true },
  1057. };
  1058. }
  1059. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  1060. var matches;
  1061. if (typeof data !== "string") {
  1062. if (this.isBinary(data)) {
  1063. // binary .stl
  1064. var babylonMesh = new babylonjs_1.Mesh("stlmesh", scene);
  1065. this.parseBinary(babylonMesh, data);
  1066. if (meshes) {
  1067. meshes.push(babylonMesh);
  1068. }
  1069. return true;
  1070. }
  1071. // ASCII .stl
  1072. // convert to string
  1073. var array_buffer = new Uint8Array(data);
  1074. var str = '';
  1075. for (var i = 0; i < data.byteLength; i++) {
  1076. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  1077. }
  1078. data = str;
  1079. }
  1080. //if arrived here, data is a string, containing the STLA data.
  1081. while (matches = this.solidPattern.exec(data)) {
  1082. var meshName = matches[1];
  1083. var meshNameFromEnd = matches[3];
  1084. if (meshName != meshNameFromEnd) {
  1085. babylonjs_1.Tools.Error("Error in STL, solid name != endsolid name");
  1086. return false;
  1087. }
  1088. // check meshesNames
  1089. if (meshesNames && meshName) {
  1090. if (meshesNames instanceof Array) {
  1091. if (!meshesNames.indexOf(meshName)) {
  1092. continue;
  1093. }
  1094. }
  1095. else {
  1096. if (meshName !== meshesNames) {
  1097. continue;
  1098. }
  1099. }
  1100. }
  1101. // stl mesh name can be empty as well
  1102. meshName = meshName || "stlmesh";
  1103. var babylonMesh = new babylonjs_1.Mesh(meshName, scene);
  1104. this.parseASCII(babylonMesh, matches[2]);
  1105. if (meshes) {
  1106. meshes.push(babylonMesh);
  1107. }
  1108. }
  1109. return true;
  1110. };
  1111. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  1112. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  1113. if (result) {
  1114. scene.createDefaultCameraOrLight();
  1115. }
  1116. return result;
  1117. };
  1118. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  1119. var container = new babylonjs_1.AssetContainer(scene);
  1120. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  1121. container.removeAllFromScene();
  1122. return container;
  1123. };
  1124. STLFileLoader.prototype.isBinary = function (data) {
  1125. // check if file size is correct for binary stl
  1126. var faceSize, nFaces, reader;
  1127. reader = new DataView(data);
  1128. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  1129. nFaces = reader.getUint32(80, true);
  1130. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  1131. return true;
  1132. }
  1133. // check characters higher than ASCII to confirm binary
  1134. var fileLength = reader.byteLength;
  1135. for (var index = 0; index < fileLength; index++) {
  1136. if (reader.getUint8(index) > 127) {
  1137. return true;
  1138. }
  1139. }
  1140. return false;
  1141. };
  1142. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  1143. var reader = new DataView(data);
  1144. var faces = reader.getUint32(80, true);
  1145. var dataOffset = 84;
  1146. var faceLength = 12 * 4 + 2;
  1147. var offset = 0;
  1148. var positions = new Float32Array(faces * 3 * 3);
  1149. var normals = new Float32Array(faces * 3 * 3);
  1150. var indices = new Uint32Array(faces * 3);
  1151. var indicesCount = 0;
  1152. for (var face = 0; face < faces; face++) {
  1153. var start = dataOffset + face * faceLength;
  1154. var normalX = reader.getFloat32(start, true);
  1155. var normalY = reader.getFloat32(start + 4, true);
  1156. var normalZ = reader.getFloat32(start + 8, true);
  1157. for (var i = 1; i <= 3; i++) {
  1158. var vertexstart = start + i * 12;
  1159. // ordering is intentional to match ascii import
  1160. positions[offset] = reader.getFloat32(vertexstart, true);
  1161. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  1162. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  1163. normals[offset] = normalX;
  1164. normals[offset + 2] = normalY;
  1165. normals[offset + 1] = normalZ;
  1166. offset += 3;
  1167. }
  1168. indices[indicesCount] = indicesCount++;
  1169. indices[indicesCount] = indicesCount++;
  1170. indices[indicesCount] = indicesCount++;
  1171. }
  1172. mesh.setVerticesData(babylonjs_1.VertexBuffer.PositionKind, positions);
  1173. mesh.setVerticesData(babylonjs_1.VertexBuffer.NormalKind, normals);
  1174. mesh.setIndices(indices);
  1175. mesh.computeWorldMatrix(true);
  1176. };
  1177. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  1178. var positions = [];
  1179. var normals = [];
  1180. var indices = [];
  1181. var indicesCount = 0;
  1182. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  1183. var matches;
  1184. while (matches = this.facetsPattern.exec(solidData)) {
  1185. var facet = matches[1];
  1186. //one normal per face
  1187. var normalMatches = this.normalPattern.exec(facet);
  1188. this.normalPattern.lastIndex = 0;
  1189. if (!normalMatches) {
  1190. continue;
  1191. }
  1192. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  1193. var vertexMatch;
  1194. while (vertexMatch = this.vertexPattern.exec(facet)) {
  1195. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  1196. normals.push(normal[0], normal[1], normal[2]);
  1197. }
  1198. indices.push(indicesCount++, indicesCount++, indicesCount++);
  1199. this.vertexPattern.lastIndex = 0;
  1200. }
  1201. this.facetsPattern.lastIndex = 0;
  1202. mesh.setVerticesData(babylonjs_1.VertexBuffer.PositionKind, positions);
  1203. mesh.setVerticesData(babylonjs_1.VertexBuffer.NormalKind, normals);
  1204. mesh.setIndices(indices);
  1205. mesh.computeWorldMatrix(true);
  1206. };
  1207. return STLFileLoader;
  1208. }());
  1209. exports.STLFileLoader = STLFileLoader;
  1210. if (babylonjs_1.SceneLoader) {
  1211. babylonjs_1.SceneLoader.RegisterPlugin(new STLFileLoader());
  1212. }
  1213. /***/ }),
  1214. /***/ "./src/glTF/1.0/glTFBinaryExtension.ts":
  1215. /*!*********************************************!*\
  1216. !*** ./src/glTF/1.0/glTFBinaryExtension.ts ***!
  1217. \*********************************************/
  1218. /*! no static exports found */
  1219. /***/ (function(module, exports, __webpack_require__) {
  1220. "use strict";
  1221. var __extends = (this && this.__extends) || (function () {
  1222. var extendStatics = function (d, b) {
  1223. extendStatics = Object.setPrototypeOf ||
  1224. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1225. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1226. return extendStatics(d, b);
  1227. }
  1228. return function (d, b) {
  1229. extendStatics(d, b);
  1230. function __() { this.constructor = d; }
  1231. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1232. };
  1233. })();
  1234. Object.defineProperty(exports, "__esModule", { value: true });
  1235. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  1236. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  1237. var glTFLoaderV1_1 = __webpack_require__(/*! ./glTFLoaderV1 */ "./src/glTF/1.0/glTFLoaderV1.ts");
  1238. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  1239. var glTFLoaderV1_2 = __webpack_require__(/*! ./glTFLoaderV1 */ "./src/glTF/1.0/glTFLoaderV1.ts");
  1240. var BinaryExtensionBufferName = "binary_glTF";
  1241. var GLTFBinaryExtension = /** @class */ (function (_super) {
  1242. __extends(GLTFBinaryExtension, _super);
  1243. function GLTFBinaryExtension() {
  1244. return _super.call(this, "KHR_binary_glTF") || this;
  1245. }
  1246. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1247. var extensionsUsed = data.json.extensionsUsed;
  1248. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  1249. return false;
  1250. }
  1251. this._bin = data.bin;
  1252. onSuccess(glTFLoaderV1_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  1253. return true;
  1254. };
  1255. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1256. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1257. return false;
  1258. }
  1259. if (id !== BinaryExtensionBufferName) {
  1260. return false;
  1261. }
  1262. onSuccess(this._bin);
  1263. return true;
  1264. };
  1265. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1266. var texture = gltfRuntime.textures[id];
  1267. var source = gltfRuntime.images[texture.source];
  1268. if (!source.extensions || !(this.name in source.extensions)) {
  1269. return false;
  1270. }
  1271. var sourceExt = source.extensions[this.name];
  1272. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1273. var buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  1274. onSuccess(buffer);
  1275. return true;
  1276. };
  1277. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1278. var shader = gltfRuntime.shaders[id];
  1279. if (!shader.extensions || !(this.name in shader.extensions)) {
  1280. return false;
  1281. }
  1282. var binaryExtensionShader = shader.extensions[this.name];
  1283. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1284. var shaderBytes = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  1285. setTimeout(function () {
  1286. var shaderString = glTFLoaderUtils_1.GLTFUtils.DecodeBufferToText(shaderBytes);
  1287. onSuccess(shaderString);
  1288. });
  1289. return true;
  1290. };
  1291. return GLTFBinaryExtension;
  1292. }(glTFLoaderExtension_1.GLTFLoaderExtension));
  1293. exports.GLTFBinaryExtension = GLTFBinaryExtension;
  1294. glTFLoaderV1_2.GLTFLoaderV1.RegisterExtension(new GLTFBinaryExtension());
  1295. /***/ }),
  1296. /***/ "./src/glTF/1.0/glTFLoaderExtension.ts":
  1297. /*!*********************************************!*\
  1298. !*** ./src/glTF/1.0/glTFLoaderExtension.ts ***!
  1299. \*********************************************/
  1300. /*! no static exports found */
  1301. /***/ (function(module, exports, __webpack_require__) {
  1302. "use strict";
  1303. Object.defineProperty(exports, "__esModule", { value: true });
  1304. var glTFLoaderV1_1 = __webpack_require__(/*! ./glTFLoaderV1 */ "./src/glTF/1.0/glTFLoaderV1.ts");
  1305. var GLTFLoaderExtension = /** @class */ (function () {
  1306. function GLTFLoaderExtension(name) {
  1307. this._name = name;
  1308. }
  1309. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1310. get: function () {
  1311. return this._name;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. /**
  1317. * Defines an override for loading the runtime
  1318. * Return true to stop further extensions from loading the runtime
  1319. */
  1320. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1321. return false;
  1322. };
  1323. /**
  1324. * Defines an onverride for creating gltf runtime
  1325. * Return true to stop further extensions from creating the runtime
  1326. */
  1327. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1328. return false;
  1329. };
  1330. /**
  1331. * Defines an override for loading buffers
  1332. * Return true to stop further extensions from loading this buffer
  1333. */
  1334. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1335. return false;
  1336. };
  1337. /**
  1338. * Defines an override for loading texture buffers
  1339. * Return true to stop further extensions from loading this texture data
  1340. */
  1341. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1342. return false;
  1343. };
  1344. /**
  1345. * Defines an override for creating textures
  1346. * Return true to stop further extensions from loading this texture
  1347. */
  1348. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1349. return false;
  1350. };
  1351. /**
  1352. * Defines an override for loading shader strings
  1353. * Return true to stop further extensions from loading this shader data
  1354. */
  1355. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1356. return false;
  1357. };
  1358. /**
  1359. * Defines an override for loading materials
  1360. * Return true to stop further extensions from loading this material
  1361. */
  1362. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1363. return false;
  1364. };
  1365. // ---------
  1366. // Utilities
  1367. // ---------
  1368. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1369. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1370. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1371. }, function () {
  1372. setTimeout(function () {
  1373. if (!onSuccess) {
  1374. return;
  1375. }
  1376. onSuccess(glTFLoaderV1_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  1377. });
  1378. });
  1379. };
  1380. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1381. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1382. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  1383. }, function () {
  1384. setTimeout(function () {
  1385. onSuccess();
  1386. });
  1387. });
  1388. };
  1389. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1390. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1391. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1392. }, function () {
  1393. glTFLoaderV1_1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1394. });
  1395. };
  1396. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1397. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  1398. if (buffer) {
  1399. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1400. }
  1401. }, onError);
  1402. };
  1403. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1404. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1405. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1406. }, function () {
  1407. glTFLoaderV1_1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1408. });
  1409. };
  1410. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1411. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1412. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1413. }, function () {
  1414. glTFLoaderV1_1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1415. });
  1416. };
  1417. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1418. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1419. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1420. }, function () {
  1421. glTFLoaderV1_1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1422. });
  1423. };
  1424. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1425. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1426. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1427. }, function () {
  1428. glTFLoaderV1_1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1429. });
  1430. };
  1431. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1432. for (var extensionName in glTFLoaderV1_1.GLTFLoaderV1.Extensions) {
  1433. var loaderExtension = glTFLoaderV1_1.GLTFLoaderV1.Extensions[extensionName];
  1434. if (func(loaderExtension)) {
  1435. return;
  1436. }
  1437. }
  1438. defaultFunc();
  1439. };
  1440. return GLTFLoaderExtension;
  1441. }());
  1442. exports.GLTFLoaderExtension = GLTFLoaderExtension;
  1443. /***/ }),
  1444. /***/ "./src/glTF/1.0/glTFLoaderInterfaces.ts":
  1445. /*!**********************************************!*\
  1446. !*** ./src/glTF/1.0/glTFLoaderInterfaces.ts ***!
  1447. \**********************************************/
  1448. /*! no static exports found */
  1449. /***/ (function(module, exports, __webpack_require__) {
  1450. "use strict";
  1451. Object.defineProperty(exports, "__esModule", { value: true });
  1452. /**
  1453. * Enums
  1454. */
  1455. var EComponentType;
  1456. (function (EComponentType) {
  1457. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1458. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1459. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1460. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1461. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1462. })(EComponentType = exports.EComponentType || (exports.EComponentType = {}));
  1463. var EShaderType;
  1464. (function (EShaderType) {
  1465. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1466. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1467. })(EShaderType = exports.EShaderType || (exports.EShaderType = {}));
  1468. var EParameterType;
  1469. (function (EParameterType) {
  1470. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1471. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1472. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1473. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1474. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1475. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1476. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1477. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1478. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1479. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1480. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1481. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1482. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1483. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1484. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1485. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1486. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1487. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1488. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1489. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1490. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1491. })(EParameterType = exports.EParameterType || (exports.EParameterType = {}));
  1492. var ETextureWrapMode;
  1493. (function (ETextureWrapMode) {
  1494. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1495. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1496. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1497. })(ETextureWrapMode = exports.ETextureWrapMode || (exports.ETextureWrapMode = {}));
  1498. var ETextureFilterType;
  1499. (function (ETextureFilterType) {
  1500. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1501. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1502. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1503. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1504. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1505. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1506. })(ETextureFilterType = exports.ETextureFilterType || (exports.ETextureFilterType = {}));
  1507. var ETextureFormat;
  1508. (function (ETextureFormat) {
  1509. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1510. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1511. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1512. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1513. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1514. })(ETextureFormat = exports.ETextureFormat || (exports.ETextureFormat = {}));
  1515. var ECullingType;
  1516. (function (ECullingType) {
  1517. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1518. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1519. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1520. })(ECullingType = exports.ECullingType || (exports.ECullingType = {}));
  1521. var EBlendingFunction;
  1522. (function (EBlendingFunction) {
  1523. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1524. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1525. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1526. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1527. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1528. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1529. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1530. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  1531. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  1532. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  1533. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  1534. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  1535. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  1536. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  1537. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  1538. })(EBlendingFunction = exports.EBlendingFunction || (exports.EBlendingFunction = {}));
  1539. /***/ }),
  1540. /***/ "./src/glTF/1.0/glTFLoaderUtils.ts":
  1541. /*!*****************************************!*\
  1542. !*** ./src/glTF/1.0/glTFLoaderUtils.ts ***!
  1543. \*****************************************/
  1544. /*! no static exports found */
  1545. /***/ (function(module, exports, __webpack_require__) {
  1546. "use strict";
  1547. Object.defineProperty(exports, "__esModule", { value: true });
  1548. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1549. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  1550. /**
  1551. * Utils functions for GLTF
  1552. */
  1553. var GLTFUtils = /** @class */ (function () {
  1554. function GLTFUtils() {
  1555. }
  1556. /**
  1557. * Sets the given "parameter" matrix
  1558. * @param scene: the Scene object
  1559. * @param source: the source node where to pick the matrix
  1560. * @param parameter: the GLTF technique parameter
  1561. * @param uniformName: the name of the shader's uniform
  1562. * @param shaderMaterial: the shader material
  1563. */
  1564. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1565. var mat = null;
  1566. if (parameter.semantic === "MODEL") {
  1567. mat = source.getWorldMatrix();
  1568. }
  1569. else if (parameter.semantic === "PROJECTION") {
  1570. mat = scene.getProjectionMatrix();
  1571. }
  1572. else if (parameter.semantic === "VIEW") {
  1573. mat = scene.getViewMatrix();
  1574. }
  1575. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1576. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1577. }
  1578. else if (parameter.semantic === "MODELVIEW") {
  1579. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1580. }
  1581. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1582. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1583. }
  1584. else if (parameter.semantic === "MODELINVERSE") {
  1585. mat = source.getWorldMatrix().invert();
  1586. }
  1587. else if (parameter.semantic === "VIEWINVERSE") {
  1588. mat = scene.getViewMatrix().invert();
  1589. }
  1590. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1591. mat = scene.getProjectionMatrix().invert();
  1592. }
  1593. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1594. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1595. }
  1596. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1597. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1598. }
  1599. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1600. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().invert());
  1601. }
  1602. else {
  1603. debugger;
  1604. }
  1605. if (mat) {
  1606. switch (parameter.type) {
  1607. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2:
  1608. shaderMaterial.setMatrix2x2(uniformName, babylonjs_1.Matrix.GetAsMatrix2x2(mat));
  1609. break;
  1610. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3:
  1611. shaderMaterial.setMatrix3x3(uniformName, babylonjs_1.Matrix.GetAsMatrix3x3(mat));
  1612. break;
  1613. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4:
  1614. shaderMaterial.setMatrix(uniformName, mat);
  1615. break;
  1616. default: break;
  1617. }
  1618. }
  1619. };
  1620. /**
  1621. * Sets the given "parameter" matrix
  1622. * @param shaderMaterial: the shader material
  1623. * @param uniform: the name of the shader's uniform
  1624. * @param value: the value of the uniform
  1625. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1626. */
  1627. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1628. switch (type) {
  1629. case glTFLoaderInterfaces_1.EParameterType.FLOAT:
  1630. shaderMaterial.setFloat(uniform, value);
  1631. return true;
  1632. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC2:
  1633. shaderMaterial.setVector2(uniform, babylonjs_1.Vector2.FromArray(value));
  1634. return true;
  1635. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC3:
  1636. shaderMaterial.setVector3(uniform, babylonjs_1.Vector3.FromArray(value));
  1637. return true;
  1638. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC4:
  1639. shaderMaterial.setVector4(uniform, babylonjs_1.Vector4.FromArray(value));
  1640. return true;
  1641. default: return false;
  1642. }
  1643. };
  1644. /**
  1645. * Returns the wrap mode of the texture
  1646. * @param mode: the mode value
  1647. */
  1648. GLTFUtils.GetWrapMode = function (mode) {
  1649. switch (mode) {
  1650. case glTFLoaderInterfaces_1.ETextureWrapMode.CLAMP_TO_EDGE: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  1651. case glTFLoaderInterfaces_1.ETextureWrapMode.MIRRORED_REPEAT: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  1652. case glTFLoaderInterfaces_1.ETextureWrapMode.REPEAT: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  1653. default: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  1654. }
  1655. };
  1656. /**
  1657. * Returns the byte stride giving an accessor
  1658. * @param accessor: the GLTF accessor objet
  1659. */
  1660. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1661. // Needs this function since "byteStride" isn't requiered in glTF format
  1662. var type = accessor.type;
  1663. switch (type) {
  1664. case "VEC2": return 2;
  1665. case "VEC3": return 3;
  1666. case "VEC4": return 4;
  1667. case "MAT2": return 4;
  1668. case "MAT3": return 9;
  1669. case "MAT4": return 16;
  1670. default: return 1;
  1671. }
  1672. };
  1673. /**
  1674. * Returns the texture filter mode giving a mode value
  1675. * @param mode: the filter mode value
  1676. */
  1677. GLTFUtils.GetTextureFilterMode = function (mode) {
  1678. switch (mode) {
  1679. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR:
  1680. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1681. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return babylonjs_1.Texture.TRILINEAR_SAMPLINGMODE;
  1682. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST:
  1683. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return babylonjs_1.Texture.NEAREST_SAMPLINGMODE;
  1684. default: return babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  1685. }
  1686. };
  1687. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1688. var byteOffset = bufferView.byteOffset + byteOffset;
  1689. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1690. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1691. throw new Error("Buffer access is out of range");
  1692. }
  1693. var buffer = loadedBufferView.buffer;
  1694. byteOffset += loadedBufferView.byteOffset;
  1695. switch (componentType) {
  1696. case glTFLoaderInterfaces_1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1697. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1698. case glTFLoaderInterfaces_1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1699. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1700. default: return new Float32Array(buffer, byteOffset, byteLength);
  1701. }
  1702. };
  1703. /**
  1704. * Returns a buffer from its accessor
  1705. * @param gltfRuntime: the GLTF runtime
  1706. * @param accessor: the GLTF accessor
  1707. */
  1708. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1709. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1710. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1711. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1712. };
  1713. /**
  1714. * Decodes a buffer view into a string
  1715. * @param view: the buffer view
  1716. */
  1717. GLTFUtils.DecodeBufferToText = function (view) {
  1718. var result = "";
  1719. var length = view.byteLength;
  1720. for (var i = 0; i < length; ++i) {
  1721. result += String.fromCharCode(view[i]);
  1722. }
  1723. return result;
  1724. };
  1725. /**
  1726. * Returns the default material of gltf. Related to
  1727. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1728. * @param scene: the Babylon.js scene
  1729. */
  1730. GLTFUtils.GetDefaultMaterial = function (scene) {
  1731. if (!GLTFUtils._DefaultMaterial) {
  1732. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  1733. "precision highp float;",
  1734. "",
  1735. "uniform mat4 worldView;",
  1736. "uniform mat4 projection;",
  1737. "",
  1738. "attribute vec3 position;",
  1739. "",
  1740. "void main(void)",
  1741. "{",
  1742. " gl_Position = projection * worldView * vec4(position, 1.0);",
  1743. "}"
  1744. ].join("\n");
  1745. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  1746. "precision highp float;",
  1747. "",
  1748. "uniform vec4 u_emission;",
  1749. "",
  1750. "void main(void)",
  1751. "{",
  1752. " gl_FragColor = u_emission;",
  1753. "}"
  1754. ].join("\n");
  1755. var shaderPath = {
  1756. vertex: "GLTFDefaultMaterial",
  1757. fragment: "GLTFDefaultMaterial"
  1758. };
  1759. var options = {
  1760. attributes: ["position"],
  1761. uniforms: ["worldView", "projection", "u_emission"],
  1762. samplers: new Array(),
  1763. needAlphaBlending: false
  1764. };
  1765. GLTFUtils._DefaultMaterial = new babylonjs_1.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  1766. GLTFUtils._DefaultMaterial.setColor4("u_emission", new babylonjs_1.Color4(0.5, 0.5, 0.5, 1.0));
  1767. }
  1768. return GLTFUtils._DefaultMaterial;
  1769. };
  1770. // The GLTF default material
  1771. GLTFUtils._DefaultMaterial = null;
  1772. return GLTFUtils;
  1773. }());
  1774. exports.GLTFUtils = GLTFUtils;
  1775. /***/ }),
  1776. /***/ "./src/glTF/1.0/glTFLoaderV1.ts":
  1777. /*!**************************************!*\
  1778. !*** ./src/glTF/1.0/glTFLoaderV1.ts ***!
  1779. \**************************************/
  1780. /*! no static exports found */
  1781. /***/ (function(module, exports, __webpack_require__) {
  1782. "use strict";
  1783. Object.defineProperty(exports, "__esModule", { value: true });
  1784. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  1785. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  1786. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1787. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  1788. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  1789. /**
  1790. * Tokenizer. Used for shaders compatibility
  1791. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1792. */
  1793. var ETokenType;
  1794. (function (ETokenType) {
  1795. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1796. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1797. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1798. })(ETokenType || (ETokenType = {}));
  1799. var Tokenizer = /** @class */ (function () {
  1800. function Tokenizer(toParse) {
  1801. this._pos = 0;
  1802. this.currentToken = ETokenType.UNKNOWN;
  1803. this.currentIdentifier = "";
  1804. this.currentString = "";
  1805. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1806. this._toParse = toParse;
  1807. this._maxPos = toParse.length;
  1808. }
  1809. Tokenizer.prototype.getNextToken = function () {
  1810. if (this.isEnd()) {
  1811. return ETokenType.END_OF_INPUT;
  1812. }
  1813. this.currentString = this.read();
  1814. this.currentToken = ETokenType.UNKNOWN;
  1815. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1816. this.currentToken = ETokenType.IDENTIFIER;
  1817. this.currentIdentifier = this.currentString;
  1818. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1819. this.currentIdentifier += this.currentString;
  1820. this.forward();
  1821. }
  1822. }
  1823. return this.currentToken;
  1824. };
  1825. Tokenizer.prototype.peek = function () {
  1826. return this._toParse[this._pos];
  1827. };
  1828. Tokenizer.prototype.read = function () {
  1829. return this._toParse[this._pos++];
  1830. };
  1831. Tokenizer.prototype.forward = function () {
  1832. this._pos++;
  1833. };
  1834. Tokenizer.prototype.isEnd = function () {
  1835. return this._pos >= this._maxPos;
  1836. };
  1837. return Tokenizer;
  1838. }());
  1839. /**
  1840. * Values
  1841. */
  1842. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1843. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1844. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1845. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1846. /**
  1847. * Parse
  1848. */
  1849. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1850. for (var buf in parsedBuffers) {
  1851. var parsedBuffer = parsedBuffers[buf];
  1852. gltfRuntime.buffers[buf] = parsedBuffer;
  1853. gltfRuntime.buffersCount++;
  1854. }
  1855. };
  1856. var parseShaders = function (parsedShaders, gltfRuntime) {
  1857. for (var sha in parsedShaders) {
  1858. var parsedShader = parsedShaders[sha];
  1859. gltfRuntime.shaders[sha] = parsedShader;
  1860. gltfRuntime.shaderscount++;
  1861. }
  1862. };
  1863. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1864. for (var object in parsedObjects) {
  1865. var parsedObject = parsedObjects[object];
  1866. gltfRuntime[runtimeProperty][object] = parsedObject;
  1867. }
  1868. };
  1869. /**
  1870. * Utils
  1871. */
  1872. var normalizeUVs = function (buffer) {
  1873. if (!buffer) {
  1874. return;
  1875. }
  1876. for (var i = 0; i < buffer.length / 2; i++) {
  1877. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  1878. }
  1879. };
  1880. var getAttribute = function (attributeParameter) {
  1881. if (attributeParameter.semantic === "NORMAL") {
  1882. return "normal";
  1883. }
  1884. else if (attributeParameter.semantic === "POSITION") {
  1885. return "position";
  1886. }
  1887. else if (attributeParameter.semantic === "JOINT") {
  1888. return "matricesIndices";
  1889. }
  1890. else if (attributeParameter.semantic === "WEIGHT") {
  1891. return "matricesWeights";
  1892. }
  1893. else if (attributeParameter.semantic === "COLOR") {
  1894. return "color";
  1895. }
  1896. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  1897. var channel = Number(attributeParameter.semantic.split("_")[1]);
  1898. return "uv" + (channel === 0 ? "" : channel + 1);
  1899. }
  1900. return null;
  1901. };
  1902. /**
  1903. * Loads and creates animations
  1904. */
  1905. var loadAnimations = function (gltfRuntime) {
  1906. for (var anim in gltfRuntime.animations) {
  1907. var animation = gltfRuntime.animations[anim];
  1908. if (!animation.channels || !animation.samplers) {
  1909. continue;
  1910. }
  1911. var lastAnimation = null;
  1912. for (var i = 0; i < animation.channels.length; i++) {
  1913. // Get parameters and load buffers
  1914. var channel = animation.channels[i];
  1915. var sampler = animation.samplers[channel.sampler];
  1916. if (!sampler) {
  1917. continue;
  1918. }
  1919. var inputData = null;
  1920. var outputData = null;
  1921. if (animation.parameters) {
  1922. inputData = animation.parameters[sampler.input];
  1923. outputData = animation.parameters[sampler.output];
  1924. }
  1925. else {
  1926. inputData = sampler.input;
  1927. outputData = sampler.output;
  1928. }
  1929. var bufferInput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  1930. var bufferOutput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  1931. var targetID = channel.target.id;
  1932. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  1933. if (targetNode === null) {
  1934. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  1935. }
  1936. if (targetNode === null) {
  1937. babylonjs_1.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  1938. continue;
  1939. }
  1940. var isBone = targetNode instanceof babylonjs_1.Bone;
  1941. // Get target path (position, rotation or scaling)
  1942. var targetPath = channel.target.path;
  1943. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1944. if (targetPathIndex !== -1) {
  1945. targetPath = babylonAnimationPaths[targetPathIndex];
  1946. }
  1947. // Determine animation type
  1948. var animationType = babylonjs_1.Animation.ANIMATIONTYPE_MATRIX;
  1949. if (!isBone) {
  1950. if (targetPath === "rotationQuaternion") {
  1951. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  1952. targetNode.rotationQuaternion = new babylonjs_1.Quaternion();
  1953. }
  1954. else {
  1955. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  1956. }
  1957. }
  1958. // Create animation and key frames
  1959. var babylonAnimation = null;
  1960. var keys = [];
  1961. var arrayOffset = 0;
  1962. var modifyKey = false;
  1963. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1964. babylonAnimation = lastAnimation;
  1965. modifyKey = true;
  1966. }
  1967. if (!modifyKey) {
  1968. babylonAnimation = new babylonjs_1.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, babylonjs_1.Animation.ANIMATIONLOOPMODE_CYCLE);
  1969. }
  1970. // For each frame
  1971. for (var j = 0; j < bufferInput.length; j++) {
  1972. var value = null;
  1973. if (targetPath === "rotationQuaternion") { // VEC4
  1974. value = babylonjs_1.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1975. arrayOffset += 4;
  1976. }
  1977. else { // Position and scaling are VEC3
  1978. value = babylonjs_1.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1979. arrayOffset += 3;
  1980. }
  1981. if (isBone) {
  1982. var bone = targetNode;
  1983. var translation = babylonjs_1.Vector3.Zero();
  1984. var rotationQuaternion = new babylonjs_1.Quaternion();
  1985. var scaling = babylonjs_1.Vector3.Zero();
  1986. // Warning on decompose
  1987. var mat = bone.getBaseMatrix();
  1988. if (modifyKey && lastAnimation) {
  1989. mat = lastAnimation.getKeys()[j].value;
  1990. }
  1991. mat.decompose(scaling, rotationQuaternion, translation);
  1992. if (targetPath === "position") {
  1993. translation = value;
  1994. }
  1995. else if (targetPath === "rotationQuaternion") {
  1996. rotationQuaternion = value;
  1997. }
  1998. else {
  1999. scaling = value;
  2000. }
  2001. value = babylonjs_1.Matrix.Compose(scaling, rotationQuaternion, translation);
  2002. }
  2003. if (!modifyKey) {
  2004. keys.push({
  2005. frame: bufferInput[j],
  2006. value: value
  2007. });
  2008. }
  2009. else if (lastAnimation) {
  2010. lastAnimation.getKeys()[j].value = value;
  2011. }
  2012. }
  2013. // Finish
  2014. if (!modifyKey && babylonAnimation) {
  2015. babylonAnimation.setKeys(keys);
  2016. targetNode.animations.push(babylonAnimation);
  2017. }
  2018. lastAnimation = babylonAnimation;
  2019. gltfRuntime.scene.stopAnimation(targetNode);
  2020. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  2021. }
  2022. }
  2023. };
  2024. /**
  2025. * Returns the bones transformation matrix
  2026. */
  2027. var configureBoneTransformation = function (node) {
  2028. var mat = null;
  2029. if (node.translation || node.rotation || node.scale) {
  2030. var scale = babylonjs_1.Vector3.FromArray(node.scale || [1, 1, 1]);
  2031. var rotation = babylonjs_1.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  2032. var position = babylonjs_1.Vector3.FromArray(node.translation || [0, 0, 0]);
  2033. mat = babylonjs_1.Matrix.Compose(scale, rotation, position);
  2034. }
  2035. else {
  2036. mat = babylonjs_1.Matrix.FromArray(node.matrix);
  2037. }
  2038. return mat;
  2039. };
  2040. /**
  2041. * Returns the parent bone
  2042. */
  2043. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  2044. // Try to find
  2045. for (var i = 0; i < newSkeleton.bones.length; i++) {
  2046. if (newSkeleton.bones[i].name === jointName) {
  2047. return newSkeleton.bones[i];
  2048. }
  2049. }
  2050. // Not found, search in gltf nodes
  2051. var nodes = gltfRuntime.nodes;
  2052. for (var nde in nodes) {
  2053. var node = nodes[nde];
  2054. if (!node.jointName) {
  2055. continue;
  2056. }
  2057. var children = node.children;
  2058. for (var i = 0; i < children.length; i++) {
  2059. var child = gltfRuntime.nodes[children[i]];
  2060. if (!child.jointName) {
  2061. continue;
  2062. }
  2063. if (child.jointName === jointName) {
  2064. var mat = configureBoneTransformation(node);
  2065. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  2066. bone.id = nde;
  2067. return bone;
  2068. }
  2069. }
  2070. }
  2071. return null;
  2072. };
  2073. /**
  2074. * Returns the appropriate root node
  2075. */
  2076. var getNodeToRoot = function (nodesToRoot, id) {
  2077. for (var i = 0; i < nodesToRoot.length; i++) {
  2078. var nodeToRoot = nodesToRoot[i];
  2079. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  2080. var child = nodeToRoot.node.children[j];
  2081. if (child === id) {
  2082. return nodeToRoot.bone;
  2083. }
  2084. }
  2085. }
  2086. return null;
  2087. };
  2088. /**
  2089. * Returns the node with the joint name
  2090. */
  2091. var getJointNode = function (gltfRuntime, jointName) {
  2092. var nodes = gltfRuntime.nodes;
  2093. var node = nodes[jointName];
  2094. if (node) {
  2095. return {
  2096. node: node,
  2097. id: jointName
  2098. };
  2099. }
  2100. for (var nde in nodes) {
  2101. node = nodes[nde];
  2102. if (node.jointName === jointName) {
  2103. return {
  2104. node: node,
  2105. id: nde
  2106. };
  2107. }
  2108. }
  2109. return null;
  2110. };
  2111. /**
  2112. * Checks if a nodes is in joints
  2113. */
  2114. var nodeIsInJoints = function (skins, id) {
  2115. for (var i = 0; i < skins.jointNames.length; i++) {
  2116. if (skins.jointNames[i] === id) {
  2117. return true;
  2118. }
  2119. }
  2120. return false;
  2121. };
  2122. /**
  2123. * Fills the nodes to root for bones and builds hierarchy
  2124. */
  2125. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  2126. // Creates nodes for root
  2127. for (var nde in gltfRuntime.nodes) {
  2128. var node = gltfRuntime.nodes[nde];
  2129. var id = nde;
  2130. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  2131. continue;
  2132. }
  2133. // Create node to root bone
  2134. var mat = configureBoneTransformation(node);
  2135. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, null, mat);
  2136. bone.id = id;
  2137. nodesToRoot.push({ bone: bone, node: node, id: id });
  2138. }
  2139. // Parenting
  2140. for (var i = 0; i < nodesToRoot.length; i++) {
  2141. var nodeToRoot = nodesToRoot[i];
  2142. var children = nodeToRoot.node.children;
  2143. for (var j = 0; j < children.length; j++) {
  2144. var child = null;
  2145. for (var k = 0; k < nodesToRoot.length; k++) {
  2146. if (nodesToRoot[k].id === children[j]) {
  2147. child = nodesToRoot[k];
  2148. break;
  2149. }
  2150. }
  2151. if (child) {
  2152. child.bone._parent = nodeToRoot.bone;
  2153. nodeToRoot.bone.children.push(child.bone);
  2154. }
  2155. }
  2156. }
  2157. };
  2158. /**
  2159. * Imports a skeleton
  2160. */
  2161. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  2162. if (!newSkeleton) {
  2163. newSkeleton = new babylonjs_1.Skeleton(skins.name || "", "", gltfRuntime.scene);
  2164. }
  2165. if (!skins.babylonSkeleton) {
  2166. return newSkeleton;
  2167. }
  2168. // Find the root bones
  2169. var nodesToRoot = [];
  2170. var nodesToRootToAdd = [];
  2171. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  2172. newSkeleton.bones = [];
  2173. // Joints
  2174. for (var i = 0; i < skins.jointNames.length; i++) {
  2175. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  2176. if (!jointNode) {
  2177. continue;
  2178. }
  2179. var node = jointNode.node;
  2180. if (!node) {
  2181. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  2182. continue;
  2183. }
  2184. var id = jointNode.id;
  2185. // Optimize, if the bone already exists...
  2186. var existingBone = gltfRuntime.scene.getBoneByID(id);
  2187. if (existingBone) {
  2188. newSkeleton.bones.push(existingBone);
  2189. continue;
  2190. }
  2191. // Search for parent bone
  2192. var foundBone = false;
  2193. var parentBone = null;
  2194. for (var j = 0; j < i; j++) {
  2195. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  2196. if (!jointNode_1) {
  2197. continue;
  2198. }
  2199. var joint = jointNode_1.node;
  2200. if (!joint) {
  2201. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  2202. continue;
  2203. }
  2204. var children = joint.children;
  2205. if (!children) {
  2206. continue;
  2207. }
  2208. foundBone = false;
  2209. for (var k = 0; k < children.length; k++) {
  2210. if (children[k] === id) {
  2211. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  2212. foundBone = true;
  2213. break;
  2214. }
  2215. }
  2216. if (foundBone) {
  2217. break;
  2218. }
  2219. }
  2220. // Create bone
  2221. var mat = configureBoneTransformation(node);
  2222. if (!parentBone && nodesToRoot.length > 0) {
  2223. parentBone = getNodeToRoot(nodesToRoot, id);
  2224. if (parentBone) {
  2225. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  2226. nodesToRootToAdd.push(parentBone);
  2227. }
  2228. }
  2229. }
  2230. var bone = new babylonjs_1.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  2231. bone.id = id;
  2232. }
  2233. // Polish
  2234. var bones = newSkeleton.bones;
  2235. newSkeleton.bones = [];
  2236. for (var i = 0; i < skins.jointNames.length; i++) {
  2237. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  2238. if (!jointNode) {
  2239. continue;
  2240. }
  2241. for (var j = 0; j < bones.length; j++) {
  2242. if (bones[j].id === jointNode.id) {
  2243. newSkeleton.bones.push(bones[j]);
  2244. break;
  2245. }
  2246. }
  2247. }
  2248. newSkeleton.prepare();
  2249. // Finish
  2250. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  2251. newSkeleton.bones.push(nodesToRootToAdd[i]);
  2252. }
  2253. return newSkeleton;
  2254. };
  2255. /**
  2256. * Imports a mesh and its geometries
  2257. */
  2258. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  2259. if (!newMesh) {
  2260. newMesh = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  2261. newMesh.id = id;
  2262. }
  2263. if (!node.babylonNode) {
  2264. return newMesh;
  2265. }
  2266. var subMaterials = [];
  2267. var vertexData = null;
  2268. var verticesStarts = new Array();
  2269. var verticesCounts = new Array();
  2270. var indexStarts = new Array();
  2271. var indexCounts = new Array();
  2272. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2273. var meshID = meshes[meshIndex];
  2274. var mesh = gltfRuntime.meshes[meshID];
  2275. if (!mesh) {
  2276. continue;
  2277. }
  2278. // Positions, normals and UVs
  2279. for (var i = 0; i < mesh.primitives.length; i++) {
  2280. // Temporary vertex data
  2281. var tempVertexData = new babylonjs_1.VertexData();
  2282. var primitive = mesh.primitives[i];
  2283. if (primitive.mode !== 4) {
  2284. // continue;
  2285. }
  2286. var attributes = primitive.attributes;
  2287. var accessor = null;
  2288. var buffer = null;
  2289. // Set positions, normal and uvs
  2290. for (var semantic in attributes) {
  2291. // Link accessor and buffer view
  2292. accessor = gltfRuntime.accessors[attributes[semantic]];
  2293. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2294. if (semantic === "NORMAL") {
  2295. tempVertexData.normals = new Float32Array(buffer.length);
  2296. tempVertexData.normals.set(buffer);
  2297. }
  2298. else if (semantic === "POSITION") {
  2299. if (glTFFileLoader_1.GLTFFileLoader.HomogeneousCoordinates) {
  2300. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  2301. for (var j = 0; j < buffer.length; j += 4) {
  2302. tempVertexData.positions[j] = buffer[j];
  2303. tempVertexData.positions[j + 1] = buffer[j + 1];
  2304. tempVertexData.positions[j + 2] = buffer[j + 2];
  2305. }
  2306. }
  2307. else {
  2308. tempVertexData.positions = new Float32Array(buffer.length);
  2309. tempVertexData.positions.set(buffer);
  2310. }
  2311. verticesCounts.push(tempVertexData.positions.length);
  2312. }
  2313. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2314. var channel = Number(semantic.split("_")[1]);
  2315. var uvKind = babylonjs_1.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2316. var uvs = new Float32Array(buffer.length);
  2317. uvs.set(buffer);
  2318. normalizeUVs(uvs);
  2319. tempVertexData.set(uvs, uvKind);
  2320. }
  2321. else if (semantic === "JOINT") {
  2322. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  2323. tempVertexData.matricesIndices.set(buffer);
  2324. }
  2325. else if (semantic === "WEIGHT") {
  2326. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  2327. tempVertexData.matricesWeights.set(buffer);
  2328. }
  2329. else if (semantic === "COLOR") {
  2330. tempVertexData.colors = new Float32Array(buffer.length);
  2331. tempVertexData.colors.set(buffer);
  2332. }
  2333. }
  2334. // Indices
  2335. accessor = gltfRuntime.accessors[primitive.indices];
  2336. if (accessor) {
  2337. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2338. tempVertexData.indices = new Int32Array(buffer.length);
  2339. tempVertexData.indices.set(buffer);
  2340. indexCounts.push(tempVertexData.indices.length);
  2341. }
  2342. else {
  2343. // Set indices on the fly
  2344. var indices = [];
  2345. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  2346. indices.push(j);
  2347. }
  2348. tempVertexData.indices = new Int32Array(indices);
  2349. indexCounts.push(tempVertexData.indices.length);
  2350. }
  2351. if (!vertexData) {
  2352. vertexData = tempVertexData;
  2353. }
  2354. else {
  2355. vertexData.merge(tempVertexData);
  2356. }
  2357. // Sub material
  2358. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  2359. subMaterials.push(material_1 === null ? glTFLoaderUtils_1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  2360. // Update vertices start and index start
  2361. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2362. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2363. }
  2364. }
  2365. var material;
  2366. if (subMaterials.length > 1) {
  2367. material = new babylonjs_1.MultiMaterial("multimat" + id, gltfRuntime.scene);
  2368. material.subMaterials = subMaterials;
  2369. }
  2370. else {
  2371. material = new babylonjs_1.StandardMaterial("multimat" + id, gltfRuntime.scene);
  2372. }
  2373. if (subMaterials.length === 1) {
  2374. material = subMaterials[0];
  2375. }
  2376. if (!newMesh.material) {
  2377. newMesh.material = material;
  2378. }
  2379. // Apply geometry
  2380. new babylonjs_1.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  2381. newMesh.computeWorldMatrix(true);
  2382. // Apply submeshes
  2383. newMesh.subMeshes = [];
  2384. var index = 0;
  2385. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2386. var meshID = meshes[meshIndex];
  2387. var mesh = gltfRuntime.meshes[meshID];
  2388. if (!mesh) {
  2389. continue;
  2390. }
  2391. for (var i = 0; i < mesh.primitives.length; i++) {
  2392. if (mesh.primitives[i].mode !== 4) {
  2393. //continue;
  2394. }
  2395. babylonjs_1.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  2396. index++;
  2397. }
  2398. }
  2399. // Finish
  2400. return newMesh;
  2401. };
  2402. /**
  2403. * Configure node transformation from position, rotation and scaling
  2404. */
  2405. var configureNode = function (newNode, position, rotation, scaling) {
  2406. if (newNode.position) {
  2407. newNode.position = position;
  2408. }
  2409. if (newNode.rotationQuaternion || newNode.rotation) {
  2410. newNode.rotationQuaternion = rotation;
  2411. }
  2412. if (newNode.scaling) {
  2413. newNode.scaling = scaling;
  2414. }
  2415. };
  2416. /**
  2417. * Configures node from transformation matrix
  2418. */
  2419. var configureNodeFromMatrix = function (newNode, node, parent) {
  2420. if (node.matrix) {
  2421. var position = new babylonjs_1.Vector3(0, 0, 0);
  2422. var rotation = new babylonjs_1.Quaternion();
  2423. var scaling = new babylonjs_1.Vector3(0, 0, 0);
  2424. var mat = babylonjs_1.Matrix.FromArray(node.matrix);
  2425. mat.decompose(scaling, rotation, position);
  2426. configureNode(newNode, position, rotation, scaling);
  2427. }
  2428. else if (node.translation && node.rotation && node.scale) {
  2429. configureNode(newNode, babylonjs_1.Vector3.FromArray(node.translation), babylonjs_1.Quaternion.FromArray(node.rotation), babylonjs_1.Vector3.FromArray(node.scale));
  2430. }
  2431. newNode.computeWorldMatrix(true);
  2432. };
  2433. /**
  2434. * Imports a node
  2435. */
  2436. var importNode = function (gltfRuntime, node, id, parent) {
  2437. var lastNode = null;
  2438. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  2439. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  2440. return null;
  2441. }
  2442. }
  2443. // Meshes
  2444. if (node.skin) {
  2445. if (node.meshes) {
  2446. var skin = gltfRuntime.skins[node.skin];
  2447. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  2448. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  2449. if (newMesh.skeleton === null) {
  2450. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  2451. if (!skin.babylonSkeleton) {
  2452. skin.babylonSkeleton = newMesh.skeleton;
  2453. }
  2454. }
  2455. lastNode = newMesh;
  2456. }
  2457. }
  2458. else if (node.meshes) {
  2459. /**
  2460. * Improve meshes property
  2461. */
  2462. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  2463. lastNode = newMesh;
  2464. }
  2465. // Lights
  2466. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2467. var light = gltfRuntime.lights[node.light];
  2468. if (light) {
  2469. if (light.type === "ambient") {
  2470. var ambienLight = light[light.type];
  2471. var hemiLight = new babylonjs_1.HemisphericLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  2472. hemiLight.name = node.name || "";
  2473. if (ambienLight.color) {
  2474. hemiLight.diffuse = babylonjs_1.Color3.FromArray(ambienLight.color);
  2475. }
  2476. lastNode = hemiLight;
  2477. }
  2478. else if (light.type === "directional") {
  2479. var directionalLight = light[light.type];
  2480. var dirLight = new babylonjs_1.DirectionalLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  2481. dirLight.name = node.name || "";
  2482. if (directionalLight.color) {
  2483. dirLight.diffuse = babylonjs_1.Color3.FromArray(directionalLight.color);
  2484. }
  2485. lastNode = dirLight;
  2486. }
  2487. else if (light.type === "point") {
  2488. var pointLight = light[light.type];
  2489. var ptLight = new babylonjs_1.PointLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  2490. ptLight.name = node.name || "";
  2491. if (pointLight.color) {
  2492. ptLight.diffuse = babylonjs_1.Color3.FromArray(pointLight.color);
  2493. }
  2494. lastNode = ptLight;
  2495. }
  2496. else if (light.type === "spot") {
  2497. var spotLight = light[light.type];
  2498. var spLight = new babylonjs_1.SpotLight(node.light, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  2499. spLight.name = node.name || "";
  2500. if (spotLight.color) {
  2501. spLight.diffuse = babylonjs_1.Color3.FromArray(spotLight.color);
  2502. }
  2503. if (spotLight.fallOfAngle) {
  2504. spLight.angle = spotLight.fallOfAngle;
  2505. }
  2506. if (spotLight.fallOffExponent) {
  2507. spLight.exponent = spotLight.fallOffExponent;
  2508. }
  2509. lastNode = spLight;
  2510. }
  2511. }
  2512. }
  2513. // Cameras
  2514. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2515. var camera = gltfRuntime.cameras[node.camera];
  2516. if (camera) {
  2517. if (camera.type === "orthographic") {
  2518. var orthoCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  2519. orthoCamera.name = node.name || "";
  2520. orthoCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  2521. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2522. lastNode = orthoCamera;
  2523. }
  2524. else if (camera.type === "perspective") {
  2525. var perspectiveCamera = camera[camera.type];
  2526. var persCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  2527. persCamera.name = node.name || "";
  2528. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2529. if (!perspectiveCamera.aspectRatio) {
  2530. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2531. }
  2532. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2533. persCamera.maxZ = perspectiveCamera.zfar;
  2534. persCamera.minZ = perspectiveCamera.znear;
  2535. }
  2536. lastNode = persCamera;
  2537. }
  2538. }
  2539. }
  2540. // Empty node
  2541. if (!node.jointName) {
  2542. if (node.babylonNode) {
  2543. return node.babylonNode;
  2544. }
  2545. else if (lastNode === null) {
  2546. var dummy = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  2547. node.babylonNode = dummy;
  2548. lastNode = dummy;
  2549. }
  2550. }
  2551. if (lastNode !== null) {
  2552. if (node.matrix && lastNode instanceof babylonjs_1.Mesh) {
  2553. configureNodeFromMatrix(lastNode, node, parent);
  2554. }
  2555. else {
  2556. var translation = node.translation || [0, 0, 0];
  2557. var rotation = node.rotation || [0, 0, 0, 1];
  2558. var scale = node.scale || [1, 1, 1];
  2559. configureNode(lastNode, babylonjs_1.Vector3.FromArray(translation), babylonjs_1.Quaternion.FromArray(rotation), babylonjs_1.Vector3.FromArray(scale));
  2560. }
  2561. lastNode.updateCache(true);
  2562. node.babylonNode = lastNode;
  2563. }
  2564. return lastNode;
  2565. };
  2566. /**
  2567. * Traverses nodes and creates them
  2568. */
  2569. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2570. if (meshIncluded === void 0) { meshIncluded = false; }
  2571. var node = gltfRuntime.nodes[id];
  2572. var newNode = null;
  2573. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  2574. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2575. meshIncluded = true;
  2576. }
  2577. else {
  2578. meshIncluded = false;
  2579. }
  2580. }
  2581. else {
  2582. meshIncluded = true;
  2583. }
  2584. if (!node.jointName && meshIncluded) {
  2585. newNode = importNode(gltfRuntime, node, id, parent);
  2586. if (newNode !== null) {
  2587. newNode.id = id;
  2588. newNode.parent = parent;
  2589. }
  2590. }
  2591. if (node.children) {
  2592. for (var i = 0; i < node.children.length; i++) {
  2593. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2594. }
  2595. }
  2596. };
  2597. /**
  2598. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2599. */
  2600. var postLoad = function (gltfRuntime) {
  2601. // Nodes
  2602. var currentScene = gltfRuntime.currentScene;
  2603. if (currentScene) {
  2604. for (var i = 0; i < currentScene.nodes.length; i++) {
  2605. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2606. }
  2607. }
  2608. else {
  2609. for (var thing in gltfRuntime.scenes) {
  2610. currentScene = gltfRuntime.scenes[thing];
  2611. for (var i = 0; i < currentScene.nodes.length; i++) {
  2612. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2613. }
  2614. }
  2615. }
  2616. // Set animations
  2617. loadAnimations(gltfRuntime);
  2618. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2619. var skeleton = gltfRuntime.scene.skeletons[i];
  2620. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2621. }
  2622. };
  2623. /**
  2624. * onBind shaderrs callback to set uniforms and matrices
  2625. */
  2626. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2627. var materialValues = material.values || technique.parameters;
  2628. for (var unif in unTreatedUniforms) {
  2629. var uniform = unTreatedUniforms[unif];
  2630. var type = uniform.type;
  2631. if (type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4) {
  2632. if (uniform.semantic && !uniform.source && !uniform.node) {
  2633. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2634. }
  2635. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2636. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  2637. if (source === null) {
  2638. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  2639. }
  2640. if (source === null) {
  2641. continue;
  2642. }
  2643. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2644. }
  2645. }
  2646. else {
  2647. var value = materialValues[technique.uniforms[unif]];
  2648. if (!value) {
  2649. continue;
  2650. }
  2651. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  2652. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2653. if (texture === null || texture === undefined) {
  2654. continue;
  2655. }
  2656. shaderMaterial.getEffect().setTexture(unif, texture);
  2657. }
  2658. else {
  2659. glTFLoaderUtils_1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  2660. }
  2661. }
  2662. }
  2663. onSuccess(shaderMaterial);
  2664. };
  2665. /**
  2666. * Prepare uniforms to send the only one time
  2667. * Loads the appropriate textures
  2668. */
  2669. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2670. var materialValues = material.values || technique.parameters;
  2671. var techniqueUniforms = technique.uniforms;
  2672. /**
  2673. * Prepare values here (not matrices)
  2674. */
  2675. for (var unif in unTreatedUniforms) {
  2676. var uniform = unTreatedUniforms[unif];
  2677. var type = uniform.type;
  2678. var value = materialValues[techniqueUniforms[unif]];
  2679. if (value === undefined) {
  2680. // In case the value is the same for all materials
  2681. value = uniform.value;
  2682. }
  2683. if (!value) {
  2684. continue;
  2685. }
  2686. var onLoadTexture = function (uniformName) {
  2687. return function (texture) {
  2688. if (uniform.value && uniformName) {
  2689. // Static uniform
  2690. shaderMaterial.setTexture(uniformName, texture);
  2691. delete unTreatedUniforms[uniformName];
  2692. }
  2693. };
  2694. };
  2695. // Texture (sampler2D)
  2696. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  2697. glTFLoaderExtension_1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2698. }
  2699. // Others
  2700. else {
  2701. if (uniform.value && glTFLoaderUtils_1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2702. // Static uniform
  2703. delete unTreatedUniforms[unif];
  2704. }
  2705. }
  2706. }
  2707. };
  2708. /**
  2709. * Shader compilation failed
  2710. */
  2711. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2712. return function (effect, error) {
  2713. shaderMaterial.dispose(true);
  2714. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2715. };
  2716. };
  2717. /**
  2718. * Shader compilation success
  2719. */
  2720. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2721. return function (_) {
  2722. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2723. shaderMaterial.onBind = function (mesh) {
  2724. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2725. };
  2726. };
  2727. };
  2728. /**
  2729. * Returns the appropriate uniform if already handled by babylon
  2730. */
  2731. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2732. for (var unif in technique.uniforms) {
  2733. var uniform = technique.uniforms[unif];
  2734. var uniformParameter = technique.parameters[uniform];
  2735. if (tokenizer.currentIdentifier === unif) {
  2736. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2737. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2738. if (transformIndex !== -1) {
  2739. delete unTreatedUniforms[unif];
  2740. return babylonTransforms[transformIndex];
  2741. }
  2742. }
  2743. }
  2744. }
  2745. return tokenizer.currentIdentifier;
  2746. };
  2747. /**
  2748. * All shaders loaded. Create materials one by one
  2749. */
  2750. var importMaterials = function (gltfRuntime) {
  2751. // Create materials
  2752. for (var mat in gltfRuntime.materials) {
  2753. glTFLoaderExtension_1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2754. }
  2755. };
  2756. /**
  2757. * Implementation of the base glTF spec
  2758. */
  2759. var GLTFLoaderBase = /** @class */ (function () {
  2760. function GLTFLoaderBase() {
  2761. }
  2762. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2763. var gltfRuntime = {
  2764. extensions: {},
  2765. accessors: {},
  2766. buffers: {},
  2767. bufferViews: {},
  2768. meshes: {},
  2769. lights: {},
  2770. cameras: {},
  2771. nodes: {},
  2772. images: {},
  2773. textures: {},
  2774. shaders: {},
  2775. programs: {},
  2776. samplers: {},
  2777. techniques: {},
  2778. materials: {},
  2779. animations: {},
  2780. skins: {},
  2781. extensionsUsed: [],
  2782. scenes: {},
  2783. buffersCount: 0,
  2784. shaderscount: 0,
  2785. scene: scene,
  2786. rootUrl: rootUrl,
  2787. loadedBufferCount: 0,
  2788. loadedBufferViews: {},
  2789. loadedShaderCount: 0,
  2790. importOnlyMeshes: false,
  2791. dummyNodes: []
  2792. };
  2793. // Parse
  2794. if (parsedData.extensions) {
  2795. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2796. }
  2797. if (parsedData.extensionsUsed) {
  2798. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2799. }
  2800. if (parsedData.buffers) {
  2801. parseBuffers(parsedData.buffers, gltfRuntime);
  2802. }
  2803. if (parsedData.bufferViews) {
  2804. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2805. }
  2806. if (parsedData.accessors) {
  2807. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2808. }
  2809. if (parsedData.meshes) {
  2810. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2811. }
  2812. if (parsedData.lights) {
  2813. parseObject(parsedData.lights, "lights", gltfRuntime);
  2814. }
  2815. if (parsedData.cameras) {
  2816. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2817. }
  2818. if (parsedData.nodes) {
  2819. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2820. }
  2821. if (parsedData.images) {
  2822. parseObject(parsedData.images, "images", gltfRuntime);
  2823. }
  2824. if (parsedData.textures) {
  2825. parseObject(parsedData.textures, "textures", gltfRuntime);
  2826. }
  2827. if (parsedData.shaders) {
  2828. parseShaders(parsedData.shaders, gltfRuntime);
  2829. }
  2830. if (parsedData.programs) {
  2831. parseObject(parsedData.programs, "programs", gltfRuntime);
  2832. }
  2833. if (parsedData.samplers) {
  2834. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2835. }
  2836. if (parsedData.techniques) {
  2837. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2838. }
  2839. if (parsedData.materials) {
  2840. parseObject(parsedData.materials, "materials", gltfRuntime);
  2841. }
  2842. if (parsedData.animations) {
  2843. parseObject(parsedData.animations, "animations", gltfRuntime);
  2844. }
  2845. if (parsedData.skins) {
  2846. parseObject(parsedData.skins, "skins", gltfRuntime);
  2847. }
  2848. if (parsedData.scenes) {
  2849. gltfRuntime.scenes = parsedData.scenes;
  2850. }
  2851. if (parsedData.scene && parsedData.scenes) {
  2852. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2853. }
  2854. return gltfRuntime;
  2855. };
  2856. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2857. var buffer = gltfRuntime.buffers[id];
  2858. if (babylonjs_1.Tools.IsBase64(buffer.uri)) {
  2859. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(buffer.uri))); });
  2860. }
  2861. else {
  2862. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  2863. if (request) {
  2864. onError(request.status + " " + request.statusText);
  2865. }
  2866. });
  2867. }
  2868. };
  2869. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2870. var texture = gltfRuntime.textures[id];
  2871. if (!texture || !texture.source) {
  2872. onError("");
  2873. return;
  2874. }
  2875. if (texture.babylonTexture) {
  2876. onSuccess(null);
  2877. return;
  2878. }
  2879. var source = gltfRuntime.images[texture.source];
  2880. if (babylonjs_1.Tools.IsBase64(source.uri)) {
  2881. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(source.uri))); });
  2882. }
  2883. else {
  2884. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  2885. if (request) {
  2886. onError(request.status + " " + request.statusText);
  2887. }
  2888. });
  2889. }
  2890. };
  2891. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2892. var texture = gltfRuntime.textures[id];
  2893. if (texture.babylonTexture) {
  2894. onSuccess(texture.babylonTexture);
  2895. return;
  2896. }
  2897. var sampler = gltfRuntime.samplers[texture.sampler];
  2898. var createMipMaps = (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  2899. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  2900. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  2901. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  2902. var samplingMode = babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  2903. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  2904. var blobURL = URL.createObjectURL(blob);
  2905. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  2906. var newTexture = new babylonjs_1.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  2907. if (sampler.wrapS !== undefined) {
  2908. newTexture.wrapU = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapS);
  2909. }
  2910. if (sampler.wrapT !== undefined) {
  2911. newTexture.wrapV = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapT);
  2912. }
  2913. newTexture.name = id;
  2914. texture.babylonTexture = newTexture;
  2915. onSuccess(newTexture);
  2916. };
  2917. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2918. var shader = gltfRuntime.shaders[id];
  2919. if (babylonjs_1.Tools.IsBase64(shader.uri)) {
  2920. var shaderString = atob(shader.uri.split(",")[1]);
  2921. if (onSuccess) {
  2922. onSuccess(shaderString);
  2923. }
  2924. }
  2925. else {
  2926. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  2927. if (request && onError) {
  2928. onError(request.status + " " + request.statusText);
  2929. }
  2930. });
  2931. }
  2932. };
  2933. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2934. var material = gltfRuntime.materials[id];
  2935. if (!material.technique) {
  2936. if (onError) {
  2937. onError("No technique found.");
  2938. }
  2939. return;
  2940. }
  2941. var technique = gltfRuntime.techniques[material.technique];
  2942. if (!technique) {
  2943. var defaultMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  2944. defaultMaterial.diffuseColor = new babylonjs_1.Color3(0.5, 0.5, 0.5);
  2945. defaultMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  2946. onSuccess(defaultMaterial);
  2947. return;
  2948. }
  2949. var program = gltfRuntime.programs[technique.program];
  2950. var states = technique.states;
  2951. var vertexShader = babylonjs_1.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2952. var pixelShader = babylonjs_1.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2953. var newVertexShader = "";
  2954. var newPixelShader = "";
  2955. var vertexTokenizer = new Tokenizer(vertexShader);
  2956. var pixelTokenizer = new Tokenizer(pixelShader);
  2957. var unTreatedUniforms = {};
  2958. var uniforms = [];
  2959. var attributes = [];
  2960. var samplers = [];
  2961. // Fill uniform, sampler2D and attributes
  2962. for (var unif in technique.uniforms) {
  2963. var uniform = technique.uniforms[unif];
  2964. var uniformParameter = technique.parameters[uniform];
  2965. unTreatedUniforms[unif] = uniformParameter;
  2966. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2967. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2968. if (transformIndex !== -1) {
  2969. uniforms.push(babylonTransforms[transformIndex]);
  2970. delete unTreatedUniforms[unif];
  2971. }
  2972. else {
  2973. uniforms.push(unif);
  2974. }
  2975. }
  2976. else if (uniformParameter.type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  2977. samplers.push(unif);
  2978. }
  2979. else {
  2980. uniforms.push(unif);
  2981. }
  2982. }
  2983. for (var attr in technique.attributes) {
  2984. var attribute = technique.attributes[attr];
  2985. var attributeParameter = technique.parameters[attribute];
  2986. if (attributeParameter.semantic) {
  2987. var name_1 = getAttribute(attributeParameter);
  2988. if (name_1) {
  2989. attributes.push(name_1);
  2990. }
  2991. }
  2992. }
  2993. // Configure vertex shader
  2994. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2995. var tokenType = vertexTokenizer.currentToken;
  2996. if (tokenType !== ETokenType.IDENTIFIER) {
  2997. newVertexShader += vertexTokenizer.currentString;
  2998. continue;
  2999. }
  3000. var foundAttribute = false;
  3001. for (var attr in technique.attributes) {
  3002. var attribute = technique.attributes[attr];
  3003. var attributeParameter = technique.parameters[attribute];
  3004. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  3005. newVertexShader += getAttribute(attributeParameter);
  3006. foundAttribute = true;
  3007. break;
  3008. }
  3009. }
  3010. if (foundAttribute) {
  3011. continue;
  3012. }
  3013. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  3014. }
  3015. // Configure pixel shader
  3016. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  3017. var tokenType = pixelTokenizer.currentToken;
  3018. if (tokenType !== ETokenType.IDENTIFIER) {
  3019. newPixelShader += pixelTokenizer.currentString;
  3020. continue;
  3021. }
  3022. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  3023. }
  3024. // Create shader material
  3025. var shaderPath = {
  3026. vertex: program.vertexShader + id,
  3027. fragment: program.fragmentShader + id
  3028. };
  3029. var options = {
  3030. attributes: attributes,
  3031. uniforms: uniforms,
  3032. samplers: samplers,
  3033. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  3034. };
  3035. babylonjs_1.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  3036. babylonjs_1.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  3037. var shaderMaterial = new babylonjs_1.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  3038. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  3039. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  3040. shaderMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  3041. if (states && states.functions) {
  3042. var functions = states.functions;
  3043. if (functions.cullFace && functions.cullFace[0] !== glTFLoaderInterfaces_1.ECullingType.BACK) {
  3044. shaderMaterial.backFaceCulling = false;
  3045. }
  3046. var blendFunc = functions.blendFuncSeparate;
  3047. if (blendFunc) {
  3048. if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  3049. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_COMBINE;
  3050. }
  3051. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  3052. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ONEONE;
  3053. }
  3054. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  3055. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ADD;
  3056. }
  3057. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  3058. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_SUBTRACT;
  3059. }
  3060. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.DST_COLOR && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  3061. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MULTIPLY;
  3062. }
  3063. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  3064. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MAXIMIZED;
  3065. }
  3066. }
  3067. }
  3068. };
  3069. return GLTFLoaderBase;
  3070. }());
  3071. exports.GLTFLoaderBase = GLTFLoaderBase;
  3072. /**
  3073. * glTF V1 Loader
  3074. */
  3075. var GLTFLoaderV1 = /** @class */ (function () {
  3076. function GLTFLoaderV1() {
  3077. this.state = null;
  3078. }
  3079. GLTFLoaderV1.RegisterExtension = function (extension) {
  3080. if (GLTFLoaderV1.Extensions[extension.name]) {
  3081. babylonjs_1.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  3082. return;
  3083. }
  3084. GLTFLoaderV1.Extensions[extension.name] = extension;
  3085. };
  3086. GLTFLoaderV1.prototype.dispose = function () {
  3087. // do nothing
  3088. };
  3089. GLTFLoaderV1.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  3090. var _this = this;
  3091. scene.useRightHandedSystem = true;
  3092. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  3093. gltfRuntime.importOnlyMeshes = true;
  3094. if (meshesNames === "") {
  3095. gltfRuntime.importMeshesNames = [];
  3096. }
  3097. else if (typeof meshesNames === "string") {
  3098. gltfRuntime.importMeshesNames = [meshesNames];
  3099. }
  3100. else if (meshesNames && !(meshesNames instanceof Array)) {
  3101. gltfRuntime.importMeshesNames = [meshesNames];
  3102. }
  3103. else {
  3104. gltfRuntime.importMeshesNames = [];
  3105. babylonjs_1.Tools.Warn("Argument meshesNames must be of type string or string[]");
  3106. }
  3107. // Create nodes
  3108. _this._createNodes(gltfRuntime);
  3109. var meshes = new Array();
  3110. var skeletons = new Array();
  3111. // Fill arrays of meshes and skeletons
  3112. for (var nde in gltfRuntime.nodes) {
  3113. var node = gltfRuntime.nodes[nde];
  3114. if (node.babylonNode instanceof babylonjs_1.AbstractMesh) {
  3115. meshes.push(node.babylonNode);
  3116. }
  3117. }
  3118. for (var skl in gltfRuntime.skins) {
  3119. var skin = gltfRuntime.skins[skl];
  3120. if (skin.babylonSkeleton instanceof babylonjs_1.Skeleton) {
  3121. skeletons.push(skin.babylonSkeleton);
  3122. }
  3123. }
  3124. // Load buffers, shaders, materials, etc.
  3125. _this._loadBuffersAsync(gltfRuntime, function () {
  3126. _this._loadShadersAsync(gltfRuntime, function () {
  3127. importMaterials(gltfRuntime);
  3128. postLoad(gltfRuntime);
  3129. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3130. onSuccess(meshes, skeletons);
  3131. }
  3132. });
  3133. }, onProgress);
  3134. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3135. onSuccess(meshes, skeletons);
  3136. }
  3137. }, onError);
  3138. return true;
  3139. };
  3140. /**
  3141. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  3142. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  3143. * @param scene the scene the meshes should be added to
  3144. * @param data gltf data containing information of the meshes in a loaded file
  3145. * @param rootUrl root url to load from
  3146. * @param onProgress event that fires when loading progress has occured
  3147. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  3148. */
  3149. GLTFLoaderV1.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  3150. var _this = this;
  3151. return new Promise(function (resolve, reject) {
  3152. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  3153. resolve({
  3154. meshes: meshes,
  3155. particleSystems: [],
  3156. skeletons: skeletons,
  3157. animationGroups: []
  3158. });
  3159. }, onProgress, function (message) {
  3160. reject(new Error(message));
  3161. });
  3162. });
  3163. };
  3164. GLTFLoaderV1.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  3165. var _this = this;
  3166. scene.useRightHandedSystem = true;
  3167. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  3168. // Load runtime extensios
  3169. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  3170. // Create nodes
  3171. _this._createNodes(gltfRuntime);
  3172. // Load buffers, shaders, materials, etc.
  3173. _this._loadBuffersAsync(gltfRuntime, function () {
  3174. _this._loadShadersAsync(gltfRuntime, function () {
  3175. importMaterials(gltfRuntime);
  3176. postLoad(gltfRuntime);
  3177. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  3178. onSuccess();
  3179. }
  3180. });
  3181. });
  3182. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  3183. onSuccess();
  3184. }
  3185. }, onError);
  3186. }, onError);
  3187. };
  3188. /**
  3189. * Imports all objects from a loaded gltf file and adds them to the scene
  3190. * @param scene the scene the objects should be added to
  3191. * @param data gltf data containing information of the meshes in a loaded file
  3192. * @param rootUrl root url to load from
  3193. * @param onProgress event that fires when loading progress has occured
  3194. * @returns a promise which completes when objects have been loaded to the scene
  3195. */
  3196. GLTFLoaderV1.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  3197. var _this = this;
  3198. return new Promise(function (resolve, reject) {
  3199. _this._loadAsync(scene, data, rootUrl, function () {
  3200. resolve();
  3201. }, onProgress, function (message) {
  3202. reject(new Error(message));
  3203. });
  3204. });
  3205. };
  3206. GLTFLoaderV1.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  3207. var hasShaders = false;
  3208. var processShader = function (sha, shader) {
  3209. glTFLoaderExtension_1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  3210. if (shaderString instanceof ArrayBuffer) {
  3211. return;
  3212. }
  3213. gltfRuntime.loadedShaderCount++;
  3214. if (shaderString) {
  3215. babylonjs_1.Effect.ShadersStore[sha + (shader.type === glTFLoaderInterfaces_1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  3216. }
  3217. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  3218. onload();
  3219. }
  3220. }, function () {
  3221. babylonjs_1.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  3222. });
  3223. };
  3224. for (var sha in gltfRuntime.shaders) {
  3225. hasShaders = true;
  3226. var shader = gltfRuntime.shaders[sha];
  3227. if (shader) {
  3228. processShader.bind(this, sha, shader)();
  3229. }
  3230. else {
  3231. babylonjs_1.Tools.Error("No shader named: " + sha);
  3232. }
  3233. }
  3234. if (!hasShaders) {
  3235. onload();
  3236. }
  3237. };
  3238. GLTFLoaderV1.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  3239. var hasBuffers = false;
  3240. var processBuffer = function (buf, buffer) {
  3241. glTFLoaderExtension_1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  3242. gltfRuntime.loadedBufferCount++;
  3243. if (bufferView) {
  3244. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  3245. babylonjs_1.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  3246. }
  3247. gltfRuntime.loadedBufferViews[buf] = bufferView;
  3248. }
  3249. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  3250. onLoad();
  3251. }
  3252. }, function () {
  3253. babylonjs_1.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  3254. });
  3255. };
  3256. for (var buf in gltfRuntime.buffers) {
  3257. hasBuffers = true;
  3258. var buffer = gltfRuntime.buffers[buf];
  3259. if (buffer) {
  3260. processBuffer.bind(this, buf, buffer)();
  3261. }
  3262. else {
  3263. babylonjs_1.Tools.Error("No buffer named: " + buf);
  3264. }
  3265. }
  3266. if (!hasBuffers) {
  3267. onLoad();
  3268. }
  3269. };
  3270. GLTFLoaderV1.prototype._createNodes = function (gltfRuntime) {
  3271. var currentScene = gltfRuntime.currentScene;
  3272. if (currentScene) {
  3273. // Only one scene even if multiple scenes are defined
  3274. for (var i = 0; i < currentScene.nodes.length; i++) {
  3275. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3276. }
  3277. }
  3278. else {
  3279. // Load all scenes
  3280. for (var thing in gltfRuntime.scenes) {
  3281. currentScene = gltfRuntime.scenes[thing];
  3282. for (var i = 0; i < currentScene.nodes.length; i++) {
  3283. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3284. }
  3285. }
  3286. }
  3287. };
  3288. GLTFLoaderV1.Extensions = {};
  3289. return GLTFLoaderV1;
  3290. }());
  3291. exports.GLTFLoaderV1 = GLTFLoaderV1;
  3292. glTFFileLoader_1.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoaderV1(); };
  3293. /***/ }),
  3294. /***/ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts":
  3295. /*!******************************************************!*\
  3296. !*** ./src/glTF/1.0/glTFMaterialsCommonExtension.ts ***!
  3297. \******************************************************/
  3298. /*! no static exports found */
  3299. /***/ (function(module, exports, __webpack_require__) {
  3300. "use strict";
  3301. var __extends = (this && this.__extends) || (function () {
  3302. var extendStatics = function (d, b) {
  3303. extendStatics = Object.setPrototypeOf ||
  3304. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3305. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3306. return extendStatics(d, b);
  3307. }
  3308. return function (d, b) {
  3309. extendStatics(d, b);
  3310. function __() { this.constructor = d; }
  3311. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3312. };
  3313. })();
  3314. Object.defineProperty(exports, "__esModule", { value: true });
  3315. var _1 = __webpack_require__(/*! . */ "./src/glTF/1.0/index.ts");
  3316. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3317. var glTFLoaderV1_1 = __webpack_require__(/*! ./glTFLoaderV1 */ "./src/glTF/1.0/glTFLoaderV1.ts");
  3318. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  3319. __extends(GLTFMaterialsCommonExtension, _super);
  3320. function GLTFMaterialsCommonExtension() {
  3321. return _super.call(this, "KHR_materials_common") || this;
  3322. }
  3323. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3324. if (!gltfRuntime.extensions) {
  3325. return false;
  3326. }
  3327. var extension = gltfRuntime.extensions[this.name];
  3328. if (!extension) {
  3329. return false;
  3330. }
  3331. // Create lights
  3332. var lights = extension.lights;
  3333. if (lights) {
  3334. for (var thing in lights) {
  3335. var light = lights[thing];
  3336. switch (light.type) {
  3337. case "ambient":
  3338. var ambientLight = new babylonjs_1.HemisphericLight(light.name, new babylonjs_1.Vector3(0, 1, 0), gltfRuntime.scene);
  3339. var ambient = light.ambient;
  3340. if (ambient) {
  3341. ambientLight.diffuse = babylonjs_1.Color3.FromArray(ambient.color || [1, 1, 1]);
  3342. }
  3343. break;
  3344. case "point":
  3345. var pointLight = new babylonjs_1.PointLight(light.name, new babylonjs_1.Vector3(10, 10, 10), gltfRuntime.scene);
  3346. var point = light.point;
  3347. if (point) {
  3348. pointLight.diffuse = babylonjs_1.Color3.FromArray(point.color || [1, 1, 1]);
  3349. }
  3350. break;
  3351. case "directional":
  3352. var dirLight = new babylonjs_1.DirectionalLight(light.name, new babylonjs_1.Vector3(0, -1, 0), gltfRuntime.scene);
  3353. var directional = light.directional;
  3354. if (directional) {
  3355. dirLight.diffuse = babylonjs_1.Color3.FromArray(directional.color || [1, 1, 1]);
  3356. }
  3357. break;
  3358. case "spot":
  3359. var spot = light.spot;
  3360. if (spot) {
  3361. var spotLight = new babylonjs_1.SpotLight(light.name, new babylonjs_1.Vector3(0, 10, 0), new babylonjs_1.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  3362. spotLight.diffuse = babylonjs_1.Color3.FromArray(spot.color || [1, 1, 1]);
  3363. }
  3364. break;
  3365. default:
  3366. babylonjs_1.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3367. break;
  3368. }
  3369. }
  3370. }
  3371. return false;
  3372. };
  3373. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3374. var material = gltfRuntime.materials[id];
  3375. if (!material || !material.extensions) {
  3376. return false;
  3377. }
  3378. var extension = material.extensions[this.name];
  3379. if (!extension) {
  3380. return false;
  3381. }
  3382. var standardMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  3383. standardMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  3384. if (extension.technique === "CONSTANT") {
  3385. standardMaterial.disableLighting = true;
  3386. }
  3387. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3388. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3389. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3390. // Ambient
  3391. if (typeof extension.values.ambient === "string") {
  3392. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3393. }
  3394. else {
  3395. standardMaterial.ambientColor = babylonjs_1.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3396. }
  3397. // Diffuse
  3398. if (typeof extension.values.diffuse === "string") {
  3399. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3400. }
  3401. else {
  3402. standardMaterial.diffuseColor = babylonjs_1.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3403. }
  3404. // Emission
  3405. if (typeof extension.values.emission === "string") {
  3406. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3407. }
  3408. else {
  3409. standardMaterial.emissiveColor = babylonjs_1.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3410. }
  3411. // Specular
  3412. if (typeof extension.values.specular === "string") {
  3413. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3414. }
  3415. else {
  3416. standardMaterial.specularColor = babylonjs_1.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3417. }
  3418. return true;
  3419. };
  3420. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3421. // Create buffer from texture url
  3422. _1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3423. // Create texture from buffer
  3424. _1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3425. }, onError);
  3426. };
  3427. return GLTFMaterialsCommonExtension;
  3428. }(_1.GLTFLoaderExtension));
  3429. exports.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3430. glTFLoaderV1_1.GLTFLoaderV1.RegisterExtension(new GLTFMaterialsCommonExtension());
  3431. /***/ }),
  3432. /***/ "./src/glTF/1.0/index.ts":
  3433. /*!*******************************!*\
  3434. !*** ./src/glTF/1.0/index.ts ***!
  3435. \*******************************/
  3436. /*! no static exports found */
  3437. /***/ (function(module, exports, __webpack_require__) {
  3438. "use strict";
  3439. function __export(m) {
  3440. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  3441. }
  3442. Object.defineProperty(exports, "__esModule", { value: true });
  3443. __export(__webpack_require__(/*! ./glTFBinaryExtension */ "./src/glTF/1.0/glTFBinaryExtension.ts"));
  3444. __export(__webpack_require__(/*! ./glTFLoaderV1 */ "./src/glTF/1.0/glTFLoaderV1.ts"));
  3445. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts"));
  3446. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts"));
  3447. __export(__webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts"));
  3448. __export(__webpack_require__(/*! ./glTFMaterialsCommonExtension */ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts"));
  3449. /***/ }),
  3450. /***/ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts":
  3451. /*!***********************************************************!*\
  3452. !*** ./src/glTF/2.0/Extensions/EXT_lights_image_based.ts ***!
  3453. \***********************************************************/
  3454. /*! no static exports found */
  3455. /***/ (function(module, exports, __webpack_require__) {
  3456. "use strict";
  3457. Object.defineProperty(exports, "__esModule", { value: true });
  3458. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3459. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3460. var NAME = "EXT_lights_image_based";
  3461. /**
  3462. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  3463. */
  3464. var EXT_lights_image_based = /** @class */ (function () {
  3465. /** @hidden */
  3466. function EXT_lights_image_based(loader) {
  3467. /** The name of this extension. */
  3468. this.name = NAME;
  3469. /** Defines whether this extension is enabled. */
  3470. this.enabled = true;
  3471. this._loader = loader;
  3472. }
  3473. /** @hidden */
  3474. EXT_lights_image_based.prototype.dispose = function () {
  3475. delete this._loader;
  3476. delete this._lights;
  3477. };
  3478. /** @hidden */
  3479. EXT_lights_image_based.prototype.onLoading = function () {
  3480. var extensions = this._loader.gltf.extensions;
  3481. if (extensions && extensions[this.name]) {
  3482. var extension = extensions[this.name];
  3483. this._lights = extension.lights;
  3484. }
  3485. };
  3486. /** @hidden */
  3487. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  3488. var _this = this;
  3489. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3490. var promises = new Array();
  3491. promises.push(_this._loader.loadSceneAsync(context, scene));
  3492. _this._loader.logOpen("" + extensionContext);
  3493. var light = glTFLoader_1.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  3494. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  3495. _this._loader.babylonScene.environmentTexture = texture;
  3496. }));
  3497. _this._loader.logClose();
  3498. return Promise.all(promises).then(function () { });
  3499. });
  3500. };
  3501. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  3502. var _this = this;
  3503. if (!light._loaded) {
  3504. var promises = new Array();
  3505. this._loader.logOpen("" + context);
  3506. var imageData_1 = new Array(light.specularImages.length);
  3507. var _loop_1 = function (mipmap) {
  3508. var faces = light.specularImages[mipmap];
  3509. imageData_1[mipmap] = new Array(faces.length);
  3510. var _loop_2 = function (face) {
  3511. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  3512. this_1._loader.logOpen("" + specularImageContext);
  3513. var index = faces[face];
  3514. var image = glTFLoader_1.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  3515. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  3516. imageData_1[mipmap][face] = data;
  3517. }));
  3518. this_1._loader.logClose();
  3519. };
  3520. for (var face = 0; face < faces.length; face++) {
  3521. _loop_2(face);
  3522. }
  3523. };
  3524. var this_1 = this;
  3525. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  3526. _loop_1(mipmap);
  3527. }
  3528. this._loader.logClose();
  3529. light._loaded = Promise.all(promises).then(function () {
  3530. var babylonTexture = new babylonjs_1.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  3531. light._babylonTexture = babylonTexture;
  3532. if (light.intensity != undefined) {
  3533. babylonTexture.level = light.intensity;
  3534. }
  3535. if (light.rotation) {
  3536. var rotation = babylonjs_1.Quaternion.FromArray(light.rotation);
  3537. // Invert the rotation so that positive rotation is counter-clockwise.
  3538. if (!_this._loader.babylonScene.useRightHandedSystem) {
  3539. rotation = babylonjs_1.Quaternion.Inverse(rotation);
  3540. }
  3541. babylonjs_1.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  3542. }
  3543. var sphericalHarmonics = babylonjs_1.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  3544. sphericalHarmonics.scale(light.intensity);
  3545. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  3546. var sphericalPolynomial = babylonjs_1.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  3547. // Compute the lod generation scale to fit exactly to the number of levels available.
  3548. var lodGenerationScale = (imageData_1.length - 1) / babylonjs_1.Scalar.Log2(light.specularImageSize);
  3549. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  3550. });
  3551. }
  3552. return light._loaded.then(function () {
  3553. return light._babylonTexture;
  3554. });
  3555. };
  3556. return EXT_lights_image_based;
  3557. }());
  3558. exports.EXT_lights_image_based = EXT_lights_image_based;
  3559. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  3560. /***/ }),
  3561. /***/ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts":
  3562. /*!***************************************************************!*\
  3563. !*** ./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts ***!
  3564. \***************************************************************/
  3565. /*! no static exports found */
  3566. /***/ (function(module, exports, __webpack_require__) {
  3567. "use strict";
  3568. Object.defineProperty(exports, "__esModule", { value: true });
  3569. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3570. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3571. var NAME = "KHR_draco_mesh_compression";
  3572. /**
  3573. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  3574. */
  3575. var KHR_draco_mesh_compression = /** @class */ (function () {
  3576. /** @hidden */
  3577. function KHR_draco_mesh_compression(loader) {
  3578. /** The name of this extension. */
  3579. this.name = NAME;
  3580. /** Defines whether this extension is enabled. */
  3581. this.enabled = babylonjs_1.DracoCompression.DecoderAvailable;
  3582. this._loader = loader;
  3583. }
  3584. /** @hidden */
  3585. KHR_draco_mesh_compression.prototype.dispose = function () {
  3586. if (this._dracoCompression) {
  3587. this._dracoCompression.dispose();
  3588. delete this._dracoCompression;
  3589. }
  3590. delete this._loader;
  3591. };
  3592. /** @hidden */
  3593. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3594. var _this = this;
  3595. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  3596. if (primitive.mode != undefined) {
  3597. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  3598. primitive.mode !== 4 /* TRIANGLES */) {
  3599. throw new Error(context + ": Unsupported mode " + primitive.mode);
  3600. }
  3601. // TODO: handle triangle strips
  3602. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  3603. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3604. }
  3605. }
  3606. var attributes = {};
  3607. var loadAttribute = function (name, kind) {
  3608. var uniqueId = extension.attributes[name];
  3609. if (uniqueId == undefined) {
  3610. return;
  3611. }
  3612. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3613. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3614. babylonMesh._delayInfo.push(kind);
  3615. }
  3616. attributes[kind] = uniqueId;
  3617. };
  3618. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  3619. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  3620. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  3621. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  3622. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  3623. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  3624. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  3625. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind);
  3626. var bufferView = glTFLoader_1.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  3627. if (!bufferView._dracoBabylonGeometry) {
  3628. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  3629. if (!_this._dracoCompression) {
  3630. _this._dracoCompression = new babylonjs_1.DracoCompression();
  3631. }
  3632. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  3633. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, _this._loader.babylonScene);
  3634. babylonVertexData.applyToGeometry(babylonGeometry);
  3635. return babylonGeometry;
  3636. }).catch(function (error) {
  3637. throw new Error(context + ": " + error.message);
  3638. });
  3639. });
  3640. }
  3641. return bufferView._dracoBabylonGeometry;
  3642. });
  3643. };
  3644. return KHR_draco_mesh_compression;
  3645. }());
  3646. exports.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  3647. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  3648. /***/ }),
  3649. /***/ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts":
  3650. /*!********************************************************!*\
  3651. !*** ./src/glTF/2.0/Extensions/KHR_lights_punctual.ts ***!
  3652. \********************************************************/
  3653. /*! no static exports found */
  3654. /***/ (function(module, exports, __webpack_require__) {
  3655. "use strict";
  3656. Object.defineProperty(exports, "__esModule", { value: true });
  3657. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3658. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3659. var NAME = "KHR_lights_punctual";
  3660. var LightType;
  3661. (function (LightType) {
  3662. LightType["DIRECTIONAL"] = "directional";
  3663. LightType["POINT"] = "point";
  3664. LightType["SPOT"] = "spot";
  3665. })(LightType || (LightType = {}));
  3666. /**
  3667. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  3668. */
  3669. var KHR_lights = /** @class */ (function () {
  3670. /** @hidden */
  3671. function KHR_lights(loader) {
  3672. /** The name of this extension. */
  3673. this.name = NAME;
  3674. /** Defines whether this extension is enabled. */
  3675. this.enabled = true;
  3676. this._loader = loader;
  3677. }
  3678. /** @hidden */
  3679. KHR_lights.prototype.dispose = function () {
  3680. delete this._loader;
  3681. delete this._lights;
  3682. };
  3683. /** @hidden */
  3684. KHR_lights.prototype.onLoading = function () {
  3685. var extensions = this._loader.gltf.extensions;
  3686. if (extensions && extensions[this.name]) {
  3687. var extension = extensions[this.name];
  3688. this._lights = extension.lights;
  3689. }
  3690. };
  3691. /** @hidden */
  3692. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  3693. var _this = this;
  3694. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3695. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  3696. var babylonLight;
  3697. var light = glTFLoader_1.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  3698. var name = light.name || babylonMesh.name;
  3699. switch (light.type) {
  3700. case LightType.DIRECTIONAL: {
  3701. babylonLight = new babylonjs_1.DirectionalLight(name, babylonjs_1.Vector3.Backward(), _this._loader.babylonScene);
  3702. break;
  3703. }
  3704. case LightType.POINT: {
  3705. babylonLight = new babylonjs_1.PointLight(name, babylonjs_1.Vector3.Zero(), _this._loader.babylonScene);
  3706. break;
  3707. }
  3708. case LightType.SPOT: {
  3709. var babylonSpotLight = new babylonjs_1.SpotLight(name, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  3710. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  3711. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  3712. babylonLight = babylonSpotLight;
  3713. break;
  3714. }
  3715. default: {
  3716. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  3717. }
  3718. }
  3719. babylonLight.falloffType = babylonjs_1.Light.FALLOFF_GLTF;
  3720. babylonLight.diffuse = light.color ? babylonjs_1.Color3.FromArray(light.color) : babylonjs_1.Color3.White();
  3721. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  3722. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  3723. babylonLight.parent = babylonMesh;
  3724. assign(babylonMesh);
  3725. });
  3726. });
  3727. };
  3728. return KHR_lights;
  3729. }());
  3730. exports.KHR_lights = KHR_lights;
  3731. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  3732. /***/ }),
  3733. /***/ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts":
  3734. /*!************************************************************************!*\
  3735. !*** ./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts ***!
  3736. \************************************************************************/
  3737. /*! no static exports found */
  3738. /***/ (function(module, exports, __webpack_require__) {
  3739. "use strict";
  3740. Object.defineProperty(exports, "__esModule", { value: true });
  3741. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3742. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3743. var NAME = "KHR_materials_pbrSpecularGlossiness";
  3744. /**
  3745. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  3746. */
  3747. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  3748. /** @hidden */
  3749. function KHR_materials_pbrSpecularGlossiness(loader) {
  3750. /** The name of this extension. */
  3751. this.name = NAME;
  3752. /** Defines whether this extension is enabled. */
  3753. this.enabled = true;
  3754. this._loader = loader;
  3755. }
  3756. /** @hidden */
  3757. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  3758. delete this._loader;
  3759. };
  3760. /** @hidden */
  3761. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3762. var _this = this;
  3763. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  3764. var promises = new Array();
  3765. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3766. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  3767. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3768. return Promise.all(promises).then(function () { });
  3769. });
  3770. };
  3771. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  3772. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  3773. throw new Error(context + ": Material type not supported");
  3774. }
  3775. var promises = new Array();
  3776. babylonMaterial.metallic = null;
  3777. babylonMaterial.roughness = null;
  3778. if (properties.diffuseFactor) {
  3779. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.diffuseFactor);
  3780. babylonMaterial.alpha = properties.diffuseFactor[3];
  3781. }
  3782. else {
  3783. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  3784. }
  3785. babylonMaterial.reflectivityColor = properties.specularFactor ? babylonjs_1.Color3.FromArray(properties.specularFactor) : babylonjs_1.Color3.White();
  3786. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  3787. if (properties.diffuseTexture) {
  3788. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  3789. babylonMaterial.albedoTexture = texture;
  3790. return Promise.resolve();
  3791. }));
  3792. }
  3793. if (properties.specularGlossinessTexture) {
  3794. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  3795. babylonMaterial.reflectivityTexture = texture;
  3796. return Promise.resolve();
  3797. }));
  3798. babylonMaterial.reflectivityTexture.hasAlpha = true;
  3799. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3800. }
  3801. return Promise.all(promises).then(function () { });
  3802. };
  3803. return KHR_materials_pbrSpecularGlossiness;
  3804. }());
  3805. exports.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  3806. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  3807. /***/ }),
  3808. /***/ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts":
  3809. /*!********************************************************!*\
  3810. !*** ./src/glTF/2.0/Extensions/KHR_materials_unlit.ts ***!
  3811. \********************************************************/
  3812. /*! no static exports found */
  3813. /***/ (function(module, exports, __webpack_require__) {
  3814. "use strict";
  3815. Object.defineProperty(exports, "__esModule", { value: true });
  3816. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3817. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3818. var NAME = "KHR_materials_unlit";
  3819. /**
  3820. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  3821. */
  3822. var KHR_materials_unlit = /** @class */ (function () {
  3823. /** @hidden */
  3824. function KHR_materials_unlit(loader) {
  3825. /** The name of this extension. */
  3826. this.name = NAME;
  3827. /** Defines whether this extension is enabled. */
  3828. this.enabled = true;
  3829. this._loader = loader;
  3830. }
  3831. /** @hidden */
  3832. KHR_materials_unlit.prototype.dispose = function () {
  3833. delete this._loader;
  3834. };
  3835. /** @hidden */
  3836. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3837. var _this = this;
  3838. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, material, this.name, function () {
  3839. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  3840. });
  3841. };
  3842. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  3843. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  3844. throw new Error(context + ": Material type not supported");
  3845. }
  3846. var promises = new Array();
  3847. babylonMaterial.unlit = true;
  3848. var properties = material.pbrMetallicRoughness;
  3849. if (properties) {
  3850. if (properties.baseColorFactor) {
  3851. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  3852. babylonMaterial.alpha = properties.baseColorFactor[3];
  3853. }
  3854. else {
  3855. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  3856. }
  3857. if (properties.baseColorTexture) {
  3858. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3859. babylonMaterial.albedoTexture = texture;
  3860. return Promise.resolve();
  3861. }));
  3862. }
  3863. }
  3864. if (material.doubleSided) {
  3865. babylonMaterial.backFaceCulling = false;
  3866. babylonMaterial.twoSidedLighting = true;
  3867. }
  3868. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3869. return Promise.all(promises).then(function () { });
  3870. };
  3871. return KHR_materials_unlit;
  3872. }());
  3873. exports.KHR_materials_unlit = KHR_materials_unlit;
  3874. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  3875. /***/ }),
  3876. /***/ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts":
  3877. /*!**********************************************************!*\
  3878. !*** ./src/glTF/2.0/Extensions/KHR_texture_transform.ts ***!
  3879. \**********************************************************/
  3880. /*! no static exports found */
  3881. /***/ (function(module, exports, __webpack_require__) {
  3882. "use strict";
  3883. Object.defineProperty(exports, "__esModule", { value: true });
  3884. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3885. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3886. var NAME = "KHR_texture_transform";
  3887. /**
  3888. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  3889. */
  3890. var KHR_texture_transform = /** @class */ (function () {
  3891. /** @hidden */
  3892. function KHR_texture_transform(loader) {
  3893. /** The name of this extension. */
  3894. this.name = NAME;
  3895. /** Defines whether this extension is enabled. */
  3896. this.enabled = true;
  3897. this._loader = loader;
  3898. }
  3899. /** @hidden */
  3900. KHR_texture_transform.prototype.dispose = function () {
  3901. delete this._loader;
  3902. };
  3903. /** @hidden */
  3904. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  3905. var _this = this;
  3906. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  3907. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  3908. if (!(babylonTexture instanceof babylonjs_1.Texture)) {
  3909. throw new Error(extensionContext + ": Texture type not supported");
  3910. }
  3911. if (extension.offset) {
  3912. babylonTexture.uOffset = extension.offset[0];
  3913. babylonTexture.vOffset = extension.offset[1];
  3914. }
  3915. // Always rotate around the origin.
  3916. babylonTexture.uRotationCenter = 0;
  3917. babylonTexture.vRotationCenter = 0;
  3918. if (extension.rotation) {
  3919. babylonTexture.wAng = -extension.rotation;
  3920. }
  3921. if (extension.scale) {
  3922. babylonTexture.uScale = extension.scale[0];
  3923. babylonTexture.vScale = extension.scale[1];
  3924. }
  3925. if (extension.texCoord != undefined) {
  3926. babylonTexture.coordinatesIndex = extension.texCoord;
  3927. }
  3928. assign(babylonTexture);
  3929. });
  3930. });
  3931. };
  3932. return KHR_texture_transform;
  3933. }());
  3934. exports.KHR_texture_transform = KHR_texture_transform;
  3935. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  3936. /***/ }),
  3937. /***/ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts":
  3938. /*!*******************************************************!*\
  3939. !*** ./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts ***!
  3940. \*******************************************************/
  3941. /*! no static exports found */
  3942. /***/ (function(module, exports, __webpack_require__) {
  3943. "use strict";
  3944. Object.defineProperty(exports, "__esModule", { value: true });
  3945. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3946. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3947. var NAME = "MSFT_audio_emitter";
  3948. /**
  3949. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  3950. */
  3951. var MSFT_audio_emitter = /** @class */ (function () {
  3952. /** @hidden */
  3953. function MSFT_audio_emitter(loader) {
  3954. /** The name of this extension. */
  3955. this.name = NAME;
  3956. /** Defines whether this extension is enabled. */
  3957. this.enabled = true;
  3958. this._loader = loader;
  3959. }
  3960. /** @hidden */
  3961. MSFT_audio_emitter.prototype.dispose = function () {
  3962. delete this._loader;
  3963. delete this._clips;
  3964. delete this._emitters;
  3965. };
  3966. /** @hidden */
  3967. MSFT_audio_emitter.prototype.onLoading = function () {
  3968. var extensions = this._loader.gltf.extensions;
  3969. if (extensions && extensions[this.name]) {
  3970. var extension = extensions[this.name];
  3971. this._clips = extension.clips;
  3972. this._emitters = extension.emitters;
  3973. glTFLoader_1.ArrayItem.Assign(this._clips);
  3974. glTFLoader_1.ArrayItem.Assign(this._emitters);
  3975. }
  3976. };
  3977. /** @hidden */
  3978. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  3979. var _this = this;
  3980. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3981. var promises = new Array();
  3982. promises.push(_this._loader.loadSceneAsync(context, scene));
  3983. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  3984. var emitterIndex = _a[_i];
  3985. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  3986. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  3987. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  3988. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  3989. }
  3990. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  3991. }
  3992. return Promise.all(promises).then(function () { });
  3993. });
  3994. };
  3995. /** @hidden */
  3996. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  3997. var _this = this;
  3998. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3999. var promises = new Array();
  4000. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  4001. var _loop_1 = function (emitterIndex) {
  4002. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  4003. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  4004. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  4005. var sound = _a[_i];
  4006. sound.attachToMesh(babylonMesh);
  4007. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  4008. sound.setLocalDirectionToMesh(babylonjs_1.Vector3.Forward());
  4009. sound.setDirectionalCone(2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  4010. }
  4011. }
  4012. }));
  4013. };
  4014. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  4015. var emitterIndex = _a[_i];
  4016. _loop_1(emitterIndex);
  4017. }
  4018. assign(babylonMesh);
  4019. }).then(function (babylonMesh) {
  4020. return Promise.all(promises).then(function () {
  4021. return babylonMesh;
  4022. });
  4023. });
  4024. });
  4025. };
  4026. /** @hidden */
  4027. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  4028. var _this = this;
  4029. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  4030. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  4031. var promises = new Array();
  4032. glTFLoader_1.ArrayItem.Assign(extension.events);
  4033. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  4034. var event_1 = _a[_i];
  4035. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  4036. }
  4037. return Promise.all(promises).then(function () {
  4038. return babylonAnimationGroup;
  4039. });
  4040. });
  4041. });
  4042. };
  4043. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  4044. if (clip._objectURL) {
  4045. return clip._objectURL;
  4046. }
  4047. var promise;
  4048. if (clip.uri) {
  4049. promise = this._loader.loadUriAsync(context, clip.uri);
  4050. }
  4051. else {
  4052. var bufferView = glTFLoader_1.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  4053. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  4054. }
  4055. clip._objectURL = promise.then(function (data) {
  4056. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  4057. });
  4058. return clip._objectURL;
  4059. };
  4060. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  4061. var _this = this;
  4062. emitter._babylonSounds = emitter._babylonSounds || [];
  4063. if (!emitter._babylonData) {
  4064. var clipPromises = new Array();
  4065. var name_1 = emitter.name || "emitter" + emitter.index;
  4066. var options_1 = {
  4067. loop: false,
  4068. autoplay: false,
  4069. volume: emitter.volume == undefined ? 1 : emitter.volume,
  4070. };
  4071. var _loop_2 = function (i) {
  4072. var clipContext = "#/extensions/" + this_1.name + "/clips";
  4073. var clip = glTFLoader_1.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  4074. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  4075. var sound = emitter._babylonSounds[i] = new babylonjs_1.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  4076. sound.refDistance = emitter.refDistance || 1;
  4077. sound.maxDistance = emitter.maxDistance || 256;
  4078. sound.rolloffFactor = emitter.rolloffFactor || 1;
  4079. sound.distanceModel = emitter.distanceModel || 'exponential';
  4080. sound._positionInEmitterSpace = true;
  4081. }));
  4082. };
  4083. var this_1 = this;
  4084. for (var i = 0; i < emitter.clips.length; i++) {
  4085. _loop_2(i);
  4086. }
  4087. var promise = Promise.all(clipPromises).then(function () {
  4088. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  4089. var weightedSound = new babylonjs_1.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  4090. if (emitter.innerAngle) {
  4091. weightedSound.directionalConeInnerAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle);
  4092. }
  4093. if (emitter.outerAngle) {
  4094. weightedSound.directionalConeOuterAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle);
  4095. }
  4096. if (emitter.volume) {
  4097. weightedSound.volume = emitter.volume;
  4098. }
  4099. emitter._babylonData.sound = weightedSound;
  4100. });
  4101. emitter._babylonData = {
  4102. loaded: promise
  4103. };
  4104. }
  4105. return emitter._babylonData.loaded;
  4106. };
  4107. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  4108. switch (action) {
  4109. case "play" /* play */: {
  4110. return function (currentFrame) {
  4111. var frameOffset = (startOffset || 0) + (currentFrame - time);
  4112. sound.play(frameOffset);
  4113. };
  4114. }
  4115. case "stop" /* stop */: {
  4116. return function (currentFrame) {
  4117. sound.stop();
  4118. };
  4119. }
  4120. case "pause" /* pause */: {
  4121. return function (currentFrame) {
  4122. sound.pause();
  4123. };
  4124. }
  4125. default: {
  4126. throw new Error(context + ": Unsupported action " + action);
  4127. }
  4128. }
  4129. };
  4130. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  4131. var _this = this;
  4132. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  4133. return Promise.resolve();
  4134. }
  4135. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  4136. var emitterIndex = event.emitter;
  4137. var emitter = glTFLoader_1.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  4138. return this._loadEmitterAsync(context, emitter).then(function () {
  4139. var sound = emitter._babylonData.sound;
  4140. if (sound) {
  4141. var babylonAnimationEvent = new babylonjs_1.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  4142. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  4143. // Make sure all started audio stops when this animation is terminated.
  4144. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  4145. sound.stop();
  4146. });
  4147. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  4148. sound.pause();
  4149. });
  4150. }
  4151. });
  4152. };
  4153. return MSFT_audio_emitter;
  4154. }());
  4155. exports.MSFT_audio_emitter = MSFT_audio_emitter;
  4156. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  4157. /***/ }),
  4158. /***/ "./src/glTF/2.0/Extensions/MSFT_lod.ts":
  4159. /*!*********************************************!*\
  4160. !*** ./src/glTF/2.0/Extensions/MSFT_lod.ts ***!
  4161. \*********************************************/
  4162. /*! no static exports found */
  4163. /***/ (function(module, exports, __webpack_require__) {
  4164. "use strict";
  4165. Object.defineProperty(exports, "__esModule", { value: true });
  4166. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4167. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4168. var NAME = "MSFT_lod";
  4169. /**
  4170. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  4171. */
  4172. var MSFT_lod = /** @class */ (function () {
  4173. /** @hidden */
  4174. function MSFT_lod(loader) {
  4175. /** The name of this extension. */
  4176. this.name = NAME;
  4177. /** Defines whether this extension is enabled. */
  4178. this.enabled = true;
  4179. /**
  4180. * Maximum number of LODs to load, starting from the lowest LOD.
  4181. */
  4182. this.maxLODsToLoad = Number.MAX_VALUE;
  4183. /**
  4184. * Observable raised when all node LODs of one level are loaded.
  4185. * The event data is the index of the loaded LOD starting from zero.
  4186. * Dispose the loader to cancel the loading of the next level of LODs.
  4187. */
  4188. this.onNodeLODsLoadedObservable = new babylonjs_1.Observable();
  4189. /**
  4190. * Observable raised when all material LODs of one level are loaded.
  4191. * The event data is the index of the loaded LOD starting from zero.
  4192. * Dispose the loader to cancel the loading of the next level of LODs.
  4193. */
  4194. this.onMaterialLODsLoadedObservable = new babylonjs_1.Observable();
  4195. this._nodeIndexLOD = null;
  4196. this._nodeSignalLODs = new Array();
  4197. this._nodePromiseLODs = new Array();
  4198. this._materialIndexLOD = null;
  4199. this._materialSignalLODs = new Array();
  4200. this._materialPromiseLODs = new Array();
  4201. this._loader = loader;
  4202. }
  4203. /** @hidden */
  4204. MSFT_lod.prototype.dispose = function () {
  4205. delete this._loader;
  4206. this._nodeIndexLOD = null;
  4207. this._nodeSignalLODs.length = 0;
  4208. this._nodePromiseLODs.length = 0;
  4209. this._materialIndexLOD = null;
  4210. this._materialSignalLODs.length = 0;
  4211. this._materialPromiseLODs.length = 0;
  4212. this.onMaterialLODsLoadedObservable.clear();
  4213. this.onNodeLODsLoadedObservable.clear();
  4214. };
  4215. /** @hidden */
  4216. MSFT_lod.prototype.onReady = function () {
  4217. var _this = this;
  4218. var _loop_1 = function (indexLOD) {
  4219. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  4220. if (indexLOD !== 0) {
  4221. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  4222. }
  4223. _this._loader.log("Loaded node LOD " + indexLOD);
  4224. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  4225. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  4226. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  4227. if (_this._nodeSignalLODs[indexLOD]) {
  4228. _this._nodeSignalLODs[indexLOD].resolve();
  4229. }
  4230. }
  4231. });
  4232. this_1._loader._completePromises.push(promise);
  4233. };
  4234. var this_1 = this;
  4235. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  4236. _loop_1(indexLOD);
  4237. }
  4238. var _loop_2 = function (indexLOD) {
  4239. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  4240. if (indexLOD !== 0) {
  4241. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  4242. }
  4243. _this._loader.log("Loaded material LOD " + indexLOD);
  4244. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  4245. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  4246. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  4247. if (_this._materialSignalLODs[indexLOD]) {
  4248. _this._materialSignalLODs[indexLOD].resolve();
  4249. }
  4250. }
  4251. });
  4252. this_2._loader._completePromises.push(promise);
  4253. };
  4254. var this_2 = this;
  4255. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  4256. _loop_2(indexLOD);
  4257. }
  4258. };
  4259. /** @hidden */
  4260. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  4261. var _this = this;
  4262. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  4263. var firstPromise;
  4264. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  4265. _this._loader.logOpen("" + extensionContext);
  4266. var _loop_3 = function (indexLOD) {
  4267. var nodeLOD = nodeLODs[indexLOD];
  4268. if (indexLOD !== 0) {
  4269. _this._nodeIndexLOD = indexLOD;
  4270. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new babylonjs_1.Deferred();
  4271. }
  4272. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  4273. if (indexLOD !== 0) {
  4274. // TODO: should not rely on _babylonMesh
  4275. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4276. if (previousNodeLOD._babylonMesh) {
  4277. previousNodeLOD._babylonMesh.dispose();
  4278. delete previousNodeLOD._babylonMesh;
  4279. _this._disposeUnusedMaterials();
  4280. }
  4281. }
  4282. return babylonMesh;
  4283. });
  4284. if (indexLOD === 0) {
  4285. firstPromise = promise;
  4286. }
  4287. else {
  4288. _this._nodeIndexLOD = null;
  4289. }
  4290. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  4291. _this._nodePromiseLODs[indexLOD].push(promise);
  4292. };
  4293. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4294. _loop_3(indexLOD);
  4295. }
  4296. _this._loader.logClose();
  4297. return firstPromise;
  4298. });
  4299. };
  4300. /** @hidden */
  4301. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4302. var _this = this;
  4303. // Don't load material LODs if already loading a node LOD.
  4304. if (this._nodeIndexLOD) {
  4305. return null;
  4306. }
  4307. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  4308. var firstPromise;
  4309. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  4310. _this._loader.logOpen("" + extensionContext);
  4311. var _loop_4 = function (indexLOD) {
  4312. var materialLOD = materialLODs[indexLOD];
  4313. if (indexLOD !== 0) {
  4314. _this._materialIndexLOD = indexLOD;
  4315. }
  4316. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  4317. if (indexLOD === 0) {
  4318. assign(babylonMaterial);
  4319. }
  4320. }).then(function (babylonMaterial) {
  4321. if (indexLOD !== 0) {
  4322. assign(babylonMaterial);
  4323. // TODO: should not rely on _babylonData
  4324. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  4325. if (previousBabylonDataLOD[babylonDrawMode]) {
  4326. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  4327. delete previousBabylonDataLOD[babylonDrawMode];
  4328. }
  4329. }
  4330. return babylonMaterial;
  4331. });
  4332. if (indexLOD === 0) {
  4333. firstPromise = promise;
  4334. }
  4335. else {
  4336. _this._materialIndexLOD = null;
  4337. }
  4338. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  4339. _this._materialPromiseLODs[indexLOD].push(promise);
  4340. };
  4341. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4342. _loop_4(indexLOD);
  4343. }
  4344. _this._loader.logClose();
  4345. return firstPromise;
  4346. });
  4347. };
  4348. /** @hidden */
  4349. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4350. var _this = this;
  4351. // Defer the loading of uris if loading a material or node LOD.
  4352. if (this._materialIndexLOD !== null) {
  4353. this._loader.log("deferred");
  4354. var previousIndexLOD = this._materialIndexLOD - 1;
  4355. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  4356. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  4357. return _this._loader.loadUriAsync(context, uri);
  4358. });
  4359. }
  4360. else if (this._nodeIndexLOD !== null) {
  4361. this._loader.log("deferred");
  4362. var previousIndexLOD = this._nodeIndexLOD - 1;
  4363. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  4364. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  4365. return _this._loader.loadUriAsync(context, uri);
  4366. });
  4367. }
  4368. return null;
  4369. };
  4370. /**
  4371. * Gets an array of LOD properties from lowest to highest.
  4372. */
  4373. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4374. if (this.maxLODsToLoad <= 0) {
  4375. throw new Error("maxLODsToLoad must be greater than zero");
  4376. }
  4377. var properties = new Array();
  4378. for (var i = ids.length - 1; i >= 0; i--) {
  4379. properties.push(glTFLoader_1.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  4380. if (properties.length === this.maxLODsToLoad) {
  4381. return properties;
  4382. }
  4383. }
  4384. properties.push(property);
  4385. return properties;
  4386. };
  4387. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  4388. // TODO: should not rely on _babylonData
  4389. var materials = this._loader.gltf.materials;
  4390. if (materials) {
  4391. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  4392. var material = materials_1[_i];
  4393. if (material._babylonData) {
  4394. for (var drawMode in material._babylonData) {
  4395. var babylonData = material._babylonData[drawMode];
  4396. if (babylonData.meshes.length === 0) {
  4397. babylonData.material.dispose(false, true);
  4398. delete material._babylonData[drawMode];
  4399. }
  4400. }
  4401. }
  4402. }
  4403. }
  4404. };
  4405. return MSFT_lod;
  4406. }());
  4407. exports.MSFT_lod = MSFT_lod;
  4408. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  4409. /***/ }),
  4410. /***/ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts":
  4411. /*!*******************************************************!*\
  4412. !*** ./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts ***!
  4413. \*******************************************************/
  4414. /*! no static exports found */
  4415. /***/ (function(module, exports, __webpack_require__) {
  4416. "use strict";
  4417. Object.defineProperty(exports, "__esModule", { value: true });
  4418. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4419. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4420. var NAME = "MSFT_minecraftMesh";
  4421. /** @hidden */
  4422. var MSFT_minecraftMesh = /** @class */ (function () {
  4423. function MSFT_minecraftMesh(loader) {
  4424. this.name = NAME;
  4425. this.enabled = true;
  4426. this._loader = loader;
  4427. }
  4428. MSFT_minecraftMesh.prototype.dispose = function () {
  4429. delete this._loader;
  4430. };
  4431. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4432. var _this = this;
  4433. return glTFLoader_1.GLTFLoaderV2.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  4434. if (extra) {
  4435. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4436. throw new Error(extraContext + ": Material type not supported");
  4437. }
  4438. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  4439. if (babylonMaterial.needAlphaBlending()) {
  4440. babylonMaterial.forceDepthWrite = true;
  4441. babylonMaterial.separateCullingPass = true;
  4442. }
  4443. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  4444. babylonMaterial.twoSidedLighting = true;
  4445. return promise;
  4446. }
  4447. return null;
  4448. });
  4449. };
  4450. return MSFT_minecraftMesh;
  4451. }());
  4452. exports.MSFT_minecraftMesh = MSFT_minecraftMesh;
  4453. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  4454. /***/ }),
  4455. /***/ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts":
  4456. /*!*****************************************************!*\
  4457. !*** ./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts ***!
  4458. \*****************************************************/
  4459. /*! no static exports found */
  4460. /***/ (function(module, exports, __webpack_require__) {
  4461. "use strict";
  4462. Object.defineProperty(exports, "__esModule", { value: true });
  4463. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4464. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4465. var NAME = "MSFT_sRGBFactors";
  4466. /** @hidden */
  4467. var MSFT_sRGBFactors = /** @class */ (function () {
  4468. function MSFT_sRGBFactors(loader) {
  4469. this.name = NAME;
  4470. this.enabled = true;
  4471. this._loader = loader;
  4472. }
  4473. MSFT_sRGBFactors.prototype.dispose = function () {
  4474. delete this._loader;
  4475. };
  4476. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4477. var _this = this;
  4478. return glTFLoader_1.GLTFLoaderV2.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  4479. if (extra) {
  4480. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4481. throw new Error(extraContext + ": Material type not supported");
  4482. }
  4483. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  4484. if (!babylonMaterial.albedoTexture) {
  4485. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  4486. }
  4487. if (!babylonMaterial.reflectivityTexture) {
  4488. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  4489. }
  4490. return promise;
  4491. }
  4492. return null;
  4493. });
  4494. };
  4495. return MSFT_sRGBFactors;
  4496. }());
  4497. exports.MSFT_sRGBFactors = MSFT_sRGBFactors;
  4498. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  4499. /***/ }),
  4500. /***/ "./src/glTF/2.0/Extensions/index.ts":
  4501. /*!******************************************!*\
  4502. !*** ./src/glTF/2.0/Extensions/index.ts ***!
  4503. \******************************************/
  4504. /*! no static exports found */
  4505. /***/ (function(module, exports, __webpack_require__) {
  4506. "use strict";
  4507. function __export(m) {
  4508. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  4509. }
  4510. Object.defineProperty(exports, "__esModule", { value: true });
  4511. __export(__webpack_require__(/*! ./EXT_lights_image_based */ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts"));
  4512. __export(__webpack_require__(/*! ./KHR_draco_mesh_compression */ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts"));
  4513. __export(__webpack_require__(/*! ./KHR_lights_punctual */ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts"));
  4514. __export(__webpack_require__(/*! ./KHR_materials_pbrSpecularGlossiness */ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts"));
  4515. __export(__webpack_require__(/*! ./KHR_materials_unlit */ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts"));
  4516. __export(__webpack_require__(/*! ./KHR_texture_transform */ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts"));
  4517. __export(__webpack_require__(/*! ./MSFT_audio_emitter */ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts"));
  4518. __export(__webpack_require__(/*! ./MSFT_lod */ "./src/glTF/2.0/Extensions/MSFT_lod.ts"));
  4519. __export(__webpack_require__(/*! ./MSFT_minecraftMesh */ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts"));
  4520. __export(__webpack_require__(/*! ./MSFT_sRGBFactors */ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts"));
  4521. /***/ }),
  4522. /***/ "./src/glTF/2.0/glTFLoader.ts":
  4523. /*!************************************!*\
  4524. !*** ./src/glTF/2.0/glTFLoader.ts ***!
  4525. \************************************/
  4526. /*! no static exports found */
  4527. /***/ (function(module, exports, __webpack_require__) {
  4528. "use strict";
  4529. Object.defineProperty(exports, "__esModule", { value: true });
  4530. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4531. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  4532. /**
  4533. * Helper class for working with arrays when loading the glTF asset
  4534. */
  4535. var ArrayItem = /** @class */ (function () {
  4536. function ArrayItem() {
  4537. }
  4538. /**
  4539. * Gets an item from the given array.
  4540. * @param context The context when loading the asset
  4541. * @param array The array to get the item from
  4542. * @param index The index to the array
  4543. * @returns The array item
  4544. */
  4545. ArrayItem.Get = function (context, array, index) {
  4546. if (!array || index == undefined || !array[index]) {
  4547. throw new Error(context + ": Failed to find index (" + index + ")");
  4548. }
  4549. return array[index];
  4550. };
  4551. /**
  4552. * Assign an `index` field to each item of the given array.
  4553. * @param array The array of items
  4554. */
  4555. ArrayItem.Assign = function (array) {
  4556. if (array) {
  4557. for (var index = 0; index < array.length; index++) {
  4558. array[index].index = index;
  4559. }
  4560. }
  4561. };
  4562. return ArrayItem;
  4563. }());
  4564. exports.ArrayItem = ArrayItem;
  4565. /**
  4566. * The glTF 2.0 loader
  4567. */
  4568. var GLTFLoaderV2 = /** @class */ (function () {
  4569. /** @hidden */
  4570. function GLTFLoaderV2(parent) {
  4571. /** @hidden */
  4572. this._completePromises = new Array();
  4573. this._disposed = false;
  4574. this._state = null;
  4575. this._extensions = {};
  4576. this._defaultBabylonMaterialData = {};
  4577. this._requests = new Array();
  4578. this._parent = parent;
  4579. }
  4580. /**
  4581. * Registers a loader extension.
  4582. * @param name The name of the loader extension.
  4583. * @param factory The factory function that creates the loader extension.
  4584. */
  4585. GLTFLoaderV2.RegisterExtension = function (name, factory) {
  4586. if (GLTFLoaderV2.UnregisterExtension(name)) {
  4587. babylonjs_1.Tools.Warn("Extension with the name '" + name + "' already exists");
  4588. }
  4589. GLTFLoaderV2._ExtensionFactories[name] = factory;
  4590. // Keep the order of registration so that extensions registered first are called first.
  4591. GLTFLoaderV2._ExtensionNames.push(name);
  4592. };
  4593. /**
  4594. * Unregisters a loader extension.
  4595. * @param name The name of the loader extenion.
  4596. * @returns A boolean indicating whether the extension has been unregistered
  4597. */
  4598. GLTFLoaderV2.UnregisterExtension = function (name) {
  4599. if (!GLTFLoaderV2._ExtensionFactories[name]) {
  4600. return false;
  4601. }
  4602. delete GLTFLoaderV2._ExtensionFactories[name];
  4603. var index = GLTFLoaderV2._ExtensionNames.indexOf(name);
  4604. if (index !== -1) {
  4605. GLTFLoaderV2._ExtensionNames.splice(index, 1);
  4606. }
  4607. return true;
  4608. };
  4609. Object.defineProperty(GLTFLoaderV2.prototype, "state", {
  4610. /**
  4611. * Gets the loader state.
  4612. */
  4613. get: function () {
  4614. return this._state;
  4615. },
  4616. enumerable: true,
  4617. configurable: true
  4618. });
  4619. /** @hidden */
  4620. GLTFLoaderV2.prototype.dispose = function () {
  4621. if (this._disposed) {
  4622. return;
  4623. }
  4624. this._disposed = true;
  4625. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4626. var request = _a[_i];
  4627. request.abort();
  4628. }
  4629. this._requests.length = 0;
  4630. delete this.gltf;
  4631. delete this.babylonScene;
  4632. this._completePromises.length = 0;
  4633. for (var name_1 in this._extensions) {
  4634. var extension = this._extensions[name_1];
  4635. if (extension.dispose) {
  4636. this._extensions[name_1].dispose();
  4637. }
  4638. }
  4639. this._extensions = {};
  4640. delete this._rootBabylonMesh;
  4641. delete this._progressCallback;
  4642. this._parent._clear();
  4643. };
  4644. /** @hidden */
  4645. GLTFLoaderV2.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  4646. var _this = this;
  4647. return Promise.resolve().then(function () {
  4648. _this.babylonScene = scene;
  4649. _this._rootUrl = rootUrl;
  4650. _this._fileName = fileName || "scene";
  4651. _this._progressCallback = onProgress;
  4652. _this._loadData(data);
  4653. var nodes = null;
  4654. if (meshesNames) {
  4655. var nodeMap_1 = {};
  4656. if (_this.gltf.nodes) {
  4657. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  4658. var node = _a[_i];
  4659. if (node.name) {
  4660. nodeMap_1[node.name] = node.index;
  4661. }
  4662. }
  4663. }
  4664. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  4665. nodes = names.map(function (name) {
  4666. var node = nodeMap_1[name];
  4667. if (node === undefined) {
  4668. throw new Error("Failed to find node '" + name + "'");
  4669. }
  4670. return node;
  4671. });
  4672. }
  4673. return _this._loadAsync(nodes, function () {
  4674. return {
  4675. meshes: _this._getMeshes(),
  4676. particleSystems: [],
  4677. skeletons: _this._getSkeletons(),
  4678. animationGroups: _this._getAnimationGroups()
  4679. };
  4680. });
  4681. });
  4682. };
  4683. /** @hidden */
  4684. GLTFLoaderV2.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  4685. var _this = this;
  4686. return Promise.resolve().then(function () {
  4687. _this.babylonScene = scene;
  4688. _this._rootUrl = rootUrl;
  4689. _this._fileName = fileName || "scene";
  4690. _this._progressCallback = onProgress;
  4691. _this._loadData(data);
  4692. return _this._loadAsync(null, function () { return undefined; });
  4693. });
  4694. };
  4695. GLTFLoaderV2.prototype._loadAsync = function (nodes, resultFunc) {
  4696. var _this = this;
  4697. return Promise.resolve().then(function () {
  4698. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  4699. _this._loadExtensions();
  4700. _this._checkExtensions();
  4701. var loadingToReadyCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.READY];
  4702. var loadingToCompleteCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.COMPLETE];
  4703. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  4704. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  4705. _this._setState(glTFFileLoader_1.GLTFLoaderState.LOADING);
  4706. _this._extensionsOnLoading();
  4707. var promises = new Array();
  4708. if (nodes) {
  4709. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  4710. }
  4711. else {
  4712. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  4713. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  4714. }
  4715. if (_this._parent.compileMaterials) {
  4716. promises.push(_this._compileMaterialsAsync());
  4717. }
  4718. if (_this._parent.compileShadowGenerators) {
  4719. promises.push(_this._compileShadowGeneratorsAsync());
  4720. }
  4721. var resultPromise = Promise.all(promises).then(function () {
  4722. _this._setState(glTFFileLoader_1.GLTFLoaderState.READY);
  4723. _this._extensionsOnReady();
  4724. _this._startAnimations();
  4725. return resultFunc();
  4726. });
  4727. resultPromise.then(function () {
  4728. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  4729. babylonjs_1.Tools.SetImmediate(function () {
  4730. if (!_this._disposed) {
  4731. Promise.all(_this._completePromises).then(function () {
  4732. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  4733. _this._setState(glTFFileLoader_1.GLTFLoaderState.COMPLETE);
  4734. _this._parent.onCompleteObservable.notifyObservers(undefined);
  4735. _this._parent.onCompleteObservable.clear();
  4736. _this.dispose();
  4737. }, function (error) {
  4738. _this._parent.onErrorObservable.notifyObservers(error);
  4739. _this._parent.onErrorObservable.clear();
  4740. _this.dispose();
  4741. });
  4742. }
  4743. });
  4744. });
  4745. return resultPromise;
  4746. }, function (error) {
  4747. if (!_this._disposed) {
  4748. _this._parent.onErrorObservable.notifyObservers(error);
  4749. _this._parent.onErrorObservable.clear();
  4750. _this.dispose();
  4751. }
  4752. throw error;
  4753. });
  4754. };
  4755. GLTFLoaderV2.prototype._loadData = function (data) {
  4756. this.gltf = data.json;
  4757. this._setupData();
  4758. if (data.bin) {
  4759. var buffers = this.gltf.buffers;
  4760. if (buffers && buffers[0] && !buffers[0].uri) {
  4761. var binaryBuffer = buffers[0];
  4762. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  4763. babylonjs_1.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  4764. }
  4765. binaryBuffer._data = Promise.resolve(data.bin);
  4766. }
  4767. else {
  4768. babylonjs_1.Tools.Warn("Unexpected BIN chunk");
  4769. }
  4770. }
  4771. };
  4772. GLTFLoaderV2.prototype._setupData = function () {
  4773. ArrayItem.Assign(this.gltf.accessors);
  4774. ArrayItem.Assign(this.gltf.animations);
  4775. ArrayItem.Assign(this.gltf.buffers);
  4776. ArrayItem.Assign(this.gltf.bufferViews);
  4777. ArrayItem.Assign(this.gltf.cameras);
  4778. ArrayItem.Assign(this.gltf.images);
  4779. ArrayItem.Assign(this.gltf.materials);
  4780. ArrayItem.Assign(this.gltf.meshes);
  4781. ArrayItem.Assign(this.gltf.nodes);
  4782. ArrayItem.Assign(this.gltf.samplers);
  4783. ArrayItem.Assign(this.gltf.scenes);
  4784. ArrayItem.Assign(this.gltf.skins);
  4785. ArrayItem.Assign(this.gltf.textures);
  4786. if (this.gltf.nodes) {
  4787. var nodeParents = {};
  4788. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  4789. var node = _a[_i];
  4790. if (node.children) {
  4791. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  4792. var index = _c[_b];
  4793. nodeParents[index] = node.index;
  4794. }
  4795. }
  4796. }
  4797. var rootNode = this._createRootNode();
  4798. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  4799. var node = _e[_d];
  4800. var parentIndex = nodeParents[node.index];
  4801. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  4802. }
  4803. }
  4804. };
  4805. GLTFLoaderV2.prototype._loadExtensions = function () {
  4806. for (var _i = 0, _a = GLTFLoaderV2._ExtensionNames; _i < _a.length; _i++) {
  4807. var name_2 = _a[_i];
  4808. var extension = GLTFLoaderV2._ExtensionFactories[name_2](this);
  4809. this._extensions[name_2] = extension;
  4810. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  4811. }
  4812. this._parent.onExtensionLoadedObservable.clear();
  4813. };
  4814. GLTFLoaderV2.prototype._checkExtensions = function () {
  4815. if (this.gltf.extensionsRequired) {
  4816. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  4817. var name_3 = _a[_i];
  4818. var extension = this._extensions[name_3];
  4819. if (!extension || !extension.enabled) {
  4820. throw new Error("Require extension " + name_3 + " is not available");
  4821. }
  4822. }
  4823. }
  4824. };
  4825. GLTFLoaderV2.prototype._setState = function (state) {
  4826. this._state = state;
  4827. this.log(glTFFileLoader_1.GLTFLoaderState[this._state]);
  4828. };
  4829. GLTFLoaderV2.prototype._createRootNode = function () {
  4830. this._rootBabylonMesh = new babylonjs_1.Mesh("__root__", this.babylonScene);
  4831. var rootNode = {
  4832. _babylonMesh: this._rootBabylonMesh,
  4833. index: -1
  4834. };
  4835. switch (this._parent.coordinateSystemMode) {
  4836. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.AUTO: {
  4837. if (!this.babylonScene.useRightHandedSystem) {
  4838. rootNode.rotation = [0, 1, 0, 0];
  4839. rootNode.scale = [1, 1, -1];
  4840. GLTFLoaderV2._LoadTransform(rootNode, this._rootBabylonMesh);
  4841. }
  4842. break;
  4843. }
  4844. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  4845. this.babylonScene.useRightHandedSystem = true;
  4846. break;
  4847. }
  4848. default: {
  4849. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  4850. }
  4851. }
  4852. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  4853. return rootNode;
  4854. };
  4855. /**
  4856. * Loads a glTF scene.
  4857. * @param context The context when loading the asset
  4858. * @param scene The glTF scene property
  4859. * @returns A promise that resolves when the load is complete
  4860. */
  4861. GLTFLoaderV2.prototype.loadSceneAsync = function (context, scene) {
  4862. var _this = this;
  4863. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  4864. if (extensionPromise) {
  4865. return extensionPromise;
  4866. }
  4867. var promises = new Array();
  4868. this.logOpen(context + " " + (scene.name || ""));
  4869. if (scene.nodes) {
  4870. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  4871. var index = _a[_i];
  4872. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  4873. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  4874. babylonMesh.parent = _this._rootBabylonMesh;
  4875. }));
  4876. }
  4877. }
  4878. promises.push(this._loadAnimationsAsync());
  4879. this.logClose();
  4880. return Promise.all(promises).then(function () { });
  4881. };
  4882. GLTFLoaderV2.prototype._forEachPrimitive = function (node, callback) {
  4883. if (node._primitiveBabylonMeshes) {
  4884. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  4885. var babylonMesh = _a[_i];
  4886. callback(babylonMesh);
  4887. }
  4888. }
  4889. else {
  4890. callback(node._babylonMesh);
  4891. }
  4892. };
  4893. GLTFLoaderV2.prototype._getMeshes = function () {
  4894. var meshes = new Array();
  4895. // Root mesh is always first.
  4896. meshes.push(this._rootBabylonMesh);
  4897. var nodes = this.gltf.nodes;
  4898. if (nodes) {
  4899. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  4900. var node = nodes_1[_i];
  4901. if (node._babylonMesh) {
  4902. meshes.push(node._babylonMesh);
  4903. }
  4904. if (node._primitiveBabylonMeshes) {
  4905. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  4906. var babylonMesh = _b[_a];
  4907. meshes.push(babylonMesh);
  4908. }
  4909. }
  4910. }
  4911. }
  4912. return meshes;
  4913. };
  4914. GLTFLoaderV2.prototype._getSkeletons = function () {
  4915. var skeletons = new Array();
  4916. var skins = this.gltf.skins;
  4917. if (skins) {
  4918. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  4919. var skin = skins_1[_i];
  4920. if (skin._babylonSkeleton) {
  4921. skeletons.push(skin._babylonSkeleton);
  4922. }
  4923. }
  4924. }
  4925. return skeletons;
  4926. };
  4927. GLTFLoaderV2.prototype._getAnimationGroups = function () {
  4928. var animationGroups = new Array();
  4929. var animations = this.gltf.animations;
  4930. if (animations) {
  4931. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  4932. var animation = animations_1[_i];
  4933. if (animation._babylonAnimationGroup) {
  4934. animationGroups.push(animation._babylonAnimationGroup);
  4935. }
  4936. }
  4937. }
  4938. return animationGroups;
  4939. };
  4940. GLTFLoaderV2.prototype._startAnimations = function () {
  4941. switch (this._parent.animationStartMode) {
  4942. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.NONE: {
  4943. // do nothing
  4944. break;
  4945. }
  4946. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.FIRST: {
  4947. var babylonAnimationGroups = this._getAnimationGroups();
  4948. if (babylonAnimationGroups.length !== 0) {
  4949. babylonAnimationGroups[0].start(true);
  4950. }
  4951. break;
  4952. }
  4953. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.ALL: {
  4954. var babylonAnimationGroups = this._getAnimationGroups();
  4955. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  4956. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  4957. babylonAnimationGroup.start(true);
  4958. }
  4959. break;
  4960. }
  4961. default: {
  4962. babylonjs_1.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  4963. return;
  4964. }
  4965. }
  4966. };
  4967. /**
  4968. * Loads a glTF node.
  4969. * @param context The context when loading the asset
  4970. * @param node The glTF node property
  4971. * @param assign A function called synchronously after parsing the glTF properties
  4972. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  4973. */
  4974. GLTFLoaderV2.prototype.loadNodeAsync = function (context, node, assign) {
  4975. var _this = this;
  4976. if (assign === void 0) { assign = function () { }; }
  4977. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  4978. if (extensionPromise) {
  4979. return extensionPromise;
  4980. }
  4981. if (node._babylonMesh) {
  4982. throw new Error(context + ": Invalid recursive node hierarchy");
  4983. }
  4984. var promises = new Array();
  4985. this.logOpen(context + " " + (node.name || ""));
  4986. var babylonMesh = new babylonjs_1.Mesh(node.name || "node" + node.index, this.babylonScene);
  4987. node._babylonMesh = babylonMesh;
  4988. babylonMesh.setEnabled(false);
  4989. GLTFLoaderV2._LoadTransform(node, babylonMesh);
  4990. if (node.mesh != undefined) {
  4991. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  4992. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  4993. }
  4994. if (node.camera != undefined) {
  4995. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  4996. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  4997. babylonCamera.parent = babylonMesh;
  4998. }));
  4999. }
  5000. if (node.children) {
  5001. var _loop_1 = function (index) {
  5002. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  5003. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  5004. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  5005. if (childNode.skin != undefined) {
  5006. childBabylonMesh.parent = _this._rootBabylonMesh;
  5007. return;
  5008. }
  5009. childBabylonMesh.parent = babylonMesh;
  5010. }));
  5011. };
  5012. var this_1 = this;
  5013. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  5014. var index = _a[_i];
  5015. _loop_1(index);
  5016. }
  5017. }
  5018. assign(babylonMesh);
  5019. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  5020. this.logClose();
  5021. return Promise.all(promises).then(function () {
  5022. babylonMesh.setEnabled(true);
  5023. return babylonMesh;
  5024. });
  5025. };
  5026. GLTFLoaderV2.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  5027. var _this = this;
  5028. var promises = new Array();
  5029. this.logOpen(context + " " + (mesh.name || ""));
  5030. var primitives = mesh.primitives;
  5031. if (!primitives || primitives.length === 0) {
  5032. throw new Error(context + ": Primitives are missing");
  5033. }
  5034. ArrayItem.Assign(primitives);
  5035. if (primitives.length === 1) {
  5036. var primitive = primitives[0];
  5037. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  5038. }
  5039. else {
  5040. node._primitiveBabylonMeshes = [];
  5041. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  5042. var primitive = primitives_1[_i];
  5043. var primitiveBabylonMesh = new babylonjs_1.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  5044. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  5045. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  5046. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  5047. }
  5048. }
  5049. if (node.skin != undefined) {
  5050. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  5051. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  5052. }
  5053. this.logClose();
  5054. return Promise.all(promises).then(function () {
  5055. _this._forEachPrimitive(node, function (babylonMesh) {
  5056. babylonMesh._refreshBoundingInfo(true);
  5057. });
  5058. });
  5059. };
  5060. GLTFLoaderV2.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  5061. var _this = this;
  5062. var promises = new Array();
  5063. this.logOpen("" + context);
  5064. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  5065. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  5066. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  5067. babylonGeometry.applyToMesh(babylonMesh);
  5068. });
  5069. }));
  5070. var babylonDrawMode = GLTFLoaderV2._GetDrawMode(context, primitive.mode);
  5071. if (primitive.material == undefined) {
  5072. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  5073. if (!babylonMaterial) {
  5074. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  5075. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5076. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  5077. }
  5078. babylonMesh.material = babylonMaterial;
  5079. }
  5080. else {
  5081. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  5082. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  5083. babylonMesh.material = babylonMaterial;
  5084. }));
  5085. }
  5086. this.logClose();
  5087. return Promise.all(promises).then(function () { });
  5088. };
  5089. GLTFLoaderV2.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  5090. var _this = this;
  5091. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  5092. if (extensionPromise) {
  5093. return extensionPromise;
  5094. }
  5095. var attributes = primitive.attributes;
  5096. if (!attributes) {
  5097. throw new Error(context + ": Attributes are missing");
  5098. }
  5099. var promises = new Array();
  5100. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, this.babylonScene);
  5101. if (primitive.indices == undefined) {
  5102. babylonMesh.isUnIndexed = true;
  5103. }
  5104. else {
  5105. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  5106. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5107. babylonGeometry.setIndices(data);
  5108. }));
  5109. }
  5110. var loadAttribute = function (attribute, kind, callback) {
  5111. if (attributes[attribute] == undefined) {
  5112. return;
  5113. }
  5114. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  5115. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  5116. babylonMesh._delayInfo.push(kind);
  5117. }
  5118. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  5119. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  5120. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  5121. }));
  5122. if (callback) {
  5123. callback(accessor);
  5124. }
  5125. };
  5126. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  5127. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  5128. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  5129. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  5130. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  5131. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  5132. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  5133. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind, function (accessor) {
  5134. if (accessor.type === "VEC4" /* VEC4 */) {
  5135. babylonMesh.hasVertexAlpha = true;
  5136. }
  5137. });
  5138. return Promise.all(promises).then(function () {
  5139. return babylonGeometry;
  5140. });
  5141. };
  5142. GLTFLoaderV2.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  5143. if (!primitive.targets) {
  5144. return;
  5145. }
  5146. if (node._numMorphTargets == undefined) {
  5147. node._numMorphTargets = primitive.targets.length;
  5148. }
  5149. else if (primitive.targets.length !== node._numMorphTargets) {
  5150. throw new Error(context + ": Primitives do not have the same number of targets");
  5151. }
  5152. babylonMesh.morphTargetManager = new babylonjs_1.MorphTargetManager();
  5153. for (var index = 0; index < primitive.targets.length; index++) {
  5154. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  5155. babylonMesh.morphTargetManager.addTarget(new babylonjs_1.MorphTarget("morphTarget" + index, weight));
  5156. // TODO: tell the target whether it has positions, normals, tangents
  5157. }
  5158. };
  5159. GLTFLoaderV2.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  5160. if (!primitive.targets) {
  5161. return Promise.resolve();
  5162. }
  5163. var promises = new Array();
  5164. var morphTargetManager = babylonMesh.morphTargetManager;
  5165. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  5166. var babylonMorphTarget = morphTargetManager.getTarget(index);
  5167. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  5168. }
  5169. return Promise.all(promises).then(function () { });
  5170. };
  5171. GLTFLoaderV2.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  5172. var _this = this;
  5173. var promises = new Array();
  5174. var loadAttribute = function (attribute, kind, setData) {
  5175. if (attributes[attribute] == undefined) {
  5176. return;
  5177. }
  5178. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  5179. if (!babylonVertexBuffer) {
  5180. return;
  5181. }
  5182. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  5183. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5184. setData(babylonVertexBuffer, data);
  5185. }));
  5186. };
  5187. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  5188. babylonVertexBuffer.forEach(data.length, function (value, index) {
  5189. data[index] += value;
  5190. });
  5191. babylonMorphTarget.setPositions(data);
  5192. });
  5193. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  5194. babylonVertexBuffer.forEach(data.length, function (value, index) {
  5195. data[index] += value;
  5196. });
  5197. babylonMorphTarget.setNormals(data);
  5198. });
  5199. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  5200. var dataIndex = 0;
  5201. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  5202. // Tangent data for morph targets is stored as xyz delta.
  5203. // The vertexData.tangent is stored as xyzw.
  5204. // So we need to skip every fourth vertexData.tangent.
  5205. if (((index + 1) % 4) !== 0) {
  5206. data[dataIndex++] += value;
  5207. }
  5208. });
  5209. babylonMorphTarget.setTangents(data);
  5210. });
  5211. return Promise.all(promises).then(function () { });
  5212. };
  5213. GLTFLoaderV2._LoadTransform = function (node, babylonNode) {
  5214. var position = babylonjs_1.Vector3.Zero();
  5215. var rotation = babylonjs_1.Quaternion.Identity();
  5216. var scaling = babylonjs_1.Vector3.One();
  5217. if (node.matrix) {
  5218. var matrix = babylonjs_1.Matrix.FromArray(node.matrix);
  5219. matrix.decompose(scaling, rotation, position);
  5220. }
  5221. else {
  5222. if (node.translation) {
  5223. position = babylonjs_1.Vector3.FromArray(node.translation);
  5224. }
  5225. if (node.rotation) {
  5226. rotation = babylonjs_1.Quaternion.FromArray(node.rotation);
  5227. }
  5228. if (node.scale) {
  5229. scaling = babylonjs_1.Vector3.FromArray(node.scale);
  5230. }
  5231. }
  5232. babylonNode.position = position;
  5233. babylonNode.rotationQuaternion = rotation;
  5234. babylonNode.scaling = scaling;
  5235. };
  5236. GLTFLoaderV2.prototype._loadSkinAsync = function (context, node, skin) {
  5237. var _this = this;
  5238. var assignSkeleton = function (skeleton) {
  5239. _this._forEachPrimitive(node, function (babylonMesh) {
  5240. babylonMesh.skeleton = skeleton;
  5241. });
  5242. // Ignore the TRS of skinned nodes.
  5243. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  5244. node._babylonMesh.position = babylonjs_1.Vector3.Zero();
  5245. node._babylonMesh.rotationQuaternion = babylonjs_1.Quaternion.Identity();
  5246. node._babylonMesh.scaling = babylonjs_1.Vector3.One();
  5247. };
  5248. if (skin._promise) {
  5249. return skin._promise.then(function () {
  5250. assignSkeleton(skin._babylonSkeleton);
  5251. });
  5252. }
  5253. var skeletonId = "skeleton" + skin.index;
  5254. var babylonSkeleton = new babylonjs_1.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  5255. skin._babylonSkeleton = babylonSkeleton;
  5256. this._loadBones(context, skin);
  5257. assignSkeleton(babylonSkeleton);
  5258. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  5259. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  5260. }));
  5261. };
  5262. GLTFLoaderV2.prototype._loadBones = function (context, skin) {
  5263. var babylonBones = {};
  5264. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  5265. var index = _a[_i];
  5266. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  5267. this._loadBone(node, skin, babylonBones);
  5268. }
  5269. };
  5270. GLTFLoaderV2.prototype._loadBone = function (node, skin, babylonBones) {
  5271. var babylonBone = babylonBones[node.index];
  5272. if (babylonBone) {
  5273. return babylonBone;
  5274. }
  5275. var babylonParentBone = null;
  5276. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  5277. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  5278. }
  5279. var boneIndex = skin.joints.indexOf(node.index);
  5280. babylonBone = new babylonjs_1.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  5281. babylonBones[node.index] = babylonBone;
  5282. node._babylonBones = node._babylonBones || [];
  5283. node._babylonBones.push(babylonBone);
  5284. return babylonBone;
  5285. };
  5286. GLTFLoaderV2.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  5287. if (skin.inverseBindMatrices == undefined) {
  5288. return Promise.resolve(null);
  5289. }
  5290. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  5291. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  5292. };
  5293. GLTFLoaderV2.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  5294. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  5295. var babylonBone = _a[_i];
  5296. var baseMatrix = babylonjs_1.Matrix.Identity();
  5297. var boneIndex = babylonBone._index;
  5298. if (inverseBindMatricesData && boneIndex !== -1) {
  5299. babylonjs_1.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  5300. baseMatrix.invertToRef(baseMatrix);
  5301. }
  5302. var babylonParentBone = babylonBone.getParent();
  5303. if (babylonParentBone) {
  5304. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  5305. }
  5306. babylonBone.updateMatrix(baseMatrix, false, false);
  5307. babylonBone._updateDifferenceMatrix(undefined, false);
  5308. }
  5309. };
  5310. GLTFLoaderV2.prototype._getNodeMatrix = function (node) {
  5311. return node.matrix ?
  5312. babylonjs_1.Matrix.FromArray(node.matrix) :
  5313. babylonjs_1.Matrix.Compose(node.scale ? babylonjs_1.Vector3.FromArray(node.scale) : babylonjs_1.Vector3.One(), node.rotation ? babylonjs_1.Quaternion.FromArray(node.rotation) : babylonjs_1.Quaternion.Identity(), node.translation ? babylonjs_1.Vector3.FromArray(node.translation) : babylonjs_1.Vector3.Zero());
  5314. };
  5315. /**
  5316. * Loads a glTF camera.
  5317. * @param context The context when loading the asset
  5318. * @param camera The glTF camera property
  5319. * @param assign A function called synchronously after parsing the glTF properties
  5320. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  5321. */
  5322. GLTFLoaderV2.prototype.loadCameraAsync = function (context, camera, assign) {
  5323. if (assign === void 0) { assign = function () { }; }
  5324. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  5325. if (extensionPromise) {
  5326. return extensionPromise;
  5327. }
  5328. var promises = new Array();
  5329. this.logOpen(context + " " + (camera.name || ""));
  5330. var babylonCamera = new babylonjs_1.FreeCamera(camera.name || "camera" + camera.index, babylonjs_1.Vector3.Zero(), this.babylonScene, false);
  5331. babylonCamera.rotation = new babylonjs_1.Vector3(0, Math.PI, 0);
  5332. switch (camera.type) {
  5333. case "perspective" /* PERSPECTIVE */: {
  5334. var perspective = camera.perspective;
  5335. if (!perspective) {
  5336. throw new Error(context + ": Camera perspective properties are missing");
  5337. }
  5338. babylonCamera.fov = perspective.yfov;
  5339. babylonCamera.minZ = perspective.znear;
  5340. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  5341. break;
  5342. }
  5343. case "orthographic" /* ORTHOGRAPHIC */: {
  5344. if (!camera.orthographic) {
  5345. throw new Error(context + ": Camera orthographic properties are missing");
  5346. }
  5347. babylonCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  5348. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  5349. babylonCamera.orthoRight = camera.orthographic.xmag;
  5350. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  5351. babylonCamera.orthoTop = camera.orthographic.ymag;
  5352. babylonCamera.minZ = camera.orthographic.znear;
  5353. babylonCamera.maxZ = camera.orthographic.zfar;
  5354. break;
  5355. }
  5356. default: {
  5357. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  5358. }
  5359. }
  5360. assign(babylonCamera);
  5361. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  5362. return Promise.all(promises).then(function () {
  5363. return babylonCamera;
  5364. });
  5365. };
  5366. GLTFLoaderV2.prototype._loadAnimationsAsync = function () {
  5367. var animations = this.gltf.animations;
  5368. if (!animations) {
  5369. return Promise.resolve();
  5370. }
  5371. var promises = new Array();
  5372. for (var index = 0; index < animations.length; index++) {
  5373. var animation = animations[index];
  5374. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  5375. }
  5376. return Promise.all(promises).then(function () { });
  5377. };
  5378. /**
  5379. * Loads a glTF animation.
  5380. * @param context The context when loading the asset
  5381. * @param animation The glTF animation property
  5382. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  5383. */
  5384. GLTFLoaderV2.prototype.loadAnimationAsync = function (context, animation) {
  5385. var promise = this._extensionsLoadAnimationAsync(context, animation);
  5386. if (promise) {
  5387. return promise;
  5388. }
  5389. var babylonAnimationGroup = new babylonjs_1.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  5390. animation._babylonAnimationGroup = babylonAnimationGroup;
  5391. var promises = new Array();
  5392. ArrayItem.Assign(animation.channels);
  5393. ArrayItem.Assign(animation.samplers);
  5394. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  5395. var channel = _a[_i];
  5396. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  5397. }
  5398. return Promise.all(promises).then(function () {
  5399. babylonAnimationGroup.normalize(0);
  5400. return babylonAnimationGroup;
  5401. });
  5402. };
  5403. GLTFLoaderV2.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  5404. var _this = this;
  5405. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  5406. // Ignore animations that have no animation targets.
  5407. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  5408. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  5409. return Promise.resolve();
  5410. }
  5411. // Ignore animations targeting TRS of skinned nodes.
  5412. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  5413. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  5414. return Promise.resolve();
  5415. }
  5416. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  5417. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  5418. var targetPath;
  5419. var animationType;
  5420. switch (channel.target.path) {
  5421. case "translation" /* TRANSLATION */: {
  5422. targetPath = "position";
  5423. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  5424. break;
  5425. }
  5426. case "rotation" /* ROTATION */: {
  5427. targetPath = "rotationQuaternion";
  5428. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  5429. break;
  5430. }
  5431. case "scale" /* SCALE */: {
  5432. targetPath = "scaling";
  5433. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  5434. break;
  5435. }
  5436. case "weights" /* WEIGHTS */: {
  5437. targetPath = "influence";
  5438. animationType = babylonjs_1.Animation.ANIMATIONTYPE_FLOAT;
  5439. break;
  5440. }
  5441. default: {
  5442. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  5443. }
  5444. }
  5445. var outputBufferOffset = 0;
  5446. var getNextOutputValue;
  5447. switch (targetPath) {
  5448. case "position": {
  5449. getNextOutputValue = function () {
  5450. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  5451. outputBufferOffset += 3;
  5452. return value;
  5453. };
  5454. break;
  5455. }
  5456. case "rotationQuaternion": {
  5457. getNextOutputValue = function () {
  5458. var value = babylonjs_1.Quaternion.FromArray(data.output, outputBufferOffset);
  5459. outputBufferOffset += 4;
  5460. return value;
  5461. };
  5462. break;
  5463. }
  5464. case "scaling": {
  5465. getNextOutputValue = function () {
  5466. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  5467. outputBufferOffset += 3;
  5468. return value;
  5469. };
  5470. break;
  5471. }
  5472. case "influence": {
  5473. getNextOutputValue = function () {
  5474. var value = new Array(targetNode._numMorphTargets);
  5475. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  5476. value[i] = data.output[outputBufferOffset++];
  5477. }
  5478. return value;
  5479. };
  5480. break;
  5481. }
  5482. }
  5483. var getNextKey;
  5484. switch (data.interpolation) {
  5485. case "STEP" /* STEP */: {
  5486. getNextKey = function (frameIndex) { return ({
  5487. frame: data.input[frameIndex],
  5488. value: getNextOutputValue(),
  5489. interpolation: babylonjs_1.AnimationKeyInterpolation.STEP
  5490. }); };
  5491. break;
  5492. }
  5493. case "LINEAR" /* LINEAR */: {
  5494. getNextKey = function (frameIndex) { return ({
  5495. frame: data.input[frameIndex],
  5496. value: getNextOutputValue()
  5497. }); };
  5498. break;
  5499. }
  5500. case "CUBICSPLINE" /* CUBICSPLINE */: {
  5501. getNextKey = function (frameIndex) { return ({
  5502. frame: data.input[frameIndex],
  5503. inTangent: getNextOutputValue(),
  5504. value: getNextOutputValue(),
  5505. outTangent: getNextOutputValue()
  5506. }); };
  5507. break;
  5508. }
  5509. }
  5510. var keys = new Array(data.input.length);
  5511. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  5512. keys[frameIndex] = getNextKey(frameIndex);
  5513. }
  5514. if (targetPath === "influence") {
  5515. var _loop_2 = function (targetIndex) {
  5516. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  5517. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  5518. babylonAnimation.setKeys(keys.map(function (key) { return ({
  5519. frame: key.frame,
  5520. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  5521. value: key.value[targetIndex],
  5522. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  5523. }); }));
  5524. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  5525. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  5526. var babylonAnimationClone = babylonAnimation.clone();
  5527. morphTarget.animations.push(babylonAnimationClone);
  5528. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  5529. });
  5530. };
  5531. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  5532. _loop_2(targetIndex);
  5533. }
  5534. }
  5535. else {
  5536. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  5537. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  5538. babylonAnimation.setKeys(keys);
  5539. if (targetNode._babylonBones) {
  5540. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  5541. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  5542. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  5543. babylonAnimationTarget.animations.push(babylonAnimation);
  5544. }
  5545. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  5546. }
  5547. else {
  5548. targetNode._babylonMesh.animations.push(babylonAnimation);
  5549. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  5550. }
  5551. }
  5552. });
  5553. };
  5554. GLTFLoaderV2.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  5555. if (sampler._data) {
  5556. return sampler._data;
  5557. }
  5558. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  5559. switch (interpolation) {
  5560. case "STEP" /* STEP */:
  5561. case "LINEAR" /* LINEAR */:
  5562. case "CUBICSPLINE" /* CUBICSPLINE */: {
  5563. break;
  5564. }
  5565. default: {
  5566. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  5567. }
  5568. }
  5569. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  5570. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  5571. sampler._data = Promise.all([
  5572. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  5573. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  5574. ]).then(function (_a) {
  5575. var inputData = _a[0], outputData = _a[1];
  5576. return {
  5577. input: inputData,
  5578. interpolation: interpolation,
  5579. output: outputData,
  5580. };
  5581. });
  5582. return sampler._data;
  5583. };
  5584. GLTFLoaderV2.prototype._loadBufferAsync = function (context, buffer) {
  5585. if (buffer._data) {
  5586. return buffer._data;
  5587. }
  5588. if (!buffer.uri) {
  5589. throw new Error(context + "/uri: Value is missing");
  5590. }
  5591. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  5592. return buffer._data;
  5593. };
  5594. /**
  5595. * Loads a glTF buffer view.
  5596. * @param context The context when loading the asset
  5597. * @param bufferView The glTF buffer view property
  5598. * @returns A promise that resolves with the loaded data when the load is complete
  5599. */
  5600. GLTFLoaderV2.prototype.loadBufferViewAsync = function (context, bufferView) {
  5601. if (bufferView._data) {
  5602. return bufferView._data;
  5603. }
  5604. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  5605. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  5606. try {
  5607. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  5608. }
  5609. catch (e) {
  5610. throw new Error(context + ": " + e.message);
  5611. }
  5612. });
  5613. return bufferView._data;
  5614. };
  5615. GLTFLoaderV2.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  5616. if (accessor.type !== "SCALAR" /* SCALAR */) {
  5617. throw new Error(context + "/type: Invalid value " + accessor.type);
  5618. }
  5619. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  5620. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  5621. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  5622. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  5623. }
  5624. if (accessor._data) {
  5625. return accessor._data;
  5626. }
  5627. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5628. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5629. return GLTFLoaderV2._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  5630. });
  5631. return accessor._data;
  5632. };
  5633. GLTFLoaderV2.prototype._loadFloatAccessorAsync = function (context, accessor) {
  5634. // TODO: support normalized and stride
  5635. var _this = this;
  5636. if (accessor.componentType !== 5126 /* FLOAT */) {
  5637. throw new Error("Invalid component type " + accessor.componentType);
  5638. }
  5639. if (accessor._data) {
  5640. return accessor._data;
  5641. }
  5642. var numComponents = GLTFLoaderV2._GetNumComponents(context, accessor.type);
  5643. var length = numComponents * accessor.count;
  5644. if (accessor.bufferView == undefined) {
  5645. accessor._data = Promise.resolve(new Float32Array(length));
  5646. }
  5647. else {
  5648. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5649. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5650. return GLTFLoaderV2._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  5651. });
  5652. }
  5653. if (accessor.sparse) {
  5654. var sparse_1 = accessor.sparse;
  5655. accessor._data = accessor._data.then(function (data) {
  5656. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  5657. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  5658. return Promise.all([
  5659. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  5660. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  5661. ]).then(function (_a) {
  5662. var indicesData = _a[0], valuesData = _a[1];
  5663. var indices = GLTFLoaderV2._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  5664. var values = GLTFLoaderV2._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  5665. var valuesIndex = 0;
  5666. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  5667. var dataIndex = indices[indicesIndex] * numComponents;
  5668. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  5669. data[dataIndex++] = values[valuesIndex++];
  5670. }
  5671. }
  5672. return data;
  5673. });
  5674. });
  5675. }
  5676. return accessor._data;
  5677. };
  5678. GLTFLoaderV2.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  5679. var _this = this;
  5680. if (bufferView._babylonBuffer) {
  5681. return bufferView._babylonBuffer;
  5682. }
  5683. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5684. return new babylonjs_1.Buffer(_this.babylonScene.getEngine(), data, false);
  5685. });
  5686. return bufferView._babylonBuffer;
  5687. };
  5688. GLTFLoaderV2.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  5689. var _this = this;
  5690. if (accessor._babylonVertexBuffer) {
  5691. return accessor._babylonVertexBuffer;
  5692. }
  5693. if (accessor.sparse) {
  5694. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5695. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  5696. });
  5697. }
  5698. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  5699. else if (accessor.byteOffset && accessor.byteOffset % babylonjs_1.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  5700. babylonjs_1.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  5701. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5702. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  5703. });
  5704. }
  5705. else {
  5706. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5707. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  5708. var size = GLTFLoaderV2._GetNumComponents(context, accessor.type);
  5709. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  5710. });
  5711. }
  5712. return accessor._babylonVertexBuffer;
  5713. };
  5714. GLTFLoaderV2.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  5715. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  5716. throw new Error(context + ": Material type not supported");
  5717. }
  5718. var promises = new Array();
  5719. if (properties) {
  5720. if (properties.baseColorFactor) {
  5721. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  5722. babylonMaterial.alpha = properties.baseColorFactor[3];
  5723. }
  5724. else {
  5725. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  5726. }
  5727. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  5728. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  5729. if (properties.baseColorTexture) {
  5730. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  5731. babylonMaterial.albedoTexture = texture;
  5732. }));
  5733. }
  5734. if (properties.metallicRoughnessTexture) {
  5735. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  5736. babylonMaterial.metallicTexture = texture;
  5737. }));
  5738. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  5739. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  5740. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  5741. }
  5742. }
  5743. return Promise.all(promises).then(function () { });
  5744. };
  5745. /** @hidden */
  5746. GLTFLoaderV2.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  5747. if (assign === void 0) { assign = function () { }; }
  5748. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  5749. if (extensionPromise) {
  5750. return extensionPromise;
  5751. }
  5752. material._babylonData = material._babylonData || {};
  5753. var babylonData = material._babylonData[babylonDrawMode];
  5754. if (!babylonData) {
  5755. this.logOpen(context + " " + (material.name || ""));
  5756. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  5757. babylonData = {
  5758. material: babylonMaterial,
  5759. meshes: [],
  5760. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  5761. };
  5762. material._babylonData[babylonDrawMode] = babylonData;
  5763. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5764. this.logClose();
  5765. }
  5766. babylonData.meshes.push(babylonMesh);
  5767. babylonMesh.onDisposeObservable.addOnce(function () {
  5768. var index = babylonData.meshes.indexOf(babylonMesh);
  5769. if (index !== -1) {
  5770. babylonData.meshes.splice(index, 1);
  5771. }
  5772. });
  5773. assign(babylonData.material);
  5774. return babylonData.promise.then(function () {
  5775. return babylonData.material;
  5776. });
  5777. };
  5778. GLTFLoaderV2.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  5779. var babylonMaterial = new babylonjs_1.PBRMaterial(name, this.babylonScene);
  5780. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? babylonjs_1.Material.CounterClockWiseSideOrientation : babylonjs_1.Material.ClockWiseSideOrientation;
  5781. babylonMaterial.fillMode = babylonDrawMode;
  5782. babylonMaterial.enableSpecularAntiAliasing = true;
  5783. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  5784. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  5785. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  5786. babylonMaterial.metallic = 1;
  5787. babylonMaterial.roughness = 1;
  5788. return babylonMaterial;
  5789. };
  5790. /**
  5791. * Creates a Babylon material from a glTF material.
  5792. * @param context The context when loading the asset
  5793. * @param material The glTF material property
  5794. * @param babylonDrawMode The draw mode for the Babylon material
  5795. * @returns The Babylon material
  5796. */
  5797. GLTFLoaderV2.prototype.createMaterial = function (context, material, babylonDrawMode) {
  5798. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  5799. if (extensionPromise) {
  5800. return extensionPromise;
  5801. }
  5802. var name = material.name || "material" + material.index;
  5803. return this._createDefaultMaterial(name, babylonDrawMode);
  5804. };
  5805. /**
  5806. * Loads properties from a glTF material into a Babylon material.
  5807. * @param context The context when loading the asset
  5808. * @param material The glTF material property
  5809. * @param babylonMaterial The Babylon material
  5810. * @returns A promise that resolves when the load is complete
  5811. */
  5812. GLTFLoaderV2.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5813. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  5814. if (extensionPromise) {
  5815. return extensionPromise;
  5816. }
  5817. var promises = new Array();
  5818. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  5819. if (material.pbrMetallicRoughness) {
  5820. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  5821. }
  5822. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  5823. return Promise.all(promises).then(function () { });
  5824. };
  5825. /**
  5826. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  5827. * @param context The context when loading the asset
  5828. * @param material The glTF material property
  5829. * @param babylonMaterial The Babylon material
  5830. * @returns A promise that resolves when the load is complete
  5831. */
  5832. GLTFLoaderV2.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  5833. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  5834. throw new Error(context + ": Material type not supported");
  5835. }
  5836. var promises = new Array();
  5837. babylonMaterial.emissiveColor = material.emissiveFactor ? babylonjs_1.Color3.FromArray(material.emissiveFactor) : new babylonjs_1.Color3(0, 0, 0);
  5838. if (material.doubleSided) {
  5839. babylonMaterial.backFaceCulling = false;
  5840. babylonMaterial.twoSidedLighting = true;
  5841. }
  5842. if (material.normalTexture) {
  5843. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  5844. babylonMaterial.bumpTexture = texture;
  5845. }));
  5846. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  5847. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  5848. if (material.normalTexture.scale != undefined) {
  5849. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  5850. }
  5851. }
  5852. if (material.occlusionTexture) {
  5853. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  5854. babylonMaterial.ambientTexture = texture;
  5855. }));
  5856. babylonMaterial.useAmbientInGrayScale = true;
  5857. if (material.occlusionTexture.strength != undefined) {
  5858. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  5859. }
  5860. }
  5861. if (material.emissiveTexture) {
  5862. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  5863. babylonMaterial.emissiveTexture = texture;
  5864. }));
  5865. }
  5866. return Promise.all(promises).then(function () { });
  5867. };
  5868. /**
  5869. * Loads the alpha properties from a glTF material into a Babylon material.
  5870. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  5871. * @param context The context when loading the asset
  5872. * @param material The glTF material property
  5873. * @param babylonMaterial The Babylon material
  5874. */
  5875. GLTFLoaderV2.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  5876. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  5877. throw new Error(context + ": Material type not supported");
  5878. }
  5879. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  5880. switch (alphaMode) {
  5881. case "OPAQUE" /* OPAQUE */: {
  5882. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  5883. break;
  5884. }
  5885. case "MASK" /* MASK */: {
  5886. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHATEST;
  5887. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  5888. if (babylonMaterial.albedoTexture) {
  5889. babylonMaterial.albedoTexture.hasAlpha = true;
  5890. }
  5891. break;
  5892. }
  5893. case "BLEND" /* BLEND */: {
  5894. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  5895. if (babylonMaterial.albedoTexture) {
  5896. babylonMaterial.albedoTexture.hasAlpha = true;
  5897. babylonMaterial.useAlphaFromAlbedoTexture = true;
  5898. }
  5899. break;
  5900. }
  5901. default: {
  5902. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  5903. }
  5904. }
  5905. };
  5906. /**
  5907. * Loads a glTF texture info.
  5908. * @param context The context when loading the asset
  5909. * @param textureInfo The glTF texture info property
  5910. * @param assign A function called synchronously after parsing the glTF properties
  5911. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  5912. */
  5913. GLTFLoaderV2.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  5914. if (assign === void 0) { assign = function () { }; }
  5915. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  5916. if (extensionPromise) {
  5917. return extensionPromise;
  5918. }
  5919. this.logOpen("" + context);
  5920. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  5921. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  5922. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  5923. assign(babylonTexture);
  5924. });
  5925. this.logClose();
  5926. return promise;
  5927. };
  5928. GLTFLoaderV2.prototype._loadTextureAsync = function (context, texture, assign) {
  5929. var _this = this;
  5930. if (assign === void 0) { assign = function () { }; }
  5931. var promises = new Array();
  5932. this.logOpen(context + " " + (texture.name || ""));
  5933. var sampler = (texture.sampler == undefined ? GLTFLoaderV2._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  5934. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  5935. var deferred = new babylonjs_1.Deferred();
  5936. var babylonTexture = new babylonjs_1.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  5937. if (!_this._disposed) {
  5938. deferred.resolve();
  5939. }
  5940. }, function (message, exception) {
  5941. if (!_this._disposed) {
  5942. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  5943. }
  5944. });
  5945. promises.push(deferred.promise);
  5946. babylonTexture.name = texture.name || "texture" + texture.index;
  5947. babylonTexture.wrapU = samplerData.wrapU;
  5948. babylonTexture.wrapV = samplerData.wrapV;
  5949. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  5950. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  5951. var name = image.uri || _this._fileName + "#image" + image.index;
  5952. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  5953. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  5954. }));
  5955. assign(babylonTexture);
  5956. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  5957. this.logClose();
  5958. return Promise.all(promises).then(function () {
  5959. return babylonTexture;
  5960. });
  5961. };
  5962. GLTFLoaderV2.prototype._loadSampler = function (context, sampler) {
  5963. if (!sampler._data) {
  5964. sampler._data = {
  5965. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  5966. samplingMode: GLTFLoaderV2._GetTextureSamplingMode(context, sampler),
  5967. wrapU: GLTFLoaderV2._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  5968. wrapV: GLTFLoaderV2._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  5969. };
  5970. }
  5971. return sampler._data;
  5972. };
  5973. /**
  5974. * Loads a glTF image.
  5975. * @param context The context when loading the asset
  5976. * @param image The glTF image property
  5977. * @returns A promise that resolves with the loaded data when the load is complete
  5978. */
  5979. GLTFLoaderV2.prototype.loadImageAsync = function (context, image) {
  5980. if (!image._data) {
  5981. this.logOpen(context + " " + (image.name || ""));
  5982. if (image.uri) {
  5983. image._data = this.loadUriAsync(context + "/uri", image.uri);
  5984. }
  5985. else {
  5986. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  5987. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  5988. }
  5989. this.logClose();
  5990. }
  5991. return image._data;
  5992. };
  5993. /**
  5994. * Loads a glTF uri.
  5995. * @param context The context when loading the asset
  5996. * @param uri The base64 or relative uri
  5997. * @returns A promise that resolves with the loaded data when the load is complete
  5998. */
  5999. GLTFLoaderV2.prototype.loadUriAsync = function (context, uri) {
  6000. var _this = this;
  6001. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  6002. if (extensionPromise) {
  6003. return extensionPromise;
  6004. }
  6005. if (!GLTFLoaderV2._ValidateUri(uri)) {
  6006. throw new Error(context + ": '" + uri + "' is invalid");
  6007. }
  6008. if (babylonjs_1.Tools.IsBase64(uri)) {
  6009. var data = new Uint8Array(babylonjs_1.Tools.DecodeBase64(uri));
  6010. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  6011. return Promise.resolve(data);
  6012. }
  6013. this.log("Loading " + uri);
  6014. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  6015. return new Promise(function (resolve, reject) {
  6016. if (!_this._disposed) {
  6017. var request_1 = babylonjs_1.Tools.LoadFile(url, function (fileData) {
  6018. if (!_this._disposed) {
  6019. var data = new Uint8Array(fileData);
  6020. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  6021. resolve(data);
  6022. }
  6023. }, function (event) {
  6024. if (!_this._disposed) {
  6025. if (request_1) {
  6026. request_1._lengthComputable = event.lengthComputable;
  6027. request_1._loaded = event.loaded;
  6028. request_1._total = event.total;
  6029. }
  6030. if (_this._state === glTFFileLoader_1.GLTFLoaderState.LOADING) {
  6031. try {
  6032. _this._onProgress();
  6033. }
  6034. catch (e) {
  6035. reject(e);
  6036. }
  6037. }
  6038. }
  6039. }, _this.babylonScene.offlineProvider, true, function (request, exception) {
  6040. if (!_this._disposed) {
  6041. reject(new babylonjs_1.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  6042. }
  6043. });
  6044. _this._requests.push(request_1);
  6045. }
  6046. });
  6047. });
  6048. };
  6049. GLTFLoaderV2.prototype._onProgress = function () {
  6050. if (!this._progressCallback) {
  6051. return;
  6052. }
  6053. var lengthComputable = true;
  6054. var loaded = 0;
  6055. var total = 0;
  6056. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  6057. var request = _a[_i];
  6058. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  6059. return;
  6060. }
  6061. lengthComputable = lengthComputable && request._lengthComputable;
  6062. loaded += request._loaded;
  6063. total += request._total;
  6064. }
  6065. this._progressCallback(new babylonjs_1.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  6066. };
  6067. GLTFLoaderV2._GetTextureWrapMode = function (context, mode) {
  6068. // Set defaults if undefined
  6069. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  6070. switch (mode) {
  6071. case 33071 /* CLAMP_TO_EDGE */: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  6072. case 33648 /* MIRRORED_REPEAT */: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  6073. case 10497 /* REPEAT */: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  6074. default:
  6075. babylonjs_1.Tools.Warn(context + ": Invalid value (" + mode + ")");
  6076. return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  6077. }
  6078. };
  6079. GLTFLoaderV2._GetTextureSamplingMode = function (context, sampler) {
  6080. // Set defaults if undefined
  6081. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  6082. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  6083. if (magFilter === 9729 /* LINEAR */) {
  6084. switch (minFilter) {
  6085. case 9728 /* NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST;
  6086. case 9729 /* LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR;
  6087. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPNEAREST;
  6088. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPNEAREST;
  6089. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPLINEAR;
  6090. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  6091. default:
  6092. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  6093. return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  6094. }
  6095. }
  6096. else {
  6097. if (magFilter !== 9728 /* NEAREST */) {
  6098. babylonjs_1.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  6099. }
  6100. switch (minFilter) {
  6101. case 9728 /* NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST;
  6102. case 9729 /* LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR;
  6103. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  6104. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPNEAREST;
  6105. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPLINEAR;
  6106. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPLINEAR;
  6107. default:
  6108. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  6109. return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  6110. }
  6111. }
  6112. };
  6113. GLTFLoaderV2._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  6114. var buffer = bufferView.buffer;
  6115. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  6116. try {
  6117. switch (componentType) {
  6118. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  6119. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  6120. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  6121. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  6122. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  6123. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  6124. default: throw new Error("Invalid component type " + componentType);
  6125. }
  6126. }
  6127. catch (e) {
  6128. throw new Error(context + ": " + e);
  6129. }
  6130. };
  6131. GLTFLoaderV2._GetNumComponents = function (context, type) {
  6132. switch (type) {
  6133. case "SCALAR": return 1;
  6134. case "VEC2": return 2;
  6135. case "VEC3": return 3;
  6136. case "VEC4": return 4;
  6137. case "MAT2": return 4;
  6138. case "MAT3": return 9;
  6139. case "MAT4": return 16;
  6140. }
  6141. throw new Error(context + ": Invalid type (" + type + ")");
  6142. };
  6143. GLTFLoaderV2._ValidateUri = function (uri) {
  6144. return (babylonjs_1.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  6145. };
  6146. GLTFLoaderV2._GetDrawMode = function (context, mode) {
  6147. if (mode == undefined) {
  6148. mode = 4 /* TRIANGLES */;
  6149. }
  6150. switch (mode) {
  6151. case 0 /* POINTS */: return babylonjs_1.Material.PointListDrawMode;
  6152. case 1 /* LINES */: return babylonjs_1.Material.LineListDrawMode;
  6153. case 2 /* LINE_LOOP */: return babylonjs_1.Material.LineLoopDrawMode;
  6154. case 3 /* LINE_STRIP */: return babylonjs_1.Material.LineStripDrawMode;
  6155. case 4 /* TRIANGLES */: return babylonjs_1.Material.TriangleFillMode;
  6156. case 5 /* TRIANGLE_STRIP */: return babylonjs_1.Material.TriangleStripDrawMode;
  6157. case 6 /* TRIANGLE_FAN */: return babylonjs_1.Material.TriangleFanDrawMode;
  6158. }
  6159. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  6160. };
  6161. GLTFLoaderV2.prototype._compileMaterialsAsync = function () {
  6162. var _this = this;
  6163. this._parent._startPerformanceCounter("Compile materials");
  6164. var promises = new Array();
  6165. if (this.gltf.materials) {
  6166. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  6167. var material = _a[_i];
  6168. if (material._babylonData) {
  6169. for (var babylonDrawMode in material._babylonData) {
  6170. var babylonData = material._babylonData[babylonDrawMode];
  6171. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  6172. var babylonMesh = _c[_b];
  6173. // Ensure nonUniformScaling is set if necessary.
  6174. babylonMesh.computeWorldMatrix(true);
  6175. var babylonMaterial = babylonData.material;
  6176. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  6177. if (this._parent.useClipPlane) {
  6178. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  6179. }
  6180. }
  6181. }
  6182. }
  6183. }
  6184. }
  6185. return Promise.all(promises).then(function () {
  6186. _this._parent._endPerformanceCounter("Compile materials");
  6187. });
  6188. };
  6189. GLTFLoaderV2.prototype._compileShadowGeneratorsAsync = function () {
  6190. var _this = this;
  6191. this._parent._startPerformanceCounter("Compile shadow generators");
  6192. var promises = new Array();
  6193. var lights = this.babylonScene.lights;
  6194. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  6195. var light = lights_1[_i];
  6196. var generator = light.getShadowGenerator();
  6197. if (generator) {
  6198. promises.push(generator.forceCompilationAsync());
  6199. }
  6200. }
  6201. return Promise.all(promises).then(function () {
  6202. _this._parent._endPerformanceCounter("Compile shadow generators");
  6203. });
  6204. };
  6205. GLTFLoaderV2.prototype._forEachExtensions = function (action) {
  6206. for (var _i = 0, _a = GLTFLoaderV2._ExtensionNames; _i < _a.length; _i++) {
  6207. var name_4 = _a[_i];
  6208. var extension = this._extensions[name_4];
  6209. if (extension.enabled) {
  6210. action(extension);
  6211. }
  6212. }
  6213. };
  6214. GLTFLoaderV2.prototype._applyExtensions = function (property, actionAsync) {
  6215. for (var _i = 0, _a = GLTFLoaderV2._ExtensionNames; _i < _a.length; _i++) {
  6216. var name_5 = _a[_i];
  6217. var extension = this._extensions[name_5];
  6218. if (extension.enabled) {
  6219. var loaderProperty = property;
  6220. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  6221. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  6222. if (!activeLoaderExtensions[name_5]) {
  6223. activeLoaderExtensions[name_5] = true;
  6224. try {
  6225. var result = actionAsync(extension);
  6226. if (result) {
  6227. return result;
  6228. }
  6229. }
  6230. finally {
  6231. delete activeLoaderExtensions[name_5];
  6232. }
  6233. }
  6234. }
  6235. }
  6236. return null;
  6237. };
  6238. GLTFLoaderV2.prototype._extensionsOnLoading = function () {
  6239. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  6240. };
  6241. GLTFLoaderV2.prototype._extensionsOnReady = function () {
  6242. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  6243. };
  6244. GLTFLoaderV2.prototype._extensionsLoadSceneAsync = function (context, scene) {
  6245. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  6246. };
  6247. GLTFLoaderV2.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  6248. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  6249. };
  6250. GLTFLoaderV2.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  6251. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  6252. };
  6253. GLTFLoaderV2.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  6254. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  6255. };
  6256. GLTFLoaderV2.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  6257. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  6258. };
  6259. GLTFLoaderV2.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  6260. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  6261. };
  6262. GLTFLoaderV2.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  6263. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  6264. };
  6265. GLTFLoaderV2.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  6266. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  6267. };
  6268. GLTFLoaderV2.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  6269. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  6270. };
  6271. GLTFLoaderV2.prototype._extensionsLoadUriAsync = function (context, uri) {
  6272. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  6273. };
  6274. /**
  6275. * Helper method called by a loader extension to load an glTF extension.
  6276. * @param context The context when loading the asset
  6277. * @param property The glTF property to load the extension from
  6278. * @param extensionName The name of the extension to load
  6279. * @param actionAsync The action to run
  6280. * @returns The promise returned by actionAsync or null if the extension does not exist
  6281. */
  6282. GLTFLoaderV2.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  6283. if (!property.extensions) {
  6284. return null;
  6285. }
  6286. var extensions = property.extensions;
  6287. var extension = extensions[extensionName];
  6288. if (!extension) {
  6289. return null;
  6290. }
  6291. return actionAsync(context + "/extensions/" + extensionName, extension);
  6292. };
  6293. /**
  6294. * Helper method called by a loader extension to load a glTF extra.
  6295. * @param context The context when loading the asset
  6296. * @param property The glTF property to load the extra from
  6297. * @param extensionName The name of the extension to load
  6298. * @param actionAsync The action to run
  6299. * @returns The promise returned by actionAsync or null if the extra does not exist
  6300. */
  6301. GLTFLoaderV2.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  6302. if (!property.extras) {
  6303. return null;
  6304. }
  6305. var extras = property.extras;
  6306. var extra = extras[extensionName];
  6307. if (!extra) {
  6308. return null;
  6309. }
  6310. return actionAsync(context + "/extras/" + extensionName, extra);
  6311. };
  6312. /**
  6313. * Increments the indentation level and logs a message.
  6314. * @param message The message to log
  6315. */
  6316. GLTFLoaderV2.prototype.logOpen = function (message) {
  6317. this._parent._logOpen(message);
  6318. };
  6319. /**
  6320. * Decrements the indentation level.
  6321. */
  6322. GLTFLoaderV2.prototype.logClose = function () {
  6323. this._parent._logClose();
  6324. };
  6325. /**
  6326. * Logs a message
  6327. * @param message The message to log
  6328. */
  6329. GLTFLoaderV2.prototype.log = function (message) {
  6330. this._parent._log(message);
  6331. };
  6332. /**
  6333. * Starts a performance counter.
  6334. * @param counterName The name of the performance counter
  6335. */
  6336. GLTFLoaderV2.prototype.startPerformanceCounter = function (counterName) {
  6337. this._parent._startPerformanceCounter(counterName);
  6338. };
  6339. /**
  6340. * Ends a performance counter.
  6341. * @param counterName The name of the performance counter
  6342. */
  6343. GLTFLoaderV2.prototype.endPerformanceCounter = function (counterName) {
  6344. this._parent._endPerformanceCounter(counterName);
  6345. };
  6346. GLTFLoaderV2._DefaultSampler = { index: -1 };
  6347. GLTFLoaderV2._ExtensionNames = new Array();
  6348. GLTFLoaderV2._ExtensionFactories = {};
  6349. return GLTFLoaderV2;
  6350. }());
  6351. exports.GLTFLoaderV2 = GLTFLoaderV2;
  6352. glTFFileLoader_1.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoaderV2(parent); };
  6353. /***/ }),
  6354. /***/ "./src/glTF/2.0/glTFLoaderExtension.ts":
  6355. /*!*********************************************!*\
  6356. !*** ./src/glTF/2.0/glTFLoaderExtension.ts ***!
  6357. \*********************************************/
  6358. /*! no static exports found */
  6359. /***/ (function(module, exports, __webpack_require__) {
  6360. "use strict";
  6361. Object.defineProperty(exports, "__esModule", { value: true });
  6362. exports.toto = 0;
  6363. /***/ }),
  6364. /***/ "./src/glTF/2.0/glTFLoaderInterfaces.ts":
  6365. /*!**********************************************!*\
  6366. !*** ./src/glTF/2.0/glTFLoaderInterfaces.ts ***!
  6367. \**********************************************/
  6368. /*! no static exports found */
  6369. /***/ (function(module, exports, __webpack_require__) {
  6370. "use strict";
  6371. Object.defineProperty(exports, "__esModule", { value: true });
  6372. exports.toto1 = 0;
  6373. /***/ }),
  6374. /***/ "./src/glTF/2.0/index.ts":
  6375. /*!*******************************!*\
  6376. !*** ./src/glTF/2.0/index.ts ***!
  6377. \*******************************/
  6378. /*! no static exports found */
  6379. /***/ (function(module, exports, __webpack_require__) {
  6380. "use strict";
  6381. function __export(m) {
  6382. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  6383. }
  6384. Object.defineProperty(exports, "__esModule", { value: true });
  6385. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/2.0/glTFLoader.ts"));
  6386. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/2.0/glTFLoaderExtension.ts"));
  6387. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/2.0/glTFLoaderInterfaces.ts"));
  6388. __export(__webpack_require__(/*! ./Extensions */ "./src/glTF/2.0/Extensions/index.ts"));
  6389. /***/ }),
  6390. /***/ "./src/glTF/glTFFileLoader.ts":
  6391. /*!************************************!*\
  6392. !*** ./src/glTF/glTFFileLoader.ts ***!
  6393. \************************************/
  6394. /*! no static exports found */
  6395. /***/ (function(module, exports, __webpack_require__) {
  6396. "use strict";
  6397. Object.defineProperty(exports, "__esModule", { value: true });
  6398. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  6399. /**
  6400. * Mode that determines the coordinate system to use.
  6401. */
  6402. var GLTFLoaderCoordinateSystemMode;
  6403. (function (GLTFLoaderCoordinateSystemMode) {
  6404. /**
  6405. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  6406. */
  6407. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  6408. /**
  6409. * Sets the useRightHandedSystem flag on the scene.
  6410. */
  6411. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  6412. })(GLTFLoaderCoordinateSystemMode = exports.GLTFLoaderCoordinateSystemMode || (exports.GLTFLoaderCoordinateSystemMode = {}));
  6413. /**
  6414. * Mode that determines what animations will start.
  6415. */
  6416. var GLTFLoaderAnimationStartMode;
  6417. (function (GLTFLoaderAnimationStartMode) {
  6418. /**
  6419. * No animation will start.
  6420. */
  6421. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  6422. /**
  6423. * The first animation will start.
  6424. */
  6425. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  6426. /**
  6427. * All animations will start.
  6428. */
  6429. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  6430. })(GLTFLoaderAnimationStartMode = exports.GLTFLoaderAnimationStartMode || (exports.GLTFLoaderAnimationStartMode = {}));
  6431. /**
  6432. * Loader state.
  6433. */
  6434. var GLTFLoaderState;
  6435. (function (GLTFLoaderState) {
  6436. /**
  6437. * The asset is loading.
  6438. */
  6439. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  6440. /**
  6441. * The asset is ready for rendering.
  6442. */
  6443. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  6444. /**
  6445. * The asset is completely loaded.
  6446. */
  6447. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  6448. })(GLTFLoaderState = exports.GLTFLoaderState || (exports.GLTFLoaderState = {}));
  6449. /**
  6450. * File loader for loading glTF files into a scene.
  6451. */
  6452. var GLTFFileLoader = /** @class */ (function () {
  6453. function GLTFFileLoader() {
  6454. // --------------
  6455. // Common options
  6456. // --------------
  6457. /**
  6458. * Raised when the asset has been parsed
  6459. */
  6460. this.onParsedObservable = new babylonjs_1.Observable();
  6461. // ----------
  6462. // V2 options
  6463. // ----------
  6464. /**
  6465. * The coordinate system mode. Defaults to AUTO.
  6466. */
  6467. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  6468. /**
  6469. * The animation start mode. Defaults to FIRST.
  6470. */
  6471. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  6472. /**
  6473. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  6474. */
  6475. this.compileMaterials = false;
  6476. /**
  6477. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  6478. */
  6479. this.useClipPlane = false;
  6480. /**
  6481. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  6482. */
  6483. this.compileShadowGenerators = false;
  6484. /**
  6485. * Defines if the Alpha blended materials are only applied as coverage.
  6486. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  6487. * If true, no extra effects are applied to transparent pixels.
  6488. */
  6489. this.transparencyAsCoverage = false;
  6490. /**
  6491. * Function called before loading a url referenced by the asset.
  6492. */
  6493. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  6494. /**
  6495. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  6496. */
  6497. this.onMeshLoadedObservable = new babylonjs_1.Observable();
  6498. /**
  6499. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  6500. */
  6501. this.onTextureLoadedObservable = new babylonjs_1.Observable();
  6502. /**
  6503. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  6504. */
  6505. this.onMaterialLoadedObservable = new babylonjs_1.Observable();
  6506. /**
  6507. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  6508. */
  6509. this.onCameraLoadedObservable = new babylonjs_1.Observable();
  6510. /**
  6511. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  6512. * For assets with LODs, raised when all of the LODs are complete.
  6513. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  6514. */
  6515. this.onCompleteObservable = new babylonjs_1.Observable();
  6516. /**
  6517. * Observable raised when an error occurs.
  6518. */
  6519. this.onErrorObservable = new babylonjs_1.Observable();
  6520. /**
  6521. * Observable raised after the loader is disposed.
  6522. */
  6523. this.onDisposeObservable = new babylonjs_1.Observable();
  6524. /**
  6525. * Observable raised after a loader extension is created.
  6526. * Set additional options for a loader extension in this event.
  6527. */
  6528. this.onExtensionLoadedObservable = new babylonjs_1.Observable();
  6529. /**
  6530. * Defines if the loader should validate the asset.
  6531. */
  6532. this.validate = false;
  6533. /**
  6534. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  6535. */
  6536. this.onValidatedObservable = new babylonjs_1.Observable();
  6537. this._loader = null;
  6538. /**
  6539. * Name of the loader ("gltf")
  6540. */
  6541. this.name = "gltf";
  6542. /**
  6543. * Supported file extensions of the loader (.gltf, .glb)
  6544. */
  6545. this.extensions = {
  6546. ".gltf": { isBinary: false },
  6547. ".glb": { isBinary: true }
  6548. };
  6549. this._logIndentLevel = 0;
  6550. this._loggingEnabled = false;
  6551. /** @hidden */
  6552. this._log = this._logDisabled;
  6553. this._capturePerformanceCounters = false;
  6554. /** @hidden */
  6555. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  6556. /** @hidden */
  6557. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  6558. }
  6559. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  6560. /**
  6561. * Raised when the asset has been parsed
  6562. */
  6563. set: function (callback) {
  6564. if (this._onParsedObserver) {
  6565. this.onParsedObservable.remove(this._onParsedObserver);
  6566. }
  6567. this._onParsedObserver = this.onParsedObservable.add(callback);
  6568. },
  6569. enumerable: true,
  6570. configurable: true
  6571. });
  6572. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  6573. /**
  6574. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  6575. */
  6576. set: function (callback) {
  6577. if (this._onMeshLoadedObserver) {
  6578. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  6579. }
  6580. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  6581. },
  6582. enumerable: true,
  6583. configurable: true
  6584. });
  6585. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  6586. /**
  6587. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  6588. */
  6589. set: function (callback) {
  6590. if (this._onTextureLoadedObserver) {
  6591. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  6592. }
  6593. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  6594. },
  6595. enumerable: true,
  6596. configurable: true
  6597. });
  6598. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  6599. /**
  6600. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  6601. */
  6602. set: function (callback) {
  6603. if (this._onMaterialLoadedObserver) {
  6604. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  6605. }
  6606. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  6607. },
  6608. enumerable: true,
  6609. configurable: true
  6610. });
  6611. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  6612. /**
  6613. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  6614. */
  6615. set: function (callback) {
  6616. if (this._onCameraLoadedObserver) {
  6617. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  6618. }
  6619. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  6620. },
  6621. enumerable: true,
  6622. configurable: true
  6623. });
  6624. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  6625. /**
  6626. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  6627. * For assets with LODs, raised when all of the LODs are complete.
  6628. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  6629. */
  6630. set: function (callback) {
  6631. if (this._onCompleteObserver) {
  6632. this.onCompleteObservable.remove(this._onCompleteObserver);
  6633. }
  6634. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  6635. },
  6636. enumerable: true,
  6637. configurable: true
  6638. });
  6639. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  6640. /**
  6641. * Callback raised when an error occurs.
  6642. */
  6643. set: function (callback) {
  6644. if (this._onErrorObserver) {
  6645. this.onErrorObservable.remove(this._onErrorObserver);
  6646. }
  6647. this._onErrorObserver = this.onErrorObservable.add(callback);
  6648. },
  6649. enumerable: true,
  6650. configurable: true
  6651. });
  6652. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  6653. /**
  6654. * Callback raised after the loader is disposed.
  6655. */
  6656. set: function (callback) {
  6657. if (this._onDisposeObserver) {
  6658. this.onDisposeObservable.remove(this._onDisposeObserver);
  6659. }
  6660. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  6661. },
  6662. enumerable: true,
  6663. configurable: true
  6664. });
  6665. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  6666. /**
  6667. * Callback raised after a loader extension is created.
  6668. */
  6669. set: function (callback) {
  6670. if (this._onExtensionLoadedObserver) {
  6671. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  6672. }
  6673. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  6674. },
  6675. enumerable: true,
  6676. configurable: true
  6677. });
  6678. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  6679. /**
  6680. * Defines if the loader logging is enabled.
  6681. */
  6682. get: function () {
  6683. return this._loggingEnabled;
  6684. },
  6685. set: function (value) {
  6686. if (this._loggingEnabled === value) {
  6687. return;
  6688. }
  6689. this._loggingEnabled = value;
  6690. if (this._loggingEnabled) {
  6691. this._log = this._logEnabled;
  6692. }
  6693. else {
  6694. this._log = this._logDisabled;
  6695. }
  6696. },
  6697. enumerable: true,
  6698. configurable: true
  6699. });
  6700. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  6701. /**
  6702. * Defines if the loader should capture performance counters.
  6703. */
  6704. get: function () {
  6705. return this._capturePerformanceCounters;
  6706. },
  6707. set: function (value) {
  6708. if (this._capturePerformanceCounters === value) {
  6709. return;
  6710. }
  6711. this._capturePerformanceCounters = value;
  6712. if (this._capturePerformanceCounters) {
  6713. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  6714. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  6715. }
  6716. else {
  6717. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  6718. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  6719. }
  6720. },
  6721. enumerable: true,
  6722. configurable: true
  6723. });
  6724. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  6725. /**
  6726. * Callback raised after a loader extension is created.
  6727. */
  6728. set: function (callback) {
  6729. if (this._onValidatedObserver) {
  6730. this.onValidatedObservable.remove(this._onValidatedObserver);
  6731. }
  6732. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  6733. },
  6734. enumerable: true,
  6735. configurable: true
  6736. });
  6737. /**
  6738. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  6739. */
  6740. GLTFFileLoader.prototype.dispose = function () {
  6741. if (this._loader) {
  6742. this._loader.dispose();
  6743. this._loader = null;
  6744. }
  6745. this._clear();
  6746. this.onDisposeObservable.notifyObservers(undefined);
  6747. this.onDisposeObservable.clear();
  6748. };
  6749. /** @hidden */
  6750. GLTFFileLoader.prototype._clear = function () {
  6751. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  6752. this.onMeshLoadedObservable.clear();
  6753. this.onTextureLoadedObservable.clear();
  6754. this.onMaterialLoadedObservable.clear();
  6755. this.onCameraLoadedObservable.clear();
  6756. this.onCompleteObservable.clear();
  6757. this.onExtensionLoadedObservable.clear();
  6758. };
  6759. /**
  6760. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  6761. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  6762. * @param scene the scene the meshes should be added to
  6763. * @param data the glTF data to load
  6764. * @param rootUrl root url to load from
  6765. * @param onProgress event that fires when loading progress has occured
  6766. * @param fileName Defines the name of the file to load
  6767. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  6768. */
  6769. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  6770. var _this = this;
  6771. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  6772. _this._log("Loading " + (fileName || ""));
  6773. _this._loader = _this._getLoader(loaderData);
  6774. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  6775. });
  6776. };
  6777. /**
  6778. * Imports all objects from the loaded glTF data and adds them to the scene
  6779. * @param scene the scene the objects should be added to
  6780. * @param data the glTF data to load
  6781. * @param rootUrl root url to load from
  6782. * @param onProgress event that fires when loading progress has occured
  6783. * @param fileName Defines the name of the file to load
  6784. * @returns a promise which completes when objects have been loaded to the scene
  6785. */
  6786. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  6787. var _this = this;
  6788. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  6789. _this._log("Loading " + (fileName || ""));
  6790. _this._loader = _this._getLoader(loaderData);
  6791. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  6792. });
  6793. };
  6794. /**
  6795. * Load into an asset container.
  6796. * @param scene The scene to load into
  6797. * @param data The data to import
  6798. * @param rootUrl The root url for scene and resources
  6799. * @param onProgress The callback when the load progresses
  6800. * @param fileName Defines the name of the file to load
  6801. * @returns The loaded asset container
  6802. */
  6803. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  6804. var _this = this;
  6805. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  6806. _this._log("Loading " + (fileName || ""));
  6807. _this._loader = _this._getLoader(loaderData);
  6808. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  6809. var container = new babylonjs_1.AssetContainer(scene);
  6810. Array.prototype.push.apply(container.meshes, result.meshes);
  6811. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  6812. Array.prototype.push.apply(container.skeletons, result.skeletons);
  6813. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  6814. container.removeAllFromScene();
  6815. return container;
  6816. });
  6817. });
  6818. };
  6819. /**
  6820. * If the data string can be loaded directly.
  6821. * @param data string contianing the file data
  6822. * @returns if the data can be loaded directly
  6823. */
  6824. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  6825. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  6826. };
  6827. /**
  6828. * Instantiates a glTF file loader plugin.
  6829. * @returns the created plugin
  6830. */
  6831. GLTFFileLoader.prototype.createPlugin = function () {
  6832. return new GLTFFileLoader();
  6833. };
  6834. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  6835. /**
  6836. * The loader state or null if the loader is not active.
  6837. */
  6838. get: function () {
  6839. return this._loader ? this._loader.state : null;
  6840. },
  6841. enumerable: true,
  6842. configurable: true
  6843. });
  6844. /**
  6845. * Returns a promise that resolves when the asset is completely loaded.
  6846. * @returns a promise that resolves when the asset is completely loaded.
  6847. */
  6848. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  6849. var _this = this;
  6850. return new Promise(function (resolve, reject) {
  6851. _this.onCompleteObservable.addOnce(function () {
  6852. resolve();
  6853. });
  6854. _this.onErrorObservable.addOnce(function (reason) {
  6855. reject(reason);
  6856. });
  6857. });
  6858. };
  6859. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  6860. var _this = this;
  6861. return Promise.resolve().then(function () {
  6862. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  6863. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  6864. _this._startPerformanceCounter("Parse JSON");
  6865. _this._log("JSON length: " + unpacked.json.length);
  6866. var loaderData = {
  6867. json: JSON.parse(unpacked.json),
  6868. bin: unpacked.bin
  6869. };
  6870. _this._endPerformanceCounter("Parse JSON");
  6871. _this.onParsedObservable.notifyObservers(loaderData);
  6872. _this.onParsedObservable.clear();
  6873. return loaderData;
  6874. });
  6875. });
  6876. };
  6877. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  6878. var _this = this;
  6879. if (!this.validate || typeof GLTFValidator === "undefined") {
  6880. return Promise.resolve();
  6881. }
  6882. this._startPerformanceCounter("Validate JSON");
  6883. var options = {
  6884. externalResourceFunction: function (uri) {
  6885. return _this.preprocessUrlAsync(rootUrl + uri)
  6886. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  6887. .then(function (data) { return new Uint8Array(data); });
  6888. }
  6889. };
  6890. if (fileName && fileName.substr(0, 5) !== "data:") {
  6891. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  6892. }
  6893. return GLTFValidator.validateString(json, options).then(function (result) {
  6894. _this._endPerformanceCounter("Validate JSON");
  6895. _this.onValidatedObservable.notifyObservers(result);
  6896. _this.onValidatedObservable.clear();
  6897. });
  6898. };
  6899. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  6900. var asset = loaderData.json.asset || {};
  6901. this._log("Asset version: " + asset.version);
  6902. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  6903. asset.generator && this._log("Asset generator: " + asset.generator);
  6904. var version = GLTFFileLoader._parseVersion(asset.version);
  6905. if (!version) {
  6906. throw new Error("Invalid version: " + asset.version);
  6907. }
  6908. if (asset.minVersion !== undefined) {
  6909. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  6910. if (!minVersion) {
  6911. throw new Error("Invalid minimum version: " + asset.minVersion);
  6912. }
  6913. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  6914. throw new Error("Incompatible minimum version: " + asset.minVersion);
  6915. }
  6916. }
  6917. var createLoaders = {
  6918. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  6919. 2: GLTFFileLoader._CreateGLTFLoaderV2
  6920. };
  6921. var createLoader = createLoaders[version.major];
  6922. if (!createLoader) {
  6923. throw new Error("Unsupported version: " + asset.version);
  6924. }
  6925. return createLoader(this);
  6926. };
  6927. GLTFFileLoader.prototype._unpackBinary = function (data) {
  6928. this._startPerformanceCounter("Unpack binary");
  6929. this._log("Binary length: " + data.byteLength);
  6930. var Binary = {
  6931. Magic: 0x46546C67
  6932. };
  6933. var binaryReader = new BinaryReader(data);
  6934. var magic = binaryReader.readUint32();
  6935. if (magic !== Binary.Magic) {
  6936. throw new Error("Unexpected magic: " + magic);
  6937. }
  6938. var version = binaryReader.readUint32();
  6939. if (this.loggingEnabled) {
  6940. this._log("Binary version: " + version);
  6941. }
  6942. var unpacked;
  6943. switch (version) {
  6944. case 1: {
  6945. unpacked = this._unpackBinaryV1(binaryReader);
  6946. break;
  6947. }
  6948. case 2: {
  6949. unpacked = this._unpackBinaryV2(binaryReader);
  6950. break;
  6951. }
  6952. default: {
  6953. throw new Error("Unsupported version: " + version);
  6954. }
  6955. }
  6956. this._endPerformanceCounter("Unpack binary");
  6957. return unpacked;
  6958. };
  6959. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  6960. var ContentFormat = {
  6961. JSON: 0
  6962. };
  6963. var length = binaryReader.readUint32();
  6964. if (length != binaryReader.getLength()) {
  6965. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  6966. }
  6967. var contentLength = binaryReader.readUint32();
  6968. var contentFormat = binaryReader.readUint32();
  6969. var content;
  6970. switch (contentFormat) {
  6971. case ContentFormat.JSON: {
  6972. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  6973. break;
  6974. }
  6975. default: {
  6976. throw new Error("Unexpected content format: " + contentFormat);
  6977. }
  6978. }
  6979. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  6980. var body = binaryReader.readUint8Array(bytesRemaining);
  6981. return {
  6982. json: content,
  6983. bin: body
  6984. };
  6985. };
  6986. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  6987. var ChunkFormat = {
  6988. JSON: 0x4E4F534A,
  6989. BIN: 0x004E4942
  6990. };
  6991. var length = binaryReader.readUint32();
  6992. if (length !== binaryReader.getLength()) {
  6993. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  6994. }
  6995. // JSON chunk
  6996. var chunkLength = binaryReader.readUint32();
  6997. var chunkFormat = binaryReader.readUint32();
  6998. if (chunkFormat !== ChunkFormat.JSON) {
  6999. throw new Error("First chunk format is not JSON");
  7000. }
  7001. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  7002. // Look for BIN chunk
  7003. var bin = null;
  7004. while (binaryReader.getPosition() < binaryReader.getLength()) {
  7005. var chunkLength_1 = binaryReader.readUint32();
  7006. var chunkFormat_1 = binaryReader.readUint32();
  7007. switch (chunkFormat_1) {
  7008. case ChunkFormat.JSON: {
  7009. throw new Error("Unexpected JSON chunk");
  7010. }
  7011. case ChunkFormat.BIN: {
  7012. bin = binaryReader.readUint8Array(chunkLength_1);
  7013. break;
  7014. }
  7015. default: {
  7016. // ignore unrecognized chunkFormat
  7017. binaryReader.skipBytes(chunkLength_1);
  7018. break;
  7019. }
  7020. }
  7021. }
  7022. return {
  7023. json: json,
  7024. bin: bin
  7025. };
  7026. };
  7027. GLTFFileLoader._parseVersion = function (version) {
  7028. if (version === "1.0" || version === "1.0.1") {
  7029. return {
  7030. major: 1,
  7031. minor: 0
  7032. };
  7033. }
  7034. var match = (version + "").match(/^(\d+)\.(\d+)/);
  7035. if (!match) {
  7036. return null;
  7037. }
  7038. return {
  7039. major: parseInt(match[1]),
  7040. minor: parseInt(match[2])
  7041. };
  7042. };
  7043. GLTFFileLoader._compareVersion = function (a, b) {
  7044. if (a.major > b.major) {
  7045. return 1;
  7046. }
  7047. if (a.major < b.major) {
  7048. return -1;
  7049. }
  7050. if (a.minor > b.minor) {
  7051. return 1;
  7052. }
  7053. if (a.minor < b.minor) {
  7054. return -1;
  7055. }
  7056. return 0;
  7057. };
  7058. GLTFFileLoader._decodeBufferToText = function (buffer) {
  7059. var result = "";
  7060. var length = buffer.byteLength;
  7061. for (var i = 0; i < length; i++) {
  7062. result += String.fromCharCode(buffer[i]);
  7063. }
  7064. return result;
  7065. };
  7066. /** @hidden */
  7067. GLTFFileLoader.prototype._logOpen = function (message) {
  7068. this._log(message);
  7069. this._logIndentLevel++;
  7070. };
  7071. /** @hidden */
  7072. GLTFFileLoader.prototype._logClose = function () {
  7073. --this._logIndentLevel;
  7074. };
  7075. GLTFFileLoader.prototype._logEnabled = function (message) {
  7076. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  7077. babylonjs_1.Tools.Log("" + spaces + message);
  7078. };
  7079. GLTFFileLoader.prototype._logDisabled = function (message) {
  7080. };
  7081. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  7082. babylonjs_1.Tools.StartPerformanceCounter(counterName);
  7083. };
  7084. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  7085. };
  7086. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  7087. babylonjs_1.Tools.EndPerformanceCounter(counterName);
  7088. };
  7089. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  7090. };
  7091. // ----------
  7092. // V1 options
  7093. // ----------
  7094. /**
  7095. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  7096. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  7097. * Defaults to true.
  7098. * @hidden
  7099. */
  7100. GLTFFileLoader.IncrementalLoading = true;
  7101. /**
  7102. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  7103. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  7104. * @hidden
  7105. */
  7106. GLTFFileLoader.HomogeneousCoordinates = false;
  7107. GLTFFileLoader._logSpaces = " ";
  7108. return GLTFFileLoader;
  7109. }());
  7110. exports.GLTFFileLoader = GLTFFileLoader;
  7111. var BinaryReader = /** @class */ (function () {
  7112. function BinaryReader(arrayBuffer) {
  7113. this._arrayBuffer = arrayBuffer;
  7114. this._dataView = new DataView(arrayBuffer);
  7115. this._byteOffset = 0;
  7116. }
  7117. BinaryReader.prototype.getPosition = function () {
  7118. return this._byteOffset;
  7119. };
  7120. BinaryReader.prototype.getLength = function () {
  7121. return this._arrayBuffer.byteLength;
  7122. };
  7123. BinaryReader.prototype.readUint32 = function () {
  7124. var value = this._dataView.getUint32(this._byteOffset, true);
  7125. this._byteOffset += 4;
  7126. return value;
  7127. };
  7128. BinaryReader.prototype.readUint8Array = function (length) {
  7129. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  7130. this._byteOffset += length;
  7131. return value;
  7132. };
  7133. BinaryReader.prototype.skipBytes = function (length) {
  7134. this._byteOffset += length;
  7135. };
  7136. return BinaryReader;
  7137. }());
  7138. if (babylonjs_1.SceneLoader) {
  7139. babylonjs_1.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  7140. }
  7141. /***/ }),
  7142. /***/ "./src/glTF/index.ts":
  7143. /*!***************************!*\
  7144. !*** ./src/glTF/index.ts ***!
  7145. \***************************/
  7146. /*! no static exports found */
  7147. /***/ (function(module, exports, __webpack_require__) {
  7148. "use strict";
  7149. function __export(m) {
  7150. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  7151. }
  7152. Object.defineProperty(exports, "__esModule", { value: true });
  7153. __export(__webpack_require__(/*! ./glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  7154. __export(__webpack_require__(/*! ./1.0 */ "./src/glTF/1.0/index.ts"));
  7155. __export(__webpack_require__(/*! ./2.0 */ "./src/glTF/2.0/index.ts"));
  7156. /***/ }),
  7157. /***/ "./src/index.ts":
  7158. /*!**********************!*\
  7159. !*** ./src/index.ts ***!
  7160. \**********************/
  7161. /*! no static exports found */
  7162. /***/ (function(module, exports, __webpack_require__) {
  7163. "use strict";
  7164. function __export(m) {
  7165. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  7166. }
  7167. Object.defineProperty(exports, "__esModule", { value: true });
  7168. __export(__webpack_require__(/*! ./glTF */ "./src/glTF/index.ts"));
  7169. __export(__webpack_require__(/*! ./OBJ */ "./src/OBJ/index.ts"));
  7170. __export(__webpack_require__(/*! ./STL */ "./src/STL/index.ts"));
  7171. /***/ }),
  7172. /***/ "./src/legacy.ts":
  7173. /*!***********************!*\
  7174. !*** ./src/legacy.ts ***!
  7175. \***********************/
  7176. /*! no static exports found */
  7177. /***/ (function(module, exports, __webpack_require__) {
  7178. "use strict";
  7179. /* WEBPACK VAR INJECTION */(function(global) {
  7180. function __export(m) {
  7181. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  7182. }
  7183. Object.defineProperty(exports, "__esModule", { value: true });
  7184. var Loaders = __webpack_require__(/*! ./index */ "./src/index.ts");
  7185. /**
  7186. * Legacy support, defining window.BABYLON.OBJLoader... (global variable).
  7187. *
  7188. * This is the entry point for the UMD module.
  7189. * The entry point for a future ESM package should be index.ts
  7190. */
  7191. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  7192. if (typeof globalObject !== "undefined") {
  7193. globalObject.BABYLON = globalObject.BABYLON || {};
  7194. for (var loader in Loaders) {
  7195. if (Loaders.hasOwnProperty(loader)) {
  7196. globalObject.BABYLON[loader] = Loaders[loader];
  7197. }
  7198. }
  7199. }
  7200. __export(__webpack_require__(/*! ./index */ "./src/index.ts"));
  7201. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  7202. /***/ }),
  7203. /***/ "babylonjs":
  7204. /*!****************************************************************************************************!*\
  7205. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  7206. \****************************************************************************************************/
  7207. /*! no static exports found */
  7208. /***/ (function(module, exports) {
  7209. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs__;
  7210. /***/ })
  7211. /******/ });
  7212. });
  7213. //# sourceMappingURL=babylonjs.loaders.js.map