index.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887
  1. var kr=Object.defineProperty,Ur=Object.defineProperties;var Gr=Object.getOwnPropertyDescriptors;var vr=Object.getOwnPropertySymbols;var Dr=Object.prototype.hasOwnProperty,Fr=Object.prototype.propertyIsEnumerable;var br=(a,i,e)=>i in a?kr(a,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[i]=e,Kt=(a,i)=>{for(var e in i||(i={}))Dr.call(i,e)&&br(a,e,i[e]);if(vr)for(var e of vr(i))Fr.call(i,e)&&br(a,e,i[e]);return a},qt=(a,i)=>Ur(a,Gr(i));var wr=(a,i)=>{var e={};for(var o in a)Dr.call(a,o)&&i.indexOf(o)<0&&(e[o]=a[o]);if(a!=null&&vr)for(var o of vr(a))i.indexOf(o)<0&&Fr.call(a,o)&&(e[o]=a[o]);return e};var ct=(a,i,e)=>(br(a,typeof i!="symbol"?i+"":i,e),e);function _mergeNamespaces(a,i){return i.forEach(function(e){e&&typeof e!="string"&&!Array.isArray(e)&&Object.keys(e).forEach(function(o){if(o!=="default"&&!(o in a)){var s=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(a,o,s.get?s:{enumerable:!0,get:function(){return e[o]}})}})}),Object.freeze(Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}))}const p$2=function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const c of s)if(c.type==="childList")for(const d of c.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&o(d)}).observe(document,{childList:!0,subtree:!0});function e(s){const c={};return s.integrity&&(c.integrity=s.integrity),s.referrerpolicy&&(c.referrerPolicy=s.referrerpolicy),s.crossorigin==="use-credentials"?c.credentials="include":s.crossorigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function o(s){if(s.ep)return;s.ep=!0;const c=e(s);fetch(s.href,c)}};p$2();var commonjsGlobal=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function commonjsRequire(a){throw new Error('Could not dynamically require "'+a+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var react={exports:{}},react_production_min={};/*
  2. object-assign
  3. (c) Sindre Sorhus
  4. @license MIT
  5. */var getOwnPropertySymbols=Object.getOwnPropertySymbols,hasOwnProperty=Object.prototype.hasOwnProperty,propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(a){if(a==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(a)}function shouldUseNative(){try{if(!Object.assign)return!1;var a=new String("abc");if(a[5]="de",Object.getOwnPropertyNames(a)[0]==="5")return!1;for(var i={},e=0;e<10;e++)i["_"+String.fromCharCode(e)]=e;var o=Object.getOwnPropertyNames(i).map(function(c){return i[c]});if(o.join("")!=="0123456789")return!1;var s={};return"abcdefghijklmnopqrst".split("").forEach(function(c){s[c]=c}),Object.keys(Object.assign({},s)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}var objectAssign=shouldUseNative()?Object.assign:function(a,i){for(var e,o=toObject(a),s,c=1;c<arguments.length;c++){e=Object(arguments[c]);for(var d in e)hasOwnProperty.call(e,d)&&(o[d]=e[d]);if(getOwnPropertySymbols){s=getOwnPropertySymbols(e);for(var _=0;_<s.length;_++)propIsEnumerable.call(e,s[_])&&(o[s[_]]=e[s[_]])}}return o};/** @license React v17.0.2
  6. * react.production.min.js
  7. *
  8. * Copyright (c) Facebook, Inc. and its affiliates.
  9. *
  10. * This source code is licensed under the MIT license found in the
  11. * LICENSE file in the root directory of this source tree.
  12. */var l=objectAssign,n$1=60103,p$1=60106;react_production_min.Fragment=60107;react_production_min.StrictMode=60108;react_production_min.Profiler=60114;var q$1=60109,r$1=60110,t=60112;react_production_min.Suspense=60113;var u=60115,v=60116;if(typeof Symbol=="function"&&Symbol.for){var w=Symbol.for;n$1=w("react.element"),p$1=w("react.portal"),react_production_min.Fragment=w("react.fragment"),react_production_min.StrictMode=w("react.strict_mode"),react_production_min.Profiler=w("react.profiler"),q$1=w("react.provider"),r$1=w("react.context"),t=w("react.forward_ref"),react_production_min.Suspense=w("react.suspense"),u=w("react.memo"),v=w("react.lazy")}var x=typeof Symbol=="function"&&Symbol.iterator;function y$1(a){return a===null||typeof a!="object"?null:(a=x&&a[x]||a["@@iterator"],typeof a=="function"?a:null)}function z(a){for(var i="https://reactjs.org/docs/error-decoder.html?invariant="+a,e=1;e<arguments.length;e++)i+="&args[]="+encodeURIComponent(arguments[e]);return"Minified React error #"+a+"; visit "+i+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var A={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B$1={};function C(a,i,e){this.props=a,this.context=i,this.refs=B$1,this.updater=e||A}C.prototype.isReactComponent={};C.prototype.setState=function(a,i){if(typeof a!="object"&&typeof a!="function"&&a!=null)throw Error(z(85));this.updater.enqueueSetState(this,a,i,"setState")};C.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};function D$1(){}D$1.prototype=C.prototype;function E$1(a,i,e){this.props=a,this.context=i,this.refs=B$1,this.updater=e||A}var F$1=E$1.prototype=new D$1;F$1.constructor=E$1;l(F$1,C.prototype);F$1.isPureReactComponent=!0;var G$1={current:null},H$1=Object.prototype.hasOwnProperty,I$1={key:!0,ref:!0,__self:!0,__source:!0};function J(a,i,e){var o,s={},c=null,d=null;if(i!=null)for(o in i.ref!==void 0&&(d=i.ref),i.key!==void 0&&(c=""+i.key),i)H$1.call(i,o)&&!I$1.hasOwnProperty(o)&&(s[o]=i[o]);var _=arguments.length-2;if(_===1)s.children=e;else if(1<_){for(var b=Array(_),k=0;k<_;k++)b[k]=arguments[k+2];s.children=b}if(a&&a.defaultProps)for(o in _=a.defaultProps,_)s[o]===void 0&&(s[o]=_[o]);return{$$typeof:n$1,type:a,key:c,ref:d,props:s,_owner:G$1.current}}function K(a,i){return{$$typeof:n$1,type:a.type,key:i,ref:a.ref,props:a.props,_owner:a._owner}}function L(a){return typeof a=="object"&&a!==null&&a.$$typeof===n$1}function escape$1(a){var i={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(e){return i[e]})}var M$1=/\/+/g;function N$1(a,i){return typeof a=="object"&&a!==null&&a.key!=null?escape$1(""+a.key):i.toString(36)}function O$1(a,i,e,o,s){var c=typeof a;(c==="undefined"||c==="boolean")&&(a=null);var d=!1;if(a===null)d=!0;else switch(c){case"string":case"number":d=!0;break;case"object":switch(a.$$typeof){case n$1:case p$1:d=!0}}if(d)return d=a,s=s(d),a=o===""?"."+N$1(d,0):o,Array.isArray(s)?(e="",a!=null&&(e=a.replace(M$1,"$&/")+"/"),O$1(s,i,e,"",function(k){return k})):s!=null&&(L(s)&&(s=K(s,e+(!s.key||d&&d.key===s.key?"":(""+s.key).replace(M$1,"$&/")+"/")+a)),i.push(s)),1;if(d=0,o=o===""?".":o+":",Array.isArray(a))for(var _=0;_<a.length;_++){c=a[_];var b=o+N$1(c,_);d+=O$1(c,i,e,b,s)}else if(b=y$1(a),typeof b=="function")for(a=b.call(a),_=0;!(c=a.next()).done;)c=c.value,b=o+N$1(c,_++),d+=O$1(c,i,e,b,s);else if(c==="object")throw i=""+a,Error(z(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i));return d}function P$1(a,i,e){if(a==null)return a;var o=[],s=0;return O$1(a,o,"","",function(c){return i.call(e,c,s++)}),o}function Q(a){if(a._status===-1){var i=a._result;i=i(),a._status=0,a._result=i,i.then(function(e){a._status===0&&(e=e.default,a._status=1,a._result=e)},function(e){a._status===0&&(a._status=2,a._result=e)})}if(a._status===1)return a._result;throw a._result}var R$1={current:null};function S$1(){var a=R$1.current;if(a===null)throw Error(z(321));return a}var T$1={ReactCurrentDispatcher:R$1,ReactCurrentBatchConfig:{transition:0},ReactCurrentOwner:G$1,IsSomeRendererActing:{current:!1},assign:l};react_production_min.Children={map:P$1,forEach:function(a,i,e){P$1(a,function(){i.apply(this,arguments)},e)},count:function(a){var i=0;return P$1(a,function(){i++}),i},toArray:function(a){return P$1(a,function(i){return i})||[]},only:function(a){if(!L(a))throw Error(z(143));return a}};react_production_min.Component=C;react_production_min.PureComponent=E$1;react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=T$1;react_production_min.cloneElement=function(a,i,e){if(a==null)throw Error(z(267,a));var o=l({},a.props),s=a.key,c=a.ref,d=a._owner;if(i!=null){if(i.ref!==void 0&&(c=i.ref,d=G$1.current),i.key!==void 0&&(s=""+i.key),a.type&&a.type.defaultProps)var _=a.type.defaultProps;for(b in i)H$1.call(i,b)&&!I$1.hasOwnProperty(b)&&(o[b]=i[b]===void 0&&_!==void 0?_[b]:i[b])}var b=arguments.length-2;if(b===1)o.children=e;else if(1<b){_=Array(b);for(var k=0;k<b;k++)_[k]=arguments[k+2];o.children=_}return{$$typeof:n$1,type:a.type,key:s,ref:c,props:o,_owner:d}};react_production_min.createContext=function(a,i){return i===void 0&&(i=null),a={$$typeof:r$1,_calculateChangedBits:i,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null},a.Provider={$$typeof:q$1,_context:a},a.Consumer=a};react_production_min.createElement=J;react_production_min.createFactory=function(a){var i=J.bind(null,a);return i.type=a,i};react_production_min.createRef=function(){return{current:null}};react_production_min.forwardRef=function(a){return{$$typeof:t,render:a}};react_production_min.isValidElement=L;react_production_min.lazy=function(a){return{$$typeof:v,_payload:{_status:-1,_result:a},_init:Q}};react_production_min.memo=function(a,i){return{$$typeof:u,type:a,compare:i===void 0?null:i}};react_production_min.useCallback=function(a,i){return S$1().useCallback(a,i)};react_production_min.useContext=function(a,i){return S$1().useContext(a,i)};react_production_min.useDebugValue=function(){};react_production_min.useEffect=function(a,i){return S$1().useEffect(a,i)};react_production_min.useImperativeHandle=function(a,i,e){return S$1().useImperativeHandle(a,i,e)};react_production_min.useLayoutEffect=function(a,i){return S$1().useLayoutEffect(a,i)};react_production_min.useMemo=function(a,i){return S$1().useMemo(a,i)};react_production_min.useReducer=function(a,i,e){return S$1().useReducer(a,i,e)};react_production_min.useRef=function(a){return S$1().useRef(a)};react_production_min.useState=function(a){return S$1().useState(a)};react_production_min.version="17.0.2";react.exports=react_production_min;var React=react.exports,reactDom={exports:{}},reactDom_production_min={},scheduler={exports:{}},scheduler_production_min={};/** @license React v0.20.2
  13. * scheduler.production.min.js
  14. *
  15. * Copyright (c) Facebook, Inc. and its affiliates.
  16. *
  17. * This source code is licensed under the MIT license found in the
  18. * LICENSE file in the root directory of this source tree.
  19. */(function(a){var i,e,o,s;if(typeof performance=="object"&&typeof performance.now=="function"){var c=performance;a.unstable_now=function(){return c.now()}}else{var d=Date,_=d.now();a.unstable_now=function(){return d.now()-_}}if(typeof window=="undefined"||typeof MessageChannel!="function"){var b=null,k=null,j=function(){if(b!==null)try{var bt=a.unstable_now();b(!0,bt),b=null}catch(Mt){throw setTimeout(j,0),Mt}};i=function(bt){b!==null?setTimeout(i,0,bt):(b=bt,setTimeout(j,0))},e=function(bt,Mt){k=setTimeout(bt,Mt)},o=function(){clearTimeout(k)},a.unstable_shouldYield=function(){return!1},s=a.unstable_forceFrameRate=function(){}}else{var $=window.setTimeout,_e=window.clearTimeout;if(typeof console!="undefined"){var et=window.cancelAnimationFrame;typeof window.requestAnimationFrame!="function"&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"),typeof et!="function"&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills")}var tt=!1,rt=null,it=-1,nt=5,ot=0;a.unstable_shouldYield=function(){return a.unstable_now()>=ot},s=function(){},a.unstable_forceFrameRate=function(bt){0>bt||125<bt?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):nt=0<bt?Math.floor(1e3/bt):5};var at=new MessageChannel,st=at.port2;at.port1.onmessage=function(){if(rt!==null){var bt=a.unstable_now();ot=bt+nt;try{rt(!0,bt)?st.postMessage(null):(tt=!1,rt=null)}catch(Mt){throw st.postMessage(null),Mt}}else tt=!1},i=function(bt){rt=bt,tt||(tt=!0,st.postMessage(null))},e=function(bt,Mt){it=$(function(){bt(a.unstable_now())},Mt)},o=function(){_e(it),it=-1}}function ut(bt,Mt){var Rt=bt.length;bt.push(Mt);e:for(;;){var Pt=Rt-1>>>1,It=bt[Pt];if(It!==void 0&&0<ht(It,Mt))bt[Pt]=Mt,bt[Rt]=It,Rt=Pt;else break e}}function ft(bt){return bt=bt[0],bt===void 0?null:bt}function lt(bt){var Mt=bt[0];if(Mt!==void 0){var Rt=bt.pop();if(Rt!==Mt){bt[0]=Rt;e:for(var Pt=0,It=bt.length;Pt<It;){var Dt=2*(Pt+1)-1,Ct=bt[Dt],Ot=Dt+1,Ft=bt[Ot];if(Ct!==void 0&&0>ht(Ct,Rt))Ft!==void 0&&0>ht(Ft,Ct)?(bt[Pt]=Ft,bt[Ot]=Rt,Pt=Ot):(bt[Pt]=Ct,bt[Dt]=Rt,Pt=Dt);else if(Ft!==void 0&&0>ht(Ft,Rt))bt[Pt]=Ft,bt[Ot]=Rt,Pt=Ot;else break e}}return Mt}return null}function ht(bt,Mt){var Rt=bt.sortIndex-Mt.sortIndex;return Rt!==0?Rt:bt.id-Mt.id}var pt=[],mt=[],dt=1,gt=null,_t=3,yt=!1,Tt=!1,St=!1;function At(bt){for(var Mt=ft(mt);Mt!==null;){if(Mt.callback===null)lt(mt);else if(Mt.startTime<=bt)lt(mt),Mt.sortIndex=Mt.expirationTime,ut(pt,Mt);else break;Mt=ft(mt)}}function vt(bt){if(St=!1,At(bt),!Tt)if(ft(pt)!==null)Tt=!0,i(Et);else{var Mt=ft(mt);Mt!==null&&e(vt,Mt.startTime-bt)}}function Et(bt,Mt){Tt=!1,St&&(St=!1,o()),yt=!0;var Rt=_t;try{for(At(Mt),gt=ft(pt);gt!==null&&(!(gt.expirationTime>Mt)||bt&&!a.unstable_shouldYield());){var Pt=gt.callback;if(typeof Pt=="function"){gt.callback=null,_t=gt.priorityLevel;var It=Pt(gt.expirationTime<=Mt);Mt=a.unstable_now(),typeof It=="function"?gt.callback=It:gt===ft(pt)&&lt(pt),At(Mt)}else lt(pt);gt=ft(pt)}if(gt!==null)var Dt=!0;else{var Ct=ft(mt);Ct!==null&&e(vt,Ct.startTime-Mt),Dt=!1}return Dt}finally{gt=null,_t=Rt,yt=!1}}var xt=s;a.unstable_IdlePriority=5,a.unstable_ImmediatePriority=1,a.unstable_LowPriority=4,a.unstable_NormalPriority=3,a.unstable_Profiling=null,a.unstable_UserBlockingPriority=2,a.unstable_cancelCallback=function(bt){bt.callback=null},a.unstable_continueExecution=function(){Tt||yt||(Tt=!0,i(Et))},a.unstable_getCurrentPriorityLevel=function(){return _t},a.unstable_getFirstCallbackNode=function(){return ft(pt)},a.unstable_next=function(bt){switch(_t){case 1:case 2:case 3:var Mt=3;break;default:Mt=_t}var Rt=_t;_t=Mt;try{return bt()}finally{_t=Rt}},a.unstable_pauseExecution=function(){},a.unstable_requestPaint=xt,a.unstable_runWithPriority=function(bt,Mt){switch(bt){case 1:case 2:case 3:case 4:case 5:break;default:bt=3}var Rt=_t;_t=bt;try{return Mt()}finally{_t=Rt}},a.unstable_scheduleCallback=function(bt,Mt,Rt){var Pt=a.unstable_now();switch(typeof Rt=="object"&&Rt!==null?(Rt=Rt.delay,Rt=typeof Rt=="number"&&0<Rt?Pt+Rt:Pt):Rt=Pt,bt){case 1:var It=-1;break;case 2:It=250;break;case 5:It=1073741823;break;case 4:It=1e4;break;default:It=5e3}return It=Rt+It,bt={id:dt++,callback:Mt,priorityLevel:bt,startTime:Rt,expirationTime:It,sortIndex:-1},Rt>Pt?(bt.sortIndex=Rt,ut(mt,bt),ft(pt)===null&&bt===ft(mt)&&(St?o():St=!0,e(vt,Rt-Pt))):(bt.sortIndex=It,ut(pt,bt),Tt||yt||(Tt=!0,i(Et))),bt},a.unstable_wrapCallback=function(bt){var Mt=_t;return function(){var Rt=_t;_t=Mt;try{return bt.apply(this,arguments)}finally{_t=Rt}}}})(scheduler_production_min);scheduler.exports=scheduler_production_min;/** @license React v17.0.2
  20. * react-dom.production.min.js
  21. *
  22. * Copyright (c) Facebook, Inc. and its affiliates.
  23. *
  24. * This source code is licensed under the MIT license found in the
  25. * LICENSE file in the root directory of this source tree.
  26. */var aa=react.exports,m$1=objectAssign,r=scheduler.exports;function y(a){for(var i="https://reactjs.org/docs/error-decoder.html?invariant="+a,e=1;e<arguments.length;e++)i+="&args[]="+encodeURIComponent(arguments[e]);return"Minified React error #"+a+"; visit "+i+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}if(!aa)throw Error(y(227));var ba=new Set,ca={};function da(a,i){ea(a,i),ea(a+"Capture",i)}function ea(a,i){for(ca[a]=i,a=0;a<i.length;a++)ba.add(i[a])}var fa=!(typeof window=="undefined"||typeof window.document=="undefined"||typeof window.document.createElement=="undefined"),ha=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ia=Object.prototype.hasOwnProperty,ja={},ka={};function la(a){return ia.call(ka,a)?!0:ia.call(ja,a)?!1:ha.test(a)?ka[a]=!0:(ja[a]=!0,!1)}function ma(a,i,e,o){if(e!==null&&e.type===0)return!1;switch(typeof i){case"function":case"symbol":return!0;case"boolean":return o?!1:e!==null?!e.acceptsBooleans:(a=a.toLowerCase().slice(0,5),a!=="data-"&&a!=="aria-");default:return!1}}function na(a,i,e,o){if(i===null||typeof i=="undefined"||ma(a,i,e,o))return!0;if(o)return!1;if(e!==null)switch(e.type){case 3:return!i;case 4:return i===!1;case 5:return isNaN(i);case 6:return isNaN(i)||1>i}return!1}function B(a,i,e,o,s,c,d){this.acceptsBooleans=i===2||i===3||i===4,this.attributeName=o,this.attributeNamespace=s,this.mustUseProperty=e,this.propertyName=a,this.type=i,this.sanitizeURL=c,this.removeEmptyString=d}var D={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){D[a]=new B(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var i=a[0];D[i]=new B(i,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){D[a]=new B(a,2,!1,a.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){D[a]=new B(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){D[a]=new B(a,3,!1,a.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(a){D[a]=new B(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){D[a]=new B(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){D[a]=new B(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){D[a]=new B(a,5,!1,a.toLowerCase(),null,!1,!1)});var oa=/[\-:]([a-z])/g;function pa(a){return a[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var i=a.replace(oa,pa);D[i]=new B(i,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var i=a.replace(oa,pa);D[i]=new B(i,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var i=a.replace(oa,pa);D[i]=new B(i,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!1,!1)});D.xlinkHref=new B("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!0,!0)});function qa(a,i,e,o){var s=D.hasOwnProperty(i)?D[i]:null,c=s!==null?s.type===0:o?!1:!(!(2<i.length)||i[0]!=="o"&&i[0]!=="O"||i[1]!=="n"&&i[1]!=="N");c||(na(i,e,s,o)&&(e=null),o||s===null?la(i)&&(e===null?a.removeAttribute(i):a.setAttribute(i,""+e)):s.mustUseProperty?a[s.propertyName]=e===null?s.type===3?!1:"":e:(i=s.attributeName,o=s.attributeNamespace,e===null?a.removeAttribute(i):(s=s.type,e=s===3||s===4&&e===!0?"":""+e,o?a.setAttributeNS(o,i,e):a.setAttribute(i,e))))}var ra=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,sa=60103,ta=60106,ua=60107,wa=60108,xa=60114,ya=60109,za=60110,Aa=60112,Ba=60113,Ca=60120,Da=60115,Ea=60116,Fa=60121,Ga=60128,Ha=60129,Ia=60130,Ja=60131;if(typeof Symbol=="function"&&Symbol.for){var E=Symbol.for;sa=E("react.element"),ta=E("react.portal"),ua=E("react.fragment"),wa=E("react.strict_mode"),xa=E("react.profiler"),ya=E("react.provider"),za=E("react.context"),Aa=E("react.forward_ref"),Ba=E("react.suspense"),Ca=E("react.suspense_list"),Da=E("react.memo"),Ea=E("react.lazy"),Fa=E("react.block"),E("react.scope"),Ga=E("react.opaque.id"),Ha=E("react.debug_trace_mode"),Ia=E("react.offscreen"),Ja=E("react.legacy_hidden")}var Ka=typeof Symbol=="function"&&Symbol.iterator;function La(a){return a===null||typeof a!="object"?null:(a=Ka&&a[Ka]||a["@@iterator"],typeof a=="function"?a:null)}var Ma;function Na(a){if(Ma===void 0)try{throw Error()}catch(e){var i=e.stack.trim().match(/\n( *(at )?)/);Ma=i&&i[1]||""}return`
  27. `+Ma+a}var Oa=!1;function Pa(a,i){if(!a||Oa)return"";Oa=!0;var e=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(i)if(i=function(){throw Error()},Object.defineProperty(i.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(i,[])}catch(b){var o=b}Reflect.construct(a,[],i)}else{try{i.call()}catch(b){o=b}a.call(i.prototype)}else{try{throw Error()}catch(b){o=b}a()}}catch(b){if(b&&o&&typeof b.stack=="string"){for(var s=b.stack.split(`
  28. `),c=o.stack.split(`
  29. `),d=s.length-1,_=c.length-1;1<=d&&0<=_&&s[d]!==c[_];)_--;for(;1<=d&&0<=_;d--,_--)if(s[d]!==c[_]){if(d!==1||_!==1)do if(d--,_--,0>_||s[d]!==c[_])return`
  30. `+s[d].replace(" at new "," at ");while(1<=d&&0<=_);break}}}finally{Oa=!1,Error.prepareStackTrace=e}return(a=a?a.displayName||a.name:"")?Na(a):""}function Qa(a){switch(a.tag){case 5:return Na(a.type);case 16:return Na("Lazy");case 13:return Na("Suspense");case 19:return Na("SuspenseList");case 0:case 2:case 15:return a=Pa(a.type,!1),a;case 11:return a=Pa(a.type.render,!1),a;case 22:return a=Pa(a.type._render,!1),a;case 1:return a=Pa(a.type,!0),a;default:return""}}function Ra(a){if(a==null)return null;if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case ua:return"Fragment";case ta:return"Portal";case xa:return"Profiler";case wa:return"StrictMode";case Ba:return"Suspense";case Ca:return"SuspenseList"}if(typeof a=="object")switch(a.$$typeof){case za:return(a.displayName||"Context")+".Consumer";case ya:return(a._context.displayName||"Context")+".Provider";case Aa:var i=a.render;return i=i.displayName||i.name||"",a.displayName||(i!==""?"ForwardRef("+i+")":"ForwardRef");case Da:return Ra(a.type);case Fa:return Ra(a._render);case Ea:i=a._payload,a=a._init;try{return Ra(a(i))}catch{}}return null}function Sa(a){switch(typeof a){case"boolean":case"number":case"object":case"string":case"undefined":return a;default:return""}}function Ta(a){var i=a.type;return(a=a.nodeName)&&a.toLowerCase()==="input"&&(i==="checkbox"||i==="radio")}function Ua(a){var i=Ta(a)?"checked":"value",e=Object.getOwnPropertyDescriptor(a.constructor.prototype,i),o=""+a[i];if(!a.hasOwnProperty(i)&&typeof e!="undefined"&&typeof e.get=="function"&&typeof e.set=="function"){var s=e.get,c=e.set;return Object.defineProperty(a,i,{configurable:!0,get:function(){return s.call(this)},set:function(d){o=""+d,c.call(this,d)}}),Object.defineProperty(a,i,{enumerable:e.enumerable}),{getValue:function(){return o},setValue:function(d){o=""+d},stopTracking:function(){a._valueTracker=null,delete a[i]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var i=a._valueTracker;if(!i)return!0;var e=i.getValue(),o="";return a&&(o=Ta(a)?a.checked?"true":"false":a.value),a=o,a!==e?(i.setValue(a),!0):!1}function Xa(a){if(a=a||(typeof document!="undefined"?document:void 0),typeof a=="undefined")return null;try{return a.activeElement||a.body}catch{return a.body}}function Ya(a,i){var e=i.checked;return m$1({},i,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:e!=null?e:a._wrapperState.initialChecked})}function Za(a,i){var e=i.defaultValue==null?"":i.defaultValue,o=i.checked!=null?i.checked:i.defaultChecked;e=Sa(i.value!=null?i.value:e),a._wrapperState={initialChecked:o,initialValue:e,controlled:i.type==="checkbox"||i.type==="radio"?i.checked!=null:i.value!=null}}function $a(a,i){i=i.checked,i!=null&&qa(a,"checked",i,!1)}function ab(a,i){$a(a,i);var e=Sa(i.value),o=i.type;if(e!=null)o==="number"?(e===0&&a.value===""||a.value!=e)&&(a.value=""+e):a.value!==""+e&&(a.value=""+e);else if(o==="submit"||o==="reset"){a.removeAttribute("value");return}i.hasOwnProperty("value")?bb(a,i.type,e):i.hasOwnProperty("defaultValue")&&bb(a,i.type,Sa(i.defaultValue)),i.checked==null&&i.defaultChecked!=null&&(a.defaultChecked=!!i.defaultChecked)}function cb(a,i,e){if(i.hasOwnProperty("value")||i.hasOwnProperty("defaultValue")){var o=i.type;if(!(o!=="submit"&&o!=="reset"||i.value!==void 0&&i.value!==null))return;i=""+a._wrapperState.initialValue,e||i===a.value||(a.value=i),a.defaultValue=i}e=a.name,e!==""&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,e!==""&&(a.name=e)}function bb(a,i,e){(i!=="number"||Xa(a.ownerDocument)!==a)&&(e==null?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+e&&(a.defaultValue=""+e))}function db(a){var i="";return aa.Children.forEach(a,function(e){e!=null&&(i+=e)}),i}function eb(a,i){return a=m$1({children:void 0},i),(i=db(i.children))&&(a.children=i),a}function fb(a,i,e,o){if(a=a.options,i){i={};for(var s=0;s<e.length;s++)i["$"+e[s]]=!0;for(e=0;e<a.length;e++)s=i.hasOwnProperty("$"+a[e].value),a[e].selected!==s&&(a[e].selected=s),s&&o&&(a[e].defaultSelected=!0)}else{for(e=""+Sa(e),i=null,s=0;s<a.length;s++){if(a[s].value===e){a[s].selected=!0,o&&(a[s].defaultSelected=!0);return}i!==null||a[s].disabled||(i=a[s])}i!==null&&(i.selected=!0)}}function gb(a,i){if(i.dangerouslySetInnerHTML!=null)throw Error(y(91));return m$1({},i,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function hb(a,i){var e=i.value;if(e==null){if(e=i.children,i=i.defaultValue,e!=null){if(i!=null)throw Error(y(92));if(Array.isArray(e)){if(!(1>=e.length))throw Error(y(93));e=e[0]}i=e}i==null&&(i=""),e=i}a._wrapperState={initialValue:Sa(e)}}function ib(a,i){var e=Sa(i.value),o=Sa(i.defaultValue);e!=null&&(e=""+e,e!==a.value&&(a.value=e),i.defaultValue==null&&a.defaultValue!==e&&(a.defaultValue=e)),o!=null&&(a.defaultValue=""+o)}function jb(a){var i=a.textContent;i===a._wrapperState.initialValue&&i!==""&&i!==null&&(a.value=i)}var kb={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};function lb(a){switch(a){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function mb(a,i){return a==null||a==="http://www.w3.org/1999/xhtml"?lb(i):a==="http://www.w3.org/2000/svg"&&i==="foreignObject"?"http://www.w3.org/1999/xhtml":a}var nb,ob=function(a){return typeof MSApp!="undefined"&&MSApp.execUnsafeLocalFunction?function(i,e,o,s){MSApp.execUnsafeLocalFunction(function(){return a(i,e,o,s)})}:a}(function(a,i){if(a.namespaceURI!==kb.svg||"innerHTML"in a)a.innerHTML=i;else{for(nb=nb||document.createElement("div"),nb.innerHTML="<svg>"+i.valueOf().toString()+"</svg>",i=nb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;i.firstChild;)a.appendChild(i.firstChild)}});function pb(a,i){if(i){var e=a.firstChild;if(e&&e===a.lastChild&&e.nodeType===3){e.nodeValue=i;return}}a.textContent=i}var qb={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},rb=["Webkit","ms","Moz","O"];Object.keys(qb).forEach(function(a){rb.forEach(function(i){i=i+a.charAt(0).toUpperCase()+a.substring(1),qb[i]=qb[a]})});function sb(a,i,e){return i==null||typeof i=="boolean"||i===""?"":e||typeof i!="number"||i===0||qb.hasOwnProperty(a)&&qb[a]?(""+i).trim():i+"px"}function tb(a,i){a=a.style;for(var e in i)if(i.hasOwnProperty(e)){var o=e.indexOf("--")===0,s=sb(e,i[e],o);e==="float"&&(e="cssFloat"),o?a.setProperty(e,s):a[e]=s}}var ub=m$1({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function vb(a,i){if(i){if(ub[a]&&(i.children!=null||i.dangerouslySetInnerHTML!=null))throw Error(y(137,a));if(i.dangerouslySetInnerHTML!=null){if(i.children!=null)throw Error(y(60));if(!(typeof i.dangerouslySetInnerHTML=="object"&&"__html"in i.dangerouslySetInnerHTML))throw Error(y(61))}if(i.style!=null&&typeof i.style!="object")throw Error(y(62))}}function wb(a,i){if(a.indexOf("-")===-1)return typeof i.is=="string";switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function xb(a){return a=a.target||a.srcElement||window,a.correspondingUseElement&&(a=a.correspondingUseElement),a.nodeType===3?a.parentNode:a}var yb=null,zb=null,Ab=null;function Bb(a){if(a=Cb(a)){if(typeof yb!="function")throw Error(y(280));var i=a.stateNode;i&&(i=Db(i),yb(a.stateNode,a.type,i))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,i=Ab;if(Ab=zb=null,Bb(a),i)for(a=0;a<i.length;a++)Bb(i[a])}}function Gb(a,i){return a(i)}function Hb(a,i,e,o,s){return a(i,e,o,s)}function Ib(){}var Jb=Gb,Kb=!1,Lb=!1;function Mb(){(zb!==null||Ab!==null)&&(Ib(),Fb())}function Nb(a,i,e){if(Lb)return a(i,e);Lb=!0;try{return Jb(a,i,e)}finally{Lb=!1,Mb()}}function Ob(a,i){var e=a.stateNode;if(e===null)return null;var o=Db(e);if(o===null)return null;e=o[i];e:switch(i){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(o=!o.disabled)||(a=a.type,o=!(a==="button"||a==="input"||a==="select"||a==="textarea")),a=!o;break e;default:a=!1}if(a)return null;if(e&&typeof e!="function")throw Error(y(231,i,typeof e));return e}var Pb=!1;if(fa)try{var Qb={};Object.defineProperty(Qb,"passive",{get:function(){Pb=!0}}),window.addEventListener("test",Qb,Qb),window.removeEventListener("test",Qb,Qb)}catch{Pb=!1}function Rb(a,i,e,o,s,c,d,_,b){var k=Array.prototype.slice.call(arguments,3);try{i.apply(e,k)}catch(j){this.onError(j)}}var Sb=!1,Tb=null,Ub=!1,Vb=null,Wb={onError:function(a){Sb=!0,Tb=a}};function Xb(a,i,e,o,s,c,d,_,b){Sb=!1,Tb=null,Rb.apply(Wb,arguments)}function Yb(a,i,e,o,s,c,d,_,b){if(Xb.apply(this,arguments),Sb){if(Sb){var k=Tb;Sb=!1,Tb=null}else throw Error(y(198));Ub||(Ub=!0,Vb=k)}}function Zb(a){var i=a,e=a;if(a.alternate)for(;i.return;)i=i.return;else{a=i;do i=a,(i.flags&1026)!==0&&(e=i.return),a=i.return;while(a)}return i.tag===3?e:null}function $b(a){if(a.tag===13){var i=a.memoizedState;if(i===null&&(a=a.alternate,a!==null&&(i=a.memoizedState)),i!==null)return i.dehydrated}return null}function ac(a){if(Zb(a)!==a)throw Error(y(188))}function bc(a){var i=a.alternate;if(!i){if(i=Zb(a),i===null)throw Error(y(188));return i!==a?null:a}for(var e=a,o=i;;){var s=e.return;if(s===null)break;var c=s.alternate;if(c===null){if(o=s.return,o!==null){e=o;continue}break}if(s.child===c.child){for(c=s.child;c;){if(c===e)return ac(s),a;if(c===o)return ac(s),i;c=c.sibling}throw Error(y(188))}if(e.return!==o.return)e=s,o=c;else{for(var d=!1,_=s.child;_;){if(_===e){d=!0,e=s,o=c;break}if(_===o){d=!0,o=s,e=c;break}_=_.sibling}if(!d){for(_=c.child;_;){if(_===e){d=!0,e=c,o=s;break}if(_===o){d=!0,o=c,e=s;break}_=_.sibling}if(!d)throw Error(y(189))}}if(e.alternate!==o)throw Error(y(190))}if(e.tag!==3)throw Error(y(188));return e.stateNode.current===e?a:i}function cc(a){if(a=bc(a),!a)return null;for(var i=a;;){if(i.tag===5||i.tag===6)return i;if(i.child)i.child.return=i,i=i.child;else{if(i===a)break;for(;!i.sibling;){if(!i.return||i.return===a)return null;i=i.return}i.sibling.return=i.return,i=i.sibling}}return null}function dc(a,i){for(var e=a.alternate;i!==null;){if(i===a||i===e)return!0;i=i.return}return!1}var ec,fc,gc,hc,ic=!1,jc=[],kc=null,lc=null,mc=null,nc=new Map,oc=new Map,pc=[],qc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function rc(a,i,e,o,s){return{blockedOn:a,domEventName:i,eventSystemFlags:e|16,nativeEvent:s,targetContainers:[o]}}function sc(a,i){switch(a){case"focusin":case"focusout":kc=null;break;case"dragenter":case"dragleave":lc=null;break;case"mouseover":case"mouseout":mc=null;break;case"pointerover":case"pointerout":nc.delete(i.pointerId);break;case"gotpointercapture":case"lostpointercapture":oc.delete(i.pointerId)}}function tc(a,i,e,o,s,c){return a===null||a.nativeEvent!==c?(a=rc(i,e,o,s,c),i!==null&&(i=Cb(i),i!==null&&fc(i)),a):(a.eventSystemFlags|=o,i=a.targetContainers,s!==null&&i.indexOf(s)===-1&&i.push(s),a)}function uc(a,i,e,o,s){switch(i){case"focusin":return kc=tc(kc,a,i,e,o,s),!0;case"dragenter":return lc=tc(lc,a,i,e,o,s),!0;case"mouseover":return mc=tc(mc,a,i,e,o,s),!0;case"pointerover":var c=s.pointerId;return nc.set(c,tc(nc.get(c)||null,a,i,e,o,s)),!0;case"gotpointercapture":return c=s.pointerId,oc.set(c,tc(oc.get(c)||null,a,i,e,o,s)),!0}return!1}function vc(a){var i=wc(a.target);if(i!==null){var e=Zb(i);if(e!==null){if(i=e.tag,i===13){if(i=$b(e),i!==null){a.blockedOn=i,hc(a.lanePriority,function(){r.unstable_runWithPriority(a.priority,function(){gc(e)})});return}}else if(i===3&&e.stateNode.hydrate){a.blockedOn=e.tag===3?e.stateNode.containerInfo:null;return}}}a.blockedOn=null}function xc(a){if(a.blockedOn!==null)return!1;for(var i=a.targetContainers;0<i.length;){var e=yc(a.domEventName,a.eventSystemFlags,i[0],a.nativeEvent);if(e!==null)return i=Cb(e),i!==null&&fc(i),a.blockedOn=e,!1;i.shift()}return!0}function zc(a,i,e){xc(a)&&e.delete(i)}function Ac(){for(ic=!1;0<jc.length;){var a=jc[0];if(a.blockedOn!==null){a=Cb(a.blockedOn),a!==null&&ec(a);break}for(var i=a.targetContainers;0<i.length;){var e=yc(a.domEventName,a.eventSystemFlags,i[0],a.nativeEvent);if(e!==null){a.blockedOn=e;break}i.shift()}a.blockedOn===null&&jc.shift()}kc!==null&&xc(kc)&&(kc=null),lc!==null&&xc(lc)&&(lc=null),mc!==null&&xc(mc)&&(mc=null),nc.forEach(zc),oc.forEach(zc)}function Bc(a,i){a.blockedOn===i&&(a.blockedOn=null,ic||(ic=!0,r.unstable_scheduleCallback(r.unstable_NormalPriority,Ac)))}function Cc(a){function i(s){return Bc(s,a)}if(0<jc.length){Bc(jc[0],a);for(var e=1;e<jc.length;e++){var o=jc[e];o.blockedOn===a&&(o.blockedOn=null)}}for(kc!==null&&Bc(kc,a),lc!==null&&Bc(lc,a),mc!==null&&Bc(mc,a),nc.forEach(i),oc.forEach(i),e=0;e<pc.length;e++)o=pc[e],o.blockedOn===a&&(o.blockedOn=null);for(;0<pc.length&&(e=pc[0],e.blockedOn===null);)vc(e),e.blockedOn===null&&pc.shift()}function Dc(a,i){var e={};return e[a.toLowerCase()]=i.toLowerCase(),e["Webkit"+a]="webkit"+i,e["Moz"+a]="moz"+i,e}var Ec={animationend:Dc("Animation","AnimationEnd"),animationiteration:Dc("Animation","AnimationIteration"),animationstart:Dc("Animation","AnimationStart"),transitionend:Dc("Transition","TransitionEnd")},Fc={},Gc={};fa&&(Gc=document.createElement("div").style,"AnimationEvent"in window||(delete Ec.animationend.animation,delete Ec.animationiteration.animation,delete Ec.animationstart.animation),"TransitionEvent"in window||delete Ec.transitionend.transition);function Hc(a){if(Fc[a])return Fc[a];if(!Ec[a])return a;var i=Ec[a],e;for(e in i)if(i.hasOwnProperty(e)&&e in Gc)return Fc[a]=i[e];return a}var Ic=Hc("animationend"),Jc=Hc("animationiteration"),Kc=Hc("animationstart"),Lc=Hc("transitionend"),Mc=new Map,Nc=new Map,Oc=["abort","abort",Ic,"animationEnd",Jc,"animationIteration",Kc,"animationStart","canplay","canPlay","canplaythrough","canPlayThrough","durationchange","durationChange","emptied","emptied","encrypted","encrypted","ended","ended","error","error","gotpointercapture","gotPointerCapture","load","load","loadeddata","loadedData","loadedmetadata","loadedMetadata","loadstart","loadStart","lostpointercapture","lostPointerCapture","playing","playing","progress","progress","seeking","seeking","stalled","stalled","suspend","suspend","timeupdate","timeUpdate",Lc,"transitionEnd","waiting","waiting"];function Pc(a,i){for(var e=0;e<a.length;e+=2){var o=a[e],s=a[e+1];s="on"+(s[0].toUpperCase()+s.slice(1)),Nc.set(o,i),Mc.set(o,s),da(s,[o])}}var Qc=r.unstable_now;Qc();var F=8;function Rc(a){if((1&a)!==0)return F=15,1;if((2&a)!==0)return F=14,2;if((4&a)!==0)return F=13,4;var i=24&a;return i!==0?(F=12,i):(a&32)!==0?(F=11,32):(i=192&a,i!==0?(F=10,i):(a&256)!==0?(F=9,256):(i=3584&a,i!==0?(F=8,i):(a&4096)!==0?(F=7,4096):(i=4186112&a,i!==0?(F=6,i):(i=62914560&a,i!==0?(F=5,i):a&67108864?(F=4,67108864):(a&134217728)!==0?(F=3,134217728):(i=805306368&a,i!==0?(F=2,i):(1073741824&a)!==0?(F=1,1073741824):(F=8,a))))))}function Sc(a){switch(a){case 99:return 15;case 98:return 10;case 97:case 96:return 8;case 95:return 2;default:return 0}}function Tc(a){switch(a){case 15:case 14:return 99;case 13:case 12:case 11:case 10:return 98;case 9:case 8:case 7:case 6:case 4:case 5:return 97;case 3:case 2:case 1:return 95;case 0:return 90;default:throw Error(y(358,a))}}function Uc(a,i){var e=a.pendingLanes;if(e===0)return F=0;var o=0,s=0,c=a.expiredLanes,d=a.suspendedLanes,_=a.pingedLanes;if(c!==0)o=c,s=F=15;else if(c=e&134217727,c!==0){var b=c&~d;b!==0?(o=Rc(b),s=F):(_&=c,_!==0&&(o=Rc(_),s=F))}else c=e&~d,c!==0?(o=Rc(c),s=F):_!==0&&(o=Rc(_),s=F);if(o===0)return 0;if(o=31-Vc(o),o=e&((0>o?0:1<<o)<<1)-1,i!==0&&i!==o&&(i&d)===0){if(Rc(i),s<=F)return i;F=s}if(i=a.entangledLanes,i!==0)for(a=a.entanglements,i&=o;0<i;)e=31-Vc(i),s=1<<e,o|=a[e],i&=~s;return o}function Wc(a){return a=a.pendingLanes&-1073741825,a!==0?a:a&1073741824?1073741824:0}function Xc(a,i){switch(a){case 15:return 1;case 14:return 2;case 12:return a=Yc(24&~i),a===0?Xc(10,i):a;case 10:return a=Yc(192&~i),a===0?Xc(8,i):a;case 8:return a=Yc(3584&~i),a===0&&(a=Yc(4186112&~i),a===0&&(a=512)),a;case 2:return i=Yc(805306368&~i),i===0&&(i=268435456),i}throw Error(y(358,a))}function Yc(a){return a&-a}function Zc(a){for(var i=[],e=0;31>e;e++)i.push(a);return i}function $c(a,i,e){a.pendingLanes|=i;var o=i-1;a.suspendedLanes&=o,a.pingedLanes&=o,a=a.eventTimes,i=31-Vc(i),a[i]=e}var Vc=Math.clz32?Math.clz32:ad,bd=Math.log,cd=Math.LN2;function ad(a){return a===0?32:31-(bd(a)/cd|0)|0}var dd=r.unstable_UserBlockingPriority,ed=r.unstable_runWithPriority,fd=!0;function gd(a,i,e,o){Kb||Ib();var s=hd,c=Kb;Kb=!0;try{Hb(s,a,i,e,o)}finally{(Kb=c)||Mb()}}function id(a,i,e,o){ed(dd,hd.bind(null,a,i,e,o))}function hd(a,i,e,o){if(fd){var s;if((s=(i&4)===0)&&0<jc.length&&-1<qc.indexOf(a))a=rc(null,a,i,e,o),jc.push(a);else{var c=yc(a,i,e,o);if(c===null)s&&sc(a,o);else{if(s){if(-1<qc.indexOf(a)){a=rc(c,a,i,e,o),jc.push(a);return}if(uc(c,a,i,e,o))return;sc(a,o)}jd(a,i,o,null,e)}}}}function yc(a,i,e,o){var s=xb(o);if(s=wc(s),s!==null){var c=Zb(s);if(c===null)s=null;else{var d=c.tag;if(d===13){if(s=$b(c),s!==null)return s;s=null}else if(d===3){if(c.stateNode.hydrate)return c.tag===3?c.stateNode.containerInfo:null;s=null}else c!==s&&(s=null)}}return jd(a,i,o,s,e),null}var kd=null,ld=null,md=null;function nd(){if(md)return md;var a,i=ld,e=i.length,o,s="value"in kd?kd.value:kd.textContent,c=s.length;for(a=0;a<e&&i[a]===s[a];a++);var d=e-a;for(o=1;o<=d&&i[e-o]===s[c-o];o++);return md=s.slice(a,1<o?1-o:void 0)}function od(a){var i=a.keyCode;return"charCode"in a?(a=a.charCode,a===0&&i===13&&(a=13)):a=i,a===10&&(a=13),32<=a||a===13?a:0}function pd(){return!0}function qd(){return!1}function rd(a){function i(e,o,s,c,d){this._reactName=e,this._targetInst=s,this.type=o,this.nativeEvent=c,this.target=d,this.currentTarget=null;for(var _ in a)a.hasOwnProperty(_)&&(e=a[_],this[_]=e?e(c):c[_]);return this.isDefaultPrevented=(c.defaultPrevented!=null?c.defaultPrevented:c.returnValue===!1)?pd:qd,this.isPropagationStopped=qd,this}return m$1(i.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():typeof e.returnValue!="unknown"&&(e.returnValue=!1),this.isDefaultPrevented=pd)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():typeof e.cancelBubble!="unknown"&&(e.cancelBubble=!0),this.isPropagationStopped=pd)},persist:function(){},isPersistent:pd}),i}var sd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},td=rd(sd),ud=m$1({},sd,{view:0,detail:0}),vd=rd(ud),wd,xd,yd,Ad=m$1({},ud,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return a.relatedTarget===void 0?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){return"movementX"in a?a.movementX:(a!==yd&&(yd&&a.type==="mousemove"?(wd=a.screenX-yd.screenX,xd=a.screenY-yd.screenY):xd=wd=0,yd=a),wd)},movementY:function(a){return"movementY"in a?a.movementY:xd}}),Bd=rd(Ad),Cd=m$1({},Ad,{dataTransfer:0}),Dd=rd(Cd),Ed=m$1({},ud,{relatedTarget:0}),Fd=rd(Ed),Gd=m$1({},sd,{animationName:0,elapsedTime:0,pseudoElement:0}),Hd=rd(Gd),Id=m$1({},sd,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),Jd=rd(Id),Kd=m$1({},sd,{data:0}),Ld=rd(Kd),Md={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Nd={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Od={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Pd(a){var i=this.nativeEvent;return i.getModifierState?i.getModifierState(a):(a=Od[a])?!!i[a]:!1}function zd(){return Pd}var Qd=m$1({},ud,{key:function(a){if(a.key){var i=Md[a.key]||a.key;if(i!=="Unidentified")return i}return a.type==="keypress"?(a=od(a),a===13?"Enter":String.fromCharCode(a)):a.type==="keydown"||a.type==="keyup"?Nd[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return a.type==="keypress"?od(a):0},keyCode:function(a){return a.type==="keydown"||a.type==="keyup"?a.keyCode:0},which:function(a){return a.type==="keypress"?od(a):a.type==="keydown"||a.type==="keyup"?a.keyCode:0}}),Rd=rd(Qd),Sd=m$1({},Ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Td=rd(Sd),Ud=m$1({},ud,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Vd=rd(Ud),Wd=m$1({},sd,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xd=rd(Wd),Yd=m$1({},Ad,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Zd=rd(Yd),$d=[9,13,27,32],ae=fa&&"CompositionEvent"in window,be=null;fa&&"documentMode"in document&&(be=document.documentMode);var ce=fa&&"TextEvent"in window&&!be,de=fa&&(!ae||be&&8<be&&11>=be),ee=String.fromCharCode(32),fe=!1;function ge(a,i){switch(a){case"keyup":return $d.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function he(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var ie=!1;function je(a,i){switch(a){case"compositionend":return he(i);case"keypress":return i.which!==32?null:(fe=!0,ee);case"textInput":return a=i.data,a===ee&&fe?null:a;default:return null}}function ke(a,i){if(ie)return a==="compositionend"||!ae&&ge(a,i)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(i.ctrlKey||i.altKey||i.metaKey)||i.ctrlKey&&i.altKey){if(i.char&&1<i.char.length)return i.char;if(i.which)return String.fromCharCode(i.which)}return null;case"compositionend":return de&&i.locale!=="ko"?null:i.data;default:return null}}var le={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function me(a){var i=a&&a.nodeName&&a.nodeName.toLowerCase();return i==="input"?!!le[a.type]:i==="textarea"}function ne(a,i,e,o){Eb(o),i=oe(i,"onChange"),0<i.length&&(e=new td("onChange","change",null,e,o),a.push({event:e,listeners:i}))}var pe=null,qe=null;function re(a){se(a,0)}function te(a){var i=ue(a);if(Wa(i))return a}function ve(a,i){if(a==="change")return i}var we=!1;if(fa){var xe;if(fa){var ye="oninput"in document;if(!ye){var ze=document.createElement("div");ze.setAttribute("oninput","return;"),ye=typeof ze.oninput=="function"}xe=ye}else xe=!1;we=xe&&(!document.documentMode||9<document.documentMode)}function Ae(){pe&&(pe.detachEvent("onpropertychange",Be),qe=pe=null)}function Be(a){if(a.propertyName==="value"&&te(qe)){var i=[];if(ne(i,qe,a,xb(a)),a=re,Kb)a(i);else{Kb=!0;try{Gb(a,i)}finally{Kb=!1,Mb()}}}}function Ce(a,i,e){a==="focusin"?(Ae(),pe=i,qe=e,pe.attachEvent("onpropertychange",Be)):a==="focusout"&&Ae()}function De(a){if(a==="selectionchange"||a==="keyup"||a==="keydown")return te(qe)}function Ee(a,i){if(a==="click")return te(i)}function Fe(a,i){if(a==="input"||a==="change")return te(i)}function Ge(a,i){return a===i&&(a!==0||1/a===1/i)||a!==a&&i!==i}var He=typeof Object.is=="function"?Object.is:Ge,Ie=Object.prototype.hasOwnProperty;function Je(a,i){if(He(a,i))return!0;if(typeof a!="object"||a===null||typeof i!="object"||i===null)return!1;var e=Object.keys(a),o=Object.keys(i);if(e.length!==o.length)return!1;for(o=0;o<e.length;o++)if(!Ie.call(i,e[o])||!He(a[e[o]],i[e[o]]))return!1;return!0}function Ke(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function Le(a,i){var e=Ke(a);a=0;for(var o;e;){if(e.nodeType===3){if(o=a+e.textContent.length,a<=i&&o>=i)return{node:e,offset:i-a};a=o}e:{for(;e;){if(e.nextSibling){e=e.nextSibling;break e}e=e.parentNode}e=void 0}e=Ke(e)}}function Me(a,i){return a&&i?a===i?!0:a&&a.nodeType===3?!1:i&&i.nodeType===3?Me(a,i.parentNode):"contains"in a?a.contains(i):a.compareDocumentPosition?!!(a.compareDocumentPosition(i)&16):!1:!1}function Ne(){for(var a=window,i=Xa();i instanceof a.HTMLIFrameElement;){try{var e=typeof i.contentWindow.location.href=="string"}catch{e=!1}if(e)a=i.contentWindow;else break;i=Xa(a.document)}return i}function Oe(a){var i=a&&a.nodeName&&a.nodeName.toLowerCase();return i&&(i==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||i==="textarea"||a.contentEditable==="true")}var Pe=fa&&"documentMode"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;function Ue(a,i,e){var o=e.window===e?e.document:e.nodeType===9?e:e.ownerDocument;Te||Qe==null||Qe!==Xa(o)||(o=Qe,"selectionStart"in o&&Oe(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),Se&&Je(Se,o)||(Se=o,o=oe(Re,"onSelect"),0<o.length&&(i=new td("onSelect","select",null,i,e),a.push({event:i,listeners:o}),i.target=Qe)))}Pc("cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focusin focus focusout blur input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "),0);Pc("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "),1);Pc(Oc,2);for(var Ve="change selectionchange textInput compositionstart compositionend compositionupdate".split(" "),We=0;We<Ve.length;We++)Nc.set(Ve[We],0);ea("onMouseEnter",["mouseout","mouseover"]);ea("onMouseLeave",["mouseout","mouseover"]);ea("onPointerEnter",["pointerout","pointerover"]);ea("onPointerLeave",["pointerout","pointerover"]);da("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));da("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));da("onBeforeInput",["compositionend","keypress","textInput","paste"]);da("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));da("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));da("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Xe="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Ye=new Set("cancel close invalid load scroll toggle".split(" ").concat(Xe));function Ze(a,i,e){var o=a.type||"unknown-event";a.currentTarget=e,Yb(o,i,void 0,a),a.currentTarget=null}function se(a,i){i=(i&4)!==0;for(var e=0;e<a.length;e++){var o=a[e],s=o.event;o=o.listeners;e:{var c=void 0;if(i)for(var d=o.length-1;0<=d;d--){var _=o[d],b=_.instance,k=_.currentTarget;if(_=_.listener,b!==c&&s.isPropagationStopped())break e;Ze(s,_,k),c=b}else for(d=0;d<o.length;d++){if(_=o[d],b=_.instance,k=_.currentTarget,_=_.listener,b!==c&&s.isPropagationStopped())break e;Ze(s,_,k),c=b}}}if(Ub)throw a=Vb,Ub=!1,Vb=null,a}function G(a,i){var e=$e(i),o=a+"__bubble";e.has(o)||(af(i,a,2,!1),e.add(o))}var bf="_reactListening"+Math.random().toString(36).slice(2);function cf(a){a[bf]||(a[bf]=!0,ba.forEach(function(i){Ye.has(i)||df(i,!1,a,null),df(i,!0,a,null)}))}function df(a,i,e,o){var s=4<arguments.length&&arguments[4]!==void 0?arguments[4]:0,c=e;if(a==="selectionchange"&&e.nodeType!==9&&(c=e.ownerDocument),o!==null&&!i&&Ye.has(a)){if(a!=="scroll")return;s|=2,c=o}var d=$e(c),_=a+"__"+(i?"capture":"bubble");d.has(_)||(i&&(s|=4),af(c,a,s,i),d.add(_))}function af(a,i,e,o){var s=Nc.get(i);switch(s===void 0?2:s){case 0:s=gd;break;case 1:s=id;break;default:s=hd}e=s.bind(null,i,e,a),s=void 0,!Pb||i!=="touchstart"&&i!=="touchmove"&&i!=="wheel"||(s=!0),o?s!==void 0?a.addEventListener(i,e,{capture:!0,passive:s}):a.addEventListener(i,e,!0):s!==void 0?a.addEventListener(i,e,{passive:s}):a.addEventListener(i,e,!1)}function jd(a,i,e,o,s){var c=o;if((i&1)===0&&(i&2)===0&&o!==null)e:for(;;){if(o===null)return;var d=o.tag;if(d===3||d===4){var _=o.stateNode.containerInfo;if(_===s||_.nodeType===8&&_.parentNode===s)break;if(d===4)for(d=o.return;d!==null;){var b=d.tag;if((b===3||b===4)&&(b=d.stateNode.containerInfo,b===s||b.nodeType===8&&b.parentNode===s))return;d=d.return}for(;_!==null;){if(d=wc(_),d===null)return;if(b=d.tag,b===5||b===6){o=c=d;continue e}_=_.parentNode}}o=o.return}Nb(function(){var k=c,j=xb(e),$=[];e:{var _e=Mc.get(a);if(_e!==void 0){var et=td,tt=a;switch(a){case"keypress":if(od(e)===0)break e;case"keydown":case"keyup":et=Rd;break;case"focusin":tt="focus",et=Fd;break;case"focusout":tt="blur",et=Fd;break;case"beforeblur":case"afterblur":et=Fd;break;case"click":if(e.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":et=Bd;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":et=Dd;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":et=Vd;break;case Ic:case Jc:case Kc:et=Hd;break;case Lc:et=Xd;break;case"scroll":et=vd;break;case"wheel":et=Zd;break;case"copy":case"cut":case"paste":et=Jd;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":et=Td}var rt=(i&4)!==0,it=!rt&&a==="scroll",nt=rt?_e!==null?_e+"Capture":null:_e;rt=[];for(var ot=k,at;ot!==null;){at=ot;var st=at.stateNode;if(at.tag===5&&st!==null&&(at=st,nt!==null&&(st=Ob(ot,nt),st!=null&&rt.push(ef(ot,st,at)))),it)break;ot=ot.return}0<rt.length&&(_e=new et(_e,tt,null,e,j),$.push({event:_e,listeners:rt}))}}if((i&7)===0){e:{if(_e=a==="mouseover"||a==="pointerover",et=a==="mouseout"||a==="pointerout",_e&&(i&16)===0&&(tt=e.relatedTarget||e.fromElement)&&(wc(tt)||tt[ff]))break e;if((et||_e)&&(_e=j.window===j?j:(_e=j.ownerDocument)?_e.defaultView||_e.parentWindow:window,et?(tt=e.relatedTarget||e.toElement,et=k,tt=tt?wc(tt):null,tt!==null&&(it=Zb(tt),tt!==it||tt.tag!==5&&tt.tag!==6)&&(tt=null)):(et=null,tt=k),et!==tt)){if(rt=Bd,st="onMouseLeave",nt="onMouseEnter",ot="mouse",(a==="pointerout"||a==="pointerover")&&(rt=Td,st="onPointerLeave",nt="onPointerEnter",ot="pointer"),it=et==null?_e:ue(et),at=tt==null?_e:ue(tt),_e=new rt(st,ot+"leave",et,e,j),_e.target=it,_e.relatedTarget=at,st=null,wc(j)===k&&(rt=new rt(nt,ot+"enter",tt,e,j),rt.target=at,rt.relatedTarget=it,st=rt),it=st,et&&tt)t:{for(rt=et,nt=tt,ot=0,at=rt;at;at=gf(at))ot++;for(at=0,st=nt;st;st=gf(st))at++;for(;0<ot-at;)rt=gf(rt),ot--;for(;0<at-ot;)nt=gf(nt),at--;for(;ot--;){if(rt===nt||nt!==null&&rt===nt.alternate)break t;rt=gf(rt),nt=gf(nt)}rt=null}else rt=null;et!==null&&hf($,_e,et,rt,!1),tt!==null&&it!==null&&hf($,it,tt,rt,!0)}}e:{if(_e=k?ue(k):window,et=_e.nodeName&&_e.nodeName.toLowerCase(),et==="select"||et==="input"&&_e.type==="file")var ut=ve;else if(me(_e))if(we)ut=Fe;else{ut=De;var ft=Ce}else(et=_e.nodeName)&&et.toLowerCase()==="input"&&(_e.type==="checkbox"||_e.type==="radio")&&(ut=Ee);if(ut&&(ut=ut(a,k))){ne($,ut,e,j);break e}ft&&ft(a,_e,k),a==="focusout"&&(ft=_e._wrapperState)&&ft.controlled&&_e.type==="number"&&bb(_e,"number",_e.value)}switch(ft=k?ue(k):window,a){case"focusin":(me(ft)||ft.contentEditable==="true")&&(Qe=ft,Re=k,Se=null);break;case"focusout":Se=Re=Qe=null;break;case"mousedown":Te=!0;break;case"contextmenu":case"mouseup":case"dragend":Te=!1,Ue($,e,j);break;case"selectionchange":if(Pe)break;case"keydown":case"keyup":Ue($,e,j)}var lt;if(ae)e:{switch(a){case"compositionstart":var ht="onCompositionStart";break e;case"compositionend":ht="onCompositionEnd";break e;case"compositionupdate":ht="onCompositionUpdate";break e}ht=void 0}else ie?ge(a,e)&&(ht="onCompositionEnd"):a==="keydown"&&e.keyCode===229&&(ht="onCompositionStart");ht&&(de&&e.locale!=="ko"&&(ie||ht!=="onCompositionStart"?ht==="onCompositionEnd"&&ie&&(lt=nd()):(kd=j,ld="value"in kd?kd.value:kd.textContent,ie=!0)),ft=oe(k,ht),0<ft.length&&(ht=new Ld(ht,a,null,e,j),$.push({event:ht,listeners:ft}),lt?ht.data=lt:(lt=he(e),lt!==null&&(ht.data=lt)))),(lt=ce?je(a,e):ke(a,e))&&(k=oe(k,"onBeforeInput"),0<k.length&&(j=new Ld("onBeforeInput","beforeinput",null,e,j),$.push({event:j,listeners:k}),j.data=lt))}se($,i)})}function ef(a,i,e){return{instance:a,listener:i,currentTarget:e}}function oe(a,i){for(var e=i+"Capture",o=[];a!==null;){var s=a,c=s.stateNode;s.tag===5&&c!==null&&(s=c,c=Ob(a,e),c!=null&&o.unshift(ef(a,c,s)),c=Ob(a,i),c!=null&&o.push(ef(a,c,s))),a=a.return}return o}function gf(a){if(a===null)return null;do a=a.return;while(a&&a.tag!==5);return a||null}function hf(a,i,e,o,s){for(var c=i._reactName,d=[];e!==null&&e!==o;){var _=e,b=_.alternate,k=_.stateNode;if(b!==null&&b===o)break;_.tag===5&&k!==null&&(_=k,s?(b=Ob(e,c),b!=null&&d.unshift(ef(e,b,_))):s||(b=Ob(e,c),b!=null&&d.push(ef(e,b,_)))),e=e.return}d.length!==0&&a.push({event:i,listeners:d})}function jf(){}var kf=null,lf=null;function mf(a,i){switch(a){case"button":case"input":case"select":case"textarea":return!!i.autoFocus}return!1}function nf(a,i){return a==="textarea"||a==="option"||a==="noscript"||typeof i.children=="string"||typeof i.children=="number"||typeof i.dangerouslySetInnerHTML=="object"&&i.dangerouslySetInnerHTML!==null&&i.dangerouslySetInnerHTML.__html!=null}var of=typeof setTimeout=="function"?setTimeout:void 0,pf=typeof clearTimeout=="function"?clearTimeout:void 0;function qf(a){a.nodeType===1?a.textContent="":a.nodeType===9&&(a=a.body,a!=null&&(a.textContent=""))}function rf(a){for(;a!=null;a=a.nextSibling){var i=a.nodeType;if(i===1||i===3)break}return a}function sf(a){a=a.previousSibling;for(var i=0;a;){if(a.nodeType===8){var e=a.data;if(e==="$"||e==="$!"||e==="$?"){if(i===0)return a;i--}else e==="/$"&&i++}a=a.previousSibling}return null}var tf=0;function uf(a){return{$$typeof:Ga,toString:a,valueOf:a}}var vf=Math.random().toString(36).slice(2),wf="__reactFiber$"+vf,xf="__reactProps$"+vf,ff="__reactContainer$"+vf,yf="__reactEvents$"+vf;function wc(a){var i=a[wf];if(i)return i;for(var e=a.parentNode;e;){if(i=e[ff]||e[wf]){if(e=i.alternate,i.child!==null||e!==null&&e.child!==null)for(a=sf(a);a!==null;){if(e=a[wf])return e;a=sf(a)}return i}a=e,e=a.parentNode}return null}function Cb(a){return a=a[wf]||a[ff],!a||a.tag!==5&&a.tag!==6&&a.tag!==13&&a.tag!==3?null:a}function ue(a){if(a.tag===5||a.tag===6)return a.stateNode;throw Error(y(33))}function Db(a){return a[xf]||null}function $e(a){var i=a[yf];return i===void 0&&(i=a[yf]=new Set),i}var zf=[],Af=-1;function Bf(a){return{current:a}}function H(a){0>Af||(a.current=zf[Af],zf[Af]=null,Af--)}function I(a,i){Af++,zf[Af]=a.current,a.current=i}var Cf={},M=Bf(Cf),N=Bf(!1),Df=Cf;function Ef(a,i){var e=a.type.contextTypes;if(!e)return Cf;var o=a.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===i)return o.__reactInternalMemoizedMaskedChildContext;var s={},c;for(c in e)s[c]=i[c];return o&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=i,a.__reactInternalMemoizedMaskedChildContext=s),s}function Ff(a){return a=a.childContextTypes,a!=null}function Gf(){H(N),H(M)}function Hf(a,i,e){if(M.current!==Cf)throw Error(y(168));I(M,i),I(N,e)}function If(a,i,e){var o=a.stateNode;if(a=i.childContextTypes,typeof o.getChildContext!="function")return e;o=o.getChildContext();for(var s in o)if(!(s in a))throw Error(y(108,Ra(i)||"Unknown",s));return m$1({},e,o)}function Jf(a){return a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Cf,Df=M.current,I(M,a),I(N,N.current),!0}function Kf(a,i,e){var o=a.stateNode;if(!o)throw Error(y(169));e?(a=If(a,i,Df),o.__reactInternalMemoizedMergedChildContext=a,H(N),H(M),I(M,a)):H(N),I(N,e)}var Lf=null,Mf=null,Nf=r.unstable_runWithPriority,Of=r.unstable_scheduleCallback,Pf=r.unstable_cancelCallback,Qf=r.unstable_shouldYield,Rf=r.unstable_requestPaint,Sf=r.unstable_now,Tf=r.unstable_getCurrentPriorityLevel,Uf=r.unstable_ImmediatePriority,Vf=r.unstable_UserBlockingPriority,Wf=r.unstable_NormalPriority,Xf=r.unstable_LowPriority,Yf=r.unstable_IdlePriority,Zf={},$f=Rf!==void 0?Rf:function(){},ag=null,bg=null,cg=!1,dg=Sf(),O=1e4>dg?Sf:function(){return Sf()-dg};function eg(){switch(Tf()){case Uf:return 99;case Vf:return 98;case Wf:return 97;case Xf:return 96;case Yf:return 95;default:throw Error(y(332))}}function fg(a){switch(a){case 99:return Uf;case 98:return Vf;case 97:return Wf;case 96:return Xf;case 95:return Yf;default:throw Error(y(332))}}function gg(a,i){return a=fg(a),Nf(a,i)}function hg(a,i,e){return a=fg(a),Of(a,i,e)}function ig(){if(bg!==null){var a=bg;bg=null,Pf(a)}jg()}function jg(){if(!cg&&ag!==null){cg=!0;var a=0;try{var i=ag;gg(99,function(){for(;a<i.length;a++){var e=i[a];do e=e(!0);while(e!==null)}}),ag=null}catch(e){throw ag!==null&&(ag=ag.slice(a+1)),Of(Uf,ig),e}finally{cg=!1}}}var kg=ra.ReactCurrentBatchConfig;function lg(a,i){if(a&&a.defaultProps){i=m$1({},i),a=a.defaultProps;for(var e in a)i[e]===void 0&&(i[e]=a[e]);return i}return i}var mg=Bf(null),ng=null,og=null,pg=null;function qg(){pg=og=ng=null}function rg(a){var i=mg.current;H(mg),a.type._context._currentValue=i}function sg(a,i){for(;a!==null;){var e=a.alternate;if((a.childLanes&i)===i){if(e===null||(e.childLanes&i)===i)break;e.childLanes|=i}else a.childLanes|=i,e!==null&&(e.childLanes|=i);a=a.return}}function tg(a,i){ng=a,pg=og=null,a=a.dependencies,a!==null&&a.firstContext!==null&&((a.lanes&i)!==0&&(ug=!0),a.firstContext=null)}function vg(a,i){if(pg!==a&&i!==!1&&i!==0)if((typeof i!="number"||i===1073741823)&&(pg=a,i=1073741823),i={context:a,observedBits:i,next:null},og===null){if(ng===null)throw Error(y(308));og=i,ng.dependencies={lanes:0,firstContext:i,responders:null}}else og=og.next=i;return a._currentValue}var wg=!1;function xg(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null},effects:null}}function yg(a,i){a=a.updateQueue,i.updateQueue===a&&(i.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function zg(a,i){return{eventTime:a,lane:i,tag:0,payload:null,callback:null,next:null}}function Ag(a,i){if(a=a.updateQueue,a!==null){a=a.shared;var e=a.pending;e===null?i.next=i:(i.next=e.next,e.next=i),a.pending=i}}function Bg(a,i){var e=a.updateQueue,o=a.alternate;if(o!==null&&(o=o.updateQueue,e===o)){var s=null,c=null;if(e=e.firstBaseUpdate,e!==null){do{var d={eventTime:e.eventTime,lane:e.lane,tag:e.tag,payload:e.payload,callback:e.callback,next:null};c===null?s=c=d:c=c.next=d,e=e.next}while(e!==null);c===null?s=c=i:c=c.next=i}else s=c=i;e={baseState:o.baseState,firstBaseUpdate:s,lastBaseUpdate:c,shared:o.shared,effects:o.effects},a.updateQueue=e;return}a=e.lastBaseUpdate,a===null?e.firstBaseUpdate=i:a.next=i,e.lastBaseUpdate=i}function Cg(a,i,e,o){var s=a.updateQueue;wg=!1;var c=s.firstBaseUpdate,d=s.lastBaseUpdate,_=s.shared.pending;if(_!==null){s.shared.pending=null;var b=_,k=b.next;b.next=null,d===null?c=k:d.next=k,d=b;var j=a.alternate;if(j!==null){j=j.updateQueue;var $=j.lastBaseUpdate;$!==d&&($===null?j.firstBaseUpdate=k:$.next=k,j.lastBaseUpdate=b)}}if(c!==null){$=s.baseState,d=0,j=k=b=null;do{_=c.lane;var _e=c.eventTime;if((o&_)===_){j!==null&&(j=j.next={eventTime:_e,lane:0,tag:c.tag,payload:c.payload,callback:c.callback,next:null});e:{var et=a,tt=c;switch(_=i,_e=e,tt.tag){case 1:if(et=tt.payload,typeof et=="function"){$=et.call(_e,$,_);break e}$=et;break e;case 3:et.flags=et.flags&-4097|64;case 0:if(et=tt.payload,_=typeof et=="function"?et.call(_e,$,_):et,_==null)break e;$=m$1({},$,_);break e;case 2:wg=!0}}c.callback!==null&&(a.flags|=32,_=s.effects,_===null?s.effects=[c]:_.push(c))}else _e={eventTime:_e,lane:_,tag:c.tag,payload:c.payload,callback:c.callback,next:null},j===null?(k=j=_e,b=$):j=j.next=_e,d|=_;if(c=c.next,c===null){if(_=s.shared.pending,_===null)break;c=_.next,_.next=null,s.lastBaseUpdate=_,s.shared.pending=null}}while(1);j===null&&(b=$),s.baseState=b,s.firstBaseUpdate=k,s.lastBaseUpdate=j,Dg|=d,a.lanes=d,a.memoizedState=$}}function Eg(a,i,e){if(a=i.effects,i.effects=null,a!==null)for(i=0;i<a.length;i++){var o=a[i],s=o.callback;if(s!==null){if(o.callback=null,o=e,typeof s!="function")throw Error(y(191,s));s.call(o)}}}var Fg=new aa.Component().refs;function Gg(a,i,e,o){i=a.memoizedState,e=e(o,i),e=e==null?i:m$1({},i,e),a.memoizedState=e,a.lanes===0&&(a.updateQueue.baseState=e)}var Kg={isMounted:function(a){return(a=a._reactInternals)?Zb(a)===a:!1},enqueueSetState:function(a,i,e){a=a._reactInternals;var o=Hg(),s=Ig(a),c=zg(o,s);c.payload=i,e!=null&&(c.callback=e),Ag(a,c),Jg(a,s,o)},enqueueReplaceState:function(a,i,e){a=a._reactInternals;var o=Hg(),s=Ig(a),c=zg(o,s);c.tag=1,c.payload=i,e!=null&&(c.callback=e),Ag(a,c),Jg(a,s,o)},enqueueForceUpdate:function(a,i){a=a._reactInternals;var e=Hg(),o=Ig(a),s=zg(e,o);s.tag=2,i!=null&&(s.callback=i),Ag(a,s),Jg(a,o,e)}};function Lg(a,i,e,o,s,c,d){return a=a.stateNode,typeof a.shouldComponentUpdate=="function"?a.shouldComponentUpdate(o,c,d):i.prototype&&i.prototype.isPureReactComponent?!Je(e,o)||!Je(s,c):!0}function Mg(a,i,e){var o=!1,s=Cf,c=i.contextType;return typeof c=="object"&&c!==null?c=vg(c):(s=Ff(i)?Df:M.current,o=i.contextTypes,c=(o=o!=null)?Ef(a,s):Cf),i=new i(e,c),a.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,i.updater=Kg,a.stateNode=i,i._reactInternals=a,o&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=s,a.__reactInternalMemoizedMaskedChildContext=c),i}function Ng(a,i,e,o){a=i.state,typeof i.componentWillReceiveProps=="function"&&i.componentWillReceiveProps(e,o),typeof i.UNSAFE_componentWillReceiveProps=="function"&&i.UNSAFE_componentWillReceiveProps(e,o),i.state!==a&&Kg.enqueueReplaceState(i,i.state,null)}function Og(a,i,e,o){var s=a.stateNode;s.props=e,s.state=a.memoizedState,s.refs=Fg,xg(a);var c=i.contextType;typeof c=="object"&&c!==null?s.context=vg(c):(c=Ff(i)?Df:M.current,s.context=Ef(a,c)),Cg(a,e,s,o),s.state=a.memoizedState,c=i.getDerivedStateFromProps,typeof c=="function"&&(Gg(a,i,c,e),s.state=a.memoizedState),typeof i.getDerivedStateFromProps=="function"||typeof s.getSnapshotBeforeUpdate=="function"||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(i=s.state,typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount(),i!==s.state&&Kg.enqueueReplaceState(s,s.state,null),Cg(a,e,s,o),s.state=a.memoizedState),typeof s.componentDidMount=="function"&&(a.flags|=4)}var Pg=Array.isArray;function Qg(a,i,e){if(a=e.ref,a!==null&&typeof a!="function"&&typeof a!="object"){if(e._owner){if(e=e._owner,e){if(e.tag!==1)throw Error(y(309));var o=e.stateNode}if(!o)throw Error(y(147,a));var s=""+a;return i!==null&&i.ref!==null&&typeof i.ref=="function"&&i.ref._stringRef===s?i.ref:(i=function(c){var d=o.refs;d===Fg&&(d=o.refs={}),c===null?delete d[s]:d[s]=c},i._stringRef=s,i)}if(typeof a!="string")throw Error(y(284));if(!e._owner)throw Error(y(290,a))}return a}function Rg(a,i){if(a.type!=="textarea")throw Error(y(31,Object.prototype.toString.call(i)==="[object Object]"?"object with keys {"+Object.keys(i).join(", ")+"}":i))}function Sg(a){function i(it,nt){if(a){var ot=it.lastEffect;ot!==null?(ot.nextEffect=nt,it.lastEffect=nt):it.firstEffect=it.lastEffect=nt,nt.nextEffect=null,nt.flags=8}}function e(it,nt){if(!a)return null;for(;nt!==null;)i(it,nt),nt=nt.sibling;return null}function o(it,nt){for(it=new Map;nt!==null;)nt.key!==null?it.set(nt.key,nt):it.set(nt.index,nt),nt=nt.sibling;return it}function s(it,nt){return it=Tg(it,nt),it.index=0,it.sibling=null,it}function c(it,nt,ot){return it.index=ot,a?(ot=it.alternate,ot!==null?(ot=ot.index,ot<nt?(it.flags=2,nt):ot):(it.flags=2,nt)):nt}function d(it){return a&&it.alternate===null&&(it.flags=2),it}function _(it,nt,ot,at){return nt===null||nt.tag!==6?(nt=Ug(ot,it.mode,at),nt.return=it,nt):(nt=s(nt,ot),nt.return=it,nt)}function b(it,nt,ot,at){return nt!==null&&nt.elementType===ot.type?(at=s(nt,ot.props),at.ref=Qg(it,nt,ot),at.return=it,at):(at=Vg(ot.type,ot.key,ot.props,null,it.mode,at),at.ref=Qg(it,nt,ot),at.return=it,at)}function k(it,nt,ot,at){return nt===null||nt.tag!==4||nt.stateNode.containerInfo!==ot.containerInfo||nt.stateNode.implementation!==ot.implementation?(nt=Wg(ot,it.mode,at),nt.return=it,nt):(nt=s(nt,ot.children||[]),nt.return=it,nt)}function j(it,nt,ot,at,st){return nt===null||nt.tag!==7?(nt=Xg(ot,it.mode,at,st),nt.return=it,nt):(nt=s(nt,ot),nt.return=it,nt)}function $(it,nt,ot){if(typeof nt=="string"||typeof nt=="number")return nt=Ug(""+nt,it.mode,ot),nt.return=it,nt;if(typeof nt=="object"&&nt!==null){switch(nt.$$typeof){case sa:return ot=Vg(nt.type,nt.key,nt.props,null,it.mode,ot),ot.ref=Qg(it,null,nt),ot.return=it,ot;case ta:return nt=Wg(nt,it.mode,ot),nt.return=it,nt}if(Pg(nt)||La(nt))return nt=Xg(nt,it.mode,ot,null),nt.return=it,nt;Rg(it,nt)}return null}function _e(it,nt,ot,at){var st=nt!==null?nt.key:null;if(typeof ot=="string"||typeof ot=="number")return st!==null?null:_(it,nt,""+ot,at);if(typeof ot=="object"&&ot!==null){switch(ot.$$typeof){case sa:return ot.key===st?ot.type===ua?j(it,nt,ot.props.children,at,st):b(it,nt,ot,at):null;case ta:return ot.key===st?k(it,nt,ot,at):null}if(Pg(ot)||La(ot))return st!==null?null:j(it,nt,ot,at,null);Rg(it,ot)}return null}function et(it,nt,ot,at,st){if(typeof at=="string"||typeof at=="number")return it=it.get(ot)||null,_(nt,it,""+at,st);if(typeof at=="object"&&at!==null){switch(at.$$typeof){case sa:return it=it.get(at.key===null?ot:at.key)||null,at.type===ua?j(nt,it,at.props.children,st,at.key):b(nt,it,at,st);case ta:return it=it.get(at.key===null?ot:at.key)||null,k(nt,it,at,st)}if(Pg(at)||La(at))return it=it.get(ot)||null,j(nt,it,at,st,null);Rg(nt,at)}return null}function tt(it,nt,ot,at){for(var st=null,ut=null,ft=nt,lt=nt=0,ht=null;ft!==null&&lt<ot.length;lt++){ft.index>lt?(ht=ft,ft=null):ht=ft.sibling;var pt=_e(it,ft,ot[lt],at);if(pt===null){ft===null&&(ft=ht);break}a&&ft&&pt.alternate===null&&i(it,ft),nt=c(pt,nt,lt),ut===null?st=pt:ut.sibling=pt,ut=pt,ft=ht}if(lt===ot.length)return e(it,ft),st;if(ft===null){for(;lt<ot.length;lt++)ft=$(it,ot[lt],at),ft!==null&&(nt=c(ft,nt,lt),ut===null?st=ft:ut.sibling=ft,ut=ft);return st}for(ft=o(it,ft);lt<ot.length;lt++)ht=et(ft,it,lt,ot[lt],at),ht!==null&&(a&&ht.alternate!==null&&ft.delete(ht.key===null?lt:ht.key),nt=c(ht,nt,lt),ut===null?st=ht:ut.sibling=ht,ut=ht);return a&&ft.forEach(function(mt){return i(it,mt)}),st}function rt(it,nt,ot,at){var st=La(ot);if(typeof st!="function")throw Error(y(150));if(ot=st.call(ot),ot==null)throw Error(y(151));for(var ut=st=null,ft=nt,lt=nt=0,ht=null,pt=ot.next();ft!==null&&!pt.done;lt++,pt=ot.next()){ft.index>lt?(ht=ft,ft=null):ht=ft.sibling;var mt=_e(it,ft,pt.value,at);if(mt===null){ft===null&&(ft=ht);break}a&&ft&&mt.alternate===null&&i(it,ft),nt=c(mt,nt,lt),ut===null?st=mt:ut.sibling=mt,ut=mt,ft=ht}if(pt.done)return e(it,ft),st;if(ft===null){for(;!pt.done;lt++,pt=ot.next())pt=$(it,pt.value,at),pt!==null&&(nt=c(pt,nt,lt),ut===null?st=pt:ut.sibling=pt,ut=pt);return st}for(ft=o(it,ft);!pt.done;lt++,pt=ot.next())pt=et(ft,it,lt,pt.value,at),pt!==null&&(a&&pt.alternate!==null&&ft.delete(pt.key===null?lt:pt.key),nt=c(pt,nt,lt),ut===null?st=pt:ut.sibling=pt,ut=pt);return a&&ft.forEach(function(dt){return i(it,dt)}),st}return function(it,nt,ot,at){var st=typeof ot=="object"&&ot!==null&&ot.type===ua&&ot.key===null;st&&(ot=ot.props.children);var ut=typeof ot=="object"&&ot!==null;if(ut)switch(ot.$$typeof){case sa:e:{for(ut=ot.key,st=nt;st!==null;){if(st.key===ut){switch(st.tag){case 7:if(ot.type===ua){e(it,st.sibling),nt=s(st,ot.props.children),nt.return=it,it=nt;break e}break;default:if(st.elementType===ot.type){e(it,st.sibling),nt=s(st,ot.props),nt.ref=Qg(it,st,ot),nt.return=it,it=nt;break e}}e(it,st);break}else i(it,st);st=st.sibling}ot.type===ua?(nt=Xg(ot.props.children,it.mode,at,ot.key),nt.return=it,it=nt):(at=Vg(ot.type,ot.key,ot.props,null,it.mode,at),at.ref=Qg(it,nt,ot),at.return=it,it=at)}return d(it);case ta:e:{for(st=ot.key;nt!==null;){if(nt.key===st)if(nt.tag===4&&nt.stateNode.containerInfo===ot.containerInfo&&nt.stateNode.implementation===ot.implementation){e(it,nt.sibling),nt=s(nt,ot.children||[]),nt.return=it,it=nt;break e}else{e(it,nt);break}else i(it,nt);nt=nt.sibling}nt=Wg(ot,it.mode,at),nt.return=it,it=nt}return d(it)}if(typeof ot=="string"||typeof ot=="number")return ot=""+ot,nt!==null&&nt.tag===6?(e(it,nt.sibling),nt=s(nt,ot),nt.return=it,it=nt):(e(it,nt),nt=Ug(ot,it.mode,at),nt.return=it,it=nt),d(it);if(Pg(ot))return tt(it,nt,ot,at);if(La(ot))return rt(it,nt,ot,at);if(ut&&Rg(it,ot),typeof ot=="undefined"&&!st)switch(it.tag){case 1:case 22:case 0:case 11:case 15:throw Error(y(152,Ra(it.type)||"Component"))}return e(it,nt)}}var Yg=Sg(!0),Zg=Sg(!1),$g={},ah=Bf($g),bh=Bf($g),ch=Bf($g);function dh(a){if(a===$g)throw Error(y(174));return a}function eh(a,i){switch(I(ch,i),I(bh,a),I(ah,$g),a=i.nodeType,a){case 9:case 11:i=(i=i.documentElement)?i.namespaceURI:mb(null,"");break;default:a=a===8?i.parentNode:i,i=a.namespaceURI||null,a=a.tagName,i=mb(i,a)}H(ah),I(ah,i)}function fh(){H(ah),H(bh),H(ch)}function gh(a){dh(ch.current);var i=dh(ah.current),e=mb(i,a.type);i!==e&&(I(bh,a),I(ah,e))}function hh(a){bh.current===a&&(H(ah),H(bh))}var P=Bf(0);function ih(a){for(var i=a;i!==null;){if(i.tag===13){var e=i.memoizedState;if(e!==null&&(e=e.dehydrated,e===null||e.data==="$?"||e.data==="$!"))return i}else if(i.tag===19&&i.memoizedProps.revealOrder!==void 0){if((i.flags&64)!==0)return i}else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===a)break;for(;i.sibling===null;){if(i.return===null||i.return===a)return null;i=i.return}i.sibling.return=i.return,i=i.sibling}return null}var jh=null,kh=null,lh=!1;function mh(a,i){var e=nh(5,null,null,0);e.elementType="DELETED",e.type="DELETED",e.stateNode=i,e.return=a,e.flags=8,a.lastEffect!==null?(a.lastEffect.nextEffect=e,a.lastEffect=e):a.firstEffect=a.lastEffect=e}function oh(a,i){switch(a.tag){case 5:var e=a.type;return i=i.nodeType!==1||e.toLowerCase()!==i.nodeName.toLowerCase()?null:i,i!==null?(a.stateNode=i,!0):!1;case 6:return i=a.pendingProps===""||i.nodeType!==3?null:i,i!==null?(a.stateNode=i,!0):!1;case 13:return!1;default:return!1}}function ph(a){if(lh){var i=kh;if(i){var e=i;if(!oh(a,i)){if(i=rf(e.nextSibling),!i||!oh(a,i)){a.flags=a.flags&-1025|2,lh=!1,jh=a;return}mh(jh,e)}jh=a,kh=rf(i.firstChild)}else a.flags=a.flags&-1025|2,lh=!1,jh=a}}function qh(a){for(a=a.return;a!==null&&a.tag!==5&&a.tag!==3&&a.tag!==13;)a=a.return;jh=a}function rh(a){if(a!==jh)return!1;if(!lh)return qh(a),lh=!0,!1;var i=a.type;if(a.tag!==5||i!=="head"&&i!=="body"&&!nf(i,a.memoizedProps))for(i=kh;i;)mh(a,i),i=rf(i.nextSibling);if(qh(a),a.tag===13){if(a=a.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(y(317));e:{for(a=a.nextSibling,i=0;a;){if(a.nodeType===8){var e=a.data;if(e==="/$"){if(i===0){kh=rf(a.nextSibling);break e}i--}else e!=="$"&&e!=="$!"&&e!=="$?"||i++}a=a.nextSibling}kh=null}}else kh=jh?rf(a.stateNode.nextSibling):null;return!0}function sh(){kh=jh=null,lh=!1}var th=[];function uh(){for(var a=0;a<th.length;a++)th[a]._workInProgressVersionPrimary=null;th.length=0}var vh=ra.ReactCurrentDispatcher,wh=ra.ReactCurrentBatchConfig,xh=0,R=null,S=null,T=null,yh=!1,zh=!1;function Ah(){throw Error(y(321))}function Bh(a,i){if(i===null)return!1;for(var e=0;e<i.length&&e<a.length;e++)if(!He(a[e],i[e]))return!1;return!0}function Ch(a,i,e,o,s,c){if(xh=c,R=i,i.memoizedState=null,i.updateQueue=null,i.lanes=0,vh.current=a===null||a.memoizedState===null?Dh:Eh,a=e(o,s),zh){c=0;do{if(zh=!1,!(25>c))throw Error(y(301));c+=1,T=S=null,i.updateQueue=null,vh.current=Fh,a=e(o,s)}while(zh)}if(vh.current=Gh,i=S!==null&&S.next!==null,xh=0,T=S=R=null,yh=!1,i)throw Error(y(300));return a}function Hh(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return T===null?R.memoizedState=T=a:T=T.next=a,T}function Ih(){if(S===null){var a=R.alternate;a=a!==null?a.memoizedState:null}else a=S.next;var i=T===null?R.memoizedState:T.next;if(i!==null)T=i,S=a;else{if(a===null)throw Error(y(310));S=a,a={memoizedState:S.memoizedState,baseState:S.baseState,baseQueue:S.baseQueue,queue:S.queue,next:null},T===null?R.memoizedState=T=a:T=T.next=a}return T}function Jh(a,i){return typeof i=="function"?i(a):i}function Kh(a){var i=Ih(),e=i.queue;if(e===null)throw Error(y(311));e.lastRenderedReducer=a;var o=S,s=o.baseQueue,c=e.pending;if(c!==null){if(s!==null){var d=s.next;s.next=c.next,c.next=d}o.baseQueue=s=c,e.pending=null}if(s!==null){s=s.next,o=o.baseState;var _=d=c=null,b=s;do{var k=b.lane;if((xh&k)===k)_!==null&&(_=_.next={lane:0,action:b.action,eagerReducer:b.eagerReducer,eagerState:b.eagerState,next:null}),o=b.eagerReducer===a?b.eagerState:a(o,b.action);else{var j={lane:k,action:b.action,eagerReducer:b.eagerReducer,eagerState:b.eagerState,next:null};_===null?(d=_=j,c=o):_=_.next=j,R.lanes|=k,Dg|=k}b=b.next}while(b!==null&&b!==s);_===null?c=o:_.next=d,He(o,i.memoizedState)||(ug=!0),i.memoizedState=o,i.baseState=c,i.baseQueue=_,e.lastRenderedState=o}return[i.memoizedState,e.dispatch]}function Lh(a){var i=Ih(),e=i.queue;if(e===null)throw Error(y(311));e.lastRenderedReducer=a;var o=e.dispatch,s=e.pending,c=i.memoizedState;if(s!==null){e.pending=null;var d=s=s.next;do c=a(c,d.action),d=d.next;while(d!==s);He(c,i.memoizedState)||(ug=!0),i.memoizedState=c,i.baseQueue===null&&(i.baseState=c),e.lastRenderedState=c}return[c,o]}function Mh(a,i,e){var o=i._getVersion;o=o(i._source);var s=i._workInProgressVersionPrimary;if(s!==null?a=s===o:(a=a.mutableReadLanes,(a=(xh&a)===a)&&(i._workInProgressVersionPrimary=o,th.push(i))),a)return e(i._source);throw th.push(i),Error(y(350))}function Nh(a,i,e,o){var s=U;if(s===null)throw Error(y(349));var c=i._getVersion,d=c(i._source),_=vh.current,b=_.useState(function(){return Mh(s,i,e)}),k=b[1],j=b[0];b=T;var $=a.memoizedState,_e=$.refs,et=_e.getSnapshot,tt=$.source;$=$.subscribe;var rt=R;return a.memoizedState={refs:_e,source:i,subscribe:o},_.useEffect(function(){_e.getSnapshot=e,_e.setSnapshot=k;var it=c(i._source);if(!He(d,it)){it=e(i._source),He(j,it)||(k(it),it=Ig(rt),s.mutableReadLanes|=it&s.pendingLanes),it=s.mutableReadLanes,s.entangledLanes|=it;for(var nt=s.entanglements,ot=it;0<ot;){var at=31-Vc(ot),st=1<<at;nt[at]|=it,ot&=~st}}},[e,i,o]),_.useEffect(function(){return o(i._source,function(){var it=_e.getSnapshot,nt=_e.setSnapshot;try{nt(it(i._source));var ot=Ig(rt);s.mutableReadLanes|=ot&s.pendingLanes}catch(at){nt(function(){throw at})}})},[i,o]),He(et,e)&&He(tt,i)&&He($,o)||(a={pending:null,dispatch:null,lastRenderedReducer:Jh,lastRenderedState:j},a.dispatch=k=Oh.bind(null,R,a),b.queue=a,b.baseQueue=null,j=Mh(s,i,e),b.memoizedState=b.baseState=j),j}function Ph(a,i,e){var o=Ih();return Nh(o,a,i,e)}function Qh(a){var i=Hh();return typeof a=="function"&&(a=a()),i.memoizedState=i.baseState=a,a=i.queue={pending:null,dispatch:null,lastRenderedReducer:Jh,lastRenderedState:a},a=a.dispatch=Oh.bind(null,R,a),[i.memoizedState,a]}function Rh(a,i,e,o){return a={tag:a,create:i,destroy:e,deps:o,next:null},i=R.updateQueue,i===null?(i={lastEffect:null},R.updateQueue=i,i.lastEffect=a.next=a):(e=i.lastEffect,e===null?i.lastEffect=a.next=a:(o=e.next,e.next=a,a.next=o,i.lastEffect=a)),a}function Sh(a){var i=Hh();return a={current:a},i.memoizedState=a}function Th(){return Ih().memoizedState}function Uh(a,i,e,o){var s=Hh();R.flags|=a,s.memoizedState=Rh(1|i,e,void 0,o===void 0?null:o)}function Vh(a,i,e,o){var s=Ih();o=o===void 0?null:o;var c=void 0;if(S!==null){var d=S.memoizedState;if(c=d.destroy,o!==null&&Bh(o,d.deps)){Rh(i,e,c,o);return}}R.flags|=a,s.memoizedState=Rh(1|i,e,c,o)}function Wh(a,i){return Uh(516,4,a,i)}function Xh(a,i){return Vh(516,4,a,i)}function Yh(a,i){return Vh(4,2,a,i)}function Zh(a,i){if(typeof i=="function")return a=a(),i(a),function(){i(null)};if(i!=null)return a=a(),i.current=a,function(){i.current=null}}function $h(a,i,e){return e=e!=null?e.concat([a]):null,Vh(4,2,Zh.bind(null,i,a),e)}function ai(){}function bi(a,i){var e=Ih();i=i===void 0?null:i;var o=e.memoizedState;return o!==null&&i!==null&&Bh(i,o[1])?o[0]:(e.memoizedState=[a,i],a)}function ci(a,i){var e=Ih();i=i===void 0?null:i;var o=e.memoizedState;return o!==null&&i!==null&&Bh(i,o[1])?o[0]:(a=a(),e.memoizedState=[a,i],a)}function di(a,i){var e=eg();gg(98>e?98:e,function(){a(!0)}),gg(97<e?97:e,function(){var o=wh.transition;wh.transition=1;try{a(!1),i()}finally{wh.transition=o}})}function Oh(a,i,e){var o=Hg(),s=Ig(a),c={lane:s,action:e,eagerReducer:null,eagerState:null,next:null},d=i.pending;if(d===null?c.next=c:(c.next=d.next,d.next=c),i.pending=c,d=a.alternate,a===R||d!==null&&d===R)zh=yh=!0;else{if(a.lanes===0&&(d===null||d.lanes===0)&&(d=i.lastRenderedReducer,d!==null))try{var _=i.lastRenderedState,b=d(_,e);if(c.eagerReducer=d,c.eagerState=b,He(b,_))return}catch{}finally{}Jg(a,s,o)}}var Gh={readContext:vg,useCallback:Ah,useContext:Ah,useEffect:Ah,useImperativeHandle:Ah,useLayoutEffect:Ah,useMemo:Ah,useReducer:Ah,useRef:Ah,useState:Ah,useDebugValue:Ah,useDeferredValue:Ah,useTransition:Ah,useMutableSource:Ah,useOpaqueIdentifier:Ah,unstable_isNewReconciler:!1},Dh={readContext:vg,useCallback:function(a,i){return Hh().memoizedState=[a,i===void 0?null:i],a},useContext:vg,useEffect:Wh,useImperativeHandle:function(a,i,e){return e=e!=null?e.concat([a]):null,Uh(4,2,Zh.bind(null,i,a),e)},useLayoutEffect:function(a,i){return Uh(4,2,a,i)},useMemo:function(a,i){var e=Hh();return i=i===void 0?null:i,a=a(),e.memoizedState=[a,i],a},useReducer:function(a,i,e){var o=Hh();return i=e!==void 0?e(i):i,o.memoizedState=o.baseState=i,a=o.queue={pending:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:i},a=a.dispatch=Oh.bind(null,R,a),[o.memoizedState,a]},useRef:Sh,useState:Qh,useDebugValue:ai,useDeferredValue:function(a){var i=Qh(a),e=i[0],o=i[1];return Wh(function(){var s=wh.transition;wh.transition=1;try{o(a)}finally{wh.transition=s}},[a]),e},useTransition:function(){var a=Qh(!1),i=a[0];return a=di.bind(null,a[1]),Sh(a),[a,i]},useMutableSource:function(a,i,e){var o=Hh();return o.memoizedState={refs:{getSnapshot:i,setSnapshot:null},source:a,subscribe:e},Nh(o,a,i,e)},useOpaqueIdentifier:function(){if(lh){var a=!1,i=uf(function(){throw a||(a=!0,e("r:"+(tf++).toString(36))),Error(y(355))}),e=Qh(i)[1];return(R.mode&2)===0&&(R.flags|=516,Rh(5,function(){e("r:"+(tf++).toString(36))},void 0,null)),i}return i="r:"+(tf++).toString(36),Qh(i),i},unstable_isNewReconciler:!1},Eh={readContext:vg,useCallback:bi,useContext:vg,useEffect:Xh,useImperativeHandle:$h,useLayoutEffect:Yh,useMemo:ci,useReducer:Kh,useRef:Th,useState:function(){return Kh(Jh)},useDebugValue:ai,useDeferredValue:function(a){var i=Kh(Jh),e=i[0],o=i[1];return Xh(function(){var s=wh.transition;wh.transition=1;try{o(a)}finally{wh.transition=s}},[a]),e},useTransition:function(){var a=Kh(Jh)[0];return[Th().current,a]},useMutableSource:Ph,useOpaqueIdentifier:function(){return Kh(Jh)[0]},unstable_isNewReconciler:!1},Fh={readContext:vg,useCallback:bi,useContext:vg,useEffect:Xh,useImperativeHandle:$h,useLayoutEffect:Yh,useMemo:ci,useReducer:Lh,useRef:Th,useState:function(){return Lh(Jh)},useDebugValue:ai,useDeferredValue:function(a){var i=Lh(Jh),e=i[0],o=i[1];return Xh(function(){var s=wh.transition;wh.transition=1;try{o(a)}finally{wh.transition=s}},[a]),e},useTransition:function(){var a=Lh(Jh)[0];return[Th().current,a]},useMutableSource:Ph,useOpaqueIdentifier:function(){return Lh(Jh)[0]},unstable_isNewReconciler:!1},ei=ra.ReactCurrentOwner,ug=!1;function fi(a,i,e,o){i.child=a===null?Zg(i,null,e,o):Yg(i,a.child,e,o)}function gi(a,i,e,o,s){e=e.render;var c=i.ref;return tg(i,s),o=Ch(a,i,e,o,c,s),a!==null&&!ug?(i.updateQueue=a.updateQueue,i.flags&=-517,a.lanes&=~s,hi(a,i,s)):(i.flags|=1,fi(a,i,o,s),i.child)}function ii(a,i,e,o,s,c){if(a===null){var d=e.type;return typeof d=="function"&&!ji(d)&&d.defaultProps===void 0&&e.compare===null&&e.defaultProps===void 0?(i.tag=15,i.type=d,ki(a,i,d,o,s,c)):(a=Vg(e.type,null,o,i,i.mode,c),a.ref=i.ref,a.return=i,i.child=a)}return d=a.child,(s&c)===0&&(s=d.memoizedProps,e=e.compare,e=e!==null?e:Je,e(s,o)&&a.ref===i.ref)?hi(a,i,c):(i.flags|=1,a=Tg(d,o),a.ref=i.ref,a.return=i,i.child=a)}function ki(a,i,e,o,s,c){if(a!==null&&Je(a.memoizedProps,o)&&a.ref===i.ref)if(ug=!1,(c&s)!==0)(a.flags&16384)!==0&&(ug=!0);else return i.lanes=a.lanes,hi(a,i,c);return li(a,i,e,o,c)}function mi(a,i,e){var o=i.pendingProps,s=o.children,c=a!==null?a.memoizedState:null;if(o.mode==="hidden"||o.mode==="unstable-defer-without-hiding")if((i.mode&4)===0)i.memoizedState={baseLanes:0},ni(i,e);else if((e&1073741824)!==0)i.memoizedState={baseLanes:0},ni(i,c!==null?c.baseLanes:e);else return a=c!==null?c.baseLanes|e:e,i.lanes=i.childLanes=1073741824,i.memoizedState={baseLanes:a},ni(i,a),null;else c!==null?(o=c.baseLanes|e,i.memoizedState=null):o=e,ni(i,o);return fi(a,i,s,e),i.child}function oi(a,i){var e=i.ref;(a===null&&e!==null||a!==null&&a.ref!==e)&&(i.flags|=128)}function li(a,i,e,o,s){var c=Ff(e)?Df:M.current;return c=Ef(i,c),tg(i,s),e=Ch(a,i,e,o,c,s),a!==null&&!ug?(i.updateQueue=a.updateQueue,i.flags&=-517,a.lanes&=~s,hi(a,i,s)):(i.flags|=1,fi(a,i,e,s),i.child)}function pi(a,i,e,o,s){if(Ff(e)){var c=!0;Jf(i)}else c=!1;if(tg(i,s),i.stateNode===null)a!==null&&(a.alternate=null,i.alternate=null,i.flags|=2),Mg(i,e,o),Og(i,e,o,s),o=!0;else if(a===null){var d=i.stateNode,_=i.memoizedProps;d.props=_;var b=d.context,k=e.contextType;typeof k=="object"&&k!==null?k=vg(k):(k=Ff(e)?Df:M.current,k=Ef(i,k));var j=e.getDerivedStateFromProps,$=typeof j=="function"||typeof d.getSnapshotBeforeUpdate=="function";$||typeof d.UNSAFE_componentWillReceiveProps!="function"&&typeof d.componentWillReceiveProps!="function"||(_!==o||b!==k)&&Ng(i,d,o,k),wg=!1;var _e=i.memoizedState;d.state=_e,Cg(i,o,d,s),b=i.memoizedState,_!==o||_e!==b||N.current||wg?(typeof j=="function"&&(Gg(i,e,j,o),b=i.memoizedState),(_=wg||Lg(i,e,_,o,_e,b,k))?($||typeof d.UNSAFE_componentWillMount!="function"&&typeof d.componentWillMount!="function"||(typeof d.componentWillMount=="function"&&d.componentWillMount(),typeof d.UNSAFE_componentWillMount=="function"&&d.UNSAFE_componentWillMount()),typeof d.componentDidMount=="function"&&(i.flags|=4)):(typeof d.componentDidMount=="function"&&(i.flags|=4),i.memoizedProps=o,i.memoizedState=b),d.props=o,d.state=b,d.context=k,o=_):(typeof d.componentDidMount=="function"&&(i.flags|=4),o=!1)}else{d=i.stateNode,yg(a,i),_=i.memoizedProps,k=i.type===i.elementType?_:lg(i.type,_),d.props=k,$=i.pendingProps,_e=d.context,b=e.contextType,typeof b=="object"&&b!==null?b=vg(b):(b=Ff(e)?Df:M.current,b=Ef(i,b));var et=e.getDerivedStateFromProps;(j=typeof et=="function"||typeof d.getSnapshotBeforeUpdate=="function")||typeof d.UNSAFE_componentWillReceiveProps!="function"&&typeof d.componentWillReceiveProps!="function"||(_!==$||_e!==b)&&Ng(i,d,o,b),wg=!1,_e=i.memoizedState,d.state=_e,Cg(i,o,d,s);var tt=i.memoizedState;_!==$||_e!==tt||N.current||wg?(typeof et=="function"&&(Gg(i,e,et,o),tt=i.memoizedState),(k=wg||Lg(i,e,k,o,_e,tt,b))?(j||typeof d.UNSAFE_componentWillUpdate!="function"&&typeof d.componentWillUpdate!="function"||(typeof d.componentWillUpdate=="function"&&d.componentWillUpdate(o,tt,b),typeof d.UNSAFE_componentWillUpdate=="function"&&d.UNSAFE_componentWillUpdate(o,tt,b)),typeof d.componentDidUpdate=="function"&&(i.flags|=4),typeof d.getSnapshotBeforeUpdate=="function"&&(i.flags|=256)):(typeof d.componentDidUpdate!="function"||_===a.memoizedProps&&_e===a.memoizedState||(i.flags|=4),typeof d.getSnapshotBeforeUpdate!="function"||_===a.memoizedProps&&_e===a.memoizedState||(i.flags|=256),i.memoizedProps=o,i.memoizedState=tt),d.props=o,d.state=tt,d.context=b,o=k):(typeof d.componentDidUpdate!="function"||_===a.memoizedProps&&_e===a.memoizedState||(i.flags|=4),typeof d.getSnapshotBeforeUpdate!="function"||_===a.memoizedProps&&_e===a.memoizedState||(i.flags|=256),o=!1)}return qi(a,i,e,o,c,s)}function qi(a,i,e,o,s,c){oi(a,i);var d=(i.flags&64)!==0;if(!o&&!d)return s&&Kf(i,e,!1),hi(a,i,c);o=i.stateNode,ei.current=i;var _=d&&typeof e.getDerivedStateFromError!="function"?null:o.render();return i.flags|=1,a!==null&&d?(i.child=Yg(i,a.child,null,c),i.child=Yg(i,null,_,c)):fi(a,i,_,c),i.memoizedState=o.state,s&&Kf(i,e,!0),i.child}function ri(a){var i=a.stateNode;i.pendingContext?Hf(a,i.pendingContext,i.pendingContext!==i.context):i.context&&Hf(a,i.context,!1),eh(a,i.containerInfo)}var si={dehydrated:null,retryLane:0};function ti(a,i,e){var o=i.pendingProps,s=P.current,c=!1,d;return(d=(i.flags&64)!==0)||(d=a!==null&&a.memoizedState===null?!1:(s&2)!==0),d?(c=!0,i.flags&=-65):a!==null&&a.memoizedState===null||o.fallback===void 0||o.unstable_avoidThisFallback===!0||(s|=1),I(P,s&1),a===null?(o.fallback!==void 0&&ph(i),a=o.children,s=o.fallback,c?(a=ui(i,a,s,e),i.child.memoizedState={baseLanes:e},i.memoizedState=si,a):typeof o.unstable_expectedLoadTime=="number"?(a=ui(i,a,s,e),i.child.memoizedState={baseLanes:e},i.memoizedState=si,i.lanes=33554432,a):(e=vi({mode:"visible",children:a},i.mode,e,null),e.return=i,i.child=e)):a.memoizedState!==null?c?(o=wi(a,i,o.children,o.fallback,e),c=i.child,s=a.child.memoizedState,c.memoizedState=s===null?{baseLanes:e}:{baseLanes:s.baseLanes|e},c.childLanes=a.childLanes&~e,i.memoizedState=si,o):(e=xi(a,i,o.children,e),i.memoizedState=null,e):c?(o=wi(a,i,o.children,o.fallback,e),c=i.child,s=a.child.memoizedState,c.memoizedState=s===null?{baseLanes:e}:{baseLanes:s.baseLanes|e},c.childLanes=a.childLanes&~e,i.memoizedState=si,o):(e=xi(a,i,o.children,e),i.memoizedState=null,e)}function ui(a,i,e,o){var s=a.mode,c=a.child;return i={mode:"hidden",children:i},(s&2)===0&&c!==null?(c.childLanes=0,c.pendingProps=i):c=vi(i,s,0,null),e=Xg(e,s,o,null),c.return=a,e.return=a,c.sibling=e,a.child=c,e}function xi(a,i,e,o){var s=a.child;return a=s.sibling,e=Tg(s,{mode:"visible",children:e}),(i.mode&2)===0&&(e.lanes=o),e.return=i,e.sibling=null,a!==null&&(a.nextEffect=null,a.flags=8,i.firstEffect=i.lastEffect=a),i.child=e}function wi(a,i,e,o,s){var c=i.mode,d=a.child;a=d.sibling;var _={mode:"hidden",children:e};return(c&2)===0&&i.child!==d?(e=i.child,e.childLanes=0,e.pendingProps=_,d=e.lastEffect,d!==null?(i.firstEffect=e.firstEffect,i.lastEffect=d,d.nextEffect=null):i.firstEffect=i.lastEffect=null):e=Tg(d,_),a!==null?o=Tg(a,o):(o=Xg(o,c,s,null),o.flags|=2),o.return=i,e.return=i,e.sibling=o,i.child=e,o}function yi(a,i){a.lanes|=i;var e=a.alternate;e!==null&&(e.lanes|=i),sg(a.return,i)}function zi(a,i,e,o,s,c){var d=a.memoizedState;d===null?a.memoizedState={isBackwards:i,rendering:null,renderingStartTime:0,last:o,tail:e,tailMode:s,lastEffect:c}:(d.isBackwards=i,d.rendering=null,d.renderingStartTime=0,d.last=o,d.tail=e,d.tailMode=s,d.lastEffect=c)}function Ai(a,i,e){var o=i.pendingProps,s=o.revealOrder,c=o.tail;if(fi(a,i,o.children,e),o=P.current,(o&2)!==0)o=o&1|2,i.flags|=64;else{if(a!==null&&(a.flags&64)!==0)e:for(a=i.child;a!==null;){if(a.tag===13)a.memoizedState!==null&&yi(a,e);else if(a.tag===19)yi(a,e);else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===i)break e;for(;a.sibling===null;){if(a.return===null||a.return===i)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}o&=1}if(I(P,o),(i.mode&2)===0)i.memoizedState=null;else switch(s){case"forwards":for(e=i.child,s=null;e!==null;)a=e.alternate,a!==null&&ih(a)===null&&(s=e),e=e.sibling;e=s,e===null?(s=i.child,i.child=null):(s=e.sibling,e.sibling=null),zi(i,!1,s,e,c,i.lastEffect);break;case"backwards":for(e=null,s=i.child,i.child=null;s!==null;){if(a=s.alternate,a!==null&&ih(a)===null){i.child=s;break}a=s.sibling,s.sibling=e,e=s,s=a}zi(i,!0,e,null,c,i.lastEffect);break;case"together":zi(i,!1,null,null,void 0,i.lastEffect);break;default:i.memoizedState=null}return i.child}function hi(a,i,e){if(a!==null&&(i.dependencies=a.dependencies),Dg|=i.lanes,(e&i.childLanes)!==0){if(a!==null&&i.child!==a.child)throw Error(y(153));if(i.child!==null){for(a=i.child,e=Tg(a,a.pendingProps),i.child=e,e.return=i;a.sibling!==null;)a=a.sibling,e=e.sibling=Tg(a,a.pendingProps),e.return=i;e.sibling=null}return i.child}return null}var Bi,Ci,Di,Ei;Bi=function(a,i){for(var e=i.child;e!==null;){if(e.tag===5||e.tag===6)a.appendChild(e.stateNode);else if(e.tag!==4&&e.child!==null){e.child.return=e,e=e.child;continue}if(e===i)break;for(;e.sibling===null;){if(e.return===null||e.return===i)return;e=e.return}e.sibling.return=e.return,e=e.sibling}};Ci=function(){};Di=function(a,i,e,o){var s=a.memoizedProps;if(s!==o){a=i.stateNode,dh(ah.current);var c=null;switch(e){case"input":s=Ya(a,s),o=Ya(a,o),c=[];break;case"option":s=eb(a,s),o=eb(a,o),c=[];break;case"select":s=m$1({},s,{value:void 0}),o=m$1({},o,{value:void 0}),c=[];break;case"textarea":s=gb(a,s),o=gb(a,o),c=[];break;default:typeof s.onClick!="function"&&typeof o.onClick=="function"&&(a.onclick=jf)}vb(e,o);var d;e=null;for(k in s)if(!o.hasOwnProperty(k)&&s.hasOwnProperty(k)&&s[k]!=null)if(k==="style"){var _=s[k];for(d in _)_.hasOwnProperty(d)&&(e||(e={}),e[d]="")}else k!=="dangerouslySetInnerHTML"&&k!=="children"&&k!=="suppressContentEditableWarning"&&k!=="suppressHydrationWarning"&&k!=="autoFocus"&&(ca.hasOwnProperty(k)?c||(c=[]):(c=c||[]).push(k,null));for(k in o){var b=o[k];if(_=s!=null?s[k]:void 0,o.hasOwnProperty(k)&&b!==_&&(b!=null||_!=null))if(k==="style")if(_){for(d in _)!_.hasOwnProperty(d)||b&&b.hasOwnProperty(d)||(e||(e={}),e[d]="");for(d in b)b.hasOwnProperty(d)&&_[d]!==b[d]&&(e||(e={}),e[d]=b[d])}else e||(c||(c=[]),c.push(k,e)),e=b;else k==="dangerouslySetInnerHTML"?(b=b?b.__html:void 0,_=_?_.__html:void 0,b!=null&&_!==b&&(c=c||[]).push(k,b)):k==="children"?typeof b!="string"&&typeof b!="number"||(c=c||[]).push(k,""+b):k!=="suppressContentEditableWarning"&&k!=="suppressHydrationWarning"&&(ca.hasOwnProperty(k)?(b!=null&&k==="onScroll"&&G("scroll",a),c||_===b||(c=[])):typeof b=="object"&&b!==null&&b.$$typeof===Ga?b.toString():(c=c||[]).push(k,b))}e&&(c=c||[]).push("style",e);var k=c;(i.updateQueue=k)&&(i.flags|=4)}};Ei=function(a,i,e,o){e!==o&&(i.flags|=4)};function Fi(a,i){if(!lh)switch(a.tailMode){case"hidden":i=a.tail;for(var e=null;i!==null;)i.alternate!==null&&(e=i),i=i.sibling;e===null?a.tail=null:e.sibling=null;break;case"collapsed":e=a.tail;for(var o=null;e!==null;)e.alternate!==null&&(o=e),e=e.sibling;o===null?i||a.tail===null?a.tail=null:a.tail.sibling=null:o.sibling=null}}function Gi(a,i,e){var o=i.pendingProps;switch(i.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return null;case 1:return Ff(i.type)&&Gf(),null;case 3:return fh(),H(N),H(M),uh(),o=i.stateNode,o.pendingContext&&(o.context=o.pendingContext,o.pendingContext=null),(a===null||a.child===null)&&(rh(i)?i.flags|=4:o.hydrate||(i.flags|=256)),Ci(i),null;case 5:hh(i);var s=dh(ch.current);if(e=i.type,a!==null&&i.stateNode!=null)Di(a,i,e,o,s),a.ref!==i.ref&&(i.flags|=128);else{if(!o){if(i.stateNode===null)throw Error(y(166));return null}if(a=dh(ah.current),rh(i)){o=i.stateNode,e=i.type;var c=i.memoizedProps;switch(o[wf]=i,o[xf]=c,e){case"dialog":G("cancel",o),G("close",o);break;case"iframe":case"object":case"embed":G("load",o);break;case"video":case"audio":for(a=0;a<Xe.length;a++)G(Xe[a],o);break;case"source":G("error",o);break;case"img":case"image":case"link":G("error",o),G("load",o);break;case"details":G("toggle",o);break;case"input":Za(o,c),G("invalid",o);break;case"select":o._wrapperState={wasMultiple:!!c.multiple},G("invalid",o);break;case"textarea":hb(o,c),G("invalid",o)}vb(e,c),a=null;for(var d in c)c.hasOwnProperty(d)&&(s=c[d],d==="children"?typeof s=="string"?o.textContent!==s&&(a=["children",s]):typeof s=="number"&&o.textContent!==""+s&&(a=["children",""+s]):ca.hasOwnProperty(d)&&s!=null&&d==="onScroll"&&G("scroll",o));switch(e){case"input":Va(o),cb(o,c,!0);break;case"textarea":Va(o),jb(o);break;case"select":case"option":break;default:typeof c.onClick=="function"&&(o.onclick=jf)}o=a,i.updateQueue=o,o!==null&&(i.flags|=4)}else{switch(d=s.nodeType===9?s:s.ownerDocument,a===kb.html&&(a=lb(e)),a===kb.html?e==="script"?(a=d.createElement("div"),a.innerHTML="<script><\/script>",a=a.removeChild(a.firstChild)):typeof o.is=="string"?a=d.createElement(e,{is:o.is}):(a=d.createElement(e),e==="select"&&(d=a,o.multiple?d.multiple=!0:o.size&&(d.size=o.size))):a=d.createElementNS(a,e),a[wf]=i,a[xf]=o,Bi(a,i,!1,!1),i.stateNode=a,d=wb(e,o),e){case"dialog":G("cancel",a),G("close",a),s=o;break;case"iframe":case"object":case"embed":G("load",a),s=o;break;case"video":case"audio":for(s=0;s<Xe.length;s++)G(Xe[s],a);s=o;break;case"source":G("error",a),s=o;break;case"img":case"image":case"link":G("error",a),G("load",a),s=o;break;case"details":G("toggle",a),s=o;break;case"input":Za(a,o),s=Ya(a,o),G("invalid",a);break;case"option":s=eb(a,o);break;case"select":a._wrapperState={wasMultiple:!!o.multiple},s=m$1({},o,{value:void 0}),G("invalid",a);break;case"textarea":hb(a,o),s=gb(a,o),G("invalid",a);break;default:s=o}vb(e,s);var _=s;for(c in _)if(_.hasOwnProperty(c)){var b=_[c];c==="style"?tb(a,b):c==="dangerouslySetInnerHTML"?(b=b?b.__html:void 0,b!=null&&ob(a,b)):c==="children"?typeof b=="string"?(e!=="textarea"||b!=="")&&pb(a,b):typeof b=="number"&&pb(a,""+b):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(ca.hasOwnProperty(c)?b!=null&&c==="onScroll"&&G("scroll",a):b!=null&&qa(a,c,b,d))}switch(e){case"input":Va(a),cb(a,o,!1);break;case"textarea":Va(a),jb(a);break;case"option":o.value!=null&&a.setAttribute("value",""+Sa(o.value));break;case"select":a.multiple=!!o.multiple,c=o.value,c!=null?fb(a,!!o.multiple,c,!1):o.defaultValue!=null&&fb(a,!!o.multiple,o.defaultValue,!0);break;default:typeof s.onClick=="function"&&(a.onclick=jf)}mf(e,o)&&(i.flags|=4)}i.ref!==null&&(i.flags|=128)}return null;case 6:if(a&&i.stateNode!=null)Ei(a,i,a.memoizedProps,o);else{if(typeof o!="string"&&i.stateNode===null)throw Error(y(166));e=dh(ch.current),dh(ah.current),rh(i)?(o=i.stateNode,e=i.memoizedProps,o[wf]=i,o.nodeValue!==e&&(i.flags|=4)):(o=(e.nodeType===9?e:e.ownerDocument).createTextNode(o),o[wf]=i,i.stateNode=o)}return null;case 13:return H(P),o=i.memoizedState,(i.flags&64)!==0?(i.lanes=e,i):(o=o!==null,e=!1,a===null?i.memoizedProps.fallback!==void 0&&rh(i):e=a.memoizedState!==null,o&&!e&&(i.mode&2)!==0&&(a===null&&i.memoizedProps.unstable_avoidThisFallback!==!0||(P.current&1)!==0?V===0&&(V=3):((V===0||V===3)&&(V=4),U===null||(Dg&134217727)===0&&(Hi&134217727)===0||Ii(U,W))),(o||e)&&(i.flags|=4),null);case 4:return fh(),Ci(i),a===null&&cf(i.stateNode.containerInfo),null;case 10:return rg(i),null;case 17:return Ff(i.type)&&Gf(),null;case 19:if(H(P),o=i.memoizedState,o===null)return null;if(c=(i.flags&64)!==0,d=o.rendering,d===null)if(c)Fi(o,!1);else{if(V!==0||a!==null&&(a.flags&64)!==0)for(a=i.child;a!==null;){if(d=ih(a),d!==null){for(i.flags|=64,Fi(o,!1),c=d.updateQueue,c!==null&&(i.updateQueue=c,i.flags|=4),o.lastEffect===null&&(i.firstEffect=null),i.lastEffect=o.lastEffect,o=e,e=i.child;e!==null;)c=e,a=o,c.flags&=2,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null,d=c.alternate,d===null?(c.childLanes=0,c.lanes=a,c.child=null,c.memoizedProps=null,c.memoizedState=null,c.updateQueue=null,c.dependencies=null,c.stateNode=null):(c.childLanes=d.childLanes,c.lanes=d.lanes,c.child=d.child,c.memoizedProps=d.memoizedProps,c.memoizedState=d.memoizedState,c.updateQueue=d.updateQueue,c.type=d.type,a=d.dependencies,c.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),e=e.sibling;return I(P,P.current&1|2),i.child}a=a.sibling}o.tail!==null&&O()>Ji&&(i.flags|=64,c=!0,Fi(o,!1),i.lanes=33554432)}else{if(!c)if(a=ih(d),a!==null){if(i.flags|=64,c=!0,e=a.updateQueue,e!==null&&(i.updateQueue=e,i.flags|=4),Fi(o,!0),o.tail===null&&o.tailMode==="hidden"&&!d.alternate&&!lh)return i=i.lastEffect=o.lastEffect,i!==null&&(i.nextEffect=null),null}else 2*O()-o.renderingStartTime>Ji&&e!==1073741824&&(i.flags|=64,c=!0,Fi(o,!1),i.lanes=33554432);o.isBackwards?(d.sibling=i.child,i.child=d):(e=o.last,e!==null?e.sibling=d:i.child=d,o.last=d)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.lastEffect=i.lastEffect,o.renderingStartTime=O(),e.sibling=null,i=P.current,I(P,c?i&1|2:i&1),e):null;case 23:case 24:return Ki(),a!==null&&a.memoizedState!==null!=(i.memoizedState!==null)&&o.mode!=="unstable-defer-without-hiding"&&(i.flags|=4),null}throw Error(y(156,i.tag))}function Li(a){switch(a.tag){case 1:Ff(a.type)&&Gf();var i=a.flags;return i&4096?(a.flags=i&-4097|64,a):null;case 3:if(fh(),H(N),H(M),uh(),i=a.flags,(i&64)!==0)throw Error(y(285));return a.flags=i&-4097|64,a;case 5:return hh(a),null;case 13:return H(P),i=a.flags,i&4096?(a.flags=i&-4097|64,a):null;case 19:return H(P),null;case 4:return fh(),null;case 10:return rg(a),null;case 23:case 24:return Ki(),null;default:return null}}function Mi(a,i){try{var e="",o=i;do e+=Qa(o),o=o.return;while(o);var s=e}catch(c){s=`
  31. Error generating stack: `+c.message+`
  32. `+c.stack}return{value:a,source:i,stack:s}}function Ni(a,i){try{console.error(i.value)}catch(e){setTimeout(function(){throw e})}}var Oi=typeof WeakMap=="function"?WeakMap:Map;function Pi(a,i,e){e=zg(-1,e),e.tag=3,e.payload={element:null};var o=i.value;return e.callback=function(){Qi||(Qi=!0,Ri=o),Ni(a,i)},e}function Si(a,i,e){e=zg(-1,e),e.tag=3;var o=a.type.getDerivedStateFromError;if(typeof o=="function"){var s=i.value;e.payload=function(){return Ni(a,i),o(s)}}var c=a.stateNode;return c!==null&&typeof c.componentDidCatch=="function"&&(e.callback=function(){typeof o!="function"&&(Ti===null?Ti=new Set([this]):Ti.add(this),Ni(a,i));var d=i.stack;this.componentDidCatch(i.value,{componentStack:d!==null?d:""})}),e}var Ui=typeof WeakSet=="function"?WeakSet:Set;function Vi(a){var i=a.ref;if(i!==null)if(typeof i=="function")try{i(null)}catch(e){Wi(a,e)}else i.current=null}function Xi(a,i){switch(i.tag){case 0:case 11:case 15:case 22:return;case 1:if(i.flags&256&&a!==null){var e=a.memoizedProps,o=a.memoizedState;a=i.stateNode,i=a.getSnapshotBeforeUpdate(i.elementType===i.type?e:lg(i.type,e),o),a.__reactInternalSnapshotBeforeUpdate=i}return;case 3:i.flags&256&&qf(i.stateNode.containerInfo);return;case 5:case 6:case 4:case 17:return}throw Error(y(163))}function Yi(a,i,e){switch(e.tag){case 0:case 11:case 15:case 22:if(i=e.updateQueue,i=i!==null?i.lastEffect:null,i!==null){a=i=i.next;do{if((a.tag&3)===3){var o=a.create;a.destroy=o()}a=a.next}while(a!==i)}if(i=e.updateQueue,i=i!==null?i.lastEffect:null,i!==null){a=i=i.next;do{var s=a;o=s.next,s=s.tag,(s&4)!==0&&(s&1)!==0&&(Zi(e,a),$i(e,a)),a=o}while(a!==i)}return;case 1:a=e.stateNode,e.flags&4&&(i===null?a.componentDidMount():(o=e.elementType===e.type?i.memoizedProps:lg(e.type,i.memoizedProps),a.componentDidUpdate(o,i.memoizedState,a.__reactInternalSnapshotBeforeUpdate))),i=e.updateQueue,i!==null&&Eg(e,i,a);return;case 3:if(i=e.updateQueue,i!==null){if(a=null,e.child!==null)switch(e.child.tag){case 5:a=e.child.stateNode;break;case 1:a=e.child.stateNode}Eg(e,i,a)}return;case 5:a=e.stateNode,i===null&&e.flags&4&&mf(e.type,e.memoizedProps)&&a.focus();return;case 6:return;case 4:return;case 12:return;case 13:e.memoizedState===null&&(e=e.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&Cc(e))));return;case 19:case 17:case 20:case 21:case 23:case 24:return}throw Error(y(163))}function aj(a,i){for(var e=a;;){if(e.tag===5){var o=e.stateNode;if(i)o=o.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none";else{o=e.stateNode;var s=e.memoizedProps.style;s=s!=null&&s.hasOwnProperty("display")?s.display:null,o.style.display=sb("display",s)}}else if(e.tag===6)e.stateNode.nodeValue=i?"":e.memoizedProps;else if((e.tag!==23&&e.tag!==24||e.memoizedState===null||e===a)&&e.child!==null){e.child.return=e,e=e.child;continue}if(e===a)break;for(;e.sibling===null;){if(e.return===null||e.return===a)return;e=e.return}e.sibling.return=e.return,e=e.sibling}}function bj(a,i){if(Mf&&typeof Mf.onCommitFiberUnmount=="function")try{Mf.onCommitFiberUnmount(Lf,i)}catch{}switch(i.tag){case 0:case 11:case 14:case 15:case 22:if(a=i.updateQueue,a!==null&&(a=a.lastEffect,a!==null)){var e=a=a.next;do{var o=e,s=o.destroy;if(o=o.tag,s!==void 0)if((o&4)!==0)Zi(i,e);else{o=i;try{s()}catch(c){Wi(o,c)}}e=e.next}while(e!==a)}break;case 1:if(Vi(i),a=i.stateNode,typeof a.componentWillUnmount=="function")try{a.props=i.memoizedProps,a.state=i.memoizedState,a.componentWillUnmount()}catch(c){Wi(i,c)}break;case 5:Vi(i);break;case 4:cj(a,i)}}function dj(a){a.alternate=null,a.child=null,a.dependencies=null,a.firstEffect=null,a.lastEffect=null,a.memoizedProps=null,a.memoizedState=null,a.pendingProps=null,a.return=null,a.updateQueue=null}function ej(a){return a.tag===5||a.tag===3||a.tag===4}function fj(a){e:{for(var i=a.return;i!==null;){if(ej(i))break e;i=i.return}throw Error(y(160))}var e=i;switch(i=e.stateNode,e.tag){case 5:var o=!1;break;case 3:i=i.containerInfo,o=!0;break;case 4:i=i.containerInfo,o=!0;break;default:throw Error(y(161))}e.flags&16&&(pb(i,""),e.flags&=-17);e:t:for(e=a;;){for(;e.sibling===null;){if(e.return===null||ej(e.return)){e=null;break e}e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue t;e.child.return=e,e=e.child}if(!(e.flags&2)){e=e.stateNode;break e}}o?gj(a,e,i):hj(a,e,i)}function gj(a,i,e){var o=a.tag,s=o===5||o===6;if(s)a=s?a.stateNode:a.stateNode.instance,i?e.nodeType===8?e.parentNode.insertBefore(a,i):e.insertBefore(a,i):(e.nodeType===8?(i=e.parentNode,i.insertBefore(a,e)):(i=e,i.appendChild(a)),e=e._reactRootContainer,e!=null||i.onclick!==null||(i.onclick=jf));else if(o!==4&&(a=a.child,a!==null))for(gj(a,i,e),a=a.sibling;a!==null;)gj(a,i,e),a=a.sibling}function hj(a,i,e){var o=a.tag,s=o===5||o===6;if(s)a=s?a.stateNode:a.stateNode.instance,i?e.insertBefore(a,i):e.appendChild(a);else if(o!==4&&(a=a.child,a!==null))for(hj(a,i,e),a=a.sibling;a!==null;)hj(a,i,e),a=a.sibling}function cj(a,i){for(var e=i,o=!1,s,c;;){if(!o){o=e.return;e:for(;;){if(o===null)throw Error(y(160));switch(s=o.stateNode,o.tag){case 5:c=!1;break e;case 3:s=s.containerInfo,c=!0;break e;case 4:s=s.containerInfo,c=!0;break e}o=o.return}o=!0}if(e.tag===5||e.tag===6){e:for(var d=a,_=e,b=_;;)if(bj(d,b),b.child!==null&&b.tag!==4)b.child.return=b,b=b.child;else{if(b===_)break e;for(;b.sibling===null;){if(b.return===null||b.return===_)break e;b=b.return}b.sibling.return=b.return,b=b.sibling}c?(d=s,_=e.stateNode,d.nodeType===8?d.parentNode.removeChild(_):d.removeChild(_)):s.removeChild(e.stateNode)}else if(e.tag===4){if(e.child!==null){s=e.stateNode.containerInfo,c=!0,e.child.return=e,e=e.child;continue}}else if(bj(a,e),e.child!==null){e.child.return=e,e=e.child;continue}if(e===i)break;for(;e.sibling===null;){if(e.return===null||e.return===i)return;e=e.return,e.tag===4&&(o=!1)}e.sibling.return=e.return,e=e.sibling}}function ij(a,i){switch(i.tag){case 0:case 11:case 14:case 15:case 22:var e=i.updateQueue;if(e=e!==null?e.lastEffect:null,e!==null){var o=e=e.next;do(o.tag&3)===3&&(a=o.destroy,o.destroy=void 0,a!==void 0&&a()),o=o.next;while(o!==e)}return;case 1:return;case 5:if(e=i.stateNode,e!=null){o=i.memoizedProps;var s=a!==null?a.memoizedProps:o;a=i.type;var c=i.updateQueue;if(i.updateQueue=null,c!==null){for(e[xf]=o,a==="input"&&o.type==="radio"&&o.name!=null&&$a(e,o),wb(a,s),i=wb(a,o),s=0;s<c.length;s+=2){var d=c[s],_=c[s+1];d==="style"?tb(e,_):d==="dangerouslySetInnerHTML"?ob(e,_):d==="children"?pb(e,_):qa(e,d,_,i)}switch(a){case"input":ab(e,o);break;case"textarea":ib(e,o);break;case"select":a=e._wrapperState.wasMultiple,e._wrapperState.wasMultiple=!!o.multiple,c=o.value,c!=null?fb(e,!!o.multiple,c,!1):a!==!!o.multiple&&(o.defaultValue!=null?fb(e,!!o.multiple,o.defaultValue,!0):fb(e,!!o.multiple,o.multiple?[]:"",!1))}}}return;case 6:if(i.stateNode===null)throw Error(y(162));i.stateNode.nodeValue=i.memoizedProps;return;case 3:e=i.stateNode,e.hydrate&&(e.hydrate=!1,Cc(e.containerInfo));return;case 12:return;case 13:i.memoizedState!==null&&(jj=O(),aj(i.child,!0)),kj(i);return;case 19:kj(i);return;case 17:return;case 23:case 24:aj(i,i.memoizedState!==null);return}throw Error(y(163))}function kj(a){var i=a.updateQueue;if(i!==null){a.updateQueue=null;var e=a.stateNode;e===null&&(e=a.stateNode=new Ui),i.forEach(function(o){var s=lj.bind(null,a,o);e.has(o)||(e.add(o),o.then(s,s))})}}function mj(a,i){return a!==null&&(a=a.memoizedState,a===null||a.dehydrated!==null)?(i=i.memoizedState,i!==null&&i.dehydrated===null):!1}var nj=Math.ceil,oj=ra.ReactCurrentDispatcher,pj=ra.ReactCurrentOwner,X=0,U=null,Y=null,W=0,qj=0,rj=Bf(0),V=0,sj=null,tj=0,Dg=0,Hi=0,uj=0,vj=null,jj=0,Ji=1/0;function wj(){Ji=O()+500}var Z=null,Qi=!1,Ri=null,Ti=null,xj=!1,yj=null,zj=90,Aj=[],Bj=[],Cj=null,Dj=0,Ej=null,Fj=-1,Gj=0,Hj=0,Ij=null,Jj=!1;function Hg(){return(X&48)!==0?O():Fj!==-1?Fj:Fj=O()}function Ig(a){if(a=a.mode,(a&2)===0)return 1;if((a&4)===0)return eg()===99?1:2;if(Gj===0&&(Gj=tj),kg.transition!==0){Hj!==0&&(Hj=vj!==null?vj.pendingLanes:0),a=Gj;var i=4186112&~Hj;return i&=-i,i===0&&(a=4186112&~a,i=a&-a,i===0&&(i=8192)),i}return a=eg(),(X&4)!==0&&a===98?a=Xc(12,Gj):(a=Sc(a),a=Xc(a,Gj)),a}function Jg(a,i,e){if(50<Dj)throw Dj=0,Ej=null,Error(y(185));if(a=Kj(a,i),a===null)return null;$c(a,i,e),a===U&&(Hi|=i,V===4&&Ii(a,W));var o=eg();i===1?(X&8)!==0&&(X&48)===0?Lj(a):(Mj(a,e),X===0&&(wj(),ig())):((X&4)===0||o!==98&&o!==99||(Cj===null?Cj=new Set([a]):Cj.add(a)),Mj(a,e)),vj=a}function Kj(a,i){a.lanes|=i;var e=a.alternate;for(e!==null&&(e.lanes|=i),e=a,a=a.return;a!==null;)a.childLanes|=i,e=a.alternate,e!==null&&(e.childLanes|=i),e=a,a=a.return;return e.tag===3?e.stateNode:null}function Mj(a,i){for(var e=a.callbackNode,o=a.suspendedLanes,s=a.pingedLanes,c=a.expirationTimes,d=a.pendingLanes;0<d;){var _=31-Vc(d),b=1<<_,k=c[_];if(k===-1){if((b&o)===0||(b&s)!==0){k=i,Rc(b);var j=F;c[_]=10<=j?k+250:6<=j?k+5e3:-1}}else k<=i&&(a.expiredLanes|=b);d&=~b}if(o=Uc(a,a===U?W:0),i=F,o===0)e!==null&&(e!==Zf&&Pf(e),a.callbackNode=null,a.callbackPriority=0);else{if(e!==null){if(a.callbackPriority===i)return;e!==Zf&&Pf(e)}i===15?(e=Lj.bind(null,a),ag===null?(ag=[e],bg=Of(Uf,jg)):ag.push(e),e=Zf):i===14?e=hg(99,Lj.bind(null,a)):(e=Tc(i),e=hg(e,Nj.bind(null,a))),a.callbackPriority=i,a.callbackNode=e}}function Nj(a){if(Fj=-1,Hj=Gj=0,(X&48)!==0)throw Error(y(327));var i=a.callbackNode;if(Oj()&&a.callbackNode!==i)return null;var e=Uc(a,a===U?W:0);if(e===0)return null;var o=e,s=X;X|=16;var c=Pj();(U!==a||W!==o)&&(wj(),Qj(a,o));do try{Rj();break}catch(_){Sj(a,_)}while(1);if(qg(),oj.current=c,X=s,Y!==null?o=0:(U=null,W=0,o=V),(tj&Hi)!==0)Qj(a,0);else if(o!==0){if(o===2&&(X|=64,a.hydrate&&(a.hydrate=!1,qf(a.containerInfo)),e=Wc(a),e!==0&&(o=Tj(a,e))),o===1)throw i=sj,Qj(a,0),Ii(a,e),Mj(a,O()),i;switch(a.finishedWork=a.current.alternate,a.finishedLanes=e,o){case 0:case 1:throw Error(y(345));case 2:Uj(a);break;case 3:if(Ii(a,e),(e&62914560)===e&&(o=jj+500-O(),10<o)){if(Uc(a,0)!==0)break;if(s=a.suspendedLanes,(s&e)!==e){Hg(),a.pingedLanes|=a.suspendedLanes&s;break}a.timeoutHandle=of(Uj.bind(null,a),o);break}Uj(a);break;case 4:if(Ii(a,e),(e&4186112)===e)break;for(o=a.eventTimes,s=-1;0<e;){var d=31-Vc(e);c=1<<d,d=o[d],d>s&&(s=d),e&=~c}if(e=s,e=O()-e,e=(120>e?120:480>e?480:1080>e?1080:1920>e?1920:3e3>e?3e3:4320>e?4320:1960*nj(e/1960))-e,10<e){a.timeoutHandle=of(Uj.bind(null,a),e);break}Uj(a);break;case 5:Uj(a);break;default:throw Error(y(329))}}return Mj(a,O()),a.callbackNode===i?Nj.bind(null,a):null}function Ii(a,i){for(i&=~uj,i&=~Hi,a.suspendedLanes|=i,a.pingedLanes&=~i,a=a.expirationTimes;0<i;){var e=31-Vc(i),o=1<<e;a[e]=-1,i&=~o}}function Lj(a){if((X&48)!==0)throw Error(y(327));if(Oj(),a===U&&(a.expiredLanes&W)!==0){var i=W,e=Tj(a,i);(tj&Hi)!==0&&(i=Uc(a,i),e=Tj(a,i))}else i=Uc(a,0),e=Tj(a,i);if(a.tag!==0&&e===2&&(X|=64,a.hydrate&&(a.hydrate=!1,qf(a.containerInfo)),i=Wc(a),i!==0&&(e=Tj(a,i))),e===1)throw e=sj,Qj(a,0),Ii(a,i),Mj(a,O()),e;return a.finishedWork=a.current.alternate,a.finishedLanes=i,Uj(a),Mj(a,O()),null}function Vj(){if(Cj!==null){var a=Cj;Cj=null,a.forEach(function(i){i.expiredLanes|=24&i.pendingLanes,Mj(i,O())})}ig()}function Wj(a,i){var e=X;X|=1;try{return a(i)}finally{X=e,X===0&&(wj(),ig())}}function Xj(a,i){var e=X;X&=-2,X|=8;try{return a(i)}finally{X=e,X===0&&(wj(),ig())}}function ni(a,i){I(rj,qj),qj|=i,tj|=i}function Ki(){qj=rj.current,H(rj)}function Qj(a,i){a.finishedWork=null,a.finishedLanes=0;var e=a.timeoutHandle;if(e!==-1&&(a.timeoutHandle=-1,pf(e)),Y!==null)for(e=Y.return;e!==null;){var o=e;switch(o.tag){case 1:o=o.type.childContextTypes,o!=null&&Gf();break;case 3:fh(),H(N),H(M),uh();break;case 5:hh(o);break;case 4:fh();break;case 13:H(P);break;case 19:H(P);break;case 10:rg(o);break;case 23:case 24:Ki()}e=e.return}U=a,Y=Tg(a.current,null),W=qj=tj=i,V=0,sj=null,uj=Hi=Dg=0}function Sj(a,i){do{var e=Y;try{if(qg(),vh.current=Gh,yh){for(var o=R.memoizedState;o!==null;){var s=o.queue;s!==null&&(s.pending=null),o=o.next}yh=!1}if(xh=0,T=S=R=null,zh=!1,pj.current=null,e===null||e.return===null){V=1,sj=i,Y=null;break}e:{var c=a,d=e.return,_=e,b=i;if(i=W,_.flags|=2048,_.firstEffect=_.lastEffect=null,b!==null&&typeof b=="object"&&typeof b.then=="function"){var k=b;if((_.mode&2)===0){var j=_.alternate;j?(_.updateQueue=j.updateQueue,_.memoizedState=j.memoizedState,_.lanes=j.lanes):(_.updateQueue=null,_.memoizedState=null)}var $=(P.current&1)!==0,_e=d;do{var et;if(et=_e.tag===13){var tt=_e.memoizedState;if(tt!==null)et=tt.dehydrated!==null;else{var rt=_e.memoizedProps;et=rt.fallback===void 0?!1:rt.unstable_avoidThisFallback!==!0?!0:!$}}if(et){var it=_e.updateQueue;if(it===null){var nt=new Set;nt.add(k),_e.updateQueue=nt}else it.add(k);if((_e.mode&2)===0){if(_e.flags|=64,_.flags|=16384,_.flags&=-2981,_.tag===1)if(_.alternate===null)_.tag=17;else{var ot=zg(-1,1);ot.tag=2,Ag(_,ot)}_.lanes|=1;break e}b=void 0,_=i;var at=c.pingCache;if(at===null?(at=c.pingCache=new Oi,b=new Set,at.set(k,b)):(b=at.get(k),b===void 0&&(b=new Set,at.set(k,b))),!b.has(_)){b.add(_);var st=Yj.bind(null,c,k,_);k.then(st,st)}_e.flags|=4096,_e.lanes=i;break e}_e=_e.return}while(_e!==null);b=Error((Ra(_.type)||"A React component")+` suspended while rendering, but no fallback UI was specified.
  33. Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.`)}V!==5&&(V=2),b=Mi(b,_),_e=d;do{switch(_e.tag){case 3:c=b,_e.flags|=4096,i&=-i,_e.lanes|=i;var ut=Pi(_e,c,i);Bg(_e,ut);break e;case 1:c=b;var ft=_e.type,lt=_e.stateNode;if((_e.flags&64)===0&&(typeof ft.getDerivedStateFromError=="function"||lt!==null&&typeof lt.componentDidCatch=="function"&&(Ti===null||!Ti.has(lt)))){_e.flags|=4096,i&=-i,_e.lanes|=i;var ht=Si(_e,c,i);Bg(_e,ht);break e}}_e=_e.return}while(_e!==null)}Zj(e)}catch(pt){i=pt,Y===e&&e!==null&&(Y=e=e.return);continue}break}while(1)}function Pj(){var a=oj.current;return oj.current=Gh,a===null?Gh:a}function Tj(a,i){var e=X;X|=16;var o=Pj();U===a&&W===i||Qj(a,i);do try{ak();break}catch(s){Sj(a,s)}while(1);if(qg(),X=e,oj.current=o,Y!==null)throw Error(y(261));return U=null,W=0,V}function ak(){for(;Y!==null;)bk(Y)}function Rj(){for(;Y!==null&&!Qf();)bk(Y)}function bk(a){var i=ck(a.alternate,a,qj);a.memoizedProps=a.pendingProps,i===null?Zj(a):Y=i,pj.current=null}function Zj(a){var i=a;do{var e=i.alternate;if(a=i.return,(i.flags&2048)===0){if(e=Gi(e,i,qj),e!==null){Y=e;return}if(e=i,e.tag!==24&&e.tag!==23||e.memoizedState===null||(qj&1073741824)!==0||(e.mode&4)===0){for(var o=0,s=e.child;s!==null;)o|=s.lanes|s.childLanes,s=s.sibling;e.childLanes=o}a!==null&&(a.flags&2048)===0&&(a.firstEffect===null&&(a.firstEffect=i.firstEffect),i.lastEffect!==null&&(a.lastEffect!==null&&(a.lastEffect.nextEffect=i.firstEffect),a.lastEffect=i.lastEffect),1<i.flags&&(a.lastEffect!==null?a.lastEffect.nextEffect=i:a.firstEffect=i,a.lastEffect=i))}else{if(e=Li(i),e!==null){e.flags&=2047,Y=e;return}a!==null&&(a.firstEffect=a.lastEffect=null,a.flags|=2048)}if(i=i.sibling,i!==null){Y=i;return}Y=i=a}while(i!==null);V===0&&(V=5)}function Uj(a){var i=eg();return gg(99,dk.bind(null,a,i)),null}function dk(a,i){do Oj();while(yj!==null);if((X&48)!==0)throw Error(y(327));var e=a.finishedWork;if(e===null)return null;if(a.finishedWork=null,a.finishedLanes=0,e===a.current)throw Error(y(177));a.callbackNode=null;var o=e.lanes|e.childLanes,s=o,c=a.pendingLanes&~s;a.pendingLanes=s,a.suspendedLanes=0,a.pingedLanes=0,a.expiredLanes&=s,a.mutableReadLanes&=s,a.entangledLanes&=s,s=a.entanglements;for(var d=a.eventTimes,_=a.expirationTimes;0<c;){var b=31-Vc(c),k=1<<b;s[b]=0,d[b]=-1,_[b]=-1,c&=~k}if(Cj!==null&&(o&24)===0&&Cj.has(a)&&Cj.delete(a),a===U&&(Y=U=null,W=0),1<e.flags?e.lastEffect!==null?(e.lastEffect.nextEffect=e,o=e.firstEffect):o=e:o=e.firstEffect,o!==null){if(s=X,X|=32,pj.current=null,kf=fd,d=Ne(),Oe(d)){if("selectionStart"in d)_={start:d.selectionStart,end:d.selectionEnd};else e:if(_=(_=d.ownerDocument)&&_.defaultView||window,(k=_.getSelection&&_.getSelection())&&k.rangeCount!==0){_=k.anchorNode,c=k.anchorOffset,b=k.focusNode,k=k.focusOffset;try{_.nodeType,b.nodeType}catch{_=null;break e}var j=0,$=-1,_e=-1,et=0,tt=0,rt=d,it=null;t:for(;;){for(var nt;rt!==_||c!==0&&rt.nodeType!==3||($=j+c),rt!==b||k!==0&&rt.nodeType!==3||(_e=j+k),rt.nodeType===3&&(j+=rt.nodeValue.length),(nt=rt.firstChild)!==null;)it=rt,rt=nt;for(;;){if(rt===d)break t;if(it===_&&++et===c&&($=j),it===b&&++tt===k&&(_e=j),(nt=rt.nextSibling)!==null)break;rt=it,it=rt.parentNode}rt=nt}_=$===-1||_e===-1?null:{start:$,end:_e}}else _=null;_=_||{start:0,end:0}}else _=null;lf={focusedElem:d,selectionRange:_},fd=!1,Ij=null,Jj=!1,Z=o;do try{ek()}catch(pt){if(Z===null)throw Error(y(330));Wi(Z,pt),Z=Z.nextEffect}while(Z!==null);Ij=null,Z=o;do try{for(d=a;Z!==null;){var ot=Z.flags;if(ot&16&&pb(Z.stateNode,""),ot&128){var at=Z.alternate;if(at!==null){var st=at.ref;st!==null&&(typeof st=="function"?st(null):st.current=null)}}switch(ot&1038){case 2:fj(Z),Z.flags&=-3;break;case 6:fj(Z),Z.flags&=-3,ij(Z.alternate,Z);break;case 1024:Z.flags&=-1025;break;case 1028:Z.flags&=-1025,ij(Z.alternate,Z);break;case 4:ij(Z.alternate,Z);break;case 8:_=Z,cj(d,_);var ut=_.alternate;dj(_),ut!==null&&dj(ut)}Z=Z.nextEffect}}catch(pt){if(Z===null)throw Error(y(330));Wi(Z,pt),Z=Z.nextEffect}while(Z!==null);if(st=lf,at=Ne(),ot=st.focusedElem,d=st.selectionRange,at!==ot&&ot&&ot.ownerDocument&&Me(ot.ownerDocument.documentElement,ot)){for(d!==null&&Oe(ot)&&(at=d.start,st=d.end,st===void 0&&(st=at),"selectionStart"in ot?(ot.selectionStart=at,ot.selectionEnd=Math.min(st,ot.value.length)):(st=(at=ot.ownerDocument||document)&&at.defaultView||window,st.getSelection&&(st=st.getSelection(),_=ot.textContent.length,ut=Math.min(d.start,_),d=d.end===void 0?ut:Math.min(d.end,_),!st.extend&&ut>d&&(_=d,d=ut,ut=_),_=Le(ot,ut),c=Le(ot,d),_&&c&&(st.rangeCount!==1||st.anchorNode!==_.node||st.anchorOffset!==_.offset||st.focusNode!==c.node||st.focusOffset!==c.offset)&&(at=at.createRange(),at.setStart(_.node,_.offset),st.removeAllRanges(),ut>d?(st.addRange(at),st.extend(c.node,c.offset)):(at.setEnd(c.node,c.offset),st.addRange(at)))))),at=[],st=ot;st=st.parentNode;)st.nodeType===1&&at.push({element:st,left:st.scrollLeft,top:st.scrollTop});for(typeof ot.focus=="function"&&ot.focus(),ot=0;ot<at.length;ot++)st=at[ot],st.element.scrollLeft=st.left,st.element.scrollTop=st.top}fd=!!kf,lf=kf=null,a.current=e,Z=o;do try{for(ot=a;Z!==null;){var ft=Z.flags;if(ft&36&&Yi(ot,Z.alternate,Z),ft&128){at=void 0;var lt=Z.ref;if(lt!==null){var ht=Z.stateNode;switch(Z.tag){case 5:at=ht;break;default:at=ht}typeof lt=="function"?lt(at):lt.current=at}}Z=Z.nextEffect}}catch(pt){if(Z===null)throw Error(y(330));Wi(Z,pt),Z=Z.nextEffect}while(Z!==null);Z=null,$f(),X=s}else a.current=e;if(xj)xj=!1,yj=a,zj=i;else for(Z=o;Z!==null;)i=Z.nextEffect,Z.nextEffect=null,Z.flags&8&&(ft=Z,ft.sibling=null,ft.stateNode=null),Z=i;if(o=a.pendingLanes,o===0&&(Ti=null),o===1?a===Ej?Dj++:(Dj=0,Ej=a):Dj=0,e=e.stateNode,Mf&&typeof Mf.onCommitFiberRoot=="function")try{Mf.onCommitFiberRoot(Lf,e,void 0,(e.current.flags&64)===64)}catch{}if(Mj(a,O()),Qi)throw Qi=!1,a=Ri,Ri=null,a;return(X&8)!==0||ig(),null}function ek(){for(;Z!==null;){var a=Z.alternate;Jj||Ij===null||((Z.flags&8)!==0?dc(Z,Ij)&&(Jj=!0):Z.tag===13&&mj(a,Z)&&dc(Z,Ij)&&(Jj=!0));var i=Z.flags;(i&256)!==0&&Xi(a,Z),(i&512)===0||xj||(xj=!0,hg(97,function(){return Oj(),null})),Z=Z.nextEffect}}function Oj(){if(zj!==90){var a=97<zj?97:zj;return zj=90,gg(a,fk)}return!1}function $i(a,i){Aj.push(i,a),xj||(xj=!0,hg(97,function(){return Oj(),null}))}function Zi(a,i){Bj.push(i,a),xj||(xj=!0,hg(97,function(){return Oj(),null}))}function fk(){if(yj===null)return!1;var a=yj;if(yj=null,(X&48)!==0)throw Error(y(331));var i=X;X|=32;var e=Bj;Bj=[];for(var o=0;o<e.length;o+=2){var s=e[o],c=e[o+1],d=s.destroy;if(s.destroy=void 0,typeof d=="function")try{d()}catch(b){if(c===null)throw Error(y(330));Wi(c,b)}}for(e=Aj,Aj=[],o=0;o<e.length;o+=2){s=e[o],c=e[o+1];try{var _=s.create;s.destroy=_()}catch(b){if(c===null)throw Error(y(330));Wi(c,b)}}for(_=a.current.firstEffect;_!==null;)a=_.nextEffect,_.nextEffect=null,_.flags&8&&(_.sibling=null,_.stateNode=null),_=a;return X=i,ig(),!0}function gk(a,i,e){i=Mi(e,i),i=Pi(a,i,1),Ag(a,i),i=Hg(),a=Kj(a,1),a!==null&&($c(a,1,i),Mj(a,i))}function Wi(a,i){if(a.tag===3)gk(a,a,i);else for(var e=a.return;e!==null;){if(e.tag===3){gk(e,a,i);break}else if(e.tag===1){var o=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(Ti===null||!Ti.has(o))){a=Mi(i,a);var s=Si(e,a,1);if(Ag(e,s),s=Hg(),e=Kj(e,1),e!==null)$c(e,1,s),Mj(e,s);else if(typeof o.componentDidCatch=="function"&&(Ti===null||!Ti.has(o)))try{o.componentDidCatch(i,a)}catch{}break}}e=e.return}}function Yj(a,i,e){var o=a.pingCache;o!==null&&o.delete(i),i=Hg(),a.pingedLanes|=a.suspendedLanes&e,U===a&&(W&e)===e&&(V===4||V===3&&(W&62914560)===W&&500>O()-jj?Qj(a,0):uj|=e),Mj(a,i)}function lj(a,i){var e=a.stateNode;e!==null&&e.delete(i),i=0,i===0&&(i=a.mode,(i&2)===0?i=1:(i&4)===0?i=eg()===99?1:2:(Gj===0&&(Gj=tj),i=Yc(62914560&~Gj),i===0&&(i=4194304))),e=Hg(),a=Kj(a,i),a!==null&&($c(a,i,e),Mj(a,e))}var ck;ck=function(a,i,e){var o=i.lanes;if(a!==null)if(a.memoizedProps!==i.pendingProps||N.current)ug=!0;else if((e&o)!==0)ug=(a.flags&16384)!==0;else{switch(ug=!1,i.tag){case 3:ri(i),sh();break;case 5:gh(i);break;case 1:Ff(i.type)&&Jf(i);break;case 4:eh(i,i.stateNode.containerInfo);break;case 10:o=i.memoizedProps.value;var s=i.type._context;I(mg,s._currentValue),s._currentValue=o;break;case 13:if(i.memoizedState!==null)return(e&i.child.childLanes)!==0?ti(a,i,e):(I(P,P.current&1),i=hi(a,i,e),i!==null?i.sibling:null);I(P,P.current&1);break;case 19:if(o=(e&i.childLanes)!==0,(a.flags&64)!==0){if(o)return Ai(a,i,e);i.flags|=64}if(s=i.memoizedState,s!==null&&(s.rendering=null,s.tail=null,s.lastEffect=null),I(P,P.current),o)break;return null;case 23:case 24:return i.lanes=0,mi(a,i,e)}return hi(a,i,e)}else ug=!1;switch(i.lanes=0,i.tag){case 2:if(o=i.type,a!==null&&(a.alternate=null,i.alternate=null,i.flags|=2),a=i.pendingProps,s=Ef(i,M.current),tg(i,e),s=Ch(null,i,o,a,s,e),i.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0){if(i.tag=1,i.memoizedState=null,i.updateQueue=null,Ff(o)){var c=!0;Jf(i)}else c=!1;i.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,xg(i);var d=o.getDerivedStateFromProps;typeof d=="function"&&Gg(i,o,d,a),s.updater=Kg,i.stateNode=s,s._reactInternals=i,Og(i,o,a,e),i=qi(null,i,o,!0,c,e)}else i.tag=0,fi(null,i,s,e),i=i.child;return i;case 16:s=i.elementType;e:{switch(a!==null&&(a.alternate=null,i.alternate=null,i.flags|=2),a=i.pendingProps,c=s._init,s=c(s._payload),i.type=s,c=i.tag=hk(s),a=lg(s,a),c){case 0:i=li(null,i,s,a,e);break e;case 1:i=pi(null,i,s,a,e);break e;case 11:i=gi(null,i,s,a,e);break e;case 14:i=ii(null,i,s,lg(s.type,a),o,e);break e}throw Error(y(306,s,""))}return i;case 0:return o=i.type,s=i.pendingProps,s=i.elementType===o?s:lg(o,s),li(a,i,o,s,e);case 1:return o=i.type,s=i.pendingProps,s=i.elementType===o?s:lg(o,s),pi(a,i,o,s,e);case 3:if(ri(i),o=i.updateQueue,a===null||o===null)throw Error(y(282));if(o=i.pendingProps,s=i.memoizedState,s=s!==null?s.element:null,yg(a,i),Cg(i,o,null,e),o=i.memoizedState.element,o===s)sh(),i=hi(a,i,e);else{if(s=i.stateNode,(c=s.hydrate)&&(kh=rf(i.stateNode.containerInfo.firstChild),jh=i,c=lh=!0),c){if(a=s.mutableSourceEagerHydrationData,a!=null)for(s=0;s<a.length;s+=2)c=a[s],c._workInProgressVersionPrimary=a[s+1],th.push(c);for(e=Zg(i,null,o,e),i.child=e;e;)e.flags=e.flags&-3|1024,e=e.sibling}else fi(a,i,o,e),sh();i=i.child}return i;case 5:return gh(i),a===null&&ph(i),o=i.type,s=i.pendingProps,c=a!==null?a.memoizedProps:null,d=s.children,nf(o,s)?d=null:c!==null&&nf(o,c)&&(i.flags|=16),oi(a,i),fi(a,i,d,e),i.child;case 6:return a===null&&ph(i),null;case 13:return ti(a,i,e);case 4:return eh(i,i.stateNode.containerInfo),o=i.pendingProps,a===null?i.child=Yg(i,null,o,e):fi(a,i,o,e),i.child;case 11:return o=i.type,s=i.pendingProps,s=i.elementType===o?s:lg(o,s),gi(a,i,o,s,e);case 7:return fi(a,i,i.pendingProps,e),i.child;case 8:return fi(a,i,i.pendingProps.children,e),i.child;case 12:return fi(a,i,i.pendingProps.children,e),i.child;case 10:e:{o=i.type._context,s=i.pendingProps,d=i.memoizedProps,c=s.value;var _=i.type._context;if(I(mg,_._currentValue),_._currentValue=c,d!==null)if(_=d.value,c=He(_,c)?0:(typeof o._calculateChangedBits=="function"?o._calculateChangedBits(_,c):1073741823)|0,c===0){if(d.children===s.children&&!N.current){i=hi(a,i,e);break e}}else for(_=i.child,_!==null&&(_.return=i);_!==null;){var b=_.dependencies;if(b!==null){d=_.child;for(var k=b.firstContext;k!==null;){if(k.context===o&&(k.observedBits&c)!==0){_.tag===1&&(k=zg(-1,e&-e),k.tag=2,Ag(_,k)),_.lanes|=e,k=_.alternate,k!==null&&(k.lanes|=e),sg(_.return,e),b.lanes|=e;break}k=k.next}}else d=_.tag===10&&_.type===i.type?null:_.child;if(d!==null)d.return=_;else for(d=_;d!==null;){if(d===i){d=null;break}if(_=d.sibling,_!==null){_.return=d.return,d=_;break}d=d.return}_=d}fi(a,i,s.children,e),i=i.child}return i;case 9:return s=i.type,c=i.pendingProps,o=c.children,tg(i,e),s=vg(s,c.unstable_observedBits),o=o(s),i.flags|=1,fi(a,i,o,e),i.child;case 14:return s=i.type,c=lg(s,i.pendingProps),c=lg(s.type,c),ii(a,i,s,c,o,e);case 15:return ki(a,i,i.type,i.pendingProps,o,e);case 17:return o=i.type,s=i.pendingProps,s=i.elementType===o?s:lg(o,s),a!==null&&(a.alternate=null,i.alternate=null,i.flags|=2),i.tag=1,Ff(o)?(a=!0,Jf(i)):a=!1,tg(i,e),Mg(i,o,s),Og(i,o,s,e),qi(null,i,o,!0,a,e);case 19:return Ai(a,i,e);case 23:return mi(a,i,e);case 24:return mi(a,i,e)}throw Error(y(156,i.tag))};function ik(a,i,e,o){this.tag=a,this.key=e,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=i,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.flags=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childLanes=this.lanes=0,this.alternate=null}function nh(a,i,e,o){return new ik(a,i,e,o)}function ji(a){return a=a.prototype,!(!a||!a.isReactComponent)}function hk(a){if(typeof a=="function")return ji(a)?1:0;if(a!=null){if(a=a.$$typeof,a===Aa)return 11;if(a===Da)return 14}return 2}function Tg(a,i){var e=a.alternate;return e===null?(e=nh(a.tag,i,a.key,a.mode),e.elementType=a.elementType,e.type=a.type,e.stateNode=a.stateNode,e.alternate=a,a.alternate=e):(e.pendingProps=i,e.type=a.type,e.flags=0,e.nextEffect=null,e.firstEffect=null,e.lastEffect=null),e.childLanes=a.childLanes,e.lanes=a.lanes,e.child=a.child,e.memoizedProps=a.memoizedProps,e.memoizedState=a.memoizedState,e.updateQueue=a.updateQueue,i=a.dependencies,e.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext},e.sibling=a.sibling,e.index=a.index,e.ref=a.ref,e}function Vg(a,i,e,o,s,c){var d=2;if(o=a,typeof a=="function")ji(a)&&(d=1);else if(typeof a=="string")d=5;else e:switch(a){case ua:return Xg(e.children,s,c,i);case Ha:d=8,s|=16;break;case wa:d=8,s|=1;break;case xa:return a=nh(12,e,i,s|8),a.elementType=xa,a.type=xa,a.lanes=c,a;case Ba:return a=nh(13,e,i,s),a.type=Ba,a.elementType=Ba,a.lanes=c,a;case Ca:return a=nh(19,e,i,s),a.elementType=Ca,a.lanes=c,a;case Ia:return vi(e,s,c,i);case Ja:return a=nh(24,e,i,s),a.elementType=Ja,a.lanes=c,a;default:if(typeof a=="object"&&a!==null)switch(a.$$typeof){case ya:d=10;break e;case za:d=9;break e;case Aa:d=11;break e;case Da:d=14;break e;case Ea:d=16,o=null;break e;case Fa:d=22;break e}throw Error(y(130,a==null?a:typeof a,""))}return i=nh(d,e,i,s),i.elementType=a,i.type=o,i.lanes=c,i}function Xg(a,i,e,o){return a=nh(7,a,o,i),a.lanes=e,a}function vi(a,i,e,o){return a=nh(23,a,o,i),a.elementType=Ia,a.lanes=e,a}function Ug(a,i,e){return a=nh(6,a,null,i),a.lanes=e,a}function Wg(a,i,e){return i=nh(4,a.children!==null?a.children:[],a.key,i),i.lanes=e,i.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},i}function jk(a,i,e){this.tag=i,this.containerInfo=a,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.pendingContext=this.context=null,this.hydrate=e,this.callbackNode=null,this.callbackPriority=0,this.eventTimes=Zc(0),this.expirationTimes=Zc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Zc(0),this.mutableSourceEagerHydrationData=null}function kk(a,i,e){var o=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:ta,key:o==null?null:""+o,children:a,containerInfo:i,implementation:e}}function lk(a,i,e,o){var s=i.current,c=Hg(),d=Ig(s);e:if(e){e=e._reactInternals;t:{if(Zb(e)!==e||e.tag!==1)throw Error(y(170));var _=e;do{switch(_.tag){case 3:_=_.stateNode.context;break t;case 1:if(Ff(_.type)){_=_.stateNode.__reactInternalMemoizedMergedChildContext;break t}}_=_.return}while(_!==null);throw Error(y(171))}if(e.tag===1){var b=e.type;if(Ff(b)){e=If(e,b,_);break e}}e=_}else e=Cf;return i.context===null?i.context=e:i.pendingContext=e,i=zg(c,d),i.payload={element:a},o=o===void 0?null:o,o!==null&&(i.callback=o),Ag(s,i),Jg(s,d,c),d}function mk(a){if(a=a.current,!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function nk(a,i){if(a=a.memoizedState,a!==null&&a.dehydrated!==null){var e=a.retryLane;a.retryLane=e!==0&&e<i?e:i}}function ok(a,i){nk(a,i),(a=a.alternate)&&nk(a,i)}function pk(){return null}function qk(a,i,e){var o=e!=null&&e.hydrationOptions!=null&&e.hydrationOptions.mutableSources||null;if(e=new jk(a,i,e!=null&&e.hydrate===!0),i=nh(3,null,null,i===2?7:i===1?3:0),e.current=i,i.stateNode=e,xg(i),a[ff]=e.current,cf(a.nodeType===8?a.parentNode:a),o)for(a=0;a<o.length;a++){i=o[a];var s=i._getVersion;s=s(i._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[i,s]:e.mutableSourceEagerHydrationData.push(i,s)}this._internalRoot=e}qk.prototype.render=function(a){lk(a,this._internalRoot,null,null)};qk.prototype.unmount=function(){var a=this._internalRoot,i=a.containerInfo;lk(null,a,null,function(){i[ff]=null})};function rk(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11&&(a.nodeType!==8||a.nodeValue!==" react-mount-point-unstable "))}function sk(a,i){if(i||(i=a?a.nodeType===9?a.documentElement:a.firstChild:null,i=!(!i||i.nodeType!==1||!i.hasAttribute("data-reactroot"))),!i)for(var e;e=a.lastChild;)a.removeChild(e);return new qk(a,0,i?{hydrate:!0}:void 0)}function tk(a,i,e,o,s){var c=e._reactRootContainer;if(c){var d=c._internalRoot;if(typeof s=="function"){var _=s;s=function(){var k=mk(d);_.call(k)}}lk(i,d,a,s)}else{if(c=e._reactRootContainer=sk(e,o),d=c._internalRoot,typeof s=="function"){var b=s;s=function(){var k=mk(d);b.call(k)}}Xj(function(){lk(i,d,a,s)})}return mk(d)}ec=function(a){if(a.tag===13){var i=Hg();Jg(a,4,i),ok(a,4)}};fc=function(a){if(a.tag===13){var i=Hg();Jg(a,67108864,i),ok(a,67108864)}};gc=function(a){if(a.tag===13){var i=Hg(),e=Ig(a);Jg(a,e,i),ok(a,e)}};hc=function(a,i){return i()};yb=function(a,i,e){switch(i){case"input":if(ab(a,e),i=e.name,e.type==="radio"&&i!=null){for(e=a;e.parentNode;)e=e.parentNode;for(e=e.querySelectorAll("input[name="+JSON.stringify(""+i)+'][type="radio"]'),i=0;i<e.length;i++){var o=e[i];if(o!==a&&o.form===a.form){var s=Db(o);if(!s)throw Error(y(90));Wa(o),ab(o,s)}}}break;case"textarea":ib(a,e);break;case"select":i=e.value,i!=null&&fb(a,!!e.multiple,i,!1)}};Gb=Wj;Hb=function(a,i,e,o,s){var c=X;X|=4;try{return gg(98,a.bind(null,i,e,o,s))}finally{X=c,X===0&&(wj(),ig())}};Ib=function(){(X&49)===0&&(Vj(),Oj())};Jb=function(a,i){var e=X;X|=2;try{return a(i)}finally{X=e,X===0&&(wj(),ig())}};function uk(a,i){var e=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!rk(i))throw Error(y(200));return kk(a,i,null,e)}var vk={Events:[Cb,ue,Db,Eb,Fb,Oj,{current:!1}]},wk={findFiberByHostInstance:wc,bundleType:0,version:"17.0.2",rendererPackageName:"react-dom"},xk={bundleType:wk.bundleType,version:wk.version,rendererPackageName:wk.rendererPackageName,rendererConfig:wk.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ra.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){return a=cc(a),a===null?null:a.stateNode},findFiberByHostInstance:wk.findFiberByHostInstance||pk,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__!="undefined"){var yk=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!yk.isDisabled&&yk.supportsFiber)try{Lf=yk.inject(xk),Mf=yk}catch{}}reactDom_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=vk;reactDom_production_min.createPortal=uk;reactDom_production_min.findDOMNode=function(a){if(a==null)return null;if(a.nodeType===1)return a;var i=a._reactInternals;if(i===void 0)throw typeof a.render=="function"?Error(y(188)):Error(y(268,Object.keys(a)));return a=cc(i),a=a===null?null:a.stateNode,a};reactDom_production_min.flushSync=function(a,i){var e=X;if((e&48)!==0)return a(i);X|=1;try{if(a)return gg(99,a.bind(null,i))}finally{X=e,ig()}};reactDom_production_min.hydrate=function(a,i,e){if(!rk(i))throw Error(y(200));return tk(null,a,i,!0,e)};reactDom_production_min.render=function(a,i,e){if(!rk(i))throw Error(y(200));return tk(null,a,i,!1,e)};reactDom_production_min.unmountComponentAtNode=function(a){if(!rk(a))throw Error(y(40));return a._reactRootContainer?(Xj(function(){tk(null,null,a,!1,function(){a._reactRootContainer=null,a[ff]=null})}),!0):!1};reactDom_production_min.unstable_batchedUpdates=Wj;reactDom_production_min.unstable_createPortal=function(a,i){return uk(a,i,2<arguments.length&&arguments[2]!==void 0?arguments[2]:null)};reactDom_production_min.unstable_renderSubtreeIntoContainer=function(a,i,e,o){if(!rk(e))throw Error(y(200));if(a==null||a._reactInternals===void 0)throw Error(y(38));return tk(a,i,e,!1,o)};reactDom_production_min.version="17.0.2";function checkDCE(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__=="undefined"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(a){console.error(a)}}checkDCE(),reactDom.exports=reactDom_production_min;var ReactDOM=reactDom.exports;let logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(a,i,e){const o=a.match(i);return o&&o.length>=e&&parseInt(o[e],10)}function wrapPeerConnectionEvent(a,i,e){if(!a.RTCPeerConnection)return;const o=a.RTCPeerConnection.prototype,s=o.addEventListener;o.addEventListener=function(d,_){if(d!==i)return s.apply(this,arguments);const b=k=>{const j=e(k);j&&(_.handleEvent?_.handleEvent(j):_(j))};return this._eventMap=this._eventMap||{},this._eventMap[i]||(this._eventMap[i]=new Map),this._eventMap[i].set(_,b),s.apply(this,[d,b])};const c=o.removeEventListener;o.removeEventListener=function(d,_){if(d!==i||!this._eventMap||!this._eventMap[i])return c.apply(this,arguments);if(!this._eventMap[i].has(_))return c.apply(this,arguments);const b=this._eventMap[i].get(_);return this._eventMap[i].delete(_),this._eventMap[i].size===0&&delete this._eventMap[i],Object.keys(this._eventMap).length===0&&delete this._eventMap,c.apply(this,[d,b])},Object.defineProperty(o,"on"+i,{get(){return this["_on"+i]},set(d){this["_on"+i]&&(this.removeEventListener(i,this["_on"+i]),delete this["_on"+i]),d&&this.addEventListener(i,this["_on"+i]=d)},enumerable:!0,configurable:!0})}function disableLog(a){return typeof a!="boolean"?new Error("Argument type: "+typeof a+". Please use a boolean."):(logDisabled_=a,a?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(a){return typeof a!="boolean"?new Error("Argument type: "+typeof a+". Please use a boolean."):(deprecationWarnings_=!a,"adapter.js deprecation warnings "+(a?"disabled":"enabled"))}function log$15(){if(typeof window=="object"){if(logDisabled_)return;typeof console!="undefined"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function deprecated(a,i){!deprecationWarnings_||console.warn(a+" is deprecated, please use "+i+" instead.")}function detectBrowser(a){const i={browser:null,version:null};if(typeof a=="undefined"||!a.navigator)return i.browser="Not a browser.",i;const{navigator:e}=a;if(e.mozGetUserMedia)i.browser="firefox",i.version=extractVersion(e.userAgent,/Firefox\/(\d+)\./,1);else if(e.webkitGetUserMedia||a.isSecureContext===!1&&a.webkitRTCPeerConnection&&!a.RTCIceGatherer)i.browser="chrome",i.version=extractVersion(e.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(a.RTCPeerConnection&&e.userAgent.match(/AppleWebKit\/(\d+)\./))i.browser="safari",i.version=extractVersion(e.userAgent,/AppleWebKit\/(\d+)\./,1),i.supportsUnifiedPlan=a.RTCRtpTransceiver&&"currentDirection"in a.RTCRtpTransceiver.prototype;else return i.browser="Not a supported browser.",i;return i}function isObject$2(a){return Object.prototype.toString.call(a)==="[object Object]"}function compactObject(a){return isObject$2(a)?Object.keys(a).reduce(function(i,e){const o=isObject$2(a[e]),s=o?compactObject(a[e]):a[e],c=o&&!Object.keys(s).length;return s===void 0||c?i:Object.assign(i,{[e]:s})},{}):a}function walkStats(a,i,e){!i||e.has(i.id)||(e.set(i.id,i),Object.keys(i).forEach(o=>{o.endsWith("Id")?walkStats(a,a.get(i[o]),e):o.endsWith("Ids")&&i[o].forEach(s=>{walkStats(a,a.get(s),e)})}))}function filterStats(a,i,e){const o=e?"outbound-rtp":"inbound-rtp",s=new Map;if(i===null)return s;const c=[];return a.forEach(d=>{d.type==="track"&&d.trackIdentifier===i.id&&c.push(d)}),c.forEach(d=>{a.forEach(_=>{_.type===o&&_.trackId===d.id&&walkStats(a,_,s)})}),s}const logging=log$15;function shimGetUserMedia$2(a,i){const e=a&&a.navigator;if(!e.mediaDevices)return;const o=function(_){if(typeof _!="object"||_.mandatory||_.optional)return _;const b={};return Object.keys(_).forEach(k=>{if(k==="require"||k==="advanced"||k==="mediaSource")return;const j=typeof _[k]=="object"?_[k]:{ideal:_[k]};j.exact!==void 0&&typeof j.exact=="number"&&(j.min=j.max=j.exact);const $=function(_e,et){return _e?_e+et.charAt(0).toUpperCase()+et.slice(1):et==="deviceId"?"sourceId":et};if(j.ideal!==void 0){b.optional=b.optional||[];let _e={};typeof j.ideal=="number"?(_e[$("min",k)]=j.ideal,b.optional.push(_e),_e={},_e[$("max",k)]=j.ideal,b.optional.push(_e)):(_e[$("",k)]=j.ideal,b.optional.push(_e))}j.exact!==void 0&&typeof j.exact!="number"?(b.mandatory=b.mandatory||{},b.mandatory[$("",k)]=j.exact):["min","max"].forEach(_e=>{j[_e]!==void 0&&(b.mandatory=b.mandatory||{},b.mandatory[$(_e,k)]=j[_e])})}),_.advanced&&(b.optional=(b.optional||[]).concat(_.advanced)),b},s=function(_,b){if(i.version>=61)return b(_);if(_=JSON.parse(JSON.stringify(_)),_&&typeof _.audio=="object"){const k=function(j,$,_e){$ in j&&!(_e in j)&&(j[_e]=j[$],delete j[$])};_=JSON.parse(JSON.stringify(_)),k(_.audio,"autoGainControl","googAutoGainControl"),k(_.audio,"noiseSuppression","googNoiseSuppression"),_.audio=o(_.audio)}if(_&&typeof _.video=="object"){let k=_.video.facingMode;k=k&&(typeof k=="object"?k:{ideal:k});const j=i.version<66;if(k&&(k.exact==="user"||k.exact==="environment"||k.ideal==="user"||k.ideal==="environment")&&!(e.mediaDevices.getSupportedConstraints&&e.mediaDevices.getSupportedConstraints().facingMode&&!j)){delete _.video.facingMode;let $;if(k.exact==="environment"||k.ideal==="environment"?$=["back","rear"]:(k.exact==="user"||k.ideal==="user")&&($=["front"]),$)return e.mediaDevices.enumerateDevices().then(_e=>{_e=_e.filter(tt=>tt.kind==="videoinput");let et=_e.find(tt=>$.some(rt=>tt.label.toLowerCase().includes(rt)));return!et&&_e.length&&$.includes("back")&&(et=_e[_e.length-1]),et&&(_.video.deviceId=k.exact?{exact:et.deviceId}:{ideal:et.deviceId}),_.video=o(_.video),logging("chrome: "+JSON.stringify(_)),b(_)})}_.video=o(_.video)}return logging("chrome: "+JSON.stringify(_)),b(_)},c=function(_){return i.version>=64?_:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[_.name]||_.name,message:_.message,constraint:_.constraint||_.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},d=function(_,b,k){s(_,j=>{e.webkitGetUserMedia(j,b,$=>{k&&k(c($))})})};if(e.getUserMedia=d.bind(e),e.mediaDevices.getUserMedia){const _=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(b){return s(b,k=>_(k).then(j=>{if(k.audio&&!j.getAudioTracks().length||k.video&&!j.getVideoTracks().length)throw j.getTracks().forEach($=>{$.stop()}),new DOMException("","NotFoundError");return j},j=>Promise.reject(c(j))))}}}function shimGetDisplayMedia$1(a,i){if(!(a.navigator.mediaDevices&&"getDisplayMedia"in a.navigator.mediaDevices)&&!!a.navigator.mediaDevices){if(typeof i!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}a.navigator.mediaDevices.getDisplayMedia=function(o){return i(o).then(s=>{const c=o.video&&o.video.width,d=o.video&&o.video.height,_=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:_||3}},c&&(o.video.mandatory.maxWidth=c),d&&(o.video.mandatory.maxHeight=d),a.navigator.mediaDevices.getUserMedia(o)})}}}function shimMediaStream(a){a.MediaStream=a.MediaStream||a.webkitMediaStream}function shimOnTrack$1(a){if(typeof a=="object"&&a.RTCPeerConnection&&!("ontrack"in a.RTCPeerConnection.prototype)){Object.defineProperty(a.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const i=a.RTCPeerConnection.prototype.setRemoteDescription;a.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",s=>{let c;a.RTCPeerConnection.prototype.getReceivers?c=this.getReceivers().find(_=>_.track&&_.track.id===s.track.id):c={track:s.track};const d=new Event("track");d.track=s.track,d.receiver=c,d.transceiver={receiver:c},d.streams=[o.stream],this.dispatchEvent(d)}),o.stream.getTracks().forEach(s=>{let c;a.RTCPeerConnection.prototype.getReceivers?c=this.getReceivers().find(_=>_.track&&_.track.id===s.id):c={track:s};const d=new Event("track");d.track=s,d.receiver=c,d.transceiver={receiver:c},d.streams=[o.stream],this.dispatchEvent(d)})},this.addEventListener("addstream",this._ontrackpoly)),i.apply(this,arguments)}}else wrapPeerConnectionEvent(a,"track",i=>(i.transceiver||Object.defineProperty(i,"transceiver",{value:{receiver:i.receiver}}),i))}function shimGetSendersWithDtmf(a){if(typeof a=="object"&&a.RTCPeerConnection&&!("getSenders"in a.RTCPeerConnection.prototype)&&"createDTMFSender"in a.RTCPeerConnection.prototype){const i=function(s,c){return{track:c,get dtmf(){return this._dtmf===void 0&&(c.kind==="audio"?this._dtmf=s.createDTMFSender(c):this._dtmf=null),this._dtmf},_pc:s}};if(!a.RTCPeerConnection.prototype.getSenders){a.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=a.RTCPeerConnection.prototype.addTrack;a.RTCPeerConnection.prototype.addTrack=function(_,b){let k=s.apply(this,arguments);return k||(k=i(this,_),this._senders.push(k)),k};const c=a.RTCPeerConnection.prototype.removeTrack;a.RTCPeerConnection.prototype.removeTrack=function(_){c.apply(this,arguments);const b=this._senders.indexOf(_);b!==-1&&this._senders.splice(b,1)}}const e=a.RTCPeerConnection.prototype.addStream;a.RTCPeerConnection.prototype.addStream=function(c){this._senders=this._senders||[],e.apply(this,[c]),c.getTracks().forEach(d=>{this._senders.push(i(this,d))})};const o=a.RTCPeerConnection.prototype.removeStream;a.RTCPeerConnection.prototype.removeStream=function(c){this._senders=this._senders||[],o.apply(this,[c]),c.getTracks().forEach(d=>{const _=this._senders.find(b=>b.track===d);_&&this._senders.splice(this._senders.indexOf(_),1)})}}else if(typeof a=="object"&&a.RTCPeerConnection&&"getSenders"in a.RTCPeerConnection.prototype&&"createDTMFSender"in a.RTCPeerConnection.prototype&&a.RTCRtpSender&&!("dtmf"in a.RTCRtpSender.prototype)){const i=a.RTCPeerConnection.prototype.getSenders;a.RTCPeerConnection.prototype.getSenders=function(){const o=i.apply(this,[]);return o.forEach(s=>s._pc=this),o},Object.defineProperty(a.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function shimGetStats(a){if(!a.RTCPeerConnection)return;const i=a.RTCPeerConnection.prototype.getStats;a.RTCPeerConnection.prototype.getStats=function(){const[o,s,c]=arguments;if(arguments.length>0&&typeof o=="function")return i.apply(this,arguments);if(i.length===0&&(arguments.length===0||typeof o!="function"))return i.apply(this,[]);const d=function(b){const k={};return b.result().forEach($=>{const _e={id:$.id,timestamp:$.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[$.type]||$.type};$.names().forEach(et=>{_e[et]=$.stat(et)}),k[_e.id]=_e}),k},_=function(b){return new Map(Object.keys(b).map(k=>[k,b[k]]))};if(arguments.length>=2){const b=function(k){s(_(d(k)))};return i.apply(this,[b,o])}return new Promise((b,k)=>{i.apply(this,[function(j){b(_(d(j)))},k])}).then(s,c)}}function shimSenderReceiverGetStats(a){if(!(typeof a=="object"&&a.RTCPeerConnection&&a.RTCRtpSender&&a.RTCRtpReceiver))return;if(!("getStats"in a.RTCRtpSender.prototype)){const e=a.RTCPeerConnection.prototype.getSenders;e&&(a.RTCPeerConnection.prototype.getSenders=function(){const c=e.apply(this,[]);return c.forEach(d=>d._pc=this),c});const o=a.RTCPeerConnection.prototype.addTrack;o&&(a.RTCPeerConnection.prototype.addTrack=function(){const c=o.apply(this,arguments);return c._pc=this,c}),a.RTCRtpSender.prototype.getStats=function(){const c=this;return this._pc.getStats().then(d=>filterStats(d,c.track,!0))}}if(!("getStats"in a.RTCRtpReceiver.prototype)){const e=a.RTCPeerConnection.prototype.getReceivers;e&&(a.RTCPeerConnection.prototype.getReceivers=function(){const s=e.apply(this,[]);return s.forEach(c=>c._pc=this),s}),wrapPeerConnectionEvent(a,"track",o=>(o.receiver._pc=o.srcElement,o)),a.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(c=>filterStats(c,s.track,!1))}}if(!("getStats"in a.RTCRtpSender.prototype&&"getStats"in a.RTCRtpReceiver.prototype))return;const i=a.RTCPeerConnection.prototype.getStats;a.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof a.MediaStreamTrack){const o=arguments[0];let s,c,d;return this.getSenders().forEach(_=>{_.track===o&&(s?d=!0:s=_)}),this.getReceivers().forEach(_=>(_.track===o&&(c?d=!0:c=_),_.track===o)),d||s&&c?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():c?c.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return i.apply(this,arguments)}}function shimAddTrackRemoveTrackWithNative(a){a.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(d=>this._shimmedLocalStreams[d][0])};const i=a.RTCPeerConnection.prototype.addTrack;a.RTCPeerConnection.prototype.addTrack=function(d,_){if(!_)return i.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const b=i.apply(this,arguments);return this._shimmedLocalStreams[_.id]?this._shimmedLocalStreams[_.id].indexOf(b)===-1&&this._shimmedLocalStreams[_.id].push(b):this._shimmedLocalStreams[_.id]=[_,b],b};const e=a.RTCPeerConnection.prototype.addStream;a.RTCPeerConnection.prototype.addStream=function(d){this._shimmedLocalStreams=this._shimmedLocalStreams||{},d.getTracks().forEach(k=>{if(this.getSenders().find($=>$.track===k))throw new DOMException("Track already exists.","InvalidAccessError")});const _=this.getSenders();e.apply(this,arguments);const b=this.getSenders().filter(k=>_.indexOf(k)===-1);this._shimmedLocalStreams[d.id]=[d].concat(b)};const o=a.RTCPeerConnection.prototype.removeStream;a.RTCPeerConnection.prototype.removeStream=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[d.id],o.apply(this,arguments)};const s=a.RTCPeerConnection.prototype.removeTrack;a.RTCPeerConnection.prototype.removeTrack=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},d&&Object.keys(this._shimmedLocalStreams).forEach(_=>{const b=this._shimmedLocalStreams[_].indexOf(d);b!==-1&&this._shimmedLocalStreams[_].splice(b,1),this._shimmedLocalStreams[_].length===1&&delete this._shimmedLocalStreams[_]}),s.apply(this,arguments)}}function shimAddTrackRemoveTrack(a,i){if(!a.RTCPeerConnection)return;if(a.RTCPeerConnection.prototype.addTrack&&i.version>=65)return shimAddTrackRemoveTrackWithNative(a);const e=a.RTCPeerConnection.prototype.getLocalStreams;a.RTCPeerConnection.prototype.getLocalStreams=function(){const j=e.apply(this);return this._reverseStreams=this._reverseStreams||{},j.map($=>this._reverseStreams[$.id])};const o=a.RTCPeerConnection.prototype.addStream;a.RTCPeerConnection.prototype.addStream=function(j){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},j.getTracks().forEach($=>{if(this.getSenders().find(et=>et.track===$))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[j.id]){const $=new a.MediaStream(j.getTracks());this._streams[j.id]=$,this._reverseStreams[$.id]=j,j=$}o.apply(this,[j])};const s=a.RTCPeerConnection.prototype.removeStream;a.RTCPeerConnection.prototype.removeStream=function(j){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[j.id]||j]),delete this._reverseStreams[this._streams[j.id]?this._streams[j.id].id:j.id],delete this._streams[j.id]},a.RTCPeerConnection.prototype.addTrack=function(j,$){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const _e=[].slice.call(arguments,1);if(_e.length!==1||!_e[0].getTracks().find(rt=>rt===j))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(rt=>rt.track===j))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const tt=this._streams[$.id];if(tt)tt.addTrack(j),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const rt=new a.MediaStream([j]);this._streams[$.id]=rt,this._reverseStreams[rt.id]=$,this.addStream(rt)}return this.getSenders().find(rt=>rt.track===j)};function c(k,j){let $=j.sdp;return Object.keys(k._reverseStreams||[]).forEach(_e=>{const et=k._reverseStreams[_e],tt=k._streams[et.id];$=$.replace(new RegExp(tt.id,"g"),et.id)}),new RTCSessionDescription({type:j.type,sdp:$})}function d(k,j){let $=j.sdp;return Object.keys(k._reverseStreams||[]).forEach(_e=>{const et=k._reverseStreams[_e],tt=k._streams[et.id];$=$.replace(new RegExp(et.id,"g"),tt.id)}),new RTCSessionDescription({type:j.type,sdp:$})}["createOffer","createAnswer"].forEach(function(k){const j=a.RTCPeerConnection.prototype[k],$={[k](){const _e=arguments;return arguments.length&&typeof arguments[0]=="function"?j.apply(this,[tt=>{const rt=c(this,tt);_e[0].apply(null,[rt])},tt=>{_e[1]&&_e[1].apply(null,tt)},arguments[2]]):j.apply(this,arguments).then(tt=>c(this,tt))}};a.RTCPeerConnection.prototype[k]=$[k]});const _=a.RTCPeerConnection.prototype.setLocalDescription;a.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?_.apply(this,arguments):(arguments[0]=d(this,arguments[0]),_.apply(this,arguments))};const b=Object.getOwnPropertyDescriptor(a.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(a.RTCPeerConnection.prototype,"localDescription",{get(){const k=b.get.apply(this);return k.type===""?k:c(this,k)}}),a.RTCPeerConnection.prototype.removeTrack=function(j){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!j._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(j._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let _e;Object.keys(this._streams).forEach(et=>{this._streams[et].getTracks().find(rt=>j.track===rt)&&(_e=this._streams[et])}),_e&&(_e.getTracks().length===1?this.removeStream(this._reverseStreams[_e.id]):_e.removeTrack(j.track),this.dispatchEvent(new Event("negotiationneeded")))}}function shimPeerConnection$1(a,i){!a.RTCPeerConnection&&a.webkitRTCPeerConnection&&(a.RTCPeerConnection=a.webkitRTCPeerConnection),!!a.RTCPeerConnection&&i.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){const o=a.RTCPeerConnection.prototype[e],s={[e](){return arguments[0]=new(e==="addIceCandidate"?a.RTCIceCandidate:a.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)}};a.RTCPeerConnection.prototype[e]=s[e]})}function fixNegotiationNeeded(a,i){wrapPeerConnectionEvent(a,"negotiationneeded",e=>{const o=e.target;if(!((i.version<72||o.getConfiguration&&o.getConfiguration().sdpSemantics==="plan-b")&&o.signalingState!=="stable"))return e})}var chromeShim=Object.freeze(Object.defineProperty({__proto__:null,shimMediaStream,shimOnTrack:shimOnTrack$1,shimGetSendersWithDtmf,shimGetStats,shimSenderReceiverGetStats,shimAddTrackRemoveTrackWithNative,shimAddTrackRemoveTrack,shimPeerConnection:shimPeerConnection$1,fixNegotiationNeeded,shimGetUserMedia:shimGetUserMedia$2,shimGetDisplayMedia:shimGetDisplayMedia$1},Symbol.toStringTag,{value:"Module"}));function shimGetUserMedia$1(a,i){const e=a&&a.navigator,o=a&&a.MediaStreamTrack;if(e.getUserMedia=function(s,c,d){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),e.mediaDevices.getUserMedia(s).then(c,d)},!(i.version>55&&"autoGainControl"in e.mediaDevices.getSupportedConstraints())){const s=function(d,_,b){_ in d&&!(b in d)&&(d[b]=d[_],delete d[_])},c=e.mediaDevices.getUserMedia.bind(e.mediaDevices);if(e.mediaDevices.getUserMedia=function(d){return typeof d=="object"&&typeof d.audio=="object"&&(d=JSON.parse(JSON.stringify(d)),s(d.audio,"autoGainControl","mozAutoGainControl"),s(d.audio,"noiseSuppression","mozNoiseSuppression")),c(d)},o&&o.prototype.getSettings){const d=o.prototype.getSettings;o.prototype.getSettings=function(){const _=d.apply(this,arguments);return s(_,"mozAutoGainControl","autoGainControl"),s(_,"mozNoiseSuppression","noiseSuppression"),_}}if(o&&o.prototype.applyConstraints){const d=o.prototype.applyConstraints;o.prototype.applyConstraints=function(_){return this.kind==="audio"&&typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)),s(_,"autoGainControl","mozAutoGainControl"),s(_,"noiseSuppression","mozNoiseSuppression")),d.apply(this,[_])}}}}function shimGetDisplayMedia(a,i){a.navigator.mediaDevices&&"getDisplayMedia"in a.navigator.mediaDevices||!a.navigator.mediaDevices||(a.navigator.mediaDevices.getDisplayMedia=function(o){if(!(o&&o.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return o.video===!0?o.video={mediaSource:i}:o.video.mediaSource=i,a.navigator.mediaDevices.getUserMedia(o)})}function shimOnTrack(a){typeof a=="object"&&a.RTCTrackEvent&&"receiver"in a.RTCTrackEvent.prototype&&!("transceiver"in a.RTCTrackEvent.prototype)&&Object.defineProperty(a.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimPeerConnection(a,i){if(typeof a!="object"||!(a.RTCPeerConnection||a.mozRTCPeerConnection))return;!a.RTCPeerConnection&&a.mozRTCPeerConnection&&(a.RTCPeerConnection=a.mozRTCPeerConnection),i.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const c=a.RTCPeerConnection.prototype[s],d={[s](){return arguments[0]=new(s==="addIceCandidate"?a.RTCIceCandidate:a.RTCSessionDescription)(arguments[0]),c.apply(this,arguments)}};a.RTCPeerConnection.prototype[s]=d[s]});const e={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},o=a.RTCPeerConnection.prototype.getStats;a.RTCPeerConnection.prototype.getStats=function(){const[c,d,_]=arguments;return o.apply(this,[c||null]).then(b=>{if(i.version<53&&!d)try{b.forEach(k=>{k.type=e[k.type]||k.type})}catch(k){if(k.name!=="TypeError")throw k;b.forEach((j,$)=>{b.set($,Object.assign({},j,{type:e[j.type]||j.type}))})}return b}).then(d,_)}}function shimSenderGetStats(a){if(!(typeof a=="object"&&a.RTCPeerConnection&&a.RTCRtpSender)||a.RTCRtpSender&&"getStats"in a.RTCRtpSender.prototype)return;const i=a.RTCPeerConnection.prototype.getSenders;i&&(a.RTCPeerConnection.prototype.getSenders=function(){const s=i.apply(this,[]);return s.forEach(c=>c._pc=this),s});const e=a.RTCPeerConnection.prototype.addTrack;e&&(a.RTCPeerConnection.prototype.addTrack=function(){const s=e.apply(this,arguments);return s._pc=this,s}),a.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function shimReceiverGetStats(a){if(!(typeof a=="object"&&a.RTCPeerConnection&&a.RTCRtpSender)||a.RTCRtpSender&&"getStats"in a.RTCRtpReceiver.prototype)return;const i=a.RTCPeerConnection.prototype.getReceivers;i&&(a.RTCPeerConnection.prototype.getReceivers=function(){const o=i.apply(this,[]);return o.forEach(s=>s._pc=this),o}),wrapPeerConnectionEvent(a,"track",e=>(e.receiver._pc=e.srcElement,e)),a.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function shimRemoveStream(a){!a.RTCPeerConnection||"removeStream"in a.RTCPeerConnection.prototype||(a.RTCPeerConnection.prototype.removeStream=function(e){deprecated("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&e.getTracks().includes(o.track)&&this.removeTrack(o)})})}function shimRTCDataChannel(a){a.DataChannel&&!a.RTCDataChannel&&(a.RTCDataChannel=a.DataChannel)}function shimAddTransceiver(a){if(!(typeof a=="object"&&a.RTCPeerConnection))return;const i=a.RTCPeerConnection.prototype.addTransceiver;i&&(a.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const o=arguments[1],s=o&&"sendEncodings"in o;s&&o.sendEncodings.forEach(d=>{if("rid"in d&&!/^[a-z0-9]{0,16}$/i.test(d.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in d&&!(parseFloat(d.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in d&&!(parseFloat(d.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const c=i.apply(this,arguments);if(s){const{sender:d}=c,_=d.getParameters();(!("encodings"in _)||_.encodings.length===1&&Object.keys(_.encodings[0]).length===0)&&(_.encodings=o.sendEncodings,d.sendEncodings=o.sendEncodings,this.setParametersPromises.push(d.setParameters(_).then(()=>{delete d.sendEncodings}).catch(()=>{delete d.sendEncodings})))}return c})}function shimGetParameters(a){if(!(typeof a=="object"&&a.RTCRtpSender))return;const i=a.RTCRtpSender.prototype.getParameters;i&&(a.RTCRtpSender.prototype.getParameters=function(){const o=i.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function shimCreateOffer(a){if(!(typeof a=="object"&&a.RTCPeerConnection))return;const i=a.RTCPeerConnection.prototype.createOffer;a.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>i.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):i.apply(this,arguments)}}function shimCreateAnswer(a){if(!(typeof a=="object"&&a.RTCPeerConnection))return;const i=a.RTCPeerConnection.prototype.createAnswer;a.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>i.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):i.apply(this,arguments)}}var firefoxShim=Object.freeze(Object.defineProperty({__proto__:null,shimOnTrack,shimPeerConnection,shimSenderGetStats,shimReceiverGetStats,shimRemoveStream,shimRTCDataChannel,shimAddTransceiver,shimGetParameters,shimCreateOffer,shimCreateAnswer,shimGetUserMedia:shimGetUserMedia$1,shimGetDisplayMedia},Symbol.toStringTag,{value:"Module"}));function shimLocalStreamsAPI(a){if(!(typeof a!="object"||!a.RTCPeerConnection)){if("getLocalStreams"in a.RTCPeerConnection.prototype||(a.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in a.RTCPeerConnection.prototype)){const i=a.RTCPeerConnection.prototype.addTrack;a.RTCPeerConnection.prototype.addStream=function(o){this._localStreams||(this._localStreams=[]),this._localStreams.includes(o)||this._localStreams.push(o),o.getAudioTracks().forEach(s=>i.call(this,s,o)),o.getVideoTracks().forEach(s=>i.call(this,s,o))},a.RTCPeerConnection.prototype.addTrack=function(o,...s){return s&&s.forEach(c=>{this._localStreams?this._localStreams.includes(c)||this._localStreams.push(c):this._localStreams=[c]}),i.apply(this,arguments)}}"removeStream"in a.RTCPeerConnection.prototype||(a.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(e);if(o===-1)return;this._localStreams.splice(o,1);const s=e.getTracks();this.getSenders().forEach(c=>{s.includes(c.track)&&this.removeTrack(c)})})}}function shimRemoteStreamsAPI(a){if(!(typeof a!="object"||!a.RTCPeerConnection)&&("getRemoteStreams"in a.RTCPeerConnection.prototype||(a.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in a.RTCPeerConnection.prototype))){Object.defineProperty(a.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=o=>{o.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const c=new Event("addstream");c.stream=s,this.dispatchEvent(c)})})}});const i=a.RTCPeerConnection.prototype.setRemoteDescription;a.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(c=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(c)>=0)return;o._remoteStreams.push(c);const d=new Event("addstream");d.stream=c,o.dispatchEvent(d)})}),i.apply(o,arguments)}}}function shimCallbacksAPI(a){if(typeof a!="object"||!a.RTCPeerConnection)return;const i=a.RTCPeerConnection.prototype,e=i.createOffer,o=i.createAnswer,s=i.setLocalDescription,c=i.setRemoteDescription,d=i.addIceCandidate;i.createOffer=function(k,j){const $=arguments.length>=2?arguments[2]:arguments[0],_e=e.apply(this,[$]);return j?(_e.then(k,j),Promise.resolve()):_e},i.createAnswer=function(k,j){const $=arguments.length>=2?arguments[2]:arguments[0],_e=o.apply(this,[$]);return j?(_e.then(k,j),Promise.resolve()):_e};let _=function(b,k,j){const $=s.apply(this,[b]);return j?($.then(k,j),Promise.resolve()):$};i.setLocalDescription=_,_=function(b,k,j){const $=c.apply(this,[b]);return j?($.then(k,j),Promise.resolve()):$},i.setRemoteDescription=_,_=function(b,k,j){const $=d.apply(this,[b]);return j?($.then(k,j),Promise.resolve()):$},i.addIceCandidate=_}function shimGetUserMedia(a){const i=a&&a.navigator;if(i.mediaDevices&&i.mediaDevices.getUserMedia){const e=i.mediaDevices,o=e.getUserMedia.bind(e);i.mediaDevices.getUserMedia=s=>o(shimConstraints(s))}!i.getUserMedia&&i.mediaDevices&&i.mediaDevices.getUserMedia&&(i.getUserMedia=function(o,s,c){i.mediaDevices.getUserMedia(o).then(s,c)}.bind(i))}function shimConstraints(a){return a&&a.video!==void 0?Object.assign({},a,{video:compactObject(a.video)}):a}function shimRTCIceServerUrls(a){if(!a.RTCPeerConnection)return;const i=a.RTCPeerConnection;a.RTCPeerConnection=function(o,s){if(o&&o.iceServers){const c=[];for(let d=0;d<o.iceServers.length;d++){let _=o.iceServers[d];!_.hasOwnProperty("urls")&&_.hasOwnProperty("url")?(deprecated("RTCIceServer.url","RTCIceServer.urls"),_=JSON.parse(JSON.stringify(_)),_.urls=_.url,delete _.url,c.push(_)):c.push(o.iceServers[d])}o.iceServers=c}return new i(o,s)},a.RTCPeerConnection.prototype=i.prototype,"generateCertificate"in i&&Object.defineProperty(a.RTCPeerConnection,"generateCertificate",{get(){return i.generateCertificate}})}function shimTrackEventTransceiver(a){typeof a=="object"&&a.RTCTrackEvent&&"receiver"in a.RTCTrackEvent.prototype&&!("transceiver"in a.RTCTrackEvent.prototype)&&Object.defineProperty(a.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimCreateOfferLegacy(a){const i=a.RTCPeerConnection.prototype.createOffer;a.RTCPeerConnection.prototype.createOffer=function(o){if(o){typeof o.offerToReceiveAudio!="undefined"&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const s=this.getTransceivers().find(d=>d.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):o.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof o.offerToReceiveVideo!="undefined"&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const c=this.getTransceivers().find(d=>d.receiver.track.kind==="video");o.offerToReceiveVideo===!1&&c?c.direction==="sendrecv"?c.setDirection?c.setDirection("sendonly"):c.direction="sendonly":c.direction==="recvonly"&&(c.setDirection?c.setDirection("inactive"):c.direction="inactive"):o.offerToReceiveVideo===!0&&!c&&this.addTransceiver("video",{direction:"recvonly"})}return i.apply(this,arguments)}}function shimAudioContext(a){typeof a!="object"||a.AudioContext||(a.AudioContext=a.webkitAudioContext)}var safariShim=Object.freeze(Object.defineProperty({__proto__:null,shimLocalStreamsAPI,shimRemoteStreamsAPI,shimCallbacksAPI,shimGetUserMedia,shimConstraints,shimRTCIceServerUrls,shimTrackEventTransceiver,shimCreateOfferLegacy,shimAudioContext},Symbol.toStringTag,{value:"Module"})),sdp$1={exports:{}};(function(a){const i={};i.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)},i.localCName=i.generateIdentifier(),i.splitLines=function(e){return e.trim().split(`
  34. `).map(o=>o.trim())},i.splitSections=function(e){return e.split(`
  35. m=`).map((s,c)=>(c>0?"m="+s:s).trim()+`\r
  36. `)},i.getDescription=function(e){const o=i.splitSections(e);return o&&o[0]},i.getMediaSections=function(e){const o=i.splitSections(e);return o.shift(),o},i.matchPrefix=function(e,o){return i.splitLines(e).filter(s=>s.indexOf(o)===0)},i.parseCandidate=function(e){let o;e.indexOf("a=candidate:")===0?o=e.substring(12).split(" "):o=e.substring(10).split(" ");const s={foundation:o[0],component:{1:"rtp",2:"rtcp"}[o[1]]||o[1],protocol:o[2].toLowerCase(),priority:parseInt(o[3],10),ip:o[4],address:o[4],port:parseInt(o[5],10),type:o[7]};for(let c=8;c<o.length;c+=2)switch(o[c]){case"raddr":s.relatedAddress=o[c+1];break;case"rport":s.relatedPort=parseInt(o[c+1],10);break;case"tcptype":s.tcpType=o[c+1];break;case"ufrag":s.ufrag=o[c+1],s.usernameFragment=o[c+1];break;default:s[o[c]]===void 0&&(s[o[c]]=o[c+1]);break}return s},i.writeCandidate=function(e){const o=[];o.push(e.foundation);const s=e.component;s==="rtp"?o.push(1):s==="rtcp"?o.push(2):o.push(s),o.push(e.protocol.toUpperCase()),o.push(e.priority),o.push(e.address||e.ip),o.push(e.port);const c=e.type;return o.push("typ"),o.push(c),c!=="host"&&e.relatedAddress&&e.relatedPort&&(o.push("raddr"),o.push(e.relatedAddress),o.push("rport"),o.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()==="tcp"&&(o.push("tcptype"),o.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(o.push("ufrag"),o.push(e.usernameFragment||e.ufrag)),"candidate:"+o.join(" ")},i.parseIceOptions=function(e){return e.substr(14).split(" ")},i.parseRtpMap=function(e){let o=e.substr(9).split(" ");const s={payloadType:parseInt(o.shift(),10)};return o=o[0].split("/"),s.name=o[0],s.clockRate=parseInt(o[1],10),s.channels=o.length===3?parseInt(o[2],10):1,s.numChannels=s.channels,s},i.writeRtpMap=function(e){let o=e.payloadType;e.preferredPayloadType!==void 0&&(o=e.preferredPayloadType);const s=e.channels||e.numChannels||1;return"a=rtpmap:"+o+" "+e.name+"/"+e.clockRate+(s!==1?"/"+s:"")+`\r
  37. `},i.parseExtmap=function(e){const o=e.substr(9).split(" ");return{id:parseInt(o[0],10),direction:o[0].indexOf("/")>0?o[0].split("/")[1]:"sendrecv",uri:o[1]}},i.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&e.direction!=="sendrecv"?"/"+e.direction:"")+" "+e.uri+`\r
  38. `},i.parseFmtp=function(e){const o={};let s;const c=e.substr(e.indexOf(" ")+1).split(";");for(let d=0;d<c.length;d++)s=c[d].trim().split("="),o[s[0].trim()]=s[1];return o},i.writeFmtp=function(e){let o="",s=e.payloadType;if(e.preferredPayloadType!==void 0&&(s=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const c=[];Object.keys(e.parameters).forEach(d=>{e.parameters[d]!==void 0?c.push(d+"="+e.parameters[d]):c.push(d)}),o+="a=fmtp:"+s+" "+c.join(";")+`\r
  39. `}return o},i.parseRtcpFb=function(e){const o=e.substr(e.indexOf(" ")+1).split(" ");return{type:o.shift(),parameter:o.join(" ")}},i.writeRtcpFb=function(e){let o="",s=e.payloadType;return e.preferredPayloadType!==void 0&&(s=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(c=>{o+="a=rtcp-fb:"+s+" "+c.type+(c.parameter&&c.parameter.length?" "+c.parameter:"")+`\r
  40. `}),o},i.parseSsrcMedia=function(e){const o=e.indexOf(" "),s={ssrc:parseInt(e.substr(7,o-7),10)},c=e.indexOf(":",o);return c>-1?(s.attribute=e.substr(o+1,c-o-1),s.value=e.substr(c+1)):s.attribute=e.substr(o+1),s},i.parseSsrcGroup=function(e){const o=e.substr(13).split(" ");return{semantics:o.shift(),ssrcs:o.map(s=>parseInt(s,10))}},i.getMid=function(e){const o=i.matchPrefix(e,"a=mid:")[0];if(o)return o.substr(6)},i.parseFingerprint=function(e){const o=e.substr(14).split(" ");return{algorithm:o[0].toLowerCase(),value:o[1].toUpperCase()}},i.getDtlsParameters=function(e,o){const s=i.matchPrefix(e+o,"a=fingerprint:");return{role:"auto",fingerprints:s.map(i.parseFingerprint)}},i.writeDtlsParameters=function(e,o){let s="a=setup:"+o+`\r
  41. `;return e.fingerprints.forEach(c=>{s+="a=fingerprint:"+c.algorithm+" "+c.value+`\r
  42. `}),s},i.parseCryptoLine=function(e){const o=e.substr(9).split(" ");return{tag:parseInt(o[0],10),cryptoSuite:o[1],keyParams:o[2],sessionParams:o.slice(3)}},i.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+(typeof e.keyParams=="object"?i.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+`\r
  43. `},i.parseCryptoKeyParams=function(e){if(e.indexOf("inline:")!==0)return null;const o=e.substr(7).split("|");return{keyMethod:"inline",keySalt:o[0],lifeTime:o[1],mkiValue:o[2]?o[2].split(":")[0]:void 0,mkiLength:o[2]?o[2].split(":")[1]:void 0}},i.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},i.getCryptoParameters=function(e,o){return i.matchPrefix(e+o,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(e,o){const s=i.matchPrefix(e+o,"a=ice-ufrag:")[0],c=i.matchPrefix(e+o,"a=ice-pwd:")[0];return s&&c?{usernameFragment:s.substr(12),password:c.substr(10)}:null},i.writeIceParameters=function(e){let o="a=ice-ufrag:"+e.usernameFragment+`\r
  44. a=ice-pwd:`+e.password+`\r
  45. `;return e.iceLite&&(o+=`a=ice-lite\r
  46. `),o},i.parseRtpParameters=function(e){const o={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},c=i.splitLines(e)[0].split(" ");for(let d=3;d<c.length;d++){const _=c[d],b=i.matchPrefix(e,"a=rtpmap:"+_+" ")[0];if(b){const k=i.parseRtpMap(b),j=i.matchPrefix(e,"a=fmtp:"+_+" ");switch(k.parameters=j.length?i.parseFmtp(j[0]):{},k.rtcpFeedback=i.matchPrefix(e,"a=rtcp-fb:"+_+" ").map(i.parseRtcpFb),o.codecs.push(k),k.name.toUpperCase()){case"RED":case"ULPFEC":o.fecMechanisms.push(k.name.toUpperCase());break}}}return i.matchPrefix(e,"a=extmap:").forEach(d=>{o.headerExtensions.push(i.parseExtmap(d))}),o},i.writeRtpDescription=function(e,o){let s="";s+="m="+e+" ",s+=o.codecs.length>0?"9":"0",s+=" UDP/TLS/RTP/SAVPF ",s+=o.codecs.map(d=>d.preferredPayloadType!==void 0?d.preferredPayloadType:d.payloadType).join(" ")+`\r
  47. `,s+=`c=IN IP4 0.0.0.0\r
  48. `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
  49. `,o.codecs.forEach(d=>{s+=i.writeRtpMap(d),s+=i.writeFmtp(d),s+=i.writeRtcpFb(d)});let c=0;return o.codecs.forEach(d=>{d.maxptime>c&&(c=d.maxptime)}),c>0&&(s+="a=maxptime:"+c+`\r
  50. `),o.headerExtensions&&o.headerExtensions.forEach(d=>{s+=i.writeExtmap(d)}),s},i.parseRtpEncodingParameters=function(e){const o=[],s=i.parseRtpParameters(e),c=s.fecMechanisms.indexOf("RED")!==-1,d=s.fecMechanisms.indexOf("ULPFEC")!==-1,_=i.matchPrefix(e,"a=ssrc:").map(_e=>i.parseSsrcMedia(_e)).filter(_e=>_e.attribute==="cname"),b=_.length>0&&_[0].ssrc;let k;const j=i.matchPrefix(e,"a=ssrc-group:FID").map(_e=>_e.substr(17).split(" ").map(tt=>parseInt(tt,10)));j.length>0&&j[0].length>1&&j[0][0]===b&&(k=j[0][1]),s.codecs.forEach(_e=>{if(_e.name.toUpperCase()==="RTX"&&_e.parameters.apt){let et={ssrc:b,codecPayloadType:parseInt(_e.parameters.apt,10)};b&&k&&(et.rtx={ssrc:k}),o.push(et),c&&(et=JSON.parse(JSON.stringify(et)),et.fec={ssrc:b,mechanism:d?"red+ulpfec":"red"},o.push(et))}}),o.length===0&&b&&o.push({ssrc:b});let $=i.matchPrefix(e,"b=");return $.length&&($[0].indexOf("b=TIAS:")===0?$=parseInt($[0].substr(7),10):$[0].indexOf("b=AS:")===0?$=parseInt($[0].substr(5),10)*1e3*.95-50*40*8:$=void 0,o.forEach(_e=>{_e.maxBitrate=$})),o},i.parseRtcpParameters=function(e){const o={},s=i.matchPrefix(e,"a=ssrc:").map(_=>i.parseSsrcMedia(_)).filter(_=>_.attribute==="cname")[0];s&&(o.cname=s.value,o.ssrc=s.ssrc);const c=i.matchPrefix(e,"a=rtcp-rsize");o.reducedSize=c.length>0,o.compound=c.length===0;const d=i.matchPrefix(e,"a=rtcp-mux");return o.mux=d.length>0,o},i.writeRtcpParameters=function(e){let o="";return e.reducedSize&&(o+=`a=rtcp-rsize\r
  51. `),e.mux&&(o+=`a=rtcp-mux\r
  52. `),e.ssrc!==void 0&&e.cname&&(o+="a=ssrc:"+e.ssrc+" cname:"+e.cname+`\r
  53. `),o},i.parseMsid=function(e){let o;const s=i.matchPrefix(e,"a=msid:");if(s.length===1)return o=s[0].substr(7).split(" "),{stream:o[0],track:o[1]};const c=i.matchPrefix(e,"a=ssrc:").map(d=>i.parseSsrcMedia(d)).filter(d=>d.attribute==="msid");if(c.length>0)return o=c[0].value.split(" "),{stream:o[0],track:o[1]}},i.parseSctpDescription=function(e){const o=i.parseMLine(e),s=i.matchPrefix(e,"a=max-message-size:");let c;s.length>0&&(c=parseInt(s[0].substr(19),10)),isNaN(c)&&(c=65536);const d=i.matchPrefix(e,"a=sctp-port:");if(d.length>0)return{port:parseInt(d[0].substr(12),10),protocol:o.fmt,maxMessageSize:c};const _=i.matchPrefix(e,"a=sctpmap:");if(_.length>0){const b=_[0].substr(10).split(" ");return{port:parseInt(b[0],10),protocol:b[1],maxMessageSize:c}}},i.writeSctpDescription=function(e,o){let s=[];return e.protocol!=="DTLS/SCTP"?s=["m="+e.kind+" 9 "+e.protocol+" "+o.protocol+`\r
  54. `,`c=IN IP4 0.0.0.0\r
  55. `,"a=sctp-port:"+o.port+`\r
  56. `]:s=["m="+e.kind+" 9 "+e.protocol+" "+o.port+`\r
  57. `,`c=IN IP4 0.0.0.0\r
  58. `,"a=sctpmap:"+o.port+" "+o.protocol+` 65535\r
  59. `],o.maxMessageSize!==void 0&&s.push("a=max-message-size:"+o.maxMessageSize+`\r
  60. `),s.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(e,o,s){let c;const d=o!==void 0?o:2;return e?c=e:c=i.generateSessionId(),`v=0\r
  61. o=`+(s||"thisisadapterortc")+" "+c+" "+d+` IN IP4 127.0.0.1\r
  62. s=-\r
  63. t=0 0\r
  64. `},i.getDirection=function(e,o){const s=i.splitLines(e);for(let c=0;c<s.length;c++)switch(s[c]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[c].substr(2)}return o?i.getDirection(o):"sendrecv"},i.getKind=function(e){return i.splitLines(e)[0].split(" ")[0].substr(2)},i.isRejected=function(e){return e.split(" ",2)[1]==="0"},i.parseMLine=function(e){const s=i.splitLines(e)[0].substr(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},i.parseOLine=function(e){const s=i.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},i.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;const o=i.splitLines(e);for(let s=0;s<o.length;s++)if(o[s].length<2||o[s].charAt(1)!=="=")return!1;return!0},a.exports=i})(sdp$1);var SDPUtils=sdp$1.exports,sdp=_mergeNamespaces({__proto__:null,default:SDPUtils},[sdp$1.exports]);function shimRTCIceCandidate(a){if(!a.RTCIceCandidate||a.RTCIceCandidate&&"foundation"in a.RTCIceCandidate.prototype)return;const i=a.RTCIceCandidate;a.RTCIceCandidate=function(o){if(typeof o=="object"&&o.candidate&&o.candidate.indexOf("a=")===0&&(o=JSON.parse(JSON.stringify(o)),o.candidate=o.candidate.substr(2)),o.candidate&&o.candidate.length){const s=new i(o),c=SDPUtils.parseCandidate(o.candidate),d=Object.assign(s,c);return d.toJSON=function(){return{candidate:d.candidate,sdpMid:d.sdpMid,sdpMLineIndex:d.sdpMLineIndex,usernameFragment:d.usernameFragment}},d}return new i(o)},a.RTCIceCandidate.prototype=i.prototype,wrapPeerConnectionEvent(a,"icecandidate",e=>(e.candidate&&Object.defineProperty(e,"candidate",{value:new a.RTCIceCandidate(e.candidate),writable:"false"}),e))}function shimMaxMessageSize(a,i){if(!a.RTCPeerConnection)return;"sctp"in a.RTCPeerConnection.prototype||Object.defineProperty(a.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp=="undefined"?null:this._sctp}});const e=function(_){if(!_||!_.sdp)return!1;const b=SDPUtils.splitSections(_.sdp);return b.shift(),b.some(k=>{const j=SDPUtils.parseMLine(k);return j&&j.kind==="application"&&j.protocol.indexOf("SCTP")!==-1})},o=function(_){const b=_.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(b===null||b.length<2)return-1;const k=parseInt(b[1],10);return k!==k?-1:k},s=function(_){let b=65536;return i.browser==="firefox"&&(i.version<57?_===-1?b=16384:b=2147483637:i.version<60?b=i.version===57?65535:65536:b=2147483637),b},c=function(_,b){let k=65536;i.browser==="firefox"&&i.version===57&&(k=65535);const j=SDPUtils.matchPrefix(_.sdp,"a=max-message-size:");return j.length>0?k=parseInt(j[0].substr(19),10):i.browser==="firefox"&&b!==-1&&(k=2147483637),k},d=a.RTCPeerConnection.prototype.setRemoteDescription;a.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,i.browser==="chrome"&&i.version>=76){const{sdpSemantics:b}=this.getConfiguration();b==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp=="undefined"?null:this._sctp},enumerable:!0,configurable:!0})}if(e(arguments[0])){const b=o(arguments[0]),k=s(b),j=c(arguments[0],b);let $;k===0&&j===0?$=Number.POSITIVE_INFINITY:k===0||j===0?$=Math.max(k,j):$=Math.min(k,j);const _e={};Object.defineProperty(_e,"maxMessageSize",{get(){return $}}),this._sctp=_e}return d.apply(this,arguments)}}function shimSendThrowTypeError(a){if(!(a.RTCPeerConnection&&"createDataChannel"in a.RTCPeerConnection.prototype))return;function i(o,s){const c=o.send;o.send=function(){const _=arguments[0],b=_.length||_.size||_.byteLength;if(o.readyState==="open"&&s.sctp&&b>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return c.apply(o,arguments)}}const e=a.RTCPeerConnection.prototype.createDataChannel;a.RTCPeerConnection.prototype.createDataChannel=function(){const s=e.apply(this,arguments);return i(s,this),s},wrapPeerConnectionEvent(a,"datachannel",o=>(i(o.channel,o.target),o))}function shimConnectionState(a){if(!a.RTCPeerConnection||"connectionState"in a.RTCPeerConnection.prototype)return;const i=a.RTCPeerConnection.prototype;Object.defineProperty(i,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(i,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const o=i[e];i[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const c=s.target;if(c._lastConnectionState!==c.connectionState){c._lastConnectionState=c.connectionState;const d=new Event("connectionstatechange",s);c.dispatchEvent(d)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),o.apply(this,arguments)}})}function removeExtmapAllowMixed(a,i){if(!a.RTCPeerConnection||i.browser==="chrome"&&i.version>=71||i.browser==="safari"&&i.version>=605)return;const e=a.RTCPeerConnection.prototype.setRemoteDescription;a.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
  65. a=extmap-allow-mixed`)!==-1){const c=s.sdp.split(`
  66. `).filter(d=>d.trim()!=="a=extmap-allow-mixed").join(`
  67. `);a.RTCSessionDescription&&s instanceof a.RTCSessionDescription?arguments[0]=new a.RTCSessionDescription({type:s.type,sdp:c}):s.sdp=c}return e.apply(this,arguments)}}function shimAddIceCandidateNullOrEmpty(a,i){if(!(a.RTCPeerConnection&&a.RTCPeerConnection.prototype))return;const e=a.RTCPeerConnection.prototype.addIceCandidate;!e||e.length===0||(a.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(i.browser==="chrome"&&i.version<78||i.browser==="firefox"&&i.version<68||i.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():e.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function shimParameterlessSetLocalDescription(a,i){if(!(a.RTCPeerConnection&&a.RTCPeerConnection.prototype))return;const e=a.RTCPeerConnection.prototype.setLocalDescription;!e||e.length===0||(a.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return e.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?e.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(d=>e.apply(this,[d]))})}var commonShim=Object.freeze(Object.defineProperty({__proto__:null,shimRTCIceCandidate,shimMaxMessageSize,shimSendThrowTypeError,shimConnectionState,removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty,shimParameterlessSetLocalDescription},Symbol.toStringTag,{value:"Module"}));function adapterFactory({window:a}={},i={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const e=log$15,o=detectBrowser(a),s={browserDetails:o,commonShim,extractVersion,disableLog,disableWarnings,sdp};switch(o.browser){case"chrome":if(!chromeShim||!shimPeerConnection$1||!i.shimChrome)return e("Chrome shim is not included in this adapter release."),s;if(o.version===null)return e("Chrome shim can not determine version, not shimming."),s;e("adapter.js shimming chrome."),s.browserShim=chromeShim,shimAddIceCandidateNullOrEmpty(a,o),shimParameterlessSetLocalDescription(a),shimGetUserMedia$2(a,o),shimMediaStream(a),shimPeerConnection$1(a,o),shimOnTrack$1(a),shimAddTrackRemoveTrack(a,o),shimGetSendersWithDtmf(a),shimGetStats(a),shimSenderReceiverGetStats(a),fixNegotiationNeeded(a,o),shimRTCIceCandidate(a),shimConnectionState(a),shimMaxMessageSize(a,o),shimSendThrowTypeError(a),removeExtmapAllowMixed(a,o);break;case"firefox":if(!firefoxShim||!shimPeerConnection||!i.shimFirefox)return e("Firefox shim is not included in this adapter release."),s;e("adapter.js shimming firefox."),s.browserShim=firefoxShim,shimAddIceCandidateNullOrEmpty(a,o),shimParameterlessSetLocalDescription(a),shimGetUserMedia$1(a,o),shimPeerConnection(a,o),shimOnTrack(a),shimRemoveStream(a),shimSenderGetStats(a),shimReceiverGetStats(a),shimRTCDataChannel(a),shimAddTransceiver(a),shimGetParameters(a),shimCreateOffer(a),shimCreateAnswer(a),shimRTCIceCandidate(a),shimConnectionState(a),shimMaxMessageSize(a,o),shimSendThrowTypeError(a);break;case"safari":if(!safariShim||!i.shimSafari)return e("Safari shim is not included in this adapter release."),s;e("adapter.js shimming safari."),s.browserShim=safariShim,shimAddIceCandidateNullOrEmpty(a,o),shimParameterlessSetLocalDescription(a),shimRTCIceServerUrls(a),shimCreateOfferLegacy(a),shimCallbacksAPI(a),shimLocalStreamsAPI(a),shimRemoteStreamsAPI(a),shimTrackEventTransceiver(a),shimGetUserMedia(a),shimAudioContext(a),shimRTCIceCandidate(a),shimMaxMessageSize(a,o),shimSendThrowTypeError(a),removeExtmapAllowMixed(a,o);break;default:e("Unsupported browser!");break}return s}adapterFactory({window:typeof window=="undefined"?void 0:window});Promise.prototype._timeout=function(a,i){let e;return new Promise((o,s)=>(e=window.setTimeout(()=>{s(i)},a),this.then(c=>{clearTimeout(e),o(c)},c=>{clearTimeout(e),s(c)})))};function clear(){const a=console.log;console.log=function(...i){typeof i[0]=="string"&&i[0].indexOf("Babylon.js")==0||a(...i)}}clear();var Constants=function(){function a(){}return a.ALPHA_DISABLE=0,a.ALPHA_ADD=1,a.ALPHA_COMBINE=2,a.ALPHA_SUBTRACT=3,a.ALPHA_MULTIPLY=4,a.ALPHA_MAXIMIZED=5,a.ALPHA_ONEONE=6,a.ALPHA_PREMULTIPLIED=7,a.ALPHA_PREMULTIPLIED_PORTERDUFF=8,a.ALPHA_INTERPOLATE=9,a.ALPHA_SCREENMODE=10,a.ALPHA_ONEONE_ONEONE=11,a.ALPHA_ALPHATOCOLOR=12,a.ALPHA_REVERSEONEMINUS=13,a.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,a.ALPHA_ONEONE_ONEZERO=15,a.ALPHA_EXCLUSION=16,a.ALPHA_LAYER_ACCUMULATE=17,a.ALPHA_EQUATION_ADD=0,a.ALPHA_EQUATION_SUBSTRACT=1,a.ALPHA_EQUATION_REVERSE_SUBTRACT=2,a.ALPHA_EQUATION_MAX=3,a.ALPHA_EQUATION_MIN=4,a.ALPHA_EQUATION_DARKEN=5,a.DELAYLOADSTATE_NONE=0,a.DELAYLOADSTATE_LOADED=1,a.DELAYLOADSTATE_LOADING=2,a.DELAYLOADSTATE_NOTLOADED=4,a.NEVER=512,a.ALWAYS=519,a.LESS=513,a.EQUAL=514,a.LEQUAL=515,a.GREATER=516,a.GEQUAL=518,a.NOTEQUAL=517,a.KEEP=7680,a.ZERO=0,a.REPLACE=7681,a.INCR=7682,a.DECR=7683,a.INVERT=5386,a.INCR_WRAP=34055,a.DECR_WRAP=34056,a.TEXTURE_CLAMP_ADDRESSMODE=0,a.TEXTURE_WRAP_ADDRESSMODE=1,a.TEXTURE_MIRROR_ADDRESSMODE=2,a.TEXTURE_CREATIONFLAG_STORAGE=1,a.TEXTUREFORMAT_ALPHA=0,a.TEXTUREFORMAT_LUMINANCE=1,a.TEXTUREFORMAT_LUMINANCE_ALPHA=2,a.TEXTUREFORMAT_RGB=4,a.TEXTUREFORMAT_RGBA=5,a.TEXTUREFORMAT_RED=6,a.TEXTUREFORMAT_R=6,a.TEXTUREFORMAT_RG=7,a.TEXTUREFORMAT_RED_INTEGER=8,a.TEXTUREFORMAT_R_INTEGER=8,a.TEXTUREFORMAT_RG_INTEGER=9,a.TEXTUREFORMAT_RGB_INTEGER=10,a.TEXTUREFORMAT_RGBA_INTEGER=11,a.TEXTUREFORMAT_BGRA=12,a.TEXTUREFORMAT_DEPTH24_STENCIL8=13,a.TEXTUREFORMAT_DEPTH32_FLOAT=14,a.TEXTUREFORMAT_DEPTH16=15,a.TEXTUREFORMAT_DEPTH24=16,a.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,a.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,a.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,a.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,a.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,a.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,a.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,a.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,a.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,a.TEXTURETYPE_UNSIGNED_BYTE=0,a.TEXTURETYPE_UNSIGNED_INT=0,a.TEXTURETYPE_FLOAT=1,a.TEXTURETYPE_HALF_FLOAT=2,a.TEXTURETYPE_BYTE=3,a.TEXTURETYPE_SHORT=4,a.TEXTURETYPE_UNSIGNED_SHORT=5,a.TEXTURETYPE_INT=6,a.TEXTURETYPE_UNSIGNED_INTEGER=7,a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,a.TEXTURETYPE_UNSIGNED_INT_24_8=12,a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,a.TEXTURETYPE_UNDEFINED=16,a.TEXTURE_NEAREST_SAMPLINGMODE=1,a.TEXTURE_NEAREST_NEAREST=1,a.TEXTURE_BILINEAR_SAMPLINGMODE=2,a.TEXTURE_LINEAR_LINEAR=2,a.TEXTURE_TRILINEAR_SAMPLINGMODE=3,a.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,a.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,a.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,a.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,a.TEXTURE_NEAREST_LINEAR=7,a.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,a.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,a.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,a.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,a.TEXTURE_LINEAR_NEAREST=12,a.TEXTURE_EXPLICIT_MODE=0,a.TEXTURE_SPHERICAL_MODE=1,a.TEXTURE_PLANAR_MODE=2,a.TEXTURE_CUBIC_MODE=3,a.TEXTURE_PROJECTION_MODE=4,a.TEXTURE_SKYBOX_MODE=5,a.TEXTURE_INVCUBIC_MODE=6,a.TEXTURE_EQUIRECTANGULAR_MODE=7,a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,a.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,a.TEXTURE_FILTERING_QUALITY_HIGH=64,a.TEXTURE_FILTERING_QUALITY_MEDIUM=16,a.TEXTURE_FILTERING_QUALITY_LOW=8,a.SCALEMODE_FLOOR=1,a.SCALEMODE_NEAREST=2,a.SCALEMODE_CEILING=3,a.MATERIAL_TextureDirtyFlag=1,a.MATERIAL_LightDirtyFlag=2,a.MATERIAL_FresnelDirtyFlag=4,a.MATERIAL_AttributesDirtyFlag=8,a.MATERIAL_MiscDirtyFlag=16,a.MATERIAL_PrePassDirtyFlag=32,a.MATERIAL_AllDirtyFlag=63,a.MATERIAL_TriangleFillMode=0,a.MATERIAL_WireFrameFillMode=1,a.MATERIAL_PointFillMode=2,a.MATERIAL_PointListDrawMode=3,a.MATERIAL_LineListDrawMode=4,a.MATERIAL_LineLoopDrawMode=5,a.MATERIAL_LineStripDrawMode=6,a.MATERIAL_TriangleStripDrawMode=7,a.MATERIAL_TriangleFanDrawMode=8,a.MATERIAL_ClockWiseSideOrientation=0,a.MATERIAL_CounterClockWiseSideOrientation=1,a.ACTION_NothingTrigger=0,a.ACTION_OnPickTrigger=1,a.ACTION_OnLeftPickTrigger=2,a.ACTION_OnRightPickTrigger=3,a.ACTION_OnCenterPickTrigger=4,a.ACTION_OnPickDownTrigger=5,a.ACTION_OnDoublePickTrigger=6,a.ACTION_OnPickUpTrigger=7,a.ACTION_OnPickOutTrigger=16,a.ACTION_OnLongPressTrigger=8,a.ACTION_OnPointerOverTrigger=9,a.ACTION_OnPointerOutTrigger=10,a.ACTION_OnEveryFrameTrigger=11,a.ACTION_OnIntersectionEnterTrigger=12,a.ACTION_OnIntersectionExitTrigger=13,a.ACTION_OnKeyDownTrigger=14,a.ACTION_OnKeyUpTrigger=15,a.PARTICLES_BILLBOARDMODE_Y=2,a.PARTICLES_BILLBOARDMODE_ALL=7,a.PARTICLES_BILLBOARDMODE_STRETCHED=8,a.MESHES_CULLINGSTRATEGY_STANDARD=0,a.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,a.SCENELOADER_NO_LOGGING=0,a.SCENELOADER_MINIMAL_LOGGING=1,a.SCENELOADER_SUMMARY_LOGGING=2,a.SCENELOADER_DETAILED_LOGGING=3,a.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,a.PREPASS_POSITION_TEXTURE_TYPE=1,a.PREPASS_VELOCITY_TEXTURE_TYPE=2,a.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,a.PREPASS_COLOR_TEXTURE_TYPE=4,a.PREPASS_DEPTH_TEXTURE_TYPE=5,a.PREPASS_NORMAL_TEXTURE_TYPE=6,a.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,a.BUFFER_CREATIONFLAG_READ=1,a.BUFFER_CREATIONFLAG_WRITE=2,a.BUFFER_CREATIONFLAG_READWRITE=3,a.BUFFER_CREATIONFLAG_UNIFORM=4,a.BUFFER_CREATIONFLAG_VERTEX=8,a.BUFFER_CREATIONFLAG_INDEX=16,a.BUFFER_CREATIONFLAG_STORAGE=32,a.RENDERPASS_MAIN=0,a.INPUT_ALT_KEY=18,a.INPUT_CTRL_KEY=17,a.INPUT_META_KEY1=91,a.INPUT_META_KEY2=92,a.INPUT_META_KEY3=93,a.INPUT_SHIFT_KEY=16,a.SNAPSHOTRENDERING_STANDARD=0,a.SNAPSHOTRENDERING_FAST=1,a.PERSPECTIVE_CAMERA=0,a.ORTHOGRAPHIC_CAMERA=1,a.FOVMODE_VERTICAL_FIXED=0,a.FOVMODE_HORIZONTAL_FIXED=1,a.RIG_MODE_NONE=0,a.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,a.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,a.RIG_MODE_STEREOSCOPIC_INTERLACED=14,a.RIG_MODE_VR=20,a.RIG_MODE_WEBVR=21,a.RIG_MODE_CUSTOM=22,a.MAX_SUPPORTED_UV_SETS=6,a.GL_ALPHA_EQUATION_ADD=32774,a.GL_ALPHA_EQUATION_MIN=32775,a.GL_ALPHA_EQUATION_MAX=32776,a.GL_ALPHA_EQUATION_SUBTRACT=32778,a.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,a.GL_ALPHA_FUNCTION_SRC=768,a.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,a.GL_ALPHA_FUNCTION_SRC_ALPHA=770,a.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,a.GL_ALPHA_FUNCTION_DST_ALPHA=772,a.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,a.GL_ALPHA_FUNCTION_DST_COLOR=774,a.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,a.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,a.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,a.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,a.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,a.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,a}();/*! *****************************************************************************
  68. Copyright (c) Microsoft Corporation.
  69. Permission to use, copy, modify, and/or distribute this software for any
  70. purpose with or without fee is hereby granted.
  71. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  73. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  75. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  76. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  77. PERFORMANCE OF THIS SOFTWARE.
  78. ***************************************************************************** */var extendStatics=function(a,i){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,o){e.__proto__=o}||function(e,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(e[s]=o[s])},extendStatics(a,i)};function __extends(a,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");extendStatics(a,i);function e(){this.constructor=a}a.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}var __assign=function(){return __assign=Object.assign||function(i){for(var e,o=1,s=arguments.length;o<s;o++){e=arguments[o];for(var c in e)Object.prototype.hasOwnProperty.call(e,c)&&(i[c]=e[c])}return i},__assign.apply(this,arguments)};function __decorate(a,i,e,o){var s=arguments.length,c=s<3?i:o===null?o=Object.getOwnPropertyDescriptor(i,e):o,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(a,i,e,o);else for(var _=a.length-1;_>=0;_--)(d=a[_])&&(c=(s<3?d(c):s>3?d(i,e,c):d(i,e))||c);return s>3&&c&&Object.defineProperty(i,e,c),c}function __awaiter(a,i,e,o){function s(c){return c instanceof e?c:new e(function(d){d(c)})}return new(e||(e=Promise))(function(c,d){function _(j){try{k(o.next(j))}catch($){d($)}}function b(j){try{k(o.throw(j))}catch($){d($)}}function k(j){j.done?c(j.value):s(j.value).then(_,b)}k((o=o.apply(a,i||[])).next())})}function __generator(a,i){var e={label:0,sent:function(){if(c[0]&1)throw c[1];return c[1]},trys:[],ops:[]},o,s,c,d;return d={next:_(0),throw:_(1),return:_(2)},typeof Symbol=="function"&&(d[Symbol.iterator]=function(){return this}),d;function _(k){return function(j){return b([k,j])}}function b(k){if(o)throw new TypeError("Generator is already executing.");for(;e;)try{if(o=1,s&&(c=k[0]&2?s.return:k[0]?s.throw||((c=s.return)&&c.call(s),0):s.next)&&!(c=c.call(s,k[1])).done)return c;switch(s=0,c&&(k=[k[0]&2,c.value]),k[0]){case 0:case 1:c=k;break;case 4:return e.label++,{value:k[1],done:!1};case 5:e.label++,s=k[1],k=[0];continue;case 7:k=e.ops.pop(),e.trys.pop();continue;default:if(c=e.trys,!(c=c.length>0&&c[c.length-1])&&(k[0]===6||k[0]===2)){e=0;continue}if(k[0]===3&&(!c||k[1]>c[0]&&k[1]<c[3])){e.label=k[1];break}if(k[0]===6&&e.label<c[1]){e.label=c[1],c=k;break}if(c&&e.label<c[2]){e.label=c[2],e.ops.push(k);break}c[2]&&e.ops.pop(),e.trys.pop();continue}k=i.call(a,e)}catch(j){k=[6,j],s=0}finally{o=c=0}if(k[0]&5)throw k[1];return{value:k[0]?k[1]:void 0,done:!0}}}function __spreadArray(a,i,e){if(e||arguments.length===2)for(var o=0,s=i.length,c;o<s;o++)(c||!(o in i))&&(c||(c=Array.prototype.slice.call(i,0,o)),c[o]=i[o]);return a.concat(c||Array.prototype.slice.call(i))}var EngineStore=function(){function a(){}return Object.defineProperty(a,"LastCreatedEngine",{get:function(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]},enumerable:!1,configurable:!0}),Object.defineProperty(a,"LastCreatedScene",{get:function(){return this._LastCreatedScene},enumerable:!1,configurable:!0}),a.Instances=new Array,a._LastCreatedScene=null,a.UseFallbackTexture=!0,a.FallbackTexture="",a}(),EventState=function(){function a(i,e,o,s){e===void 0&&(e=!1),this.initialize(i,e,o,s)}return a.prototype.initialize=function(i,e,o,s){return e===void 0&&(e=!1),this.mask=i,this.skipNextObservers=e,this.target=o,this.currentTarget=s,this},a}(),Observer=function(){function a(i,e,o){o===void 0&&(o=null),this.callback=i,this.mask=e,this.scope=o,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}return a}(),Observable=function(){function a(i){this._observers=new Array,this._eventState=new EventState(0),i&&(this._onObserverAdded=i)}return a.FromPromise=function(i,e){var o=new a;return i.then(function(s){o.notifyObservers(s)}).catch(function(s){if(e)e.notifyObservers(s);else throw s}),o},Object.defineProperty(a.prototype,"observers",{get:function(){return this._observers},enumerable:!1,configurable:!0}),a.prototype.add=function(i,e,o,s,c){if(e===void 0&&(e=-1),o===void 0&&(o=!1),s===void 0&&(s=null),c===void 0&&(c=!1),!i)return null;var d=new Observer(i,e,s);return d.unregisterOnNextCall=c,o?this._observers.unshift(d):this._observers.push(d),this._onObserverAdded&&this._onObserverAdded(d),d},a.prototype.addOnce=function(i){return this.add(i,void 0,void 0,void 0,!0)},a.prototype.remove=function(i){if(!i)return!1;var e=this._observers.indexOf(i);return e!==-1?(this._deferUnregister(i),!0):!1},a.prototype.removeCallback=function(i,e){for(var o=0;o<this._observers.length;o++){var s=this._observers[o];if(!s._willBeUnregistered&&s.callback===i&&(!e||e===s.scope))return this._deferUnregister(s),!0}return!1},a.prototype._deferUnregister=function(i){var e=this;i.unregisterOnNextCall=!1,i._willBeUnregistered=!0,setTimeout(function(){e._remove(i)},0)},a.prototype._remove=function(i){if(!i)return!1;var e=this._observers.indexOf(i);return e!==-1?(this._observers.splice(e,1),!0):!1},a.prototype.makeObserverTopPriority=function(i){this._remove(i),this._observers.unshift(i)},a.prototype.makeObserverBottomPriority=function(i){this._remove(i),this._observers.push(i)},a.prototype.notifyObservers=function(i,e,o,s,c){if(e===void 0&&(e=-1),!this._observers.length)return!0;var d=this._eventState;d.mask=e,d.target=o,d.currentTarget=s,d.skipNextObservers=!1,d.lastReturnValue=i,d.userInfo=c;for(var _=0,b=this._observers;_<b.length;_++){var k=b[_];if(!k._willBeUnregistered&&(k.mask&e&&(k.scope?d.lastReturnValue=k.callback.apply(k.scope,[i,d]):d.lastReturnValue=k.callback(i,d),k.unregisterOnNextCall&&this._deferUnregister(k)),d.skipNextObservers))return!1}return!0},a.prototype.notifyObserversWithPromise=function(i,e,o,s,c){var d=this;e===void 0&&(e=-1);var _=Promise.resolve(i);if(!this._observers.length)return _;var b=this._eventState;return b.mask=e,b.target=o,b.currentTarget=s,b.skipNextObservers=!1,b.userInfo=c,this._observers.forEach(function(k){b.skipNextObservers||k._willBeUnregistered||k.mask&e&&(k.scope?_=_.then(function(j){return b.lastReturnValue=j,k.callback.apply(k.scope,[i,b])}):_=_.then(function(j){return b.lastReturnValue=j,k.callback(i,b)}),k.unregisterOnNextCall&&d._deferUnregister(k))}),_.then(function(){return i})},a.prototype.notifyObserver=function(i,e,o){if(o===void 0&&(o=-1),!i._willBeUnregistered){var s=this._eventState;s.mask=o,s.skipNextObservers=!1,i.callback(e,s),i.unregisterOnNextCall&&this._deferUnregister(i)}},a.prototype.hasObservers=function(){return this._observers.length>0},a.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},a.prototype.clone=function(){var i=new a;return i._observers=this._observers.slice(0),i},a.prototype.hasSpecificMask=function(i){i===void 0&&(i=-1);for(var e=0,o=this._observers;e<o.length;e++){var s=o[e];if(s.mask&i||s.mask===i)return!0}return!1},a}();function IsWindowObjectExist(){return typeof window!="undefined"}function IsNavigatorAvailable(){return typeof navigator!="undefined"}function IsDocumentAvailable(){return typeof document!="undefined"}function GetDOMTextContent(a){for(var i="",e=a.firstChild;e;)e.nodeType===3&&(i+=e.textContent),e=e.nextSibling;return i}var DomManagement={IsWindowObjectExist,IsNavigatorAvailable,IsDocumentAvailable,GetDOMTextContent},Logger$2=function(){function a(){}return a._CheckLimit=function(i,e){var o=a._LogLimitOutputs[i];return o?o.current++:(o={limit:e,current:1},a._LogLimitOutputs[i]=o),o.current<=o.limit},a._GenerateLimitMessage=function(i,e){var o=a._LogLimitOutputs[i];if(!(!o||!a.MessageLimitReached)&&o.current===o.limit)switch(e){case 0:a.Log(a.MessageLimitReached.replace(/%LIMIT%/g,""+o.limit).replace(/%TYPE%/g,"log"));break;case 1:a.Warn(a.MessageLimitReached.replace(/%LIMIT%/g,""+o.limit).replace(/%TYPE%/g,"warning"));break;case 2:a.Error(a.MessageLimitReached.replace(/%LIMIT%/g,""+o.limit).replace(/%TYPE%/g,"error"));break}},a._AddLogEntry=function(i){a._LogCache=i+a._LogCache,a.OnNewCacheEntry&&a.OnNewCacheEntry(i)},a._FormatMessage=function(i){var e=function(s){return s<10?"0"+s:""+s},o=new Date;return"["+e(o.getHours())+":"+e(o.getMinutes())+":"+e(o.getSeconds())+"]: "+i},a._LogDisabled=function(i,e){},a._LogEnabled=function(i,e){if(!(e!==void 0&&!a._CheckLimit(i,e))){var o=a._FormatMessage(i);console.log("BJS - "+o);var s="<div style='color:white'>"+o+"</div><br>";a._AddLogEntry(s),a._GenerateLimitMessage(i,0)}},a._WarnDisabled=function(i,e){},a._WarnEnabled=function(i,e){if(!(e!==void 0&&!a._CheckLimit(i,e))){var o=a._FormatMessage(i);console.warn("BJS - "+o);var s="<div style='color:orange'>"+i+"</div><br>";a._AddLogEntry(s),a._GenerateLimitMessage(i,1)}},a._ErrorDisabled=function(i,e){},a._ErrorEnabled=function(i,e){if(!(e!==void 0&&!a._CheckLimit(i,e))){var o=a._FormatMessage(i);a.errorsCount++,console.error("BJS - "+o);var s="<div style='color:red'>"+o+"</div><br>";a._AddLogEntry(s),a._GenerateLimitMessage(i,2)}},Object.defineProperty(a,"LogCache",{get:function(){return a._LogCache},enumerable:!1,configurable:!0}),a.ClearLogCache=function(){a._LogCache="",a._LogLimitOutputs={},a.errorsCount=0},Object.defineProperty(a,"LogLevels",{set:function(i){(i&a.MessageLogLevel)===a.MessageLogLevel?a.Log=a._LogEnabled:a.Log=a._LogDisabled,(i&a.WarningLogLevel)===a.WarningLogLevel?a.Warn=a._WarnEnabled:a.Warn=a._WarnDisabled,(i&a.ErrorLogLevel)===a.ErrorLogLevel?a.Error=a._ErrorEnabled:a.Error=a._ErrorDisabled},enumerable:!1,configurable:!0}),a.NoneLogLevel=0,a.MessageLogLevel=1,a.WarningLogLevel=2,a.ErrorLogLevel=4,a.AllLogLevel=7,a.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",a._LogCache="",a._LogLimitOutputs={},a.errorsCount=0,a.Log=a._LogEnabled,a.Warn=a._WarnEnabled,a.Error=a._ErrorEnabled,a}(),EndsWith=function(a,i){return a.indexOf(i,a.length-i.length)!==-1},StartsWith=function(a,i){return a?a.indexOf(i)===0:!1},Decode=function(a){if(typeof TextDecoder!="undefined")return new TextDecoder().decode(a);for(var i="",e=0;e<a.byteLength;e++)i+=String.fromCharCode(a[e]);return i},EncodeArrayBufferToBase64=function(a){for(var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",e="",o,s,c,d,_,b,k,j=0,$=ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);j<$.length;)o=$[j++],s=j<$.length?$[j++]:Number.NaN,c=j<$.length?$[j++]:Number.NaN,d=o>>2,_=(o&3)<<4|s>>4,b=(s&15)<<2|c>>6,k=c&63,isNaN(s)?b=k=64:isNaN(c)&&(k=64),e+=i.charAt(d)+i.charAt(_)+i.charAt(b)+i.charAt(k);return e},DecodeBase64ToString=function(a){return atob(a)},DecodeBase64ToBinary=function(a){for(var i=DecodeBase64ToString(a),e=i.length,o=new Uint8Array(new ArrayBuffer(e)),s=0;s<e;s++)o[s]=i.charCodeAt(s);return o.buffer},PadNumber=function(a,i){for(var e=String(a);e.length<i;)e="0"+e;return e},StringTools={EndsWith,StartsWith,Decode,EncodeArrayBufferToBase64,DecodeBase64ToString,DecodeBase64ToBinary,PadNumber},ShaderCodeNode=function(){function a(){this.children=[]}return a.prototype.isValid=function(i){return!0},a.prototype.process=function(i,e){var o="";if(this.line){var s=this.line,c=e.processor;if(c){if(c.lineProcessor&&(s=c.lineProcessor(s,e.isFragment,e.processingContext)),c.attributeProcessor&&StartsWith(this.line,"attribute"))s=c.attributeProcessor(this.line,i,e.processingContext);else if(c.varyingProcessor&&StartsWith(this.line,"varying"))s=c.varyingProcessor(this.line,e.isFragment,i,e.processingContext);else if(c.uniformProcessor&&c.uniformRegexp&&c.uniformRegexp.test(this.line))e.lookForClosingBracketForUniformBuffer||(s=c.uniformProcessor(this.line,e.isFragment,i,e.processingContext));else if(c.uniformBufferProcessor&&c.uniformBufferRegexp&&c.uniformBufferRegexp.test(this.line))e.lookForClosingBracketForUniformBuffer||(s=c.uniformBufferProcessor(this.line,e.isFragment,e.processingContext),e.lookForClosingBracketForUniformBuffer=!0);else if(c.textureProcessor&&c.textureRegexp&&c.textureRegexp.test(this.line))s=c.textureProcessor(this.line,e.isFragment,i,e.processingContext);else if((c.uniformProcessor||c.uniformBufferProcessor)&&StartsWith(this.line,"uniform")&&!e.lookForClosingBracketForUniformBuffer){var d=/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/;d.test(this.line)?c.uniformProcessor&&(s=c.uniformProcessor(this.line,e.isFragment,i,e.processingContext)):c.uniformBufferProcessor&&(s=c.uniformBufferProcessor(this.line,e.isFragment,e.processingContext),e.lookForClosingBracketForUniformBuffer=!0)}e.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(e.lookForClosingBracketForUniformBuffer=!1,c.endOfUniformBufferProcessor&&(s=c.endOfUniformBufferProcessor(this.line,e.isFragment,e.processingContext)))}o+=s+`\r
  79. `}return this.children.forEach(function(_){o+=_.process(i,e)}),this.additionalDefineKey&&(i[this.additionalDefineKey]=this.additionalDefineValue||"true"),o},a}(),ShaderCodeCursor=function(){function a(){}return Object.defineProperty(a.prototype,"currentLine",{get:function(){return this._lines[this.lineIndex]},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"canRead",{get:function(){return this.lineIndex<this._lines.length-1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"lines",{set:function(i){this._lines=[];for(var e=0,o=i;e<o.length;e++){var s=o[e];if(s[0]==="#"){this._lines.push(s);continue}for(var c=s.split(";"),d=0;d<c.length;d++){var _=c[d];_=_.trim(),_&&this._lines.push(_+(d!==c.length-1?";":""))}}},enumerable:!1,configurable:!0}),a}(),ShaderCodeConditionNode=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.process=function(e,o){for(var s=0;s<this.children.length;s++){var c=this.children[s];if(c.isValid(e))return c.process(e,o)}return""},i}(ShaderCodeNode),ShaderCodeTestNode=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.isValid=function(e){return this.testExpression.isTrue(e)},i}(ShaderCodeNode),ShaderDefineExpression=function(){function a(){}return a.prototype.isTrue=function(i){return!0},a.postfixToInfix=function(i){for(var e=[],o=0,s=i;o<s.length;o++){var c=s[o];if(a._OperatorPriority[c]===void 0)e.push(c);else{var d=e[e.length-1],_=e[e.length-2];e.length-=2,e.push("("+_+c+d+")")}}return e[e.length-1]},a.infixToPostfix=function(i){for(var e=[],o=-1,s=function(){k=k.trim(),k!==""&&(e.push(k),k="")},c=function(_e){o<a._Stack.length-1&&(a._Stack[++o]=_e)},d=function(){return a._Stack[o]},_=function(){return o===-1?"!!INVALID EXPRESSION!!":a._Stack[o--]},b=0,k="";b<i.length;){var j=i.charAt(b),$=b<i.length-1?i.substr(b,2):"";if(j==="(")k="",c(j);else if(j===")"){for(s();o!==-1&&d()!=="(";)e.push(_());_()}else if(a._OperatorPriority[$]>1){for(s();o!==-1&&a._OperatorPriority[d()]>=a._OperatorPriority[$];)e.push(_());c($),b++}else k+=j;b++}for(s();o!==-1;)d()==="("?_():e.push(_());return e},a._OperatorPriority={")":0,"(":1,"||":2,"&&":3},a._Stack=["","","","","","","","","","","","","","","","","","","",""],a}(),ShaderDefineIsDefinedOperator=function(a){__extends(i,a);function i(e,o){o===void 0&&(o=!1);var s=a.call(this)||this;return s.define=e,s.not=o,s}return i.prototype.isTrue=function(e){var o=e[this.define]!==void 0;return this.not&&(o=!o),o},i}(ShaderDefineExpression),ShaderDefineOrOperator=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.isTrue=function(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)},i}(ShaderDefineExpression),ShaderDefineAndOperator=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.isTrue=function(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)},i}(ShaderDefineExpression),ShaderDefineArithmeticOperator=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this)||this;return c.define=e,c.operand=o,c.testValue=s,c}return i.prototype.isTrue=function(e){var o=e[this.define];o===void 0&&(o=this.define);var s=!1,c=parseInt(o),d=parseInt(this.testValue);switch(this.operand){case">":s=c>d;break;case"<":s=c<d;break;case"<=":s=c<=d;break;case">=":s=c>=d;break;case"==":s=c===d;break}return s},i}(ShaderDefineExpression);function _WarnImport(a){return a+" needs to be imported before as it contains a side-effect required by your code."}var ShaderLanguage;(function(a){a[a.GLSL=0]="GLSL",a[a.WGSL=1]="WGSL"})(ShaderLanguage||(ShaderLanguage={}));var regexSE=/defined\s*?\((.+?)\)/g,regexSERevert=/defined\s*?\[(.+?)\]/g,ShaderProcessor=function(){function a(){}return a.Initialize=function(i){i.processor&&i.processor.initializeShaders&&i.processor.initializeShaders(i.processingContext)},a.Process=function(i,e,o,s){var c=this,d;!((d=e.processor)===null||d===void 0)&&d.preProcessShaderCode&&(i=e.processor.preProcessShaderCode(i)),this._ProcessIncludes(i,e,function(_){var b=c._ProcessShaderConversion(_,e,s);o(b)})},a.PreProcess=function(i,e,o,s){var c=this,d;!((d=e.processor)===null||d===void 0)&&d.preProcessShaderCode&&(i=e.processor.preProcessShaderCode(i)),this._ProcessIncludes(i,e,function(_){var b=c._ApplyPreProcessing(_,e,s);o(b)})},a.Finalize=function(i,e,o){return!o.processor||!o.processor.finalizeShaders?{vertexCode:i,fragmentCode:e}:o.processor.finalizeShaders(i,e,o.processingContext)},a._ProcessPrecision=function(i,e){var o;if(!((o=e.processor)===null||o===void 0)&&o.noPrecision)return i;var s=e.shouldUseHighPrecisionShader;return i.indexOf("precision highp float")===-1?s?i=`precision highp float;
  80. `+i:i=`precision mediump float;
  81. `+i:s||(i=i.replace("precision highp float","precision mediump float")),i},a._ExtractOperation=function(i){var e=/defined\((.+)\)/,o=e.exec(i);if(o&&o.length)return new ShaderDefineIsDefinedOperator(o[1].trim(),i[0]==="!");for(var s=["==",">=","<=","<",">"],c="",d=0,_=0,b=s;_<b.length&&(c=b[_],d=i.indexOf(c),!(d>-1));_++);if(d===-1)return new ShaderDefineIsDefinedOperator(i);var k=i.substring(0,d).trim(),j=i.substring(d+c.length).trim();return new ShaderDefineArithmeticOperator(k,c,j)},a._BuildSubExpression=function(i){i=i.replace(regexSE,"defined[$1]");for(var e=ShaderDefineExpression.infixToPostfix(i),o=[],s=0,c=e;s<c.length;s++){var d=c[s];if(d!=="||"&&d!=="&&")o.push(d);else if(o.length>=2){var _=o[o.length-1],b=o[o.length-2];o.length-=2;var k=d=="&&"?new ShaderDefineAndOperator:new ShaderDefineOrOperator;typeof _=="string"&&(_=_.replace(regexSERevert,"defined($1)")),typeof b=="string"&&(b=b.replace(regexSERevert,"defined($1)")),k.leftOperand=typeof b=="string"?this._ExtractOperation(b):b,k.rightOperand=typeof _=="string"?this._ExtractOperation(_):_,o.push(k)}}var j=o[o.length-1];return typeof j=="string"&&(j=j.replace(regexSERevert,"defined($1)")),typeof j=="string"?this._ExtractOperation(j):j},a._BuildExpression=function(i,e){var o=new ShaderCodeTestNode,s=i.substring(0,e),c=i.substring(e);return c=c.substring(0,(c.indexOf("//")+1||c.length+1)-1).trim(),s==="#ifdef"?o.testExpression=new ShaderDefineIsDefinedOperator(c):s==="#ifndef"?o.testExpression=new ShaderDefineIsDefinedOperator(c,!0):o.testExpression=this._BuildSubExpression(c),o},a._MoveCursorWithinIf=function(i,e,o){for(var s=i.currentLine;this._MoveCursor(i,o);){s=i.currentLine;var c=s.substring(0,5).toLowerCase();if(c==="#else"){var d=new ShaderCodeNode;e.children.push(d),this._MoveCursor(i,d);return}else if(c==="#elif"){var _=this._BuildExpression(s,5);e.children.push(_),o=_}}},a._MoveCursor=function(i,e){for(;i.canRead;){i.lineIndex++;var o=i.currentLine,s=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/,c=s.exec(o);if(c&&c.length){var d=c[0];switch(d){case"#ifdef":{var _=new ShaderCodeConditionNode;e.children.push(_);var b=this._BuildExpression(o,6);_.children.push(b),this._MoveCursorWithinIf(i,_,b);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{var _=new ShaderCodeConditionNode;e.children.push(_);var b=this._BuildExpression(o,7);_.children.push(b),this._MoveCursorWithinIf(i,_,b);break}case"#if":{var _=new ShaderCodeConditionNode,b=this._BuildExpression(o,3);e.children.push(_),_.children.push(b),this._MoveCursorWithinIf(i,_,b);break}}}else{var k=new ShaderCodeNode;if(k.line=o,e.children.push(k),o[0]==="#"&&o[1]==="d"){var j=o.replace(";","").split(" ");k.additionalDefineKey=j[1],j.length===3&&(k.additionalDefineValue=j[2])}}}return!1},a._EvaluatePreProcessors=function(i,e,o){var s=new ShaderCodeNode,c=new ShaderCodeCursor;return c.lineIndex=-1,c.lines=i.split(`
  82. `),this._MoveCursor(c,s),s.process(e,o)},a._PreparePreProcessors=function(i,e){for(var o,s=i.defines,c={},d=0,_=s;d<_.length;d++){var b=_[d],k=b.replace("#define","").replace(";","").trim(),j=k.split(" ");c[j[0]]=j.length>1?j[1]:""}return((o=i.processor)===null||o===void 0?void 0:o.shaderLanguage)===ShaderLanguage.GLSL&&(c.GL_ES="true"),c.__VERSION__=i.version,c[i.platformName]="true",e._getGlobalDefines(c),c},a._ProcessShaderConversion=function(i,e,o){var s=this._ProcessPrecision(i,e);if(!e.processor)return s;if(e.processor.shaderLanguage===ShaderLanguage.GLSL&&s.indexOf("#version 3")!==-1)return s.replace("#version 300 es","");var c=e.defines,d=this._PreparePreProcessors(e,o);return e.processor.preProcessor&&(s=e.processor.preProcessor(s,c,e.isFragment,e.processingContext)),s=this._EvaluatePreProcessors(s,d,e),e.processor.postProcessor&&(s=e.processor.postProcessor(s,c,e.isFragment,e.processingContext,o)),o._features.needShaderCodeInlining&&(s=o.inlineShaderCode(s)),s},a._ApplyPreProcessing=function(i,e,o){var s,c,d=i,_=e.defines,b=this._PreparePreProcessors(e,o);return!((s=e.processor)===null||s===void 0)&&s.preProcessor&&(d=e.processor.preProcessor(d,_,e.isFragment,e.processingContext)),d=this._EvaluatePreProcessors(d,b,e),!((c=e.processor)===null||c===void 0)&&c.postProcessor&&(d=e.processor.postProcessor(d,_,e.isFragment,e.processingContext,o)),o._features.needShaderCodeInlining&&(d=o.inlineShaderCode(d)),d},a._ProcessIncludes=function(i,e,o){for(var s=this,c=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,d=c.exec(i),_=new String(i),b=!1;d!=null;){var k=d[1];if(k.indexOf("__decl__")!==-1&&(k=k.replace(/__decl__/,""),e.supportsUniformBuffers&&(k=k.replace(/Vertex/,"Ubo"),k=k.replace(/Fragment/,"Ubo")),k=k+"Declaration"),e.includesShadersStore[k]){var j=e.includesShadersStore[k];if(d[2])for(var $=d[3].split(","),_e=0;_e<$.length;_e+=2){var et=new RegExp($[_e],"g"),tt=$[_e+1];j=j.replace(et,tt)}if(d[4]){var rt=d[5];if(rt.indexOf("..")!==-1){var it=rt.split(".."),nt=parseInt(it[0]),ot=parseInt(it[1]),at=j.slice(0);j="",isNaN(ot)&&(ot=e.indexParameters[it[1]]);for(var st=nt;st<ot;st++)e.supportsUniformBuffers||(at=at.replace(/light\{X\}.(\w*)/g,function(ft,lt){return lt+"{X}"})),j+=at.replace(/\{X\}/g,st.toString())+`
  83. `}else e.supportsUniformBuffers||(j=j.replace(/light\{X\}.(\w*)/g,function(ft,lt){return lt+"{X}"})),j=j.replace(/\{X\}/g,rt)}_=_.replace(d[0],j),b=b||j.indexOf("#include<")>=0||j.indexOf("#include <")>=0}else{var ut=e.shadersRepository+"ShadersInclude/"+k+".fx";a._FileToolsLoadFile(ut,function(ft){e.includesShadersStore[k]=ft,s._ProcessIncludes(_,e,o)});return}d=c.exec(i)}b?this._ProcessIncludes(_.toString(),e,o):o(_)},a._FileToolsLoadFile=function(i,e,o,s,c,d){throw _WarnImport("FileTools")},a}(),ShaderStore=function(){function a(){}return a.GetShadersRepository=function(i){return i===void 0&&(i=ShaderLanguage.GLSL),i===ShaderLanguage.GLSL?a.ShadersRepository:a.ShadersRepositoryWGSL},a.GetShadersStore=function(i){return i===void 0&&(i=ShaderLanguage.GLSL),i===ShaderLanguage.GLSL?a.ShadersStore:a.ShadersStoreWGSL},a.GetIncludesShadersStore=function(i){return i===void 0&&(i=ShaderLanguage.GLSL),i===ShaderLanguage.GLSL?a.IncludesShadersStore:a.IncludesShadersStoreWGSL},a.ShadersRepository="src/Shaders/",a.ShadersStore={},a.IncludesShadersStore={},a.ShadersRepositoryWGSL="src/ShadersWGSL/",a.ShadersStoreWGSL={},a.IncludesShadersStoreWGSL={},a}(),Effect$1=function(){function a(i,e,o,s,c,d,_,b,k,j,$,_e){var et=this;s===void 0&&(s=null),d===void 0&&(d=null),_===void 0&&(_=null),b===void 0&&(b=null),k===void 0&&(k=null),$===void 0&&($=""),_e===void 0&&(_e=ShaderLanguage.GLSL);var tt,rt;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new Observable,this.onErrorObservable=new Observable,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this.name=i,this._key=$;var it=null;if(e.attributes){var nt=e;if(this._engine=o,this._attributesNames=nt.attributes,this._uniformsNames=nt.uniformsNames.concat(nt.samplers),this._samplerList=nt.samplers.slice(),this.defines=nt.defines,this.onError=nt.onError,this.onCompiled=nt.onCompiled,this._fallbacks=nt.fallbacks,this._indexParameters=nt.indexParameters,this._transformFeedbackVaryings=nt.transformFeedbackVaryings||null,this._multiTarget=!!nt.multiTarget,this._shaderLanguage=(tt=nt.shaderLanguage)!==null&&tt!==void 0?tt:ShaderLanguage.GLSL,nt.uniformBuffersNames){this._uniformBuffersNamesList=nt.uniformBuffersNames.slice();for(var ot=0;ot<nt.uniformBuffersNames.length;ot++)this._uniformBuffersNames[nt.uniformBuffersNames[ot]]=ot}it=(rt=nt.processFinalCode)!==null&&rt!==void 0?rt:null}else this._engine=c,this.defines=d==null?"":d,this._uniformsNames=o.concat(s),this._samplerList=s?s.slice():[],this._attributesNames=e,this._uniformBuffersNamesList=[],this._shaderLanguage=_e,this.onError=k,this.onCompiled=b,this._indexParameters=j,this._fallbacks=_;this._attributeLocationByName={},this.uniqueId=a._uniqueIdSeed++;var at,st,ut=IsWindowObjectExist()?this._engine.getHostDocument():null;i.vertexSource?at="source:"+i.vertexSource:i.vertexElement?(at=ut?ut.getElementById(i.vertexElement):null,at||(at=i.vertexElement)):at=i.vertex||i,i.fragmentSource?st="source:"+i.fragmentSource:i.fragmentElement?(st=ut?ut.getElementById(i.fragmentElement):null,st||(st=i.fragmentElement)):st=i.fragment||i,this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage);var ft={defines:this.defines.split(`
  84. `),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:ShaderStore.GetShadersRepository(this._shaderLanguage),includesShadersStore:ShaderStore.GetIncludesShadersStore(this._shaderLanguage),version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer},lt=[void 0,void 0],ht=function(){if(lt[0]&&lt[1]){ft.isFragment=!0;var pt=lt[0],mt=lt[1];ShaderProcessor.Process(mt,ft,function(dt){it&&(dt=it("fragment",dt));var gt=ShaderProcessor.Finalize(pt,dt,ft);et._useFinalCode(gt.vertexCode,gt.fragmentCode,i)},et._engine)}};this._loadShader(at,"Vertex","",function(pt){ShaderProcessor.Initialize(ft),ShaderProcessor.Process(pt,ft,function(mt){et._rawVertexSourceCode=pt,it&&(mt=it("vertex",mt)),lt[0]=mt,ht()},et._engine)}),this._loadShader(st,"Fragment","Pixel",function(pt){et._rawFragmentSourceCode=pt,lt[1]=pt,ht()})}return Object.defineProperty(a,"ShadersRepository",{get:function(){return ShaderStore.ShadersRepository},set:function(i){ShaderStore.ShadersRepository=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new Observable),this._onBindObservable},enumerable:!1,configurable:!0}),a.prototype._useFinalCode=function(i,e,o){if(o){var s=o.vertexElement||o.vertex||o.spectorName||o,c=o.fragmentElement||o.fragment||o.spectorName||o;this._vertexSourceCode=(this._shaderLanguage===ShaderLanguage.WGSL?"//":"")+"#define SHADER_NAME vertex:"+s+`
  85. `+i,this._fragmentSourceCode=(this._shaderLanguage===ShaderLanguage.WGSL?"//":"")+"#define SHADER_NAME fragment:"+c+`
  86. `+e}else this._vertexSourceCode=i,this._fragmentSourceCode=e;this._prepareEffect()},Object.defineProperty(a.prototype,"key",{get:function(){return this._key},enumerable:!1,configurable:!0}),a.prototype.isReady=function(){try{return this._isReadyInternal()}catch{return!1}},a.prototype._isReadyInternal=function(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1},a.prototype.getEngine=function(){return this._engine},a.prototype.getPipelineContext=function(){return this._pipelineContext},a.prototype.getAttributesNames=function(){return this._attributesNames},a.prototype.getAttributeLocation=function(i){return this._attributes[i]},a.prototype.getAttributeLocationByName=function(i){return this._attributeLocationByName[i]},a.prototype.getAttributesCount=function(){return this._attributes.length},a.prototype.getUniformIndex=function(i){return this._uniformsNames.indexOf(i)},a.prototype.getUniform=function(i){return this._uniforms[i]},a.prototype.getSamplers=function(){return this._samplerList},a.prototype.getUniformNames=function(){return this._uniformsNames},a.prototype.getUniformBuffersNames=function(){return this._uniformBuffersNamesList},a.prototype.getIndexParameters=function(){return this._indexParameters},a.prototype.getCompilationError=function(){return this._compilationError},a.prototype.allFallbacksProcessed=function(){return this._allFallbacksProcessed},a.prototype.executeWhenCompiled=function(i){var e=this;if(this.isReady()){i(this);return}this.onCompileObservable.add(function(o){i(o)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(function(){e._checkIsReady(null)},16)},a.prototype._checkIsReady=function(i){var e=this;try{if(this._isReadyInternal())return}catch(o){this._processCompilationErrors(o,i);return}setTimeout(function(){e._checkIsReady(i)},16)},a.prototype._loadShader=function(i,e,o,s){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement){var c=GetDOMTextContent(i);s(c);return}if(i.substr(0,7)==="source:"){s(i.substr(7));return}if(i.substr(0,7)==="base64:"){var d=window.atob(i.substr(7));s(d);return}var _=ShaderStore.GetShadersStore(this._shaderLanguage);if(_[i+e+"Shader"]){s(_[i+e+"Shader"]);return}if(o&&_[i+o+"Shader"]){s(_[i+o+"Shader"]);return}var b;i[0]==="."||i[0]==="/"||i.indexOf("http")>-1?b=i:b=ShaderStore.GetShadersRepository(this._shaderLanguage)+i,this._engine._loadFile(b+"."+e.toLowerCase()+".fx",s)},Object.defineProperty(a.prototype,"vertexSourceCode",{get:function(){var i,e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(e=(i=this._pipelineContext)===null||i===void 0?void 0:i._getVertexShaderCode())!==null&&e!==void 0?e:this._vertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"fragmentSourceCode",{get:function(){var i,e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(e=(i=this._pipelineContext)===null||i===void 0?void 0:i._getFragmentShaderCode())!==null&&e!==void 0?e:this._fragmentSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rawVertexSourceCode",{get:function(){return this._rawVertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rawFragmentSourceCode",{get:function(){return this._rawFragmentSourceCode},enumerable:!1,configurable:!0}),a.prototype._rebuildProgram=function(i,e,o,s){var c=this;this._isReady=!1,this._vertexSourceCodeOverride=i,this._fragmentSourceCodeOverride=e,this.onError=function(d,_){s&&s(_)},this.onCompiled=function(){var d=c.getEngine().scenes;if(d)for(var _=0;_<d.length;_++)d[_].markAllMaterialsAsDirty(63);c._pipelineContext._handlesSpectorRebuildCallback(o)},this._fallbacks=null,this._prepareEffect()},a.prototype._prepareEffect=function(){var i=this,e=this._attributesNames,o=this.defines,s=this._pipelineContext;this._isReady=!1;try{var c=this._engine;this._pipelineContext=c.createPipelineContext(this._processingContext),this._pipelineContext._name=this._key;var d=this._rebuildProgram.bind(this);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?c._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,d,null,this._transformFeedbackVaryings,this._key):c._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,d,o,this._transformFeedbackVaryings,this._key),c._executeWhenRenderingStateIsCompiled(this._pipelineContext,function(){if(i._attributes=[],i._pipelineContext._fillEffectInformation(i,i._uniformBuffersNames,i._uniformsNames,i._uniforms,i._samplerList,i._samplers,e,i._attributes),e)for(var _=0;_<e.length;_++){var b=e[_];i._attributeLocationByName[b]=i._attributes[_]}c.bindSamplers(i),i._compilationError="",i._isReady=!0,i.onCompiled&&i.onCompiled(i),i.onCompileObservable.notifyObservers(i),i.onCompileObservable.clear(),i._fallbacks&&i._fallbacks.unBindMesh(),s&&i.getEngine()._deletePipelineContext(s)}),this._pipelineContext.isAsync&&this._checkIsReady(s)}catch(_){this._processCompilationErrors(_,s)}},a.prototype._getShaderCodeAndErrorLine=function(i,e,o){var s=o?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/,c=null;if(e&&i){var d=e.match(s);if(d&&d.length===2){var _=parseInt(d[1]),b=i.split(`
  87. `,-1);b.length>=_&&(c="Offending line ["+_+"] in "+(o?"fragment":"vertex")+" code: "+b[_-1])}}return[i,c]},a.prototype._processCompilationErrors=function(i,e){var o,s,c,d,_;e===void 0&&(e=null),this._compilationError=i.message;var b=this._attributesNames,k=this._fallbacks;if(Logger$2.Error("Unable to compile effect:"),Logger$2.Error("Uniforms: "+this._uniformsNames.map(function(et){return" "+et})),Logger$2.Error("Attributes: "+b.map(function(et){return" "+et})),Logger$2.Error(`Defines:\r
  88. `+this.defines),a.LogShaderCodeOnCompilationError){var j=null,$=null,_e=null;!((c=this._pipelineContext)===null||c===void 0)&&c._getVertexShaderCode()&&(o=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),_e=o[0],j=o[1],_e&&(Logger$2.Error("Vertex code:"),Logger$2.Error(_e))),!((d=this._pipelineContext)===null||d===void 0)&&d._getFragmentShaderCode()&&(s=this._getShaderCodeAndErrorLine((_=this._pipelineContext)===null||_===void 0?void 0:_._getFragmentShaderCode(),this._compilationError,!0),_e=s[0],$=s[1],_e&&(Logger$2.Error("Fragment code:"),Logger$2.Error(_e))),j&&Logger$2.Error(j),$&&Logger$2.Error($)}Logger$2.Error("Error: "+this._compilationError),e&&(this._pipelineContext=e,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)),k?(this._pipelineContext=null,k.hasMoreFallbacks?(this._allFallbacksProcessed=!1,Logger$2.Error("Trying next fallback."),this.defines=k.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):this._allFallbacksProcessed=!0},Object.defineProperty(a.prototype,"isSupported",{get:function(){return this._compilationError===""},enumerable:!1,configurable:!0}),a.prototype._bindTexture=function(i,e){this._engine._bindTexture(this._samplers[i],e,i)},a.prototype.setTexture=function(i,e){this._engine.setTexture(this._samplers[i],this._uniforms[i],e,i)},a.prototype.setDepthStencilTexture=function(i,e){this._engine.setDepthStencilTexture(this._samplers[i],this._uniforms[i],e,i)},a.prototype.setTextureArray=function(i,e){var o=i+"Ex";if(this._samplerList.indexOf(o+"0")===-1){for(var s=this._samplerList.indexOf(i),c=1;c<e.length;c++){var d=o+(c-1).toString();this._samplerList.splice(s+c,0,d)}for(var _=0,b=0,k=this._samplerList;b<k.length;b++){var j=k[b];this._samplers[j]=_,_+=1}}this._engine.setTextureArray(this._samplers[i],this._uniforms[i],e,i)},a.prototype.setTextureFromPostProcess=function(i,e){this._engine.setTextureFromPostProcess(this._samplers[i],e,i)},a.prototype.setTextureFromPostProcessOutput=function(i,e){this._engine.setTextureFromPostProcessOutput(this._samplers[i],e,i)},a.prototype.bindUniformBuffer=function(i,e){var o=this._uniformBuffersNames[e];o===void 0||a._baseCache[o]===i&&this._engine._features.useUBOBindingCache||(a._baseCache[o]=i,this._engine.bindUniformBufferBase(i,o,e))},a.prototype.bindUniformBlock=function(i,e){this._engine.bindUniformBlock(this._pipelineContext,i,e)},a.prototype.setInt=function(i,e){return this._pipelineContext.setInt(i,e),this},a.prototype.setInt2=function(i,e,o){return this._pipelineContext.setInt2(i,e,o),this},a.prototype.setInt3=function(i,e,o,s){return this._pipelineContext.setInt3(i,e,o,s),this},a.prototype.setInt4=function(i,e,o,s,c){return this._pipelineContext.setInt4(i,e,o,s,c),this},a.prototype.setIntArray=function(i,e){return this._pipelineContext.setIntArray(i,e),this},a.prototype.setIntArray2=function(i,e){return this._pipelineContext.setIntArray2(i,e),this},a.prototype.setIntArray3=function(i,e){return this._pipelineContext.setIntArray3(i,e),this},a.prototype.setIntArray4=function(i,e){return this._pipelineContext.setIntArray4(i,e),this},a.prototype.setFloatArray=function(i,e){return this._pipelineContext.setArray(i,e),this},a.prototype.setFloatArray2=function(i,e){return this._pipelineContext.setArray2(i,e),this},a.prototype.setFloatArray3=function(i,e){return this._pipelineContext.setArray3(i,e),this},a.prototype.setFloatArray4=function(i,e){return this._pipelineContext.setArray4(i,e),this},a.prototype.setArray=function(i,e){return this._pipelineContext.setArray(i,e),this},a.prototype.setArray2=function(i,e){return this._pipelineContext.setArray2(i,e),this},a.prototype.setArray3=function(i,e){return this._pipelineContext.setArray3(i,e),this},a.prototype.setArray4=function(i,e){return this._pipelineContext.setArray4(i,e),this},a.prototype.setMatrices=function(i,e){return this._pipelineContext.setMatrices(i,e),this},a.prototype.setMatrix=function(i,e){return this._pipelineContext.setMatrix(i,e),this},a.prototype.setMatrix3x3=function(i,e){return this._pipelineContext.setMatrix3x3(i,e),this},a.prototype.setMatrix2x2=function(i,e){return this._pipelineContext.setMatrix2x2(i,e),this},a.prototype.setFloat=function(i,e){return this._pipelineContext.setFloat(i,e),this},a.prototype.setBool=function(i,e){return this._pipelineContext.setInt(i,e?1:0),this},a.prototype.setVector2=function(i,e){return this._pipelineContext.setVector2(i,e),this},a.prototype.setFloat2=function(i,e,o){return this._pipelineContext.setFloat2(i,e,o),this},a.prototype.setVector3=function(i,e){return this._pipelineContext.setVector3(i,e),this},a.prototype.setFloat3=function(i,e,o,s){return this._pipelineContext.setFloat3(i,e,o,s),this},a.prototype.setVector4=function(i,e){return this._pipelineContext.setVector4(i,e),this},a.prototype.setFloat4=function(i,e,o,s,c){return this._pipelineContext.setFloat4(i,e,o,s,c),this},a.prototype.setColor3=function(i,e){return this._pipelineContext.setColor3(i,e),this},a.prototype.setColor4=function(i,e,o){return this._pipelineContext.setColor4(i,e,o),this},a.prototype.setDirectColor4=function(i,e){return this._pipelineContext.setDirectColor4(i,e),this},a.prototype.dispose=function(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseEffect(this)},a.RegisterShader=function(i,e,o,s){s===void 0&&(s=ShaderLanguage.GLSL),e&&(ShaderStore.GetShadersStore(s)[i+"PixelShader"]=e),o&&(ShaderStore.GetShadersStore(s)[i+"VertexShader"]=o)},a.ResetCache=function(){a._baseCache={}},a.LogShaderCodeOnCompilationError=!0,a._uniqueIdSeed=0,a._baseCache={},a.ShadersStore=ShaderStore.ShadersStore,a.IncludesShadersStore=ShaderStore.IncludesShadersStore,a}(),DepthCullingState=function(){function a(i){i===void 0&&(i=!0),this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,i&&this.reset()}return Object.defineProperty(a.prototype,"isDirty",{get:function(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"zOffset",{get:function(){return this._zOffset},set:function(i){this._zOffset!==i&&(this._zOffset=i,this._isZOffsetDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"zOffsetUnits",{get:function(){return this._zOffsetUnits},set:function(i){this._zOffsetUnits!==i&&(this._zOffsetUnits=i,this._isZOffsetDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"cullFace",{get:function(){return this._cullFace},set:function(i){this._cullFace!==i&&(this._cullFace=i,this._isCullFaceDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"cull",{get:function(){return this._cull},set:function(i){this._cull!==i&&(this._cull=i,this._isCullDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(i){this._depthFunc!==i&&(this._depthFunc=i,this._isDepthFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"depthMask",{get:function(){return this._depthMask},set:function(i){this._depthMask!==i&&(this._depthMask=i,this._isDepthMaskDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"depthTest",{get:function(){return this._depthTest},set:function(i){this._depthTest!==i&&(this._depthTest=i,this._isDepthTestDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"frontFace",{get:function(){return this._frontFace},set:function(i){this._frontFace!==i&&(this._frontFace=i,this._isFrontFaceDirty=!0)},enumerable:!1,configurable:!0}),a.prototype.reset=function(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1},a.prototype.apply=function(i){!this.isDirty||(this._isCullDirty&&(this.cull?i.enable(i.CULL_FACE):i.disable(i.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(i.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(i.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?i.enable(i.DEPTH_TEST):i.disable(i.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(i.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(i.enable(i.POLYGON_OFFSET_FILL),i.polygonOffset(this.zOffset,this.zOffsetUnits)):i.disable(i.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(i.frontFace(this.frontFace),this._isFrontFaceDirty=!1))},a}(),StencilState=function(){function a(){this.reset()}return a.prototype.reset=function(){this.enabled=!1,this.mask=255,this.func=a.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=a.KEEP,this.opDepthFail=a.KEEP,this.opStencilDepthPass=a.REPLACE},Object.defineProperty(a.prototype,"stencilFunc",{get:function(){return this.func},set:function(i){this.func=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilFuncRef",{get:function(){return this.funcRef},set:function(i){this.funcRef=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilFuncMask",{get:function(){return this.funcMask},set:function(i){this.funcMask=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilOpStencilFail",{get:function(){return this.opStencilFail},set:function(i){this.opStencilFail=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilOpDepthFail",{get:function(){return this.opDepthFail},set:function(i){this.opDepthFail=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilOpStencilDepthPass",{get:function(){return this.opStencilDepthPass},set:function(i){this.opStencilDepthPass=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilMask",{get:function(){return this.mask},set:function(i){this.mask=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilTest",{get:function(){return this.enabled},set:function(i){this.enabled=i},enumerable:!1,configurable:!0}),a.ALWAYS=519,a.KEEP=7680,a.REPLACE=7681,a}(),AlphaState=function(){function a(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}return Object.defineProperty(a.prototype,"isDirty",{get:function(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"alphaBlend",{get:function(){return this._alphaBlend},set:function(i){this._alphaBlend!==i&&(this._alphaBlend=i,this._isAlphaBlendDirty=!0)},enumerable:!1,configurable:!0}),a.prototype.setAlphaBlendConstants=function(i,e,o,s){this._blendConstants[0]===i&&this._blendConstants[1]===e&&this._blendConstants[2]===o&&this._blendConstants[3]===s||(this._blendConstants[0]=i,this._blendConstants[1]=e,this._blendConstants[2]=o,this._blendConstants[3]=s,this._isBlendConstantsDirty=!0)},a.prototype.setAlphaBlendFunctionParameters=function(i,e,o,s){this._blendFunctionParameters[0]===i&&this._blendFunctionParameters[1]===e&&this._blendFunctionParameters[2]===o&&this._blendFunctionParameters[3]===s||(this._blendFunctionParameters[0]=i,this._blendFunctionParameters[1]=e,this._blendFunctionParameters[2]=o,this._blendFunctionParameters[3]=s,this._isBlendFunctionParametersDirty=!0)},a.prototype.setAlphaEquationParameters=function(i,e){this._blendEquationParameters[0]===i&&this._blendEquationParameters[1]===e||(this._blendEquationParameters[0]=i,this._blendEquationParameters[1]=e,this._isBlendEquationParametersDirty=!0)},a.prototype.reset=function(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1},a.prototype.apply=function(i){!this.isDirty||(this._isAlphaBlendDirty&&(this._alphaBlend?i.enable(i.BLEND):i.disable(i.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(i.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(i.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(i.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))},a}(),TextureSampler=function(){function a(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}return Object.defineProperty(a.prototype,"wrapU",{get:function(){return this._cachedWrapU},set:function(i){this._cachedWrapU=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"wrapV",{get:function(){return this._cachedWrapV},set:function(i){this._cachedWrapV=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"wrapR",{get:function(){return this._cachedWrapR},set:function(i){this._cachedWrapR=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"anisotropicFilteringLevel",{get:function(){return this._cachedAnisotropicFilteringLevel},set:function(i){this._cachedAnisotropicFilteringLevel=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"comparisonFunction",{get:function(){return this._comparisonFunction},set:function(i){this._comparisonFunction=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useMipMaps",{get:function(){return this._useMipMaps},set:function(i){this._useMipMaps=i},enumerable:!1,configurable:!0}),a.prototype.setParameters=function(i,e,o,s,c,d){return i===void 0&&(i=1),e===void 0&&(e=1),o===void 0&&(o=1),s===void 0&&(s=1),c===void 0&&(c=2),d===void 0&&(d=0),this._cachedWrapU=i,this._cachedWrapV=e,this._cachedWrapR=o,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=c,this._comparisonFunction=d,this},a.prototype.compareSampler=function(i){return this._cachedWrapU===i._cachedWrapU&&this._cachedWrapV===i._cachedWrapV&&this._cachedWrapR===i._cachedWrapR&&this._cachedAnisotropicFilteringLevel===i._cachedAnisotropicFilteringLevel&&this.samplingMode===i.samplingMode&&this._comparisonFunction===i._comparisonFunction&&this._useMipMaps===i._useMipMaps},a}(),InternalTextureSource;(function(a){a[a.Unknown=0]="Unknown",a[a.Url=1]="Url",a[a.Temp=2]="Temp",a[a.Raw=3]="Raw",a[a.Dynamic=4]="Dynamic",a[a.RenderTarget=5]="RenderTarget",a[a.MultiRenderTarget=6]="MultiRenderTarget",a[a.Cube=7]="Cube",a[a.CubeRaw=8]="CubeRaw",a[a.CubePrefiltered=9]="CubePrefiltered",a[a.Raw3D=10]="Raw3D",a[a.Raw2DArray=11]="Raw2DArray",a[a.DepthStencil=12]="DepthStencil",a[a.CubeRawRGBD=13]="CubeRawRGBD",a[a.Depth=14]="Depth"})(InternalTextureSource||(InternalTextureSource={}));var InternalTexture=function(a){__extends(i,a);function i(e,o,s){s===void 0&&(s=!1);var c=a.call(this)||this;return c.isReady=!1,c.isCube=!1,c.is3D=!1,c.is2DArray=!1,c.isMultiview=!1,c.url="",c.generateMipMaps=!1,c.samples=0,c.type=-1,c.format=-1,c.onLoadedObservable=new Observable,c.onErrorObservable=new Observable,c.onRebuildCallback=null,c.width=0,c.height=0,c.depth=0,c.baseWidth=0,c.baseHeight=0,c.baseDepth=0,c.invertY=!1,c._invertVScale=!1,c._associatedChannel=-1,c._source=InternalTextureSource.Unknown,c._buffer=null,c._bufferView=null,c._bufferViewArray=null,c._bufferViewArrayArray=null,c._size=0,c._extension="",c._files=null,c._workingCanvas=null,c._workingContext=null,c._cachedCoordinatesMode=null,c._isDisabled=!1,c._compression=null,c._sphericalPolynomial=null,c._sphericalPolynomialPromise=null,c._sphericalPolynomialComputed=!1,c._lodGenerationScale=0,c._lodGenerationOffset=0,c._useSRGBBuffer=!1,c._lodTextureHigh=null,c._lodTextureMid=null,c._lodTextureLow=null,c._isRGBD=!1,c._linearSpecularLOD=!1,c._irradianceTexture=null,c._hardwareTexture=null,c._references=1,c._gammaSpace=null,c._engine=e,c._source=o,c._uniqueId=i._Counter++,s||(c._hardwareTexture=e._createHardwareTexture()),c}return Object.defineProperty(i.prototype,"useMipMaps",{get:function(){return this.generateMipMaps},set:function(e){this.generateMipMaps=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),i.prototype.getEngine=function(){return this._engine},Object.defineProperty(i.prototype,"source",{get:function(){return this._source},enumerable:!1,configurable:!0}),i.prototype.incrementReferences=function(){this._references++},i.prototype.updateSize=function(e,o,s){s===void 0&&(s=1),this._engine.updateTextureDimensions(this,e,o,s),this.width=e,this.height=o,this.depth=s,this.baseWidth=e,this.baseHeight=o,this.baseDepth=s,this._size=e*o*s},i.prototype._rebuild=function(){var e=this,o;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){var s=this.onRebuildCallback(this),c=function(_){_._swapAndDie(e,!1),e.isReady=s.isReady};s.isAsync?s.proxy.then(c):c(s.proxy);return}var d;switch(this.source){case InternalTextureSource.Temp:break;case InternalTextureSource.Url:d=this._engine.createTexture((o=this._originalUrl)!==null&&o!==void 0?o:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,function(){d._swapAndDie(e,!1),e.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case InternalTextureSource.Raw:d=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),d._swapAndDie(this,!1),this.isReady=!0;break;case InternalTextureSource.Raw3D:d=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),d._swapAndDie(this,!1),this.isReady=!0;break;case InternalTextureSource.Raw2DArray:d=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),d._swapAndDie(this,!1),this.isReady=!0;break;case InternalTextureSource.Dynamic:d=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),d._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case InternalTextureSource.Cube:d=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,function(){d._swapAndDie(e,!1),e.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case InternalTextureSource.CubeRaw:d=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),d._swapAndDie(this,!1),this.isReady=!0;break;case InternalTextureSource.CubeRawRGBD:return;case InternalTextureSource.CubePrefiltered:d=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,function(_){_&&_._swapAndDie(e,!1),e.isReady=!0},null,this.format,this._extension),d._sphericalPolynomial=this._sphericalPolynomial;return}},i.prototype._swapAndDie=function(e,o){var s;o===void 0&&(o=!0),(s=this._hardwareTexture)===null||s===void 0||s.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),e._hardwareTexture=this._hardwareTexture,o&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);var c=this._engine.getLoadedTexturesCache(),d=c.indexOf(this);d!==-1&&c.splice(d,1);var d=c.indexOf(e);d===-1&&c.push(e)},i.prototype.dispose=function(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null)},i._Counter=0,i}(TextureSampler),WebGLShaderProcessor=function(){function a(){this.shaderLanguage=ShaderLanguage.GLSL}return a.prototype.postProcessor=function(i,e,o,s,c){if(!c.getCaps().drawBuffersExtension){var d=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;i=i.replace(d,"")}return i},a}(),WebGL2ShaderProcessor=function(){function a(){this.shaderLanguage=ShaderLanguage.GLSL}return a.prototype.attributeProcessor=function(i){return i.replace("attribute","in")},a.prototype.varyingProcessor=function(i,e){return i.replace("varying",e?"in":"out")},a.prototype.postProcessor=function(i,e,o,s,c){var d=i.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,_=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(i=i.replace(_,""),i=i.replace(/texture2D\s*\(/g,"texture("),o)i=i.replace(/texture2DLodEXT\s*\(/g,"textureLod("),i=i.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),i=i.replace(/textureCube\s*\(/g,"texture("),i=i.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),i=i.replace(/gl_FragColor/g,"glFragColor"),i=i.replace(/gl_FragData/g,"glFragData"),i=i.replace(/void\s+?main\s*\(/g,(d?"":`out vec4 glFragColor;
  89. `)+"void main(");else{var b=e.indexOf("#define MULTIVIEW")!==-1;if(b)return`#extension GL_OVR_multiview2 : require
  90. layout (num_views = 2) in;
  91. `+i}return i},a}(),DataBuffer=function(){function a(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=a._Counter++}return Object.defineProperty(a.prototype,"underlyingResource",{get:function(){return null},enumerable:!1,configurable:!0}),a._Counter=0,a}(),WebGLDataBuffer=function(a){__extends(i,a);function i(e){var o=a.call(this)||this;return o._buffer=e,o}return Object.defineProperty(i.prototype,"underlyingResource",{get:function(){return this._buffer},enumerable:!1,configurable:!0}),i}(DataBuffer),WebGLPipelineContext=function(){function a(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null}return Object.defineProperty(a.prototype,"isAsync",{get:function(){return this.isParallelCompiled},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isReady",{get:function(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1},enumerable:!1,configurable:!0}),a.prototype._handlesSpectorRebuildCallback=function(i){i&&this.program&&i(this.program)},a.prototype._fillEffectInformation=function(i,e,o,s,c,d,_,b){var k=this.engine;if(k.supportsUniformBuffers)for(var j in e)i.bindUniformBlock(j,e[j]);var $=this.engine.getUniforms(this,o);$.forEach(function(nt,ot){s[o[ot]]=nt}),this._uniforms=s;var _e;for(_e=0;_e<c.length;_e++){var et=i.getUniform(c[_e]);et==null&&(c.splice(_e,1),_e--)}c.forEach(function(nt,ot){d[nt]=ot});for(var tt=0,rt=k.getAttributes(this,_);tt<rt.length;tt++){var it=rt[tt];b.push(it)}},a.prototype.dispose=function(){this._uniforms={}},a.prototype._cacheMatrix=function(i,e){var o=this._valueCache[i],s=e.updateFlag;return o!==void 0&&o===s?!1:(this._valueCache[i]=s,!0)},a.prototype._cacheFloat2=function(i,e,o){var s=this._valueCache[i];if(!s||s.length!==2)return s=[e,o],this._valueCache[i]=s,!0;var c=!1;return s[0]!==e&&(s[0]=e,c=!0),s[1]!==o&&(s[1]=o,c=!0),c},a.prototype._cacheFloat3=function(i,e,o,s){var c=this._valueCache[i];if(!c||c.length!==3)return c=[e,o,s],this._valueCache[i]=c,!0;var d=!1;return c[0]!==e&&(c[0]=e,d=!0),c[1]!==o&&(c[1]=o,d=!0),c[2]!==s&&(c[2]=s,d=!0),d},a.prototype._cacheFloat4=function(i,e,o,s,c){var d=this._valueCache[i];if(!d||d.length!==4)return d=[e,o,s,c],this._valueCache[i]=d,!0;var _=!1;return d[0]!==e&&(d[0]=e,_=!0),d[1]!==o&&(d[1]=o,_=!0),d[2]!==s&&(d[2]=s,_=!0),d[3]!==c&&(d[3]=c,_=!0),_},a.prototype.setInt=function(i,e){var o=this._valueCache[i];o!==void 0&&o===e||this.engine.setInt(this._uniforms[i],e)&&(this._valueCache[i]=e)},a.prototype.setInt2=function(i,e,o){this._cacheFloat2(i,e,o)&&(this.engine.setInt2(this._uniforms[i],e,o)||(this._valueCache[i]=null))},a.prototype.setInt3=function(i,e,o,s){this._cacheFloat3(i,e,o,s)&&(this.engine.setInt3(this._uniforms[i],e,o,s)||(this._valueCache[i]=null))},a.prototype.setInt4=function(i,e,o,s,c){this._cacheFloat4(i,e,o,s,c)&&(this.engine.setInt4(this._uniforms[i],e,o,s,c)||(this._valueCache[i]=null))},a.prototype.setIntArray=function(i,e){this._valueCache[i]=null,this.engine.setIntArray(this._uniforms[i],e)},a.prototype.setIntArray2=function(i,e){this._valueCache[i]=null,this.engine.setIntArray2(this._uniforms[i],e)},a.prototype.setIntArray3=function(i,e){this._valueCache[i]=null,this.engine.setIntArray3(this._uniforms[i],e)},a.prototype.setIntArray4=function(i,e){this._valueCache[i]=null,this.engine.setIntArray4(this._uniforms[i],e)},a.prototype.setArray=function(i,e){this._valueCache[i]=null,this.engine.setArray(this._uniforms[i],e)},a.prototype.setArray2=function(i,e){this._valueCache[i]=null,this.engine.setArray2(this._uniforms[i],e)},a.prototype.setArray3=function(i,e){this._valueCache[i]=null,this.engine.setArray3(this._uniforms[i],e)},a.prototype.setArray4=function(i,e){this._valueCache[i]=null,this.engine.setArray4(this._uniforms[i],e)},a.prototype.setMatrices=function(i,e){!e||(this._valueCache[i]=null,this.engine.setMatrices(this._uniforms[i],e))},a.prototype.setMatrix=function(i,e){this._cacheMatrix(i,e)&&(this.engine.setMatrices(this._uniforms[i],e.toArray())||(this._valueCache[i]=null))},a.prototype.setMatrix3x3=function(i,e){this._valueCache[i]=null,this.engine.setMatrix3x3(this._uniforms[i],e)},a.prototype.setMatrix2x2=function(i,e){this._valueCache[i]=null,this.engine.setMatrix2x2(this._uniforms[i],e)},a.prototype.setFloat=function(i,e){var o=this._valueCache[i];o!==void 0&&o===e||this.engine.setFloat(this._uniforms[i],e)&&(this._valueCache[i]=e)},a.prototype.setVector2=function(i,e){this._cacheFloat2(i,e.x,e.y)&&(this.engine.setFloat2(this._uniforms[i],e.x,e.y)||(this._valueCache[i]=null))},a.prototype.setFloat2=function(i,e,o){this._cacheFloat2(i,e,o)&&(this.engine.setFloat2(this._uniforms[i],e,o)||(this._valueCache[i]=null))},a.prototype.setVector3=function(i,e){this._cacheFloat3(i,e.x,e.y,e.z)&&(this.engine.setFloat3(this._uniforms[i],e.x,e.y,e.z)||(this._valueCache[i]=null))},a.prototype.setFloat3=function(i,e,o,s){this._cacheFloat3(i,e,o,s)&&(this.engine.setFloat3(this._uniforms[i],e,o,s)||(this._valueCache[i]=null))},a.prototype.setVector4=function(i,e){this._cacheFloat4(i,e.x,e.y,e.z,e.w)&&(this.engine.setFloat4(this._uniforms[i],e.x,e.y,e.z,e.w)||(this._valueCache[i]=null))},a.prototype.setFloat4=function(i,e,o,s,c){this._cacheFloat4(i,e,o,s,c)&&(this.engine.setFloat4(this._uniforms[i],e,o,s,c)||(this._valueCache[i]=null))},a.prototype.setColor3=function(i,e){this._cacheFloat3(i,e.r,e.g,e.b)&&(this.engine.setFloat3(this._uniforms[i],e.r,e.g,e.b)||(this._valueCache[i]=null))},a.prototype.setColor4=function(i,e,o){this._cacheFloat4(i,e.r,e.g,e.b,o)&&(this.engine.setFloat4(this._uniforms[i],e.r,e.g,e.b,o)||(this._valueCache[i]=null))},a.prototype.setDirectColor4=function(i,e){this._cacheFloat4(i,e.r,e.g,e.b,e.a)&&(this.engine.setFloat4(this._uniforms[i],e.r,e.g,e.b,e.a)||(this._valueCache[i]=null))},a.prototype._getVertexShaderCode=function(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null},a.prototype._getFragmentShaderCode=function(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null},a}(),PerformanceConfigurator=function(){function a(){}return a.SetMatrixPrecision=function(i){if(a.MatrixTrackPrecisionChange=!1,i&&!a.MatrixUse64Bits&&a.MatrixTrackedMatrices)for(var e=0;e<a.MatrixTrackedMatrices.length;++e){var o=a.MatrixTrackedMatrices[e],s=o._m;o._m=new Array(16);for(var c=0;c<16;++c)o._m[c]=s[c]}a.MatrixUse64Bits=i,a.MatrixCurrentType=a.MatrixUse64Bits?Array:Float32Array,a.MatrixTrackedMatrices=null},a.MatrixUse64Bits=!1,a.MatrixTrackPrecisionChange=!0,a.MatrixCurrentType=Float32Array,a.MatrixTrackedMatrices=[],a}(),WebGLHardwareTexture=function(){function a(i,e){if(i===void 0&&(i=null),this._MSAARenderBuffer=null,this._context=e,!i&&(i=e.createTexture(),!i))throw new Error("Unable to create webGL texture");this.set(i)}return Object.defineProperty(a.prototype,"underlyingResource",{get:function(){return this._webGLTexture},enumerable:!1,configurable:!0}),a.prototype.setUsage=function(i,e,o,s,c){},a.prototype.set=function(i){this._webGLTexture=i},a.prototype.reset=function(){this._webGLTexture=null,this._MSAARenderBuffer=null},a.prototype.release=function(){this._MSAARenderBuffer&&(this._context.deleteRenderbuffer(this._MSAARenderBuffer),this._MSAARenderBuffer=null),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()},a}(),DrawWrapper=function(){function a(i,e){e===void 0&&(e=!0),this.effect=null,this.defines=null,this.drawContext=i.createDrawContext(),e&&(this.materialContext=i.createMaterialContext())}return a.IsWrapper=function(i){return i.getPipelineContext===void 0},a.GetEffect=function(i){return i.getPipelineContext===void 0?i.effect:i},a.prototype.setEffect=function(i,e,o){var s;o===void 0&&(o=!0),this.effect=i,e!==void 0&&(this.defines=e),o&&((s=this.drawContext)===null||s===void 0||s.reset())},a.prototype.dispose=function(){var i;(i=this.drawContext)===null||i===void 0||i.dispose()},a}(),StencilStateComposer=function(){function a(i){i===void 0&&(i=!0),this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,i&&this.reset()}return Object.defineProperty(a.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"func",{get:function(){return this._func},set:function(i){this._func!==i&&(this._func=i,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"funcRef",{get:function(){return this._funcRef},set:function(i){this._funcRef!==i&&(this._funcRef=i,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"funcMask",{get:function(){return this._funcMask},set:function(i){this._funcMask!==i&&(this._funcMask=i,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"opStencilFail",{get:function(){return this._opStencilFail},set:function(i){this._opStencilFail!==i&&(this._opStencilFail=i,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"opDepthFail",{get:function(){return this._opDepthFail},set:function(i){this._opDepthFail!==i&&(this._opDepthFail=i,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"opStencilDepthPass",{get:function(){return this._opStencilDepthPass},set:function(i){this._opStencilDepthPass!==i&&(this._opStencilDepthPass=i,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"mask",{get:function(){return this._mask},set:function(i){this._mask!==i&&(this._mask=i,this._isStencilMaskDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"enabled",{get:function(){return this._enabled},set:function(i){this._enabled!==i&&(this._enabled=i,this._isStencilTestDirty=!0)},enumerable:!1,configurable:!0}),a.prototype.reset=function(){var i;this.stencilMaterial=void 0,(i=this.stencilGlobal)===null||i===void 0||i.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},a.prototype.apply=function(i){var e;if(!!i){var o=!this.useStencilGlobalOnly&&!!(!((e=this.stencilMaterial)===null||e===void 0)&&e.enabled);this.enabled=o?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=o?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=o?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=o?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=o?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=o?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=o?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=o?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?i.enable(i.STENCIL_TEST):i.disable(i.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(i.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(i.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(i.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}},a}(),BufferPointer=function(){function a(){}return a}(),ThinEngine=function(){function a(i,e,o,s){var c=this;this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new Observable,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new Observable,this.onContextRestoredObservable=new Observable,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new DepthCullingState,this._stencilStateComposer=new StencilStateComposer,this._stencilState=new StencilState,this._alphaState=new AlphaState,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=new Array,this._renderTargetWrapperCache=new Array,this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._activeRequests=new Array,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new Observable,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={};var d=null;if(o=o||{},this._stencilStateComposer.stencilGlobal=this._stencilState,PerformanceConfigurator.SetMatrixPrecision(!!o.useHighPrecisionMatrix),!!i){if(s=s||o.adaptToDeviceRatio||!1,i.getContext){if(d=i,this._renderingCanvas=d,e!==void 0&&(o.antialias=e),o.deterministicLockstep===void 0&&(o.deterministicLockstep=!1),o.lockstepMaxSteps===void 0&&(o.lockstepMaxSteps=4),o.timeStep===void 0&&(o.timeStep=1/60),o.preserveDrawingBuffer===void 0&&(o.preserveDrawingBuffer=!1),o.audioEngine===void 0&&(o.audioEngine=!0),o.audioEngineOptions!==void 0&&o.audioEngineOptions.audioContext!==void 0&&(this._audioContext=o.audioEngineOptions.audioContext),o.audioEngineOptions!==void 0&&o.audioEngineOptions.audioDestination!==void 0&&(this._audioDestination=o.audioEngineOptions.audioDestination),o.stencil===void 0&&(o.stencil=!0),o.premultipliedAlpha===!1&&(this.premultipliedAlpha=!1),o.xrCompatible===void 0&&(o.xrCompatible=!0),this._doNotHandleContextLost=!!o.doNotHandleContextLost,navigator&&navigator.userAgent){this._checkForMobile=function(){var dt=navigator.userAgent;c.hostInformation.isMobile=dt.indexOf("Mobile")!==-1||dt.indexOf("Mac")!==-1&&IsDocumentAvailable()&&"ontouchend"in document},this._checkForMobile(),IsWindowObjectExist()&&window.addEventListener("resize",this._checkForMobile);for(var _=navigator.userAgent,b=0,k=a.ExceptionList;b<k.length;b++){var j=k[b],$=j.key,_e=j.targets,et=new RegExp($);if(et.test(_)){if(j.capture&&j.captureConstraint){var tt=j.capture,rt=j.captureConstraint,it=new RegExp(tt),nt=it.exec(_);if(nt&&nt.length>0){var ot=parseInt(nt[nt.length-1]);if(ot>=rt)continue}}for(var at=0,st=_e;at<st.length;at++){var ut=st[at];switch(ut){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break}}}}}if(this._doNotHandleContextLost||(this._onContextLost=function(dt){dt.preventDefault(),c._contextWasLost=!0,Logger$2.Warn("WebGL context lost."),c.onContextLostObservable.notifyObservers(c)},this._onContextRestored=function(){c._restoreEngineAfterContextLost(c._initGLContext.bind(c))},d.addEventListener("webglcontextlost",this._onContextLost,!1),d.addEventListener("webglcontextrestored",this._onContextRestored,!1),o.powerPreference="high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(o.xrCompatible=!1),!o.disableWebGL2Support)try{this._gl=d.getContext("webgl2",o)||d.getContext("experimental-webgl2",o),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch{}if(!this._gl){if(!d)throw new Error("The provided canvas is null or undefined.");try{this._gl=d.getContext("webgl",o)||d.getContext("experimental-webgl",o)}catch{throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=i,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";var ft=this._gl.getContextAttributes();ft&&(o.stencil=ft.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),o.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=o.useHighPrecisionFloats);var lt=IsWindowObjectExist()&&window.devicePixelRatio||1,ht=o.limitDeviceRatio||lt;this._hardwareScalingLevel=s?1/Math.min(ht,lt):1,this.resize(),this._isStencilEnable=!!o.stencil,this._initGLContext(),this._initFeatures();for(var pt=0;pt<this._caps.maxVertexAttribs;pt++)this._currentBufferPointers[pt]=new BufferPointer;this._shaderProcessor=this.webGLVersion>1?new WebGL2ShaderProcessor:new WebGLShaderProcessor,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._creationOptions=o;var mt="Babylon.js v"+a.Version;console.log(mt+(" - "+this.description)),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",mt)}}return Object.defineProperty(a,"NpmPackage",{get:function(){return"babylonjs@5.0.0-alpha.63"},enumerable:!1,configurable:!0}),Object.defineProperty(a,"Version",{get:function(){return"5.0.0-alpha.63"},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"description",{get:function(){var i=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(i+=" - Parallel shader compilation"),i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"name",{get:function(){return"WebGL"},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"version",{get:function(){return this._webGLVersion},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ShadersRepository",{get:function(){return Effect$1.ShadersRepository},set:function(i){Effect$1.ShadersRepository=i},enumerable:!1,configurable:!0}),a.prototype._getShaderProcessor=function(i){return this._shaderProcessor},Object.defineProperty(a.prototype,"useReverseDepthBuffer",{get:function(){return this._useReverseDepthBuffer},set:function(i){i!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=i,i?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"frameId",{get:function(){return this._frameId},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"supportsUniformBuffers",{get:function(){return this.webGLVersion>1&&!this.disableUniformBuffers},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"_shouldUseHighPrecisionShader",{get:function(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"activeRenderLoops",{get:function(){return this._activeRenderLoops},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(i){this._doNotHandleContextLost=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"_supportsHardwareTextureRescaling",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"framebufferDimensionsObject",{set:function(i){this._framebufferDimensionsObject=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"emptyTexture2DArray",{get:function(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var i=new Uint8Array(4),e=[i,i,i,i,i,i];this._emptyCubeTexture=this.createRawCubeTexture(e,1,5,0,!1,!1,1)}return this._emptyCubeTexture},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isWebGPU",{get:function(){return this._isWebGPU},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"shaderPlatformName",{get:function(){return this._shaderPlatformName},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"snapshotRendering",{get:function(){return!1},set:function(i){},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"snapshotRenderingMode",{get:function(){return this._snapshotRenderingMode},set:function(i){this._snapshotRenderingMode=i},enumerable:!1,configurable:!0}),a.prototype.snapshotRenderingReset=function(){this.snapshotRendering=!1},a._createCanvas=function(i,e){if(typeof document=="undefined")return new OffscreenCanvas(i,e);var o=document.createElement("canvas");return o.width=i,o.height=e,o},a.prototype.createCanvas=function(i,e){return a._createCanvas(i,e)},a.prototype.createCanvasImage=function(){return document.createElement("img")},a.prototype._restoreEngineAfterContextLost=function(i){var e=this;setTimeout(function(){return __awaiter(e,void 0,void 0,function(){var o,s,c,d,_;return __generator(this,function(b){switch(b.label){case 0:return this._dummyFramebuffer=null,o=this._depthCullingState.depthTest,s=this._depthCullingState.depthFunc,c=this._depthCullingState.depthMask,d=this._stencilState.stencilTest,[4,i()];case 1:return b.sent(),this._rebuildEffects(),(_=this._rebuildComputeEffects)===null||_===void 0||_.call(this),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this._rebuildBuffers(),this.wipeCaches(!0),this._depthCullingState.depthTest=o,this._depthCullingState.depthFunc=s,this._depthCullingState.depthMask=c,this._stencilState.stencilTest=d,Logger$2.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1,[2]}})})},0)},a.prototype._sharedInit=function(i,e,o){this._renderingCanvas=i},a.prototype._getShaderProcessingContext=function(i){return null},a.prototype._rebuildInternalTextures=function(){for(var i=this._internalTexturesCache.slice(),e=0,o=i;e<o.length;e++){var s=o[e];s._rebuild()}},a.prototype._rebuildRenderTargetWrappers=function(){for(var i=this._renderTargetWrapperCache.slice(),e=0,o=i;e<o.length;e++){var s=o[e];s._rebuild()}},a.prototype._rebuildEffects=function(){for(var i in this._compiledEffects){var e=this._compiledEffects[i];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}Effect$1.ResetCache()},a.prototype.areAllEffectsReady=function(){for(var i in this._compiledEffects){var e=this._compiledEffects[i];if(!e.isReady())return!1}return!0},a.prototype._rebuildBuffers=function(){for(var i=0,e=this._uniformBuffers;i<e.length;i++){var o=e[i];o._rebuild()}for(var s=0,c=this._storageBuffers;s<c.length;s++){var d=c[s];d._rebuild()}},a.prototype._initGLContext=function(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1},this._glVersion=this._gl.getParameter(this._gl.VERSION);var i=this._gl.getExtension("WEBGL_debug_renderer_info");if(i!=null&&(this._glRenderer=this._gl.getParameter(i.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(i.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor="Unknown vendor"),this._glRenderer||(this._glRenderer="Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._gl.getParameter(this._gl.MAX_SAMPLES);else{var e=this._gl.getExtension("WEBGL_draw_buffers");if(e!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var o=0;o<16;o++)this._gl["COLOR_ATTACHMENT"+o+"_WEBGL"]=e["COLOR_ATTACHMENT"+o+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var s=this._gl.getExtension("WEBGL_depth_texture");s!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=s.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var c=this._gl.getExtension("OES_vertex_array_object");c!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=c.createVertexArrayOES.bind(c),this._gl.bindVertexArray=c.bindVertexArrayOES.bind(c),this._gl.deleteVertexArray=c.deleteVertexArrayOES.bind(c))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var d=this._gl.getExtension("ANGLE_instanced_arrays");d!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=d.drawArraysInstancedANGLE.bind(d),this._gl.drawElementsInstanced=d.drawElementsInstancedANGLE.bind(d),this._gl.vertexAttribDivisor=d.vertexAttribDivisorANGLE.bind(d)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){var _=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),b=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);_&&b&&(this._caps.highPrecisionShaderSupported=_.precision!==0&&b.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{var k=this._gl.getExtension("EXT_blend_minmax");k!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=k.MAX_EXT,this._gl.MIN=k.MIN_EXT)}if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0;else{var j=this._gl.getExtension("EXT_sRGB");j!=null&&(this._caps.supportSRGBBuffers=!0,this._gl.SRGB=j.SRGB_EXT,this._gl.SRGB8=j.SRGB_ALPHA_EXT,this._gl.SRGB8_ALPHA8=j.SRGB_ALPHA_EXT)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var $=0;$<this._maxSimultaneousTextures;$++)this._nextFreeTextureSlots.push($)},a.prototype._initFeatures=function(){this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,_collectUbosUpdatedInFrame:!1}},Object.defineProperty(a.prototype,"webGLVersion",{get:function(){return this._webGLVersion},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"ThinEngine"},Object.defineProperty(a.prototype,"isStencilEnable",{get:function(){return this._isStencilEnable},enumerable:!1,configurable:!0}),a.prototype._prepareWorkingCanvas=function(){if(!this._workingCanvas){this._workingCanvas=this.createCanvas(1,1);var i=this._workingCanvas.getContext("2d");i&&(this._workingContext=i)}},a.prototype.resetTextureCache=function(){for(var i in this._boundTexturesCache)!this._boundTexturesCache.hasOwnProperty(i)||(this._boundTexturesCache[i]=null);this._currentTextureChannel=-1},a.prototype.getInfo=function(){return this.getGlInfo()},a.prototype.getGlInfo=function(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}},a.prototype.setHardwareScalingLevel=function(i){this._hardwareScalingLevel=i,this.resize()},a.prototype.getHardwareScalingLevel=function(){return this._hardwareScalingLevel},a.prototype.getLoadedTexturesCache=function(){return this._internalTexturesCache},a.prototype.getCaps=function(){return this._caps},a.prototype.stopRenderLoop=function(i){if(!i){this._activeRenderLoops=[];return}var e=this._activeRenderLoops.indexOf(i);e>=0&&this._activeRenderLoops.splice(e,1)},a.prototype._renderLoop=function(){if(!this._contextWasLost){var i=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(i=!1),i){this.beginFrame();for(var e=0;e<this._activeRenderLoops.length;e++){var o=this._activeRenderLoops[e];o()}this.endFrame()}}this._activeRenderLoops.length>0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1},a.prototype.getRenderingCanvas=function(){return this._renderingCanvas},a.prototype.getAudioContext=function(){return this._audioContext},a.prototype.getAudioDestination=function(){return this._audioDestination},a.prototype.getHostWindow=function(){return IsWindowObjectExist()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null},a.prototype.getRenderWidth=function(i){return i===void 0&&(i=!1),!i&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth},a.prototype.getRenderHeight=function(i){return i===void 0&&(i=!1),!i&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight},a.prototype._queueNewFrame=function(i,e){return a.QueueNewFrame(i,e)},a.prototype.runRenderLoop=function(i){this._activeRenderLoops.indexOf(i)===-1&&(this._activeRenderLoops.push(i),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))},a.prototype.clear=function(i,e,o,s){s===void 0&&(s=!1);var c=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=c;var d=0;e&&i&&(this._gl.clearColor(i.r,i.g,i.b,i.a!==void 0?i.a:1),d|=this._gl.COLOR_BUFFER_BIT),o&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),d|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),d|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(d)},a.prototype._viewport=function(i,e,o,s){(i!==this._viewportCached.x||e!==this._viewportCached.y||o!==this._viewportCached.z||s!==this._viewportCached.w)&&(this._viewportCached.x=i,this._viewportCached.y=e,this._viewportCached.z=o,this._viewportCached.w=s,this._gl.viewport(i,e,o,s))},a.prototype.setViewport=function(i,e,o){var s=e||this.getRenderWidth(),c=o||this.getRenderHeight(),d=i.x||0,_=i.y||0;this._cachedViewport=i,this._viewport(d*s,_*c,s*i.width,c*i.height)},a.prototype.beginFrame=function(){},a.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._frameId++},a.prototype.resize=function(i){i===void 0&&(i=!1);var e,o;IsWindowObjectExist()?(e=this._renderingCanvas?this._renderingCanvas.clientWidth||this._renderingCanvas.width:window.innerWidth,o=this._renderingCanvas?this._renderingCanvas.clientHeight||this._renderingCanvas.height:window.innerHeight):(e=this._renderingCanvas?this._renderingCanvas.width:100,o=this._renderingCanvas?this._renderingCanvas.height:100),this.setSize(e/this._hardwareScalingLevel,o/this._hardwareScalingLevel,i)},a.prototype.setSize=function(i,e,o){return o===void 0&&(o=!1),!this._renderingCanvas||(i=i|0,e=e|0,!o&&this._renderingCanvas.width===i&&this._renderingCanvas.height===e)?!1:(this._renderingCanvas.width=i,this._renderingCanvas.height=e,!0)},a.prototype.bindFramebuffer=function(i,e,o,s,c,d,_){var b,k,j,$,_e;e===void 0&&(e=0),d===void 0&&(d=0),_===void 0&&(_=0);var et=i;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=i,this._bindUnboundFramebuffer(et._MSAAFramebuffer?et._MSAAFramebuffer:et._framebuffer);var tt=this._gl;i.is2DArray?tt.framebufferTextureLayer(tt.FRAMEBUFFER,tt.COLOR_ATTACHMENT0,(b=i.texture._hardwareTexture)===null||b===void 0?void 0:b.underlyingResource,d,_):i.isCube&&tt.framebufferTexture2D(tt.FRAMEBUFFER,tt.COLOR_ATTACHMENT0,tt.TEXTURE_CUBE_MAP_POSITIVE_X+e,(k=i.texture._hardwareTexture)===null||k===void 0?void 0:k.underlyingResource,d);var rt=i._depthStencilTexture;if(rt){var it=i._depthStencilTextureWithStencil?tt.DEPTH_STENCIL_ATTACHMENT:tt.DEPTH_ATTACHMENT;i.is2DArray?tt.framebufferTextureLayer(tt.FRAMEBUFFER,it,(j=rt._hardwareTexture)===null||j===void 0?void 0:j.underlyingResource,d,_):i.isCube?tt.framebufferTexture2D(tt.FRAMEBUFFER,it,tt.TEXTURE_CUBE_MAP_POSITIVE_X+e,($=rt._hardwareTexture)===null||$===void 0?void 0:$.underlyingResource,d):tt.framebufferTexture2D(tt.FRAMEBUFFER,it,tt.TEXTURE_2D,(_e=rt._hardwareTexture)===null||_e===void 0?void 0:_e.underlyingResource,d)}this._cachedViewport&&!c?this.setViewport(this._cachedViewport,o,s):(o||(o=i.width,d&&(o=o/Math.pow(2,d))),s||(s=i.height,d&&(s=s/Math.pow(2,d))),this._viewport(0,0,o,s)),this.wipeCaches()},a.prototype.setState=function(i,e,o,s,c,d,_){var b,k;e===void 0&&(e=0),s===void 0&&(s=!1),_===void 0&&(_=0),(this._depthCullingState.cull!==i||o)&&(this._depthCullingState.cull=i);var j=!((k=(b=this.cullBackFaces)!==null&&b!==void 0?b:c)!==null&&k!==void 0)||k?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==j||o)&&(this._depthCullingState.cullFace=j),this.setZOffset(e),this.setZOffsetUnits(_);var $=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==$||o)&&(this._depthCullingState.frontFace=$),this._stencilStateComposer.stencilMaterial=d},a.prototype.setZOffset=function(i){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-i:i},a.prototype.getZOffset=function(){var i=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-i:i},a.prototype.setZOffsetUnits=function(i){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-i:i},a.prototype.getZOffsetUnits=function(){var i=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-i:i},a.prototype._bindUnboundFramebuffer=function(i){this._currentFramebuffer!==i&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,i),this._currentFramebuffer=i)},a.prototype._currentFrameBufferIsDefaultFrameBuffer=function(){return this._currentFramebuffer===null},a.prototype.generateMipmaps=function(i){this._bindTextureDirectly(this._gl.TEXTURE_2D,i,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)},a.prototype.unBindFramebuffer=function(i,e,o){var s;e===void 0&&(e=!1);var c=i;this._currentRenderTarget=null;var d=this._gl;if(c._MSAAFramebuffer){if(i.isMulti){this.unBindMultiColorAttachmentFramebuffer(i,e,o);return}d.bindFramebuffer(d.READ_FRAMEBUFFER,c._MSAAFramebuffer),d.bindFramebuffer(d.DRAW_FRAMEBUFFER,c._framebuffer),d.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,d.COLOR_BUFFER_BIT,d.NEAREST)}((s=i.texture)===null||s===void 0?void 0:s.generateMipMaps)&&!e&&!i.isCube&&this.generateMipmaps(i.texture),o&&(c._MSAAFramebuffer&&this._bindUnboundFramebuffer(c._framebuffer),o()),this._bindUnboundFramebuffer(null)},a.prototype.flushFramebuffer=function(){this._gl.flush()},a.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()},a.prototype._resetVertexBufferBinding=function(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null},a.prototype.createVertexBuffer=function(i){return this._createVertexBuffer(i,this._gl.STATIC_DRAW)},a.prototype._createVertexBuffer=function(i,e){var o=this._gl.createBuffer();if(!o)throw new Error("Unable to create vertex buffer");var s=new WebGLDataBuffer(o);return this.bindArrayBuffer(s),i instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(i),e):this._gl.bufferData(this._gl.ARRAY_BUFFER,i,e),this._resetVertexBufferBinding(),s.references=1,s},a.prototype.createDynamicVertexBuffer=function(i){return this._createVertexBuffer(i,this._gl.DYNAMIC_DRAW)},a.prototype._resetIndexBufferBinding=function(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null},a.prototype.createIndexBuffer=function(i,e){var o=this._gl.createBuffer(),s=new WebGLDataBuffer(o);if(!o)throw new Error("Unable to create index buffer");this.bindIndexBuffer(s);var c=this._normalizeIndexData(i);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,c,e?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),s.references=1,s.is32Bits=c.BYTES_PER_ELEMENT===4,s},a.prototype._normalizeIndexData=function(i){var e=i.BYTES_PER_ELEMENT;if(e===2)return i;if(this._caps.uintIndices){if(i instanceof Uint32Array)return i;for(var o=0;o<i.length;o++)if(i[o]>=65535)return new Uint32Array(i);return new Uint16Array(i)}return new Uint16Array(i)},a.prototype.bindArrayBuffer=function(i){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(i,this._gl.ARRAY_BUFFER)},a.prototype.bindUniformBlock=function(i,e,o){var s=i.program,c=this._gl.getUniformBlockIndex(s,e);this._gl.uniformBlockBinding(s,c,o)},a.prototype.bindIndexBuffer=function(i){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(i,this._gl.ELEMENT_ARRAY_BUFFER)},a.prototype.bindBuffer=function(i,e){(this._vaoRecordInProgress||this._currentBoundBuffer[e]!==i)&&(this._gl.bindBuffer(e,i?i.underlyingResource:null),this._currentBoundBuffer[e]=i)},a.prototype.updateArrayBuffer=function(i){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,i)},a.prototype._vertexAttribPointer=function(i,e,o,s,c,d,_){var b=this._currentBufferPointers[e];if(!!b){var k=!1;b.active?(b.buffer!==i&&(b.buffer=i,k=!0),b.size!==o&&(b.size=o,k=!0),b.type!==s&&(b.type=s,k=!0),b.normalized!==c&&(b.normalized=c,k=!0),b.stride!==d&&(b.stride=d,k=!0),b.offset!==_&&(b.offset=_,k=!0)):(k=!0,b.active=!0,b.index=e,b.size=o,b.type=s,b.normalized=c,b.stride=d,b.offset=_,b.buffer=i),(k||this._vaoRecordInProgress)&&(this.bindArrayBuffer(i),this._gl.vertexAttribPointer(e,o,s,c,d,_))}},a.prototype._bindIndexBufferWithCache=function(i){i!=null&&this._cachedIndexBuffer!==i&&(this._cachedIndexBuffer=i,this.bindIndexBuffer(i),this._uintIndicesCurrentlySet=i.is32Bits)},a.prototype._bindVertexBuffersAttributes=function(i,e,o){var s=e.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var c=0;c<s.length;c++){var d=e.getAttributeLocation(c);if(d>=0){var _=s[c],b=null;if(o&&(b=o[_]),b||(b=i[_]),!b)continue;this._gl.enableVertexAttribArray(d),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[d]=!0);var k=b.getBuffer();k&&(this._vertexAttribPointer(k,d,b.getSize(),b.type,b.normalized,b.byteStride,b.byteOffset),b.getIsInstanced()&&(this._gl.vertexAttribDivisor(d,b.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(d),this._currentInstanceBuffers.push(k))))}}},a.prototype.recordVertexArrayObject=function(i,e,o,s){var c=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(c),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(i,o,s),this.bindIndexBuffer(e),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),c},a.prototype.bindVertexArrayObject=function(i,e){this._cachedVertexArrayObject!==i&&(this._cachedVertexArrayObject=i,this._gl.bindVertexArray(i),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=e!=null&&e.is32Bits,this._mustWipeVertexAttributes=!0)},a.prototype.bindBuffersDirectly=function(i,e,o,s,c){if(this._cachedVertexBuffers!==i||this._cachedEffectForVertexBuffers!==c){this._cachedVertexBuffers=i,this._cachedEffectForVertexBuffers=c;var d=c.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var _=0,b=0;b<d;b++)if(b<o.length){var k=c.getAttributeLocation(b);k>=0&&(this._gl.enableVertexAttribArray(k),this._vertexAttribArraysEnabled[k]=!0,this._vertexAttribPointer(i,k,o[b],this._gl.FLOAT,!1,s,_)),_+=o[b]*4}}this._bindIndexBufferWithCache(e)},a.prototype._unbindVertexArrayObject=function(){!this._cachedVertexArrayObject||(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},a.prototype.bindBuffers=function(i,e,o,s){(this._cachedVertexBuffers!==i||this._cachedEffectForVertexBuffers!==o)&&(this._cachedVertexBuffers=i,this._cachedEffectForVertexBuffers=o,this._bindVertexBuffersAttributes(i,o,s)),this._bindIndexBufferWithCache(e)},a.prototype.unbindInstanceAttributes=function(){for(var i,e=0,o=this._currentInstanceLocations.length;e<o;e++){var s=this._currentInstanceBuffers[e];i!=s&&s.references&&(i=s,this.bindArrayBuffer(s));var c=this._currentInstanceLocations[e];this._gl.vertexAttribDivisor(c,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0},a.prototype.releaseVertexArrayObject=function(i){this._gl.deleteVertexArray(i)},a.prototype._releaseBuffer=function(i){return i.references--,i.references===0?(this._deleteBuffer(i),!0):!1},a.prototype._deleteBuffer=function(i){this._gl.deleteBuffer(i.underlyingResource)},a.prototype.updateAndBindInstancesBuffer=function(i,e,o){if(this.bindArrayBuffer(i),e&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e),o[0].index!==void 0)this.bindInstancesBuffer(i,o,!0);else for(var s=0;s<4;s++){var c=o[s];this._vertexAttribArraysEnabled[c]||(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0),this._vertexAttribPointer(i,c,4,this._gl.FLOAT,!1,64,s*16),this._gl.vertexAttribDivisor(c,1),this._currentInstanceLocations.push(c),this._currentInstanceBuffers.push(i)}},a.prototype.bindInstancesBuffer=function(i,e,o){o===void 0&&(o=!0),this.bindArrayBuffer(i);var s=0;if(o)for(var c=0;c<e.length;c++){var d=e[c];s+=d.attributeSize*4}for(var c=0;c<e.length;c++){var d=e[c];d.index===void 0&&(d.index=this._currentEffect.getAttributeLocationByName(d.attributeName)),!(d.index<0)&&(this._vertexAttribArraysEnabled[d.index]||(this._gl.enableVertexAttribArray(d.index),this._vertexAttribArraysEnabled[d.index]=!0),this._vertexAttribPointer(i,d.index,d.attributeSize,d.attributeType||this._gl.FLOAT,d.normalized||!1,s,d.offset),this._gl.vertexAttribDivisor(d.index,d.divisor===void 0?1:d.divisor),this._currentInstanceLocations.push(d.index),this._currentInstanceBuffers.push(i))}},a.prototype.disableInstanceAttributeByName=function(i){if(!!this._currentEffect){var e=this._currentEffect.getAttributeLocationByName(i);this.disableInstanceAttribute(e)}},a.prototype.disableInstanceAttribute=function(i){for(var e=!1,o;(o=this._currentInstanceLocations.indexOf(i))!==-1;)this._currentInstanceLocations.splice(o,1),this._currentInstanceBuffers.splice(o,1),e=!0,o=this._currentInstanceLocations.indexOf(i);e&&(this._gl.vertexAttribDivisor(i,0),this.disableAttributeByIndex(i))},a.prototype.disableAttributeByIndex=function(i){this._gl.disableVertexAttribArray(i),this._vertexAttribArraysEnabled[i]=!1,this._currentBufferPointers[i].active=!1},a.prototype.draw=function(i,e,o,s){this.drawElementsType(i?0:1,e,o,s)},a.prototype.drawPointClouds=function(i,e,o){this.drawArraysType(2,i,e,o)},a.prototype.drawUnIndexed=function(i,e,o,s){this.drawArraysType(i?0:1,e,o,s)},a.prototype.drawElementsType=function(i,e,o,s){this.applyStates(),this._reportDrawCall();var c=this._drawMode(i),d=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,_=this._uintIndicesCurrentlySet?4:2;s?this._gl.drawElementsInstanced(c,o,d,e*_,s):this._gl.drawElements(c,o,d,e*_)},a.prototype.drawArraysType=function(i,e,o,s){this.applyStates(),this._reportDrawCall();var c=this._drawMode(i);s?this._gl.drawArraysInstanced(c,e,o,s):this._gl.drawArrays(c,e,o)},a.prototype._drawMode=function(i){switch(i){case 0:return this._gl.TRIANGLES;case 2:return this._gl.POINTS;case 1:return this._gl.LINES;case 3:return this._gl.POINTS;case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}},a.prototype._reportDrawCall=function(){},a.prototype._releaseEffect=function(i){if(this._compiledEffects[i._key]){delete this._compiledEffects[i._key];var e=i.getPipelineContext();e&&this._deletePipelineContext(e)}},a.prototype._deletePipelineContext=function(i){var e=i;e&&e.program&&(e.program.__SPECTOR_rebuildProgram=null,this._gl.deleteProgram(e.program))},a.prototype._getGlobalDefines=function(i){if(i){this.isNDCHalfZRange?i.IS_NDC_HALF_ZRANGE="":delete i.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?i.USE_REVERSE_DEPTHBUFFER="":delete i.USE_REVERSE_DEPTHBUFFER;return}else{var e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+=`
  92. `),e+="#define USE_REVERSE_DEPTHBUFFER"),e}},a.prototype.createEffect=function(i,e,o,s,c,d,_,b,k,j){var $;j===void 0&&(j=ShaderLanguage.GLSL);var _e=i.vertexElement||i.vertex||i.vertexToken||i.vertexSource||i,et=i.fragmentElement||i.fragment||i.fragmentToken||i.fragmentSource||i,tt=this._getGlobalDefines(),rt=($=c!=null?c:e.defines)!==null&&$!==void 0?$:"";tt&&(rt+=tt);var it=_e+"+"+et+"@"+rt;if(this._compiledEffects[it]){var nt=this._compiledEffects[it];return _&&nt.isReady()&&_(nt),nt}var ot=new Effect$1(i,e,o,s,this,c,d,_,b,k,it,j);return this._compiledEffects[it]=ot,ot},a._ConcatenateShader=function(i,e,o){return o===void 0&&(o=""),o+(e?e+`
  93. `:"")+i},a.prototype._compileShader=function(i,e,o,s){return this._compileRawShader(a._ConcatenateShader(i,o,s),e)},a.prototype._compileRawShader=function(i,e){for(var o=this._gl;o.getError()!=o.NO_ERROR;);var s=o.createShader(e==="vertex"?o.VERTEX_SHADER:o.FRAGMENT_SHADER);if(!s)throw new Error("Something went wrong while creating a gl "+e+" shader object. gl error="+o.getError()+", gl isContextLost="+o.isContextLost()+", _contextWasLost="+this._contextWasLost);return o.shaderSource(s,i),o.compileShader(s),s},a.prototype._getShaderSource=function(i){return this._gl.getShaderSource(i)},a.prototype.createRawShaderProgram=function(i,e,o,s,c){c===void 0&&(c=null),s=s||this._gl;var d=this._compileRawShader(e,"vertex"),_=this._compileRawShader(o,"fragment");return this._createShaderProgram(i,d,_,s,c)},a.prototype.createShaderProgram=function(i,e,o,s,c,d){d===void 0&&(d=null),c=c||this._gl;var _=this._webGLVersion>1?`#version 300 es
  94. #define WEBGL2
  95. `:"",b=this._compileShader(e,"vertex",s,_),k=this._compileShader(o,"fragment",s,_);return this._createShaderProgram(i,b,k,c,d)},a.prototype.inlineShaderCode=function(i){return i},a.prototype.createPipelineContext=function(i){var e=new WebGLPipelineContext;return e.engine=this,this._caps.parallelShaderCompile&&(e.isParallelCompiled=!0),e},a.prototype.createMaterialContext=function(){},a.prototype.createDrawContext=function(){},a.prototype._createShaderProgram=function(i,e,o,s,c){var d=s.createProgram();if(i.program=d,!d)throw new Error("Unable to create program");return s.attachShader(d,e),s.attachShader(d,o),s.linkProgram(d),i.context=s,i.vertexShader=e,i.fragmentShader=o,i.isParallelCompiled||this._finalizePipelineContext(i),d},a.prototype._finalizePipelineContext=function(i){var e=i.context,o=i.vertexShader,s=i.fragmentShader,c=i.program,d=e.getProgramParameter(c,e.LINK_STATUS);if(!d){if(!this._gl.getShaderParameter(o,this._gl.COMPILE_STATUS)){var _=this._gl.getShaderInfoLog(o);if(_)throw i.vertexCompilationError=_,new Error("VERTEX SHADER "+_)}if(!this._gl.getShaderParameter(s,this._gl.COMPILE_STATUS)){var _=this._gl.getShaderInfoLog(s);if(_)throw i.fragmentCompilationError=_,new Error("FRAGMENT SHADER "+_)}var b=e.getProgramInfoLog(c);if(b)throw i.programLinkError=b,new Error(b)}if(this.validateShaderPrograms){e.validateProgram(c);var k=e.getProgramParameter(c,e.VALIDATE_STATUS);if(!k){var b=e.getProgramInfoLog(c);if(b)throw i.programValidationError=b,new Error(b)}}e.deleteShader(o),e.deleteShader(s),i.vertexShader=void 0,i.fragmentShader=void 0,i.onCompiled&&(i.onCompiled(),i.onCompiled=void 0)},a.prototype._preparePipelineContext=function(i,e,o,s,c,d,_,b,k,j){var $=i;s?$.program=this.createRawShaderProgram($,e,o,void 0,k):$.program=this.createShaderProgram($,e,o,b,void 0,k),$.program.__SPECTOR_rebuildProgram=_},a.prototype._isRenderingStateCompiled=function(i){var e=i;return this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)?(this._finalizePipelineContext(e),!0):!1},a.prototype._executeWhenRenderingStateIsCompiled=function(i,e){var o=i;if(!o.isParallelCompiled){e();return}var s=o.onCompiled;s?o.onCompiled=function(){s(),e()}:o.onCompiled=e},a.prototype.getUniforms=function(i,e){for(var o=new Array,s=i,c=0;c<e.length;c++)o.push(this._gl.getUniformLocation(s.program,e[c]));return o},a.prototype.getAttributes=function(i,e){for(var o=[],s=i,c=0;c<e.length;c++)try{o.push(this._gl.getAttribLocation(s.program,e[c]))}catch{o.push(-1)}return o},a.prototype.enableEffect=function(i){i=i!==null&&DrawWrapper.IsWrapper(i)?i.effect:i,!(!i||i===this._currentEffect)&&(this._stencilStateComposer.stencilMaterial=void 0,i=i,this.bindSamplers(i),this._currentEffect=i,i.onBind&&i.onBind(i),i._onBindObservable&&i._onBindObservable.notifyObservers(i))},a.prototype.setInt=function(i,e){return i?(this._gl.uniform1i(i,e),!0):!1},a.prototype.setInt2=function(i,e,o){return i?(this._gl.uniform2i(i,e,o),!0):!1},a.prototype.setInt3=function(i,e,o,s){return i?(this._gl.uniform3i(i,e,o,s),!0):!1},a.prototype.setInt4=function(i,e,o,s,c){return i?(this._gl.uniform4i(i,e,o,s,c),!0):!1},a.prototype.setIntArray=function(i,e){return i?(this._gl.uniform1iv(i,e),!0):!1},a.prototype.setIntArray2=function(i,e){return!i||e.length%2!==0?!1:(this._gl.uniform2iv(i,e),!0)},a.prototype.setIntArray3=function(i,e){return!i||e.length%3!==0?!1:(this._gl.uniform3iv(i,e),!0)},a.prototype.setIntArray4=function(i,e){return!i||e.length%4!==0?!1:(this._gl.uniform4iv(i,e),!0)},a.prototype.setArray=function(i,e){return!i||e.length<1?!1:(this._gl.uniform1fv(i,e),!0)},a.prototype.setArray2=function(i,e){return!i||e.length%2!==0?!1:(this._gl.uniform2fv(i,e),!0)},a.prototype.setArray3=function(i,e){return!i||e.length%3!==0?!1:(this._gl.uniform3fv(i,e),!0)},a.prototype.setArray4=function(i,e){return!i||e.length%4!==0?!1:(this._gl.uniform4fv(i,e),!0)},a.prototype.setMatrices=function(i,e){return i?(this._gl.uniformMatrix4fv(i,!1,e),!0):!1},a.prototype.setMatrix3x3=function(i,e){return i?(this._gl.uniformMatrix3fv(i,!1,e),!0):!1},a.prototype.setMatrix2x2=function(i,e){return i?(this._gl.uniformMatrix2fv(i,!1,e),!0):!1},a.prototype.setFloat=function(i,e){return i?(this._gl.uniform1f(i,e),!0):!1},a.prototype.setFloat2=function(i,e,o){return i?(this._gl.uniform2f(i,e,o),!0):!1},a.prototype.setFloat3=function(i,e,o,s){return i?(this._gl.uniform3f(i,e,o,s),!0):!1},a.prototype.setFloat4=function(i,e,o,s,c){return i?(this._gl.uniform4f(i,e,o,s,c),!0):!1},a.prototype.applyStates=function(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;var i=this._colorWrite;this._gl.colorMask(i,i,i,i)}},a.prototype.setColorWrite=function(i){i!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=i)},a.prototype.getColorWrite=function(){return this._colorWrite},Object.defineProperty(a.prototype,"depthCullingState",{get:function(){return this._depthCullingState},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"alphaState",{get:function(){return this._alphaState},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilState",{get:function(){return this._stencilState},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stencilStateComposer",{get:function(){return this._stencilStateComposer},enumerable:!1,configurable:!0}),a.prototype.clearInternalTexturesCache=function(){this._internalTexturesCache=[]},a.prototype.wipeCaches=function(i){this.preventCacheWipeBetweenFrames&&!i||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),i&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))},a.prototype._getSamplingParameters=function(i,e){var o=this._gl,s=o.NEAREST,c=o.NEAREST;switch(i){case 11:s=o.LINEAR,e?c=o.LINEAR_MIPMAP_NEAREST:c=o.LINEAR;break;case 3:s=o.LINEAR,e?c=o.LINEAR_MIPMAP_LINEAR:c=o.LINEAR;break;case 8:s=o.NEAREST,e?c=o.NEAREST_MIPMAP_LINEAR:c=o.NEAREST;break;case 4:s=o.NEAREST,e?c=o.NEAREST_MIPMAP_NEAREST:c=o.NEAREST;break;case 5:s=o.NEAREST,e?c=o.LINEAR_MIPMAP_NEAREST:c=o.LINEAR;break;case 6:s=o.NEAREST,e?c=o.LINEAR_MIPMAP_LINEAR:c=o.LINEAR;break;case 7:s=o.NEAREST,c=o.LINEAR;break;case 1:s=o.NEAREST,c=o.NEAREST;break;case 9:s=o.LINEAR,e?c=o.NEAREST_MIPMAP_NEAREST:c=o.NEAREST;break;case 10:s=o.LINEAR,e?c=o.NEAREST_MIPMAP_LINEAR:c=o.NEAREST;break;case 2:s=o.LINEAR,c=o.LINEAR;break;case 12:s=o.LINEAR,c=o.NEAREST;break}return{min:c,mag:s}},a.prototype._createTexture=function(){var i=this._gl.createTexture();if(!i)throw new Error("Unable to create texture");return i},a.prototype._createHardwareTexture=function(){return new WebGLHardwareTexture(this._createTexture(),this._gl)},a.prototype._createInternalTexture=function(i,e,o,s){s===void 0&&(s=InternalTextureSource.Unknown);var c={};e!==void 0&&typeof e=="object"?(c.generateMipMaps=e.generateMipMaps,c.type=e.type===void 0?0:e.type,c.samplingMode=e.samplingMode===void 0?3:e.samplingMode,c.format=e.format===void 0?5:e.format):(c.generateMipMaps=e,c.type=0,c.samplingMode=3,c.format=5),(c.type===1&&!this._caps.textureFloatLinearFiltering||c.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(c.samplingMode=1),c.type===1&&!this._caps.textureFloat&&(c.type=0,Logger$2.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));var d=this._gl,_=new InternalTexture(this,s),b=i.width||i,k=i.height||i,j=i.layers||0,$=this._getSamplingParameters(c.samplingMode,!!c.generateMipMaps),_e=j!==0?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,et=this._getRGBABufferInternalSizedFormat(c.type,c.format),tt=this._getInternalFormat(c.format),rt=this._getWebGLTextureType(c.type);return this._bindTextureDirectly(_e,_),j!==0?(_.is2DArray=!0,d.texImage3D(_e,0,et,b,k,j,0,tt,rt,null)):d.texImage2D(_e,0,et,b,k,0,tt,rt,null),d.texParameteri(_e,d.TEXTURE_MAG_FILTER,$.mag),d.texParameteri(_e,d.TEXTURE_MIN_FILTER,$.min),d.texParameteri(_e,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(_e,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),c.generateMipMaps&&this._gl.generateMipmap(_e),this._bindTextureDirectly(_e,null),_.baseWidth=b,_.baseHeight=k,_.width=b,_.height=k,_.depth=j,_.isReady=!0,_.samples=1,_.generateMipMaps=!!c.generateMipMaps,_.samplingMode=c.samplingMode,_.type=c.type,_.format=c.format,this._internalTexturesCache.push(_),_},a.prototype._getUseSRGBBuffer=function(i,e){return i&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||e)},a.prototype._createTextureBase=function(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it){var nt=this;c===void 0&&(c=3),d===void 0&&(d=null),_===void 0&&(_=null),j===void 0&&(j=null),$===void 0&&($=null),_e===void 0&&(_e=null),et===void 0&&(et=null),i=i||"";var ot=i.substr(0,5)==="data:",at=i.substr(0,5)==="blob:",st=ot&&i.indexOf(";base64,")!==-1,ut=$||new InternalTexture(this,InternalTextureSource.Url),ft=i;this._transformTextureUrl&&!st&&!$&&!j&&(i=this._transformTextureUrl(i)),ft!==i&&(ut._originalUrl=ft);var lt=i.lastIndexOf("."),ht=et||(lt>-1?i.substring(lt).toLowerCase():""),pt=null,mt=ht.indexOf("?");mt>-1&&(ht=ht.split("?")[0]);for(var dt=0,gt=a._TextureLoaders;dt<gt.length;dt++){var _t=gt[dt];if(_t.canLoad(ht,tt)){pt=_t;break}}s&&s._addPendingData(ut),ut.url=i,ut.generateMipMaps=!e,ut.samplingMode=c,ut.invertY=o,ut._useSRGBBuffer=this._getUseSRGBBuffer(!!it,e),this._doNotHandleContextLost||(ut._buffer=j);var yt=null;d&&!$&&(yt=ut.onLoadedObservable.add(d)),$||this._internalTexturesCache.push(ut);var Tt=function(vt,Et){s&&s._removePendingData(ut),i===ft?(yt&&ut.onLoadedObservable.remove(yt),EngineStore.UseFallbackTexture&&nt._createTextureBase(EngineStore.FallbackTexture,e,ut.invertY,s,c,null,_,b,k,j,ut),vt=(vt||"Unknown error")+(EngineStore.UseFallbackTexture?" - Fallback texture was used":""),ut.onErrorObservable.notifyObservers({message:vt,exception:Et}),_&&_(vt,Et)):(Logger$2.Warn("Failed to load "+i+", falling back to "+ft),nt._createTextureBase(ft,e,ut.invertY,s,c,d,_,b,k,j,ut,_e,et,tt,rt,it))};if(pt){var St=function(vt){pt.loadData(vt,ut,function(Et,xt,bt,Mt,Rt,Pt){Pt?Tt("TextureLoader failed to load data"):b(ut,ht,s,{width:Et,height:xt},ut.invertY,!bt,Mt,function(){return Rt(),!1},c)},rt)};j?j instanceof ArrayBuffer?St(new Uint8Array(j)):ArrayBuffer.isView(j)?St(j):_&&_("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(i,function(vt){return St(new Uint8Array(vt))},void 0,s?s.offlineProvider:void 0,!0,function(vt,Et){Tt("Unable to load "+(vt&&vt.responseURL,Et))})}else{var At=function(vt){at&&!nt._doNotHandleContextLost&&(ut._buffer=vt),b(ut,ht,s,vt,ut.invertY,e,!1,k,c)};!ot||st?j&&(typeof j.decoding=="string"||j.close)?At(j):a._FileToolsLoadImage(i,At,Tt,s?s.offlineProvider:null,tt,ut.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof j=="string"||j instanceof ArrayBuffer||ArrayBuffer.isView(j)||j instanceof Blob?a._FileToolsLoadImage(j,At,Tt,s?s.offlineProvider:null,tt,ut.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):j&&At(j)}return ut},a.prototype.createTexture=function(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt){var it=this;return c===void 0&&(c=3),d===void 0&&(d=null),_===void 0&&(_=null),b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=null),$===void 0&&($=null),this._createTextureBase(i,e,o,s,c,d,_,this._prepareWebGLTexture.bind(this),function(nt,ot,at,st,ut,ft){var lt=it._gl,ht=at.width===nt&&at.height===ot,pt=j?it._getInternalFormat(j,ut._useSRGBBuffer):st===".jpg"&&!ut._useSRGBBuffer?lt.RGB:ut._useSRGBBuffer?lt.SRGB8_ALPHA8:lt.RGBA,mt=j?it._getInternalFormat(j):st===".jpg"&&!ut._useSRGBBuffer?lt.RGB:lt.RGBA;if(ut._useSRGBBuffer&&it.webGLVersion===1&&(mt=pt),ht)return lt.texImage2D(lt.TEXTURE_2D,0,pt,mt,lt.UNSIGNED_BYTE,at),!1;var dt=it._caps.maxTextureSize;if(at.width>dt||at.height>dt||!it._supportsHardwareTextureRescaling)return it._prepareWorkingCanvas(),!it._workingCanvas||!it._workingContext||(it._workingCanvas.width=nt,it._workingCanvas.height=ot,it._workingContext.drawImage(at,0,0,at.width,at.height,0,0,nt,ot),lt.texImage2D(lt.TEXTURE_2D,0,pt,mt,lt.UNSIGNED_BYTE,it._workingCanvas),ut.width=nt,ut.height=ot),!1;var gt=new InternalTexture(it,InternalTextureSource.Temp);return it._bindTextureDirectly(lt.TEXTURE_2D,gt,!0),lt.texImage2D(lt.TEXTURE_2D,0,pt,mt,lt.UNSIGNED_BYTE,at),it._rescaleTexture(gt,ut,s,pt,function(){it._releaseTexture(gt),it._bindTextureDirectly(lt.TEXTURE_2D,ut,!0),ft()}),!0},b,k,j,$,_e,et,rt)},a._FileToolsLoadImage=function(i,e,o,s,c,d){throw _WarnImport("FileTools")},a.prototype._rescaleTexture=function(i,e,o,s,c){},a.prototype.createRawTexture=function(i,e,o,s,c,d,_,b,k){throw _WarnImport("Engine.RawTexture")},a.prototype.createRawCubeTexture=function(i,e,o,s,c,d,_,b){throw _WarnImport("Engine.RawTexture")},a.prototype.createRawTexture3D=function(i,e,o,s,c,d,_,b,k,j){throw _WarnImport("Engine.RawTexture")},a.prototype.createRawTexture2DArray=function(i,e,o,s,c,d,_,b,k,j){throw _WarnImport("Engine.RawTexture")},a.prototype._unpackFlipY=function(i){this._unpackFlipYCached!==i&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,i?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=i))},a.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)},a.prototype._getTextureTarget=function(i){return i.isCube?this._gl.TEXTURE_CUBE_MAP:i.is3D?this._gl.TEXTURE_3D:i.is2DArray||i.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D},a.prototype.updateTextureSamplingMode=function(i,e,o){o===void 0&&(o=!1);var s=this._getTextureTarget(e),c=this._getSamplingParameters(i,e.generateMipMaps||o);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,c.mag,e),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,c.min),o&&(e.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),e.samplingMode=i},a.prototype.updateTextureDimensions=function(i,e,o,s){},a.prototype.updateTextureWrappingMode=function(i,e,o,s){o===void 0&&(o=null),s===void 0&&(s=null);var c=this._getTextureTarget(i);e!==null&&(this._setTextureParameterInteger(c,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(e),i),i._cachedWrapU=e),o!==null&&(this._setTextureParameterInteger(c,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(o),i),i._cachedWrapV=o),(i.is2DArray||i.is3D)&&s!==null&&(this._setTextureParameterInteger(c,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),i),i._cachedWrapR=s),this._bindTextureDirectly(c,null)},a.prototype._setupDepthStencilTexture=function(i,e,o,s,c,d){d===void 0&&(d=1);var _=e.width||e,b=e.height||e,k=e.layers||0;i.baseWidth=_,i.baseHeight=b,i.width=_,i.height=b,i.is2DArray=k>0,i.depth=k,i.isReady=!0,i.samples=d,i.generateMipMaps=!1,i.samplingMode=s?2:1,i.type=0,i._comparisonFunction=c;var j=this._gl,$=this._getTextureTarget(i),_e=this._getSamplingParameters(i.samplingMode,!1);j.texParameteri($,j.TEXTURE_MAG_FILTER,_e.mag),j.texParameteri($,j.TEXTURE_MIN_FILTER,_e.min),j.texParameteri($,j.TEXTURE_WRAP_S,j.CLAMP_TO_EDGE),j.texParameteri($,j.TEXTURE_WRAP_T,j.CLAMP_TO_EDGE),c===0?(j.texParameteri($,j.TEXTURE_COMPARE_FUNC,515),j.texParameteri($,j.TEXTURE_COMPARE_MODE,j.NONE)):(j.texParameteri($,j.TEXTURE_COMPARE_FUNC,c),j.texParameteri($,j.TEXTURE_COMPARE_MODE,j.COMPARE_REF_TO_TEXTURE))},a.prototype._uploadCompressedDataToTextureDirectly=function(i,e,o,s,c,d,_){d===void 0&&(d=0),_===void 0&&(_=0);var b=this._gl,k=b.TEXTURE_2D;if(i.isCube&&(k=b.TEXTURE_CUBE_MAP_POSITIVE_X+d),i._useSRGBBuffer)switch(e){case 36492:e=b.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:e=b.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?e=b.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:i._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?e=b.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:i._useSRGBBuffer=!1;break;default:i._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(k,_,e,o,s,0,c)},a.prototype._uploadDataToTextureDirectly=function(i,e,o,s,c,d){o===void 0&&(o=0),s===void 0&&(s=0),d===void 0&&(d=!1);var _=this._gl,b=this._getWebGLTextureType(i.type),k=this._getInternalFormat(i.format),j=c===void 0?this._getRGBABufferInternalSizedFormat(i.type,i.format,i._useSRGBBuffer):this._getInternalFormat(c,i._useSRGBBuffer);this._unpackFlipY(i.invertY);var $=_.TEXTURE_2D;i.isCube&&($=_.TEXTURE_CUBE_MAP_POSITIVE_X+o);var _e=Math.round(Math.log(i.width)*Math.LOG2E),et=Math.round(Math.log(i.height)*Math.LOG2E),tt=d?i.width:Math.pow(2,Math.max(_e-s,0)),rt=d?i.height:Math.pow(2,Math.max(et-s,0));_.texImage2D($,s,j,tt,rt,0,k,b,e)},a.prototype.updateTextureData=function(i,e,o,s,c,d,_,b){_===void 0&&(_=0),b===void 0&&(b=0);var k=this._gl,j=this._getWebGLTextureType(i.type),$=this._getInternalFormat(i.format);this._unpackFlipY(i.invertY);var _e=k.TEXTURE_2D;i.isCube&&(_e=k.TEXTURE_CUBE_MAP_POSITIVE_X+_),k.texSubImage2D(_e,b,o,s,c,d,$,j,e)},a.prototype._uploadArrayBufferViewToTexture=function(i,e,o,s){o===void 0&&(o=0),s===void 0&&(s=0);var c=this._gl,d=i.isCube?c.TEXTURE_CUBE_MAP:c.TEXTURE_2D;this._bindTextureDirectly(d,i,!0),this._uploadDataToTextureDirectly(i,e,o,s),this._bindTextureDirectly(d,null,!0)},a.prototype._prepareWebGLTextureContinuation=function(i,e,o,s,c){var d=this._gl;if(!!d){var _=this._getSamplingParameters(c,!o);d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,_.mag),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,_.min),!o&&!s&&d.generateMipmap(d.TEXTURE_2D),this._bindTextureDirectly(d.TEXTURE_2D,null),e&&e._removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear()}},a.prototype._prepareWebGLTexture=function(i,e,o,s,c,d,_,b,k){var j=this;k===void 0&&(k=3);var $=this.getCaps().maxTextureSize,_e=Math.min($,this.needPOTTextures?a.GetExponentOfTwo(s.width,$):s.width),et=Math.min($,this.needPOTTextures?a.GetExponentOfTwo(s.height,$):s.height),tt=this._gl;if(!!tt){if(!i._hardwareTexture){o&&o._removePendingData(i);return}this._bindTextureDirectly(tt.TEXTURE_2D,i,!0),this._unpackFlipY(c===void 0?!0:!!c),i.baseWidth=s.width,i.baseHeight=s.height,i.width=_e,i.height=et,i.isReady=!0,!b(_e,et,s,e,i,function(){j._prepareWebGLTextureContinuation(i,o,d,_,k)})&&this._prepareWebGLTextureContinuation(i,o,d,_,k)}},a.prototype._setupFramebufferDepthAttachments=function(i,e,o,s,c){c===void 0&&(c=1);var d=this._gl;if(i&&e)return this._createRenderBuffer(o,s,c,d.DEPTH_STENCIL,d.DEPTH24_STENCIL8,d.DEPTH_STENCIL_ATTACHMENT);if(e){var _=d.DEPTH_COMPONENT16;return this._webGLVersion>1&&(_=d.DEPTH_COMPONENT32F),this._createRenderBuffer(o,s,c,_,_,d.DEPTH_ATTACHMENT)}return i?this._createRenderBuffer(o,s,c,d.STENCIL_INDEX8,d.STENCIL_INDEX8,d.STENCIL_ATTACHMENT):null},a.prototype._createRenderBuffer=function(i,e,o,s,c,d,_){_===void 0&&(_=!0);var b=this._gl,k=b.createRenderbuffer();return b.bindRenderbuffer(b.RENDERBUFFER,k),o>1&&b.renderbufferStorageMultisample?b.renderbufferStorageMultisample(b.RENDERBUFFER,o,c,i,e):b.renderbufferStorage(b.RENDERBUFFER,s,i,e),b.framebufferRenderbuffer(b.FRAMEBUFFER,d,b.RENDERBUFFER,k),_&&b.bindRenderbuffer(b.RENDERBUFFER,null),k},a.prototype._releaseTexture=function(i){var e;this._deleteTexture((e=i._hardwareTexture)===null||e===void 0?void 0:e.underlyingResource),this.unbindAllTextures();var o=this._internalTexturesCache.indexOf(i);o!==-1&&this._internalTexturesCache.splice(o,1),i._lodTextureHigh&&i._lodTextureHigh.dispose(),i._lodTextureMid&&i._lodTextureMid.dispose(),i._lodTextureLow&&i._lodTextureLow.dispose(),i._irradianceTexture&&i._irradianceTexture.dispose()},a.prototype._releaseRenderTargetWrapper=function(i){var e=this._renderTargetWrapperCache.indexOf(i);e!==-1&&this._renderTargetWrapperCache.splice(e,1)},a.prototype._deleteTexture=function(i){i&&this._gl.deleteTexture(i)},a.prototype._setProgram=function(i){this._currentProgram!==i&&(this._gl.useProgram(i),this._currentProgram=i)},a.prototype.bindSamplers=function(i){var e=i.getPipelineContext();this._setProgram(e.program);for(var o=i.getSamplers(),s=0;s<o.length;s++){var c=i.getUniform(o[s]);c&&(this._boundUniforms[s]=c)}this._currentEffect=null},a.prototype._activateCurrentTexture=function(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)},a.prototype._bindTextureDirectly=function(i,e,o,s){var c,d;o===void 0&&(o=!1),s===void 0&&(s=!1);var _=!1,b=e&&e._associatedChannel>-1;o&&b&&(this._activeChannel=e._associatedChannel);var k=this._boundTexturesCache[this._activeChannel];if(k!==e||s){if(this._activateCurrentTexture(),e&&e.isMultiview)throw console.error(i,e),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(i,(d=(c=e==null?void 0:e._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource)!==null&&d!==void 0?d:null),this._boundTexturesCache[this._activeChannel]=e,e&&(e._associatedChannel=this._activeChannel)}else o&&(_=!0,this._activateCurrentTexture());return b&&!o&&this._bindSamplerUniformToChannel(e._associatedChannel,this._activeChannel),_},a.prototype._bindTexture=function(i,e,o){if(i!==void 0){e&&(e._associatedChannel=i),this._activeChannel=i;var s=e?this._getTextureTarget(e):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,e)}},a.prototype.unbindAllTextures=function(){for(var i=0;i<this._maxSimultaneousTextures;i++)this._activeChannel=i,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))},a.prototype.setTexture=function(i,e,o,s){i!==void 0&&(e&&(this._boundUniforms[i]=e),this._setTexture(i,o))},a.prototype._bindSamplerUniformToChannel=function(i,e){var o=this._boundUniforms[i];!o||o._currentState===e||(this._gl.uniform1i(o,e),o._currentState=e)},a.prototype._getTextureWrapMode=function(i){switch(i){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},a.prototype._setTexture=function(i,e,o,s,c){if(o===void 0&&(o=!1),s===void 0&&(s=!1),!e)return this._boundTexturesCache[i]!=null&&(this._activeChannel=i,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(e.video)this._activeChannel=i,e.update();else if(e.delayLoadState===4)return e.delayLoad(),!1;var d;s?d=e.depthStencilTexture:e.isReady()?d=e.getInternalTexture():e.isCube?d=this.emptyCubeTexture:e.is3D?d=this.emptyTexture3D:e.is2DArray?d=this.emptyTexture2DArray:d=this.emptyTexture,!o&&d&&(d._associatedChannel=i);var _=!0;this._boundTexturesCache[i]===d&&(o||this._bindSamplerUniformToChannel(d._associatedChannel,i),_=!1),this._activeChannel=i;var b=this._getTextureTarget(d);if(_&&this._bindTextureDirectly(b,d,o),d&&!d.isMultiview){if(d.isCube&&d._cachedCoordinatesMode!==e.coordinatesMode){d._cachedCoordinatesMode=e.coordinatesMode;var k=e.coordinatesMode!==3&&e.coordinatesMode!==5?1:0;e.wrapU=k,e.wrapV=k}d._cachedWrapU!==e.wrapU&&(d._cachedWrapU=e.wrapU,this._setTextureParameterInteger(b,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(e.wrapU),d)),d._cachedWrapV!==e.wrapV&&(d._cachedWrapV=e.wrapV,this._setTextureParameterInteger(b,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(e.wrapV),d)),d.is3D&&d._cachedWrapR!==e.wrapR&&(d._cachedWrapR=e.wrapR,this._setTextureParameterInteger(b,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(e.wrapR),d)),this._setAnisotropicLevel(b,d,e.anisotropicFilteringLevel)}return!0},a.prototype.setTextureArray=function(i,e,o,s){if(!(i===void 0||!e)){(!this._textureUnits||this._textureUnits.length!==o.length)&&(this._textureUnits=new Int32Array(o.length));for(var c=0;c<o.length;c++){var d=o[c].getInternalTexture();d?(this._textureUnits[c]=i+c,d._associatedChannel=i+c):this._textureUnits[c]=-1}this._gl.uniform1iv(e,this._textureUnits);for(var _=0;_<o.length;_++)this._setTexture(this._textureUnits[_],o[_],!0)}},a.prototype._setAnisotropicLevel=function(i,e,o){var s=this._caps.textureAnisotropicFilterExtension;e.samplingMode!==11&&e.samplingMode!==3&&e.samplingMode!==2&&(o=1),s&&e._cachedAnisotropicFilteringLevel!==o&&(this._setTextureParameterFloat(i,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(o,this._caps.maxAnisotropy),e),e._cachedAnisotropicFilteringLevel=o)},a.prototype._setTextureParameterFloat=function(i,e,o,s){this._bindTextureDirectly(i,s,!0,!0),this._gl.texParameterf(i,e,o)},a.prototype._setTextureParameterInteger=function(i,e,o,s){s&&this._bindTextureDirectly(i,s,!0,!0),this._gl.texParameteri(i,e,o)},a.prototype.unbindAllAttributes=function(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(var i=0;i<this._caps.maxVertexAttribs;i++)this.disableAttributeByIndex(i);return}for(var i=0,e=this._vertexAttribArraysEnabled.length;i<e;i++)i>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[i]||this.disableAttributeByIndex(i)},a.prototype.releaseEffects=function(){for(var i in this._compiledEffects){var e=this._compiledEffects[i].getPipelineContext();this._deletePipelineContext(e)}this._compiledEffects={}},a.prototype.dispose=function(){var i;this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),(i=this.releaseComputeEffects)===null||i===void 0||i.call(this),this.unbindAllAttributes(),this._boundUniforms=[],IsWindowObjectExist()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,Effect$1.ResetCache();for(var e=0,o=this._activeRequests;e<o.length;e++){var s=o[e];s.abort()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},a.prototype.attachContextLostEvent=function(i){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",i,!1)},a.prototype.attachContextRestoredEvent=function(i){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",i,!1)},a.prototype.getError=function(){return this._gl.getError()},a.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)},a.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)},a.prototype._canRenderToFramebuffer=function(i){for(var e=this._gl;e.getError()!==e.NO_ERROR;);var o=!0,s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s),e.texImage2D(e.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(i),1,1,0,e.RGBA,this._getWebGLTextureType(i),null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);var c=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,c),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);var d=e.checkFramebufferStatus(e.FRAMEBUFFER);if(o=o&&d===e.FRAMEBUFFER_COMPLETE,o=o&&e.getError()===e.NO_ERROR,o&&(e.clear(e.COLOR_BUFFER_BIT),o=o&&e.getError()===e.NO_ERROR),o){e.bindFramebuffer(e.FRAMEBUFFER,null);var _=e.RGBA,b=e.UNSIGNED_BYTE,k=new Uint8Array(4);e.readPixels(0,0,1,1,_,b,k),o=o&&e.getError()===e.NO_ERROR}for(e.deleteTexture(s),e.deleteFramebuffer(c),e.bindFramebuffer(e.FRAMEBUFFER,null);!o&&e.getError()!==e.NO_ERROR;);return o},a.prototype._getWebGLTextureType=function(i){if(this._webGLVersion===1){switch(i){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(i){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE},a.prototype._getInternalFormat=function(i,e){e===void 0&&(e=!1);var o=e?this._gl.SRGB8_ALPHA8:this._gl.RGBA;switch(i){case 0:o=this._gl.ALPHA;break;case 1:o=this._gl.LUMINANCE;break;case 2:o=this._gl.LUMINANCE_ALPHA;break;case 6:o=this._gl.RED;break;case 7:o=this._gl.RG;break;case 4:o=e?this._gl.SRGB:this._gl.RGB;break;case 5:o=e?this._gl.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(i){case 8:o=this._gl.RED_INTEGER;break;case 9:o=this._gl.RG_INTEGER;break;case 10:o=this._gl.RGB_INTEGER;break;case 11:o=this._gl.RGBA_INTEGER;break}return o},a.prototype._getRGBABufferInternalSizedFormat=function(i,e,o){if(o===void 0&&(o=!1),this._webGLVersion===1){if(e!==void 0)switch(e){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return o?this._gl.SRGB:this._gl.RGB}return this._gl.RGBA}switch(i){case 3:switch(e){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(e){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return o?this._gl.SRGB8:this._gl.RGB8;case 5:return o?this._gl.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(e){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;case 11:return this._gl.RGBA16I;default:return this._gl.RGBA16I}case 5:switch(e){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(e){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(e){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(e){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(e){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(e){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return o?this._gl.SRGB8_ALPHA8:this._gl.RGBA8},a.prototype._getRGBAMultiSampleBufferFormat=function(i){return i===1?this._gl.RGBA32F:i===2?this._gl.RGBA16F:this._gl.RGBA8},a.prototype._loadFile=function(i,e,o,s,c,d){var _=this,b=a._FileToolsLoadFile(i,e,o,s,c,d);return this._activeRequests.push(b),b.onCompleteObservable.add(function(k){_._activeRequests.splice(_._activeRequests.indexOf(k),1)}),b},a._FileToolsLoadFile=function(i,e,o,s,c,d){throw _WarnImport("FileTools")},a.prototype.readPixels=function(i,e,o,s,c,d){c===void 0&&(c=!0),d===void 0&&(d=!0);var _=c?4:3,b=c?this._gl.RGBA:this._gl.RGB,k=new Uint8Array(s*o*_);return d&&this.flushFramebuffer(),this._gl.readPixels(i,e,o,s,b,this._gl.UNSIGNED_BYTE,k),Promise.resolve(k)},Object.defineProperty(a,"IsSupportedAsync",{get:function(){return Promise.resolve(this.isSupported())},enumerable:!1,configurable:!0}),Object.defineProperty(a,"IsSupported",{get:function(){return this.isSupported()},enumerable:!1,configurable:!0}),a.isSupported=function(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{var i=this._createCanvas(1,1),e=i.getContext("webgl")||i.getContext("experimental-webgl");this._IsSupported=e!=null&&!!window.WebGLRenderingContext}catch{this._IsSupported=!1}return this._IsSupported},Object.defineProperty(a,"HasMajorPerformanceCaveat",{get:function(){if(this._HasMajorPerformanceCaveat===null)try{var i=this._createCanvas(1,1),e=i.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||i.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!e}catch{this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat},enumerable:!1,configurable:!0}),a.CeilingPOT=function(i){return i--,i|=i>>1,i|=i>>2,i|=i>>4,i|=i>>8,i|=i>>16,i++,i},a.FloorPOT=function(i){return i=i|i>>1,i=i|i>>2,i=i|i>>4,i=i|i>>8,i=i|i>>16,i-(i>>1)},a.NearestPOT=function(i){var e=a.CeilingPOT(i),o=a.FloorPOT(i);return e-i>i-o?o:e},a.GetExponentOfTwo=function(i,e,o){o===void 0&&(o=2);var s;switch(o){case 1:s=a.FloorPOT(i);break;case 2:s=a.NearestPOT(i);break;case 3:default:s=a.CeilingPOT(i);break}return Math.min(s,e)},a.QueueNewFrame=function(i,e){return IsWindowObjectExist()?(e||(e=window),e.requestPostAnimationFrame?e.requestPostAnimationFrame(i):e.requestAnimationFrame?e.requestAnimationFrame(i):e.msRequestAnimationFrame?e.msRequestAnimationFrame(i):e.webkitRequestAnimationFrame?e.webkitRequestAnimationFrame(i):e.mozRequestAnimationFrame?e.mozRequestAnimationFrame(i):e.oRequestAnimationFrame?e.oRequestAnimationFrame(i):window.setTimeout(i,16)):typeof requestAnimationFrame!="undefined"?requestAnimationFrame(i):setTimeout(i,16)},a.prototype.getHostDocument=function(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:document},a.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]}],a._TextureLoaders=[],a.CollisionsEpsilon=.001,a._IsSupported=null,a._HasMajorPerformanceCaveat=null,a}(),PrecisionDate=function(){function a(){}return Object.defineProperty(a,"Now",{get:function(){return DomManagement.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!1,configurable:!0}),a}(),PerformanceMonitor=function(){function a(i){i===void 0&&(i=30),this._enabled=!0,this._rollingFrameTime=new RollingAverage(i)}return a.prototype.sampleFrame=function(i){if(i===void 0&&(i=PrecisionDate.Now),!!this._enabled){if(this._lastFrameTimeMs!=null){var e=i-this._lastFrameTimeMs;this._rollingFrameTime.add(e)}this._lastFrameTimeMs=i}},Object.defineProperty(a.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"instantaneousFPS",{get:function(){var i=this._rollingFrameTime.history(0);return i===0?0:1e3/i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!1,configurable:!0}),a.prototype.enable=function(){this._enabled=!0},a.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(a.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!1,configurable:!0}),a.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},a}(),RollingAverage=function(){function a(i){this._samples=new Array(i),this.reset()}return a.prototype.add=function(i){var e;if(this.isSaturated()){var o=this._samples[this._pos];e=o-this.average,this.average-=e/(this._sampleCount-1),this._m2-=e*(o-this.average)}else this._sampleCount++;e=i-this.average,this.average+=e/this._sampleCount,this._m2+=e*(i-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=i,this._pos++,this._pos%=this._samples.length},a.prototype.history=function(i){if(i>=this._sampleCount||i>=this._samples.length)return 0;var e=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(e-i)]},a.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},a.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},a.prototype._wrapPosition=function(i){var e=this._samples.length;return(i%e+e)%e},a}(),PerfCounter=function(){function a(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(a.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"average",{get:function(){return this._average},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"current",{get:function(){return this._current},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!1,configurable:!0}),a.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},a.prototype.addCount=function(i,e){!a.Enabled||(this._current+=i,e&&this._fetchResult())},a.prototype.beginMonitoring=function(){!a.Enabled||(this._startMonitoringTime=PrecisionDate.Now)},a.prototype.endMonitoring=function(i){if(i===void 0&&(i=!0),!!a.Enabled){i&&this.fetchNewFrame();var e=PrecisionDate.Now;this._current=e-this._startMonitoringTime,i&&this._fetchResult()}},a.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var i=PrecisionDate.Now;i-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=i,this._lastSecAccumulated=0,this._lastSecValueCount=0)},a.Enabled=!0,a}();ThinEngine.prototype.setAlphaConstants=function(a,i,e,o){this._alphaState.setAlphaBlendConstants(a,i,e,o)};ThinEngine.prototype.setAlphaMode=function(a,i){if(i===void 0&&(i=!1),this._alphaMode!==a){switch(a){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break}i||(this.depthCullingState.depthMask=a===0),this._alphaMode=a}};ThinEngine.prototype.getAlphaMode=function(){return this._alphaMode};ThinEngine.prototype.setAlphaEquation=function(a){if(this._alphaEquation!==a){switch(a){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774);break}this._alphaEquation=a}};ThinEngine.prototype.getAlphaEquation=function(){return this._alphaEquation};function allocateAndCopyTypedBuffer(a,i,e,o){switch(e===void 0&&(e=!1),a){case 3:{var s=i instanceof ArrayBuffer?new Int8Array(i):new Int8Array(i);return o&&s.set(new Int8Array(o)),s}case 0:{var c=i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i);return o&&c.set(new Uint8Array(o)),c}case 4:{var d=i instanceof ArrayBuffer?new Int16Array(i):new Int16Array(e?i/2:i);return o&&d.set(new Int16Array(o)),d}case 5:case 8:case 9:case 10:case 2:{var _=i instanceof ArrayBuffer?new Uint16Array(i):new Uint16Array(e?i/2:i);return o&&_.set(new Uint16Array(o)),_}case 6:{var b=i instanceof ArrayBuffer?new Int32Array(i):new Int32Array(e?i/4:i);return o&&b.set(new Int32Array(o)),b}case 7:case 11:case 12:case 13:case 14:case 15:{var k=i instanceof ArrayBuffer?new Uint32Array(i):new Uint32Array(e?i/4:i);return o&&k.set(new Uint32Array(o)),k}case 1:{var j=i instanceof ArrayBuffer?new Float32Array(i):new Float32Array(e?i/4:i);return o&&j.set(new Float32Array(o)),j}}var $=i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i);return o&&$.set(new Uint8Array(o)),$}ThinEngine.prototype._readTexturePixelsSync=function(a,i,e,o,s,c,d,_){var b,k;o===void 0&&(o=-1),s===void 0&&(s=0),c===void 0&&(c=null),d===void 0&&(d=!0),_===void 0&&(_=!1);var j=this._gl;if(!j)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){var $=j.createFramebuffer();if(!$)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=$}j.bindFramebuffer(j.FRAMEBUFFER,this._dummyFramebuffer),o>-1?j.framebufferTexture2D(j.FRAMEBUFFER,j.COLOR_ATTACHMENT0,j.TEXTURE_CUBE_MAP_POSITIVE_X+o,(b=a._hardwareTexture)===null||b===void 0?void 0:b.underlyingResource,s):j.framebufferTexture2D(j.FRAMEBUFFER,j.COLOR_ATTACHMENT0,j.TEXTURE_2D,(k=a._hardwareTexture)===null||k===void 0?void 0:k.underlyingResource,s);var _e=a.type!==void 0?this._getWebGLTextureType(a.type):j.UNSIGNED_BYTE;if(_)c||(c=allocateAndCopyTypedBuffer(a.type,4*i*e));else switch(_e){case j.UNSIGNED_BYTE:c||(c=new Uint8Array(4*i*e)),_e=j.UNSIGNED_BYTE;break;default:c||(c=new Float32Array(4*i*e)),_e=j.FLOAT;break}return d&&this.flushFramebuffer(),j.readPixels(0,0,i,e,j.RGBA,_e,c),j.bindFramebuffer(j.FRAMEBUFFER,this._currentFramebuffer),c};ThinEngine.prototype._readTexturePixels=function(a,i,e,o,s,c,d,_){return o===void 0&&(o=-1),s===void 0&&(s=0),c===void 0&&(c=null),d===void 0&&(d=!0),_===void 0&&(_=!1),Promise.resolve(this._readTexturePixelsSync(a,i,e,o,s,c,d,_))};ThinEngine.prototype.updateDynamicIndexBuffer=function(a,i,e){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(a);var o;i instanceof Uint16Array||i instanceof Uint32Array?o=i:o=a.is32Bits?new Uint32Array(i):new Uint16Array(i),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,o,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};ThinEngine.prototype.updateDynamicVertexBuffer=function(a,i,e,o){this.bindArrayBuffer(a),e===void 0&&(e=0);var s=i.length||i.byteLength;o===void 0||o>=s&&e===0?i instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,e,new Float32Array(i)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,e,i):i instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(i).subarray(e,e+o)):(i instanceof ArrayBuffer?i=new Uint8Array(i,e,o):i=new Uint8Array(i.buffer,i.byteOffset+e,o),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,i)),this._resetVertexBufferBinding()};var Engine=function(a){__extends(i,a);function i(e,o,s,c){c===void 0&&(c=!1);var d=a.call(this,e,o,s,c)||this;if(d.enableOfflineSupport=!1,d.disableManifestCheck=!1,d.scenes=new Array,d._virtualScenes=new Array,d.onNewSceneAddedObservable=new Observable,d.postProcesses=new Array,d.isPointerLock=!1,d.onResizeObservable=new Observable,d.onCanvasBlurObservable=new Observable,d.onCanvasFocusObservable=new Observable,d.onCanvasPointerOutObservable=new Observable,d.onBeginFrameObservable=new Observable,d.customAnimationFrameRequester=null,d.onEndFrameObservable=new Observable,d.onBeforeShaderCompilationObservable=new Observable,d.onAfterShaderCompilationObservable=new Observable,d._deterministicLockstep=!1,d._lockstepMaxSteps=4,d._timeStep=1/60,d._fps=60,d._deltaTime=0,d._drawCalls=new PerfCounter,d.canvasTabIndex=1,d.disablePerformanceMonitorInBackground=!1,d._performanceMonitor=new PerformanceMonitor,d._compatibilityMode=!0,d.currentRenderPassId=0,d._renderPassNames=["main"],i.Instances.push(d),!e)return d;if(d._features.supportRenderPasses=!0,s=d._creationOptions,e.getContext){var _=e;if(d._sharedInit(_,!!s.doNotHandleTouchAction,s.audioEngine),IsWindowObjectExist()){var b=document;d._onFullscreenChange=function(){b.fullscreen!==void 0?d.isFullscreen=b.fullscreen:b.mozFullScreen!==void 0?d.isFullscreen=b.mozFullScreen:b.webkitIsFullScreen!==void 0?d.isFullscreen=b.webkitIsFullScreen:b.msIsFullScreen!==void 0&&(d.isFullscreen=b.msIsFullScreen),d.isFullscreen&&d._pointerLockRequested&&_&&i._RequestPointerlock(_)},document.addEventListener("fullscreenchange",d._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",d._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",d._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",d._onFullscreenChange,!1),d._onPointerLockChange=function(){d.isPointerLock=b.mozPointerLockElement===_||b.webkitPointerLockElement===_||b.msPointerLockElement===_||b.pointerLockElement===_},document.addEventListener("pointerlockchange",d._onPointerLockChange,!1),document.addEventListener("mspointerlockchange",d._onPointerLockChange,!1),document.addEventListener("mozpointerlockchange",d._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",d._onPointerLockChange,!1),!i.audioEngine&&s.audioEngine&&i.AudioEngineFactory&&(i.audioEngine=i.AudioEngineFactory(d.getRenderingCanvas(),d.getAudioContext(),d.getAudioDestination()))}d._connectVREvents(),d.enableOfflineSupport=i.OfflineProviderFactory!==void 0,d._deterministicLockstep=!!s.deterministicLockstep,d._lockstepMaxSteps=s.lockstepMaxSteps||0,d._timeStep=s.timeStep||1/60}return d._prepareVRComponent(),s.autoEnableWebVR&&d.initWebVR(),d}return Object.defineProperty(i,"NpmPackage",{get:function(){return ThinEngine.NpmPackage},enumerable:!1,configurable:!0}),Object.defineProperty(i,"Version",{get:function(){return ThinEngine.Version},enumerable:!1,configurable:!0}),Object.defineProperty(i,"Instances",{get:function(){return EngineStore.Instances},enumerable:!1,configurable:!0}),Object.defineProperty(i,"LastCreatedEngine",{get:function(){return EngineStore.LastCreatedEngine},enumerable:!1,configurable:!0}),Object.defineProperty(i,"LastCreatedScene",{get:function(){return EngineStore.LastCreatedScene},enumerable:!1,configurable:!0}),i.prototype.createImageBitmap=function(e,o){return createImageBitmap(e,o)},i.prototype.resizeImageBitmap=function(e,o,s){var c=this.createCanvas(o,s),d=c.getContext("2d");if(!d)throw new Error("Unable to get 2d context for resizeImageBitmap");d.drawImage(e,0,0);var _=d.getImageData(0,0,o,s).data;return _},i.MarkAllMaterialsAsDirty=function(e,o){for(var s=0;s<i.Instances.length;s++)for(var c=i.Instances[s],d=0;d<c.scenes.length;d++)c.scenes[d].markAllMaterialsAsDirty(e,o)},i.DefaultLoadingScreenFactory=function(e){throw _WarnImport("LoadingScreen")},Object.defineProperty(i.prototype,"_supportsHardwareTextureRescaling",{get:function(){return!!i._RescalePostProcessFactory},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"compatibilityMode",{get:function(){return this._compatibilityMode},set:function(e){this._compatibilityMode=!0},enumerable:!1,configurable:!0}),i.prototype.getInputElement=function(){return this._renderingCanvas},i.prototype._sharedInit=function(e,o,s){var c=this;if(a.prototype._sharedInit.call(this,e,o,s),this._onCanvasFocus=function(){c.onCanvasFocusObservable.notifyObservers(c)},this._onCanvasBlur=function(){c.onCanvasBlurObservable.notifyObservers(c)},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),this._onBlur=function(){c.disablePerformanceMonitorInBackground&&c._performanceMonitor.disable(),c._windowIsBackground=!0},this._onFocus=function(){c.disablePerformanceMonitorInBackground&&c._performanceMonitor.enable(),c._windowIsBackground=!1},this._onCanvasPointerOut=function(_){document.elementFromPoint(_.clientX,_.clientY)!==e&&c.onCanvasPointerOutObservable.notifyObservers(_)},IsWindowObjectExist()){var d=this.getHostWindow();d&&(d.addEventListener("blur",this._onBlur),d.addEventListener("focus",this._onFocus))}e.addEventListener("pointerout",this._onCanvasPointerOut),o||this._disableTouchAction(),!i.audioEngine&&s&&i.AudioEngineFactory&&(i.audioEngine=i.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination()))},i.prototype.getAspectRatio=function(e,o){o===void 0&&(o=!1);var s=e.viewport;return this.getRenderWidth(o)*s.width/(this.getRenderHeight(o)*s.height)},i.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},i.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},i.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},i.prototype.isDeterministicLockStep=function(){return this._deterministicLockstep},i.prototype.getLockstepMaxSteps=function(){return this._lockstepMaxSteps},i.prototype.getTimeStep=function(){return this._timeStep*1e3},i.prototype.generateMipMapsForCubemap=function(e,o){if(o===void 0&&(o=!0),e.generateMipMaps){var s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,e,!0),s.generateMipmap(s.TEXTURE_CUBE_MAP),o&&this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)}},i.prototype.getDepthBuffer=function(){return this._depthCullingState.depthTest},i.prototype.setDepthBuffer=function(e){this._depthCullingState.depthTest=e},i.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},i.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},i.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},i.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},i.prototype.getStencilMask=function(){return this._stencilState.stencilMask},i.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},i.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},i.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},i.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},i.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},i.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},i.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},i.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},i.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},i.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},i.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},i.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},i.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},i.prototype.setDitheringState=function(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)},i.prototype.setRasterizerState=function(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)},i.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},i.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},i.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},i.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},i.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},i.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},i.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},i.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},i.prototype.setDirectViewport=function(e,o,s,c){var d=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,o,s,c),d},i.prototype.scissorClear=function(e,o,s,c,d){this.enableScissor(e,o,s,c),this.clear(d,!0,!0,!0),this.disableScissor()},i.prototype.enableScissor=function(e,o,s,c){var d=this._gl;d.enable(d.SCISSOR_TEST),d.scissor(e,o,s,c)},i.prototype.disableScissor=function(){var e=this._gl;e.disable(e.SCISSOR_TEST)},i.prototype._reportDrawCall=function(e){e===void 0&&(e=1),this._drawCalls.addCount(e,!1)},i.prototype.initWebVR=function(){throw _WarnImport("WebVRCamera")},i.prototype._prepareVRComponent=function(){},i.prototype._connectVREvents=function(e,o){},i.prototype._submitVRFrame=function(){},i.prototype.disableVR=function(){},i.prototype.isVRPresenting=function(){return!1},i.prototype._requestVRFrame=function(){},i.prototype._loadFileAsync=function(e,o,s){var c=this;return new Promise(function(d,_){c._loadFile(e,function(b){d(b)},void 0,o,s,function(b,k){_(k)})})},i.prototype.getVertexShaderSource=function(e){var o=this._gl.getAttachedShaders(e);return o?this._gl.getShaderSource(o[0]):null},i.prototype.getFragmentShaderSource=function(e){var o=this._gl.getAttachedShaders(e);return o?this._gl.getShaderSource(o[1]):null},i.prototype.setDepthStencilTexture=function(e,o,s,c){e!==void 0&&(o&&(this._boundUniforms[e]=o),!s||!s.depthStencilTexture?this._setTexture(e,null,void 0,void 0,c):this._setTexture(e,s,!1,!0,c))},i.prototype.setTextureFromPostProcess=function(e,o,s){var c,d=null;o&&(o._textures.data[o._currentRenderTextureInd]?d=o._textures.data[o._currentRenderTextureInd]:o._forcedOutputTexture&&(d=o._forcedOutputTexture)),this._bindTexture(e,(c=d==null?void 0:d.texture)!==null&&c!==void 0?c:null,s)},i.prototype.setTextureFromPostProcessOutput=function(e,o,s){var c,d;this._bindTexture(e,(d=(c=o==null?void 0:o._outputTexture)===null||c===void 0?void 0:c.texture)!==null&&d!==void 0?d:null,s)},i.prototype._rebuildBuffers=function(){for(var e=0,o=this.scenes;e<o.length;e++){var s=o[e];s.resetCachedMaterial(),s._rebuildGeometries(),s._rebuildTextures()}for(var c=0,d=this._virtualScenes;c<d.length;c++){var s=d[c];s.resetCachedMaterial(),s._rebuildGeometries(),s._rebuildTextures()}a.prototype._rebuildBuffers.call(this)},i.prototype._renderFrame=function(){for(var e=0;e<this._activeRenderLoops.length;e++){var o=this._activeRenderLoops[e];o()}},i.prototype._renderLoop=function(){if(!this._contextWasLost){var e=!0;!this.renderEvenInBackground&&this._windowIsBackground&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1},i.prototype._renderViews=function(){return!1},i.prototype.switchFullscreen=function(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)},i.prototype.enterFullscreen=function(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&i._RequestFullscreen(this._renderingCanvas))},i.prototype.exitFullscreen=function(){this.isFullscreen&&i._ExitFullscreen()},i.prototype.enterPointerlock=function(){this._renderingCanvas&&i._RequestPointerlock(this._renderingCanvas)},i.prototype.exitPointerlock=function(){i._ExitPointerlock()},i.prototype.beginFrame=function(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),a.prototype.beginFrame.call(this)},i.prototype.endFrame=function(){a.prototype.endFrame.call(this),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)},i.prototype.resize=function(e){e===void 0&&(e=!1),!this.isVRPresenting()&&a.prototype.resize.call(this,e)},i.prototype.setSize=function(e,o,s){if(s===void 0&&(s=!1),!this._renderingCanvas||!a.prototype.setSize.call(this,e,o,s))return!1;if(this.scenes){for(var c=0;c<this.scenes.length;c++)for(var d=this.scenes[c],_=0;_<d.cameras.length;_++){var b=d.cameras[_];b._currentRenderId=0}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0},i.prototype._deletePipelineContext=function(e){var o=e;o&&o.program&&o.transformFeedback&&(this.deleteTransformFeedback(o.transformFeedback),o.transformFeedback=null),a.prototype._deletePipelineContext.call(this,e)},i.prototype.createShaderProgram=function(e,o,s,c,d,_){_===void 0&&(_=null),d=d||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);var b=a.prototype.createShaderProgram.call(this,e,o,s,c,d,_);return this.onAfterShaderCompilationObservable.notifyObservers(this),b},i.prototype._createShaderProgram=function(e,o,s,c,d){d===void 0&&(d=null);var _=c.createProgram();if(e.program=_,!_)throw new Error("Unable to create program");if(c.attachShader(_,o),c.attachShader(_,s),this.webGLVersion>1&&d){var b=this.createTransformFeedback();this.bindTransformFeedback(b),this.setTranformFeedbackVaryings(_,d),e.transformFeedback=b}return c.linkProgram(_),this.webGLVersion>1&&d&&this.bindTransformFeedback(null),e.context=c,e.vertexShader=o,e.fragmentShader=s,e.isParallelCompiled||this._finalizePipelineContext(e),_},i.prototype._releaseTexture=function(e){a.prototype._releaseTexture.call(this,e)},i.prototype._releaseRenderTargetWrapper=function(e){a.prototype._releaseRenderTargetWrapper.call(this,e),this.scenes.forEach(function(o){o.postProcesses.forEach(function(s){s._outputTexture===e&&(s._outputTexture=null)}),o.cameras.forEach(function(s){s._postProcesses.forEach(function(c){c&&c._outputTexture===e&&(c._outputTexture=null)})})})},i.prototype.getRenderPassNames=function(){return this._renderPassNames},i.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},i.prototype.createRenderPassId=function(e){var o=++i._RenderPassIdCounter;return this._renderPassNames[o]=e!=null?e:"NONAME",o},i.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(var o=0;o<this.scenes.length;++o)for(var s=this.scenes[o],c=0;c<s.meshes.length;++c){var d=s.meshes[c];if(d.subMeshes)for(var _=0;_<d.subMeshes.length;++_){var b=d.subMeshes[_];b._removeDrawWrapper(e)}}},i.prototype._rescaleTexture=function(e,o,s,c,d){var _=this;this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);var b=this.createRenderTargetTexture({width:o.width,height:o.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&i._RescalePostProcessFactory&&(this._rescalePostProcess=i._RescalePostProcessFactory(this)),this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(function(){_._rescalePostProcess.onApply=function(j){j._bindTexture("textureSampler",e)};var k=s;k||(k=_.scenes[_.scenes.length-1]),k.postProcessManager.directRender([_._rescalePostProcess],b,!0),_._bindTextureDirectly(_._gl.TEXTURE_2D,o,!0),_._gl.copyTexImage2D(_._gl.TEXTURE_2D,0,c,0,0,o.width,o.height,0),_.unBindFramebuffer(b),b.dispose(),d&&d()})},i.prototype.getFps=function(){return this._fps},i.prototype.getDeltaTime=function(){return this._deltaTime},i.prototype._measureFps=function(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0},i.prototype._uploadImageToTexture=function(e,o,s,c){s===void 0&&(s=0),c===void 0&&(c=0);var d=this._gl,_=this._getWebGLTextureType(e.type),b=this._getInternalFormat(e.format),k=this._getRGBABufferInternalSizedFormat(e.type,b),j=e.isCube?d.TEXTURE_CUBE_MAP:d.TEXTURE_2D;this._bindTextureDirectly(j,e,!0),this._unpackFlipY(e.invertY);var $=d.TEXTURE_2D;e.isCube&&($=d.TEXTURE_CUBE_MAP_POSITIVE_X+s),d.texImage2D($,c,k,b,_,o),this._bindTextureDirectly(j,null,!0)},i.prototype.updateTextureComparisonFunction=function(e,o){if(this.webGLVersion===1){Logger$2.Error("WebGL 1 does not support texture comparison.");return}var s=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),o===0?(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_FUNC,515),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_MODE,s.NONE)):(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_FUNC,o),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),o===0?(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_FUNC,515),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_MODE,s.NONE)):(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_FUNC,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=o},i.prototype.createInstancesBuffer=function(e){var o=this._gl.createBuffer();if(!o)throw new Error("Unable to create instance buffer");var s=new WebGLDataBuffer(o);return s.capacity=e,this.bindArrayBuffer(s),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),s.references=1,s},i.prototype.deleteInstancesBuffer=function(e){this._gl.deleteBuffer(e)},i.prototype._clientWaitAsync=function(e,o,s){o===void 0&&(o=0),s===void 0&&(s=10);var c=this._gl;return new Promise(function(d,_){var b=function(){var k=c.clientWaitSync(e,o,0);if(k==c.WAIT_FAILED){_();return}if(k==c.TIMEOUT_EXPIRED){setTimeout(b,s);return}d()};b()})},i.prototype._readPixelsAsync=function(e,o,s,c,d,_,b){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");var k=this._gl,j=k.createBuffer();k.bindBuffer(k.PIXEL_PACK_BUFFER,j),k.bufferData(k.PIXEL_PACK_BUFFER,b.byteLength,k.STREAM_READ),k.readPixels(e,o,s,c,d,_,0),k.bindBuffer(k.PIXEL_PACK_BUFFER,null);var $=k.fenceSync(k.SYNC_GPU_COMMANDS_COMPLETE,0);return $?(k.flush(),this._clientWaitAsync($,0,10).then(function(){return k.deleteSync($),k.bindBuffer(k.PIXEL_PACK_BUFFER,j),k.getBufferSubData(k.PIXEL_PACK_BUFFER,0,b),k.bindBuffer(k.PIXEL_PACK_BUFFER,null),k.deleteBuffer(j),b})):null},i.prototype.dispose=function(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();i.Instances.length===1&&i.audioEngine&&(i.audioEngine.dispose(),i.audioEngine=null),this.disableVR(),this.deviceInputSystem&&this.deviceInputSystem.dispose(),IsWindowObjectExist()&&(window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut)),IsDocumentAvailable()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange))),a.prototype.dispose.call(this);var e=i.Instances.indexOf(this);e>=0&&i.Instances.splice(e,1),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()},i.prototype._disableTouchAction=function(){!this._renderingCanvas||!this._renderingCanvas.setAttribute||(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.msTouchAction="none")},i.prototype.displayLoadingUI=function(){if(!!IsWindowObjectExist()){var e=this.loadingScreen;e&&e.displayLoadingUI()}},i.prototype.hideLoadingUI=function(){if(!!IsWindowObjectExist()){var e=this._loadingScreen;e&&e.hideLoadingUI()}},Object.defineProperty(i.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=i.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!1,configurable:!0}),i.prototype.createVideoElement=function(e){return document.createElement("video")},i._RequestPointerlock=function(e){e.requestPointerLock=e.requestPointerLock||e.msRequestPointerLock||e.mozRequestPointerLock||e.webkitRequestPointerLock,e.requestPointerLock&&e.requestPointerLock()},i._ExitPointerlock=function(){var e=document;document.exitPointerLock=document.exitPointerLock||e.msExitPointerLock||e.mozExitPointerLock||e.webkitExitPointerLock,document.exitPointerLock&&document.exitPointerLock()},i._RequestFullscreen=function(e){var o=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;!o||o.call(e)},i._ExitFullscreen=function(){var e=document;document.exitFullscreen?document.exitFullscreen():e.mozCancelFullScreen?e.mozCancelFullScreen():e.webkitCancelFullScreen?e.webkitCancelFullScreen():e.msCancelFullScreen&&e.msCancelFullScreen()},i.prototype.getFontOffset=function(e){var o=document.createElement("span");o.innerHTML="Hg",o.setAttribute("style","font: "+e+" !important");var s=document.createElement("div");s.style.display="inline-block",s.style.width="1px",s.style.height="0px",s.style.verticalAlign="bottom";var c=document.createElement("div");c.style.whiteSpace="nowrap",c.appendChild(o),c.appendChild(s),document.body.appendChild(c);var d=0,_=0;try{_=s.getBoundingClientRect().top-o.getBoundingClientRect().top,s.style.verticalAlign="baseline",d=s.getBoundingClientRect().top-o.getBoundingClientRect().top}finally{document.body.removeChild(c)}return{ascent:d,height:_,descent:_-d}},i.ALPHA_DISABLE=0,i.ALPHA_ADD=1,i.ALPHA_COMBINE=2,i.ALPHA_SUBTRACT=3,i.ALPHA_MULTIPLY=4,i.ALPHA_MAXIMIZED=5,i.ALPHA_ONEONE=6,i.ALPHA_PREMULTIPLIED=7,i.ALPHA_PREMULTIPLIED_PORTERDUFF=8,i.ALPHA_INTERPOLATE=9,i.ALPHA_SCREENMODE=10,i.DELAYLOADSTATE_NONE=0,i.DELAYLOADSTATE_LOADED=1,i.DELAYLOADSTATE_LOADING=2,i.DELAYLOADSTATE_NOTLOADED=4,i.NEVER=512,i.ALWAYS=519,i.LESS=513,i.EQUAL=514,i.LEQUAL=515,i.GREATER=516,i.GEQUAL=518,i.NOTEQUAL=517,i.KEEP=7680,i.REPLACE=7681,i.INCR=7682,i.DECR=7683,i.INVERT=5386,i.INCR_WRAP=34055,i.DECR_WRAP=34056,i.TEXTURE_CLAMP_ADDRESSMODE=0,i.TEXTURE_WRAP_ADDRESSMODE=1,i.TEXTURE_MIRROR_ADDRESSMODE=2,i.TEXTUREFORMAT_ALPHA=0,i.TEXTUREFORMAT_LUMINANCE=1,i.TEXTUREFORMAT_LUMINANCE_ALPHA=2,i.TEXTUREFORMAT_RGB=4,i.TEXTUREFORMAT_RGBA=5,i.TEXTUREFORMAT_RED=6,i.TEXTUREFORMAT_R=6,i.TEXTUREFORMAT_RG=7,i.TEXTUREFORMAT_RED_INTEGER=8,i.TEXTUREFORMAT_R_INTEGER=8,i.TEXTUREFORMAT_RG_INTEGER=9,i.TEXTUREFORMAT_RGB_INTEGER=10,i.TEXTUREFORMAT_RGBA_INTEGER=11,i.TEXTURETYPE_UNSIGNED_BYTE=0,i.TEXTURETYPE_UNSIGNED_INT=0,i.TEXTURETYPE_FLOAT=1,i.TEXTURETYPE_HALF_FLOAT=2,i.TEXTURETYPE_BYTE=3,i.TEXTURETYPE_SHORT=4,i.TEXTURETYPE_UNSIGNED_SHORT=5,i.TEXTURETYPE_INT=6,i.TEXTURETYPE_UNSIGNED_INTEGER=7,i.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,i.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,i.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,i.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,i.TEXTURETYPE_UNSIGNED_INT_24_8=12,i.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,i.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,i.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,i.TEXTURE_NEAREST_SAMPLINGMODE=1,i.TEXTURE_BILINEAR_SAMPLINGMODE=2,i.TEXTURE_TRILINEAR_SAMPLINGMODE=3,i.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,i.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,i.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,i.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,i.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,i.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,i.TEXTURE_NEAREST_LINEAR=7,i.TEXTURE_NEAREST_NEAREST=1,i.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,i.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,i.TEXTURE_LINEAR_LINEAR=2,i.TEXTURE_LINEAR_NEAREST=12,i.TEXTURE_EXPLICIT_MODE=0,i.TEXTURE_SPHERICAL_MODE=1,i.TEXTURE_PLANAR_MODE=2,i.TEXTURE_CUBIC_MODE=3,i.TEXTURE_PROJECTION_MODE=4,i.TEXTURE_SKYBOX_MODE=5,i.TEXTURE_INVCUBIC_MODE=6,i.TEXTURE_EQUIRECTANGULAR_MODE=7,i.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,i.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,i.SCALEMODE_FLOOR=1,i.SCALEMODE_NEAREST=2,i.SCALEMODE_CEILING=3,i._RescalePostProcessFactory=null,i._RenderPassIdCounter=0,i}(ThinEngine),RenderTargetWrapper=function(){function a(i,e,o,s){this._textures=null,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=i,this._isCube=e,this._size=o,this._engine=s,this._depthStencilTexture=null}return Object.defineProperty(a.prototype,"isCube",{get:function(){return this._isCube},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isMulti",{get:function(){return this._isMulti},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"is2DArray",{get:function(){return this.layers>0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"size",{get:function(){return this.width},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"width",{get:function(){return this._size.width||this._size},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"height",{get:function(){return this._size.height||this._size},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"layers",{get:function(){return this._size.layers||0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"texture",{get:function(){var i,e;return(e=(i=this._textures)===null||i===void 0?void 0:i[0])!==null&&e!==void 0?e:null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"textures",{get:function(){return this._textures},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"samples",{get:function(){var i,e;return(e=(i=this.texture)===null||i===void 0?void 0:i.samples)!==null&&e!==void 0?e:1},enumerable:!1,configurable:!0}),a.prototype.setSamples=function(i,e,o){return e===void 0&&(e=!0),o===void 0&&(o=!1),this.samples===i&&!o?i:this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,i,e):this._engine.updateRenderTargetTextureSampleCount(this,i)},a.prototype.setTextures=function(i){Array.isArray(i)?this._textures=i:i?this._textures=[i]:this._textures=null},a.prototype.setTexture=function(i,e,o){e===void 0&&(e=0),o===void 0&&(o=!0),this._textures||(this._textures=[]),this._textures[e]&&o&&this._textures[e].dispose(),this._textures[e]=i},a.prototype.createDepthStencilTexture=function(i,e,o,s,c){var d;return i===void 0&&(i=0),e===void 0&&(e=!0),o===void 0&&(o=!1),s===void 0&&(s=1),c===void 0&&(c=15),(d=this._depthStencilTexture)===null||d===void 0||d.dispose(),this._depthStencilTextureWithStencil=o,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:e,comparisonFunction:i,generateStencil:o,isCube:this._isCube,samples:s,depthTextureFormat:c},this),this._depthStencilTexture},a.prototype._shareDepth=function(i){this._depthStencilTexture&&(i._depthStencilTexture&&i._depthStencilTexture.dispose(),i._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())},a.prototype._swapAndDie=function(i){this.texture&&this.texture._swapAndDie(i),this._textures=null,this.dispose(!0)},a.prototype._cloneRenderTargetWrapper=function(){var i,e,o,s,c,d,_=null;if(this._isMulti){var b=this.textures;if(b&&b.length>0){var k=!1,j=b.length,$=b[b.length-1]._source;($===InternalTextureSource.Depth||$===InternalTextureSource.DepthStencil)&&(k=!0,j--);for(var _e=[],et=[],tt=0;tt<j;++tt){var rt=b[tt];_e.push(rt.samplingMode),et.push(rt.type)}var it={samplingModes:_e,generateMipMaps:b[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:k,types:et,textureCount:j},nt={width:this.width,height:this.height};_=this._engine.createMultipleRenderTarget(nt,it)}}else{var ot={};if(ot.generateDepthBuffer=this._generateDepthBuffer,ot.generateMipMaps=(e=(i=this.texture)===null||i===void 0?void 0:i.generateMipMaps)!==null&&e!==void 0?e:!1,ot.generateStencilBuffer=this._generateStencilBuffer,ot.samplingMode=(o=this.texture)===null||o===void 0?void 0:o.samplingMode,ot.type=(s=this.texture)===null||s===void 0?void 0:s.type,ot.format=(c=this.texture)===null||c===void 0?void 0:c.format,this.isCube)_=this._engine.createRenderTargetCubeTexture(this.width,ot);else{var nt={width:this.width,height:this.height,layers:this.is2DArray?(d=this.texture)===null||d===void 0?void 0:d.depth:void 0};_=this._engine.createRenderTargetTexture(nt,ot)}_.texture.isReady=!0}return _},a.prototype._swapRenderTargetWrapper=function(i){if(this._textures&&i._textures)for(var e=0;e<this._textures.length;++e)this._textures[e]._swapAndDie(i._textures[e],!1),i._textures[e].isReady=!0;this._depthStencilTexture&&i._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(i._depthStencilTexture),i._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null},a.prototype._rebuild=function(){var i=this._cloneRenderTargetWrapper();if(!!i){if(this._depthStencilTexture){var e=this._depthStencilTexture.samplingMode,o=e===2||e===3||e===11;i.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,o,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples)}this.samples>1&&i.setSamples(this.samples),i._swapRenderTargetWrapper(this),i.dispose()}},a.prototype.releaseTextures=function(){var i,e;if(this._textures)for(var o=0;(e=o<((i=this._textures)===null||i===void 0?void 0:i.length))!==null&&e!==void 0&&e;++o)this._textures[o].dispose();this._textures=null},a.prototype.dispose=function(i){var e;i===void 0&&(i=!1),i||((e=this._depthStencilTexture)===null||e===void 0||e.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)},a}(),NullEngineOptions=function(){function a(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}return a}();(function(a){__extends(i,a);function i(e){e===void 0&&(e=new NullEngineOptions);var o=a.call(this,null)||this;Engine.Instances.push(o),e.deterministicLockstep===void 0&&(e.deterministicLockstep=!1),e.lockstepMaxSteps===void 0&&(e.lockstepMaxSteps=4),o._options=e,PerformanceConfigurator.SetMatrixPrecision(!!e.useHighPrecisionMatrix),o._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1},o._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,_collectUbosUpdatedInFrame:!1},Logger$2.Log("Babylon.js v"+Engine.Version+" - Null engine");var s=typeof self!="undefined"?self:typeof global!="undefined"?global:window;return typeof URL=="undefined"&&(s.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob=="undefined"&&(s.Blob=function(){}),o}return i.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},i.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},i.prototype.getHardwareScalingLevel=function(){return 1},i.prototype.createVertexBuffer=function(e){var o=new DataBuffer;return o.references=1,o},i.prototype.createIndexBuffer=function(e){var o=new DataBuffer;return o.references=1,o},i.prototype.clear=function(e,o,s,c){},i.prototype.getRenderWidth=function(e){return e===void 0&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},i.prototype.getRenderHeight=function(e){return e===void 0&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},i.prototype.setViewport=function(e,o,s){this._cachedViewport=e},i.prototype.createShaderProgram=function(e,o,s,c,d){return{__SPECTOR_rebuildProgram:null}},i.prototype.getUniforms=function(e,o){return[]},i.prototype.getAttributes=function(e,o){return[]},i.prototype.bindSamplers=function(e){this._currentEffect=null},i.prototype.enableEffect=function(e){e=e!==null&&DrawWrapper.IsWrapper(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))},i.prototype.setState=function(e,o,s,c,d,_,b){},i.prototype.setIntArray=function(e,o){return!0},i.prototype.setIntArray2=function(e,o){return!0},i.prototype.setIntArray3=function(e,o){return!0},i.prototype.setIntArray4=function(e,o){return!0},i.prototype.setFloatArray=function(e,o){return!0},i.prototype.setFloatArray2=function(e,o){return!0},i.prototype.setFloatArray3=function(e,o){return!0},i.prototype.setFloatArray4=function(e,o){return!0},i.prototype.setArray=function(e,o){return!0},i.prototype.setArray2=function(e,o){return!0},i.prototype.setArray3=function(e,o){return!0},i.prototype.setArray4=function(e,o){return!0},i.prototype.setMatrices=function(e,o){return!0},i.prototype.setMatrix3x3=function(e,o){return!0},i.prototype.setMatrix2x2=function(e,o){return!0},i.prototype.setFloat=function(e,o){return!0},i.prototype.setFloat2=function(e,o,s){return!0},i.prototype.setFloat3=function(e,o,s,c){return!0},i.prototype.setBool=function(e,o){return!0},i.prototype.setFloat4=function(e,o,s,c,d){return!0},i.prototype.setAlphaMode=function(e,o){o===void 0&&(o=!1),this._alphaMode!==e&&(this.alphaState.alphaBlend=e!==0,o||this.setDepthWrite(e===0),this._alphaMode=e)},i.prototype.bindBuffers=function(e,o,s){},i.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},i.prototype.draw=function(e,o,s,c){},i.prototype.drawElementsType=function(e,o,s,c){},i.prototype.drawArraysType=function(e,o,s,c){},i.prototype._createTexture=function(){return{}},i.prototype._releaseTexture=function(e){},i.prototype.createTexture=function(e,o,s,c,d,_,b,k,j,$,_e,et){d===void 0&&(d=3),_===void 0&&(_=null),$===void 0&&($=null);var tt=new InternalTexture(this,InternalTextureSource.Url),rt=String(e);return tt.url=rt,tt.generateMipMaps=!o,tt.samplingMode=d,tt.invertY=s,tt.baseWidth=this._options.textureSize,tt.baseHeight=this._options.textureSize,tt.width=this._options.textureSize,tt.height=this._options.textureSize,$&&(tt.format=$),tt.isReady=!0,_&&_(),this._internalTexturesCache.push(tt),tt},i.prototype._createHardwareRenderTargetWrapper=function(e,o,s){var c=new RenderTargetWrapper(e,o,s,this);return this._renderTargetWrapperCache.push(c),c},i.prototype.createRenderTargetTexture=function(e,o){var s=this._createHardwareRenderTargetWrapper(!1,!1,e),c={};o!==void 0&&typeof o=="object"?(c.generateMipMaps=o.generateMipMaps,c.generateDepthBuffer=o.generateDepthBuffer===void 0?!0:o.generateDepthBuffer,c.generateStencilBuffer=c.generateDepthBuffer&&o.generateStencilBuffer,c.type=o.type===void 0?0:o.type,c.samplingMode=o.samplingMode===void 0?3:o.samplingMode):(c.generateMipMaps=o,c.generateDepthBuffer=!0,c.generateStencilBuffer=!1,c.type=0,c.samplingMode=3);var d=new InternalTexture(this,InternalTextureSource.RenderTarget),_=e.width||e,b=e.height||e;return s._generateDepthBuffer=c.generateDepthBuffer,s._generateStencilBuffer=!!c.generateStencilBuffer,d.baseWidth=_,d.baseHeight=b,d.width=_,d.height=b,d.isReady=!0,d.samples=1,d.generateMipMaps=!!c.generateMipMaps,d.samplingMode=c.samplingMode,d.type=c.type,this._internalTexturesCache.push(d),s},i.prototype.updateTextureSamplingMode=function(e,o){o.samplingMode=e},i.prototype.createRawTexture=function(e,o,s,c,d,_,b,k,j,$){k===void 0&&(k=null),j===void 0&&(j=0);var _e=new InternalTexture(this,InternalTextureSource.Raw);return _e.baseWidth=o,_e.baseHeight=s,_e.width=o,_e.height=s,_e.format=c,_e.generateMipMaps=d,_e.samplingMode=b,_e.invertY=_,_e._compression=k,_e.type=j,this._doNotHandleContextLost||(_e._bufferView=e),_e},i.prototype.updateRawTexture=function(e,o,s,c,d,_){d===void 0&&(d=null),_===void 0&&(_=0),e&&(e._bufferView=o,e.format=s,e.invertY=c,e._compression=d,e.type=_)},i.prototype.bindFramebuffer=function(e,o,s,c,d){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!d&&this.setViewport(this._cachedViewport,s,c)},i.prototype.unBindFramebuffer=function(e,o,s){this._currentRenderTarget=null,s&&s(),this._currentFramebuffer=null},i.prototype.createDynamicVertexBuffer=function(e){var o=new DataBuffer;return o.references=1,o.capacity=1,o},i.prototype.updateDynamicTexture=function(e,o,s,c,d){},i.prototype.areAllEffectsReady=function(){return!0},i.prototype.getError=function(){return 0},i.prototype._getUnpackAlignement=function(){return 1},i.prototype._unpackFlipY=function(e){},i.prototype.updateDynamicIndexBuffer=function(e,o,s){},i.prototype.updateDynamicVertexBuffer=function(e,o,s,c){},i.prototype._bindTextureDirectly=function(e,o){return this._boundTexturesCache[this._activeChannel]!==o?(this._boundTexturesCache[this._activeChannel]=o,!0):!1},i.prototype._bindTexture=function(e,o){e<0||this._bindTextureDirectly(0,o)},i.prototype._deleteBuffer=function(e){},i.prototype.releaseEffects=function(){},i.prototype.displayLoadingUI=function(){},i.prototype.hideLoadingUI=function(){},i.prototype._uploadCompressedDataToTextureDirectly=function(e,o,s,c,d,_,b){},i.prototype._uploadDataToTextureDirectly=function(e,o,s,c){},i.prototype._uploadArrayBufferViewToTexture=function(e,o,s,c){},i.prototype._uploadImageToTexture=function(e,o,s,c){},i})(Engine);ThinEngine.prototype._debugPushGroup=function(a,i){};ThinEngine.prototype._debugPopGroup=function(a){};ThinEngine.prototype._debugInsertMarker=function(a,i){};ThinEngine.prototype._debugFlushPendingCommands=function(){};var cloneValue=function(a,i){return!a||a.getClassName&&a.getClassName()==="Mesh"?null:a.getClassName&&a.getClassName()==="SubMesh"?a.clone(i):a.clone?a.clone():null};function getAllPropertyNames(a){var i=[];do Object.getOwnPropertyNames(a).forEach(function(e){i.indexOf(e)===-1&&i.push(e)});while(a=Object.getPrototypeOf(a));return i}var DeepCopier=function(){function a(){}return a.DeepCopy=function(i,e,o,s){for(var c=getAllPropertyNames(i),d=0,_=c;d<_.length;d++){var b=_[d];if(!(b[0]==="_"&&(!s||s.indexOf(b)===-1))&&!EndsWith(b,"Observable")&&!(o&&o.indexOf(b)!==-1)){var k=i[b],j=typeof k;if(j!=="function")try{if(j==="object")if(k instanceof Array){if(e[b]=[],k.length>0)if(typeof k[0]=="object")for(var $=0;$<k.length;$++){var _e=cloneValue(k[$],e);e[b].indexOf(_e)===-1&&e[b].push(_e)}else e[b]=k.slice(0)}else e[b]=cloneValue(k,e);else e[b]=k}catch(et){Logger$2.Warn(et.message)}}}},a}();function createXMLHttpRequest(){return typeof _native!="undefined"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}var WebRequest=function(){function a(){this._xhr=createXMLHttpRequest()}return a.prototype._injectCustomRequestHeaders=function(){for(var i in a.CustomRequestHeaders){var e=a.CustomRequestHeaders[i];e&&this._xhr.setRequestHeader(i,e)}},Object.defineProperty(a.prototype,"onprogress",{get:function(){return this._xhr.onprogress},set:function(i){this._xhr.onprogress=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"readyState",{get:function(){return this._xhr.readyState},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"status",{get:function(){return this._xhr.status},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"statusText",{get:function(){return this._xhr.statusText},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"response",{get:function(){return this._xhr.response},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"responseURL",{get:function(){return this._xhr.responseURL},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"responseText",{get:function(){return this._xhr.responseText},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"responseType",{get:function(){return this._xhr.responseType},set:function(i){this._xhr.responseType=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"timeout",{get:function(){return this._xhr.timeout},set:function(i){this._xhr.timeout=i},enumerable:!1,configurable:!0}),a.prototype.addEventListener=function(i,e,o){this._xhr.addEventListener(i,e,o)},a.prototype.removeEventListener=function(i,e,o){this._xhr.removeEventListener(i,e,o)},a.prototype.abort=function(){this._xhr.abort()},a.prototype.send=function(i){a.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(i)},a.prototype.open=function(i,e){for(var o=0,s=a.CustomRequestModifiers;o<s.length;o++){var c=s[o];c(this._xhr,e)}return e=e.replace("file:http:","http:"),e=e.replace("file:https:","https:"),this._xhr.open(i,e,!0)},a.prototype.setRequestHeader=function(i,e){this._xhr.setRequestHeader(i,e)},a.prototype.getResponseHeader=function(i){return this._xhr.getResponseHeader(i)},a.CustomRequestHeaders={},a.CustomRequestModifiers=new Array,a}(),FilesInputStore=function(){function a(){}return a.FilesToLoad={},a}(),RetryStrategy=function(){function a(){}return a.ExponentialBackoff=function(i,e){return i===void 0&&(i=3),e===void 0&&(e=500),function(o,s,c){return s.status!==0||c>=i||o.indexOf("file:")!==-1?-1:Math.pow(2,c)*e}},a}(),BaseError=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i._setPrototypeOf=Object.setPrototypeOf||function(e,o){return e.__proto__=o,e},i}(Error),TimingTools=function(){function a(){}return a.SetImmediate=function(i){IsWindowObjectExist()&&window.setImmediate?window.setImmediate(i):setTimeout(i,1)},a}(),FileTools,_injectLTSFileTools=function(a,i,e,o,s,c,d,_,b,k){FileTools={DecodeBase64UrlToBinary:a,DecodeBase64UrlToString:i,DefaultRetryStrategy:e.DefaultRetryStrategy,BaseUrl:e.BaseUrl,CorsBehavior:e.CorsBehavior,PreprocessUrl:e.PreprocessUrl,IsBase64DataUrl:o,IsFileURL:s,LoadFile:c,LoadImage:d,ReadFile:_,RequestFile:b,SetCorsBehavior:k},Object.defineProperty(FileTools,"DefaultRetryStrategy",{get:function(){return e.DefaultRetryStrategy},set:function(j){e.DefaultRetryStrategy=j}}),Object.defineProperty(FileTools,"BaseUrl",{get:function(){return e.BaseUrl},set:function(j){e.BaseUrl=j}}),Object.defineProperty(FileTools,"PreprocessUrl",{get:function(){return e.PreprocessUrl},set:function(j){e.PreprocessUrl=j}}),Object.defineProperty(FileTools,"CorsBehavior",{get:function(){return e.CorsBehavior},set:function(j){e.CorsBehavior=j}})},base64DataUrlRegEx=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i),LoadFileError=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e)||this;return s.name="LoadFileError",BaseError._setPrototypeOf(s,i.prototype),o instanceof WebRequest?s.request=o:s.file=o,s}return i}(BaseError),RequestFileError=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e)||this;return s.request=o,s.name="RequestFileError",BaseError._setPrototypeOf(s,i.prototype),s}return i}(BaseError),ReadFileError=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e)||this;return s.file=o,s.name="ReadFileError",BaseError._setPrototypeOf(s,i.prototype),s}return i}(BaseError),FileToolsOptions={DefaultRetryStrategy:RetryStrategy.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:function(a){return a}},_CleanUrl=function(a){return a=a.replace(/#/mg,"%23"),a},SetCorsBehavior=function(a,i){if(!(a&&a.indexOf("data:")===0)&&FileToolsOptions.CorsBehavior)if(typeof FileToolsOptions.CorsBehavior=="string"||FileToolsOptions.CorsBehavior instanceof String)i.crossOrigin=FileToolsOptions.CorsBehavior;else{var e=FileToolsOptions.CorsBehavior(a);e&&(i.crossOrigin=e)}},LoadImage=function(a,i,e,o,s,c){var d;s===void 0&&(s="");var _,b=!1;a instanceof ArrayBuffer||ArrayBuffer.isView(a)?typeof Blob!="undefined"?(_=URL.createObjectURL(new Blob([a],{type:s})),b=!0):_="data:"+s+";base64,"+EncodeArrayBufferToBase64(a):a instanceof Blob?(_=URL.createObjectURL(a),b=!0):(_=_CleanUrl(a),_=FileToolsOptions.PreprocessUrl(a));var k=EngineStore.LastCreatedEngine,j=function(ot){if(e){var at=_||a.toString();e("Error while trying to load image: "+(at.indexOf("http")===0||at.length<=128?at:at.slice(0,128)+"..."),ot)}};if(typeof Image=="undefined"||((d=k==null?void 0:k._features.forceBitmapOverHTMLImageElement)!==null&&d!==void 0?d:!1))return LoadFile(_,function(ot){k.createImageBitmap(new Blob([ot],{type:s}),__assign({premultiplyAlpha:"none"},c)).then(function(at){i(at),b&&URL.revokeObjectURL(_)}).catch(function(at){e&&e("Error while trying to load image: "+a,at)})},void 0,o||void 0,!0,function(ot,at){j(at)}),null;var $=new Image;SetCorsBehavior(_,$);var _e=function(){$.removeEventListener("load",_e),$.removeEventListener("error",et),i($),b&&$.src&&URL.revokeObjectURL($.src)},et=function(ot){$.removeEventListener("load",_e),$.removeEventListener("error",et),j(ot),b&&$.src&&URL.revokeObjectURL($.src)};$.addEventListener("load",_e),$.addEventListener("error",et);var tt=function(){$.src=_},rt=function(){o&&o.loadImage(_,$)};if(_.substr(0,5)!=="data:"&&o&&o.enableTexturesOffline)o.open(rt,tt);else{if(_.indexOf("file:")!==-1){var it=decodeURIComponent(_.substring(5).toLowerCase());if(FilesInputStore.FilesToLoad[it]){try{var nt;try{nt=URL.createObjectURL(FilesInputStore.FilesToLoad[it])}catch{nt=URL.createObjectURL(FilesInputStore.FilesToLoad[it])}$.src=nt,b=!0}catch{$.src=""}return $}}tt()}return $},ReadFile=function(a,i,e,o,s){var c=new FileReader,d={onCompleteObservable:new Observable,abort:function(){return c.abort()}};return c.onloadend=function(_){return d.onCompleteObservable.notifyObservers(d)},s&&(c.onerror=function(_){s(new ReadFileError("Unable to read "+a.name,a))}),c.onload=function(_){i(_.target.result)},e&&(c.onprogress=e),o?c.readAsArrayBuffer(a):c.readAsText(a),d},LoadFile=function(a,i,e,o,s,c,d){if(a.name)return ReadFile(a,i,e,s,c?function($){c(void 0,$)}:void 0);var _=a;if(_.indexOf("file:")!==-1){var b=decodeURIComponent(_.substring(5).toLowerCase());b.indexOf("./")===0&&(b=b.substring(2));var k=FilesInputStore.FilesToLoad[b];if(k)return ReadFile(k,i,e,s,c?function($){return c(void 0,new LoadFileError($.message,$.file))}:void 0)}if(IsBase64DataUrl(_)){var j={onCompleteObservable:new Observable,abort:function(){return function(){}}};try{i(s?DecodeBase64UrlToBinary(_):DecodeBase64UrlToString(_))}catch($){c?c(void 0,$):Logger$2.Error($.message||"Failed to parse the Data URL")}return TimingTools.SetImmediate(function(){j.onCompleteObservable.notifyObservers(j)}),j}return RequestFile(_,function($,_e){i($,_e?_e.responseURL:void 0)},e,o,s,c?function($){c($.request,new LoadFileError($.message,$.request))}:void 0,d)},RequestFile=function(a,i,e,o,s,c,d){a=_CleanUrl(a),a=FileToolsOptions.PreprocessUrl(a);var _=FileToolsOptions.BaseUrl+a,b=!1,k={onCompleteObservable:new Observable,abort:function(){return b=!0}},j=function(){var et=new WebRequest,tt=null;k.abort=function(){b=!0,et.readyState!==(XMLHttpRequest.DONE||4)&&et.abort(),tt!==null&&(clearTimeout(tt),tt=null)};var rt=function(nt){var ot=nt.message||"Unknown error";c?c(new RequestFileError(ot,et)):Logger$2.Error(ot)},it=function(nt){if(et.open("GET",_),d)try{d(et)}catch(st){rt(st);return}s&&(et.responseType="arraybuffer"),e&&et.addEventListener("progress",e);var ot=function(){et.removeEventListener("loadend",ot),k.onCompleteObservable.notifyObservers(k),k.onCompleteObservable.clear()};et.addEventListener("loadend",ot);var at=function(){if(!b&&et.readyState===(XMLHttpRequest.DONE||4)){if(et.removeEventListener("readystatechange",at),et.status>=200&&et.status<300||et.status===0&&(!IsWindowObjectExist()||IsFileURL())){try{i(s?et.response:et.responseText,et)}catch(lt){rt(lt)}return}var st=FileToolsOptions.DefaultRetryStrategy;if(st){var ut=st(_,et,nt);if(ut!==-1){et.removeEventListener("loadend",ot),et=new WebRequest,tt=setTimeout(function(){return it(nt+1)},ut);return}}var ft=new RequestFileError("Error status: "+et.status+" "+et.statusText+" - Unable to load "+_,et);c&&c(ft)}};et.addEventListener("readystatechange",at),et.send()};it(0)};if(o&&o.enableSceneOffline){var $=function(et){et&&et.status>400?c&&c(et):j()},_e=function(){o&&o.loadFile(FileToolsOptions.BaseUrl+a,function(et){b||i(et),k.onCompleteObservable.notifyObservers(k)},e?function(et){b||e(et)}:void 0,$,s)};o.open(_e,$)}else j();return k},IsFileURL=function(){return typeof location!="undefined"&&location.protocol==="file:"},IsBase64DataUrl=function(a){return base64DataUrlRegEx.test(a)};function DecodeBase64UrlToBinary(a){return DecodeBase64ToBinary(a.split(",")[1])}var DecodeBase64UrlToString=function(a){return DecodeBase64ToString(a.split(",")[1])},initSideEffects$1=function(){ThinEngine._FileToolsLoadImage=LoadImage,ThinEngine._FileToolsLoadFile=LoadFile,ShaderProcessor._FileToolsLoadFile=LoadFile};initSideEffects$1();_injectLTSFileTools(DecodeBase64UrlToBinary,DecodeBase64UrlToString,FileToolsOptions,IsBase64DataUrl,IsFileURL,LoadFile,LoadImage,ReadFile,RequestFile,SetCorsBehavior);var PromiseStates;(function(a){a[a.Pending=0]="Pending",a[a.Fulfilled=1]="Fulfilled",a[a.Rejected=2]="Rejected"})(PromiseStates||(PromiseStates={}));var FulFillmentAgregator=function(){function a(){this.count=0,this.target=0,this.results=[]}return a}(),InternalPromise=function(){function a(i){var e=this;if(this._state=PromiseStates.Pending,this._children=new Array,this._rejectWasConsumed=!1,!!i)try{i(function(o){e._resolve(o)},function(o){e._reject(o)})}catch(o){this._reject(o)}}return Object.defineProperty(a.prototype,"_result",{get:function(){return this._resultValue},set:function(i){this._resultValue=i,this._parent&&this._parent._result===void 0&&(this._parent._result=i)},enumerable:!1,configurable:!0}),a.prototype.catch=function(i){return this.then(void 0,i)},a.prototype.then=function(i,e){var o=this,s=new a;return s._onFulfilled=i,s._onRejected=e,this._children.push(s),s._parent=this,this._state!==PromiseStates.Pending&&setTimeout(function(){o._state===PromiseStates.Fulfilled||o._rejectWasConsumed?s._resolve(o._result):s._reject(o._reason)}),s},a.prototype._moveChildren=function(i){var e,o=this;if((e=this._children).push.apply(e,i.splice(0,i.length)),this._children.forEach(function(k){k._parent=o}),this._state===PromiseStates.Fulfilled)for(var s=0,c=this._children;s<c.length;s++){var d=c[s];d._resolve(this._result)}else if(this._state===PromiseStates.Rejected)for(var _=0,b=this._children;_<b.length;_++){var d=b[_];d._reject(this._reason)}},a.prototype._resolve=function(i){try{this._state=PromiseStates.Fulfilled;var e=null;if(this._onFulfilled&&(e=this._onFulfilled(i)),e!=null)if(e._state!==void 0){var o=e;o._parent=this,o._moveChildren(this._children),i=o._result}else i=e;this._result=i;for(var s=0,c=this._children;s<c.length;s++){var d=c[s];d._resolve(i)}this._children.length=0,delete this._onFulfilled,delete this._onRejected}catch(_){this._reject(_,!0)}},a.prototype._reject=function(i,e){if(e===void 0&&(e=!1),this._state=PromiseStates.Rejected,this._reason=i,this._onRejected&&!e)try{this._onRejected(i),this._rejectWasConsumed=!0}catch(d){i=d}for(var o=0,s=this._children;o<s.length;o++){var c=s[o];this._rejectWasConsumed?c._resolve(null):c._reject(i)}this._children.length=0,delete this._onFulfilled,delete this._onRejected},a.resolve=function(i){var e=new a;return e._resolve(i),e},a._RegisterForFulfillment=function(i,e,o){i.then(function(s){return e.results[o]=s,e.count++,e.count===e.target&&e.rootPromise._resolve(e.results),null},function(s){e.rootPromise._state!==PromiseStates.Rejected&&e.rootPromise._reject(s)})},a.all=function(i){var e=new a,o=new FulFillmentAgregator;if(o.target=i.length,o.rootPromise=e,i.length)for(var s=0;s<i.length;s++)a._RegisterForFulfillment(i[s],o,s);else e._resolve([]);return e},a.race=function(i){var e=new a;if(i.length)for(var o=0,s=i;o<s.length;o++){var c=s[o];c.then(function(d){return e&&(e._resolve(d),e=null),null},function(d){e&&(e._reject(d),e=null)})}return e},a}(),PromisePolyfill=function(){function a(){}return a.Apply=function(i){if(i===void 0&&(i=!1),i||typeof Promise=="undefined"){var e=window;e.Promise=InternalPromise}},a}(),_RegisteredTypes={};function RegisterClass(a,i){_RegisteredTypes[a]=i}function GetClass(a){return _RegisteredTypes[a]}var InstantiationTools=function(){function a(){}return a.Instantiate=function(i){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[i])return this.RegisteredExternalClasses[i];var e=GetClass(i);if(e)return e;Logger$2.Warn(i+" not found, you may have missed an import.");for(var o=i.split("."),s=window||this,c=0,d=o.length;c<d;c++)s=s[o[c]];return typeof s!="function"?null:s},a.RegisteredExternalClasses={},a}();function RandomGUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(a){var i=Math.random()*16|0,e=a==="x"?i:i&3|8;return e.toString(16)})}var SliceTools=function(){function a(){}return a.Slice=function(i,e,o){return i.slice?i.slice(e,o):Array.prototype.slice.call(i,e,o)},a.SliceToArray=function(i,e,o){return Array.isArray(i)?i.slice(e,o):Array.prototype.slice.call(i,e,o)},a}(),Tools=function(){function a(){}return Object.defineProperty(a,"BaseUrl",{get:function(){return FileToolsOptions.BaseUrl},set:function(i){FileToolsOptions.BaseUrl=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"DefaultRetryStrategy",{get:function(){return FileToolsOptions.DefaultRetryStrategy},set:function(i){FileToolsOptions.DefaultRetryStrategy=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"CorsBehavior",{get:function(){return FileToolsOptions.CorsBehavior},set:function(i){FileToolsOptions.CorsBehavior=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"UseFallbackTexture",{get:function(){return EngineStore.UseFallbackTexture},set:function(i){EngineStore.UseFallbackTexture=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"RegisteredExternalClasses",{get:function(){return InstantiationTools.RegisteredExternalClasses},set:function(i){InstantiationTools.RegisteredExternalClasses=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"fallbackTexture",{get:function(){return EngineStore.FallbackTexture},set:function(i){EngineStore.FallbackTexture=i},enumerable:!1,configurable:!0}),a.FetchToRef=function(i,e,o,s,c,d){var _=Math.abs(i)*o%o|0,b=Math.abs(e)*s%s|0,k=(_+b*o)*4;d.r=c[k]/255,d.g=c[k+1]/255,d.b=c[k+2]/255,d.a=c[k+3]/255},a.Mix=function(i,e,o){return i*(1-o)+e*o},a.Instantiate=function(i){return InstantiationTools.Instantiate(i)},a.Slice=function(i,e,o){return SliceTools.Slice(i,e,o)},a.SliceToArray=function(i,e,o){return SliceTools.SliceToArray(i,e,o)},a.SetImmediate=function(i){TimingTools.SetImmediate(i)},a.IsExponentOfTwo=function(i){var e=1;do e*=2;while(e<i);return e===i},a.FloatRound=function(i){return Math.fround?Math.fround(i):(a._tmpFloatArray[0]=i,a._tmpFloatArray[0])},a.GetFilename=function(i){var e=i.lastIndexOf("/");return e<0?i:i.substring(e+1)},a.GetFolderPath=function(i,e){e===void 0&&(e=!1);var o=i.lastIndexOf("/");return o<0?e?i:"":i.substring(0,o+1)},a.ToDegrees=function(i){return i*180/Math.PI},a.ToRadians=function(i){return i*Math.PI/180},a.MakeArray=function(i,e){return e!==!0&&(i===void 0||i==null)?null:Array.isArray(i)?i:[i]},a.GetPointerPrefix=function(i){var e="pointer";return IsWindowObjectExist()&&!window.PointerEvent&&IsNavigatorAvailable()&&!navigator.pointerEnabled&&(e="mouse"),i._badDesktopOS&&!i._badOS&&!(document&&"ontouchend"in document)&&(e="mouse"),e},a.SetCorsBehavior=function(i,e){SetCorsBehavior(i,e)},a.CleanUrl=function(i){return i=i.replace(/#/gm,"%23"),i},Object.defineProperty(a,"PreprocessUrl",{get:function(){return FileToolsOptions.PreprocessUrl},set:function(i){FileToolsOptions.PreprocessUrl=i},enumerable:!1,configurable:!0}),a.LoadImage=function(i,e,o,s,c,d){return LoadImage(i,e,o,s,c,d)},a.LoadFile=function(i,e,o,s,c,d){return LoadFile(i,e,o,s,c,d)},a.LoadFileAsync=function(i,e){return e===void 0&&(e=!0),new Promise(function(o,s){LoadFile(i,function(c){o(c)},void 0,void 0,e,function(c,d){s(d)})})},a.LoadScript=function(i,e,o,s){if(!!IsWindowObjectExist()){var c=document.getElementsByTagName("head")[0],d=document.createElement("script");d.setAttribute("type","text/javascript"),d.setAttribute("src",i),s&&(d.id=s),d.onload=function(){e&&e()},d.onerror=function(_){o&&o("Unable to load script '"+i+"'",_)},c.appendChild(d)}},a.LoadScriptAsync=function(i,e){var o=this;return new Promise(function(s,c){o.LoadScript(i,function(){s()},function(d,_){c(_)})})},a.ReadFileAsDataURL=function(i,e,o){var s=new FileReader,c={onCompleteObservable:new Observable,abort:function(){return s.abort()}};return s.onloadend=function(d){c.onCompleteObservable.notifyObservers(c)},s.onload=function(d){e(d.target.result)},s.onprogress=o,s.readAsDataURL(i),c},a.ReadFile=function(i,e,o,s,c){return ReadFile(i,e,o,s,c)},a.FileAsURL=function(i){var e=new Blob([i]),o=window.URL||window.webkitURL,s=o.createObjectURL(e);return s},a.Format=function(i,e){return e===void 0&&(e=2),i.toFixed(e)},a.DeepCopy=function(i,e,o,s){DeepCopier.DeepCopy(i,e,o,s)},a.IsEmpty=function(i){for(var e in i)if(i.hasOwnProperty(e))return!1;return!0},a.RegisterTopRootEvents=function(i,e){for(var o=0;o<e.length;o++){var s=e[o];i.addEventListener(s.name,s.handler,!1);try{window.parent&&window.parent.addEventListener(s.name,s.handler,!1)}catch{}}},a.UnregisterTopRootEvents=function(i,e){for(var o=0;o<e.length;o++){var s=e[o];i.removeEventListener(s.name,s.handler);try{i.parent&&i.parent.removeEventListener(s.name,s.handler)}catch{}}},a.DumpFramebuffer=function(i,e,o,s,c,d){return c===void 0&&(c="image/png"),__awaiter(this,void 0,void 0,function(){var _,b;return __generator(this,function(k){switch(k.label){case 0:return[4,o.readPixels(0,0,i,e)];case 1:return _=k.sent(),b=new Uint8Array(_.buffer),a.DumpData(i,e,b,s,c,d,!0),[2]}})})},a.DumpData=function(i,e,o,s,c,d,_,b,k){c===void 0&&(c="image/png"),_===void 0&&(_=!1),b===void 0&&(b=!1),a._ScreenshotCanvas||(a._ScreenshotCanvas=document.createElement("canvas")),a._ScreenshotCanvas.width=i,a._ScreenshotCanvas.height=e;var j=a._ScreenshotCanvas.getContext("2d");if(j){if(o instanceof Float32Array){for(var $=new Uint8Array(o.length),_e=o.length;_e--;){var et=o[_e];$[_e]=et<0?0:et>1?1:Math.round(et*255)}o=$}var tt=j.createImageData(i,e),rt=tt.data;rt.set(o),j.putImageData(tt,0,0);var it=a._ScreenshotCanvas;if(_){var nt=document.createElement("canvas");nt.width=i,nt.height=e;var ot=nt.getContext("2d");if(!ot)return;ot.translate(0,e),ot.scale(1,-1),ot.drawImage(a._ScreenshotCanvas,0,0),it=nt}b?a.ToBlob(it,function(at){var st=new FileReader;st.onload=function(ut){var ft=ut.target.result;s&&s(ft)},st.readAsArrayBuffer(at)},c,k):a.EncodeScreenshotCanvasData(s,c,d,it,k)}},a.DumpDataAsync=function(i,e,o,s,c,d,_,b){return s===void 0&&(s="image/png"),d===void 0&&(d=!1),_===void 0&&(_=!1),new Promise(function(k){a.DumpData(i,e,o,function(j){return k(j)},s,c,d,_,b)})},a.ToBlob=function(i,e,o,s){o===void 0&&(o="image/png"),i.toBlob||(i.toBlob=function(c,d,_){var b=this;setTimeout(function(){for(var k=atob(b.toDataURL(d,_).split(",")[1]),j=k.length,$=new Uint8Array(j),_e=0;_e<j;_e++)$[_e]=k.charCodeAt(_e);c(new Blob([$]))})}),i.toBlob(function(c){e(c)},o,s)},a.EncodeScreenshotCanvasData=function(i,e,o,s,c){if(e===void 0&&(e="image/png"),i){var d=(s!=null?s:a._ScreenshotCanvas).toDataURL(e,c);i(d)}else this.ToBlob(s!=null?s:a._ScreenshotCanvas,function(_){if("download"in document.createElement("a")){if(!o){var b=new Date,k=(b.getFullYear()+"-"+(b.getMonth()+1)).slice(2)+"-"+b.getDate()+"_"+b.getHours()+"-"+("0"+b.getMinutes()).slice(-2);o="screenshot_"+k+".png"}a.Download(_,o)}else{var j=URL.createObjectURL(_),$=window.open("");if(!$)return;var _e=$.document.createElement("img");_e.onload=function(){URL.revokeObjectURL(j)},_e.src=j,$.document.body.appendChild(_e)}},e,c)},a.Download=function(i,e){if(navigator&&navigator.msSaveBlob){navigator.msSaveBlob(i,e);return}var o=window.URL.createObjectURL(i),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=o,s.download=e,s.addEventListener("click",function(){s.parentElement&&s.parentElement.removeChild(s)}),s.click(),window.URL.revokeObjectURL(o)},a.BackCompatCameraNoPreventDefault=function(i){return typeof i[0]=="boolean"?i[0]:typeof i[1]=="boolean"?i[1]:!1},a.CreateScreenshot=function(i,e,o,s,c){throw _WarnImport("ScreenshotTools")},a.CreateScreenshotAsync=function(i,e,o,s){throw _WarnImport("ScreenshotTools")},a.CreateScreenshotUsingRenderTarget=function(i,e,o,s,c,d,_,b){throw _WarnImport("ScreenshotTools")},a.CreateScreenshotUsingRenderTargetAsync=function(i,e,o,s,c,d,_){throw _WarnImport("ScreenshotTools")},a.RandomId=function(){return RandomGUID()},a.IsBase64=function(i){return IsBase64DataUrl(i)},a.DecodeBase64=function(i){return DecodeBase64UrlToBinary(i)},Object.defineProperty(a,"errorsCount",{get:function(){return Logger$2.errorsCount},enumerable:!1,configurable:!0}),a.Log=function(i){Logger$2.Log(i)},a.Warn=function(i){Logger$2.Warn(i)},a.Error=function(i){Logger$2.Error(i)},Object.defineProperty(a,"LogCache",{get:function(){return Logger$2.LogCache},enumerable:!1,configurable:!0}),a.ClearLogCache=function(){Logger$2.ClearLogCache()},Object.defineProperty(a,"LogLevels",{set:function(i){Logger$2.LogLevels=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"PerformanceLogLevel",{set:function(i){if((i&a.PerformanceUserMarkLogLevel)===a.PerformanceUserMarkLogLevel){a.StartPerformanceCounter=a._StartUserMark,a.EndPerformanceCounter=a._EndUserMark;return}if((i&a.PerformanceConsoleLogLevel)===a.PerformanceConsoleLogLevel){a.StartPerformanceCounter=a._StartPerformanceConsole,a.EndPerformanceCounter=a._EndPerformanceConsole;return}a.StartPerformanceCounter=a._StartPerformanceCounterDisabled,a.EndPerformanceCounter=a._EndPerformanceCounterDisabled},enumerable:!1,configurable:!0}),a._StartPerformanceCounterDisabled=function(i,e){},a._EndPerformanceCounterDisabled=function(i,e){},a._StartUserMark=function(i,e){if(e===void 0&&(e=!0),!a._performance){if(!IsWindowObjectExist())return;a._performance=window.performance}!e||!a._performance.mark||a._performance.mark(i+"-Begin")},a._EndUserMark=function(i,e){e===void 0&&(e=!0),!(!e||!a._performance.mark)&&(a._performance.mark(i+"-End"),a._performance.measure(i,i+"-Begin",i+"-End"))},a._StartPerformanceConsole=function(i,e){e===void 0&&(e=!0),e&&(a._StartUserMark(i,e),console.time&&console.time(i))},a._EndPerformanceConsole=function(i,e){e===void 0&&(e=!0),e&&(a._EndUserMark(i,e),console.timeEnd(i))},Object.defineProperty(a,"Now",{get:function(){return PrecisionDate.Now},enumerable:!1,configurable:!0}),a.GetClassName=function(i,e){e===void 0&&(e=!1);var o=null;if(!e&&i.getClassName)o=i.getClassName();else{if(i instanceof Object){var s=e?i:Object.getPrototypeOf(i);o=s.constructor.__bjsclassName__}o||(o=typeof i)}return o},a.First=function(i,e){for(var o=0,s=i;o<s.length;o++){var c=s[o];if(e(c))return c}return null},a.getFullClassName=function(i,e){e===void 0&&(e=!1);var o=null,s=null;if(!e&&i.getClassName)o=i.getClassName();else{if(i instanceof Object){var c=e?i:Object.getPrototypeOf(i);o=c.constructor.__bjsclassName__,s=c.constructor.__bjsmoduleName__}o||(o=typeof i)}return o?(s!=null?s+".":"")+o:null},a.DelayAsync=function(i){return new Promise(function(e){setTimeout(function(){e()},i)})},a.IsSafari=function(){return IsNavigatorAvailable()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1},a.UseCustomRequestHeaders=!1,a.CustomRequestHeaders=WebRequest.CustomRequestHeaders,a._tmpFloatArray=new Float32Array(1),a.GetDOMTextContent=GetDOMTextContent,a.GetAbsoluteUrl=typeof document=="object"?function(i){var e=document.createElement("a");return e.href=i,e.href}:typeof URL=="function"&&typeof location=="object"?function(i){return new URL(i,location.origin).href}:function(i){throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},a.NoneLogLevel=Logger$2.NoneLogLevel,a.MessageLogLevel=Logger$2.MessageLogLevel,a.WarningLogLevel=Logger$2.WarningLogLevel,a.ErrorLogLevel=Logger$2.ErrorLogLevel,a.AllLogLevel=Logger$2.AllLogLevel,a.IsWindowObjectExist=IsWindowObjectExist,a.PerformanceNoneLogLevel=0,a.PerformanceUserMarkLogLevel=1,a.PerformanceConsoleLogLevel=2,a.StartPerformanceCounter=a._StartPerformanceCounterDisabled,a.EndPerformanceCounter=a._EndPerformanceCounterDisabled,a}(),AsyncLoop=function(){function a(i,e,o,s){s===void 0&&(s=0),this.iterations=i,this.index=s-1,this._done=!1,this._fn=e,this._successCallback=o}return a.prototype.executeNext=function(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())},a.prototype.breakLoop=function(){this._done=!0,this._successCallback()},a.Run=function(i,e,o,s){s===void 0&&(s=0);var c=new a(i,e,o,s);return c.executeNext(),c},a.SyncAsyncForLoop=function(i,e,o,s,c,d){return d===void 0&&(d=0),a.Run(Math.ceil(i/e),function(_){c&&c()?_.breakLoop():setTimeout(function(){for(var b=0;b<e;++b){var k=_.index*e+b;if(k>=i)break;if(o(k),c&&c()){_.breakLoop();break}}_.executeNext()},d)},s)},a}();EngineStore.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";PromisePolyfill.Apply();var Scalar=function(){function a(){}return a.WithinEpsilon=function(i,e,o){return o===void 0&&(o=1401298e-51),Math.abs(i-e)<=o},a.ToHex=function(i){var e=i.toString(16);return i<=15?("0"+e).toUpperCase():e.toUpperCase()},a.Sign=function(i){return i=+i,i===0||isNaN(i)?i:i>0?1:-1},a.Clamp=function(i,e,o){return e===void 0&&(e=0),o===void 0&&(o=1),Math.min(o,Math.max(e,i))},a.Log2=function(i){return Math.log(i)*Math.LOG2E},a.ILog2=function(i){if(Math.log2)return Math.floor(Math.log2(i));if(i<0)return NaN;if(i===0)return-1/0;var e=0;if(i<1){for(;i<1;)e++,i=i*2;e=-e}else if(i>1)for(;i>1;)e++,i=Math.floor(i/2);return e},a.Repeat=function(i,e){return i-Math.floor(i/e)*e},a.Normalize=function(i,e,o){return(i-e)/(o-e)},a.Denormalize=function(i,e,o){return i*(o-e)+e},a.DeltaAngle=function(i,e){var o=a.Repeat(e-i,360);return o>180&&(o-=360),o},a.PingPong=function(i,e){var o=a.Repeat(i,e*2);return e-Math.abs(o-e)},a.SmoothStep=function(i,e,o){var s=a.Clamp(o);return s=-2*s*s*s+3*s*s,e*s+i*(1-s)},a.MoveTowards=function(i,e,o){var s=0;return Math.abs(e-i)<=o?s=e:s=i+a.Sign(e-i)*o,s},a.MoveTowardsAngle=function(i,e,o){var s=a.DeltaAngle(i,e),c=0;return-o<s&&s<o?c=e:(e=i+s,c=a.MoveTowards(i,e,o)),c},a.Lerp=function(i,e,o){return i+(e-i)*o},a.LerpAngle=function(i,e,o){var s=a.Repeat(e-i,360);return s>180&&(s-=360),i+s*a.Clamp(o)},a.InverseLerp=function(i,e,o){var s=0;return i!=e?s=a.Clamp((o-i)/(e-i)):s=0,s},a.Hermite=function(i,e,o,s,c){var d=c*c,_=c*d,b=2*_-3*d+1,k=-2*_+3*d,j=_-2*d+c,$=_-d;return i*b+o*k+e*j+s*$},a.Hermite1stDerivative=function(i,e,o,s,c){var d=c*c;return(d-c)*6*i+(3*d-4*c+1)*e+(-d+c)*6*o+(3*d-2*c)*s},a.RandomRange=function(i,e){return i===e?i:Math.random()*(e-i)+i},a.RangeToPercent=function(i,e,o){return(i-e)/(o-e)},a.PercentToRange=function(i,e,o){return(o-e)*i+e},a.NormalizeRadians=function(i){return i-=a.TwoPi*Math.floor((i+Math.PI)/a.TwoPi),i},a.HCF=function(i,e){var o=i%e;return o===0?e:a.HCF(e,o)},a.TwoPi=Math.PI*2,a}(),ToGammaSpace=1/2.2,ToLinearSpace=2.2,PHI=(1+Math.sqrt(5))/2,Epsilon=.001,ArrayTools=function(){function a(){}return a.BuildArray=function(i,e){for(var o=[],s=0;s<i;++s)o.push(e());return o},a.BuildTuple=function(i,e){return a.BuildArray(i,e)},a}(),Vector2=function(){function a(i,e){i===void 0&&(i=0),e===void 0&&(e=0),this.x=i,this.y=e}return a.prototype.toString=function(){return"{X: "+this.x+" Y: "+this.y+"}"},a.prototype.getClassName=function(){return"Vector2"},a.prototype.getHashCode=function(){var i=this.x|0;return i=i*397^(this.y|0),i},a.prototype.toArray=function(i,e){return e===void 0&&(e=0),i[e]=this.x,i[e+1]=this.y,this},a.prototype.fromArray=function(i,e){return e===void 0&&(e=0),a.FromArrayToRef(i,e,this),this},a.prototype.asArray=function(){var i=new Array;return this.toArray(i,0),i},a.prototype.copyFrom=function(i){return this.x=i.x,this.y=i.y,this},a.prototype.copyFromFloats=function(i,e){return this.x=i,this.y=e,this},a.prototype.set=function(i,e){return this.copyFromFloats(i,e)},a.prototype.add=function(i){return new a(this.x+i.x,this.y+i.y)},a.prototype.addToRef=function(i,e){return e.x=this.x+i.x,e.y=this.y+i.y,this},a.prototype.addInPlace=function(i){return this.x+=i.x,this.y+=i.y,this},a.prototype.addVector3=function(i){return new a(this.x+i.x,this.y+i.y)},a.prototype.subtract=function(i){return new a(this.x-i.x,this.y-i.y)},a.prototype.subtractToRef=function(i,e){return e.x=this.x-i.x,e.y=this.y-i.y,this},a.prototype.subtractInPlace=function(i){return this.x-=i.x,this.y-=i.y,this},a.prototype.multiplyInPlace=function(i){return this.x*=i.x,this.y*=i.y,this},a.prototype.multiply=function(i){return new a(this.x*i.x,this.y*i.y)},a.prototype.multiplyToRef=function(i,e){return e.x=this.x*i.x,e.y=this.y*i.y,this},a.prototype.multiplyByFloats=function(i,e){return new a(this.x*i,this.y*e)},a.prototype.divide=function(i){return new a(this.x/i.x,this.y/i.y)},a.prototype.divideToRef=function(i,e){return e.x=this.x/i.x,e.y=this.y/i.y,this},a.prototype.divideInPlace=function(i){return this.divideToRef(i,this)},a.prototype.negate=function(){return new a(-this.x,-this.y)},a.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this},a.prototype.negateToRef=function(i){return i.copyFromFloats(this.x*-1,this.y*-1)},a.prototype.scaleInPlace=function(i){return this.x*=i,this.y*=i,this},a.prototype.scale=function(i){var e=new a(0,0);return this.scaleToRef(i,e),e},a.prototype.scaleToRef=function(i,e){return e.x=this.x*i,e.y=this.y*i,this},a.prototype.scaleAndAddToRef=function(i,e){return e.x+=this.x*i,e.y+=this.y*i,this},a.prototype.equals=function(i){return i&&this.x===i.x&&this.y===i.y},a.prototype.equalsWithEpsilon=function(i,e){return e===void 0&&(e=Epsilon),i&&Scalar.WithinEpsilon(this.x,i.x,e)&&Scalar.WithinEpsilon(this.y,i.y,e)},a.prototype.floor=function(){return new a(Math.floor(this.x),Math.floor(this.y))},a.prototype.fract=function(){return new a(this.x-Math.floor(this.x),this.y-Math.floor(this.y))},a.prototype.rotateToRef=function(i,e){var o=Math.cos(i),s=Math.sin(i);return e.x=o*this.x-s*this.y,e.y=s*this.x+o*this.y,this},a.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},a.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},a.prototype.normalize=function(){return a.NormalizeToRef(this,this),this},a.prototype.clone=function(){return new a(this.x,this.y)},a.Zero=function(){return new a(0,0)},a.One=function(){return new a(1,1)},a.FromArray=function(i,e){return e===void 0&&(e=0),new a(i[e],i[e+1])},a.FromArrayToRef=function(i,e,o){o.x=i[e],o.y=i[e+1]},a.CatmullRom=function(i,e,o,s,c){var d=c*c,_=c*d,b=.5*(2*e.x+(-i.x+o.x)*c+(2*i.x-5*e.x+4*o.x-s.x)*d+(-i.x+3*e.x-3*o.x+s.x)*_),k=.5*(2*e.y+(-i.y+o.y)*c+(2*i.y-5*e.y+4*o.y-s.y)*d+(-i.y+3*e.y-3*o.y+s.y)*_);return new a(b,k)},a.Clamp=function(i,e,o){var s=i.x;s=s>o.x?o.x:s,s=s<e.x?e.x:s;var c=i.y;return c=c>o.y?o.y:c,c=c<e.y?e.y:c,new a(s,c)},a.Hermite=function(i,e,o,s,c){var d=c*c,_=c*d,b=2*_-3*d+1,k=-2*_+3*d,j=_-2*d+c,$=_-d,_e=i.x*b+o.x*k+e.x*j+s.x*$,et=i.y*b+o.y*k+e.y*j+s.y*$;return new a(_e,et)},a.Hermite1stDerivative=function(i,e,o,s,c){var d=a.Zero();return this.Hermite1stDerivativeToRef(i,e,o,s,c,d),d},a.Hermite1stDerivativeToRef=function(i,e,o,s,c,d){var _=c*c;d.x=(_-c)*6*i.x+(3*_-4*c+1)*e.x+(-_+c)*6*o.x+(3*_-2*c)*s.x,d.y=(_-c)*6*i.y+(3*_-4*c+1)*e.y+(-_+c)*6*o.y+(3*_-2*c)*s.y},a.Lerp=function(i,e,o){var s=i.x+(e.x-i.x)*o,c=i.y+(e.y-i.y)*o;return new a(s,c)},a.Dot=function(i,e){return i.x*e.x+i.y*e.y},a.Normalize=function(i){var e=a.Zero();return this.NormalizeToRef(i,e),e},a.NormalizeToRef=function(i,e){var o=i.length();o!==0&&(e.x=i.x/o,e.y=i.y/o)},a.Minimize=function(i,e){var o=i.x<e.x?i.x:e.x,s=i.y<e.y?i.y:e.y;return new a(o,s)},a.Maximize=function(i,e){var o=i.x>e.x?i.x:e.x,s=i.y>e.y?i.y:e.y;return new a(o,s)},a.Transform=function(i,e){var o=a.Zero();return a.TransformToRef(i,e,o),o},a.TransformToRef=function(i,e,o){var s=e.m,c=i.x*s[0]+i.y*s[4]+s[12],d=i.x*s[1]+i.y*s[5]+s[13];o.x=c,o.y=d},a.PointInTriangle=function(i,e,o,s){var c=.5*(-o.y*s.x+e.y*(-o.x+s.x)+e.x*(o.y-s.y)+o.x*s.y),d=c<0?-1:1,_=(e.y*s.x-e.x*s.y+(s.y-e.y)*i.x+(e.x-s.x)*i.y)*d,b=(e.x*o.y-e.y*o.x+(e.y-o.y)*i.x+(o.x-e.x)*i.y)*d;return _>0&&b>0&&_+b<2*c*d},a.Distance=function(i,e){return Math.sqrt(a.DistanceSquared(i,e))},a.DistanceSquared=function(i,e){var o=i.x-e.x,s=i.y-e.y;return o*o+s*s},a.Center=function(i,e){return a.CenterToRef(i,e,a.Zero())},a.CenterToRef=function(i,e,o){return o.copyFromFloats((i.x+e.x)/2,(i.y+e.y)/2)},a.DistanceOfPointFromSegment=function(i,e,o){var s=a.DistanceSquared(e,o);if(s===0)return a.Distance(i,e);var c=o.subtract(e),d=Math.max(0,Math.min(1,a.Dot(i.subtract(e),c)/s)),_=e.add(c.multiplyByFloats(d,d));return a.Distance(i,_)},a}(),Vector3=function(){function a(i,e,o){i===void 0&&(i=0),e===void 0&&(e=0),o===void 0&&(o=0),this._isDirty=!0,this._x=i,this._y=e,this._z=o}return Object.defineProperty(a.prototype,"x",{get:function(){return this._x},set:function(i){this._x=i,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"y",{get:function(){return this._y},set:function(i){this._y=i,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"z",{get:function(){return this._z},set:function(i){this._z=i,this._isDirty=!0},enumerable:!1,configurable:!0}),a.prototype.toString=function(){return"{X: "+this._x+" Y: "+this._y+" Z: "+this._z+"}"},a.prototype.getClassName=function(){return"Vector3"},a.prototype.getHashCode=function(){var i=this._x|0;return i=i*397^(this._y|0),i=i*397^(this._z|0),i},a.prototype.asArray=function(){var i=[];return this.toArray(i,0),i},a.prototype.toArray=function(i,e){return e===void 0&&(e=0),i[e]=this._x,i[e+1]=this._y,i[e+2]=this._z,this},a.prototype.fromArray=function(i,e){return e===void 0&&(e=0),a.FromArrayToRef(i,e,this),this},a.prototype.toQuaternion=function(){return Quaternion.RotationYawPitchRoll(this._y,this._x,this._z)},a.prototype.addInPlace=function(i){return this.addInPlaceFromFloats(i._x,i._y,i._z)},a.prototype.addInPlaceFromFloats=function(i,e,o){return this.x+=i,this.y+=e,this.z+=o,this},a.prototype.add=function(i){return new a(this._x+i._x,this._y+i._y,this._z+i._z)},a.prototype.addToRef=function(i,e){return e.copyFromFloats(this._x+i._x,this._y+i._y,this._z+i._z)},a.prototype.subtractInPlace=function(i){return this.x-=i._x,this.y-=i._y,this.z-=i._z,this},a.prototype.subtract=function(i){return new a(this._x-i._x,this._y-i._y,this._z-i._z)},a.prototype.subtractToRef=function(i,e){return this.subtractFromFloatsToRef(i._x,i._y,i._z,e)},a.prototype.subtractFromFloats=function(i,e,o){return new a(this._x-i,this._y-e,this._z-o)},a.prototype.subtractFromFloatsToRef=function(i,e,o,s){return s.copyFromFloats(this._x-i,this._y-e,this._z-o)},a.prototype.negate=function(){return new a(-this._x,-this._y,-this._z)},a.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},a.prototype.negateToRef=function(i){return i.copyFromFloats(this._x*-1,this._y*-1,this._z*-1)},a.prototype.scaleInPlace=function(i){return this.x*=i,this.y*=i,this.z*=i,this},a.prototype.scale=function(i){return new a(this._x*i,this._y*i,this._z*i)},a.prototype.scaleToRef=function(i,e){return e.copyFromFloats(this._x*i,this._y*i,this._z*i)},a.prototype.scaleAndAddToRef=function(i,e){return e.addInPlaceFromFloats(this._x*i,this._y*i,this._z*i)},a.prototype.projectOnPlane=function(i,e){var o=a.Zero();return this.projectOnPlaneToRef(i,e,o),o},a.prototype.projectOnPlaneToRef=function(i,e,o){var s=i.normal,c=i.d,d=MathTmp.Vector3[0];this.subtractToRef(e,d),d.normalize();var _=a.Dot(d,s),b=-(a.Dot(e,s)+c)/_,k=d.scaleInPlace(b);e.addToRef(k,o)},a.prototype.equals=function(i){return i&&this._x===i._x&&this._y===i._y&&this._z===i._z},a.prototype.equalsWithEpsilon=function(i,e){return e===void 0&&(e=Epsilon),i&&Scalar.WithinEpsilon(this._x,i._x,e)&&Scalar.WithinEpsilon(this._y,i._y,e)&&Scalar.WithinEpsilon(this._z,i._z,e)},a.prototype.equalsToFloats=function(i,e,o){return this._x===i&&this._y===e&&this._z===o},a.prototype.multiplyInPlace=function(i){return this.x*=i._x,this.y*=i._y,this.z*=i._z,this},a.prototype.multiply=function(i){return this.multiplyByFloats(i._x,i._y,i._z)},a.prototype.multiplyToRef=function(i,e){return e.copyFromFloats(this._x*i._x,this._y*i._y,this._z*i._z)},a.prototype.multiplyByFloats=function(i,e,o){return new a(this._x*i,this._y*e,this._z*o)},a.prototype.divide=function(i){return new a(this._x/i._x,this._y/i._y,this._z/i._z)},a.prototype.divideToRef=function(i,e){return e.copyFromFloats(this._x/i._x,this._y/i._y,this._z/i._z)},a.prototype.divideInPlace=function(i){return this.divideToRef(i,this)},a.prototype.minimizeInPlace=function(i){return this.minimizeInPlaceFromFloats(i._x,i._y,i._z)},a.prototype.maximizeInPlace=function(i){return this.maximizeInPlaceFromFloats(i._x,i._y,i._z)},a.prototype.minimizeInPlaceFromFloats=function(i,e,o){return i<this._x&&(this.x=i),e<this._y&&(this.y=e),o<this._z&&(this.z=o),this},a.prototype.maximizeInPlaceFromFloats=function(i,e,o){return i>this._x&&(this.x=i),e>this._y&&(this.y=e),o>this._z&&(this.z=o),this},a.prototype.isNonUniformWithinEpsilon=function(i){var e=Math.abs(this._x),o=Math.abs(this._y);if(!Scalar.WithinEpsilon(e,o,i))return!0;var s=Math.abs(this._z);return!Scalar.WithinEpsilon(e,s,i)||!Scalar.WithinEpsilon(o,s,i)},Object.defineProperty(a.prototype,"isNonUniform",{get:function(){var i=Math.abs(this._x),e=Math.abs(this._y);if(i!==e)return!0;var o=Math.abs(this._z);return i!==o},enumerable:!1,configurable:!0}),a.prototype.floor=function(){return new a(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))},a.prototype.fract=function(){return new a(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))},a.prototype.length=function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)},a.prototype.lengthSquared=function(){return this._x*this._x+this._y*this._y+this._z*this._z},a.prototype.normalize=function(){return this.normalizeFromLength(this.length())},a.prototype.reorderInPlace=function(i){var e=this;return i=i.toLowerCase(),i==="xyz"?this:(MathTmp.Vector3[0].copyFrom(this),["x","y","z"].forEach(function(o,s){e[o]=MathTmp.Vector3[0][i[s]]}),this)},a.prototype.rotateByQuaternionToRef=function(i,e){return i.toRotationMatrix(MathTmp.Matrix[0]),a.TransformCoordinatesToRef(this,MathTmp.Matrix[0],e),e},a.prototype.rotateByQuaternionAroundPointToRef=function(i,e,o){return this.subtractToRef(e,MathTmp.Vector3[0]),MathTmp.Vector3[0].rotateByQuaternionToRef(i,MathTmp.Vector3[0]),e.addToRef(MathTmp.Vector3[0],o),o},a.prototype.cross=function(i){return a.Cross(this,i)},a.prototype.normalizeFromLength=function(i){return i===0||i===1?this:this.scaleInPlace(1/i)},a.prototype.normalizeToNew=function(){var i=new a(0,0,0);return this.normalizeToRef(i),i},a.prototype.normalizeToRef=function(i){var e=this.length();return e===0||e===1?i.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/e,i)},a.prototype.clone=function(){return new a(this._x,this._y,this._z)},a.prototype.copyFrom=function(i){return this.copyFromFloats(i._x,i._y,i._z)},a.prototype.copyFromFloats=function(i,e,o){return this.x=i,this.y=e,this.z=o,this},a.prototype.set=function(i,e,o){return this.copyFromFloats(i,e,o)},a.prototype.setAll=function(i){return this.x=this.y=this.z=i,this},a.GetClipFactor=function(i,e,o,s){var c=a.Dot(i,o)-s,d=a.Dot(e,o)-s,_=c/(c-d);return _},a.GetAngleBetweenVectors=function(i,e,o){var s=i.normalizeToRef(MathTmp.Vector3[1]),c=e.normalizeToRef(MathTmp.Vector3[2]),d=a.Dot(s,c),_=Math.acos(d),b=MathTmp.Vector3[3];return a.CrossToRef(s,c,b),a.Dot(b,o)>0?isNaN(_)?0:_:isNaN(_)?-Math.PI:-Math.acos(d)},a.GetAngleBetweenVectorsOnPlane=function(i,e,o){MathTmp.Vector3[0].copyFrom(i);var s=MathTmp.Vector3[0];MathTmp.Vector3[1].copyFrom(e);var c=MathTmp.Vector3[1];MathTmp.Vector3[2].copyFrom(o);var d=MathTmp.Vector3[2],_=MathTmp.Vector3[3],b=MathTmp.Vector3[4];s.normalize(),c.normalize(),d.normalize(),a.CrossToRef(d,s,_),a.CrossToRef(_,d,b);var k=Math.atan2(a.Dot(c,_),a.Dot(c,b));return Scalar.NormalizeRadians(k)},a.SlerpToRef=function(i,e,o,s){o=Scalar.Clamp(o,0,1);var c=MathTmp.Vector3[0],d=MathTmp.Vector3[1],_,b;c.copyFrom(i),_=c.length(),c.normalizeFromLength(_),d.copyFrom(e),b=d.length(),d.normalizeFromLength(b);var k=a.Dot(c,d),j,$;if(k<1-Epsilon){var _e=Math.acos(k),et=1/Math.sin(_e);j=Math.sin((1-o)*_e)*et,$=Math.sin(o*_e)*et}else j=1-o,$=o;c.scaleInPlace(j),d.scaleInPlace($),s.copyFrom(c).addInPlace(d),s.scaleInPlace(Scalar.Lerp(_,b,o))},a.SmoothToRef=function(i,e,o,s,c){a.SlerpToRef(i,e,s===0?1:o/s,c)},a.FromArray=function(i,e){return e===void 0&&(e=0),new a(i[e],i[e+1],i[e+2])},a.FromFloatArray=function(i,e){return a.FromArray(i,e)},a.FromArrayToRef=function(i,e,o){o.x=i[e],o.y=i[e+1],o.z=i[e+2]},a.FromFloatArrayToRef=function(i,e,o){return a.FromArrayToRef(i,e,o)},a.FromFloatsToRef=function(i,e,o,s){s.copyFromFloats(i,e,o)},a.Zero=function(){return new a(0,0,0)},a.One=function(){return new a(1,1,1)},a.Up=function(){return new a(0,1,0)},Object.defineProperty(a,"UpReadOnly",{get:function(){return a._UpReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(a,"RightReadOnly",{get:function(){return a._RightReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(a,"LeftHandedForwardReadOnly",{get:function(){return a._LeftHandedForwardReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(a,"RightHandedForwardReadOnly",{get:function(){return a._RightHandedForwardReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ZeroReadOnly",{get:function(){return a._ZeroReadOnly},enumerable:!1,configurable:!0}),a.Down=function(){return new a(0,-1,0)},a.Forward=function(i){return i===void 0&&(i=!1),new a(0,0,i?-1:1)},a.Backward=function(i){return i===void 0&&(i=!1),new a(0,0,i?1:-1)},a.Right=function(){return new a(1,0,0)},a.Left=function(){return new a(-1,0,0)},a.TransformCoordinates=function(i,e){var o=a.Zero();return a.TransformCoordinatesToRef(i,e,o),o},a.TransformCoordinatesToRef=function(i,e,o){a.TransformCoordinatesFromFloatsToRef(i._x,i._y,i._z,e,o)},a.TransformCoordinatesFromFloatsToRef=function(i,e,o,s,c){var d=s.m,_=i*d[0]+e*d[4]+o*d[8]+d[12],b=i*d[1]+e*d[5]+o*d[9]+d[13],k=i*d[2]+e*d[6]+o*d[10]+d[14],j=1/(i*d[3]+e*d[7]+o*d[11]+d[15]);c.x=_*j,c.y=b*j,c.z=k*j},a.TransformNormal=function(i,e){var o=a.Zero();return a.TransformNormalToRef(i,e,o),o},a.TransformNormalToRef=function(i,e,o){this.TransformNormalFromFloatsToRef(i._x,i._y,i._z,e,o)},a.TransformNormalFromFloatsToRef=function(i,e,o,s,c){var d=s.m;c.x=i*d[0]+e*d[4]+o*d[8],c.y=i*d[1]+e*d[5]+o*d[9],c.z=i*d[2]+e*d[6]+o*d[10]},a.CatmullRom=function(i,e,o,s,c){var d=c*c,_=c*d,b=.5*(2*e._x+(-i._x+o._x)*c+(2*i._x-5*e._x+4*o._x-s._x)*d+(-i._x+3*e._x-3*o._x+s._x)*_),k=.5*(2*e._y+(-i._y+o._y)*c+(2*i._y-5*e._y+4*o._y-s._y)*d+(-i._y+3*e._y-3*o._y+s._y)*_),j=.5*(2*e._z+(-i._z+o._z)*c+(2*i._z-5*e._z+4*o._z-s._z)*d+(-i._z+3*e._z-3*o._z+s._z)*_);return new a(b,k,j)},a.Clamp=function(i,e,o){var s=new a;return a.ClampToRef(i,e,o,s),s},a.ClampToRef=function(i,e,o,s){var c=i._x;c=c>o._x?o._x:c,c=c<e._x?e._x:c;var d=i._y;d=d>o._y?o._y:d,d=d<e._y?e._y:d;var _=i._z;_=_>o._z?o._z:_,_=_<e._z?e._z:_,s.copyFromFloats(c,d,_)},a.CheckExtends=function(i,e,o){e.minimizeInPlace(i),o.maximizeInPlace(i)},a.Hermite=function(i,e,o,s,c){var d=c*c,_=c*d,b=2*_-3*d+1,k=-2*_+3*d,j=_-2*d+c,$=_-d,_e=i._x*b+o._x*k+e._x*j+s._x*$,et=i._y*b+o._y*k+e._y*j+s._y*$,tt=i._z*b+o._z*k+e._z*j+s._z*$;return new a(_e,et,tt)},a.Hermite1stDerivative=function(i,e,o,s,c){var d=a.Zero();return this.Hermite1stDerivativeToRef(i,e,o,s,c,d),d},a.Hermite1stDerivativeToRef=function(i,e,o,s,c,d){var _=c*c;d.x=(_-c)*6*i.x+(3*_-4*c+1)*e.x+(-_+c)*6*o.x+(3*_-2*c)*s.x,d.y=(_-c)*6*i.y+(3*_-4*c+1)*e.y+(-_+c)*6*o.y+(3*_-2*c)*s.y,d.z=(_-c)*6*i.z+(3*_-4*c+1)*e.z+(-_+c)*6*o.z+(3*_-2*c)*s.z},a.Lerp=function(i,e,o){var s=new a(0,0,0);return a.LerpToRef(i,e,o,s),s},a.LerpToRef=function(i,e,o,s){s.x=i._x+(e._x-i._x)*o,s.y=i._y+(e._y-i._y)*o,s.z=i._z+(e._z-i._z)*o},a.Dot=function(i,e){return i._x*e._x+i._y*e._y+i._z*e._z},a.Cross=function(i,e){var o=a.Zero();return a.CrossToRef(i,e,o),o},a.CrossToRef=function(i,e,o){var s=i._y*e._z-i._z*e._y,c=i._z*e._x-i._x*e._z,d=i._x*e._y-i._y*e._x;o.copyFromFloats(s,c,d)},a.Normalize=function(i){var e=a.Zero();return a.NormalizeToRef(i,e),e},a.NormalizeToRef=function(i,e){i.normalizeToRef(e)},a.Project=function(i,e,o,s){var c=new a;return a.ProjectToRef(i,e,o,s,c),c},a.ProjectToRef=function(i,e,o,s,c){var d=s.width,_=s.height,b=s.x,k=s.y,j=MathTmp.Matrix[1];Matrix.FromValuesToRef(d/2,0,0,0,0,-_/2,0,0,0,0,.5,0,b+d/2,_/2+k,.5,1,j);var $=MathTmp.Matrix[0];return e.multiplyToRef(o,$),$.multiplyToRef(j,$),a.TransformCoordinatesToRef(i,$,c),c},a._UnprojectFromInvertedMatrixToRef=function(i,e,o){a.TransformCoordinatesToRef(i,e,o);var s=e.m,c=i._x*s[3]+i._y*s[7]+i._z*s[11]+s[15];Scalar.WithinEpsilon(c,1)&&o.scaleInPlace(1/c)},a.UnprojectFromTransform=function(i,e,o,s,c){var d=MathTmp.Matrix[0];s.multiplyToRef(c,d),d.invert(),i.x=i._x/e*2-1,i.y=-(i._y/o*2-1);var _=new a;return a._UnprojectFromInvertedMatrixToRef(i,d,_),_},a.Unproject=function(i,e,o,s,c,d){var _=a.Zero();return a.UnprojectToRef(i,e,o,s,c,d,_),_},a.UnprojectToRef=function(i,e,o,s,c,d,_){a.UnprojectFloatsToRef(i._x,i._y,i._z,e,o,s,c,d,_)},a.UnprojectFloatsToRef=function(i,e,o,s,c,d,_,b,k){var j=MathTmp.Matrix[0];d.multiplyToRef(_,j),j.multiplyToRef(b,j),j.invert();var $=MathTmp.Vector3[0];$.x=i/s*2-1,$.y=-(e/c*2-1),$.z=2*o-1,a._UnprojectFromInvertedMatrixToRef($,j,k)},a.Minimize=function(i,e){var o=i.clone();return o.minimizeInPlace(e),o},a.Maximize=function(i,e){var o=i.clone();return o.maximizeInPlace(e),o},a.Distance=function(i,e){return Math.sqrt(a.DistanceSquared(i,e))},a.DistanceSquared=function(i,e){var o=i._x-e._x,s=i._y-e._y,c=i._z-e._z;return o*o+s*s+c*c},a.ProjectOnTriangleToRef=function(i,e,o,s,c){var d=MathTmp.Vector3[0],_=MathTmp.Vector3[1],b=MathTmp.Vector3[2],k=MathTmp.Vector3[3],j=MathTmp.Vector3[4];o.subtractToRef(e,d),s.subtractToRef(e,_),s.subtractToRef(o,b);var $=d.length(),_e=_.length(),et=b.length();if($<Epsilon||_e<Epsilon||et<Epsilon)return c.copyFrom(e),a.Distance(i,e);i.subtractToRef(e,j),a.CrossToRef(d,_,k);var tt=k.length();if(tt<Epsilon)return c.copyFrom(e),a.Distance(i,e);k.normalizeFromLength(tt);var rt=j.length();if(rt<Epsilon)return c.copyFrom(e),0;j.normalizeFromLength(rt);var it=a.Dot(k,j),nt=MathTmp.Vector3[5],ot=MathTmp.Vector3[6];nt.copyFrom(k).scaleInPlace(-rt*it),ot.copyFrom(i).addInPlace(nt);var at=MathTmp.Vector3[4],st=MathTmp.Vector3[5],ut=MathTmp.Vector3[7],ft=MathTmp.Vector3[8];at.copyFrom(d).scaleInPlace(1/$),ft.copyFrom(_).scaleInPlace(1/_e),at.addInPlace(ft).scaleInPlace(-1),st.copyFrom(d).scaleInPlace(-1/$),ft.copyFrom(b).scaleInPlace(1/et),st.addInPlace(ft).scaleInPlace(-1),ut.copyFrom(b).scaleInPlace(-1/et),ft.copyFrom(_).scaleInPlace(-1/_e),ut.addInPlace(ft).scaleInPlace(-1);var lt=MathTmp.Vector3[9],ht,pt,mt,dt;lt.copyFrom(ot).subtractInPlace(e),a.CrossToRef(at,lt,ft),ht=a.Dot(ft,k),pt=ht,lt.copyFrom(ot).subtractInPlace(o),a.CrossToRef(st,lt,ft),ht=a.Dot(ft,k),mt=ht,lt.copyFrom(ot).subtractInPlace(s),a.CrossToRef(ut,lt,ft),ht=a.Dot(ft,k),dt=ht;var gt=MathTmp.Vector3[10],_t,yt;pt>0&&mt<0?(gt.copyFrom(d),_t=e,yt=o):mt>0&&dt<0?(gt.copyFrom(b),_t=o,yt=s):(gt.copyFrom(_).scaleInPlace(-1),_t=s,yt=e);var Tt=MathTmp.Vector3[9],St=MathTmp.Vector3[4];_t.subtractToRef(ot,ft),yt.subtractToRef(ot,Tt),a.CrossToRef(ft,Tt,St);var At=a.Dot(St,k)<0;if(!At)return c.copyFrom(ot),Math.abs(rt*it);var vt=MathTmp.Vector3[5];a.CrossToRef(gt,St,vt),vt.normalize();var Et=MathTmp.Vector3[9];Et.copyFrom(_t).subtractInPlace(ot);var xt=Et.length();if(xt<Epsilon)return c.copyFrom(_t),a.Distance(i,_t);Et.normalizeFromLength(xt);var bt=a.Dot(vt,Et),Mt=MathTmp.Vector3[7];Mt.copyFrom(ot).addInPlace(vt.scaleInPlace(xt*bt)),ft.copyFrom(Mt).subtractInPlace(_t),rt=gt.length(),gt.normalizeFromLength(rt);var Rt=a.Dot(ft,gt)/Math.max(rt,Epsilon);return Rt=Scalar.Clamp(Rt,0,1),Mt.copyFrom(_t).addInPlace(gt.scaleInPlace(Rt*rt)),c.copyFrom(Mt),a.Distance(i,Mt)},a.Center=function(i,e){return a.CenterToRef(i,e,a.Zero())},a.CenterToRef=function(i,e,o){return o.copyFromFloats((i._x+e._x)/2,(i._y+e._y)/2,(i._z+e._z)/2)},a.RotationFromAxis=function(i,e,o){var s=a.Zero();return a.RotationFromAxisToRef(i,e,o,s),s},a.RotationFromAxisToRef=function(i,e,o,s){var c=MathTmp.Quaternion[0];Quaternion.RotationQuaternionFromAxisToRef(i,e,o,c),c.toEulerAnglesToRef(s)},a._UpReadOnly=a.Up(),a._LeftHandedForwardReadOnly=a.Forward(!1),a._RightHandedForwardReadOnly=a.Forward(!0),a._RightReadOnly=a.Right(),a._ZeroReadOnly=a.Zero(),a}(),Vector4=function(){function a(i,e,o,s){this.x=i,this.y=e,this.z=o,this.w=s}return a.prototype.toString=function(){return"{X: "+this.x+" Y: "+this.y+" Z: "+this.z+" W: "+this.w+"}"},a.prototype.getClassName=function(){return"Vector4"},a.prototype.getHashCode=function(){var i=this.x|0;return i=i*397^(this.y|0),i=i*397^(this.z|0),i=i*397^(this.w|0),i},a.prototype.asArray=function(){var i=new Array;return this.toArray(i,0),i},a.prototype.toArray=function(i,e){return e===void 0&&(e=0),i[e]=this.x,i[e+1]=this.y,i[e+2]=this.z,i[e+3]=this.w,this},a.prototype.fromArray=function(i,e){return e===void 0&&(e=0),a.FromArrayToRef(i,e,this),this},a.prototype.addInPlace=function(i){return this.x+=i.x,this.y+=i.y,this.z+=i.z,this.w+=i.w,this},a.prototype.add=function(i){return new a(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},a.prototype.addToRef=function(i,e){return e.x=this.x+i.x,e.y=this.y+i.y,e.z=this.z+i.z,e.w=this.w+i.w,this},a.prototype.subtractInPlace=function(i){return this.x-=i.x,this.y-=i.y,this.z-=i.z,this.w-=i.w,this},a.prototype.subtract=function(i){return new a(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},a.prototype.subtractToRef=function(i,e){return e.x=this.x-i.x,e.y=this.y-i.y,e.z=this.z-i.z,e.w=this.w-i.w,this},a.prototype.subtractFromFloats=function(i,e,o,s){return new a(this.x-i,this.y-e,this.z-o,this.w-s)},a.prototype.subtractFromFloatsToRef=function(i,e,o,s,c){return c.x=this.x-i,c.y=this.y-e,c.z=this.z-o,c.w=this.w-s,this},a.prototype.negate=function(){return new a(-this.x,-this.y,-this.z,-this.w)},a.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this},a.prototype.negateToRef=function(i){return i.copyFromFloats(this.x*-1,this.y*-1,this.z*-1,this.w*-1)},a.prototype.scaleInPlace=function(i){return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},a.prototype.scale=function(i){return new a(this.x*i,this.y*i,this.z*i,this.w*i)},a.prototype.scaleToRef=function(i,e){return e.x=this.x*i,e.y=this.y*i,e.z=this.z*i,e.w=this.w*i,this},a.prototype.scaleAndAddToRef=function(i,e){return e.x+=this.x*i,e.y+=this.y*i,e.z+=this.z*i,e.w+=this.w*i,this},a.prototype.equals=function(i){return i&&this.x===i.x&&this.y===i.y&&this.z===i.z&&this.w===i.w},a.prototype.equalsWithEpsilon=function(i,e){return e===void 0&&(e=Epsilon),i&&Scalar.WithinEpsilon(this.x,i.x,e)&&Scalar.WithinEpsilon(this.y,i.y,e)&&Scalar.WithinEpsilon(this.z,i.z,e)&&Scalar.WithinEpsilon(this.w,i.w,e)},a.prototype.equalsToFloats=function(i,e,o,s){return this.x===i&&this.y===e&&this.z===o&&this.w===s},a.prototype.multiplyInPlace=function(i){return this.x*=i.x,this.y*=i.y,this.z*=i.z,this.w*=i.w,this},a.prototype.multiply=function(i){return new a(this.x*i.x,this.y*i.y,this.z*i.z,this.w*i.w)},a.prototype.multiplyToRef=function(i,e){return e.x=this.x*i.x,e.y=this.y*i.y,e.z=this.z*i.z,e.w=this.w*i.w,this},a.prototype.multiplyByFloats=function(i,e,o,s){return new a(this.x*i,this.y*e,this.z*o,this.w*s)},a.prototype.divide=function(i){return new a(this.x/i.x,this.y/i.y,this.z/i.z,this.w/i.w)},a.prototype.divideToRef=function(i,e){return e.x=this.x/i.x,e.y=this.y/i.y,e.z=this.z/i.z,e.w=this.w/i.w,this},a.prototype.divideInPlace=function(i){return this.divideToRef(i,this)},a.prototype.minimizeInPlace=function(i){return i.x<this.x&&(this.x=i.x),i.y<this.y&&(this.y=i.y),i.z<this.z&&(this.z=i.z),i.w<this.w&&(this.w=i.w),this},a.prototype.maximizeInPlace=function(i){return i.x>this.x&&(this.x=i.x),i.y>this.y&&(this.y=i.y),i.z>this.z&&(this.z=i.z),i.w>this.w&&(this.w=i.w),this},a.prototype.floor=function(){return new a(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},a.prototype.fract=function(){return new a(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},a.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},a.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},a.prototype.normalize=function(){var i=this.length();return i===0?this:this.scaleInPlace(1/i)},a.prototype.toVector3=function(){return new Vector3(this.x,this.y,this.z)},a.prototype.clone=function(){return new a(this.x,this.y,this.z,this.w)},a.prototype.copyFrom=function(i){return this.x=i.x,this.y=i.y,this.z=i.z,this.w=i.w,this},a.prototype.copyFromFloats=function(i,e,o,s){return this.x=i,this.y=e,this.z=o,this.w=s,this},a.prototype.set=function(i,e,o,s){return this.copyFromFloats(i,e,o,s)},a.prototype.setAll=function(i){return this.x=this.y=this.z=this.w=i,this},a.FromArray=function(i,e){return e||(e=0),new a(i[e],i[e+1],i[e+2],i[e+3])},a.FromArrayToRef=function(i,e,o){o.x=i[e],o.y=i[e+1],o.z=i[e+2],o.w=i[e+3]},a.FromFloatArrayToRef=function(i,e,o){a.FromArrayToRef(i,e,o)},a.FromFloatsToRef=function(i,e,o,s,c){c.x=i,c.y=e,c.z=o,c.w=s},a.Zero=function(){return new a(0,0,0,0)},a.One=function(){return new a(1,1,1,1)},a.Normalize=function(i){var e=a.Zero();return a.NormalizeToRef(i,e),e},a.NormalizeToRef=function(i,e){e.copyFrom(i),e.normalize()},a.Minimize=function(i,e){var o=i.clone();return o.minimizeInPlace(e),o},a.Maximize=function(i,e){var o=i.clone();return o.maximizeInPlace(e),o},a.Distance=function(i,e){return Math.sqrt(a.DistanceSquared(i,e))},a.DistanceSquared=function(i,e){var o=i.x-e.x,s=i.y-e.y,c=i.z-e.z,d=i.w-e.w;return o*o+s*s+c*c+d*d},a.Center=function(i,e){return a.CenterToRef(i,e,a.Zero())},a.CenterToRef=function(i,e,o){return o.copyFromFloats((i.x+e.x)/2,(i.y+e.y)/2,(i.z+e.z)/2,(i.w+e.w)/2)},a.TransformCoordinates=function(i,e){var o=a.Zero();return a.TransformCoordinatesToRef(i,e,o),o},a.TransformCoordinatesToRef=function(i,e,o){a.TransformCoordinatesFromFloatsToRef(i._x,i._y,i._z,e,o)},a.TransformCoordinatesFromFloatsToRef=function(i,e,o,s,c){var d=s.m,_=i*d[0]+e*d[4]+o*d[8]+d[12],b=i*d[1]+e*d[5]+o*d[9]+d[13],k=i*d[2]+e*d[6]+o*d[10]+d[14],j=i*d[3]+e*d[7]+o*d[11]+d[15];c.x=_,c.y=b,c.z=k,c.w=j},a.TransformNormal=function(i,e){var o=a.Zero();return a.TransformNormalToRef(i,e,o),o},a.TransformNormalToRef=function(i,e,o){var s=e.m,c=i.x*s[0]+i.y*s[4]+i.z*s[8],d=i.x*s[1]+i.y*s[5]+i.z*s[9],_=i.x*s[2]+i.y*s[6]+i.z*s[10];o.x=c,o.y=d,o.z=_,o.w=i.w},a.TransformNormalFromFloatsToRef=function(i,e,o,s,c,d){var _=c.m;d.x=i*_[0]+e*_[4]+o*_[8],d.y=i*_[1]+e*_[5]+o*_[9],d.z=i*_[2]+e*_[6]+o*_[10],d.w=s},a.FromVector3=function(i,e){return e===void 0&&(e=0),new a(i._x,i._y,i._z,e)},a}(),Quaternion=function(){function a(i,e,o,s){i===void 0&&(i=0),e===void 0&&(e=0),o===void 0&&(o=0),s===void 0&&(s=1),this._isDirty=!0,this._x=i,this._y=e,this._z=o,this._w=s}return Object.defineProperty(a.prototype,"x",{get:function(){return this._x},set:function(i){this._x=i,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"y",{get:function(){return this._y},set:function(i){this._y=i,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"z",{get:function(){return this._z},set:function(i){this._z=i,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"w",{get:function(){return this._w},set:function(i){this._w=i,this._isDirty=!0},enumerable:!1,configurable:!0}),a.prototype.toString=function(){return"{X: "+this._x+" Y: "+this._y+" Z: "+this._z+" W: "+this._w+"}"},a.prototype.getClassName=function(){return"Quaternion"},a.prototype.getHashCode=function(){var i=this._x|0;return i=i*397^(this._y|0),i=i*397^(this._z|0),i=i*397^(this._w|0),i},a.prototype.asArray=function(){return[this._x,this._y,this._z,this._w]},a.prototype.equals=function(i){return i&&this._x===i._x&&this._y===i._y&&this._z===i._z&&this._w===i._w},a.prototype.equalsWithEpsilon=function(i,e){return e===void 0&&(e=Epsilon),i&&Scalar.WithinEpsilon(this._x,i._x,e)&&Scalar.WithinEpsilon(this._y,i._y,e)&&Scalar.WithinEpsilon(this._z,i._z,e)&&Scalar.WithinEpsilon(this._w,i._w,e)},a.prototype.clone=function(){return new a(this._x,this._y,this._z,this._w)},a.prototype.copyFrom=function(i){return this.x=i._x,this.y=i._y,this.z=i._z,this.w=i._w,this},a.prototype.copyFromFloats=function(i,e,o,s){return this.x=i,this.y=e,this.z=o,this.w=s,this},a.prototype.set=function(i,e,o,s){return this.copyFromFloats(i,e,o,s)},a.prototype.add=function(i){return new a(this._x+i._x,this._y+i._y,this._z+i._z,this._w+i._w)},a.prototype.addInPlace=function(i){return this._x+=i._x,this._y+=i._y,this._z+=i._z,this._w+=i._w,this},a.prototype.subtract=function(i){return new a(this._x-i._x,this._y-i._y,this._z-i._z,this._w-i._w)},a.prototype.scale=function(i){return new a(this._x*i,this._y*i,this._z*i,this._w*i)},a.prototype.scaleToRef=function(i,e){return e.x=this._x*i,e.y=this._y*i,e.z=this._z*i,e.w=this._w*i,this},a.prototype.scaleInPlace=function(i){return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},a.prototype.scaleAndAddToRef=function(i,e){return e.x+=this._x*i,e.y+=this._y*i,e.z+=this._z*i,e.w+=this._w*i,this},a.prototype.multiply=function(i){var e=new a(0,0,0,1);return this.multiplyToRef(i,e),e},a.prototype.multiplyToRef=function(i,e){var o=this._x*i._w+this._y*i._z-this._z*i._y+this._w*i._x,s=-this._x*i._z+this._y*i._w+this._z*i._x+this._w*i._y,c=this._x*i._y-this._y*i._x+this._z*i._w+this._w*i._z,d=-this._x*i._x-this._y*i._y-this._z*i._z+this._w*i._w;return e.copyFromFloats(o,s,c,d),this},a.prototype.multiplyInPlace=function(i){return this.multiplyToRef(i,this),this},a.prototype.conjugateToRef=function(i){return i.copyFromFloats(-this._x,-this._y,-this._z,this._w),this},a.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},a.prototype.conjugate=function(){var i=new a(-this._x,-this._y,-this._z,this._w);return i},a.prototype.length=function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},a.prototype.normalize=function(){var i=this.length();if(i===0)return this;var e=1/i;return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},a.prototype.toEulerAngles=function(){var i=Vector3.Zero();return this.toEulerAnglesToRef(i),i},a.prototype.toEulerAnglesToRef=function(i){var e=this._z,o=this._x,s=this._y,c=this._w,d=c*c,_=e*e,b=o*o,k=s*s,j=s*e-o*c,$=.4999999;return j<-$?(i.y=2*Math.atan2(s,c),i.x=Math.PI/2,i.z=0):j>$?(i.y=2*Math.atan2(s,c),i.x=-Math.PI/2,i.z=0):(i.z=Math.atan2(2*(o*s+e*c),-_-b+k+d),i.x=Math.asin(-2*(e*s-o*c)),i.y=Math.atan2(2*(e*o+s*c),_-b-k+d)),this},a.prototype.toRotationMatrix=function(i){return Matrix.FromQuaternionToRef(this,i),this},a.prototype.fromRotationMatrix=function(i){return a.FromRotationMatrixToRef(i,this),this},a.FromRotationMatrix=function(i){var e=new a;return a.FromRotationMatrixToRef(i,e),e},a.FromRotationMatrixToRef=function(i,e){var o=i.m,s=o[0],c=o[4],d=o[8],_=o[1],b=o[5],k=o[9],j=o[2],$=o[6],_e=o[10],et=s+b+_e,tt;et>0?(tt=.5/Math.sqrt(et+1),e.w=.25/tt,e.x=($-k)*tt,e.y=(d-j)*tt,e.z=(_-c)*tt):s>b&&s>_e?(tt=2*Math.sqrt(1+s-b-_e),e.w=($-k)/tt,e.x=.25*tt,e.y=(c+_)/tt,e.z=(d+j)/tt):b>_e?(tt=2*Math.sqrt(1+b-s-_e),e.w=(d-j)/tt,e.x=(c+_)/tt,e.y=.25*tt,e.z=(k+$)/tt):(tt=2*Math.sqrt(1+_e-s-b),e.w=(_-c)/tt,e.x=(d+j)/tt,e.y=(k+$)/tt,e.z=.25*tt)},a.Dot=function(i,e){return i._x*e._x+i._y*e._y+i._z*e._z+i._w*e._w},a.AreClose=function(i,e){var o=a.Dot(i,e);return o>=0},a.SmoothToRef=function(i,e,o,s,c){var d=s===0?1:o/s;d=Scalar.Clamp(d,0,1),a.SlerpToRef(i,e,d,c)},a.Zero=function(){return new a(0,0,0,0)},a.Inverse=function(i){return new a(-i._x,-i._y,-i._z,i._w)},a.InverseToRef=function(i,e){return e.set(-i._x,-i._y,-i._z,i._w),e},a.Identity=function(){return new a(0,0,0,1)},a.IsIdentity=function(i){return i&&i._x===0&&i._y===0&&i._z===0&&i._w===1},a.RotationAxis=function(i,e){return a.RotationAxisToRef(i,e,new a)},a.RotationAxisToRef=function(i,e,o){var s=Math.sin(e/2);return i.normalize(),o.w=Math.cos(e/2),o.x=i._x*s,o.y=i._y*s,o.z=i._z*s,o},a.FromArray=function(i,e){return e||(e=0),new a(i[e],i[e+1],i[e+2],i[e+3])},a.FromArrayToRef=function(i,e,o){o.x=i[e],o.y=i[e+1],o.z=i[e+2],o.w=i[e+3]},a.FromEulerAngles=function(i,e,o){var s=new a;return a.RotationYawPitchRollToRef(e,i,o,s),s},a.FromEulerAnglesToRef=function(i,e,o,s){return a.RotationYawPitchRollToRef(e,i,o,s),s},a.FromEulerVector=function(i){var e=new a;return a.RotationYawPitchRollToRef(i._y,i._x,i._z,e),e},a.FromEulerVectorToRef=function(i,e){return a.RotationYawPitchRollToRef(i._y,i._x,i._z,e),e},a.FromUnitVectorsToRef=function(i,e,o){var s=Vector3.Dot(i,e)+1;return s<Epsilon?Math.abs(i.x)>Math.abs(i.z)?o.set(-i.y,i.x,0,0):o.set(0,-i.z,i.y,0):(Vector3.CrossToRef(i,e,TmpVectors.Vector3[0]),o.set(TmpVectors.Vector3[0].x,TmpVectors.Vector3[0].y,TmpVectors.Vector3[0].z,s)),o.normalize()},a.RotationYawPitchRoll=function(i,e,o){var s=new a;return a.RotationYawPitchRollToRef(i,e,o,s),s},a.RotationYawPitchRollToRef=function(i,e,o,s){var c=o*.5,d=e*.5,_=i*.5,b=Math.sin(c),k=Math.cos(c),j=Math.sin(d),$=Math.cos(d),_e=Math.sin(_),et=Math.cos(_);s.x=et*j*k+_e*$*b,s.y=_e*$*k-et*j*b,s.z=et*$*b-_e*j*k,s.w=et*$*k+_e*j*b},a.RotationAlphaBetaGamma=function(i,e,o){var s=new a;return a.RotationAlphaBetaGammaToRef(i,e,o,s),s},a.RotationAlphaBetaGammaToRef=function(i,e,o,s){var c=(o+i)*.5,d=(o-i)*.5,_=e*.5;s.x=Math.cos(d)*Math.sin(_),s.y=Math.sin(d)*Math.sin(_),s.z=Math.sin(c)*Math.cos(_),s.w=Math.cos(c)*Math.cos(_)},a.RotationQuaternionFromAxis=function(i,e,o){var s=new a(0,0,0,0);return a.RotationQuaternionFromAxisToRef(i,e,o,s),s},a.RotationQuaternionFromAxisToRef=function(i,e,o,s){var c=MathTmp.Matrix[0];Matrix.FromXYZAxesToRef(i.normalize(),e.normalize(),o.normalize(),c),a.FromRotationMatrixToRef(c,s)},a.FromLookDirectionLH=function(i,e){var o=new a;return a.FromLookDirectionLHToRef(i,e,o),o},a.FromLookDirectionLHToRef=function(i,e,o){var s=MathTmp.Matrix[0];Matrix.LookDirectionLHToRef(i,e,s),a.FromRotationMatrixToRef(s,o)},a.FromLookDirectionRH=function(i,e){var o=new a;return a.FromLookDirectionRHToRef(i,e,o),o},a.FromLookDirectionRHToRef=function(i,e,o){var s=MathTmp.Matrix[0];return Matrix.LookDirectionRHToRef(i,e,s),a.FromRotationMatrixToRef(s,o)},a.Slerp=function(i,e,o){var s=a.Identity();return a.SlerpToRef(i,e,o,s),s},a.SlerpToRef=function(i,e,o,s){var c,d,_=i._x*e._x+i._y*e._y+i._z*e._z+i._w*e._w,b=!1;if(_<0&&(b=!0,_=-_),_>.999999)d=1-o,c=b?-o:o;else{var k=Math.acos(_),j=1/Math.sin(k);d=Math.sin((1-o)*k)*j,c=b?-Math.sin(o*k)*j:Math.sin(o*k)*j}s.x=d*i._x+c*e._x,s.y=d*i._y+c*e._y,s.z=d*i._z+c*e._z,s.w=d*i._w+c*e._w},a.Hermite=function(i,e,o,s,c){var d=c*c,_=c*d,b=2*_-3*d+1,k=-2*_+3*d,j=_-2*d+c,$=_-d,_e=i._x*b+o._x*k+e._x*j+s._x*$,et=i._y*b+o._y*k+e._y*j+s._y*$,tt=i._z*b+o._z*k+e._z*j+s._z*$,rt=i._w*b+o._w*k+e._w*j+s._w*$;return new a(_e,et,tt,rt)},a.Hermite1stDerivative=function(i,e,o,s,c){var d=a.Zero();return this.Hermite1stDerivativeToRef(i,e,o,s,c,d),d},a.Hermite1stDerivativeToRef=function(i,e,o,s,c,d){var _=c*c;d.x=(_-c)*6*i.x+(3*_-4*c+1)*e.x+(-_+c)*6*o.x+(3*_-2*c)*s.x,d.y=(_-c)*6*i.y+(3*_-4*c+1)*e.y+(-_+c)*6*o.y+(3*_-2*c)*s.y,d.z=(_-c)*6*i.z+(3*_-4*c+1)*e.z+(-_+c)*6*o.z+(3*_-2*c)*s.z,d.w=(_-c)*6*i.w+(3*_-4*c+1)*e.w+(-_+c)*6*o.w+(3*_-2*c)*s.w},a}(),Matrix=function(){function a(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,PerformanceConfigurator.MatrixTrackPrecisionChange&&PerformanceConfigurator.MatrixTrackedMatrices.push(this),this._m=new PerformanceConfigurator.MatrixCurrentType(16),this._markAsUpdated()}return Object.defineProperty(a,"Use64Bits",{get:function(){return PerformanceConfigurator.MatrixUse64Bits},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"m",{get:function(){return this._m},enumerable:!1,configurable:!0}),a.prototype._markAsUpdated=function(){this.updateFlag=a._updateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0},a.prototype._updateIdentityStatus=function(i,e,o,s){e===void 0&&(e=!1),o===void 0&&(o=!1),s===void 0&&(s=!0),this._isIdentity=i,this._isIdentity3x2=i||o,this._isIdentityDirty=this._isIdentity?!1:e,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:s},a.prototype.isIdentity=function(){if(this._isIdentityDirty){this._isIdentityDirty=!1;var i=this._m;this._isIdentity=i[0]===1&&i[1]===0&&i[2]===0&&i[3]===0&&i[4]===0&&i[5]===1&&i[6]===0&&i[7]===0&&i[8]===0&&i[9]===0&&i[10]===1&&i[11]===0&&i[12]===0&&i[13]===0&&i[14]===0&&i[15]===1}return this._isIdentity},a.prototype.isIdentityAs3x2=function(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2},a.prototype.determinant=function(){if(this._isIdentity===!0)return 1;var i=this._m,e=i[0],o=i[1],s=i[2],c=i[3],d=i[4],_=i[5],b=i[6],k=i[7],j=i[8],$=i[9],_e=i[10],et=i[11],tt=i[12],rt=i[13],it=i[14],nt=i[15],ot=_e*nt-it*et,at=$*nt-rt*et,st=$*it-rt*_e,ut=j*nt-tt*et,ft=j*it-_e*tt,lt=j*rt-tt*$,ht=+(_*ot-b*at+k*st),pt=-(d*ot-b*ut+k*ft),mt=+(d*at-_*ut+k*lt),dt=-(d*st-_*ft+b*lt);return e*ht+o*pt+s*mt+c*dt},a.prototype.toArray=function(){return this._m},a.prototype.asArray=function(){return this._m},a.prototype.invert=function(){return this.invertToRef(this),this},a.prototype.reset=function(){return a.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this},a.prototype.add=function(i){var e=new a;return this.addToRef(i,e),e},a.prototype.addToRef=function(i,e){for(var o=this._m,s=e._m,c=i.m,d=0;d<16;d++)s[d]=o[d]+c[d];return e._markAsUpdated(),this},a.prototype.addToSelf=function(i){for(var e=this._m,o=i.m,s=0;s<16;s++)e[s]+=o[s];return this._markAsUpdated(),this},a.prototype.invertToRef=function(i){if(this._isIdentity===!0)return a.IdentityToRef(i),this;var e=this._m,o=e[0],s=e[1],c=e[2],d=e[3],_=e[4],b=e[5],k=e[6],j=e[7],$=e[8],_e=e[9],et=e[10],tt=e[11],rt=e[12],it=e[13],nt=e[14],ot=e[15],at=et*ot-nt*tt,st=_e*ot-it*tt,ut=_e*nt-it*et,ft=$*ot-rt*tt,lt=$*nt-et*rt,ht=$*it-rt*_e,pt=+(b*at-k*st+j*ut),mt=-(_*at-k*ft+j*lt),dt=+(_*st-b*ft+j*ht),gt=-(_*ut-b*lt+k*ht),_t=o*pt+s*mt+c*dt+d*gt;if(_t===0)return i.copyFrom(this),this;var yt=1/_t,Tt=k*ot-nt*j,St=b*ot-it*j,At=b*nt-it*k,vt=_*ot-rt*j,Et=_*nt-rt*k,xt=_*it-rt*b,bt=k*tt-et*j,Mt=b*tt-_e*j,Rt=b*et-_e*k,Pt=_*tt-$*j,It=_*et-$*k,Dt=_*_e-$*b,Ct=-(s*at-c*st+d*ut),Ot=+(o*at-c*ft+d*lt),Ft=-(o*st-s*ft+d*ht),wt=+(o*ut-s*lt+c*ht),Bt=+(s*Tt-c*St+d*At),Ut=-(o*Tt-c*vt+d*Et),Vt=+(o*St-s*vt+d*xt),Gt=-(o*At-s*Et+c*xt),Lt=-(s*bt-c*Mt+d*Rt),Ht=+(o*bt-c*Pt+d*It),Wt=-(o*Mt-s*Pt+d*Dt),Yt=+(o*Rt-s*It+c*Dt);return a.FromValuesToRef(pt*yt,Ct*yt,Bt*yt,Lt*yt,mt*yt,Ot*yt,Ut*yt,Ht*yt,dt*yt,Ft*yt,Vt*yt,Wt*yt,gt*yt,wt*yt,Gt*yt,Yt*yt,i),this},a.prototype.addAtIndex=function(i,e){return this._m[i]+=e,this._markAsUpdated(),this},a.prototype.multiplyAtIndex=function(i,e){return this._m[i]*=e,this._markAsUpdated(),this},a.prototype.setTranslationFromFloats=function(i,e,o){return this._m[12]=i,this._m[13]=e,this._m[14]=o,this._markAsUpdated(),this},a.prototype.addTranslationFromFloats=function(i,e,o){return this._m[12]+=i,this._m[13]+=e,this._m[14]+=o,this._markAsUpdated(),this},a.prototype.setTranslation=function(i){return this.setTranslationFromFloats(i._x,i._y,i._z)},a.prototype.getTranslation=function(){return new Vector3(this._m[12],this._m[13],this._m[14])},a.prototype.getTranslationToRef=function(i){return i.x=this._m[12],i.y=this._m[13],i.z=this._m[14],this},a.prototype.removeRotationAndScaling=function(){var i=this.m;return a.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i[12],i[13],i[14],i[15],this),this._updateIdentityStatus(i[12]===0&&i[13]===0&&i[14]===0&&i[15]===1),this},a.prototype.multiply=function(i){var e=new a;return this.multiplyToRef(i,e),e},a.prototype.copyFrom=function(i){i.copyToArray(this._m);var e=i;return this.updateFlag=e.updateFlag,this._updateIdentityStatus(e._isIdentity,e._isIdentityDirty,e._isIdentity3x2,e._isIdentity3x2Dirty),this},a.prototype.copyToArray=function(i,e){e===void 0&&(e=0);var o=this._m;return i[e]=o[0],i[e+1]=o[1],i[e+2]=o[2],i[e+3]=o[3],i[e+4]=o[4],i[e+5]=o[5],i[e+6]=o[6],i[e+7]=o[7],i[e+8]=o[8],i[e+9]=o[9],i[e+10]=o[10],i[e+11]=o[11],i[e+12]=o[12],i[e+13]=o[13],i[e+14]=o[14],i[e+15]=o[15],this},a.prototype.multiplyToRef=function(i,e){return this._isIdentity?(e.copyFrom(i),this):i._isIdentity?(e.copyFrom(this),this):(this.multiplyToArray(i,e._m,0),e._markAsUpdated(),this)},a.prototype.multiplyToArray=function(i,e,o){var s=this._m,c=i.m,d=s[0],_=s[1],b=s[2],k=s[3],j=s[4],$=s[5],_e=s[6],et=s[7],tt=s[8],rt=s[9],it=s[10],nt=s[11],ot=s[12],at=s[13],st=s[14],ut=s[15],ft=c[0],lt=c[1],ht=c[2],pt=c[3],mt=c[4],dt=c[5],gt=c[6],_t=c[7],yt=c[8],Tt=c[9],St=c[10],At=c[11],vt=c[12],Et=c[13],xt=c[14],bt=c[15];return e[o]=d*ft+_*mt+b*yt+k*vt,e[o+1]=d*lt+_*dt+b*Tt+k*Et,e[o+2]=d*ht+_*gt+b*St+k*xt,e[o+3]=d*pt+_*_t+b*At+k*bt,e[o+4]=j*ft+$*mt+_e*yt+et*vt,e[o+5]=j*lt+$*dt+_e*Tt+et*Et,e[o+6]=j*ht+$*gt+_e*St+et*xt,e[o+7]=j*pt+$*_t+_e*At+et*bt,e[o+8]=tt*ft+rt*mt+it*yt+nt*vt,e[o+9]=tt*lt+rt*dt+it*Tt+nt*Et,e[o+10]=tt*ht+rt*gt+it*St+nt*xt,e[o+11]=tt*pt+rt*_t+it*At+nt*bt,e[o+12]=ot*ft+at*mt+st*yt+ut*vt,e[o+13]=ot*lt+at*dt+st*Tt+ut*Et,e[o+14]=ot*ht+at*gt+st*St+ut*xt,e[o+15]=ot*pt+at*_t+st*At+ut*bt,this},a.prototype.equals=function(i){var e=i;if(!e)return!1;if((this._isIdentity||e._isIdentity)&&!this._isIdentityDirty&&!e._isIdentityDirty)return this._isIdentity&&e._isIdentity;var o=this.m,s=e.m;return o[0]===s[0]&&o[1]===s[1]&&o[2]===s[2]&&o[3]===s[3]&&o[4]===s[4]&&o[5]===s[5]&&o[6]===s[6]&&o[7]===s[7]&&o[8]===s[8]&&o[9]===s[9]&&o[10]===s[10]&&o[11]===s[11]&&o[12]===s[12]&&o[13]===s[13]&&o[14]===s[14]&&o[15]===s[15]},a.prototype.clone=function(){var i=new a;return i.copyFrom(this),i},a.prototype.getClassName=function(){return"Matrix"},a.prototype.getHashCode=function(){for(var i=this._m[0]|0,e=1;e<16;e++)i=i*397^(this._m[e]|0);return i},a.prototype.decomposeToTransformNode=function(i){return i.rotationQuaternion=i.rotationQuaternion||new Quaternion,this.decompose(i.scaling,i.rotationQuaternion,i.position)},a.prototype.decompose=function(i,e,o,s){if(this._isIdentity)return o&&o.setAll(0),i&&i.setAll(1),e&&e.copyFromFloats(0,0,0,1),!0;var c=this._m;if(o&&o.copyFromFloats(c[12],c[13],c[14]),i=i||MathTmp.Vector3[0],i.x=Math.sqrt(c[0]*c[0]+c[1]*c[1]+c[2]*c[2]),i.y=Math.sqrt(c[4]*c[4]+c[5]*c[5]+c[6]*c[6]),i.z=Math.sqrt(c[8]*c[8]+c[9]*c[9]+c[10]*c[10]),s){var d=s.scaling.x<0?-1:1,_=s.scaling.y<0?-1:1,b=s.scaling.z<0?-1:1;i.x*=d,i.y*=_,i.z*=b}else this.determinant()<=0&&(i.y*=-1);if(i._x===0||i._y===0||i._z===0)return e&&e.copyFromFloats(0,0,0,1),!1;if(e){var k=1/i._x,j=1/i._y,$=1/i._z;a.FromValuesToRef(c[0]*k,c[1]*k,c[2]*k,0,c[4]*j,c[5]*j,c[6]*j,0,c[8]*$,c[9]*$,c[10]*$,0,0,0,0,1,MathTmp.Matrix[0]),Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0],e)}return!0},a.prototype.getRow=function(i){if(i<0||i>3)return null;var e=i*4;return new Vector4(this._m[e+0],this._m[e+1],this._m[e+2],this._m[e+3])},a.prototype.setRow=function(i,e){return this.setRowFromFloats(i,e.x,e.y,e.z,e.w)},a.prototype.transpose=function(){return a.Transpose(this)},a.prototype.transposeToRef=function(i){return a.TransposeToRef(this,i),this},a.prototype.setRowFromFloats=function(i,e,o,s,c){if(i<0||i>3)return this;var d=i*4;return this._m[d+0]=e,this._m[d+1]=o,this._m[d+2]=s,this._m[d+3]=c,this._markAsUpdated(),this},a.prototype.scale=function(i){var e=new a;return this.scaleToRef(i,e),e},a.prototype.scaleToRef=function(i,e){for(var o=0;o<16;o++)e._m[o]=this._m[o]*i;return e._markAsUpdated(),this},a.prototype.scaleAndAddToRef=function(i,e){for(var o=0;o<16;o++)e._m[o]+=this._m[o]*i;return e._markAsUpdated(),this},a.prototype.toNormalMatrix=function(i){var e=MathTmp.Matrix[0];this.invertToRef(e),e.transposeToRef(i);var o=i._m;a.FromValuesToRef(o[0],o[1],o[2],0,o[4],o[5],o[6],0,o[8],o[9],o[10],0,0,0,0,1,i)},a.prototype.getRotationMatrix=function(){var i=new a;return this.getRotationMatrixToRef(i),i},a.prototype.getRotationMatrixToRef=function(i){var e=MathTmp.Vector3[0];if(!this.decompose(e))return a.IdentityToRef(i),this;var o=this._m,s=1/e._x,c=1/e._y,d=1/e._z;return a.FromValuesToRef(o[0]*s,o[1]*s,o[2]*s,0,o[4]*c,o[5]*c,o[6]*c,0,o[8]*d,o[9]*d,o[10]*d,0,0,0,0,1,i),this},a.prototype.toggleModelMatrixHandInPlace=function(){var i=this._m;i[2]*=-1,i[6]*=-1,i[8]*=-1,i[9]*=-1,i[14]*=-1,this._markAsUpdated()},a.prototype.toggleProjectionMatrixHandInPlace=function(){var i=this._m;i[8]*=-1,i[9]*=-1,i[10]*=-1,i[11]*=-1,this._markAsUpdated()},a.FromArray=function(i,e){e===void 0&&(e=0);var o=new a;return a.FromArrayToRef(i,e,o),o},a.FromArrayToRef=function(i,e,o){for(var s=0;s<16;s++)o._m[s]=i[s+e];o._markAsUpdated()},a.FromFloat32ArrayToRefScaled=function(i,e,o,s){for(var c=0;c<16;c++)s._m[c]=i[c+e]*o;s._markAsUpdated()},Object.defineProperty(a,"IdentityReadOnly",{get:function(){return a._identityReadOnly},enumerable:!1,configurable:!0}),a.FromValuesToRef=function(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it,nt){var ot=nt._m;ot[0]=i,ot[1]=e,ot[2]=o,ot[3]=s,ot[4]=c,ot[5]=d,ot[6]=_,ot[7]=b,ot[8]=k,ot[9]=j,ot[10]=$,ot[11]=_e,ot[12]=et,ot[13]=tt,ot[14]=rt,ot[15]=it,nt._markAsUpdated()},a.FromValues=function(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it){var nt=new a,ot=nt._m;return ot[0]=i,ot[1]=e,ot[2]=o,ot[3]=s,ot[4]=c,ot[5]=d,ot[6]=_,ot[7]=b,ot[8]=k,ot[9]=j,ot[10]=$,ot[11]=_e,ot[12]=et,ot[13]=tt,ot[14]=rt,ot[15]=it,nt._markAsUpdated(),nt},a.Compose=function(i,e,o){var s=new a;return a.ComposeToRef(i,e,o,s),s},a.ComposeToRef=function(i,e,o,s){var c=s._m,d=e._x,_=e._y,b=e._z,k=e._w,j=d+d,$=_+_,_e=b+b,et=d*j,tt=d*$,rt=d*_e,it=_*$,nt=_*_e,ot=b*_e,at=k*j,st=k*$,ut=k*_e,ft=i._x,lt=i._y,ht=i._z;c[0]=(1-(it+ot))*ft,c[1]=(tt+ut)*ft,c[2]=(rt-st)*ft,c[3]=0,c[4]=(tt-ut)*lt,c[5]=(1-(et+ot))*lt,c[6]=(nt+at)*lt,c[7]=0,c[8]=(rt+st)*ht,c[9]=(nt-at)*ht,c[10]=(1-(et+it))*ht,c[11]=0,c[12]=o._x,c[13]=o._y,c[14]=o._z,c[15]=1,s._markAsUpdated()},a.Identity=function(){var i=a.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return i._updateIdentityStatus(!0),i},a.IdentityToRef=function(i){a.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i),i._updateIdentityStatus(!0)},a.Zero=function(){var i=a.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return i._updateIdentityStatus(!1),i},a.RotationX=function(i){var e=new a;return a.RotationXToRef(i,e),e},a.Invert=function(i){var e=new a;return i.invertToRef(e),e},a.RotationXToRef=function(i,e){var o=Math.sin(i),s=Math.cos(i);a.FromValuesToRef(1,0,0,0,0,s,o,0,0,-o,s,0,0,0,0,1,e),e._updateIdentityStatus(s===1&&o===0)},a.RotationY=function(i){var e=new a;return a.RotationYToRef(i,e),e},a.RotationYToRef=function(i,e){var o=Math.sin(i),s=Math.cos(i);a.FromValuesToRef(s,0,-o,0,0,1,0,0,o,0,s,0,0,0,0,1,e),e._updateIdentityStatus(s===1&&o===0)},a.RotationZ=function(i){var e=new a;return a.RotationZToRef(i,e),e},a.RotationZToRef=function(i,e){var o=Math.sin(i),s=Math.cos(i);a.FromValuesToRef(s,o,0,0,-o,s,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(s===1&&o===0)},a.RotationAxis=function(i,e){var o=new a;return a.RotationAxisToRef(i,e,o),o},a.RotationAxisToRef=function(i,e,o){var s=Math.sin(-e),c=Math.cos(-e),d=1-c;i.normalize();var _=o._m;_[0]=i._x*i._x*d+c,_[1]=i._x*i._y*d-i._z*s,_[2]=i._x*i._z*d+i._y*s,_[3]=0,_[4]=i._y*i._x*d+i._z*s,_[5]=i._y*i._y*d+c,_[6]=i._y*i._z*d-i._x*s,_[7]=0,_[8]=i._z*i._x*d-i._y*s,_[9]=i._z*i._y*d+i._x*s,_[10]=i._z*i._z*d+c,_[11]=0,_[12]=0,_[13]=0,_[14]=0,_[15]=1,o._markAsUpdated()},a.RotationAlignToRef=function(i,e,o){var s=Vector3.Dot(e,i),c=o._m;if(s<-1+Epsilon)c[0]=-1,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=-1,c[6]=0,c[7]=0,c[8]=0,c[9]=0,c[10]=1,c[11]=0;else{var d=Vector3.Cross(e,i),_=1/(1+s);c[0]=d._x*d._x*_+s,c[1]=d._y*d._x*_-d._z,c[2]=d._z*d._x*_+d._y,c[3]=0,c[4]=d._x*d._y*_+d._z,c[5]=d._y*d._y*_+s,c[6]=d._z*d._y*_-d._x,c[7]=0,c[8]=d._x*d._z*_-d._y,c[9]=d._y*d._z*_+d._x,c[10]=d._z*d._z*_+s,c[11]=0}c[12]=0,c[13]=0,c[14]=0,c[15]=1,o._markAsUpdated()},a.RotationYawPitchRoll=function(i,e,o){var s=new a;return a.RotationYawPitchRollToRef(i,e,o,s),s},a.RotationYawPitchRollToRef=function(i,e,o,s){Quaternion.RotationYawPitchRollToRef(i,e,o,MathTmp.Quaternion[0]),MathTmp.Quaternion[0].toRotationMatrix(s)},a.Scaling=function(i,e,o){var s=new a;return a.ScalingToRef(i,e,o,s),s},a.ScalingToRef=function(i,e,o,s){a.FromValuesToRef(i,0,0,0,0,e,0,0,0,0,o,0,0,0,0,1,s),s._updateIdentityStatus(i===1&&e===1&&o===1)},a.Translation=function(i,e,o){var s=new a;return a.TranslationToRef(i,e,o,s),s},a.TranslationToRef=function(i,e,o,s){a.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,e,o,1,s),s._updateIdentityStatus(i===0&&e===0&&o===0)},a.Lerp=function(i,e,o){var s=new a;return a.LerpToRef(i,e,o,s),s},a.LerpToRef=function(i,e,o,s){for(var c=s._m,d=i.m,_=e.m,b=0;b<16;b++)c[b]=d[b]*(1-o)+_[b]*o;s._markAsUpdated()},a.DecomposeLerp=function(i,e,o){var s=new a;return a.DecomposeLerpToRef(i,e,o,s),s},a.DecomposeLerpToRef=function(i,e,o,s){var c=MathTmp.Vector3[0],d=MathTmp.Quaternion[0],_=MathTmp.Vector3[1];i.decompose(c,d,_);var b=MathTmp.Vector3[2],k=MathTmp.Quaternion[1],j=MathTmp.Vector3[3];e.decompose(b,k,j);var $=MathTmp.Vector3[4];Vector3.LerpToRef(c,b,o,$);var _e=MathTmp.Quaternion[2];Quaternion.SlerpToRef(d,k,o,_e);var et=MathTmp.Vector3[5];Vector3.LerpToRef(_,j,o,et),a.ComposeToRef($,_e,et,s)},a.LookAtLH=function(i,e,o){var s=new a;return a.LookAtLHToRef(i,e,o,s),s},a.LookAtLHToRef=function(i,e,o,s){var c=MathTmp.Vector3[0],d=MathTmp.Vector3[1],_=MathTmp.Vector3[2];e.subtractToRef(i,_),_.normalize(),Vector3.CrossToRef(o,_,c);var b=c.lengthSquared();b===0?c.x=1:c.normalizeFromLength(Math.sqrt(b)),Vector3.CrossToRef(_,c,d),d.normalize();var k=-Vector3.Dot(c,i),j=-Vector3.Dot(d,i),$=-Vector3.Dot(_,i);a.FromValuesToRef(c._x,d._x,_._x,0,c._y,d._y,_._y,0,c._z,d._z,_._z,0,k,j,$,1,s)},a.LookAtRH=function(i,e,o){var s=new a;return a.LookAtRHToRef(i,e,o,s),s},a.LookAtRHToRef=function(i,e,o,s){var c=MathTmp.Vector3[0],d=MathTmp.Vector3[1],_=MathTmp.Vector3[2];i.subtractToRef(e,_),_.normalize(),Vector3.CrossToRef(o,_,c);var b=c.lengthSquared();b===0?c.x=1:c.normalizeFromLength(Math.sqrt(b)),Vector3.CrossToRef(_,c,d),d.normalize();var k=-Vector3.Dot(c,i),j=-Vector3.Dot(d,i),$=-Vector3.Dot(_,i);a.FromValuesToRef(c._x,d._x,_._x,0,c._y,d._y,_._y,0,c._z,d._z,_._z,0,k,j,$,1,s)},a.LookDirectionLH=function(i,e){var o=new a;return a.LookDirectionLHToRef(i,e,o),o},a.LookDirectionLHToRef=function(i,e,o){var s=MathTmp.Vector3[0];s.copyFrom(i),s.scaleInPlace(-1);var c=MathTmp.Vector3[1];Vector3.CrossToRef(e,s,c),a.FromValuesToRef(c._x,c._y,c._z,0,e._x,e._y,e._z,0,s._x,s._y,s._z,0,0,0,0,1,o)},a.LookDirectionRH=function(i,e){var o=new a;return a.LookDirectionRHToRef(i,e,o),o},a.LookDirectionRHToRef=function(i,e,o){var s=MathTmp.Vector3[2];Vector3.CrossToRef(e,i,s),a.FromValuesToRef(s._x,s._y,s._z,0,e._x,e._y,e._z,0,i._x,i._y,i._z,0,0,0,0,1,o)},a.OrthoLH=function(i,e,o,s,c){var d=new a;return a.OrthoLHToRef(i,e,o,s,d,c),d},a.OrthoLHToRef=function(i,e,o,s,c,d){var _=o,b=s,k=2/i,j=2/e,$=2/(b-_),_e=-(b+_)/(b-_);a.FromValuesToRef(k,0,0,0,0,j,0,0,0,0,$,0,0,0,_e,1,c),d&&c.multiplyToRef(mtxConvertNDCToHalfZRange,c),c._updateIdentityStatus(k===1&&j===1&&$===1&&_e===0)},a.OrthoOffCenterLH=function(i,e,o,s,c,d,_){var b=new a;return a.OrthoOffCenterLHToRef(i,e,o,s,c,d,b,_),b},a.OrthoOffCenterLHToRef=function(i,e,o,s,c,d,_,b){var k=c,j=d,$=2/(e-i),_e=2/(s-o),et=2/(j-k),tt=-(j+k)/(j-k),rt=(i+e)/(i-e),it=(s+o)/(o-s);a.FromValuesToRef($,0,0,0,0,_e,0,0,0,0,et,0,rt,it,tt,1,_),b&&_.multiplyToRef(mtxConvertNDCToHalfZRange,_),_._markAsUpdated()},a.OrthoOffCenterRH=function(i,e,o,s,c,d,_){var b=new a;return a.OrthoOffCenterRHToRef(i,e,o,s,c,d,b,_),b},a.OrthoOffCenterRHToRef=function(i,e,o,s,c,d,_,b){a.OrthoOffCenterLHToRef(i,e,o,s,c,d,_,b),_._m[10]*=-1},a.PerspectiveLH=function(i,e,o,s,c,d){d===void 0&&(d=0);var _=new a,b=o,k=s,j=2*b/i,$=2*b/e,_e=(k+b)/(k-b),et=-2*k*b/(k-b),tt=Math.tan(d);return a.FromValuesToRef(j,0,0,0,0,$,0,tt,0,0,_e,1,0,0,et,0,_),c&&_.multiplyToRef(mtxConvertNDCToHalfZRange,_),_._updateIdentityStatus(!1),_},a.PerspectiveFovLH=function(i,e,o,s,c,d,_){d===void 0&&(d=0),_===void 0&&(_=!1);var b=new a;return a.PerspectiveFovLHToRef(i,e,o,s,b,!0,c,d,_),b},a.PerspectiveFovLHToRef=function(i,e,o,s,c,d,_,b,k){d===void 0&&(d=!0),b===void 0&&(b=0),k===void 0&&(k=!1);var j=o,$=s,_e=1/Math.tan(i*.5),et=d?_e/e:_e,tt=d?_e:_e*e,rt=k&&j===0?-1:$!==0?($+j)/($-j):1,it=k&&j===0?2*$:$!==0?-2*$*j/($-j):-2*j,nt=Math.tan(b);a.FromValuesToRef(et,0,0,0,0,tt,0,nt,0,0,rt,1,0,0,it,0,c),_&&c.multiplyToRef(mtxConvertNDCToHalfZRange,c),c._updateIdentityStatus(!1)},a.PerspectiveFovReverseLHToRef=function(i,e,o,s,c,d,_,b){d===void 0&&(d=!0),b===void 0&&(b=0);var k=1/Math.tan(i*.5),j=d?k/e:k,$=d?k:k*e,_e=Math.tan(b);a.FromValuesToRef(j,0,0,0,0,$,0,_e,0,0,-o,1,0,0,1,0,c),_&&c.multiplyToRef(mtxConvertNDCToHalfZRange,c),c._updateIdentityStatus(!1)},a.PerspectiveFovRH=function(i,e,o,s,c,d,_){d===void 0&&(d=0),_===void 0&&(_=!1);var b=new a;return a.PerspectiveFovRHToRef(i,e,o,s,b,!0,c,d,_),b},a.PerspectiveFovRHToRef=function(i,e,o,s,c,d,_,b,k){d===void 0&&(d=!0),b===void 0&&(b=0),k===void 0&&(k=!1);var j=o,$=s,_e=1/Math.tan(i*.5),et=d?_e/e:_e,tt=d?_e:_e*e,rt=k&&j===0?1:$!==0?-($+j)/($-j):-1,it=k&&j===0?2*$:$!==0?-2*$*j/($-j):-2*j,nt=Math.tan(b);a.FromValuesToRef(et,0,0,0,0,tt,0,nt,0,0,rt,-1,0,0,it,0,c),_&&c.multiplyToRef(mtxConvertNDCToHalfZRange,c),c._updateIdentityStatus(!1)},a.PerspectiveFovReverseRHToRef=function(i,e,o,s,c,d,_,b){d===void 0&&(d=!0),b===void 0&&(b=0);var k=1/Math.tan(i*.5),j=d?k/e:k,$=d?k:k*e,_e=Math.tan(b);a.FromValuesToRef(j,0,0,0,0,$,0,_e,0,0,-o,-1,0,0,-1,0,c),_&&c.multiplyToRef(mtxConvertNDCToHalfZRange,c),c._updateIdentityStatus(!1)},a.PerspectiveFovWebVRToRef=function(i,e,o,s,c,d,_){c===void 0&&(c=!1),_===void 0&&(_=0);var b=c?-1:1,k=Math.tan(i.upDegrees*Math.PI/180),j=Math.tan(i.downDegrees*Math.PI/180),$=Math.tan(i.leftDegrees*Math.PI/180),_e=Math.tan(i.rightDegrees*Math.PI/180),et=2/($+_e),tt=2/(k+j),rt=Math.tan(_),it=s._m;it[0]=et,it[1]=it[2]=it[3]=it[4]=0,it[5]=tt,it[6]=0,it[7]=rt,it[8]=($-_e)*et*.5,it[9]=-((k-j)*tt*.5),it[10]=-o/(e-o),it[11]=1*b,it[12]=it[13]=it[15]=0,it[14]=-(2*o*e)/(o-e),d&&s.multiplyToRef(mtxConvertNDCToHalfZRange,s),s._markAsUpdated()},a.GetFinalMatrix=function(i,e,o,s,c,d){var _=i.width,b=i.height,k=i.x,j=i.y,$=a.FromValues(_/2,0,0,0,0,-b/2,0,0,0,0,d-c,0,k+_/2,b/2+j,c,1),_e=MathTmp.Matrix[0];return e.multiplyToRef(o,_e),_e.multiplyToRef(s,_e),_e.multiply($)},a.GetAsMatrix2x2=function(i){var e=i.m,o=[e[0],e[1],e[4],e[5]];return PerformanceConfigurator.MatrixUse64Bits?o:new Float32Array(o)},a.GetAsMatrix3x3=function(i){var e=i.m,o=[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]];return PerformanceConfigurator.MatrixUse64Bits?o:new Float32Array(o)},a.Transpose=function(i){var e=new a;return a.TransposeToRef(i,e),e},a.TransposeToRef=function(i,e){var o=e._m,s=i.m;o[0]=s[0],o[1]=s[4],o[2]=s[8],o[3]=s[12],o[4]=s[1],o[5]=s[5],o[6]=s[9],o[7]=s[13],o[8]=s[2],o[9]=s[6],o[10]=s[10],o[11]=s[14],o[12]=s[3],o[13]=s[7],o[14]=s[11],o[15]=s[15],e._markAsUpdated(),e._updateIdentityStatus(i._isIdentity,i._isIdentityDirty)},a.Reflection=function(i){var e=new a;return a.ReflectionToRef(i,e),e},a.ReflectionToRef=function(i,e){i.normalize();var o=i.normal.x,s=i.normal.y,c=i.normal.z,d=-2*o,_=-2*s,b=-2*c;a.FromValuesToRef(d*o+1,_*o,b*o,0,d*s,_*s+1,b*s,0,d*c,_*c,b*c+1,0,d*i.d,_*i.d,b*i.d,1,e)},a.FromXYZAxesToRef=function(i,e,o,s){a.FromValuesToRef(i._x,i._y,i._z,0,e._x,e._y,e._z,0,o._x,o._y,o._z,0,0,0,0,1,s)},a.FromQuaternionToRef=function(i,e){var o=i._x*i._x,s=i._y*i._y,c=i._z*i._z,d=i._x*i._y,_=i._z*i._w,b=i._z*i._x,k=i._y*i._w,j=i._y*i._z,$=i._x*i._w;e._m[0]=1-2*(s+c),e._m[1]=2*(d+_),e._m[2]=2*(b-k),e._m[3]=0,e._m[4]=2*(d-_),e._m[5]=1-2*(c+o),e._m[6]=2*(j+$),e._m[7]=0,e._m[8]=2*(b+k),e._m[9]=2*(j-$),e._m[10]=1-2*(s+o),e._m[11]=0,e._m[12]=0,e._m[13]=0,e._m[14]=0,e._m[15]=1,e._markAsUpdated()},a._updateFlagSeed=0,a._identityReadOnly=a.Identity(),a}(),MathTmp=function(){function a(){}return a.Vector3=ArrayTools.BuildTuple(11,Vector3.Zero),a.Matrix=ArrayTools.BuildTuple(2,Matrix.Identity),a.Quaternion=ArrayTools.BuildTuple(3,Quaternion.Zero),a}(),TmpVectors=function(){function a(){}return a.Vector2=ArrayTools.BuildTuple(3,Vector2.Zero),a.Vector3=ArrayTools.BuildTuple(13,Vector3.Zero),a.Vector4=ArrayTools.BuildTuple(3,Vector4.Zero),a.Quaternion=ArrayTools.BuildTuple(2,Quaternion.Zero),a.Matrix=ArrayTools.BuildTuple(8,Matrix.Identity),a}();RegisterClass("BABYLON.Vector2",Vector2);RegisterClass("BABYLON.Vector3",Vector3);RegisterClass("BABYLON.Vector4",Vector4);RegisterClass("BABYLON.Matrix",Matrix);var mtxConvertNDCToHalfZRange=Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1),Buffer=function(){function a(i,e,o,s,c,d,_,b){s===void 0&&(s=0),c===void 0&&(c=!1),d===void 0&&(d=!1),_===void 0&&(_=!1),this._isAlreadyOwned=!1,i.getScene?this._engine=i.getScene().getEngine():this._engine=i,this._updatable=o,this._instanced=d,this._divisor=b||1,e instanceof DataBuffer?(this._data=null,this._buffer=e):(this._data=e,this._buffer=null),this.byteStride=_?s:s*Float32Array.BYTES_PER_ELEMENT,c||this.create()}return a.prototype.createVertexBuffer=function(i,e,o,s,c,d,_){d===void 0&&(d=!1);var b=d?e:e*Float32Array.BYTES_PER_ELEMENT,k=s?d?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new VertexBuffer(this._engine,this,i,this._updatable,!0,k,c===void 0?this._instanced:c,b,o,void 0,void 0,!0,this._divisor||_)},a.prototype.isUpdatable=function(){return this._updatable},a.prototype.getData=function(){return this._data},a.prototype.getBuffer=function(){return this._buffer},a.prototype.getStrideSize=function(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT},a.prototype.create=function(i){i===void 0&&(i=null),!(!i&&this._buffer)&&(i=i||this._data,i&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,i),this._data=i):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(i),this._data=i):this._buffer=this._engine.createVertexBuffer(i)))},a.prototype._rebuild=function(){this._buffer=null,this.create(this._data)},a.prototype.update=function(i){this.create(i)},a.prototype.updateDirectly=function(i,e,o,s){s===void 0&&(s=!1),!!this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,i,s?e:e*Float32Array.BYTES_PER_ELEMENT,o?o*this.byteStride:void 0),this._data=null)},a.prototype._increaseReferences=function(){if(!!this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}},a.prototype.dispose=function(){!this._buffer||this._engine._releaseBuffer(this._buffer)&&(this._buffer=null,this._data=null)},a}(),VertexBuffer=function(){function a(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt){if($===void 0&&($=!1),_e===void 0&&(_e=!1),et===void 0&&(et=1),tt===void 0&&(tt=!1),e instanceof Buffer?(this._buffer=e,this._ownsBuffer=tt):(this._buffer=new Buffer(i,e,s,d,c,_,_e),this._ownsBuffer=!0),this.uniqueId=a._Counter++,this._kind=o,j==null){var rt=this.getData();this.type=a.FLOAT,rt instanceof Int8Array?this.type=a.BYTE:rt instanceof Uint8Array?this.type=a.UNSIGNED_BYTE:rt instanceof Int16Array?this.type=a.SHORT:rt instanceof Uint16Array?this.type=a.UNSIGNED_SHORT:rt instanceof Int32Array?this.type=a.INT:rt instanceof Uint32Array&&(this.type=a.UNSIGNED_INT)}else this.type=j;var it=a.GetTypeByteLength(this.type);_e?(this._size=k||(d?d/it:a.DeduceStride(o)),this.byteStride=d||this._buffer.byteStride||this._size*it,this.byteOffset=b||0):(this._size=k||d||a.DeduceStride(o),this.byteStride=d?d*it:this._buffer.byteStride||this._size*it,this.byteOffset=(b||0)*it),this.normalized=$,this._instanced=_!==void 0?_:!1,this._instanceDivisor=_?et:0,this._computeHashCode()}return Object.defineProperty(a.prototype,"instanceDivisor",{get:function(){return this._instanceDivisor},set:function(i){this._instanceDivisor=i,i==0?this._instanced=!1:this._instanced=!0,this._computeHashCode()},enumerable:!1,configurable:!0}),a.prototype._computeHashCode=function(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)},a.prototype._rebuild=function(){!this._buffer||this._buffer._rebuild()},a.prototype.getKind=function(){return this._kind},a.prototype.isUpdatable=function(){return this._buffer.isUpdatable()},a.prototype.getData=function(){return this._buffer.getData()},a.prototype.getFloatData=function(i,e){var o=this.getData();if(!o)return null;var s=this.getSize()*a.GetTypeByteLength(this.type),c=i*this.getSize();if(this.type!==a.FLOAT||this.byteStride!==s){var d=new Float32Array(c);return this.forEach(c,function($,_e){return d[_e]=$}),d}if(!(o instanceof Array||o instanceof Float32Array)||this.byteOffset!==0||o.length!==c)if(o instanceof Array){var _=this.byteOffset/4;return SliceTools.Slice(o,_,_+c)}else{if(o instanceof ArrayBuffer)return new Float32Array(o,this.byteOffset,c);var _=o.byteOffset+this.byteOffset;if(e){var b=new Float32Array(c),k=new Float32Array(o.buffer,_,c);return b.set(k),b}var j=_%4;return j&&(_=Math.max(0,_-j)),new Float32Array(o.buffer,_,c)}return e?SliceTools.Slice(o):o},a.prototype.getBuffer=function(){return this._buffer.getBuffer()},a.prototype.getStrideSize=function(){return this.byteStride/a.GetTypeByteLength(this.type)},a.prototype.getOffset=function(){return this.byteOffset/a.GetTypeByteLength(this.type)},a.prototype.getSize=function(i){return i===void 0&&(i=!1),i?this._size*a.GetTypeByteLength(this.type):this._size},a.prototype.getIsInstanced=function(){return this._instanced},a.prototype.getInstanceDivisor=function(){return this._instanceDivisor},a.prototype.create=function(i){this._buffer.create(i)},a.prototype.update=function(i){this._buffer.update(i)},a.prototype.updateDirectly=function(i,e,o){o===void 0&&(o=!1),this._buffer.updateDirectly(i,e,void 0,o)},a.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose()},a.prototype.forEach=function(i,e){a.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,i,this.normalized,e)},a.DeduceStride=function(i){switch(i){case a.UVKind:case a.UV2Kind:case a.UV3Kind:case a.UV4Kind:case a.UV5Kind:case a.UV6Kind:return 2;case a.NormalKind:case a.PositionKind:return 3;case a.ColorKind:case a.MatricesIndicesKind:case a.MatricesIndicesExtraKind:case a.MatricesWeightsKind:case a.MatricesWeightsExtraKind:case a.TangentKind:return 4;default:throw new Error("Invalid kind '"+i+"'")}},a.GetTypeByteLength=function(i){switch(i){case a.BYTE:case a.UNSIGNED_BYTE:return 1;case a.SHORT:case a.UNSIGNED_SHORT:return 2;case a.INT:case a.UNSIGNED_INT:case a.FLOAT:return 4;default:throw new Error("Invalid type '"+i+"'")}},a.ForEach=function(i,e,o,s,c,d,_,b){if(i instanceof Array)for(var k=e/4,j=o/4,$=0;$<d;$+=s){for(var _e=0;_e<s;_e++)b(i[k+_e],$+_e);k+=j}else for(var et=i instanceof ArrayBuffer?new DataView(i):new DataView(i.buffer,i.byteOffset,i.byteLength),tt=a.GetTypeByteLength(c),$=0;$<d;$+=s){for(var rt=e,_e=0;_e<s;_e++){var it=a._GetFloatValue(et,c,rt,_);b(it,$+_e),rt+=tt}e+=o}},a._GetFloatValue=function(i,e,o,s){switch(e){case a.BYTE:{var c=i.getInt8(o);return s&&(c=Math.max(c/127,-1)),c}case a.UNSIGNED_BYTE:{var c=i.getUint8(o);return s&&(c=c/255),c}case a.SHORT:{var c=i.getInt16(o,!0);return s&&(c=Math.max(c/32767,-1)),c}case a.UNSIGNED_SHORT:{var c=i.getUint16(o,!0);return s&&(c=c/65535),c}case a.INT:return i.getInt32(o,!0);case a.UNSIGNED_INT:return i.getUint32(o,!0);case a.FLOAT:return i.getFloat32(o,!0);default:throw new Error("Invalid component type "+e)}},a._Counter=0,a.BYTE=5120,a.UNSIGNED_BYTE=5121,a.SHORT=5122,a.UNSIGNED_SHORT=5123,a.INT=5124,a.UNSIGNED_INT=5125,a.FLOAT=5126,a.PositionKind="position",a.NormalKind="normal",a.TangentKind="tangent",a.UVKind="uv",a.UV2Kind="uv2",a.UV3Kind="uv3",a.UV4Kind="uv4",a.UV5Kind="uv5",a.UV6Kind="uv6",a.ColorKind="color",a.MatricesIndicesKind="matricesIndices",a.MatricesWeightsKind="matricesWeights",a.MatricesIndicesExtraKind="matricesIndicesExtra",a.MatricesWeightsExtraKind="matricesWeightsExtra",a}(),Color3=function(){function a(i,e,o){i===void 0&&(i=0),e===void 0&&(e=0),o===void 0&&(o=0),this.r=i,this.g=e,this.b=o}return a.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},a.prototype.getClassName=function(){return"Color3"},a.prototype.getHashCode=function(){var i=this.r*255|0;return i=i*397^(this.g*255|0),i=i*397^(this.b*255|0),i},a.prototype.toArray=function(i,e){return e===void 0&&(e=0),i[e]=this.r,i[e+1]=this.g,i[e+2]=this.b,this},a.prototype.fromArray=function(i,e){return e===void 0&&(e=0),a.FromArrayToRef(i,e,this),this},a.prototype.toColor4=function(i){return i===void 0&&(i=1),new Color4(this.r,this.g,this.b,i)},a.prototype.asArray=function(){var i=new Array;return this.toArray(i,0),i},a.prototype.toLuminance=function(){return this.r*.3+this.g*.59+this.b*.11},a.prototype.multiply=function(i){return new a(this.r*i.r,this.g*i.g,this.b*i.b)},a.prototype.multiplyToRef=function(i,e){return e.r=this.r*i.r,e.g=this.g*i.g,e.b=this.b*i.b,this},a.prototype.equals=function(i){return i&&this.r===i.r&&this.g===i.g&&this.b===i.b},a.prototype.equalsFloats=function(i,e,o){return this.r===i&&this.g===e&&this.b===o},a.prototype.scale=function(i){return new a(this.r*i,this.g*i,this.b*i)},a.prototype.scaleToRef=function(i,e){return e.r=this.r*i,e.g=this.g*i,e.b=this.b*i,this},a.prototype.scaleAndAddToRef=function(i,e){return e.r+=this.r*i,e.g+=this.g*i,e.b+=this.b*i,this},a.prototype.clampToRef=function(i,e,o){return i===void 0&&(i=0),e===void 0&&(e=1),o.r=Scalar.Clamp(this.r,i,e),o.g=Scalar.Clamp(this.g,i,e),o.b=Scalar.Clamp(this.b,i,e),this},a.prototype.add=function(i){return new a(this.r+i.r,this.g+i.g,this.b+i.b)},a.prototype.addToRef=function(i,e){return e.r=this.r+i.r,e.g=this.g+i.g,e.b=this.b+i.b,this},a.prototype.subtract=function(i){return new a(this.r-i.r,this.g-i.g,this.b-i.b)},a.prototype.subtractToRef=function(i,e){return e.r=this.r-i.r,e.g=this.g-i.g,e.b=this.b-i.b,this},a.prototype.clone=function(){return new a(this.r,this.g,this.b)},a.prototype.copyFrom=function(i){return this.r=i.r,this.g=i.g,this.b=i.b,this},a.prototype.copyFromFloats=function(i,e,o){return this.r=i,this.g=e,this.b=o,this},a.prototype.set=function(i,e,o){return this.copyFromFloats(i,e,o)},a.prototype.toHexString=function(){var i=Math.round(this.r*255),e=Math.round(this.g*255),o=Math.round(this.b*255);return"#"+Scalar.ToHex(i)+Scalar.ToHex(e)+Scalar.ToHex(o)},a.prototype.toLinearSpace=function(){var i=new a;return this.toLinearSpaceToRef(i),i},a.prototype.toHSV=function(){var i=new a;return this.toHSVToRef(i),i},a.prototype.toHSVToRef=function(i){var e=this.r,o=this.g,s=this.b,c=Math.max(e,o,s),d=Math.min(e,o,s),_=0,b=0,k=c,j=c-d;c!==0&&(b=j/c),c!=d&&(c==e?(_=(o-s)/j,o<s&&(_+=6)):c==o?_=(s-e)/j+2:c==s&&(_=(e-o)/j+4),_*=60),i.r=_,i.g=b,i.b=k},a.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,ToLinearSpace),i.g=Math.pow(this.g,ToLinearSpace),i.b=Math.pow(this.b,ToLinearSpace),this},a.prototype.toGammaSpace=function(){var i=new a;return this.toGammaSpaceToRef(i),i},a.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,ToGammaSpace),i.g=Math.pow(this.g,ToGammaSpace),i.b=Math.pow(this.b,ToGammaSpace),this},a.HSVtoRGBToRef=function(i,e,o,s){var c=o*e,d=i/60,_=c*(1-Math.abs(d%2-1)),b=0,k=0,j=0;d>=0&&d<=1?(b=c,k=_):d>=1&&d<=2?(b=_,k=c):d>=2&&d<=3?(k=c,j=_):d>=3&&d<=4?(k=_,j=c):d>=4&&d<=5?(b=_,j=c):d>=5&&d<=6&&(b=c,j=_);var $=o-c;s.set(b+$,k+$,j+$)},a.FromHexString=function(i){if(i.substring(0,1)!=="#"||i.length!==7)return new a(0,0,0);var e=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return a.FromInts(e,o,s)},a.FromArray=function(i,e){return e===void 0&&(e=0),new a(i[e],i[e+1],i[e+2])},a.FromArrayToRef=function(i,e,o){e===void 0&&(e=0),o.r=i[e],o.g=i[e+1],o.b=i[e+2]},a.FromInts=function(i,e,o){return new a(i/255,e/255,o/255)},a.Lerp=function(i,e,o){var s=new a(0,0,0);return a.LerpToRef(i,e,o,s),s},a.LerpToRef=function(i,e,o,s){s.r=i.r+(e.r-i.r)*o,s.g=i.g+(e.g-i.g)*o,s.b=i.b+(e.b-i.b)*o},a.Hermite=function(i,e,o,s,c){var d=c*c,_=c*d,b=2*_-3*d+1,k=-2*_+3*d,j=_-2*d+c,$=_-d,_e=i.r*b+o.r*k+e.r*j+s.r*$,et=i.g*b+o.g*k+e.g*j+s.g*$,tt=i.b*b+o.b*k+e.b*j+s.b*$;return new a(_e,et,tt)},a.Hermite1stDerivative=function(i,e,o,s,c){var d=a.Black();return this.Hermite1stDerivativeToRef(i,e,o,s,c,d),d},a.Hermite1stDerivativeToRef=function(i,e,o,s,c,d){var _=c*c;d.r=(_-c)*6*i.r+(3*_-4*c+1)*e.r+(-_+c)*6*o.r+(3*_-2*c)*s.r,d.g=(_-c)*6*i.g+(3*_-4*c+1)*e.g+(-_+c)*6*o.g+(3*_-2*c)*s.g,d.b=(_-c)*6*i.b+(3*_-4*c+1)*e.b+(-_+c)*6*o.b+(3*_-2*c)*s.b},a.Red=function(){return new a(1,0,0)},a.Green=function(){return new a(0,1,0)},a.Blue=function(){return new a(0,0,1)},a.Black=function(){return new a(0,0,0)},Object.defineProperty(a,"BlackReadOnly",{get:function(){return a._BlackReadOnly},enumerable:!1,configurable:!0}),a.White=function(){return new a(1,1,1)},a.Purple=function(){return new a(.5,0,.5)},a.Magenta=function(){return new a(1,0,1)},a.Yellow=function(){return new a(1,1,0)},a.Gray=function(){return new a(.5,.5,.5)},a.Teal=function(){return new a(0,1,1)},a.Random=function(){return new a(Math.random(),Math.random(),Math.random())},a._BlackReadOnly=a.Black(),a}(),Color4=function(){function a(i,e,o,s){i===void 0&&(i=0),e===void 0&&(e=0),o===void 0&&(o=0),s===void 0&&(s=1),this.r=i,this.g=e,this.b=o,this.a=s}return a.prototype.addInPlace=function(i){return this.r+=i.r,this.g+=i.g,this.b+=i.b,this.a+=i.a,this},a.prototype.asArray=function(){var i=new Array;return this.toArray(i,0),i},a.prototype.toArray=function(i,e){return e===void 0&&(e=0),i[e]=this.r,i[e+1]=this.g,i[e+2]=this.b,i[e+3]=this.a,this},a.prototype.fromArray=function(i,e){return e===void 0&&(e=0),a.FromArrayToRef(i,e,this),this},a.prototype.equals=function(i){return i&&this.r===i.r&&this.g===i.g&&this.b===i.b&&this.a===i.a},a.prototype.add=function(i){return new a(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},a.prototype.subtract=function(i){return new a(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},a.prototype.subtractToRef=function(i,e){return e.r=this.r-i.r,e.g=this.g-i.g,e.b=this.b-i.b,e.a=this.a-i.a,this},a.prototype.scale=function(i){return new a(this.r*i,this.g*i,this.b*i,this.a*i)},a.prototype.scaleToRef=function(i,e){return e.r=this.r*i,e.g=this.g*i,e.b=this.b*i,e.a=this.a*i,this},a.prototype.scaleAndAddToRef=function(i,e){return e.r+=this.r*i,e.g+=this.g*i,e.b+=this.b*i,e.a+=this.a*i,this},a.prototype.clampToRef=function(i,e,o){return i===void 0&&(i=0),e===void 0&&(e=1),o.r=Scalar.Clamp(this.r,i,e),o.g=Scalar.Clamp(this.g,i,e),o.b=Scalar.Clamp(this.b,i,e),o.a=Scalar.Clamp(this.a,i,e),this},a.prototype.multiply=function(i){return new a(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},a.prototype.multiplyToRef=function(i,e){return e.r=this.r*i.r,e.g=this.g*i.g,e.b=this.b*i.b,e.a=this.a*i.a,e},a.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},a.prototype.getClassName=function(){return"Color4"},a.prototype.getHashCode=function(){var i=this.r*255|0;return i=i*397^(this.g*255|0),i=i*397^(this.b*255|0),i=i*397^(this.a*255|0),i},a.prototype.clone=function(){return new a(this.r,this.g,this.b,this.a)},a.prototype.copyFrom=function(i){return this.r=i.r,this.g=i.g,this.b=i.b,this.a=i.a,this},a.prototype.copyFromFloats=function(i,e,o,s){return this.r=i,this.g=e,this.b=o,this.a=s,this},a.prototype.set=function(i,e,o,s){return this.copyFromFloats(i,e,o,s)},a.prototype.toHexString=function(i){i===void 0&&(i=!1);var e=Math.round(this.r*255),o=Math.round(this.g*255),s=Math.round(this.b*255);if(i)return"#"+Scalar.ToHex(e)+Scalar.ToHex(o)+Scalar.ToHex(s);var c=Math.round(this.a*255);return"#"+Scalar.ToHex(e)+Scalar.ToHex(o)+Scalar.ToHex(s)+Scalar.ToHex(c)},a.prototype.toLinearSpace=function(){var i=new a;return this.toLinearSpaceToRef(i),i},a.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,ToLinearSpace),i.g=Math.pow(this.g,ToLinearSpace),i.b=Math.pow(this.b,ToLinearSpace),i.a=this.a,this},a.prototype.toGammaSpace=function(){var i=new a;return this.toGammaSpaceToRef(i),i},a.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,ToGammaSpace),i.g=Math.pow(this.g,ToGammaSpace),i.b=Math.pow(this.b,ToGammaSpace),i.a=this.a,this},a.FromHexString=function(i){if(i.substring(0,1)!=="#"||i.length!==9&&i.length!==7)return new a(0,0,0,0);var e=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16),c=i.length===9?parseInt(i.substring(7,9),16):255;return a.FromInts(e,o,s,c)},a.Lerp=function(i,e,o){var s=new a(0,0,0,0);return a.LerpToRef(i,e,o,s),s},a.LerpToRef=function(i,e,o,s){s.r=i.r+(e.r-i.r)*o,s.g=i.g+(e.g-i.g)*o,s.b=i.b+(e.b-i.b)*o,s.a=i.a+(e.a-i.a)*o},a.Hermite=function(i,e,o,s,c){var d=c*c,_=c*d,b=2*_-3*d+1,k=-2*_+3*d,j=_-2*d+c,$=_-d,_e=i.r*b+o.r*k+e.r*j+s.r*$,et=i.g*b+o.g*k+e.g*j+s.g*$,tt=i.b*b+o.b*k+e.b*j+s.b*$,rt=i.a*b+o.a*k+e.a*j+s.a*$;return new a(_e,et,tt,rt)},a.Hermite1stDerivative=function(i,e,o,s,c){var d=new a;return this.Hermite1stDerivativeToRef(i,e,o,s,c,d),d},a.Hermite1stDerivativeToRef=function(i,e,o,s,c,d){var _=c*c;d.r=(_-c)*6*i.r+(3*_-4*c+1)*e.r+(-_+c)*6*o.r+(3*_-2*c)*s.r,d.g=(_-c)*6*i.g+(3*_-4*c+1)*e.g+(-_+c)*6*o.g+(3*_-2*c)*s.g,d.b=(_-c)*6*i.b+(3*_-4*c+1)*e.b+(-_+c)*6*o.b+(3*_-2*c)*s.b,d.a=(_-c)*6*i.a+(3*_-4*c+1)*e.a+(-_+c)*6*o.a+(3*_-2*c)*s.a},a.FromColor3=function(i,e){return e===void 0&&(e=1),new a(i.r,i.g,i.b,e)},a.FromArray=function(i,e){return e===void 0&&(e=0),new a(i[e],i[e+1],i[e+2],i[e+3])},a.FromArrayToRef=function(i,e,o){e===void 0&&(e=0),o.r=i[e],o.g=i[e+1],o.b=i[e+2],o.a=i[e+3]},a.FromInts=function(i,e,o,s){return new a(i/255,e/255,o/255,s/255)},a.CheckColors4=function(i,e){if(i.length===e*3){for(var o=[],s=0;s<i.length;s+=3){var c=s/3*4;o[c]=i[s],o[c+1]=i[s+1],o[c+2]=i[s+2],o[c+3]=1}return o}return i},a}(),TmpColors=function(){function a(){}return a.Color3=ArrayTools.BuildArray(3,Color3.Black),a.Color4=ArrayTools.BuildArray(3,function(){return new Color4(0,0,0,0)}),a}();RegisterClass("BABYLON.Color3",Color3);RegisterClass("BABYLON.Color4",Color4);var AndOrNotEvaluator=function(){function a(){}return a.Eval=function(i,e){return i.match(/\([^\(\)]*\)/g)?i=i.replace(/\([^\(\)]*\)/g,function(o){return o=o.slice(1,o.length-1),a._HandleParenthesisContent(o,e)}):i=a._HandleParenthesisContent(i,e),i==="true"?!0:i==="false"?!1:a.Eval(i,e)},a._HandleParenthesisContent=function(i,e){e=e||function(j){return j==="true"};var o,s=i.split("||");for(var c in s)if(s.hasOwnProperty(c)){var d=a._SimplifyNegation(s[c].trim()),_=d.split("&&");if(_.length>1)for(var b=0;b<_.length;++b){var k=a._SimplifyNegation(_[b].trim());if(k!=="true"&&k!=="false"?k[0]==="!"?o=!e(k.substring(1)):o=e(k):o=k==="true",!o){d="false";break}}if(o||d==="true"){o=!0;break}d!=="true"&&d!=="false"?d[0]==="!"?o=!e(d.substring(1)):o=e(d):o=d==="true"}return o?"true":"false"},a._SimplifyNegation=function(i){return i=i.replace(/^[\s!]+/,function(e){return e=e.replace(/[\s]/g,function(){return""}),e.length%2?"!":""}),i=i.trim(),i==="!true"?i="false":i==="!false"&&(i="true"),i},a}(),Tags=function(){function a(){}return a.EnableFor=function(i){i._tags=i._tags||{},i.hasTags=function(){return a.HasTags(i)},i.addTags=function(e){return a.AddTagsTo(i,e)},i.removeTags=function(e){return a.RemoveTagsFrom(i,e)},i.matchesTagsQuery=function(e){return a.MatchesQuery(i,e)}},a.DisableFor=function(i){delete i._tags,delete i.hasTags,delete i.addTags,delete i.removeTags,delete i.matchesTagsQuery},a.HasTags=function(i){if(!i._tags)return!1;var e=i._tags;for(var o in e)if(e.hasOwnProperty(o))return!0;return!1},a.GetTags=function(i,e){if(e===void 0&&(e=!0),!i._tags)return null;if(e){var o=[];for(var s in i._tags)i._tags.hasOwnProperty(s)&&i._tags[s]===!0&&o.push(s);return o.join(" ")}else return i._tags},a.AddTagsTo=function(i,e){if(!!e&&typeof e=="string"){var o=e.split(" ");o.forEach(function(s,c,d){a._AddTagTo(i,s)})}},a._AddTagTo=function(i,e){e=e.trim(),!(e===""||e==="true"||e==="false")&&(e.match(/[\s]/)||e.match(/^([!]|([|]|[&]){2})/)||(a.EnableFor(i),i._tags[e]=!0))},a.RemoveTagsFrom=function(i,e){if(!!a.HasTags(i)){var o=e.split(" ");for(var s in o)a._RemoveTagFrom(i,o[s])}},a._RemoveTagFrom=function(i,e){delete i._tags[e]},a.MatchesQuery=function(i,e){return e===void 0?!0:e===""?a.HasTags(i):AndOrNotEvaluator.Eval(e,function(o){return a.HasTags(i)&&i._tags[o]})},a}(),__decoratorInitialStore$1={},__mergedStore$1={},_copySource$1=function(a,i,e){var o=a();Tags&&Tags.AddTagsTo(o,i.tags);var s=getMergedStore(o);for(var c in s){var d=s[c],_=i[c],b=d.type;if(_!=null&&(c!=="uniqueId"||SerializationHelper.AllowLoadingUniqueId))switch(b){case 0:case 6:case 11:o[c]=_;break;case 1:o[c]=e||_.isRenderTarget?_:_.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:o[c]=e?_:_.clone();break}}return o};function getDirectStore$1(a){var i=a.getClassName();return __decoratorInitialStore$1[i]||(__decoratorInitialStore$1[i]={}),__decoratorInitialStore$1[i]}function getMergedStore(a){var i=a.getClassName();if(__mergedStore$1[i])return __mergedStore$1[i];__mergedStore$1[i]={};for(var e=__mergedStore$1[i],o=a,s=i;s;){var c=__decoratorInitialStore$1[s];for(var d in c)e[d]=c[d];var _=void 0,b=!1;do{if(_=Object.getPrototypeOf(o),!_.getClassName){b=!0;break}if(_.getClassName()!==s)break;o=_}while(_);if(b)break;s=_.getClassName(),o=_}return e}function generateSerializableMember$1(a,i){return function(e,o){var s=getDirectStore$1(e);s[o]||(s[o]={type:a,sourceName:i})}}function generateExpandMember(a,i){return i===void 0&&(i=null),function(e,o){var s=i||"_"+o;Object.defineProperty(e,o,{get:function(){return this[s]},set:function(c){this[s]!==c&&(this[s]=c,e[a].apply(this))},enumerable:!0,configurable:!0})}}function expandToProperty(a,i){return i===void 0&&(i=null),generateExpandMember(a,i)}function serialize(a){return generateSerializableMember$1(0,a)}function serializeAsTexture(a){return generateSerializableMember$1(1,a)}function serializeAsColor3(a){return generateSerializableMember$1(2,a)}function serializeAsFresnelParameters(a){return generateSerializableMember$1(3,a)}function serializeAsVector2(a){return generateSerializableMember$1(4,a)}function serializeAsVector3(a){return generateSerializableMember$1(5,a)}function serializeAsMeshReference(a){return generateSerializableMember$1(6,a)}function serializeAsColorCurves(a){return generateSerializableMember$1(7,a)}function serializeAsColor4(a){return generateSerializableMember$1(8,a)}function serializeAsImageProcessingConfiguration(a){return generateSerializableMember$1(9,a)}function serializeAsQuaternion(a){return generateSerializableMember$1(10,a)}function serializeAsMatrix(a){return generateSerializableMember$1(12,a)}function serializeAsCameraReference(a){return generateSerializableMember$1(11,a)}var SerializationHelper=function(){function a(){}return a.AppendSerializedAnimations=function(i,e){if(i.animations){e.animations=[];for(var o=0;o<i.animations.length;o++){var s=i.animations[o];e.animations.push(s.serialize())}}},a.Serialize=function(i,e){e||(e={}),Tags&&(e.tags=Tags.GetTags(i));var o=getMergedStore(i);for(var s in o){var c=o[s],d=c.sourceName||s,_=c.type,b=i[s];if(b!=null&&(s!=="uniqueId"||a.AllowLoadingUniqueId))switch(_){case 0:e[d]=b;break;case 1:e[d]=b.serialize();break;case 2:e[d]=b.asArray();break;case 3:e[d]=b.serialize();break;case 4:e[d]=b.asArray();break;case 5:e[d]=b.asArray();break;case 6:e[d]=b.id;break;case 7:e[d]=b.serialize();break;case 8:e[d]=b.asArray();break;case 9:e[d]=b.serialize();break;case 10:e[d]=b.asArray();break;case 11:e[d]=b.id;break;case 12:e[d]=b.asArray();break}}return e},a.Parse=function(i,e,o,s){s===void 0&&(s=null);var c=i();s||(s=""),Tags&&Tags.AddTagsTo(c,e.tags);var d=getMergedStore(c);for(var _ in d){var b=d[_],k=e[b.sourceName||_],j=b.type;if(k!=null&&(_!=="uniqueId"||a.AllowLoadingUniqueId)){var $=c;switch(j){case 0:$[_]=k;break;case 1:o&&($[_]=a._TextureParser(k,o,s));break;case 2:$[_]=Color3.FromArray(k);break;case 3:$[_]=a._FresnelParametersParser(k);break;case 4:$[_]=Vector2.FromArray(k);break;case 5:$[_]=Vector3.FromArray(k);break;case 6:o&&($[_]=o.getLastMeshById(k));break;case 7:$[_]=a._ColorCurvesParser(k);break;case 8:$[_]=Color4.FromArray(k);break;case 9:$[_]=a._ImageProcessingConfigurationParser(k);break;case 10:$[_]=Quaternion.FromArray(k);break;case 11:o&&($[_]=o.getCameraById(k));case 12:$[_]=Matrix.FromArray(k);break}}}return c},a.Clone=function(i,e){return _copySource$1(i,e,!1)},a.Instanciate=function(i,e){return _copySource$1(i,e,!0)},a.AllowLoadingUniqueId=!1,a._ImageProcessingConfigurationParser=function(i){throw _WarnImport("ImageProcessingConfiguration")},a._FresnelParametersParser=function(i){throw _WarnImport("FresnelParameters")},a._ColorCurvesParser=function(i){throw _WarnImport("ColorCurves")},a._TextureParser=function(i,e,o){throw _WarnImport("Texture")},a}();function nativeOverride(a,i,e,o){var s=e.value;e.value=function(){for(var c=[],d=0;d<arguments.length;d++)c[d]=arguments[d];var _=s;if(typeof _native!="undefined"&&_native[i]){var b=_native[i];o?_=function(){for(var k=[],j=0;j<arguments.length;j++)k[j]=arguments[j];return o.apply(void 0,k)?b.apply(void 0,k):s.apply(void 0,k)}:_=b}return a[i]=_,_.apply(void 0,c)}}nativeOverride.filter=function(a){return function(i,e,o){return nativeOverride(i,e,o,a)}};function inlineScheduler(a,i,e){try{var o=a.next();o.done?i(o):o.value?o.value.then(function(){o.value=void 0,i(o)},e):i(o)}catch(s){e(s)}}function createYieldingScheduler(a){a===void 0&&(a=25);var i;return function(e,o,s){var c=performance.now();i===void 0||c-i>a?(i=c,setTimeout(function(){inlineScheduler(e,o,s)},0)):inlineScheduler(e,o,s)}}function runCoroutine(a,i,e,o,s){var c=function(){var d,_=function(b){b.done?e(b.value):d===void 0?d=!0:c()};do d=void 0,!s||!s.aborted?i(a,_,o):o(new Error("Aborted")),d===void 0&&(d=!1);while(d)};c()}function runCoroutineSync(a,i){var e;return runCoroutine(a,inlineScheduler,function(o){return e=o},function(o){throw o},i),e}function runCoroutineAsync(a,i,e){return new Promise(function(o,s){runCoroutine(a,i,o,s,e)})}function makeSyncFunction(a,i){return function(){for(var e=[],o=0;o<arguments.length;o++)e[o]=arguments[o];return runCoroutineSync(a.apply(void 0,e),i)}}var VertexData=function(){function a(){this._applyTo=makeSyncFunction(this._applyToCoroutine.bind(this))}return a.prototype.set=function(i,e){switch(i.length||Logger$2.Warn("Setting vertex data kind '"+e+"' with an empty array"),e){case VertexBuffer.PositionKind:this.positions=i;break;case VertexBuffer.NormalKind:this.normals=i;break;case VertexBuffer.TangentKind:this.tangents=i;break;case VertexBuffer.UVKind:this.uvs=i;break;case VertexBuffer.UV2Kind:this.uvs2=i;break;case VertexBuffer.UV3Kind:this.uvs3=i;break;case VertexBuffer.UV4Kind:this.uvs4=i;break;case VertexBuffer.UV5Kind:this.uvs5=i;break;case VertexBuffer.UV6Kind:this.uvs6=i;break;case VertexBuffer.ColorKind:this.colors=i;break;case VertexBuffer.MatricesIndicesKind:this.matricesIndices=i;break;case VertexBuffer.MatricesWeightsKind:this.matricesWeights=i;break;case VertexBuffer.MatricesIndicesExtraKind:this.matricesIndicesExtra=i;break;case VertexBuffer.MatricesWeightsExtraKind:this.matricesWeightsExtra=i;break}},a.prototype.applyToMesh=function(i,e){return this._applyTo(i,e,!1),this},a.prototype.applyToGeometry=function(i,e){return this._applyTo(i,e,!1),this},a.prototype.updateMesh=function(i){return this._update(i),this},a.prototype.updateGeometry=function(i){return this._update(i),this},a.prototype._applyToCoroutine=function(i,e,o){return e===void 0&&(e=!1),__generator(this,function(s){switch(s.label){case 0:return this.positions?(i.setVerticesData(VertexBuffer.PositionKind,this.positions,e),o?[4]:[3,2]):[3,2];case 1:s.sent(),s.label=2;case 2:return this.normals?(i.setVerticesData(VertexBuffer.NormalKind,this.normals,e),o?[4]:[3,4]):[3,4];case 3:s.sent(),s.label=4;case 4:return this.tangents?(i.setVerticesData(VertexBuffer.TangentKind,this.tangents,e),o?[4]:[3,6]):[3,6];case 5:s.sent(),s.label=6;case 6:return this.uvs?(i.setVerticesData(VertexBuffer.UVKind,this.uvs,e),o?[4]:[3,8]):[3,8];case 7:s.sent(),s.label=8;case 8:return this.uvs2?(i.setVerticesData(VertexBuffer.UV2Kind,this.uvs2,e),o?[4]:[3,10]):[3,10];case 9:s.sent(),s.label=10;case 10:return this.uvs3?(i.setVerticesData(VertexBuffer.UV3Kind,this.uvs3,e),o?[4]:[3,12]):[3,12];case 11:s.sent(),s.label=12;case 12:return this.uvs4?(i.setVerticesData(VertexBuffer.UV4Kind,this.uvs4,e),o?[4]:[3,14]):[3,14];case 13:s.sent(),s.label=14;case 14:return this.uvs5?(i.setVerticesData(VertexBuffer.UV5Kind,this.uvs5,e),o?[4]:[3,16]):[3,16];case 15:s.sent(),s.label=16;case 16:return this.uvs6?(i.setVerticesData(VertexBuffer.UV6Kind,this.uvs6,e),o?[4]:[3,18]):[3,18];case 17:s.sent(),s.label=18;case 18:return this.colors?(i.setVerticesData(VertexBuffer.ColorKind,this.colors,e),o?[4]:[3,20]):[3,20];case 19:s.sent(),s.label=20;case 20:return this.matricesIndices?(i.setVerticesData(VertexBuffer.MatricesIndicesKind,this.matricesIndices,e),o?[4]:[3,22]):[3,22];case 21:s.sent(),s.label=22;case 22:return this.matricesWeights?(i.setVerticesData(VertexBuffer.MatricesWeightsKind,this.matricesWeights,e),o?[4]:[3,24]):[3,24];case 23:s.sent(),s.label=24;case 24:return this.matricesIndicesExtra?(i.setVerticesData(VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,e),o?[4]:[3,26]):[3,26];case 25:s.sent(),s.label=26;case 26:return this.matricesWeightsExtra?(i.setVerticesData(VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,e),o?[4]:[3,28]):[3,28];case 27:s.sent(),s.label=28;case 28:return this.indices?(i.setIndices(this.indices,null,e),o?[4]:[3,30]):[3,31];case 29:s.sent(),s.label=30;case 30:return[3,32];case 31:i.setIndices([],null),s.label=32;case 32:return[2,this]}})},a.prototype._update=function(i,e,o){return this.positions&&i.updateVerticesData(VertexBuffer.PositionKind,this.positions,e,o),this.normals&&i.updateVerticesData(VertexBuffer.NormalKind,this.normals,e,o),this.tangents&&i.updateVerticesData(VertexBuffer.TangentKind,this.tangents,e,o),this.uvs&&i.updateVerticesData(VertexBuffer.UVKind,this.uvs,e,o),this.uvs2&&i.updateVerticesData(VertexBuffer.UV2Kind,this.uvs2,e,o),this.uvs3&&i.updateVerticesData(VertexBuffer.UV3Kind,this.uvs3,e,o),this.uvs4&&i.updateVerticesData(VertexBuffer.UV4Kind,this.uvs4,e,o),this.uvs5&&i.updateVerticesData(VertexBuffer.UV5Kind,this.uvs5,e,o),this.uvs6&&i.updateVerticesData(VertexBuffer.UV6Kind,this.uvs6,e,o),this.colors&&i.updateVerticesData(VertexBuffer.ColorKind,this.colors,e,o),this.matricesIndices&&i.updateVerticesData(VertexBuffer.MatricesIndicesKind,this.matricesIndices,e,o),this.matricesWeights&&i.updateVerticesData(VertexBuffer.MatricesWeightsKind,this.matricesWeights,e,o),this.matricesIndicesExtra&&i.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,o),this.matricesWeightsExtra&&i.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,o),this.indices&&i.setIndices(this.indices,null),this},a._TransformVector3Coordinates=function(i,e){for(var o=TmpVectors.Vector3[0],s=TmpVectors.Vector3[1],c=0;c<i.length;c+=3)Vector3.FromArrayToRef(i,c,o),Vector3.TransformCoordinatesToRef(o,e,s),i[c]=s.x,i[c+1]=s.y,i[c+2]=s.z},a._TransformVector3Normals=function(i,e){for(var o=TmpVectors.Vector3[0],s=TmpVectors.Vector3[1],c=0;c<i.length;c+=3)Vector3.FromArrayToRef(i,c,o),Vector3.TransformNormalToRef(o,e,s),i[c]=s.x,i[c+1]=s.y,i[c+2]=s.z},a._TransformVector4Normals=function(i,e){for(var o=TmpVectors.Vector4[0],s=TmpVectors.Vector4[1],c=0;c<i.length;c+=4)Vector4.FromArrayToRef(i,c,o),Vector4.TransformNormalToRef(o,e,s),i[c]=s.x,i[c+1]=s.y,i[c+2]=s.z,i[c+3]=s.w},a._FlipFaces=function(i){for(var e=0;e<i.length;e+=3){var o=i[e+1];i[e+1]=i[e+2],i[e+2]=o}},a.prototype.transform=function(i){var e=i.determinant()<0;return this.positions&&a._TransformVector3Coordinates(this.positions,i),this.normals&&a._TransformVector3Normals(this.normals,i),this.tangents&&a._TransformVector4Normals(this.tangents,i),e&&this.indices&&a._FlipFaces(this.indices),this},a.prototype.merge=function(i,e){return e===void 0&&(e=!1),runCoroutineSync(this._mergeCoroutine(i,e,!1))},a.prototype._mergeCoroutine=function(i,e,o){var s,c,_e,d,_,b,k,j,$,_e,et,tt,rt,it,nt;return e===void 0&&(e=!1),__generator(this,function(ot){switch(ot.label){case 0:for(this._validate(),i=Array.isArray(i)?i:[i],s=0,c=i;s<c.length;s++)if(_e=c[s],_e._validate(),!this.normals!=!_e.normals||!this.tangents!=!_e.tangents||!this.uvs!=!_e.uvs||!this.uvs2!=!_e.uvs2||!this.uvs3!=!_e.uvs3||!this.uvs4!=!_e.uvs4||!this.uvs5!=!_e.uvs5||!this.uvs6!=!_e.uvs6||!this.colors!=!_e.colors||!this.matricesIndices!=!_e.matricesIndices||!this.matricesWeights!=!_e.matricesWeights||!this.matricesIndicesExtra!=!_e.matricesIndicesExtra||!this.matricesWeightsExtra!=!_e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(d=i.reduce(function(at,st){var ut,ft;return at+((ft=(ut=st.indices)===null||ut===void 0?void 0:ut.length)!==null&&ft!==void 0?ft:0)},(rt=(tt=this.indices)===null||tt===void 0?void 0:tt.length)!==null&&rt!==void 0?rt:0),!(d>0))return[3,4];_=(nt=(it=this.indices)===null||it===void 0?void 0:it.length)!==null&&nt!==void 0?nt:0,this.indices||(this.indices=new Array(d)),this.indices.length!==d&&(Array.isArray(this.indices)?this.indices.length=d:(b=e||this.indices instanceof Uint32Array?new Uint32Array(d):new Uint16Array(d),b.set(this.indices),this.indices=b)),k=this.positions?this.positions.length/3:0,j=0,$=i,ot.label=1;case 1:if(!(j<$.length))return[3,4];if(_e=$[j],!_e.indices)return[3,3];for(et=0;et<_e.indices.length;et++)this.indices[_+et]=_e.indices[et]+k;return k+=_e.positions.length/3,_+=_e.indices.length,o?[4]:[3,3];case 2:ot.sent(),ot.label=3;case 3:return j++,[3,1];case 4:return this.positions=a._mergeElement(this.positions,i.map(function(at){return at.positions})),o?[4]:[3,6];case 5:ot.sent(),ot.label=6;case 6:return this.normals=a._mergeElement(this.normals,i.map(function(at){return at.normals})),o?[4]:[3,8];case 7:ot.sent(),ot.label=8;case 8:return this.tangents=a._mergeElement(this.tangents,i.map(function(at){return at.tangents})),o?[4]:[3,10];case 9:ot.sent(),ot.label=10;case 10:return this.uvs=a._mergeElement(this.uvs,i.map(function(at){return at.uvs})),o?[4]:[3,12];case 11:ot.sent(),ot.label=12;case 12:return this.uvs2=a._mergeElement(this.uvs2,i.map(function(at){return at.uvs2})),o?[4]:[3,14];case 13:ot.sent(),ot.label=14;case 14:return this.uvs3=a._mergeElement(this.uvs3,i.map(function(at){return at.uvs3})),o?[4]:[3,16];case 15:ot.sent(),ot.label=16;case 16:return this.uvs4=a._mergeElement(this.uvs4,i.map(function(at){return at.uvs4})),o?[4]:[3,18];case 17:ot.sent(),ot.label=18;case 18:return this.uvs5=a._mergeElement(this.uvs5,i.map(function(at){return at.uvs5})),o?[4]:[3,20];case 19:ot.sent(),ot.label=20;case 20:return this.uvs6=a._mergeElement(this.uvs6,i.map(function(at){return at.uvs6})),o?[4]:[3,22];case 21:ot.sent(),ot.label=22;case 22:return this.colors=a._mergeElement(this.colors,i.map(function(at){return at.colors})),o?[4]:[3,24];case 23:ot.sent(),ot.label=24;case 24:return this.matricesIndices=a._mergeElement(this.matricesIndices,i.map(function(at){return at.matricesIndices})),o?[4]:[3,26];case 25:ot.sent(),ot.label=26;case 26:return this.matricesWeights=a._mergeElement(this.matricesWeights,i.map(function(at){return at.matricesWeights})),o?[4]:[3,28];case 27:ot.sent(),ot.label=28;case 28:return this.matricesIndicesExtra=a._mergeElement(this.matricesIndicesExtra,i.map(function(at){return at.matricesIndicesExtra})),o?[4]:[3,30];case 29:ot.sent(),ot.label=30;case 30:return this.matricesWeightsExtra=a._mergeElement(this.matricesWeightsExtra,i.map(function(at){return at.matricesWeightsExtra})),[2,this]}})},a._mergeElement=function(i,e){var o=e.filter(function(tt){return tt!=null});if(o.length===0)return i;if(!i)return this._mergeElement(o[0],o.slice(1));var s=o.reduce(function(tt,rt){return tt+rt.length},i.length);if(i instanceof Float32Array){var c=new Float32Array(s);c.set(i);for(var d=i.length,_=0,b=o;_<b.length;_++){var k=b[_];c.set(k,d),d+=k.length}return c}else{for(var j=new Array(s),$=0;$<i.length;$++)j[$]=i[$];for(var d=i.length,_e=0,et=o;_e<et.length;_e++){for(var k=et[_e],$=0;$<k.length;$++)j[d+$]=k[$];d+=k.length}return j}},a.prototype._validate=function(){if(!this.positions)throw new Error("Positions are required");var i=function(s,c){var d=VertexBuffer.DeduceStride(s);if(c.length%d!==0)throw new Error("The "+s+"s array count must be a multiple of "+d);return c.length/d},e=i(VertexBuffer.PositionKind,this.positions),o=function(s,c){var d=i(s,c);if(d!==e)throw new Error("The "+s+"s element count ("+d+") does not match the positions count ("+e+")")};this.normals&&o(VertexBuffer.NormalKind,this.normals),this.tangents&&o(VertexBuffer.TangentKind,this.tangents),this.uvs&&o(VertexBuffer.UVKind,this.uvs),this.uvs2&&o(VertexBuffer.UV2Kind,this.uvs2),this.uvs3&&o(VertexBuffer.UV3Kind,this.uvs3),this.uvs4&&o(VertexBuffer.UV4Kind,this.uvs4),this.uvs5&&o(VertexBuffer.UV5Kind,this.uvs5),this.uvs6&&o(VertexBuffer.UV6Kind,this.uvs6),this.colors&&o(VertexBuffer.ColorKind,this.colors),this.matricesIndices&&o(VertexBuffer.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&o(VertexBuffer.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&o(VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&o(VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra)},a.prototype.serialize=function(){var i={};return this.positions&&(i.positions=this.positions),this.normals&&(i.normals=this.normals),this.tangents&&(i.tangents=this.tangents),this.uvs&&(i.uvs=this.uvs),this.uvs2&&(i.uvs2=this.uvs2),this.uvs3&&(i.uvs3=this.uvs3),this.uvs4&&(i.uvs4=this.uvs4),this.uvs5&&(i.uvs5=this.uvs5),this.uvs6&&(i.uvs6=this.uvs6),this.colors&&(i.colors=this.colors),this.matricesIndices&&(i.matricesIndices=this.matricesIndices,i.matricesIndices._isExpanded=!0),this.matricesWeights&&(i.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra,i.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra),i.indices=this.indices,i},a.ExtractFromMesh=function(i,e,o){return a._ExtractFrom(i,e,o)},a.ExtractFromGeometry=function(i,e,o){return a._ExtractFrom(i,e,o)},a._ExtractFrom=function(i,e,o){var s=new a;return i.isVerticesDataPresent(VertexBuffer.PositionKind)&&(s.positions=i.getVerticesData(VertexBuffer.PositionKind,e,o)),i.isVerticesDataPresent(VertexBuffer.NormalKind)&&(s.normals=i.getVerticesData(VertexBuffer.NormalKind,e,o)),i.isVerticesDataPresent(VertexBuffer.TangentKind)&&(s.tangents=i.getVerticesData(VertexBuffer.TangentKind,e,o)),i.isVerticesDataPresent(VertexBuffer.UVKind)&&(s.uvs=i.getVerticesData(VertexBuffer.UVKind,e,o)),i.isVerticesDataPresent(VertexBuffer.UV2Kind)&&(s.uvs2=i.getVerticesData(VertexBuffer.UV2Kind,e,o)),i.isVerticesDataPresent(VertexBuffer.UV3Kind)&&(s.uvs3=i.getVerticesData(VertexBuffer.UV3Kind,e,o)),i.isVerticesDataPresent(VertexBuffer.UV4Kind)&&(s.uvs4=i.getVerticesData(VertexBuffer.UV4Kind,e,o)),i.isVerticesDataPresent(VertexBuffer.UV5Kind)&&(s.uvs5=i.getVerticesData(VertexBuffer.UV5Kind,e,o)),i.isVerticesDataPresent(VertexBuffer.UV6Kind)&&(s.uvs6=i.getVerticesData(VertexBuffer.UV6Kind,e,o)),i.isVerticesDataPresent(VertexBuffer.ColorKind)&&(s.colors=i.getVerticesData(VertexBuffer.ColorKind,e,o)),i.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)&&(s.matricesIndices=i.getVerticesData(VertexBuffer.MatricesIndicesKind,e,o)),i.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)&&(s.matricesWeights=i.getVerticesData(VertexBuffer.MatricesWeightsKind,e,o)),i.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=i.getVerticesData(VertexBuffer.MatricesIndicesExtraKind,e,o)),i.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=i.getVerticesData(VertexBuffer.MatricesWeightsExtraKind,e,o)),s.indices=i.getIndices(e,o),s},a.CreateRibbon=function(i){throw _WarnImport("ribbonBuilder")},a.CreateBox=function(i){throw _WarnImport("boxBuilder")},a.CreateTiledBox=function(i){throw _WarnImport("tiledBoxBuilder")},a.CreateTiledPlane=function(i){throw _WarnImport("tiledPlaneBuilder")},a.CreateSphere=function(i){throw _WarnImport("sphereBuilder")},a.CreateCylinder=function(i){throw _WarnImport("cylinderBuilder")},a.CreateTorus=function(i){throw _WarnImport("torusBuilder")},a.CreateLineSystem=function(i){throw _WarnImport("linesBuilder")},a.CreateDashedLines=function(i){throw _WarnImport("linesBuilder")},a.CreateGround=function(i){throw _WarnImport("groundBuilder")},a.CreateTiledGround=function(i){throw _WarnImport("groundBuilder")},a.CreateGroundFromHeightMap=function(i){throw _WarnImport("groundBuilder")},a.CreatePlane=function(i){throw _WarnImport("planeBuilder")},a.CreateDisc=function(i){throw _WarnImport("discBuilder")},a.CreatePolygon=function(i,e,o,s,c,d,_){throw _WarnImport("polygonBuilder")},a.CreateIcoSphere=function(i){throw _WarnImport("icoSphereBuilder")},a.CreatePolyhedron=function(i){throw _WarnImport("polyhedronBuilder")},a.CreateCapsule=function(i){throw i===void 0&&(i={orientation:Vector3.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}),_WarnImport("capsuleBuilder")},a.CreateTorusKnot=function(i){throw _WarnImport("torusKnotBuilder")},a.ComputeNormals=function(i,e,o,s){var c=0,d=0,_=0,b=0,k=0,j=0,$=0,_e=0,et=0,tt=0,rt=0,it=0,nt=0,ot=0,at=0,st=0,ut=0,ft=0,lt=0,ht=0,pt=!1,mt=!1,dt=!1,gt=!1,_t=1,yt=0,Tt=null;if(s&&(pt=!!s.facetNormals,mt=!!s.facetPositions,dt=!!s.facetPartitioning,_t=s.useRightHandedSystem===!0?-1:1,yt=s.ratio||0,gt=!!s.depthSort,Tt=s.distanceTo,gt)){Tt===void 0&&(Tt=Vector3.Zero());var St=s.depthSortedFacets}var At=0,vt=0,Et=0,xt=0;if(dt&&s&&s.bbSize){var bt=0,Mt=0,Rt=0,Pt=0,It=0,Dt=0,Ct=0,Ot=0,Ft=0,wt=0,Bt=0,Ut=0,Vt=0,Gt=0,Lt=0,Ht=0,Wt=s.bbSize.x>s.bbSize.y?s.bbSize.x:s.bbSize.y;Wt=Wt>s.bbSize.z?Wt:s.bbSize.z,At=s.subDiv.X*yt/s.bbSize.x,vt=s.subDiv.Y*yt/s.bbSize.y,Et=s.subDiv.Z*yt/s.bbSize.z,xt=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0}for(c=0;c<i.length;c++)o[c]=0;var Yt=e.length/3|0;for(c=0;c<Yt;c++){if(it=e[c*3]*3,nt=it+1,ot=it+2,at=e[c*3+1]*3,st=at+1,ut=at+2,ft=e[c*3+2]*3,lt=ft+1,ht=ft+2,d=i[it]-i[at],_=i[nt]-i[st],b=i[ot]-i[ut],k=i[ft]-i[at],j=i[lt]-i[st],$=i[ht]-i[ut],_e=_t*(_*$-b*j),et=_t*(b*k-d*$),tt=_t*(d*j-_*k),rt=Math.sqrt(_e*_e+et*et+tt*tt),rt=rt===0?1:rt,_e/=rt,et/=rt,tt/=rt,pt&&s&&(s.facetNormals[c].x=_e,s.facetNormals[c].y=et,s.facetNormals[c].z=tt),mt&&s&&(s.facetPositions[c].x=(i[it]+i[at]+i[ft])/3,s.facetPositions[c].y=(i[nt]+i[st]+i[lt])/3,s.facetPositions[c].z=(i[ot]+i[ut]+i[ht])/3),dt&&s&&(bt=Math.floor((s.facetPositions[c].x-s.bInfo.minimum.x*yt)*At),Mt=Math.floor((s.facetPositions[c].y-s.bInfo.minimum.y*yt)*vt),Rt=Math.floor((s.facetPositions[c].z-s.bInfo.minimum.z*yt)*Et),Pt=Math.floor((i[it]-s.bInfo.minimum.x*yt)*At),It=Math.floor((i[nt]-s.bInfo.minimum.y*yt)*vt),Dt=Math.floor((i[ot]-s.bInfo.minimum.z*yt)*Et),Ct=Math.floor((i[at]-s.bInfo.minimum.x*yt)*At),Ot=Math.floor((i[st]-s.bInfo.minimum.y*yt)*vt),Ft=Math.floor((i[ut]-s.bInfo.minimum.z*yt)*Et),wt=Math.floor((i[ft]-s.bInfo.minimum.x*yt)*At),Bt=Math.floor((i[lt]-s.bInfo.minimum.y*yt)*vt),Ut=Math.floor((i[ht]-s.bInfo.minimum.z*yt)*Et),Gt=Pt+s.subDiv.max*It+xt*Dt,Lt=Ct+s.subDiv.max*Ot+xt*Ft,Ht=wt+s.subDiv.max*Bt+xt*Ut,Vt=bt+s.subDiv.max*Mt+xt*Rt,s.facetPartitioning[Vt]=s.facetPartitioning[Vt]?s.facetPartitioning[Vt]:new Array,s.facetPartitioning[Gt]=s.facetPartitioning[Gt]?s.facetPartitioning[Gt]:new Array,s.facetPartitioning[Lt]=s.facetPartitioning[Lt]?s.facetPartitioning[Lt]:new Array,s.facetPartitioning[Ht]=s.facetPartitioning[Ht]?s.facetPartitioning[Ht]:new Array,s.facetPartitioning[Gt].push(c),Lt!=Gt&&s.facetPartitioning[Lt].push(c),Ht==Lt||Ht==Gt||s.facetPartitioning[Ht].push(c),Vt==Gt||Vt==Lt||Vt==Ht||s.facetPartitioning[Vt].push(c)),gt&&s&&s.facetPositions){var jt=St[c];jt.ind=c*3,jt.sqDistance=Vector3.DistanceSquared(s.facetPositions[c],Tt)}o[it]+=_e,o[nt]+=et,o[ot]+=tt,o[at]+=_e,o[st]+=et,o[ut]+=tt,o[ft]+=_e,o[lt]+=et,o[ht]+=tt}for(c=0;c<o.length/3;c++)_e=o[c*3],et=o[c*3+1],tt=o[c*3+2],rt=Math.sqrt(_e*_e+et*et+tt*tt),rt=rt===0?1:rt,_e/=rt,et/=rt,tt/=rt,o[c*3]=_e,o[c*3+1]=et,o[c*3+2]=tt},a._ComputeSides=function(i,e,o,s,c,d,_){var b=o.length,k=s.length,j,$;switch(i=i||a.DEFAULTSIDE,i){case a.FRONTSIDE:break;case a.BACKSIDE:var _e;for(j=0;j<b;j+=3)_e=o[j],o[j]=o[j+2],o[j+2]=_e;for($=0;$<k;$++)s[$]=-s[$];break;case a.DOUBLESIDE:for(var et=e.length,tt=et/3,rt=0;rt<et;rt++)e[et+rt]=e[rt];for(j=0;j<b;j+=3)o[j+b]=o[j+2]+tt,o[j+1+b]=o[j+1]+tt,o[j+2+b]=o[j]+tt;for($=0;$<k;$++)s[k+$]=-s[$];var it=c.length,nt=0;for(nt=0;nt<it;nt++)c[nt+it]=c[nt];for(d=d||new Vector4(0,0,1,1),_=_||new Vector4(0,0,1,1),nt=0,j=0;j<it/2;j++)c[nt]=d.x+(d.z-d.x)*c[nt],c[nt+1]=d.y+(d.w-d.y)*c[nt+1],c[nt+it]=_.x+(_.z-_.x)*c[nt+it],c[nt+it+1]=_.y+(_.w-_.y)*c[nt+it+1],nt+=2;break}},a.ImportVertexData=function(i,e){var o=new a,s=i.positions;s&&o.set(s,VertexBuffer.PositionKind);var c=i.normals;c&&o.set(c,VertexBuffer.NormalKind);var d=i.tangents;d&&o.set(d,VertexBuffer.TangentKind);var _=i.uvs;_&&o.set(_,VertexBuffer.UVKind);var b=i.uv2s;b&&o.set(b,VertexBuffer.UV2Kind);var k=i.uv3s;k&&o.set(k,VertexBuffer.UV3Kind);var j=i.uv4s;j&&o.set(j,VertexBuffer.UV4Kind);var $=i.uv5s;$&&o.set($,VertexBuffer.UV5Kind);var _e=i.uv6s;_e&&o.set(_e,VertexBuffer.UV6Kind);var et=i.colors;et&&o.set(Color4.CheckColors4(et,s.length/3),VertexBuffer.ColorKind);var tt=i.matricesIndices;tt&&o.set(tt,VertexBuffer.MatricesIndicesKind);var rt=i.matricesWeights;rt&&o.set(rt,VertexBuffer.MatricesWeightsKind);var it=i.indices;it&&(o.indices=it),e.setAllVerticesData(o,i.updatable)},a.FRONTSIDE=0,a.BACKSIDE=1,a.DOUBLESIDE=2,a.DEFAULTSIDE=0,__decorate([nativeOverride.filter(function(){for(var i=[],e=0;e<arguments.length;e++)i[e]=arguments[e];var o=i[0];return!Array.isArray(o)})],a,"_TransformVector3Coordinates",null),__decorate([nativeOverride.filter(function(){for(var i=[],e=0;e<arguments.length;e++)i[e]=arguments[e];var o=i[0];return!Array.isArray(o)})],a,"_TransformVector3Normals",null),__decorate([nativeOverride.filter(function(){for(var i=[],e=0;e<arguments.length;e++)i[e]=arguments[e];var o=i[0];return!Array.isArray(o)})],a,"_TransformVector4Normals",null),__decorate([nativeOverride.filter(function(){for(var i=[],e=0;e<arguments.length;e++)i[e]=arguments[e];var o=i[0];return!Array.isArray(o)})],a,"_FlipFaces",null),a}(),_InternalNodeDataInfo=function(){function a(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new Observable,this._onClonedObservable=new Observable}return a}(),Node$2=function(){function a(i,e){e===void 0&&(e=null),this._isDirty=!1,this._nodeDataStorage=new _InternalNodeDataInfo,this.state="",this.metadata=null,this.reservedDataStore=null,this._parentContainer=null,this.animations=new Array,this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=Matrix.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new Observable,this._onDisposeObserver=null,this._behaviors=new Array,this.name=i,this.id=i,this._scene=e||EngineStore.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return a.AddNodeConstructor=function(i,e){this._NodeConstructors[i]=e},a.Construct=function(i,e,o,s){var c=this._NodeConstructors[i];return c?c(e,o,s):null},Object.defineProperty(a.prototype,"doNotSerialize",{get:function(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1},set:function(i){this._nodeDataStorage._doNotSerialize=i},enumerable:!1,configurable:!0}),a.prototype.isDisposed=function(){return this._nodeDataStorage._isDisposed},Object.defineProperty(a.prototype,"parent",{get:function(){return this._parentNode},set:function(i){if(this._parentNode!==i){var e=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){var o=this._parentNode._children.indexOf(this);o!==-1&&this._parentNode._children.splice(o,1),!i&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=i,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),e||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}},enumerable:!1,configurable:!0}),a.prototype._addToSceneRootNodes=function(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))},a.prototype._removeFromSceneRootNodes=function(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){var i=this._scene.rootNodes,e=i.length-1;i[this._nodeDataStorage._sceneRootNodesIndex]=i[e],i[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}},Object.defineProperty(a.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(i){this._animationPropertiesOverride=i},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"Node"},Object.defineProperty(a.prototype,"onDispose",{set:function(i){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onEnabledStateChangedObservable",{get:function(){return this._nodeDataStorage._onEnabledStateChangedObservable},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onClonedObservable",{get:function(){return this._nodeDataStorage._onClonedObservable},enumerable:!1,configurable:!0}),a.prototype.getScene=function(){return this._scene},a.prototype.getEngine=function(){return this._scene.getEngine()},a.prototype.addBehavior=function(i,e){var o=this;e===void 0&&(e=!1);var s=this._behaviors.indexOf(i);return s!==-1?this:(i.init(),this._scene.isLoading&&!e?this._scene.onDataLoadedObservable.addOnce(function(){i.attach(o)}):i.attach(this),this._behaviors.push(i),this)},a.prototype.removeBehavior=function(i){var e=this._behaviors.indexOf(i);return e===-1?this:(this._behaviors[e].detach(),this._behaviors.splice(e,1),this)},Object.defineProperty(a.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!1,configurable:!0}),a.prototype.getBehaviorByName=function(i){for(var e=0,o=this._behaviors;e<o.length;e++){var s=o[e];if(s.name===i)return s}return null},a.prototype.getWorldMatrix=function(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix},a.prototype._getWorldMatrixDeterminant=function(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant},Object.defineProperty(a.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!1,configurable:!0}),a.prototype._initCache=function(){this._cache={},this._cache.parent=void 0},a.prototype.updateCache=function(i){!i&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())},a.prototype._getActionManagerForTrigger=function(i,e){return this.parent?this.parent._getActionManagerForTrigger(i,!1):null},a.prototype._updateCache=function(i){},a.prototype._isSynchronized=function(){return!0},a.prototype._markSyncedWithParent=function(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)},a.prototype.isSynchronizedWithParent=function(){return this._parentNode?this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0},a.prototype.isSynchronized=function(){return this._cache.parent!=this._parentNode?(this._cache.parent=this._parentNode,!1):this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()},a.prototype.isReady=function(i){return this._nodeDataStorage._isReady},a.prototype.markAsDirty=function(i){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},a.prototype.isEnabled=function(i){return i===void 0&&(i=!0),i===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1},a.prototype._syncParentEnabledState=function(){this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children&&this._children.forEach(function(i){i._syncParentEnabledState()})},a.prototype.setEnabled=function(i){this._nodeDataStorage._isEnabled!==i&&(this._nodeDataStorage._isEnabled=i,this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(i),this._syncParentEnabledState())},a.prototype.isDescendantOf=function(i){return this.parent?this.parent===i?!0:this.parent.isDescendantOf(i):!1},a.prototype._getDescendants=function(i,e,o){if(e===void 0&&(e=!1),!!this._children)for(var s=0;s<this._children.length;s++){var c=this._children[s];(!o||o(c))&&i.push(c),e||c._getDescendants(i,!1,o)}},a.prototype.getDescendants=function(i,e){var o=new Array;return this._getDescendants(o,i,e),o},a.prototype.getChildMeshes=function(i,e){var o=[];return this._getDescendants(o,i,function(s){return(!e||e(s))&&s.cullingStrategy!==void 0}),o},a.prototype.getChildren=function(i,e){return e===void 0&&(e=!0),this.getDescendants(e,i)},a.prototype._setReady=function(i){if(i!==this._nodeDataStorage._isReady){if(!i){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}},a.prototype.getAnimationByName=function(i){for(var e=0;e<this.animations.length;e++){var o=this.animations[e];if(o.name===i)return o}return null},a.prototype.createAnimationRange=function(i,e,o){if(!this._ranges[i]){this._ranges[i]=a._AnimationRangeFactory(i,e,o);for(var s=0,c=this.animations.length;s<c;s++)this.animations[s]&&this.animations[s].createRange(i,e,o)}},a.prototype.deleteAnimationRange=function(i,e){e===void 0&&(e=!0);for(var o=0,s=this.animations.length;o<s;o++)this.animations[o]&&this.animations[o].deleteRange(i,e);this._ranges[i]=null},a.prototype.getAnimationRange=function(i){return this._ranges[i]||null},a.prototype.getAnimationRanges=function(){var i=[],e;for(e in this._ranges)i.push(this._ranges[e]);return i},a.prototype.beginAnimation=function(i,e,o,s){var c=this.getAnimationRange(i);return c?this._scene.beginAnimation(this,c.from,c.to,e,o,s):null},a.prototype.serializeAnimationRanges=function(){var i=[];for(var e in this._ranges){var o=this._ranges[e];if(!!o){var s={};s.name=e,s.from=o.from,s.to=o.to,i.push(s)}}return i},a.prototype.computeWorldMatrix=function(i){return this._worldMatrix||(this._worldMatrix=Matrix.Identity()),this._worldMatrix},a.prototype.dispose=function(i,e){if(e===void 0&&(e=!1),this._nodeDataStorage._isDisposed=!0,!i)for(var o=this.getDescendants(!0),s=0,c=o;s<c.length;s++){var d=c[s];d.dispose(i,e)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(var _=0,b=this._behaviors;_<b.length;_++){var k=b[_];k.detach()}this._behaviors=[],this.metadata=null},a.ParseAnimationRanges=function(i,e,o){if(e.ranges)for(var s=0;s<e.ranges.length;s++){var c=e.ranges[s];i.createAnimationRange(c.name,c.from,c.to)}},a.prototype.getHierarchyBoundingVectors=function(i,e){i===void 0&&(i=!0),e===void 0&&(e=null),this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);var o,s,c=this;if(c.getBoundingInfo&&c.subMeshes){var d=c.getBoundingInfo();o=d.boundingBox.minimumWorld.clone(),s=d.boundingBox.maximumWorld.clone()}else o=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(i)for(var _=this.getDescendants(!1),b=0,k=_;b<k.length;b++){var j=k[b],$=j;if($.computeWorldMatrix(!0),!(e&&!e($))&&!(!$.getBoundingInfo||$.getTotalVertices()===0)){var _e=$.getBoundingInfo(),et=_e.boundingBox,tt=et.minimumWorld,rt=et.maximumWorld;Vector3.CheckExtends(tt,o,s),Vector3.CheckExtends(rt,o,s)}}return{min:o,max:s}},a._AnimationRangeFactory=function(i,e,o){throw _WarnImport("AnimationRange")},a._NodeConstructors={},__decorate([serialize()],a.prototype,"name",void 0),__decorate([serialize()],a.prototype,"id",void 0),__decorate([serialize()],a.prototype,"uniqueId",void 0),__decorate([serialize()],a.prototype,"state",void 0),__decorate([serialize()],a.prototype,"metadata",void 0),a}(),Space;(function(a){a[a.LOCAL=0]="LOCAL",a[a.WORLD=1]="WORLD",a[a.BONE=2]="BONE"})(Space||(Space={}));var Axis=function(){function a(){}return a.X=new Vector3(1,0,0),a.Y=new Vector3(0,1,0),a.Z=new Vector3(0,0,1),a}(),Coordinate;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(Coordinate||(Coordinate={}));var TransformNode=function(a){__extends(i,a);function i(e,o,s){o===void 0&&(o=null),s===void 0&&(s=!0);var c=a.call(this,e,o)||this;return c._forward=new Vector3(0,0,1),c._forwardInverted=new Vector3(0,0,-1),c._up=new Vector3(0,1,0),c._right=new Vector3(1,0,0),c._rightInverted=new Vector3(-1,0,0),c._position=Vector3.Zero(),c._rotation=Vector3.Zero(),c._rotationQuaternion=null,c._scaling=Vector3.One(),c._transformToBoneReferal=null,c._isAbsoluteSynced=!1,c._billboardMode=i.BILLBOARDMODE_NONE,c._preserveParentRotationForBillboard=!1,c.scalingDeterminant=1,c._infiniteDistance=!1,c.ignoreNonUniformScaling=!1,c.reIntegrateRotationIntoRotationQuaternion=!1,c._poseMatrix=null,c._localMatrix=Matrix.Zero(),c._usePivotMatrix=!1,c._absolutePosition=Vector3.Zero(),c._absoluteScaling=Vector3.Zero(),c._absoluteRotationQuaternion=Quaternion.Identity(),c._pivotMatrix=Matrix.Identity(),c._postMultiplyPivotMatrix=!1,c._isWorldMatrixFrozen=!1,c._indexInSceneTransformNodesArray=-1,c.onAfterWorldMatrixUpdateObservable=new Observable,c._nonUniformScaling=!1,s&&c.getScene().addTransformNode(c),c}return Object.defineProperty(i.prototype,"billboardMode",{get:function(){return this._billboardMode},set:function(e){this._billboardMode!==e&&(this._billboardMode=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"preserveParentRotationForBillboard",{get:function(){return this._preserveParentRotationForBillboard},set:function(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"infiniteDistance",{get:function(){return this._infiniteDistance},set:function(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._isDirty=!0},enumerable:!1,configurable:!0}),i.prototype.isUsingPivotMatrix=function(){return this._usePivotMatrix},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"forward",{get:function(){return Vector3.Normalize(Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._forwardInverted:this._forward,this.getWorldMatrix()))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"up",{get:function(){return Vector3.Normalize(Vector3.TransformNormal(this._up,this.getWorldMatrix()))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return Vector3.Normalize(Vector3.TransformNormal(this.getScene().useRightHandedSystem?this._rightInverted:this._right,this.getWorldMatrix()))},enumerable:!1,configurable:!0}),i.prototype.updatePoseMatrix=function(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)},i.prototype.getPoseMatrix=function(){return this._poseMatrix||(this._poseMatrix=Matrix.Identity()),this._poseMatrix},i.prototype._isSynchronized=function(){var e=this._cache;return!(this.billboardMode!==e.billboardMode||this.billboardMode!==i.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this.infiniteDistance||this.position._isDirty||this.scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this.rotation._isDirty)},i.prototype._initCache=function(){a.prototype._initCache.call(this);var e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1},Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this.getAbsolutePosition()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"absoluteScaling",{get:function(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"absoluteRotationQuaternion",{get:function(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion},enumerable:!1,configurable:!0}),i.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},i.prototype.setPivotMatrix=function(e,o){return o===void 0&&(o=!0),this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=o,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=Matrix.Invert(this._pivotMatrix)),this},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype.instantiateHierarchy=function(e,o,s){e===void 0&&(e=null);var c=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);c&&s&&s(this,c);for(var d=0,_=this.getChildTransformNodes(!0);d<_.length;d++){var b=_[d];b.instantiateHierarchy(c,o,s)}return c},i.prototype.freezeWorldMatrix=function(e,o){return e===void 0&&(e=null),o===void 0&&(o=!1),e?o?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||Quaternion.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this},i.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!1,configurable:!0}),i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(e){if(!e)return this;var o,s,c;if(e.x===void 0){if(arguments.length<3)return this;o=arguments[0],s=arguments[1],c=arguments[2]}else o=e.x,s=e.y,c=e.z;if(this.parent){var d=TmpVectors.Matrix[0];this.parent.getWorldMatrix().invertToRef(d),Vector3.TransformCoordinatesFromFloatsToRef(o,s,c,d,this.position)}else this.position.x=o,this.position.y=s,this.position.z=c;return this._absolutePosition.copyFrom(e),this},i.prototype.setPositionWithLocalVector=function(e){return this.computeWorldMatrix(),this.position=Vector3.TransformNormal(e,this._localMatrix),this},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var e=TmpVectors.Matrix[0];return this._localMatrix.invertToRef(e),Vector3.TransformNormal(this.position,e)},i.prototype.locallyTranslate=function(e){return this.computeWorldMatrix(!0),this.position=Vector3.TransformCoordinates(e,this._localMatrix),this},i.prototype.lookAt=function(e,o,s,c,d){o===void 0&&(o=0),s===void 0&&(s=0),c===void 0&&(c=0),d===void 0&&(d=Space.LOCAL);var _=i._lookAtVectorCache,b=d===Space.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(b,_),this.setDirection(_,o,s,c),d===Space.WORLD&&this.parent)if(this.rotationQuaternion){var k=TmpVectors.Matrix[0];this.rotationQuaternion.toRotationMatrix(k);var j=TmpVectors.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(j),j.invert(),k.multiplyToRef(j,k),this.rotationQuaternion.fromRotationMatrix(k)}else{var $=TmpVectors.Quaternion[0];Quaternion.FromEulerVectorToRef(this.rotation,$);var k=TmpVectors.Matrix[0];$.toRotationMatrix(k);var j=TmpVectors.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(j),j.invert(),k.multiplyToRef(j,k),$.fromRotationMatrix(k),$.toEulerAnglesToRef(this.rotation)}return this},i.prototype.getDirection=function(e){var o=Vector3.Zero();return this.getDirectionToRef(e,o),o},i.prototype.getDirectionToRef=function(e,o){return Vector3.TransformNormalToRef(e,this.getWorldMatrix(),o),this},i.prototype.setDirection=function(e,o,s,c){o===void 0&&(o=0),s===void 0&&(s=0),c===void 0&&(c=0);var d=-Math.atan2(e.z,e.x)+Math.PI/2,_=Math.sqrt(e.x*e.x+e.z*e.z),b=-Math.atan2(e.y,_);return this.rotationQuaternion?Quaternion.RotationYawPitchRollToRef(d+o,b+s,c,this.rotationQuaternion):(this.rotation.x=b+s,this.rotation.y=d+o,this.rotation.z=c),this},i.prototype.setPivotPoint=function(e,o){o===void 0&&(o=Space.LOCAL),this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);var s=this.getWorldMatrix();if(o==Space.WORLD){var c=TmpVectors.Matrix[0];s.invertToRef(c),e=Vector3.TransformCoordinates(e,c)}return this.setPivotMatrix(Matrix.Translation(-e.x,-e.y,-e.z),!0)},i.prototype.getPivotPoint=function(){var e=Vector3.Zero();return this.getPivotPointToRef(e),e},i.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},i.prototype.getAbsolutePivotPoint=function(){var e=Vector3.Zero();return this.getAbsolutePivotPointToRef(e),e},i.prototype.getAbsolutePivotPointToRef=function(e){return this.getPivotPointToRef(e),Vector3.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this},i.prototype.markAsDirty=function(e){if(this._children)for(var o=0,s=this._children;o<s.length;o++){var c=s[o];c.markAsDirty(e)}return a.prototype.markAsDirty.call(this,e)},i.prototype.setParent=function(e,o){if(o===void 0&&(o=!1),!e&&!this.parent)return this;var s=TmpVectors.Quaternion[0],c=TmpVectors.Vector3[0],d=TmpVectors.Vector3[1],_=TmpVectors.Matrix[1];Matrix.IdentityToRef(_);var b=TmpVectors.Matrix[0];this.computeWorldMatrix(!0);var k=this.rotationQuaternion;return k||(k=i._TmpRotation,Quaternion.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,k)),Matrix.ComposeToRef(this.scaling,k,this.position,b),this.parent&&b.multiplyToRef(this.parent.computeWorldMatrix(!0),b),e&&(e.computeWorldMatrix(!0).invertToRef(_),b.multiplyToRef(_,b)),b.decompose(d,s,c,o?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(d),this.position.copyFrom(c),this.parent=e,this},Object.defineProperty(i.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!1,configurable:!0}),i.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)},i.prototype.attachToBone=function(e,o){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=o,this.parent=e,e.getSkeleton().prepare(),e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},i.prototype.detachFromBone=function(e){return e===void 0&&(e=!1),this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)},i.prototype.rotate=function(e,o,s){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));var c;if(!s||s===Space.LOCAL)c=Quaternion.RotationAxisToRef(e,o,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(c,this.rotationQuaternion);else{if(this.parent){var d=TmpVectors.Matrix[0];this.parent.getWorldMatrix().invertToRef(d),e=Vector3.TransformNormal(e,d)}c=Quaternion.RotationAxisToRef(e,o,i._rotationAxisCache),c.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this},i.prototype.rotateAround=function(e,o,s){o.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));var c=TmpVectors.Vector3[0],d=TmpVectors.Vector3[1],_=TmpVectors.Vector3[2],b=TmpVectors.Quaternion[0],k=TmpVectors.Matrix[0],j=TmpVectors.Matrix[1],$=TmpVectors.Matrix[2],_e=TmpVectors.Matrix[3];return e.subtractToRef(this.position,c),Matrix.TranslationToRef(c.x,c.y,c.z,k),Matrix.TranslationToRef(-c.x,-c.y,-c.z,j),Matrix.RotationAxisToRef(o,s,$),j.multiplyToRef($,_e),_e.multiplyToRef(k,_e),_e.decompose(d,b,_),this.position.addInPlace(_),b.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},i.prototype.translate=function(e,o,s){var c=e.scale(o);if(!s||s===Space.LOCAL){var d=this.getPositionExpressedInLocalSpace().add(c);this.setPositionWithLocalVector(d)}else this.setAbsolutePosition(this.getAbsolutePosition().add(c));return this},i.prototype.addRotation=function(e,o,s){var c;this.rotationQuaternion?c=this.rotationQuaternion:(c=TmpVectors.Quaternion[1],Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,c));var d=TmpVectors.Quaternion[0];return Quaternion.RotationYawPitchRollToRef(o,e,s,d),c.multiplyInPlace(d),this.rotationQuaternion||c.toEulerAnglesToRef(this.rotation),this},i.prototype._getEffectiveParent=function(){return this.parent},i.prototype.computeWorldMatrix=function(e){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;var o=this.getScene().getRenderId();if(!this._isDirty&&!e&&this.isSynchronized())return this._currentRenderId=o,this._worldMatrix;var s=this.getScene().activeCamera,c=(this._billboardMode&i.BILLBOARDMODE_USE_POSITION)!==0,d=this._billboardMode!==i.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard;d&&s&&c&&(this.lookAt(s.position),(this.billboardMode&i.BILLBOARDMODE_X)!==i.BILLBOARDMODE_X&&(this.rotation.x=0),(this.billboardMode&i.BILLBOARDMODE_Y)!==i.BILLBOARDMODE_Y&&(this.rotation.y=0),(this.billboardMode&i.BILLBOARDMODE_Z)!==i.BILLBOARDMODE_Z&&(this.rotation.z=0)),this._updateCache();var _=this._cache;_.pivotMatrixUpdated=!1,_.billboardMode=this.billboardMode,_.infiniteDistance=this.infiniteDistance,this._currentRenderId=o,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;var b=this._getEffectiveParent(),k=i._TmpScaling,j=this._position;if(this._infiniteDistance&&!this.parent&&s){var $=s.getWorldMatrix(),_e=new Vector3($.m[12],$.m[13],$.m[14]);j=i._TmpTranslation,j.copyFromFloats(this._position.x+_e.x,this._position.y+_e.y,this._position.z+_e.z)}k.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);var et;if(this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,et=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){var tt=this.rotation.lengthSquared();tt&&(this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else et=i._TmpRotation,Quaternion.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,et);if(this._usePivotMatrix){var rt=TmpVectors.Matrix[1];Matrix.ScalingToRef(k.x,k.y,k.z,rt);var it=TmpVectors.Matrix[0];et.toRotationMatrix(it),this._pivotMatrix.multiplyToRef(rt,TmpVectors.Matrix[4]),TmpVectors.Matrix[4].multiplyToRef(it,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(j.x,j.y,j.z)}else Matrix.ComposeToRef(k,et,j,this._localMatrix);if(b&&b.getWorldMatrix){if(e&&b.computeWorldMatrix(e),d){this._transformToBoneReferal?b.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),TmpVectors.Matrix[7]):TmpVectors.Matrix[7].copyFrom(b.getWorldMatrix());var nt=TmpVectors.Vector3[5],ot=TmpVectors.Vector3[6];TmpVectors.Matrix[7].decompose(ot,void 0,nt),Matrix.ScalingToRef(ot.x,ot.y,ot.z,TmpVectors.Matrix[7]),TmpVectors.Matrix[7].setTranslation(nt),this._localMatrix.multiplyToRef(TmpVectors.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(b.getWorldMatrix(),TmpVectors.Matrix[6]),TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(b.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(d&&s&&this.billboardMode&&!c){var at=TmpVectors.Vector3[0];if(this._worldMatrix.getTranslationToRef(at),TmpVectors.Matrix[1].copyFrom(s.getViewMatrix()),TmpVectors.Matrix[1].setTranslationFromFloats(0,0,0),TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]),(this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL){TmpVectors.Matrix[0].decompose(void 0,TmpVectors.Quaternion[0],void 0);var st=TmpVectors.Vector3[1];TmpVectors.Quaternion[0].toEulerAnglesToRef(st),(this.billboardMode&i.BILLBOARDMODE_X)!==i.BILLBOARDMODE_X&&(st.x=0),(this.billboardMode&i.BILLBOARDMODE_Y)!==i.BILLBOARDMODE_Y&&(st.y=0),(this.billboardMode&i.BILLBOARDMODE_Z)!==i.BILLBOARDMODE_Z&&(st.z=0),Matrix.RotationYawPitchRollToRef(st.y,st.x,st.z,TmpVectors.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(TmpVectors.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):b&&b._nonUniformScaling?this._updateNonUniformScalingState(b._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=Matrix.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix},i.prototype.resetLocalMatrix=function(e){if(e===void 0&&(e=!0),this.computeWorldMatrix(),e)for(var o=this.getChildren(),s=0;s<o.length;++s){var c=o[s];if(c){c.computeWorldMatrix();var d=TmpVectors.Matrix[0];c._localMatrix.multiplyToRef(this._localMatrix,d);var _=TmpVectors.Quaternion[0];d.decompose(c.scaling,_,c.position),c.rotationQuaternion?c.rotationQuaternion.copyFrom(_):_.toEulerAnglesToRef(c.rotation)}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=Quaternion.Identity()),this._worldMatrix=Matrix.Identity()},i.prototype._afterComputeWorldMatrix=function(){},i.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},i.prototype.getPositionInCameraSpace=function(e){return e===void 0&&(e=null),e||(e=this.getScene().activeCamera),Vector3.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())},i.prototype.getDistanceToCamera=function(e){return e===void 0&&(e=null),e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()},i.prototype.clone=function(e,o,s){var c=this,d=SerializationHelper.Clone(function(){return new i(e,c.getScene())},this);if(d.name=e,d.id=e,o&&(d.parent=o),!s)for(var _=this.getDescendants(!0),b=0;b<_.length;b++){var k=_[b];k.clone&&k.clone(e+"."+k.name,d)}return d},i.prototype.serialize=function(e){var o=SerializationHelper.Serialize(this,e);return o.type=this.getClassName(),o.uniqueId=this.uniqueId,this.parent&&(o.parentId=this.parent.uniqueId),o.localMatrix=this.getPivotMatrix().asArray(),o.isEnabled=this.isEnabled(),this.parent&&(o.parentId=this.parent.uniqueId),o},i.Parse=function(e,o,s){var c=SerializationHelper.Parse(function(){return new i(e.name,o)},e,o,s);return e.localMatrix?c.setPreTransformMatrix(Matrix.FromArray(e.localMatrix)):e.pivotMatrix&&c.setPivotMatrix(Matrix.FromArray(e.pivotMatrix)),c.setEnabled(e.isEnabled),e.parentId&&(c._waitingParentId=e.parentId),c},i.prototype.getChildTransformNodes=function(e,o){var s=[];return this._getDescendants(s,e,function(c){return(!o||o(c))&&c instanceof i}),s},i.prototype.dispose=function(e,o){if(o===void 0&&(o=!1),this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){var s=this._parentContainer.transformNodes.indexOf(this);s>-1&&this._parentContainer.transformNodes.splice(s,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e)for(var c=this.getChildTransformNodes(!0),d=0,_=c;d<_.length;d++){var b=_[d];b.parent=null,b.computeWorldMatrix(!0)}a.prototype.dispose.call(this,e,o)},i.prototype.normalizeToUnitCube=function(e,o,s){e===void 0&&(e=!0),o===void 0&&(o=!1);var c=null,d=null;o&&(this.rotationQuaternion?(d=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(c=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));var _=this.getHierarchyBoundingVectors(e,s),b=_.max.subtract(_.min),k=Math.max(b.x,b.y,b.z);if(k===0)return this;var j=1/k;return this.scaling.scaleInPlace(j),o&&(this.rotationQuaternion&&d?this.rotationQuaternion.copyFrom(d):this.rotation&&c&&this.rotation.copyFrom(c)),this},i.prototype._syncAbsoluteScalingAndRotation=function(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)},i.BILLBOARDMODE_NONE=0,i.BILLBOARDMODE_X=1,i.BILLBOARDMODE_Y=2,i.BILLBOARDMODE_Z=4,i.BILLBOARDMODE_ALL=7,i.BILLBOARDMODE_USE_POSITION=128,i._TmpRotation=Quaternion.Zero(),i._TmpScaling=Vector3.Zero(),i._TmpTranslation=Vector3.Zero(),i._lookAtVectorCache=new Vector3(0,0,0),i._rotationAxisCache=new Quaternion,__decorate([serializeAsVector3("position")],i.prototype,"_position",void 0),__decorate([serializeAsVector3("rotation")],i.prototype,"_rotation",void 0),__decorate([serializeAsQuaternion("rotationQuaternion")],i.prototype,"_rotationQuaternion",void 0),__decorate([serializeAsVector3("scaling")],i.prototype,"_scaling",void 0),__decorate([serialize("billboardMode")],i.prototype,"_billboardMode",void 0),__decorate([serialize()],i.prototype,"scalingDeterminant",void 0),__decorate([serialize("infiniteDistance")],i.prototype,"_infiniteDistance",void 0),__decorate([serialize()],i.prototype,"ignoreNonUniformScaling",void 0),__decorate([serialize()],i.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0),i}(Node$2),PickingInfo=function(){function a(){this._pickingUnavailable=!1,this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}return a.prototype.getNormal=function(i,e){if(i===void 0&&(i=!1),e===void 0&&(e=!0),!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind))return null;var o=this.pickedMesh.getIndices();if(!o)return null;var s;if(e){var c=this.pickedMesh.getVerticesData(VertexBuffer.NormalKind),d=Vector3.FromArray(c,o[this.faceId*3]*3),_=Vector3.FromArray(c,o[this.faceId*3+1]*3),b=Vector3.FromArray(c,o[this.faceId*3+2]*3);d=d.scale(this.bu),_=_.scale(this.bv),b=b.scale(1-this.bu-this.bv),s=new Vector3(d.x+_.x+b.x,d.y+_.y+b.y,d.z+_.z+b.z)}else{var k=this.pickedMesh.getVerticesData(VertexBuffer.PositionKind),j=Vector3.FromArray(k,o[this.faceId*3]*3),$=Vector3.FromArray(k,o[this.faceId*3+1]*3),_e=Vector3.FromArray(k,o[this.faceId*3+2]*3),et=j.subtract($),tt=_e.subtract($);s=Vector3.Cross(et,tt)}if(i){var rt=this.pickedMesh.getWorldMatrix();this.pickedMesh.nonUniformScaling&&(TmpVectors.Matrix[0].copyFrom(rt),rt=TmpVectors.Matrix[0],rt.setTranslationFromFloats(0,0,0),rt.invert(),rt.transposeToRef(TmpVectors.Matrix[1]),rt=TmpVectors.Matrix[1]),s=Vector3.TransformNormal(s,rt)}return s.normalize(),s},a.prototype.getTextureCoordinates=function(){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(VertexBuffer.UVKind))return null;var i=this.pickedMesh.getIndices();if(!i)return null;var e=this.pickedMesh.getVerticesData(VertexBuffer.UVKind);if(!e)return null;var o=Vector2.FromArray(e,i[this.faceId*3]*2),s=Vector2.FromArray(e,i[this.faceId*3+1]*2),c=Vector2.FromArray(e,i[this.faceId*3+2]*2);return o=o.scale(this.bu),s=s.scale(this.bv),c=c.scale(1-this.bu-this.bv),new Vector2(o.x+s.x+c.x,o.y+s.y+c.y)},a}(),BoundingBox=function(){function a(i,e,o){this.vectors=ArrayTools.BuildArray(8,Vector3.Zero),this.center=Vector3.Zero(),this.centerWorld=Vector3.Zero(),this.extendSize=Vector3.Zero(),this.extendSizeWorld=Vector3.Zero(),this.directions=ArrayTools.BuildArray(3,Vector3.Zero),this.vectorsWorld=ArrayTools.BuildArray(8,Vector3.Zero),this.minimumWorld=Vector3.Zero(),this.maximumWorld=Vector3.Zero(),this.minimum=Vector3.Zero(),this.maximum=Vector3.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(i,e,o)}return a.prototype.reConstruct=function(i,e,o){var s=i.x,c=i.y,d=i.z,_=e.x,b=e.y,k=e.z,j=this.vectors;this.minimum.copyFromFloats(s,c,d),this.maximum.copyFromFloats(_,b,k),j[0].copyFromFloats(s,c,d),j[1].copyFromFloats(_,b,k),j[2].copyFromFloats(_,c,d),j[3].copyFromFloats(s,b,d),j[4].copyFromFloats(s,c,k),j[5].copyFromFloats(_,b,d),j[6].copyFromFloats(s,b,k),j[7].copyFromFloats(_,c,k),e.addToRef(i,this.center).scaleInPlace(.5),e.subtractToRef(i,this.extendSize).scaleInPlace(.5),this._worldMatrix=o||Matrix.IdentityReadOnly,this._update(this._worldMatrix)},a.prototype.scale=function(i){var e=a.TmpVector3,o=this.maximum.subtractToRef(this.minimum,e[0]),s=o.length();o.normalizeFromLength(s);var c=s*i,d=o.scaleInPlace(c*.5),_=this.center.subtractToRef(d,e[1]),b=this.center.addToRef(d,e[2]);return this.reConstruct(_,b,this._worldMatrix),this},a.prototype.getWorldMatrix=function(){return this._worldMatrix},a.prototype._update=function(i){var e=this.minimumWorld,o=this.maximumWorld,s=this.directions,c=this.vectorsWorld,d=this.vectors;if(i.isIdentity()){e.copyFrom(this.minimum),o.copyFrom(this.maximum);for(var _=0;_<8;++_)c[_].copyFrom(d[_]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{e.setAll(Number.MAX_VALUE),o.setAll(-Number.MAX_VALUE);for(var _=0;_<8;++_){var b=c[_];Vector3.TransformCoordinatesToRef(d[_],i,b),e.minimizeInPlace(b),o.maximizeInPlace(b)}o.subtractToRef(e,this.extendSizeWorld).scaleInPlace(.5),o.addToRef(e,this.centerWorld).scaleInPlace(.5)}Vector3.FromArrayToRef(i.m,0,s[0]),Vector3.FromArrayToRef(i.m,4,s[1]),Vector3.FromArrayToRef(i.m,8,s[2]),this._worldMatrix=i},a.prototype.isInFrustum=function(i){return a.IsInFrustum(this.vectorsWorld,i)},a.prototype.isCompletelyInFrustum=function(i){return a.IsCompletelyInFrustum(this.vectorsWorld,i)},a.prototype.intersectsPoint=function(i){var e=this.minimumWorld,o=this.maximumWorld,s=e.x,c=e.y,d=e.z,_=o.x,b=o.y,k=o.z,j=i.x,$=i.y,_e=i.z,et=-Epsilon;return!(_-j<et||et>j-s||b-$<et||et>$-c||k-_e<et||et>_e-d)},a.prototype.intersectsSphere=function(i){return a.IntersectsSphere(this.minimumWorld,this.maximumWorld,i.centerWorld,i.radiusWorld)},a.prototype.intersectsMinMax=function(i,e){var o=this.minimumWorld,s=this.maximumWorld,c=o.x,d=o.y,_=o.z,b=s.x,k=s.y,j=s.z,$=i.x,_e=i.y,et=i.z,tt=e.x,rt=e.y,it=e.z;return!(b<$||c>tt||k<_e||d>rt||j<et||_>it)},a.prototype.dispose=function(){var i,e;(i=this._drawWrapperFront)===null||i===void 0||i.dispose(),(e=this._drawWrapperBack)===null||e===void 0||e.dispose()},a.Intersects=function(i,e){return i.intersectsMinMax(e.minimumWorld,e.maximumWorld)},a.IntersectsSphere=function(i,e,o,s){var c=a.TmpVector3[0];Vector3.ClampToRef(o,i,e,c);var d=Vector3.DistanceSquared(o,c);return d<=s*s},a.IsCompletelyInFrustum=function(i,e){for(var o=0;o<6;++o)for(var s=e[o],c=0;c<8;++c)if(s.dotCoordinate(i[c])<0)return!1;return!0},a.IsInFrustum=function(i,e){for(var o=0;o<6;++o){for(var s=!0,c=e[o],d=0;d<8;++d)if(c.dotCoordinate(i[d])>=0){s=!1;break}if(s)return!1}return!0},a.TmpVector3=ArrayTools.BuildArray(3,Vector3.Zero),a}(),BoundingSphere=function(){function a(i,e,o){this.center=Vector3.Zero(),this.centerWorld=Vector3.Zero(),this.minimum=Vector3.Zero(),this.maximum=Vector3.Zero(),this.reConstruct(i,e,o)}return a.prototype.reConstruct=function(i,e,o){this.minimum.copyFrom(i),this.maximum.copyFrom(e);var s=Vector3.Distance(i,e);e.addToRef(i,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(o||Matrix.IdentityReadOnly)},a.prototype.scale=function(i){var e=this.radius*i,o=a.TmpVector3,s=o[0].setAll(e),c=this.center.subtractToRef(s,o[1]),d=this.center.addToRef(s,o[2]);return this.reConstruct(c,d,this._worldMatrix),this},a.prototype.getWorldMatrix=function(){return this._worldMatrix},a.prototype._update=function(i){if(i.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{Vector3.TransformCoordinatesToRef(this.center,i,this.centerWorld);var e=a.TmpVector3[0];Vector3.TransformNormalFromFloatsToRef(1,1,1,i,e),this.radiusWorld=Math.max(Math.abs(e.x),Math.abs(e.y),Math.abs(e.z))*this.radius}},a.prototype.isInFrustum=function(i){for(var e=this.centerWorld,o=this.radiusWorld,s=0;s<6;s++)if(i[s].dotCoordinate(e)<=-o)return!1;return!0},a.prototype.isCenterInFrustum=function(i){for(var e=this.centerWorld,o=0;o<6;o++)if(i[o].dotCoordinate(e)<0)return!1;return!0},a.prototype.intersectsPoint=function(i){var e=Vector3.DistanceSquared(this.centerWorld,i);return!(this.radiusWorld*this.radiusWorld<e)},a.Intersects=function(i,e){var o=Vector3.DistanceSquared(i.centerWorld,e.centerWorld),s=i.radiusWorld+e.radiusWorld;return!(s*s<o)},a.CreateFromCenterAndRadius=function(i,e,o){this.TmpVector3[0].copyFrom(i),this.TmpVector3[1].copyFromFloats(0,0,e),this.TmpVector3[2].copyFrom(i),this.TmpVector3[0].addInPlace(this.TmpVector3[1]),this.TmpVector3[2].subtractInPlace(this.TmpVector3[1]);var s=new a(this.TmpVector3[0],this.TmpVector3[2]);return o?s._worldMatrix=o:s._worldMatrix=Matrix.Identity(),s},a.TmpVector3=ArrayTools.BuildArray(3,Vector3.Zero),a}(),_result0={min:0,max:0},_result1={min:0,max:0},computeBoxExtents=function(a,i,e){var o=Vector3.Dot(i.centerWorld,a),s=Math.abs(Vector3.Dot(i.directions[0],a))*i.extendSize.x,c=Math.abs(Vector3.Dot(i.directions[1],a))*i.extendSize.y,d=Math.abs(Vector3.Dot(i.directions[2],a))*i.extendSize.z,_=s+c+d;e.min=o-_,e.max=o+_},axisOverlap=function(a,i,e){return computeBoxExtents(a,i,_result0),computeBoxExtents(a,e,_result1),!(_result0.min>_result1.max||_result1.min>_result0.max)},BoundingInfo=function(){function a(i,e,o){this._isLocked=!1,this.boundingBox=new BoundingBox(i,e,o),this.boundingSphere=new BoundingSphere(i,e,o)}return a.prototype.reConstruct=function(i,e,o){this.boundingBox.reConstruct(i,e,o),this.boundingSphere.reConstruct(i,e,o)},Object.defineProperty(a.prototype,"minimum",{get:function(){return this.boundingBox.minimum},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"maximum",{get:function(){return this.boundingBox.maximum},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isLocked",{get:function(){return this._isLocked},set:function(i){this._isLocked=i},enumerable:!1,configurable:!0}),a.prototype.update=function(i){this._isLocked||(this.boundingBox._update(i),this.boundingSphere._update(i))},a.prototype.centerOn=function(i,e){var o=a.TmpVector3[0].copyFrom(i).subtractInPlace(e),s=a.TmpVector3[1].copyFrom(i).addInPlace(e);return this.boundingBox.reConstruct(o,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(o,s,this.boundingBox.getWorldMatrix()),this},a.prototype.encapsulate=function(i){var e=Vector3.Minimize(this.minimum,i),o=Vector3.Maximize(this.maximum,i);return this.reConstruct(e,o,this.boundingBox.getWorldMatrix()),this},a.prototype.encapsulateBoundingInfo=function(i){return this.encapsulate(i.boundingBox.centerWorld.subtract(i.boundingBox.extendSizeWorld)),this.encapsulate(i.boundingBox.centerWorld.add(i.boundingBox.extendSizeWorld)),this},a.prototype.scale=function(i){return this.boundingBox.scale(i),this.boundingSphere.scale(i),this},a.prototype.isInFrustum=function(i,e){e===void 0&&(e=0);var o=e===2||e===3;if(o&&this.boundingSphere.isCenterInFrustum(i))return!0;if(!this.boundingSphere.isInFrustum(i))return!1;var s=e===1||e===3;return s?!0:this.boundingBox.isInFrustum(i)},Object.defineProperty(a.prototype,"diagonalLength",{get:function(){var i=this.boundingBox,e=i.maximumWorld.subtractToRef(i.minimumWorld,a.TmpVector3[0]);return e.length()},enumerable:!1,configurable:!0}),a.prototype.isCompletelyInFrustum=function(i){return this.boundingBox.isCompletelyInFrustum(i)},a.prototype._checkCollision=function(i){return i._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},a.prototype.intersectsPoint=function(i){return!(!this.boundingSphere.centerWorld||!this.boundingSphere.intersectsPoint(i)||!this.boundingBox.intersectsPoint(i))},a.prototype.intersects=function(i,e){if(!BoundingSphere.Intersects(this.boundingSphere,i.boundingSphere)||!BoundingBox.Intersects(this.boundingBox,i.boundingBox))return!1;if(!e)return!0;var o=this.boundingBox,s=i.boundingBox;return!(!axisOverlap(o.directions[0],o,s)||!axisOverlap(o.directions[1],o,s)||!axisOverlap(o.directions[2],o,s)||!axisOverlap(s.directions[0],o,s)||!axisOverlap(s.directions[1],o,s)||!axisOverlap(s.directions[2],o,s)||!axisOverlap(Vector3.Cross(o.directions[0],s.directions[0]),o,s)||!axisOverlap(Vector3.Cross(o.directions[0],s.directions[1]),o,s)||!axisOverlap(Vector3.Cross(o.directions[0],s.directions[2]),o,s)||!axisOverlap(Vector3.Cross(o.directions[1],s.directions[0]),o,s)||!axisOverlap(Vector3.Cross(o.directions[1],s.directions[1]),o,s)||!axisOverlap(Vector3.Cross(o.directions[1],s.directions[2]),o,s)||!axisOverlap(Vector3.Cross(o.directions[2],s.directions[0]),o,s)||!axisOverlap(Vector3.Cross(o.directions[2],s.directions[1]),o,s)||!axisOverlap(Vector3.Cross(o.directions[2],s.directions[2]),o,s))},a.TmpVector3=ArrayTools.BuildArray(2,Vector3.Zero),a}();ThinEngine.prototype.createUniformBuffer=function(a){var i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");var e=new WebGLDataBuffer(i);return this.bindUniformBuffer(e),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),e.references=1,e};ThinEngine.prototype.createDynamicUniformBuffer=function(a){var i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");var e=new WebGLDataBuffer(i);return this.bindUniformBuffer(e),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),e.references=1,e};ThinEngine.prototype.updateUniformBuffer=function(a,i,e,o){this.bindUniformBuffer(a),e===void 0&&(e=0),o===void 0?i instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,e,i):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,e,new Float32Array(i)):i instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,i.subarray(e,e+o)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(i).subarray(e,e+o)),this.bindUniformBuffer(null)};ThinEngine.prototype.bindUniformBuffer=function(a){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,a?a.underlyingResource:null)};ThinEngine.prototype.bindUniformBufferBase=function(a,i,e){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,i,a?a.underlyingResource:null)};ThinEngine.prototype.bindUniformBlock=function(a,i,e){var o=a.program,s=this._gl.getUniformBlockIndex(o,i);this._gl.uniformBlockBinding(o,s,e)};var UniformBuffer=function(){function a(i,e,o,s){this._valueCache={},this._engine=i,this._noUBO=!i.supportsUniformBuffers,this._dynamic=o,this._name=s!=null?s:"no-name",this._data=e||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform)}return Object.defineProperty(a.prototype,"useUbo",{get:function(){return!this._noUBO},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isSync",{get:function(){return!this._needSync},enumerable:!1,configurable:!0}),a.prototype.isDynamic=function(){return this._dynamic!==void 0},a.prototype.getData=function(){return this._bufferData},a.prototype.getBuffer=function(){return this._buffer},a.prototype._fillAlignment=function(i){var e;if(i<=2?e=i:e=4,this._uniformLocationPointer%e!==0){var o=this._uniformLocationPointer;this._uniformLocationPointer+=e-this._uniformLocationPointer%e;for(var s=this._uniformLocationPointer-o,c=0;c<s;c++)this._data.push(0)}},a.prototype.addUniform=function(i,e,o){if(o===void 0&&(o=0),!this._noUBO&&this._uniformLocations[i]===void 0){var s;if(o>0){if(e instanceof Array)throw"addUniform should not be use with Array in UBO: "+i;if(this._fillAlignment(4),this._uniformArraySizes[i]={strideSize:e,arraySize:o},e==16)e=e*o;else{var c=4-e,d=c*o;e=e*o+d}s=[];for(var _=0;_<e;_++)s.push(0)}else{if(e instanceof Array)s=e,e=s.length;else{e=e,s=[];for(var _=0;_<e;_++)s.push(0)}this._fillAlignment(e)}this._uniformSizes[i]=e,this._uniformLocations[i]=this._uniformLocationPointer,this._uniformLocationPointer+=e;for(var _=0;_<e;_++)this._data.push(s[_]);this._needSync=!0}},a.prototype.addMatrix=function(i,e){this.addUniform(i,Array.prototype.slice.call(e.toArray()))},a.prototype.addFloat2=function(i,e,o){var s=[e,o];this.addUniform(i,s)},a.prototype.addFloat3=function(i,e,o,s){var c=[e,o,s];this.addUniform(i,c)},a.prototype.addColor3=function(i,e){var o=[e.r,e.g,e.b];this.addUniform(i,o)},a.prototype.addColor4=function(i,e,o){var s=[e.r,e.g,e.b,o];this.addUniform(i,s)},a.prototype.addVector3=function(i,e){var o=[e.x,e.y,e.z];this.addUniform(i,o)},a.prototype.addMatrix3x3=function(i){this.addUniform(i,12)},a.prototype.addMatrix2x2=function(i){this.addUniform(i,8)},a.prototype.create=function(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)},a.prototype._rebuild=function(){this._noUBO||!this._bufferData||(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData):this._buffer=this._engine.createUniformBuffer(this._bufferData),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))},Object.defineProperty(a.prototype,"_numBuffers",{get:function(){return this._buffers.length},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"_indexBuffer",{get:function(){return this._bufferIndex},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"name",{get:function(){return this._name},enumerable:!1,configurable:!0}),a.prototype._buffersEqual=function(i,e){for(var o=0;o<i.length;++o)if(i[o]!==e[o])return!1;return!0},a.prototype._copyBuffer=function(i,e){for(var o=0;o<i.length;++o)e[o]=i[o]},a.prototype.update=function(){if(this.bindUniformBuffer(),!this._buffer){this.create();return}if(!this._dynamic&&!this._needSync){this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(a._updatedUbosInFrame[this._name]||(a._updatedUbosInFrame[this._name]=0),a._updatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame},a.prototype._createNewBuffer=function(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()},a.prototype._checkNewFrame=function(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)},a.prototype.updateUniform=function(i,e,o){this._checkNewFrame();var s=this._uniformLocations[i];if(s===void 0){if(this._buffer){Logger$2.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(i,o),s=this._uniformLocations[i]}if(this._buffer||this.create(),this._dynamic)for(var d=0;d<o;d++)this._bufferData[s+d]=e[d];else{for(var c=!1,d=0;d<o;d++)(o===16&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[s+d]!==Tools.FloatRound(e[d]))&&(c=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+d]=e[d]);this._needSync=this._needSync||c}},a.prototype.updateUniformArray=function(i,e,o){this._checkNewFrame();var s=this._uniformLocations[i];if(s===void 0){Logger$2.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform.");return}this._buffer||this.create();var c=this._uniformArraySizes[i];if(this._dynamic)for(var k=0;k<o;k++)this._bufferData[s+k]=e[k];else{for(var d=!1,_=0,b=0,k=0;k<o;k++)if(this._bufferData[s+b*4+_]!==Tools.FloatRound(e[k])&&(d=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+b*4+_]=e[k]),_++,_===c.strideSize){for(;_<4;_++)this._bufferData[s+b*4+_]=0;_=0,b++}this._needSync=this._needSync||d}},a.prototype._cacheMatrix=function(i,e){this._checkNewFrame();var o=this._valueCache[i],s=e.updateFlag;return o!==void 0&&o===s?!1:(this._valueCache[i]=s,!0)},a.prototype._updateMatrix3x3ForUniform=function(i,e){for(var o=0;o<3;o++)a._tempBuffer[o*4]=e[o*3],a._tempBuffer[o*4+1]=e[o*3+1],a._tempBuffer[o*4+2]=e[o*3+2],a._tempBuffer[o*4+3]=0;this.updateUniform(i,a._tempBuffer,12)},a.prototype._updateMatrix3x3ForEffect=function(i,e){this._currentEffect.setMatrix3x3(i,e)},a.prototype._updateMatrix2x2ForEffect=function(i,e){this._currentEffect.setMatrix2x2(i,e)},a.prototype._updateMatrix2x2ForUniform=function(i,e){for(var o=0;o<2;o++)a._tempBuffer[o*4]=e[o*2],a._tempBuffer[o*4+1]=e[o*2+1],a._tempBuffer[o*4+2]=0,a._tempBuffer[o*4+3]=0;this.updateUniform(i,a._tempBuffer,8)},a.prototype._updateFloatForEffect=function(i,e){this._currentEffect.setFloat(i,e)},a.prototype._updateFloatForUniform=function(i,e){a._tempBuffer[0]=e,this.updateUniform(i,a._tempBuffer,1)},a.prototype._updateFloat2ForEffect=function(i,e,o,s){s===void 0&&(s=""),this._currentEffect.setFloat2(i+s,e,o)},a.prototype._updateFloat2ForUniform=function(i,e,o){a._tempBuffer[0]=e,a._tempBuffer[1]=o,this.updateUniform(i,a._tempBuffer,2)},a.prototype._updateFloat3ForEffect=function(i,e,o,s,c){c===void 0&&(c=""),this._currentEffect.setFloat3(i+c,e,o,s)},a.prototype._updateFloat3ForUniform=function(i,e,o,s){a._tempBuffer[0]=e,a._tempBuffer[1]=o,a._tempBuffer[2]=s,this.updateUniform(i,a._tempBuffer,3)},a.prototype._updateFloat4ForEffect=function(i,e,o,s,c,d){d===void 0&&(d=""),this._currentEffect.setFloat4(i+d,e,o,s,c)},a.prototype._updateFloat4ForUniform=function(i,e,o,s,c){a._tempBuffer[0]=e,a._tempBuffer[1]=o,a._tempBuffer[2]=s,a._tempBuffer[3]=c,this.updateUniform(i,a._tempBuffer,4)},a.prototype._updateFloatArrayForEffect=function(i,e){this._currentEffect.setFloatArray(i,e)},a.prototype._updateFloatArrayForUniform=function(i,e){this.updateUniformArray(i,e,e.length)},a.prototype._updateArrayForEffect=function(i,e){this._currentEffect.setArray(i,e)},a.prototype._updateArrayForUniform=function(i,e){this.updateUniformArray(i,e,e.length)},a.prototype._updateIntArrayForEffect=function(i,e){this._currentEffect.setIntArray(i,e)},a.prototype._updateIntArrayForUniform=function(i,e){a._tempBufferInt32View.set(e),this.updateUniformArray(i,a._tempBuffer,e.length)},a.prototype._updateMatrixForEffect=function(i,e){this._currentEffect.setMatrix(i,e)},a.prototype._updateMatrixForUniform=function(i,e){this._cacheMatrix(i,e)&&this.updateUniform(i,e.toArray(),16)},a.prototype._updateMatricesForEffect=function(i,e){this._currentEffect.setMatrices(i,e)},a.prototype._updateMatricesForUniform=function(i,e){this.updateUniform(i,e,e.length)},a.prototype._updateVector3ForEffect=function(i,e){this._currentEffect.setVector3(i,e)},a.prototype._updateVector3ForUniform=function(i,e){a._tempBuffer[0]=e.x,a._tempBuffer[1]=e.y,a._tempBuffer[2]=e.z,this.updateUniform(i,a._tempBuffer,3)},a.prototype._updateVector4ForEffect=function(i,e){this._currentEffect.setVector4(i,e)},a.prototype._updateVector4ForUniform=function(i,e){a._tempBuffer[0]=e.x,a._tempBuffer[1]=e.y,a._tempBuffer[2]=e.z,a._tempBuffer[3]=e.w,this.updateUniform(i,a._tempBuffer,4)},a.prototype._updateColor3ForEffect=function(i,e,o){o===void 0&&(o=""),this._currentEffect.setColor3(i+o,e)},a.prototype._updateColor3ForUniform=function(i,e){a._tempBuffer[0]=e.r,a._tempBuffer[1]=e.g,a._tempBuffer[2]=e.b,this.updateUniform(i,a._tempBuffer,3)},a.prototype._updateColor4ForEffect=function(i,e,o,s){s===void 0&&(s=""),this._currentEffect.setColor4(i+s,e,o)},a.prototype._updateDirectColor4ForEffect=function(i,e,o){o===void 0&&(o=""),this._currentEffect.setDirectColor4(i+o,e)},a.prototype._updateColor4ForUniform=function(i,e,o){a._tempBuffer[0]=e.r,a._tempBuffer[1]=e.g,a._tempBuffer[2]=e.b,a._tempBuffer[3]=o,this.updateUniform(i,a._tempBuffer,4)},a.prototype._updateDirectColor4ForUniform=function(i,e){a._tempBuffer[0]=e.r,a._tempBuffer[1]=e.g,a._tempBuffer[2]=e.b,a._tempBuffer[3]=e.a,this.updateUniform(i,a._tempBuffer,4)},a.prototype._updateIntForEffect=function(i,e,o){o===void 0&&(o=""),this._currentEffect.setInt(i+o,e)},a.prototype._updateIntForUniform=function(i,e){a._tempBufferInt32View[0]=e,this.updateUniform(i,a._tempBuffer,1)},a.prototype._updateInt2ForEffect=function(i,e,o,s){s===void 0&&(s=""),this._currentEffect.setInt2(i+s,e,o)},a.prototype._updateInt2ForUniform=function(i,e,o){a._tempBufferInt32View[0]=e,a._tempBufferInt32View[1]=o,this.updateUniform(i,a._tempBuffer,2)},a.prototype._updateInt3ForEffect=function(i,e,o,s,c){c===void 0&&(c=""),this._currentEffect.setInt3(i+c,e,o,s)},a.prototype._updateInt3ForUniform=function(i,e,o,s){a._tempBufferInt32View[0]=e,a._tempBufferInt32View[1]=o,a._tempBufferInt32View[2]=s,this.updateUniform(i,a._tempBuffer,3)},a.prototype._updateInt4ForEffect=function(i,e,o,s,c,d){d===void 0&&(d=""),this._currentEffect.setInt4(i+d,e,o,s,c)},a.prototype._updateInt4ForUniform=function(i,e,o,s,c){a._tempBufferInt32View[0]=e,a._tempBufferInt32View[1]=o,a._tempBufferInt32View[2]=s,a._tempBufferInt32View[3]=c,this.updateUniform(i,a._tempBuffer,4)},a.prototype.setTexture=function(i,e){this._currentEffect.setTexture(i,e)},a.prototype.updateUniformDirectly=function(i,e){this.updateUniform(i,e,e.length),this.update()},a.prototype.bindToEffect=function(i,e){this._currentEffect=i,this._currentEffectName=e},a.prototype.bindUniformBuffer=function(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)},a.prototype.unbindEffect=function(){this._currentEffect=void 0,this._currentEffectName=void 0},a.prototype.dispose=function(){if(!this._noUBO){var i=this._engine._uniformBuffers,e=i.indexOf(this);if(e!==-1&&(i[e]=i[i.length-1],i.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(var o=0;o<this._buffers.length;++o){var s=this._buffers[o][0];this._engine._releaseBuffer(s)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}},a._updatedUbosInFrame={},a._MAX_UNIFORM_SIZE=256,a._tempBuffer=new Float32Array(a._MAX_UNIFORM_SIZE),a._tempBufferInt32View=new Uint32Array(a._tempBuffer.buffer),a}(),_MeshCollisionData=function(){function a(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new Vector3(0,0,0),this._diffPositionForCollisions=new Vector3(0,0,0),this._collisionResponse=!0}return a}(),MathHelpers=function(){function a(){}return a.extractMinAndMaxIndexed=function(i,e,o,s,c,d){for(var _=o;_<o+s;_++){var b=e[_]*3,k=i[b],j=i[b+1],$=i[b+2];c.minimizeInPlaceFromFloats(k,j,$),d.maximizeInPlaceFromFloats(k,j,$)}},a.extractMinAndMax=function(i,e,o,s,c,d){for(var _=e,b=e*s;_<e+o;_++,b+=s){var k=i[b],j=i[b+1],$=i[b+2];c.minimizeInPlaceFromFloats(k,j,$),d.maximizeInPlaceFromFloats(k,j,$)}},__decorate([nativeOverride.filter(function(){for(var i=[],e=0;e<arguments.length;e++)i[e]=arguments[e];var o=i[0],s=i[1];return!Array.isArray(o)&&!Array.isArray(s)})],a,"extractMinAndMaxIndexed",null),__decorate([nativeOverride.filter(function(){for(var i=[],e=0;e<arguments.length;e++)i[e]=arguments[e];var o=i[0];return!Array.isArray(o)})],a,"extractMinAndMax",null),a}();function extractMinAndMaxIndexed(a,i,e,o,s){s===void 0&&(s=null);var c=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),d=new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return MathHelpers.extractMinAndMaxIndexed(a,i,e,o,c,d),s&&(c.x-=c.x*s.x+s.y,c.y-=c.y*s.x+s.y,c.z-=c.z*s.x+s.y,d.x+=d.x*s.x+s.y,d.y+=d.y*s.x+s.y,d.z+=d.z*s.x+s.y),{minimum:c,maximum:d}}function extractMinAndMax(a,i,e,o,s){o===void 0&&(o=null);var c=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),d=new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),MathHelpers.extractMinAndMax(a,i,e,s,c,d),o&&(c.x-=c.x*o.x+o.y,c.y-=c.y*o.x+o.y,c.z-=c.z*o.x+o.y,d.x+=d.x*o.x+o.y,d.y+=d.y*o.x+o.y,d.z+=d.z*o.x+o.y),{minimum:c,maximum:d}}var _FacetDataStorage=function(){function a(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=Vector3.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}return a}(),_InternalAbstractMeshDataInfo=function(){function a(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new _FacetDataStorage,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._meshCollisionData=new _MeshCollisionData}return a}(),AbstractMesh=function(a){__extends(i,a);function i(e,o){o===void 0&&(o=null);var s=a.call(this,e,o,!1)||this;return s._internalAbstractMeshDataInfo=new _InternalAbstractMeshDataInfo,s.cullingStrategy=i.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,s.onCollideObservable=new Observable,s.onCollisionPositionChangeObservable=new Observable,s.onMaterialChangedObservable=new Observable,s.definedFacingForward=!0,s._occlusionQuery=null,s._renderingGroup=null,s.alphaIndex=Number.MAX_VALUE,s.isVisible=!0,s.isPickable=!0,s.isNearPickable=!1,s.isNearGrabbable=!1,s.showSubMeshesBoundingBox=!1,s.isBlocker=!1,s.enablePointerMoveEvents=!1,s.outlineColor=Color3.Red(),s.outlineWidth=.02,s.overlayColor=Color3.Red(),s.overlayAlpha=.5,s.useOctreeForRenderingSelection=!0,s.useOctreeForPicking=!0,s.useOctreeForCollisions=!0,s.alwaysSelectAsActiveMesh=!1,s.doNotSyncBoundingInfo=!1,s.actionManager=null,s.ellipsoid=new Vector3(.5,1,.5),s.ellipsoidOffset=new Vector3(0,0,0),s.edgesWidth=1,s.edgesColor=new Color4(1,0,0,1),s._edgesRenderer=null,s._masterMesh=null,s._boundingInfo=null,s._boundingInfoIsDirty=!0,s._renderId=0,s._intersectionsInProgress=new Array,s._unIndexed=!1,s._lightSources=new Array,s._waitingData={lods:null,actions:null,freezeWorldMatrix:null},s._bonesTransformMatrices=null,s._transformMatrixTexture=null,s.onRebuildObservable=new Observable,s._onCollisionPositionChange=function(c,d,_){_===void 0&&(_=null),d.subtractToRef(s._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,s._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Engine.CollisionsEpsilon&&s.position.addInPlace(s._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),_&&s.onCollideObservable.notifyObservers(_),s.onCollisionPositionChangeObservable.notifyObservers(s.position)},s.getScene().addMesh(s),s._resyncLightSources(),s._uniformBuffer=new UniformBuffer(s.getScene().getEngine(),void 0,void 0,e),s._buildUniformLayout(),s}return Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return TransformNode.BILLBOARDMODE_NONE},enumerable:!1,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return TransformNode.BILLBOARDMODE_X},enumerable:!1,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return TransformNode.BILLBOARDMODE_Y},enumerable:!1,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return TransformNode.BILLBOARDMODE_Z},enumerable:!1,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return TransformNode.BILLBOARDMODE_ALL},enumerable:!1,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_USE_POSITION",{get:function(){return TransformNode.BILLBOARDMODE_USE_POSITION},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"facetNb",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetNb},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"partitioningSubdivisions",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"partitioningBBoxRatio",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"mustDepthSortFacets",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"facetDepthSortFrom",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"collisionRetryCount",{get:function(){return this._internalAbstractMeshDataInfo._collisionRetryCount},set:function(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isFacetDataEnabled",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"morphTargetManager",{get:function(){return this._internalAbstractMeshDataInfo._morphTargetManager},set:function(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bakedVertexAnimationManager",{get:function(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager},set:function(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),i.prototype._syncGeometryWithMorphTargetManager=function(){},i.prototype._updateNonUniformScalingState=function(e){return a.prototype._updateNonUniformScalingState.call(this,e)?(this._markSubMeshesAsMiscDirty(),!0):!1},Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._internalAbstractMeshDataInfo._visibility},set:function(e){if(this._internalAbstractMeshDataInfo._visibility!==e){var o=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(o===1&&e!==1||o!==1&&e===1)&&this._markSubMeshesAsMiscDirty()}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"renderingGroupId",{get:function(){return this._internalAbstractMeshDataInfo._renderingGroupId},set:function(e){this._internalAbstractMeshDataInfo._renderingGroupId=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._internalAbstractMeshDataInfo._material},set:function(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))},enumerable:!1,configurable:!0}),i.prototype.getMaterialForRenderPass=function(e){var o;return(o=this._internalAbstractMeshDataInfo._materialForRenderPass)===null||o===void 0?void 0:o[e]},i.prototype.setMaterialForRenderPass=function(e,o){this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=o},Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._internalAbstractMeshDataInfo._receiveShadows},set:function(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasVertexAlpha",{get:function(){return this._internalAbstractMeshDataInfo._hasVertexAlpha},set:function(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"useVertexColors",{get:function(){return this._internalAbstractMeshDataInfo._useVertexColors},set:function(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"computeBonesUsingShaders",{get:function(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders},set:function(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"numBoneInfluencers",{get:function(){return this._internalAbstractMeshDataInfo._numBoneInfluencers},set:function(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"applyFog",{get:function(){return this._internalAbstractMeshDataInfo._applyFog},set:function(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"layerMask",{get:function(){return this._internalAbstractMeshDataInfo._layerMask},set:function(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"collisionResponse",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"collisionGroup",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"surroundingMeshes",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lightSources",{get:function(){return this._lightSources},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_positions",{get:function(){return null},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._internalAbstractMeshDataInfo._skeleton},set:function(e){var o=this._internalAbstractMeshDataInfo._skeleton;o&&o.needInitialSkinMatrix&&o._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!1,configurable:!0}),i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e){var o=this._uniformBuffer;o.updateMatrix("world",e),o.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),o.update()},i.prototype.getMeshUniformBuffer=function(){return this._uniformBuffer},i.prototype.getClassName=function(){return"AbstractMesh"},i.prototype.toString=function(e){var o="Name: "+this.name+", isInstance: "+(this.getClassName()!=="InstancedMesh"?"YES":"NO");o+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);var s=this._internalAbstractMeshDataInfo._skeleton;return s&&(o+=", skeleton: "+s.name),e&&(o+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],o+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),o},i.prototype._getEffectiveParent=function(){return this._masterMesh&&this.billboardMode!==TransformNode.BILLBOARDMODE_NONE?this._masterMesh:a.prototype._getEffectiveParent.call(this)},i.prototype._getActionManagerForTrigger=function(e,o){if(o===void 0&&(o=!0),this.actionManager&&(o||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null},i.prototype._rebuild=function(e){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes)for(var o=0,s=this.subMeshes;o<s.length;o++){var c=s[o];c._rebuild()}},i.prototype._resyncLightSources=function(){this._lightSources.length=0;for(var e=0,o=this.getScene().lights;e<o.length;e++){var s=o[e];!s.isEnabled()||s.canAffectMesh(this)&&this._lightSources.push(s)}this._markSubMeshesAsLightDirty()},i.prototype._resyncLightSource=function(e){var o=e.isEnabled()&&e.canAffectMesh(this),s=this._lightSources.indexOf(e),c=!1;if(s===-1){if(!o)return;this._lightSources.push(e)}else{if(o)return;c=!0,this._lightSources.splice(s,1)}this._markSubMeshesAsLightDirty(c)},i.prototype._unBindEffect=function(){for(var e=0,o=this.subMeshes;e<o.length;e++){var s=o[e];s.setEffect(null)}},i.prototype._removeLightSource=function(e,o){var s=this._lightSources.indexOf(e);s!==-1&&(this._lightSources.splice(s,1),this._markSubMeshesAsLightDirty(o))},i.prototype._markSubMeshesAsDirty=function(e){if(!!this.subMeshes)for(var o=0,s=this.subMeshes;o<s.length;o++)for(var c=s[o],d=0;d<c._drawWrappers.length;++d){var _=c._drawWrappers[d];!_||!_.defines||!_.defines.markAllAsDirty||e(_.defines)}},i.prototype._markSubMeshesAsLightDirty=function(e){e===void 0&&(e=!1),this._markSubMeshesAsDirty(function(o){return o.markAsLightDirty(e)})},i.prototype._markSubMeshesAsAttributesDirty=function(){this._markSubMeshesAsDirty(function(e){return e.markAsAttributesDirty()})},i.prototype._markSubMeshesAsMiscDirty=function(){this._markSubMeshesAsDirty(function(e){return e.markAsMiscDirty()})},i.prototype.markAsDirty=function(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},i.prototype.resetDrawCache=function(){if(!!this.subMeshes)for(var e=0,o=this.subMeshes;e<o.length;e++){var s=o[e];s.resetDrawCache()}},Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isBlocked",{get:function(){return!1},enumerable:!1,configurable:!0}),i.prototype.getLOD=function(e){return this},i.prototype.getTotalVertices=function(){return 0},i.prototype.getTotalIndices=function(){return 0},i.prototype.getIndices=function(){return null},i.prototype.getVerticesData=function(e){return null},i.prototype.setVerticesData=function(e,o,s,c){return this},i.prototype.updateVerticesData=function(e,o,s,c){return this},i.prototype.setIndices=function(e,o){return this},i.prototype.isVerticesDataPresent=function(e){return!1},i.prototype.getBoundingInfo=function(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)},i.prototype.setBoundingInfo=function(e){return this._boundingInfo=e,this},Object.defineProperty(i.prototype,"hasBoundingInfo",{get:function(){return this._boundingInfo!==null},enumerable:!1,configurable:!0}),i.prototype.buildBoundingInfo=function(e,o,s){return this._boundingInfo=new BoundingInfo(e,o,s),this._boundingInfo},i.prototype.normalizeToUnitCube=function(e,o,s){return e===void 0&&(e=!0),o===void 0&&(o=!1),a.prototype.normalizeToUnitCube.call(this,e,o,s)},Object.defineProperty(i.prototype,"useBones",{get:function(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)&&this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)},enumerable:!1,configurable:!0}),i.prototype._preActivate=function(){},i.prototype._preActivateForIntermediateRendering=function(e){},i.prototype._activate=function(e,o){return this._renderId=e,!0},i.prototype._postActivate=function(){},i.prototype._freeze=function(){},i.prototype._unFreeze=function(){},i.prototype.getWorldMatrix=function(){return this._masterMesh&&this.billboardMode===TransformNode.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():a.prototype.getWorldMatrix.call(this)},i.prototype._getWorldMatrixDeterminant=function(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():a.prototype._getWorldMatrixDeterminant.call(this)},Object.defineProperty(i.prototype,"isAnInstance",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasInstances",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasThinInstances",{get:function(){return!1},enumerable:!1,configurable:!0}),i.prototype.movePOV=function(e,o,s){return this.position.addInPlace(this.calcMovePOV(e,o,s)),this},i.prototype.calcMovePOV=function(e,o,s){var c=new Matrix,d=this.rotationQuaternion?this.rotationQuaternion:Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);d.toRotationMatrix(c);var _=Vector3.Zero(),b=this.definedFacingForward?-1:1;return Vector3.TransformCoordinatesFromFloatsToRef(e*b,o,s*b,c,_),_},i.prototype.rotatePOV=function(e,o,s){return this.rotation.addInPlace(this.calcRotatePOV(e,o,s)),this},i.prototype.calcRotatePOV=function(e,o,s){var c=this.definedFacingForward?1:-1;return new Vector3(e*c,o,s*c)},i.prototype.refreshBoundingInfo=function(e,o){return e===void 0&&(e=!1),o===void 0&&(o=!1),this._boundingInfo&&this._boundingInfo.isLocked?this:(this._refreshBoundingInfo(this._getPositionData(e,o),null),this)},i.prototype._refreshBoundingInfo=function(e,o){if(e){var s=extractMinAndMax(e,0,this.getTotalVertices(),o);this._boundingInfo?this._boundingInfo.reConstruct(s.minimum,s.maximum):this._boundingInfo=new BoundingInfo(s.minimum,s.maximum)}if(this.subMeshes)for(var c=0;c<this.subMeshes.length;c++)this.subMeshes[c].refreshBoundingInfo(e);this._updateBoundingInfo()},i.prototype._getPositionData=function(e,o){var s,c=this.getVerticesData(VertexBuffer.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),c&&(e&&this.skeleton||o&&this.morphTargetManager)&&(c=Tools.Slice(c),this._generatePointsArray(),this._positions)){var d=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(d.length);for(var _=0;_<d.length;_++)this._internalAbstractMeshDataInfo._positions[_]=((s=d[_])===null||s===void 0?void 0:s.clone())||new Vector3}if(c&&o&&this.morphTargetManager)for(var b=0,k=0,j=0;j<c.length;j++){for(var $=0;$<this.morphTargetManager.numTargets;$++){var _e=this.morphTargetManager.getTarget($),et=_e.influence;if(et>0){var tt=_e.getPositions();tt&&(c[j]+=(tt[j]-c[j])*et)}}if(b++,this._positions&&b===3){b=0;var rt=k*3;this._positions[k++].copyFromFloats(c[rt],c[rt+1],c[rt+2])}}if(c&&e&&this.skeleton){var it=this.getVerticesData(VertexBuffer.MatricesIndicesKind),nt=this.getVerticesData(VertexBuffer.MatricesWeightsKind);if(nt&&it){var ot=this.numBoneInfluencers>4,at=ot?this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind):null,st=ot?this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind):null;this.skeleton.prepare();for(var ut=this.skeleton.getTransformMatrices(this),ft=TmpVectors.Vector3[0],lt=TmpVectors.Matrix[0],ht=TmpVectors.Matrix[1],pt=0,mt=0;mt<c.length;mt+=3,pt+=4){lt.reset();var dt,gt;for(dt=0;dt<4;dt++)gt=nt[pt+dt],gt>0&&(Matrix.FromFloat32ArrayToRefScaled(ut,Math.floor(it[pt+dt]*16),gt,ht),lt.addToSelf(ht));if(ot)for(dt=0;dt<4;dt++)gt=st[pt+dt],gt>0&&(Matrix.FromFloat32ArrayToRefScaled(ut,Math.floor(at[pt+dt]*16),gt,ht),lt.addToSelf(ht));Vector3.TransformCoordinatesFromFloatsToRef(c[mt],c[mt+1],c[mt+2],lt,ft),ft.toArray(c,mt),this._positions&&this._positions[mt/3].copyFrom(ft)}}}return c},i.prototype._updateBoundingInfo=function(){var e=this._effectiveMesh;return this._boundingInfo?this._boundingInfo.update(e.worldMatrixFromCache):this._boundingInfo=new BoundingInfo(this.position,this.position,e.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(e.worldMatrixFromCache),this},i.prototype._updateSubMeshesBoundingInfo=function(e){if(!this.subMeshes)return this;for(var o=this.subMeshes.length,s=0;s<o;s++){var c=this.subMeshes[s];(o>1||!c.IsGlobal)&&c.updateBoundingInfo(e)}return this},i.prototype._afterComputeWorldMatrix=function(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)},Object.defineProperty(i.prototype,"_effectiveMesh",{get:function(){return this.skeleton&&this.skeleton.overrideMesh||this},enumerable:!1,configurable:!0}),i.prototype.isInFrustum=function(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)},i.prototype.isCompletelyInFrustum=function(e){return this.getBoundingInfo().isCompletelyInFrustum(e)},i.prototype.intersectsMesh=function(e,o,s){o===void 0&&(o=!1);var c=this.getBoundingInfo(),d=e.getBoundingInfo();if(c.intersects(d,o))return!0;if(s)for(var _=0,b=this.getChildMeshes();_<b.length;_++){var k=b[_];if(k.intersectsMesh(e,o,!0))return!0}return!1},i.prototype.intersectsPoint=function(e){return this.getBoundingInfo().intersectsPoint(e)},Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"collider",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider},enumerable:!1,configurable:!0}),i.prototype.moveWithCollisions=function(e){var o=this.getAbsolutePosition();o.addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);var s=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=s.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,s.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this},i.prototype._collideForSubMesh=function(e,o,s){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(o)){e._lastColliderTransformMatrix=o.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var c=e.verticesStart,d=e.verticesStart+e.verticesCount,_=c;_<d;_++)e._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[_],o))}return s._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this),this},i.prototype._processCollisionsForSubMeshes=function(e,o){for(var s=this._scene.getCollidingSubMeshCandidates(this,e),c=s.length,d=0;d<c;d++){var _=s.data[d];c>1&&!_._checkCollision(e)||this._collideForSubMesh(_,o,e)}return this},i.prototype._checkCollision=function(e){if(!this.getBoundingInfo()._checkCollision(e))return this;var o=TmpVectors.Matrix[0],s=TmpVectors.Matrix[1];return Matrix.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,o),this.worldMatrixFromCache.multiplyToRef(o,s),this._processCollisionsForSubMeshes(e,s),this},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(e,o,s,c,d,_){c===void 0&&(c=!1),_===void 0&&(_=!1);var b=new PickingInfo,k=this.getClassName()==="InstancedLinesMesh"||this.getClassName()==="LinesMesh"?this.intersectionThreshold:0,j=this.getBoundingInfo();if(!this.subMeshes||!_&&(!e.intersectsSphere(j.boundingSphere,k)||!e.intersectsBox(j.boundingBox,k)))return b;if(c)return b.hit=!_,b.pickedMesh=_?null:this,b.distance=_?0:Vector3.Distance(e.origin,j.boundingSphere.center),b.subMeshId=0,b;if(!this._generatePointsArray())return b;for(var $=null,_e=this._scene.getIntersectingSubMeshCandidates(this,e),et=_e.length,tt=!1,rt=0;rt<et;rt++){var it=_e.data[rt],nt=it.getMaterial();if(!!nt&&(nt.fillMode==7||nt.fillMode==0||nt.fillMode==1||nt.fillMode==2)){tt=!0;break}}if(!tt)return b.hit=!0,b.pickedMesh=this,b.distance=Vector3.Distance(e.origin,j.boundingSphere.center),b.subMeshId=-1,b;for(var rt=0;rt<et;rt++){var it=_e.data[rt];if(!(et>1&&!it.canIntersects(e))){var ot=it.intersects(e,this._positions,this.getIndices(),o,s);if(ot&&(o||!$||ot.distance<$.distance)&&($=ot,$.subMeshId=rt,o))break}}if($){var at=d!=null?d:this.skeleton&&this.skeleton.overrideMesh?this.skeleton.overrideMesh.getWorldMatrix():this.getWorldMatrix(),st=TmpVectors.Vector3[0],ut=TmpVectors.Vector3[1];Vector3.TransformCoordinatesToRef(e.origin,at,st),e.direction.scaleToRef($.distance,ut);var ft=Vector3.TransformNormal(ut,at),lt=ft.addInPlace(st);return b.hit=!0,b.distance=Vector3.Distance(st,lt),b.pickedPoint=lt,b.pickedMesh=this,b.bu=$.bu||0,b.bv=$.bv||0,b.subMeshFaceId=$.faceId,b.faceId=$.faceId+_e.data[$.subMeshId].indexStart/(this.getClassName().indexOf("LinesMesh")!==-1?2:3),b.subMeshId=$.subMeshId,b}return b},i.prototype.clone=function(e,o,s){return null},i.prototype.releaseSubMeshes=function(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=new Array;return this},i.prototype.dispose=function(e,o){var s=this;o===void 0&&(o=!1);var c;for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this.getScene().freeActiveMeshes(),this.getScene().freeRenderingGroups(),this.actionManager!==void 0&&this.actionManager!==null&&(this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),c=0;c<this._intersectionsInProgress.length;c++){var d=this._intersectionsInProgress[c],_=d._intersectionsInProgress.indexOf(this);d._intersectionsInProgress.splice(_,1)}this._intersectionsInProgress=[];var b=this.getScene().lights;b.forEach(function($){var _e=$.includedOnlyMeshes.indexOf(s);_e!==-1&&$.includedOnlyMeshes.splice(_e,1),_e=$.excludedMeshes.indexOf(s),_e!==-1&&$.excludedMeshes.splice(_e,1);var et=$.getShadowGenerator();if(et){var tt=et.getShadowMap();tt&&tt.renderList&&(_e=tt.renderList.indexOf(s),_e!==-1&&tt.renderList.splice(_e,1))}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();var k=this.getScene().getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,k.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),k.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){var j=this._parentContainer.meshes.indexOf(this);j>-1&&this._parentContainer.meshes.splice(j,1),this._parentContainer=null}if(o&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(c=0;c<this.getScene().particleSystems.length;c++)this.getScene().particleSystems[c].emitter===this&&(this.getScene().particleSystems[c].dispose(),c--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),a.prototype.dispose.call(this,e,o)},i.prototype.addChild=function(e,o){return o===void 0&&(o=!1),e.setParent(this,o),this},i.prototype.removeChild=function(e,o){return o===void 0&&(o=!1),e.setParent(null,o),this},i.prototype._initFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=new Array),e.facetPositions||(e.facetPositions=new Array),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(var o=0;o<e.facetNb;o++)e.facetNormals[o]=Vector3.Zero(),e.facetPositions[o]=Vector3.Zero();return e.facetDataEnabled=!0,this},i.prototype.updateFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();var o=this.getVerticesData(VertexBuffer.PositionKind),s=this.getIndices(),c=this.getVerticesData(VertexBuffer.NormalKind),d=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,s instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(s);else if(s instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(s);else{for(var _=!1,b=0;b<s.length;b++)if(s[b]>65535){_=!0;break}_?e.depthSortedIndices=new Uint32Array(s):e.depthSortedIndices=new Uint16Array(s)}if(e.facetDepthSortFunction=function(rt,it){return it.sqDistance-rt.sqDistance},!e.facetDepthSortFrom){var k=this.getScene().activeCamera;e.facetDepthSortFrom=k?k.position:Vector3.Zero()}e.depthSortedFacets=[];for(var j=0;j<e.facetNb;j++){var $={ind:j*3,sqDistance:0};e.depthSortedFacets.push($)}e.invertedMatrix=Matrix.Identity(),e.facetDepthSortOrigin=Vector3.Zero()}e.bbSize.x=d.maximum.x-d.minimum.x>Epsilon?d.maximum.x-d.minimum.x:Epsilon,e.bbSize.y=d.maximum.y-d.minimum.y>Epsilon?d.maximum.y-d.minimum.y:Epsilon,e.bbSize.z=d.maximum.z-d.minimum.z>Epsilon?d.maximum.z-d.minimum.z:Epsilon;var _e=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(_e=_e>e.bbSize.z?_e:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/_e),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/_e),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/_e),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=d,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),Vector3.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,c&&VertexData.ComputeNormals(o,s,c,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);for(var et=e.depthSortedIndices.length/3|0,j=0;j<et;j++){var tt=e.depthSortedFacets[j].ind;e.depthSortedIndices[j*3]=s[tt],e.depthSortedIndices[j*3+1]=s[tt+1],e.depthSortedIndices[j*3+2]=s[tt+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this},i.prototype.getFacetLocalNormals=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals},i.prototype.getFacetLocalPositions=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions},i.prototype.getFacetLocalPartitioning=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning},i.prototype.getFacetPosition=function(e){var o=Vector3.Zero();return this.getFacetPositionToRef(e,o),o},i.prototype.getFacetPositionToRef=function(e,o){var s=this.getFacetLocalPositions()[e],c=this.getWorldMatrix();return Vector3.TransformCoordinatesToRef(s,c,o),this},i.prototype.getFacetNormal=function(e){var o=Vector3.Zero();return this.getFacetNormalToRef(e,o),o},i.prototype.getFacetNormalToRef=function(e,o){var s=this.getFacetLocalNormals()[e];return Vector3.TransformNormalToRef(s,this.getWorldMatrix(),o),this},i.prototype.getFacetsAtLocalCoordinates=function(e,o,s){var c=this.getBoundingInfo(),d=this._internalAbstractMeshDataInfo._facetData,_=Math.floor((e-c.minimum.x*d.partitioningBBoxRatio)*d.subDiv.X*d.partitioningBBoxRatio/d.bbSize.x),b=Math.floor((o-c.minimum.y*d.partitioningBBoxRatio)*d.subDiv.Y*d.partitioningBBoxRatio/d.bbSize.y),k=Math.floor((s-c.minimum.z*d.partitioningBBoxRatio)*d.subDiv.Z*d.partitioningBBoxRatio/d.bbSize.z);return _<0||_>d.subDiv.max||b<0||b>d.subDiv.max||k<0||k>d.subDiv.max?null:d.facetPartitioning[_+d.subDiv.max*b+d.subDiv.max*d.subDiv.max*k]},i.prototype.getClosestFacetAtCoordinates=function(e,o,s,c,d,_){d===void 0&&(d=!1),_===void 0&&(_=!0);var b=this.getWorldMatrix(),k=TmpVectors.Matrix[5];b.invertToRef(k);var j=TmpVectors.Vector3[8];Vector3.TransformCoordinatesFromFloatsToRef(e,o,s,k,j);var $=this.getClosestFacetAtLocalCoordinates(j.x,j.y,j.z,c,d,_);return c&&Vector3.TransformCoordinatesFromFloatsToRef(c.x,c.y,c.z,b,c),$},i.prototype.getClosestFacetAtLocalCoordinates=function(e,o,s,c,d,_){d===void 0&&(d=!1),_===void 0&&(_=!0);var b=null,k=0,j=0,$=0,_e=0,et=0,tt=0,rt=0,it=0,nt=this.getFacetLocalPositions(),ot=this.getFacetLocalNormals(),at=this.getFacetsAtLocalCoordinates(e,o,s);if(!at)return null;for(var st=Number.MAX_VALUE,ut=st,ft,lt,ht,pt=0;pt<at.length;pt++)ft=at[pt],lt=ot[ft],ht=nt[ft],_e=(e-ht.x)*lt.x+(o-ht.y)*lt.y+(s-ht.z)*lt.z,(!d||d&&_&&_e>=0||d&&!_&&_e<=0)&&(_e=lt.x*ht.x+lt.y*ht.y+lt.z*ht.z,et=-(lt.x*e+lt.y*o+lt.z*s-_e)/(lt.x*lt.x+lt.y*lt.y+lt.z*lt.z),tt=e+lt.x*et,rt=o+lt.y*et,it=s+lt.z*et,k=tt-e,j=rt-o,$=it-s,ut=k*k+j*j+$*$,ut<st&&(st=ut,b=ft,c&&(c.x=tt,c.y=rt,c.z=it)));return b},i.prototype.getFacetDataParameters=function(){return this._internalAbstractMeshDataInfo._facetData.facetParameters},i.prototype.disableFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=new Array,e.facetNormals=new Array,e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this},i.prototype.updateIndices=function(e,o,s){return this},i.prototype.createNormals=function(e){var o=this.getVerticesData(VertexBuffer.PositionKind),s=this.getIndices(),c;return this.isVerticesDataPresent(VertexBuffer.NormalKind)?c=this.getVerticesData(VertexBuffer.NormalKind):c=[],VertexData.ComputeNormals(o,s,c,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(VertexBuffer.NormalKind,c,e),this},i.prototype.alignWithNormal=function(e,o){o||(o=Axis.Y);var s=TmpVectors.Vector3[0],c=TmpVectors.Vector3[1];return Vector3.CrossToRef(o,e,c),Vector3.CrossToRef(e,c,s),this.rotationQuaternion?Quaternion.RotationQuaternionFromAxisToRef(s,e,c,this.rotationQuaternion):Vector3.RotationFromAxisToRef(s,e,c,this.rotation),this},i.prototype._checkOcclusionQuery=function(){return!1},i.prototype.disableEdgesRendering=function(){throw _WarnImport("EdgesRenderer")},i.prototype.enableEdgesRendering=function(e,o,s){throw _WarnImport("EdgesRenderer")},i.prototype.getConnectedParticleSystems=function(){var e=this;return this._scene.particleSystems.filter(function(o){return o.emitter===e})},i.OCCLUSION_TYPE_NONE=0,i.OCCLUSION_TYPE_OPTIMISTIC=1,i.OCCLUSION_TYPE_STRICT=2,i.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,i.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,i.CULLINGSTRATEGY_STANDARD=0,i.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,i.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,i.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,i}(TransformNode);RegisterClass("BABYLON.AbstractMesh",AbstractMesh);var _TimeToken=function(){function a(){this._timeElapsedQueryEnded=!1}return a}(),_OcclusionDataStorage=function(){function a(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=AbstractMesh.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE}return a}();Engine.prototype.createQuery=function(){return this._gl.createQuery()};Engine.prototype.deleteQuery=function(a){return this._gl.deleteQuery(a),this};Engine.prototype.isQueryResultAvailable=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT_AVAILABLE)};Engine.prototype.getQueryResult=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT)};Engine.prototype.beginOcclusionQuery=function(a,i){var e=this._getGlAlgorithmType(a);return this._gl.beginQuery(e,i),!0};Engine.prototype.endOcclusionQuery=function(a){var i=this._getGlAlgorithmType(a);return this._gl.endQuery(i),this};Engine.prototype._createTimeQuery=function(){var a=this.getCaps().timerQuery;return a.createQueryEXT?a.createQueryEXT():this.createQuery()};Engine.prototype._deleteTimeQuery=function(a){var i=this.getCaps().timerQuery;if(i.deleteQueryEXT){i.deleteQueryEXT(a);return}this.deleteQuery(a)};Engine.prototype._getTimeQueryResult=function(a){var i=this.getCaps().timerQuery;return i.getQueryObjectEXT?i.getQueryObjectEXT(a,i.QUERY_RESULT_EXT):this.getQueryResult(a)};Engine.prototype._getTimeQueryAvailability=function(a){var i=this.getCaps().timerQuery;return i.getQueryObjectEXT?i.getQueryObjectEXT(a,i.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(a)};Engine.prototype.startTimeQuery=function(){var a=this.getCaps(),i=a.timerQuery;if(!i)return null;var e=new _TimeToken;if(this._gl.getParameter(i.GPU_DISJOINT_EXT),a.canUseTimestampForTimerQuery)e._startTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._startTimeQuery,i.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;e._timeElapsedQuery=this._createTimeQuery(),i.beginQueryEXT?i.beginQueryEXT(i.TIME_ELAPSED_EXT,e._timeElapsedQuery):this._gl.beginQuery(i.TIME_ELAPSED_EXT,e._timeElapsedQuery),this._currentNonTimestampToken=e}return e};Engine.prototype.endTimeQuery=function(a){var i=this.getCaps(),e=i.timerQuery;if(!e||!a)return-1;if(i.canUseTimestampForTimerQuery){if(!a._startTimeQuery)return-1;a._endTimeQuery||(a._endTimeQuery=this._createTimeQuery(),e.queryCounterEXT(a._endTimeQuery,e.TIMESTAMP_EXT))}else if(!a._timeElapsedQueryEnded){if(!a._timeElapsedQuery)return-1;e.endQueryEXT?e.endQueryEXT(e.TIME_ELAPSED_EXT):this._gl.endQuery(e.TIME_ELAPSED_EXT),a._timeElapsedQueryEnded=!0}var o=this._gl.getParameter(e.GPU_DISJOINT_EXT),s=!1;if(a._endTimeQuery?s=this._getTimeQueryAvailability(a._endTimeQuery):a._timeElapsedQuery&&(s=this._getTimeQueryAvailability(a._timeElapsedQuery)),s&&!o){var c=0;if(i.canUseTimestampForTimerQuery){if(!a._startTimeQuery||!a._endTimeQuery)return-1;var d=this._getTimeQueryResult(a._startTimeQuery),_=this._getTimeQueryResult(a._endTimeQuery);c=_-d,this._deleteTimeQuery(a._startTimeQuery),this._deleteTimeQuery(a._endTimeQuery),a._startTimeQuery=null,a._endTimeQuery=null}else{if(!a._timeElapsedQuery)return-1;c=this._getTimeQueryResult(a._timeElapsedQuery),this._deleteTimeQuery(a._timeElapsedQuery),a._timeElapsedQuery=null,a._timeElapsedQueryEnded=!1,this._currentNonTimestampToken=null}return c}return-1};Engine.prototype._captureGPUFrameTime=!1;Engine.prototype._gpuFrameTime=new PerfCounter;Engine.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime};Engine.prototype.captureGPUFrameTime=function(a){var i=this;a!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=a,a?(this._onBeginFrameObserver=this.onBeginFrameObservable.add(function(){i._gpuFrameTimeToken||(i._gpuFrameTimeToken=i.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(function(){if(!!i._gpuFrameTimeToken){var e=i.endTimeQuery(i._gpuFrameTimeToken);e>-1&&(i._gpuFrameTimeToken=null,i._gpuFrameTime.fetchNewFrame(),i._gpuFrameTime.addCount(e,!0))}})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))};Engine.prototype._getGlAlgorithmType=function(a){return a===AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};Object.defineProperty(AbstractMesh.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(a){this._occlusionDataStorage.isOcclusionQueryInProgress=a},enumerable:!1,configurable:!0});Object.defineProperty(AbstractMesh.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new _OcclusionDataStorage),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(AbstractMesh.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(a){this._occlusionDataStorage.isOccluded=a},enumerable:!0,configurable:!0});Object.defineProperty(AbstractMesh.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(a){this._occlusionDataStorage.occlusionQueryAlgorithmType=a},enumerable:!0,configurable:!0});Object.defineProperty(AbstractMesh.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(a){this._occlusionDataStorage.occlusionType=a},enumerable:!0,configurable:!0});Object.defineProperty(AbstractMesh.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(a){this._occlusionDataStorage.occlusionRetryCount=a},enumerable:!0,configurable:!0});AbstractMesh.prototype._checkOcclusionQuery=function(){var a=this._occlusionDataStorage;if(a.occlusionType===AbstractMesh.OCCLUSION_TYPE_NONE)return a.isOccluded=!1,!1;var i=this.getEngine();if(!i.getCaps().supportOcclusionQuery||!i.isQueryResultAvailable)return a.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery){var e=i.isQueryResultAvailable(this._occlusionQuery);if(e){var o=i.getQueryResult(this._occlusionQuery);a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=!(o>0)}else if(a.occlusionInternalRetryCounter++,a.occlusionRetryCount!==-1&&a.occlusionInternalRetryCounter>a.occlusionRetryCount)a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=a.occlusionType===AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;else return a.occlusionType===AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded}var s=this.getScene();if(s.getBoundingBoxRenderer){var c=s.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=i.createQuery()),i.beginOcclusionQuery(a.occlusionQueryAlgorithmType,this._occlusionQuery)&&(c.renderOcclusionBoundingBox(this),i.endOcclusionQuery(a.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return a.isOccluded};Engine.prototype.createTransformFeedback=function(){return this._gl.createTransformFeedback()};Engine.prototype.deleteTransformFeedback=function(a){this._gl.deleteTransformFeedback(a)};Engine.prototype.bindTransformFeedback=function(a){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,a)};Engine.prototype.beginTransformFeedback=function(a){a===void 0&&(a=!0),this._gl.beginTransformFeedback(a?this._gl.POINTS:this._gl.TRIANGLES)};Engine.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};Engine.prototype.setTranformFeedbackVaryings=function(a,i){this._gl.transformFeedbackVaryings(a,i,this._gl.INTERLEAVED_ATTRIBS)};Engine.prototype.bindTransformFeedbackBuffer=function(a){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,a?a.underlyingResource:null)};var SmartArray=function(){function a(i){this.length=0,this.data=new Array(i),this._id=a._GlobalId++}return a.prototype.push=function(i){this.data[this.length++]=i,this.length>this.data.length&&(this.data.length*=2)},a.prototype.forEach=function(i){for(var e=0;e<this.length;e++)i(this.data[e])},a.prototype.sort=function(i){this.data.sort(i)},a.prototype.reset=function(){this.length=0},a.prototype.dispose=function(){this.reset(),this.data&&(this.data.length=0,this.data=[])},a.prototype.concat=function(i){if(i.length!==0){this.length+i.length>this.data.length&&(this.data.length=(this.length+i.length)*2);for(var e=0;e<i.length;e++)this.data[this.length++]=(i.data||i)[e]}},a.prototype.indexOf=function(i){var e=this.data.indexOf(i);return e>=this.length?-1:e},a.prototype.contains=function(i){return this.indexOf(i)!==-1},a._GlobalId=0,a}(),SmartArrayNoDuplicate=function(a){__extends(i,a);function i(){var e=a!==null&&a.apply(this,arguments)||this;return e._duplicateId=0,e}return i.prototype.push=function(e){a.prototype.push.call(this,e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId},i.prototype.pushNoDuplicate=function(e){return e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId?!1:(this.push(e),!0)},i.prototype.reset=function(){a.prototype.reset.call(this),this._duplicateId++},i.prototype.concatWithNoDuplicate=function(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(var o=0;o<e.length;o++){var s=(e.data||e)[o];this.pushNoDuplicate(s)}}},i}(SmartArray),Viewport=function(){function a(i,e,o,s){this.x=i,this.y=e,this.width=o,this.height=s}return a.prototype.toGlobal=function(i,e){return new a(this.x*i,this.y*e,this.width*i,this.height*e)},a.prototype.toGlobalToRef=function(i,e,o){return o.x=this.x*i,o.y=this.y*e,o.width=this.width*i,o.height=this.height*e,this},a.prototype.clone=function(){return new a(this.x,this.y,this.width,this.height)},a}(),Plane=function(){function a(i,e,o,s){this.normal=new Vector3(i,e,o),this.d=s}return a.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},a.prototype.clone=function(){return new a(this.normal.x,this.normal.y,this.normal.z,this.d)},a.prototype.getClassName=function(){return"Plane"},a.prototype.getHashCode=function(){var i=this.normal.getHashCode();return i=i*397^(this.d|0),i},a.prototype.normalize=function(){var i=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),e=0;return i!==0&&(e=1/i),this.normal.x*=e,this.normal.y*=e,this.normal.z*=e,this.d*=e,this},a.prototype.transform=function(i){var e=a._TmpMatrix;i.invertToRef(e);var o=e.m,s=this.normal.x,c=this.normal.y,d=this.normal.z,_=this.d,b=s*o[0]+c*o[1]+d*o[2]+_*o[3],k=s*o[4]+c*o[5]+d*o[6]+_*o[7],j=s*o[8]+c*o[9]+d*o[10]+_*o[11],$=s*o[12]+c*o[13]+d*o[14]+_*o[15];return new a(b,k,j,$)},a.prototype.dotCoordinate=function(i){return this.normal.x*i.x+this.normal.y*i.y+this.normal.z*i.z+this.d},a.prototype.copyFromPoints=function(i,e,o){var s=e.x-i.x,c=e.y-i.y,d=e.z-i.z,_=o.x-i.x,b=o.y-i.y,k=o.z-i.z,j=c*k-d*b,$=d*_-s*k,_e=s*b-c*_,et=Math.sqrt(j*j+$*$+_e*_e),tt;return et!==0?tt=1/et:tt=0,this.normal.x=j*tt,this.normal.y=$*tt,this.normal.z=_e*tt,this.d=-(this.normal.x*i.x+this.normal.y*i.y+this.normal.z*i.z),this},a.prototype.isFrontFacingTo=function(i,e){var o=Vector3.Dot(this.normal,i);return o<=e},a.prototype.signedDistanceTo=function(i){return Vector3.Dot(i,this.normal)+this.d},a.FromArray=function(i){return new a(i[0],i[1],i[2],i[3])},a.FromPoints=function(i,e,o){var s=new a(0,0,0,0);return s.copyFromPoints(i,e,o),s},a.FromPositionAndNormal=function(i,e){var o=new a(0,0,0,0);return e.normalize(),o.normal=e,o.d=-(e.x*i.x+e.y*i.y+e.z*i.z),o},a.SignedDistanceToPlaneFromPositionAndNormal=function(i,e,o){var s=-(e.x*i.x+e.y*i.y+e.z*i.z);return Vector3.Dot(o,e)+s},a._TmpMatrix=Matrix.Identity(),a}(),Frustum=function(){function a(){}return a.GetPlanes=function(i){for(var e=[],o=0;o<6;o++)e.push(new Plane(0,0,0,0));return a.GetPlanesToRef(i,e),e},a.GetNearPlaneToRef=function(i,e){var o=i.m;e.normal.x=o[3]+o[2],e.normal.y=o[7]+o[6],e.normal.z=o[11]+o[10],e.d=o[15]+o[14],e.normalize()},a.GetFarPlaneToRef=function(i,e){var o=i.m;e.normal.x=o[3]-o[2],e.normal.y=o[7]-o[6],e.normal.z=o[11]-o[10],e.d=o[15]-o[14],e.normalize()},a.GetLeftPlaneToRef=function(i,e){var o=i.m;e.normal.x=o[3]+o[0],e.normal.y=o[7]+o[4],e.normal.z=o[11]+o[8],e.d=o[15]+o[12],e.normalize()},a.GetRightPlaneToRef=function(i,e){var o=i.m;e.normal.x=o[3]-o[0],e.normal.y=o[7]-o[4],e.normal.z=o[11]-o[8],e.d=o[15]-o[12],e.normalize()},a.GetTopPlaneToRef=function(i,e){var o=i.m;e.normal.x=o[3]-o[1],e.normal.y=o[7]-o[5],e.normal.z=o[11]-o[9],e.d=o[15]-o[13],e.normalize()},a.GetBottomPlaneToRef=function(i,e){var o=i.m;e.normal.x=o[3]+o[1],e.normal.y=o[7]+o[5],e.normal.z=o[11]+o[9],e.d=o[15]+o[13],e.normalize()},a.GetPlanesToRef=function(i,e){a.GetNearPlaneToRef(i,e[0]),a.GetFarPlaneToRef(i,e[1]),a.GetLeftPlaneToRef(i,e[2]),a.GetRightPlaneToRef(i,e[3]),a.GetTopPlaneToRef(i,e[4]),a.GetBottomPlaneToRef(i,e[5])},a}(),Camera$1=function(a){__extends(i,a);function i(e,o,s,c){c===void 0&&(c=!0);var d=a.call(this,e,s)||this;return d._position=Vector3.Zero(),d._upVector=Vector3.Up(),d.orthoLeft=null,d.orthoRight=null,d.orthoBottom=null,d.orthoTop=null,d.fov=.8,d.projectionPlaneTilt=0,d.minZ=1,d.maxZ=1e4,d.inertia=.9,d.mode=i.PERSPECTIVE_CAMERA,d.isIntermediate=!1,d.viewport=new Viewport(0,0,1,1),d.layerMask=268435455,d.fovMode=i.FOVMODE_VERTICAL_FIXED,d.cameraRigMode=i.RIG_MODE_NONE,d.customRenderTargets=new Array,d.outputRenderTarget=null,d.onViewMatrixChangedObservable=new Observable,d.onProjectionMatrixChangedObservable=new Observable,d.onAfterCheckInputsObservable=new Observable,d.onRestoreStateObservable=new Observable,d.isRigCamera=!1,d._rigCameras=new Array,d._webvrViewMatrix=Matrix.Identity(),d._skipRendering=!1,d._projectionMatrix=new Matrix,d._postProcesses=new Array,d._activeMeshes=new SmartArray(256),d._globalPosition=Vector3.Zero(),d._computedViewMatrix=Matrix.Identity(),d._doNotComputeProjectionMatrix=!1,d._transformMatrix=Matrix.Zero(),d._refreshFrustumPlanes=!0,d._absoluteRotation=Quaternion.Identity(),d._isCamera=!0,d._isLeftCamera=!1,d._isRightCamera=!1,d.getScene().addCamera(d),c&&!d.getScene().activeCamera&&(d.getScene().activeCamera=d),d.position=o,d.renderPassId=d.getScene().getEngine().createRenderPassId("Camera "+e),d}return Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"upVector",{get:function(){return this._upVector},set:function(e){this._upVector=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"screenArea",{get:function(){var e,o,s,c,d=0,_=0;if(this.mode===i.PERSPECTIVE_CAMERA)this.fovMode===i.FOVMODE_VERTICAL_FIXED?(_=this.minZ*2*Math.tan(this.fov/2),d=this.getEngine().getAspectRatio(this)*_):(d=this.minZ*2*Math.tan(this.fov/2),_=d/this.getEngine().getAspectRatio(this));else{var b=this.getEngine().getRenderWidth()/2,k=this.getEngine().getRenderHeight()/2;d=((e=this.orthoRight)!==null&&e!==void 0?e:b)-((o=this.orthoLeft)!==null&&o!==void 0?o:-b),_=((s=this.orthoTop)!==null&&s!==void 0?s:k)-((c=this.orthoBottom)!==null&&c!==void 0?c:-k)}return d*_},enumerable:!1,configurable:!0}),i.prototype.storeState=function(){return this._stateStored=!0,this._storedFov=this.fov,this},i.prototype._restoreStateValues=function(){return this._stateStored?(this.fov=this._storedFov,!0):!1},i.prototype.restoreState=function(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1},i.prototype.getClassName=function(){return"Camera"},i.prototype.toString=function(e){var o="Name: "+this.name;if(o+=", type: "+this.getClassName(),this.animations)for(var s=0;s<this.animations.length;s++)o+=", animation[0]: "+this.animations[s].toString(e);return o},i.prototype.applyVerticalCorrection=function(){var e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x},Object.defineProperty(i.prototype,"globalPosition",{get:function(){return this._globalPosition},enumerable:!1,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},i.prototype.isReady=function(e){if(e===void 0&&(e=!1),e)for(var o=0,s=this._postProcesses;o<s.length;o++){var c=s[o];if(c&&!c.isReady())return!1}return a.prototype.isReady.call(this,e)},i.prototype._initCache=function(){a.prototype._initCache.call(this),this._cache.position=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0},i.prototype._updateCache=function(e){e||a.prototype._updateCache.call(this),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)},i.prototype._isSynchronized=function(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()},i.prototype._isSynchronizedViewMatrix=function(){return a.prototype._isSynchronized.call(this)?this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent():!1},i.prototype._isSynchronizedProjectionMatrix=function(){var e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;var o=this.getEngine();return this.mode===i.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===o.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===o.getRenderWidth()&&this._cache.renderHeight===o.getRenderHeight(),e},i.prototype.attachControl=function(e,o){},i.prototype.detachControl=function(e){},i.prototype.update=function(){this._checkInputs(),this.cameraRigMode!==i.RIG_MODE_NONE&&this._updateRigCameras()},i.prototype._checkInputs=function(){this.onAfterCheckInputsObservable.notifyObservers(this)},Object.defineProperty(i.prototype,"rigCameras",{get:function(){return this._rigCameras},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rigPostProcess",{get:function(){return this._rigPostProcess},enumerable:!1,configurable:!0}),i.prototype._getFirstPostProcess=function(){for(var e=0;e<this._postProcesses.length;e++)if(this._postProcesses[e]!==null)return this._postProcesses[e];return null},i.prototype._cascadePostProcessesToRigCams=function(){var e=this._getFirstPostProcess();e&&e.markTextureDirty();for(var o=0,s=this._rigCameras.length;o<s;o++){var c=this._rigCameras[o],d=c._rigPostProcess;if(d){var _=d.getEffectName()==="pass";_&&(c.isIntermediate=this._postProcesses.length===0),c._postProcesses=this._postProcesses.slice(0).concat(d),d.markTextureDirty()}else c._postProcesses=this._postProcesses.slice(0)}},i.prototype.attachPostProcess=function(e,o){return o===void 0&&(o=null),!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(Logger$2.Error("You're trying to reuse a post process not defined as reusable."),0):(o==null||o<0?this._postProcesses.push(e):this._postProcesses[o]===null?this._postProcesses[o]=e:this._postProcesses.splice(o,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))},i.prototype.detachPostProcess=function(e){var o=this._postProcesses.indexOf(e);o!==-1&&(this._postProcesses[o]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()},i.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)},i.prototype._getViewMatrix=function(){return Matrix.Identity()},i.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(e){var o,s,c,d,_,b,k,j;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var $=this.getEngine(),_e=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=$.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);var et=$.useReverseDepthBuffer,tt=void 0;_e.useRightHandedSystem?tt=Matrix.PerspectiveFovRHToRef:tt=Matrix.PerspectiveFovLHToRef,tt(this.fov,$.getAspectRatio(this),et?this.maxZ:this.minZ,et?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED,$.isNDCHalfZRange,this.projectionPlaneTilt,$.useReverseDepthBuffer)}else{var rt=$.getRenderWidth()/2,it=$.getRenderHeight()/2;_e.useRightHandedSystem?Matrix.OrthoOffCenterRHToRef((o=this.orthoLeft)!==null&&o!==void 0?o:-rt,(s=this.orthoRight)!==null&&s!==void 0?s:rt,(c=this.orthoBottom)!==null&&c!==void 0?c:-it,(d=this.orthoTop)!==null&&d!==void 0?d:it,this.minZ,this.maxZ,this._projectionMatrix,$.isNDCHalfZRange):Matrix.OrthoOffCenterLHToRef((_=this.orthoLeft)!==null&&_!==void 0?_:-rt,(b=this.orthoRight)!==null&&b!==void 0?b:rt,(k=this.orthoBottom)!==null&&k!==void 0?k:-it,(j=this.orthoTop)!==null&&j!==void 0?j:it,this.minZ,this.maxZ,this._projectionMatrix,$.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=$.getRenderWidth(),this._cache.renderHeight=$.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},i.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype._updateFrustumPlanes=function(){!this._refreshFrustumPlanes||(this.getTransformationMatrix(),this._frustumPlanes?Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e,o){if(o===void 0&&(o=!1),this._updateFrustumPlanes(),o&&this.rigCameras.length>0){var s=!1;return this.rigCameras.forEach(function(c){c._updateFrustumPlanes(),s=s||e.isInFrustum(c._frustumPlanes)}),s}else return e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.getForwardRay=function(e,o,s){throw _WarnImport("Ray")},i.prototype.getForwardRayToRef=function(e,o,s,c){throw _WarnImport("Ray")},i.prototype.dispose=function(e,o){for(o===void 0&&(o=!1),this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){var s=this._rigCameras.pop();s&&s.dispose()}if(this._parentContainer){var c=this._parentContainer.cameras.indexOf(this);c>-1&&this._parentContainer.cameras.splice(c,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==i.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var _=this._postProcesses.length;--_>=0;){var d=this._postProcesses[_];d&&d.dispose(this)}for(var _=this.customRenderTargets.length;--_>=0;)this.customRenderTargets[_].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),a.prototype.dispose.call(this,e,o)},Object.defineProperty(i.prototype,"isLeftCamera",{get:function(){return this._isLeftCamera},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isRightCamera",{get:function(){return this._isRightCamera},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!1,configurable:!0}),i.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},i.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},i.prototype.setCameraRigMode=function(e,o){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){var s=this._rigCameras.pop();s&&s.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=o.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE){var c=this.createRigCamera(this.name+"_L",0);c&&(c._isLeftCamera=!0);var d=this.createRigCamera(this.name+"_R",1);d&&(d._isRightCamera=!0),c&&d&&(this._rigCameras.push(c),this._rigCameras.push(d))}this._setRigMode(o),this._cascadePostProcessesToRigCams(),this.update()}},i.prototype._setRigMode=function(e){},i.prototype._getVRProjectionMatrix=function(){return Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._updateCameraRotationMatrix=function(){},i.prototype._updateWebVRCameraRotationMatrix=function(){},i.prototype._getWebVRProjectionMatrix=function(){return Matrix.Identity()},i.prototype._getWebVRViewMatrix=function(){return Matrix.Identity()},i.prototype.setCameraRigParameter=function(e,o){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=o,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=Tools.ToRadians(o/.0637))},i.prototype.createRigCamera=function(e,o){return null},i.prototype._updateRigCameras=function(){for(var e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)},i.prototype._setupInputs=function(){},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&(e.parentId=this.parent.uniqueId),this.inputs&&this.inputs.serialize(e),SerializationHelper.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e},i.prototype.clone=function(e){var o=SerializationHelper.Clone(i.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return o.name=e,this.onClonedObservable.notifyObservers(o),o},i.prototype.getDirection=function(e){var o=Vector3.Zero();return this.getDirectionToRef(e,o),o},Object.defineProperty(i.prototype,"absoluteRotation",{get:function(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation},enumerable:!1,configurable:!0}),i.prototype.getDirectionToRef=function(e,o){Vector3.TransformNormalToRef(e,this.getWorldMatrix(),o)},i.GetConstructorFromName=function(e,o,s,c,d){c===void 0&&(c=0),d===void 0&&(d=!0);var _=Node$2.Construct(e,o,s,{interaxial_distance:c,isStereoscopicSideBySide:d});return _||function(){return i._createDefaultParsedCamera(o,s)}},i.prototype.computeWorldMatrix=function(){return this.getWorldMatrix()},i.Parse=function(e,o){var s=e.type,c=i.GetConstructorFromName(s,e.name,o,e.interaxial_distance,e.isStereoscopicSideBySide),d=SerializationHelper.Parse(c,e,o);if(e.parentId&&(d._waitingParentId=e.parentId),d.inputs&&(d.inputs.parse(e),d._setupInputs()),e.upVector&&(d.upVector=Vector3.FromArray(e.upVector)),d.setPosition&&(d.position.copyFromFloats(0,0,0),d.setPosition(Vector3.FromArray(e.position))),e.target&&d.setTarget&&d.setTarget(Vector3.FromArray(e.target)),e.cameraRigMode){var _=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};d.setCameraRigMode(e.cameraRigMode,_)}if(e.animations){for(var b=0;b<e.animations.length;b++){var k=e.animations[b],j=GetClass("BABYLON.Animation");j&&d.animations.push(j.Parse(k))}Node$2.ParseAnimationRanges(d,e,o)}return e.autoAnimate&&o.beginAnimation(d,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&d.setEnabled(e.isEnabled),d},i._createDefaultParsedCamera=function(e,o){throw _WarnImport("UniversalCamera")},i.PERSPECTIVE_CAMERA=0,i.ORTHOGRAPHIC_CAMERA=1,i.FOVMODE_VERTICAL_FIXED=0,i.FOVMODE_HORIZONTAL_FIXED=1,i.RIG_MODE_NONE=0,i.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,i.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,i.RIG_MODE_STEREOSCOPIC_INTERLACED=14,i.RIG_MODE_VR=20,i.RIG_MODE_WEBVR=21,i.RIG_MODE_CUSTOM=22,i.ForceAttachControlToAlwaysPreventDefault=!1,__decorate([serializeAsVector3("position")],i.prototype,"_position",void 0),__decorate([serializeAsVector3("upVector")],i.prototype,"_upVector",void 0),__decorate([serialize()],i.prototype,"orthoLeft",void 0),__decorate([serialize()],i.prototype,"orthoRight",void 0),__decorate([serialize()],i.prototype,"orthoBottom",void 0),__decorate([serialize()],i.prototype,"orthoTop",void 0),__decorate([serialize()],i.prototype,"fov",void 0),__decorate([serialize()],i.prototype,"projectionPlaneTilt",void 0),__decorate([serialize()],i.prototype,"minZ",void 0),__decorate([serialize()],i.prototype,"maxZ",void 0),__decorate([serialize()],i.prototype,"inertia",void 0),__decorate([serialize()],i.prototype,"mode",void 0),__decorate([serialize()],i.prototype,"layerMask",void 0),__decorate([serialize()],i.prototype,"fovMode",void 0),__decorate([serialize()],i.prototype,"cameraRigMode",void 0),__decorate([serialize()],i.prototype,"interaxialDistance",void 0),__decorate([serialize()],i.prototype,"isStereoscopicSideBySide",void 0),i}(Node$2),StringDictionary=function(){function a(){this._count=0,this._data={}}return a.prototype.copyFrom=function(i){var e=this;this.clear(),i.forEach(function(o,s){return e.add(o,s)})},a.prototype.get=function(i){var e=this._data[i];if(e!==void 0)return e},a.prototype.getOrAddWithFactory=function(i,e){var o=this.get(i);return o!==void 0||(o=e(i),o&&this.add(i,o)),o},a.prototype.getOrAdd=function(i,e){var o=this.get(i);return o!==void 0?o:(this.add(i,e),e)},a.prototype.contains=function(i){return this._data[i]!==void 0},a.prototype.add=function(i,e){return this._data[i]!==void 0?!1:(this._data[i]=e,++this._count,!0)},a.prototype.set=function(i,e){return this._data[i]===void 0?!1:(this._data[i]=e,!0)},a.prototype.getAndRemove=function(i){var e=this.get(i);return e!==void 0?(delete this._data[i],--this._count,e):null},a.prototype.remove=function(i){return this.contains(i)?(delete this._data[i],--this._count,!0):!1},a.prototype.clear=function(){this._data={},this._count=0},Object.defineProperty(a.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),a.prototype.forEach=function(i){for(var e in this._data){var o=this._data[e];i(e,o)}},a.prototype.first=function(i){for(var e in this._data){var o=this._data[e],s=i(e,o);if(s)return s}return null},a}(),AbstractScene=function(){function a(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this._environmentTexture=null,this.postProcesses=new Array}return a.AddParser=function(i,e){this._BabylonFileParsers[i]=e},a.GetParser=function(i){return this._BabylonFileParsers[i]?this._BabylonFileParsers[i]:null},a.AddIndividualParser=function(i,e){this._IndividualBabylonFileParsers[i]=e},a.GetIndividualParser=function(i){return this._IndividualBabylonFileParsers[i]?this._IndividualBabylonFileParsers[i]:null},a.Parse=function(i,e,o,s){for(var c in this._BabylonFileParsers)this._BabylonFileParsers.hasOwnProperty(c)&&this._BabylonFileParsers[c](i,e,o,s)},Object.defineProperty(a.prototype,"environmentTexture",{get:function(){return this._environmentTexture},set:function(i){this._environmentTexture=i},enumerable:!1,configurable:!0}),a.prototype.getNodes=function(){var i=new Array;return i=i.concat(this.meshes),i=i.concat(this.lights),i=i.concat(this.cameras),i=i.concat(this.transformNodes),this.skeletons.forEach(function(e){return i=i.concat(e.bones)}),i},a._BabylonFileParsers={},a._IndividualBabylonFileParsers={},a}(),MaterialDefines=function(){function a(){this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1}return Object.defineProperty(a.prototype,"isDirty",{get:function(){return this._isDirty},enumerable:!1,configurable:!0}),a.prototype.markAsProcessed=function(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1},a.prototype.markAsUnprocessed=function(){this._isDirty=!0},a.prototype.markAllAsDirty=function(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0},a.prototype.markAsImageProcessingDirty=function(){this._areImageProcessingDirty=!0,this._isDirty=!0},a.prototype.markAsLightDirty=function(i){i===void 0&&(i=!1),this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||i,this._isDirty=!0},a.prototype.markAsAttributesDirty=function(){this._areAttributesDirty=!0,this._isDirty=!0},a.prototype.markAsTexturesDirty=function(){this._areTexturesDirty=!0,this._isDirty=!0},a.prototype.markAsFresnelDirty=function(){this._areFresnelDirty=!0,this._isDirty=!0},a.prototype.markAsMiscDirty=function(){this._areMiscDirty=!0,this._isDirty=!0},a.prototype.markAsPrePassDirty=function(){this._arePrePassDirty=!0,this._isDirty=!0},a.prototype.rebuild=function(){this._keys=[];for(var i=0,e=Object.keys(this);i<e.length;i++){var o=e[i];o[0]!=="_"&&this._keys.push(o)}},a.prototype.isEqual=function(i){if(this._keys.length!==i._keys.length)return!1;for(var e=0;e<this._keys.length;e++){var o=this._keys[e];if(this[o]!==i[o])return!1}return!0},a.prototype.cloneTo=function(i){this._keys.length!==i._keys.length&&(i._keys=this._keys.slice(0));for(var e=0;e<this._keys.length;e++){var o=this._keys[e];i[o]=this[o]}},a.prototype.reset=function(){for(var i=0;i<this._keys.length;i++){var e=this._keys[i],o=typeof this[e];switch(o){case"number":this[e]=0;break;case"string":this[e]="";break;default:this[e]=!1;break}}},a.prototype.toString=function(){for(var i="",e=0;e<this._keys.length;e++){var o=this._keys[e],s=this[o],c=typeof s;switch(c){case"number":case"string":i+="#define "+o+" "+s+`
  96. `;break;default:s&&(i+="#define "+o+`
  97. `);break}}return i},a}(),ColorCurves=function(){function a(){this._dirty=!0,this._tempColor=new Color4(0,0,0,0),this._globalCurve=new Color4(0,0,0,0),this._highlightsCurve=new Color4(0,0,0,0),this._midtonesCurve=new Color4(0,0,0,0),this._shadowsCurve=new Color4(0,0,0,0),this._positiveCurve=new Color4(0,0,0,0),this._negativeCurve=new Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(a.prototype,"globalHue",{get:function(){return this._globalHue},set:function(i){this._globalHue=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"globalDensity",{get:function(){return this._globalDensity},set:function(i){this._globalDensity=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"globalSaturation",{get:function(){return this._globalSaturation},set:function(i){this._globalSaturation=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"globalExposure",{get:function(){return this._globalExposure},set:function(i){this._globalExposure=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"highlightsHue",{get:function(){return this._highlightsHue},set:function(i){this._highlightsHue=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"highlightsDensity",{get:function(){return this._highlightsDensity},set:function(i){this._highlightsDensity=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"highlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(i){this._highlightsSaturation=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"highlightsExposure",{get:function(){return this._highlightsExposure},set:function(i){this._highlightsExposure=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"midtonesHue",{get:function(){return this._midtonesHue},set:function(i){this._midtonesHue=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"midtonesDensity",{get:function(){return this._midtonesDensity},set:function(i){this._midtonesDensity=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"midtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(i){this._midtonesSaturation=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"midtonesExposure",{get:function(){return this._midtonesExposure},set:function(i){this._midtonesExposure=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"shadowsHue",{get:function(){return this._shadowsHue},set:function(i){this._shadowsHue=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"shadowsDensity",{get:function(){return this._shadowsDensity},set:function(i){this._shadowsDensity=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"shadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(i){this._shadowsSaturation=i,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"shadowsExposure",{get:function(){return this._shadowsExposure},set:function(i){this._shadowsExposure=i,this._dirty=!0},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"ColorCurves"},a.Bind=function(i,e,o,s,c){o===void 0&&(o="vCameraColorCurvePositive"),s===void 0&&(s="vCameraColorCurveNeutral"),c===void 0&&(c="vCameraColorCurveNegative"),i._dirty&&(i._dirty=!1,i.getColorGradingDataToRef(i._globalHue,i._globalDensity,i._globalSaturation,i._globalExposure,i._globalCurve),i.getColorGradingDataToRef(i._highlightsHue,i._highlightsDensity,i._highlightsSaturation,i._highlightsExposure,i._tempColor),i._tempColor.multiplyToRef(i._globalCurve,i._highlightsCurve),i.getColorGradingDataToRef(i._midtonesHue,i._midtonesDensity,i._midtonesSaturation,i._midtonesExposure,i._tempColor),i._tempColor.multiplyToRef(i._globalCurve,i._midtonesCurve),i.getColorGradingDataToRef(i._shadowsHue,i._shadowsDensity,i._shadowsSaturation,i._shadowsExposure,i._tempColor),i._tempColor.multiplyToRef(i._globalCurve,i._shadowsCurve),i._highlightsCurve.subtractToRef(i._midtonesCurve,i._positiveCurve),i._midtonesCurve.subtractToRef(i._shadowsCurve,i._negativeCurve)),e&&(e.setFloat4(o,i._positiveCurve.r,i._positiveCurve.g,i._positiveCurve.b,i._positiveCurve.a),e.setFloat4(s,i._midtonesCurve.r,i._midtonesCurve.g,i._midtonesCurve.b,i._midtonesCurve.a),e.setFloat4(c,i._negativeCurve.r,i._negativeCurve.g,i._negativeCurve.b,i._negativeCurve.a))},a.PrepareUniforms=function(i){i.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},a.prototype.getColorGradingDataToRef=function(i,e,o,s,c){i!=null&&(i=a.clamp(i,0,360),e=a.clamp(e,-100,100),o=a.clamp(o,-100,100),s=a.clamp(s,-100,100),e=a.applyColorGradingSliderNonlinear(e),e*=.5,s=a.applyColorGradingSliderNonlinear(s),e<0&&(e*=-1,i=(i+180)%360),a.fromHSBToRef(i,e,50+.25*s,c),c.scaleToRef(2,c),c.a=1+.01*o)},a.applyColorGradingSliderNonlinear=function(i){i/=100;var e=Math.abs(i);return e=Math.pow(e,2),i<0&&(e*=-1),e*=100,e},a.fromHSBToRef=function(i,e,o,s){var c=a.clamp(i,0,360),d=a.clamp(e/100,0,1),_=a.clamp(o/100,0,1);if(d===0)s.r=_,s.g=_,s.b=_;else{c/=60;var b=Math.floor(c),k=c-b,j=_*(1-d),$=_*(1-d*k),_e=_*(1-d*(1-k));switch(b){case 0:s.r=_,s.g=_e,s.b=j;break;case 1:s.r=$,s.g=_,s.b=j;break;case 2:s.r=j,s.g=_,s.b=_e;break;case 3:s.r=j,s.g=$,s.b=_;break;case 4:s.r=_e,s.g=j,s.b=_;break;default:s.r=_,s.g=j,s.b=$;break}}s.a=1},a.clamp=function(i,e,o){return Math.min(Math.max(i,e),o)},a.prototype.clone=function(){return SerializationHelper.Clone(function(){return new a},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.Parse=function(i){return SerializationHelper.Parse(function(){return new a},i,null,null)},__decorate([serialize()],a.prototype,"_globalHue",void 0),__decorate([serialize()],a.prototype,"_globalDensity",void 0),__decorate([serialize()],a.prototype,"_globalSaturation",void 0),__decorate([serialize()],a.prototype,"_globalExposure",void 0),__decorate([serialize()],a.prototype,"_highlightsHue",void 0),__decorate([serialize()],a.prototype,"_highlightsDensity",void 0),__decorate([serialize()],a.prototype,"_highlightsSaturation",void 0),__decorate([serialize()],a.prototype,"_highlightsExposure",void 0),__decorate([serialize()],a.prototype,"_midtonesHue",void 0),__decorate([serialize()],a.prototype,"_midtonesDensity",void 0),__decorate([serialize()],a.prototype,"_midtonesSaturation",void 0),__decorate([serialize()],a.prototype,"_midtonesExposure",void 0),a}();SerializationHelper._ColorCurvesParser=ColorCurves.Parse;var ImageProcessingConfigurationDefines=function(a){__extends(i,a);function i(){var e=a.call(this)||this;return e.IMAGEPROCESSING=!1,e.VIGNETTE=!1,e.VIGNETTEBLENDMODEMULTIPLY=!1,e.VIGNETTEBLENDMODEOPAQUE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=!1,e.SAMPLER3DBGRMAP=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.EXPOSURE=!1,e.SKIPFINALCOLORCLAMP=!1,e.rebuild(),e}return i}(MaterialDefines),ImageProcessingConfiguration=function(){function a(){this.colorCurves=new ColorCurves,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=a.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCentreX=0,this.vignetteCentreY=0,this.vignetteWeight=1.5,this.vignetteColor=new Color4(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=a.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new Observable}return Object.defineProperty(a.prototype,"colorCurvesEnabled",{get:function(){return this._colorCurvesEnabled},set:function(i){this._colorCurvesEnabled!==i&&(this._colorCurvesEnabled=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"colorGradingTexture",{get:function(){return this._colorGradingTexture},set:function(i){this._colorGradingTexture!==i&&(this._colorGradingTexture=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"colorGradingEnabled",{get:function(){return this._colorGradingEnabled},set:function(i){this._colorGradingEnabled!==i&&(this._colorGradingEnabled=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"colorGradingWithGreenDepth",{get:function(){return this._colorGradingWithGreenDepth},set:function(i){this._colorGradingWithGreenDepth!==i&&(this._colorGradingWithGreenDepth=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"colorGradingBGR",{get:function(){return this._colorGradingBGR},set:function(i){this._colorGradingBGR!==i&&(this._colorGradingBGR=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"exposure",{get:function(){return this._exposure},set:function(i){this._exposure!==i&&(this._exposure=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"toneMappingEnabled",{get:function(){return this._toneMappingEnabled},set:function(i){this._toneMappingEnabled!==i&&(this._toneMappingEnabled=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"toneMappingType",{get:function(){return this._toneMappingType},set:function(i){this._toneMappingType!==i&&(this._toneMappingType=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"contrast",{get:function(){return this._contrast},set:function(i){this._contrast!==i&&(this._contrast=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"vignetteBlendMode",{get:function(){return this._vignetteBlendMode},set:function(i){this._vignetteBlendMode!==i&&(this._vignetteBlendMode=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"vignetteEnabled",{get:function(){return this._vignetteEnabled},set:function(i){this._vignetteEnabled!==i&&(this._vignetteEnabled=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"skipFinalColorClamp",{get:function(){return this._skipFinalColorClamp},set:function(i){this._skipFinalColorClamp!==i&&(this._skipFinalColorClamp=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"applyByPostProcess",{get:function(){return this._applyByPostProcess},set:function(i){this._applyByPostProcess!==i&&(this._applyByPostProcess=i,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(i){this._isEnabled!==i&&(this._isEnabled=i,this._updateParameters())},enumerable:!1,configurable:!0}),a.prototype._updateParameters=function(){this.onUpdateParameters.notifyObservers(this)},a.prototype.getClassName=function(){return"ImageProcessingConfiguration"},a.PrepareUniforms=function(i,e){e.EXPOSURE&&i.push("exposureLinear"),e.CONTRAST&&i.push("contrast"),e.COLORGRADING&&i.push("colorTransformSettings"),e.VIGNETTE&&(i.push("vInverseScreenSize"),i.push("vignetteSettings1"),i.push("vignetteSettings2")),e.COLORCURVES&&ColorCurves.PrepareUniforms(i)},a.PrepareSamplers=function(i,e){e.COLORGRADING&&i.push("txColorTransform")},a.prototype.prepareDefines=function(i,e){if(e===void 0&&(e=!1),e!==this.applyByPostProcess||!this._isEnabled){i.VIGNETTE=!1,i.TONEMAPPING=!1,i.TONEMAPPING_ACES=!1,i.CONTRAST=!1,i.EXPOSURE=!1,i.COLORCURVES=!1,i.COLORGRADING=!1,i.COLORGRADING3D=!1,i.IMAGEPROCESSING=!1,i.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,i.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}switch(i.VIGNETTE=this.vignetteEnabled,i.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===a._VIGNETTEMODE_MULTIPLY,i.VIGNETTEBLENDMODEOPAQUE=!i.VIGNETTEBLENDMODEMULTIPLY,i.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case a.TONEMAPPING_ACES:i.TONEMAPPING_ACES=!0;break;default:i.TONEMAPPING_ACES=!1;break}i.CONTRAST=this.contrast!==1,i.EXPOSURE=this.exposure!==1,i.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,i.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,i.COLORGRADING?i.COLORGRADING3D=this.colorGradingTexture.is3D:i.COLORGRADING3D=!1,i.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,i.SAMPLER3DBGRMAP=this.colorGradingBGR,i.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,i.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,i.IMAGEPROCESSING=i.VIGNETTE||i.TONEMAPPING||i.CONTRAST||i.EXPOSURE||i.COLORCURVES||i.COLORGRADING},a.prototype.isReady=function(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()},a.prototype.bind=function(i,e){if(this._colorCurvesEnabled&&this.colorCurves&&ColorCurves.Bind(this.colorCurves,i),this._vignetteEnabled){var o=1/i.getEngine().getRenderWidth(),s=1/i.getEngine().getRenderHeight();i.setFloat2("vInverseScreenSize",o,s);var c=e!=null?e:s/o,d=Math.tan(this.vignetteCameraFov*.5),_=d*c,b=Math.sqrt(_*d);_=Tools.Mix(_,b,this.vignetteStretch),d=Tools.Mix(d,b,this.vignetteStretch),i.setFloat4("vignetteSettings1",_,d,-_*this.vignetteCentreX,-d*this.vignetteCentreY);var k=-2*this.vignetteWeight;i.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,k)}if(i.setFloat("exposureLinear",this.exposure),i.setFloat("contrast",this.contrast),this.colorGradingTexture){i.setTexture("txColorTransform",this.colorGradingTexture);var j=this.colorGradingTexture.getSize().height;i.setFloat4("colorTransformSettings",(j-1)/j,.5/j,j,this.colorGradingTexture.level)}},a.prototype.clone=function(){return SerializationHelper.Clone(function(){return new a},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.Parse=function(i){return SerializationHelper.Parse(function(){return new a},i,null,null)},Object.defineProperty(a,"VIGNETTEMODE_MULTIPLY",{get:function(){return this._VIGNETTEMODE_MULTIPLY},enumerable:!1,configurable:!0}),Object.defineProperty(a,"VIGNETTEMODE_OPAQUE",{get:function(){return this._VIGNETTEMODE_OPAQUE},enumerable:!1,configurable:!0}),a.TONEMAPPING_STANDARD=0,a.TONEMAPPING_ACES=1,a._VIGNETTEMODE_MULTIPLY=0,a._VIGNETTEMODE_OPAQUE=1,__decorate([serializeAsColorCurves()],a.prototype,"colorCurves",void 0),__decorate([serialize()],a.prototype,"_colorCurvesEnabled",void 0),__decorate([serializeAsTexture("colorGradingTexture")],a.prototype,"_colorGradingTexture",void 0),__decorate([serialize()],a.prototype,"_colorGradingEnabled",void 0),__decorate([serialize()],a.prototype,"_colorGradingWithGreenDepth",void 0),__decorate([serialize()],a.prototype,"_colorGradingBGR",void 0),__decorate([serialize()],a.prototype,"_exposure",void 0),__decorate([serialize()],a.prototype,"_toneMappingEnabled",void 0),__decorate([serialize()],a.prototype,"_toneMappingType",void 0),__decorate([serialize()],a.prototype,"_contrast",void 0),__decorate([serialize()],a.prototype,"vignetteStretch",void 0),__decorate([serialize()],a.prototype,"vignetteCentreX",void 0),__decorate([serialize()],a.prototype,"vignetteCentreY",void 0),__decorate([serialize()],a.prototype,"vignetteWeight",void 0),__decorate([serializeAsColor4()],a.prototype,"vignetteColor",void 0),__decorate([serialize()],a.prototype,"vignetteCameraFov",void 0),__decorate([serialize()],a.prototype,"_vignetteBlendMode",void 0),__decorate([serialize()],a.prototype,"_vignetteEnabled",void 0),__decorate([serialize()],a.prototype,"_skipFinalColorClamp",void 0),__decorate([serialize()],a.prototype,"_applyByPostProcess",void 0),__decorate([serialize()],a.prototype,"_isEnabled",void 0),a}();SerializationHelper._ImageProcessingConfigurationParser=ImageProcessingConfiguration.Parse;var ActionEvent=function(){function a(i,e,o,s,c,d){this.source=i,this.pointerX=e,this.pointerY=o,this.meshUnderPointer=s,this.sourceEvent=c,this.additionalData=d}return a.CreateNew=function(i,e,o){var s=i.getScene();return new a(i,s.pointerX,s.pointerY,s.meshUnderPointer||i,e,o)},a.CreateNewFromSprite=function(i,e,o,s){return new a(i,e.pointerX,e.pointerY,e.meshUnderPointer,o,s)},a.CreateNewFromScene=function(i,e){return new a(null,i.pointerX,i.pointerY,i.meshUnderPointer,e)},a.CreateNewFromPrimitive=function(i,e,o,s){return new a(i,e.x,e.y,null,o,s)},a}(),PostProcessManager=function(){function a(i){this._vertexBuffers={},this._scene=i}return a.prototype._prepareBuffers=function(){if(!this._vertexBuffers[VertexBuffer.PositionKind]){var i=[];i.push(1,1),i.push(-1,1),i.push(-1,-1),i.push(1,-1),this._vertexBuffers[VertexBuffer.PositionKind]=new VertexBuffer(this._scene.getEngine(),i,VertexBuffer.PositionKind,!1,!1,2),this._buildIndexBuffer()}},a.prototype._buildIndexBuffer=function(){var i=[];i.push(0),i.push(1),i.push(2),i.push(0),i.push(2),i.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(i)},a.prototype._rebuild=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];!i||(i._rebuild(),this._buildIndexBuffer())},a.prototype._prepareFrame=function(i,e){i===void 0&&(i=null),e===void 0&&(e=null);var o=this._scene.activeCamera;return!o||(e=e||o._postProcesses.filter(function(s){return s!=null}),!e||e.length===0||!this._scene.postProcessesEnabled)?!1:(e[0].activate(o,i,e!=null),!0)},a.prototype.directRender=function(i,e,o,s,c,d){var _;e===void 0&&(e=null),o===void 0&&(o=!1),s===void 0&&(s=0),c===void 0&&(c=0),d===void 0&&(d=!1);for(var b=this._scene.getEngine(),k=0;k<i.length;k++){k<i.length-1?i[k+1].activate(this._scene.activeCamera,e==null?void 0:e.texture):(e?b.bindFramebuffer(e,s,void 0,void 0,o,c):d||b.restoreDefaultFramebuffer(),(_=b._debugInsertMarker)===null||_===void 0||_.call(b,"post process "+i[k].name+" output"));var j=i[k],$=j.apply();$&&(j.onBeforeRenderObservable.notifyObservers($),this._prepareBuffers(),b.bindBuffers(this._vertexBuffers,this._indexBuffer,$),b.drawElementsType(0,0,6),j.onAfterRenderObservable.notifyObservers($))}b.setDepthBuffer(!0),b.setDepthWrite(!0)},a.prototype._finalizeFrame=function(i,e,o,s,c){var d;c===void 0&&(c=!1);var _=this._scene.activeCamera;if(!!_&&(s=s||_._postProcesses.filter(function(et){return et!=null}),!(s.length===0||!this._scene.postProcessesEnabled))){for(var b=this._scene.getEngine(),k=0,j=s.length;k<j;k++){var $=s[k];if(k<j-1?$._outputTexture=s[k+1].activate(_,e==null?void 0:e.texture):(e?(b.bindFramebuffer(e,o,void 0,void 0,c),$._outputTexture=e):(b.restoreDefaultFramebuffer(),$._outputTexture=null),(d=b._debugInsertMarker)===null||d===void 0||d.call(b,"post process "+s[k].name+" output")),i)break;var _e=$.apply();_e&&($.onBeforeRenderObservable.notifyObservers(_e),this._prepareBuffers(),b.bindBuffers(this._vertexBuffers,this._indexBuffer,_e),b.drawElementsType(0,0,6),$.onAfterRenderObservable.notifyObservers(_e))}b.setDepthBuffer(!0),b.setDepthWrite(!0),b.setAlphaMode(0)}},a.prototype.dispose=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&(i.dispose(),this._vertexBuffers[VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)},a}(),RenderingGroup=function(){function a(i,e,o,s,c){o===void 0&&(o=null),s===void 0&&(s=null),c===void 0&&(c=null),this.index=i,this._opaqueSubMeshes=new SmartArray(256),this._transparentSubMeshes=new SmartArray(256),this._alphaTestSubMeshes=new SmartArray(256),this._depthOnlySubMeshes=new SmartArray(256),this._particleSystems=new SmartArray(256),this._spriteManagers=new SmartArray(256),this._edgesRenderers=new SmartArrayNoDuplicate(16),this._scene=e,this.opaqueSortCompareFn=o,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=c}return Object.defineProperty(a.prototype,"opaqueSortCompareFn",{set:function(i){this._opaqueSortCompareFn=i,i?this._renderOpaque=this.renderOpaqueSorted:this._renderOpaque=a.renderUnsorted},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"alphaTestSortCompareFn",{set:function(i){this._alphaTestSortCompareFn=i,i?this._renderAlphaTest=this.renderAlphaTestSorted:this._renderAlphaTest=a.renderUnsorted},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"transparentSortCompareFn",{set:function(i){i?this._transparentSortCompareFn=i:this._transparentSortCompareFn=a.defaultTransparentSortCompare,this._renderTransparent=this.renderTransparentSorted},enumerable:!1,configurable:!0}),a.prototype.render=function(i,e,o,s){if(i){i(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}var c=this._scene.getEngine();this._depthOnlySubMeshes.length!==0&&(c.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),c.setColorWrite(!0)),this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);var d=c.getStencilBuffer();if(c.setStencilBuffer(!1),e&&this._renderSprites(),o&&this._renderParticles(s),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),(this._transparentSubMeshes.length!==0||this._scene.useOrderIndependentTransparency)&&(c.setStencilBuffer(d),this._scene.useOrderIndependentTransparency?this._scene.depthPeelingRenderer.render(this._transparentSubMeshes):this._renderTransparent(this._transparentSubMeshes),c.setAlphaMode(0)),c.setStencilBuffer(!1),this._edgesRenderers.length){for(var _=0;_<this._edgesRenderers.length;_++)this._edgesRenderers.data[_].render();c.setAlphaMode(0)}c.setStencilBuffer(d)},a.prototype.renderOpaqueSorted=function(i){return a.renderSorted(i,this._opaqueSortCompareFn,this._scene.activeCamera,!1)},a.prototype.renderAlphaTestSorted=function(i){return a.renderSorted(i,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)},a.prototype.renderTransparentSorted=function(i){return a.renderSorted(i,this._transparentSortCompareFn,this._scene.activeCamera,!0)},a.renderSorted=function(i,e,o,s){for(var c=0,d,_=o?o.globalPosition:a._zeroVector;c<i.length;c++)d=i.data[c],d._alphaIndex=d.getMesh().alphaIndex,d._distanceToCamera=Vector3.Distance(d.getBoundingInfo().boundingSphere.centerWorld,_);var b=i.data.slice(0,i.length);for(e&&b.sort(e),c=0;c<b.length;c++){if(d=b[c],s){var k=d.getMaterial();if(k&&k.needDepthPrePass){var j=k.getScene().getEngine();j.setColorWrite(!1),j.setAlphaMode(0),d.render(!1),j.setColorWrite(!0)}}d.render(s)}},a.renderUnsorted=function(i){for(var e=0;e<i.length;e++){var o=i.data[e];o.render(!1)}},a.defaultTransparentSortCompare=function(i,e){return i._alphaIndex>e._alphaIndex?1:i._alphaIndex<e._alphaIndex?-1:a.backToFrontSortCompare(i,e)},a.backToFrontSortCompare=function(i,e){return i._distanceToCamera<e._distanceToCamera?1:i._distanceToCamera>e._distanceToCamera?-1:0},a.frontToBackSortCompare=function(i,e){return i._distanceToCamera<e._distanceToCamera?-1:i._distanceToCamera>e._distanceToCamera?1:0},a.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},a.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},a.prototype.dispatch=function(i,e,o){e===void 0&&(e=i.getMesh()),o===void 0&&(o=i.getMaterial()),o!=null&&(o.needAlphaBlendingForMesh(e)?this._transparentSubMeshes.push(i):o.needAlphaTesting()?(o.needDepthPrePass&&this._depthOnlySubMeshes.push(i),this._alphaTestSubMeshes.push(i)):(o.needDepthPrePass&&this._depthOnlySubMeshes.push(i),this._opaqueSubMeshes.push(i)),e._renderingGroup=this,e._edgesRenderer&&e._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(e._edgesRenderer))},a.prototype.dispatchSprites=function(i){this._spriteManagers.push(i)},a.prototype.dispatchParticles=function(i){this._particleSystems.push(i)},a.prototype._renderParticles=function(i){if(this._particleSystems.length!==0){var e=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var o=0;o<this._particleSystems.length;o++){var s=this._particleSystems.data[o];if((e&&e.layerMask&s.layerMask)!==0){var c=s.emitter;(!c.position||!i||i.indexOf(c)!==-1)&&this._scene._activeParticles.addCount(s.render(),!1)}}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}},a.prototype._renderSprites=function(){if(!(!this._scene.spritesEnabled||this._spriteManagers.length===0)){var i=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(var e=0;e<this._spriteManagers.length;e++){var o=this._spriteManagers.data[e];(i&&i.layerMask&o.layerMask)!==0&&o.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}},a._zeroVector=Vector3.Zero(),a}(),RenderingGroupInfo=function(){function a(){}return a}(),RenderingManager=function(){function a(i){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new RenderingGroupInfo,this._scene=i;for(var e=a.MIN_RENDERINGGROUPS;e<a.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}return a.prototype._clearDepthStencilBuffer=function(i,e){i===void 0&&(i=!0),e===void 0&&(e=!0),!this._depthStencilBufferAlreadyCleaned&&(this._scene.getEngine().clear(null,!1,i,e),this._depthStencilBufferAlreadyCleaned=!0)},a.prototype.render=function(i,e,o,s){var c=this._renderingGroupInfo;if(c.scene=this._scene,c.camera=this._scene.activeCamera,this._scene.spriteManagers&&s)for(var d=0;d<this._scene.spriteManagers.length;d++){var _=this._scene.spriteManagers[d];this.dispatchSprites(_)}for(var d=a.MIN_RENDERINGGROUPS;d<a.MAX_RENDERINGGROUPS;d++){this._depthStencilBufferAlreadyCleaned=d===a.MIN_RENDERINGGROUPS;var b=this._renderingGroups[d];if(!!b){var k=Math.pow(2,d);if(c.renderingGroupId=d,this._scene.onBeforeRenderingGroupObservable.notifyObservers(c,k),a.AUTOCLEAR){var j=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(d):this._autoClearDepthStencil[d];j&&j.autoClear&&this._clearDepthStencilBuffer(j.depth,j.stencil)}for(var $=0,_e=this._scene._beforeRenderingGroupDrawStage;$<_e.length;$++){var et=_e[$];et.action(d)}b.render(i,s,o,e);for(var tt=0,rt=this._scene._afterRenderingGroupDrawStage;tt<rt.length;tt++){var et=rt[tt];et.action(d)}this._scene.onAfterRenderingGroupObservable.notifyObservers(c,k)}}},a.prototype.reset=function(){for(var i=a.MIN_RENDERINGGROUPS;i<a.MAX_RENDERINGGROUPS;i++){var e=this._renderingGroups[i];e&&e.prepare()}},a.prototype.dispose=function(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null},a.prototype.freeRenderingGroups=function(){for(var i=a.MIN_RENDERINGGROUPS;i<a.MAX_RENDERINGGROUPS;i++){var e=this._renderingGroups[i];e&&e.dispose()}},a.prototype._prepareRenderingGroup=function(i){this._renderingGroups[i]===void 0&&(this._renderingGroups[i]=new RenderingGroup(i,this._scene,this._customOpaqueSortCompareFn[i],this._customAlphaTestSortCompareFn[i],this._customTransparentSortCompareFn[i]))},a.prototype.dispatchSprites=function(i){var e=i.renderingGroupId||0;this._prepareRenderingGroup(e),this._renderingGroups[e].dispatchSprites(i)},a.prototype.dispatchParticles=function(i){var e=i.renderingGroupId||0;this._prepareRenderingGroup(e),this._renderingGroups[e].dispatchParticles(i)},a.prototype.dispatch=function(i,e,o){e===void 0&&(e=i.getMesh());var s=e.renderingGroupId||0;this._prepareRenderingGroup(s),this._renderingGroups[s].dispatch(i,e,o)},a.prototype.setRenderingOrder=function(i,e,o,s){if(e===void 0&&(e=null),o===void 0&&(o=null),s===void 0&&(s=null),this._customOpaqueSortCompareFn[i]=e,this._customAlphaTestSortCompareFn[i]=o,this._customTransparentSortCompareFn[i]=s,this._renderingGroups[i]){var c=this._renderingGroups[i];c.opaqueSortCompareFn=this._customOpaqueSortCompareFn[i],c.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[i],c.transparentSortCompareFn=this._customTransparentSortCompareFn[i]}},a.prototype.setRenderingAutoClearDepthStencil=function(i,e,o,s){o===void 0&&(o=!0),s===void 0&&(s=!0),this._autoClearDepthStencil[i]={autoClear:e,depth:o,stencil:s}},a.prototype.getAutoClearDepthStencilSetup=function(i){return this._autoClearDepthStencil[i]},a.MAX_RENDERINGGROUPS=4,a.MIN_RENDERINGGROUPS=0,a.AUTOCLEAR=!0,a}(),SceneComponentConstants=function(){function a(){}return a.NAME_EFFECTLAYER="EffectLayer",a.NAME_LAYER="Layer",a.NAME_LENSFLARESYSTEM="LensFlareSystem",a.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",a.NAME_PARTICLESYSTEM="ParticleSystem",a.NAME_GAMEPAD="Gamepad",a.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",a.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",a.NAME_PREPASSRENDERER="PrePassRenderer",a.NAME_DEPTHRENDERER="DepthRenderer",a.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",a.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",a.NAME_SPRITE="Sprite",a.NAME_SUBSURFACE="SubSurface",a.NAME_OUTLINERENDERER="Outline",a.NAME_PROCEDURALTEXTURE="ProceduralTexture",a.NAME_SHADOWGENERATOR="ShadowGenerator",a.NAME_OCTREE="Octree",a.NAME_PHYSICSENGINE="PhysicsEngine",a.NAME_AUDIO="Audio",a.STEP_ISREADYFORMESH_EFFECTLAYER=0,a.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,a.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,a.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,a.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,a.STEP_BEFORECAMERADRAW_PREPASS=0,a.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,a.STEP_BEFORECAMERADRAW_LAYER=2,a.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,a.STEP_BEFORERENDERTARGETDRAW_LAYER=1,a.STEP_BEFORERENDERINGMESH_PREPASS=0,a.STEP_BEFORERENDERINGMESH_OUTLINE=1,a.STEP_AFTERRENDERINGMESH_PREPASS=0,a.STEP_AFTERRENDERINGMESH_OUTLINE=1,a.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,a.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,a.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,a.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,a.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,a.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,a.STEP_AFTERRENDERTARGETDRAW_LAYER=1,a.STEP_AFTERCAMERADRAW_PREPASS=0,a.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,a.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,a.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,a.STEP_AFTERCAMERADRAW_LAYER=4,a.STEP_AFTERRENDER_AUDIO=0,a.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,a.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,a.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,a.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,a.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,a.STEP_BEFORECLEARSTAGE_PREPASS=0,a.STEP_BEFORERENDERTARGETCLEARSTAGE_PREPASS=0,a.STEP_POINTERMOVE_SPRITE=0,a.STEP_POINTERDOWN_SPRITE=0,a.STEP_POINTERUP_SPRITE=0,a}(),Stage=function(a){__extends(i,a);function i(e){return a.apply(this,e)||this}return i.Create=function(){return Object.create(i.prototype)},i.prototype.registerStep=function(e,o,s){for(var c=0,d=Number.MAX_VALUE;c<this.length;c++){var _=this[c];if(d=_.index,e<d)break}this.splice(c,0,{index:e,component:o,action:s.bind(o)})},i.prototype.clear=function(){this.length=0},i}(Array),PointerEventTypes=function(){function a(){}return a.POINTERDOWN=1,a.POINTERUP=2,a.POINTERMOVE=4,a.POINTERWHEEL=8,a.POINTERPICK=16,a.POINTERTAP=32,a.POINTERDOUBLETAP=64,a}(),PointerInfoBase=function(){function a(i,e){this.type=i,this.event=e}return a}(),PointerInfoPre=function(a){__extends(i,a);function i(e,o,s,c){var d=a.call(this,e,o)||this;return d.ray=null,d.skipOnPointerObservable=!1,d.localPosition=new Vector2(s,c),d}return i}(PointerInfoBase),PointerInfo=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o)||this;return c.pickInfo=s,c}return i}(PointerInfoBase),AbstractActionManager=function(){function a(){this.hoverCursor="",this.actions=new Array,this.isRecursive=!1}return Object.defineProperty(a,"HasTriggers",{get:function(){for(var i in a.Triggers)if(a.Triggers.hasOwnProperty(i))return!0;return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a,"HasPickTriggers",{get:function(){for(var i in a.Triggers)if(a.Triggers.hasOwnProperty(i)){var e=parseInt(i);if(e>=1&&e<=7)return!0}return!1},enumerable:!1,configurable:!0}),a.HasSpecificTrigger=function(i){for(var e in a.Triggers)if(a.Triggers.hasOwnProperty(e)){var o=parseInt(e);if(o===i)return!0}return!1},a.Triggers={},a}(),KeyboardEventTypes=function(){function a(){}return a.KEYDOWN=1,a.KEYUP=2,a}(),KeyboardInfo=function(){function a(i,e){this.type=i,this.event=e}return a}(),KeyboardInfoPre=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s.type=e,s.event=o,s.skipOnPointerObservable=!1,s}return i}(KeyboardInfo),DeviceType;(function(a){a[a.Generic=0]="Generic",a[a.Keyboard=1]="Keyboard",a[a.Mouse=2]="Mouse",a[a.Touch=3]="Touch",a[a.DualShock=4]="DualShock",a[a.Xbox=5]="Xbox",a[a.Switch=6]="Switch"})(DeviceType||(DeviceType={}));var PointerInput;(function(a){a[a.Horizontal=0]="Horizontal",a[a.Vertical=1]="Vertical",a[a.LeftClick=2]="LeftClick",a[a.MiddleClick=3]="MiddleClick",a[a.RightClick=4]="RightClick",a[a.BrowserBack=5]="BrowserBack",a[a.BrowserForward=6]="BrowserForward",a[a.MouseWheelX=7]="MouseWheelX",a[a.MouseWheelY=8]="MouseWheelY",a[a.MouseWheelZ=9]="MouseWheelZ",a[a.DeltaHorizontal=10]="DeltaHorizontal",a[a.DeltaVertical=11]="DeltaVertical"})(PointerInput||(PointerInput={}));var DualShockInput;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.L2=6]="L2",a[a.R2=7]="R2",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.L3=10]="L3",a[a.R3=11]="R3",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.TouchPad=17]="TouchPad",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(DualShockInput||(DualShockInput={}));var XboxInput;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.LT=6]="LT",a[a.RT=7]="RT",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.LStickXAxis=17]="LStickXAxis",a[a.LStickYAxis=18]="LStickYAxis",a[a.RStickXAxis=19]="RStickXAxis",a[a.RStickYAxis=20]="RStickYAxis"})(XboxInput||(XboxInput={}));var SwitchInput;(function(a){a[a.B=0]="B",a[a.A=1]="A",a[a.Y=2]="Y",a[a.X=3]="X",a[a.L=4]="L",a[a.R=5]="R",a[a.ZL=6]="ZL",a[a.ZR=7]="ZR",a[a.Minus=8]="Minus",a[a.Plus=9]="Plus",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.Capture=17]="Capture",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(SwitchInput||(SwitchInput={}));var DeviceInputEventType;(function(a){a[a.PointerMove=0]="PointerMove",a[a.PointerDown=1]="PointerDown",a[a.PointerUp=2]="PointerUp"})(DeviceInputEventType||(DeviceInputEventType={}));var EventConstants=function(){function a(){}return a.DOM_DELTA_PIXEL=0,a.DOM_DELTA_LINE=1,a.DOM_DELTA_PAGE=2,a}(),DeviceEventFactory=function(){function a(){}return a.CreateDeviceEvent=function(i,e,o,s,c,d){switch(i){case DeviceType.Keyboard:return this._createKeyboardEvent(o,s,c,d);case DeviceType.Mouse:if(o===PointerInput.MouseWheelX||o===PointerInput.MouseWheelY||o===PointerInput.MouseWheelZ)return this._createWheelEvent(i,e,o,s,c,d);case DeviceType.Touch:return this._createPointerEvent(i,e,o,s,c,d);default:throw"Unable to generate event for device "+DeviceType[i]}},a._createPointerEvent=function(i,e,o,s,c,d){var _=this._createMouseEvent(i,e,o,s,c,d);return _.pointerId=i===DeviceType.Mouse?1:e,o===PointerInput.Horizontal||o===PointerInput.Vertical||o===PointerInput.DeltaHorizontal||o===PointerInput.DeltaVertical?_.type="pointermove":o>=PointerInput.LeftClick&&o<=PointerInput.RightClick&&(_.type=s===1?"pointerdown":"pointerup",_.button=o-2),_},a._createWheelEvent=function(i,e,o,s,c,d){var _=this._createMouseEvent(i,e,o,s,c,d);return _.type="wheel",_.deltaMode=EventConstants.DOM_DELTA_PIXEL,_.deltaX=o===PointerInput.MouseWheelX?s:c.pollInput(i,e,PointerInput.MouseWheelX),_.deltaY=o===PointerInput.MouseWheelY?s:c.pollInput(i,e,PointerInput.MouseWheelY),_.deltaZ=o===PointerInput.MouseWheelZ?s:c.pollInput(i,e,PointerInput.MouseWheelZ),_},a._createMouseEvent=function(i,e,o,s,c,d){var _=this._createEvent(d),b=c.pollInput(i,e,PointerInput.Horizontal),k=c.pollInput(i,e,PointerInput.Vertical),j=o===PointerInput.DeltaHorizontal?s:0,$=o===PointerInput.DeltaVertical?s:0,_e=o===PointerInput.DeltaHorizontal&&d?j-d.getBoundingClientRect().x:0,et=o===PointerInput.DeltaVertical&&d?$-d.getBoundingClientRect().y:0;return this._checkNonCharacterKeys(_,c),_.clientX=b,_.clientY=k,_.movementX=j,_.movementY=$,_.offsetX=_e,_.offsetY=et,_.x=b,_.y=k,_},a._createKeyboardEvent=function(i,e,o,s){var c=this._createEvent(s);return this._checkNonCharacterKeys(c,o),c.type=e===1?"keydown":"keyup",c.key=String.fromCharCode(i),c.keyCode=i,c},a._checkNonCharacterKeys=function(i,e){var o=e.isDeviceAvailable(DeviceType.Keyboard),s=o&&e.pollInput(DeviceType.Keyboard,0,18)===1,c=o&&e.pollInput(DeviceType.Keyboard,0,17)===1,d=o&&(e.pollInput(DeviceType.Keyboard,0,91)===1||e.pollInput(DeviceType.Keyboard,0,92)===1||e.pollInput(DeviceType.Keyboard,0,93)===1),_=o&&e.pollInput(DeviceType.Keyboard,0,16)===1;i.altKey=s,i.ctrlKey=c,i.metaKey=d,i.shiftKey=_},a._createEvent=function(i){var e={};return e.preventDefault=function(){},e.target=i,e},a}(),NativeDeviceInputSystemImpl=function(){function a(i){var e=this;this.onDeviceConnected=function(o,s){},this.onDeviceDisconnected=function(o,s){},this.onInputChanged=function(o){},this._nativeInput=i||this._createDummyNativeInput(),this._nativeInput.onDeviceConnected=function(o,s){e.onDeviceConnected(o,s)},this._nativeInput.onDeviceDisconnected=function(o,s){e.onDeviceDisconnected(o,s)},this._nativeInput.onInputChanged=function(o,s,c,d,_,b){var k=DeviceEventFactory.CreateDeviceEvent(o,s,c,_,e),j=k;j.deviceType=o,j.deviceSlot=s,j.inputIndex=c,j.previousState=d,j.currentState=_,e.onInputChanged(j)}}return a.prototype.configureEvents=function(){},a.prototype.pollInput=function(i,e,o){return this._nativeInput.pollInput(i,e,o)},a.prototype.isDeviceAvailable=function(i){return i===DeviceType.Mouse||i===DeviceType.Touch},a.prototype.dispose=function(){this.onDeviceConnected=function(){},this.onDeviceDisconnected=function(){},this.onInputChanged=function(){}},a.prototype._createDummyNativeInput=function(){var i={onDeviceConnected:function(e,o){},onDeviceDisconnected:function(e,o){},onInputChanged:function(e,o,s,c,d,_){},pollInput:function(){return 0},isDeviceAvailable:function(){return!1},dispose:function(){}};return i},a}(),WebDeviceInputSystemImpl=function(){function a(i){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Tools.IsSafari(),this._keyboardDownEvent=function(e){},this._keyboardUpEvent=function(e){},this._keyboardBlurEvent=function(e){},this._pointerMoveEvent=function(e){},this._pointerDownEvent=function(e){},this._pointerUpEvent=function(e){},this._pointerWheelEvent=function(e){},this._pointerBlurEvent=function(e){},this._mouseId=-1,this._isUsingFirefox=navigator&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._activeTouchIds=[],this._rollingTouchId=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=function(e){},this._gamepadDisconnectedEvent=function(e){},this._eventPrefix=Tools.GetPointerPrefix(i),this._engine=i,this.onDeviceConnected=function(e,o){},this.onDeviceDisconnected=function(e,o){},this.onInputChanged=function(e){},this.configureEvents()}return Object.defineProperty(a.prototype,"onDeviceConnected",{get:function(){return this._onDeviceConnected},set:function(i){this._onDeviceConnected=i;for(var e=0;e<this._inputs.length;e++){var o=this._inputs[e];if(o)for(var s in o){var c=+s;this._inputs[e][c]&&this._onDeviceConnected(e,c)}}},enumerable:!1,configurable:!0}),a.prototype.configureEvents=function(){var i=this._engine.getInputElement();i&&this._elementToAttachTo!==i&&(this._elementToAttachTo&&this._removeEvents(),this._elementToAttachTo=i,this._elementToAttachTo.tabIndex=this._elementToAttachTo.tabIndex!==-1?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._checkForConnectedDevices())},a.prototype.pollInput=function(i,e,o){var s=this._inputs[i][e];if(!s)throw"Unable to find device "+DeviceType[i];i>=DeviceType.Xbox&&i<=DeviceType.Switch&&navigator.getGamepads&&this._updateDevice(i,e,o);var c=s[o];if(c===void 0)throw"Unable to find input "+o+" for device "+DeviceType[i]+" in slot "+e;return c},a.prototype.isDeviceAvailable=function(i){return this._inputs[i]!==void 0},a.prototype.dispose=function(){this.onDeviceConnected=function(){},this.onDeviceDisconnected=function(){},this.onInputChanged=function(){},this._elementToAttachTo&&(this._removeEvents(),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent))},a.prototype._checkForConnectedDevices=function(){if(navigator.getGamepads)for(var i=navigator.getGamepads(),e=0,o=i;e<o.length;e++){var s=o[e];s&&this._addGamePad(s)}matchMedia("(pointer:fine)").matches&&this._addPointerDevice(DeviceType.Mouse,0,0,0)},a.prototype._addGamePad=function(i){var e=this._getGamepadDeviceType(i.id),o=i.index;this._registerDevice(e,o,i.buttons.length+i.axes.length),this._gamepads=this._gamepads||new Array(i.index+1),this._gamepads[o]=e},a.prototype._addPointerDevice=function(i,e,o,s){this._pointerActive=!0,this._registerDevice(i,e,a.MAX_POINTER_INPUTS);var c=this._inputs[i][e];c[0]=o,c[1]=s},a.prototype._registerDevice=function(i,e,o){if(e===void 0)throw"Unable to register device "+DeviceType[i]+" to undefined slot.";if(this._inputs[i]||(this._inputs[i]={}),!this._inputs[i][e]){for(var s=new Array(o),c=0;c<o;c++)s[c]=0;this._inputs[i][e]=s,this.onDeviceConnected(i,e)}},a.prototype._unregisterDevice=function(i,e){this._inputs[i][e]&&(delete this._inputs[i][e],this.onDeviceDisconnected(i,e))},a.prototype._handleKeyActions=function(){var i=this;this._keyboardDownEvent=function(e){i._keyboardActive||(i._keyboardActive=!0,i._registerDevice(DeviceType.Keyboard,0,a.MAX_KEYCODES));var o=i._inputs[DeviceType.Keyboard][0];if(o){o[e.keyCode]=1;var s=e;s.deviceType=DeviceType.Keyboard,s.deviceSlot=0,s.inputIndex=e.keyCode,s.previousState=0,s.currentState=o[e.keyCode],i.onInputChanged(s)}},this._keyboardUpEvent=function(e){i._keyboardActive||(i._keyboardActive=!0,i._registerDevice(DeviceType.Keyboard,0,a.MAX_KEYCODES));var o=i._inputs[DeviceType.Keyboard][0];if(o){o[e.keyCode]=0;var s=e;s.deviceType=DeviceType.Keyboard,s.deviceSlot=0,s.inputIndex=e.keyCode,s.previousState=1,s.currentState=o[e.keyCode],i.onInputChanged(s)}},this._keyboardBlurEvent=function(e){if(i._keyboardActive){for(var o=i._inputs[DeviceType.Keyboard][0],s=0;s<o.length;s++)if(o[s]!==0){o[s]=0;var c=DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard,0,s,1,i,i._elementToAttachTo),d=c;d.deviceType=DeviceType.Keyboard,d.deviceSlot=0,d.inputIndex=s,d.currentState=0,d.previousState=1,i.onInputChanged(d)}}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)},a.prototype._handlePointerActions=function(){var i=this;this._pointerMoveEvent=function(c){var d=i._getPointerType(c),_=d===DeviceType.Mouse?0:i._activeTouchIds.indexOf(c.pointerId);i._inputs[d]||(i._inputs[d]={}),i._inputs[d][_]||i._addPointerDevice(d,_,c.clientX,c.clientY);var b=i._inputs[d][_];if(b){var k=b[PointerInput.Horizontal],j=b[PointerInput.Vertical],$=b[PointerInput.DeltaHorizontal],_e=b[PointerInput.DeltaVertical];b[PointerInput.Horizontal]=c.clientX,b[PointerInput.Vertical]=c.clientY,b[PointerInput.DeltaHorizontal]=c.movementX,b[PointerInput.DeltaVertical]=c.movementY;var et=c;et.deviceType=d,et.deviceSlot=_,k!==c.clientX&&(et.inputIndex=PointerInput.Horizontal,et.previousState=k,et.currentState=b[PointerInput.Horizontal],i.onInputChanged(et)),j!==c.clientY&&(et.inputIndex=PointerInput.Vertical,et.previousState=j,et.currentState=b[PointerInput.Vertical],i.onInputChanged(et)),b[PointerInput.DeltaHorizontal]!==0&&(et.inputIndex=PointerInput.DeltaHorizontal,et.previousState=$,et.currentState=b[PointerInput.DeltaHorizontal],i.onInputChanged(et)),b[PointerInput.DeltaVertical]!==0&&(et.inputIndex=PointerInput.DeltaVertical,et.previousState=_e,et.currentState=b[PointerInput.DeltaVertical],i.onInputChanged(et)),!i._usingSafari&&c.button!==-1&&(et.inputIndex=c.button+2,et.previousState=b[c.button+2],b[c.button+2]=b[c.button+2]?0:1,et.currentState=b[c.button+2],i.onInputChanged(et))}},this._pointerDownEvent=function(c){var d=i._getPointerType(c),_=d===DeviceType.Mouse?0:c.pointerId;d===DeviceType.Touch&&(_=i._rollingTouchId++,i._activeTouchIds[_]=c.pointerId),i._inputs[d]||(i._inputs[d]={}),i._inputs[d][_]||i._addPointerDevice(d,_,c.clientX,c.clientY);var b=i._inputs[d][_];if(b){var k=b[PointerInput.Horizontal],j=b[PointerInput.Vertical],$=b[c.button+2];if(d===DeviceType.Mouse){if(i._mouseId===-1&&(c.pointerId===void 0?i._mouseId=i._isUsingFirefox?0:1:i._mouseId=c.pointerId),!document.pointerLockElement&&i._elementToAttachTo.hasPointerCapture)try{i._elementToAttachTo.setPointerCapture(i._mouseId)}catch{}}else if(c.pointerId&&!document.pointerLockElement&&i._elementToAttachTo.hasPointerCapture)try{i._elementToAttachTo.setPointerCapture(c.pointerId)}catch{}b[PointerInput.Horizontal]=c.clientX,b[PointerInput.Vertical]=c.clientY,b[c.button+2]=1;var _e=c;_e.deviceType=d,_e.deviceSlot=_,k!==c.clientX&&(_e.inputIndex=PointerInput.Horizontal,_e.previousState=k,_e.currentState=b[PointerInput.Horizontal],i.onInputChanged(_e)),j!==c.clientY&&(_e.inputIndex=PointerInput.Vertical,_e.previousState=j,_e.currentState=b[PointerInput.Vertical],i.onInputChanged(_e)),_e.inputIndex=c.button+2,_e.previousState=$,_e.currentState=b[c.button+2],i.onInputChanged(_e)}},this._pointerUpEvent=function(c){var d,_,b,k,j,$=i._getPointerType(c),_e=$===DeviceType.Mouse?0:i._activeTouchIds.indexOf(c.pointerId),et=(d=i._inputs[$])===null||d===void 0?void 0:d[_e];if(et&&et[c.button+2]!==0){var tt=et[PointerInput.Horizontal],rt=et[PointerInput.Vertical],it=et[c.button+2];et[PointerInput.Horizontal]=c.clientX,et[PointerInput.Vertical]=c.clientY,et[c.button+2]=0;var nt=c;if(nt.deviceType=$,nt.deviceSlot=_e,tt!==c.clientX&&(nt.inputIndex=PointerInput.Horizontal,nt.previousState=tt,nt.currentState=et[PointerInput.Horizontal],i.onInputChanged(nt)),rt!==c.clientY&&(nt.inputIndex=PointerInput.Vertical,nt.previousState=rt,nt.currentState=et[PointerInput.Vertical],i.onInputChanged(nt)),nt.inputIndex=c.button+2,nt.previousState=it,nt.currentState=et[c.button+2],$===DeviceType.Mouse&&i._mouseId>=0&&((b=(_=i._elementToAttachTo).hasPointerCapture)===null||b===void 0?void 0:b.call(_,i._mouseId))?i._elementToAttachTo.releasePointerCapture(i._mouseId):c.pointerId&&((j=(k=i._elementToAttachTo).hasPointerCapture)===null||j===void 0?void 0:j.call(k,c.pointerId))&&i._elementToAttachTo.releasePointerCapture(c.pointerId),i.onInputChanged(nt),$!==DeviceType.Mouse){var ot=i._activeTouchIds.indexOf(c.pointerId);delete i._activeTouchIds[ot],i._unregisterDevice($,_e)}}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";var e=!1,o=function(){};try{var s={passive:{get:function(){e=!0}}};this._elementToAttachTo.addEventListener("test",o,s),this._elementToAttachTo.removeEventListener("test",o,s)}catch{}this._pointerBlurEvent=function(c){var d,_,b,k,j;if(i.isDeviceAvailable(DeviceType.Mouse)){var $=i._inputs[DeviceType.Mouse][0];i._mouseId>=0&&((_=(d=i._elementToAttachTo).hasPointerCapture)===null||_===void 0?void 0:_.call(d,i._mouseId))&&i._elementToAttachTo.releasePointerCapture(i._mouseId);for(var _e=0;_e<=PointerInput.BrowserForward;_e++)if($[_e+2]===1){$[_e+2]=0;var et=DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse,0,_e+2,1,i,i._elementToAttachTo),tt=et;tt.deviceType=DeviceType.Mouse,tt.deviceSlot=0,tt.inputIndex=_e+2,tt.currentState=$[_e+2],tt.previousState=1,i.onInputChanged(tt)}}if(i.isDeviceAvailable(DeviceType.Touch)){var $=i._inputs[DeviceType.Touch];for(var rt in Object.keys(i._activeTouchIds)){var it=+rt,nt=i._activeTouchIds[it];if(!((k=(b=i._elementToAttachTo).hasPointerCapture)===null||k===void 0)&&k.call(b,nt)&&i._elementToAttachTo.releasePointerCapture(nt),((j=$[it])===null||j===void 0?void 0:j[PointerInput.LeftClick])===1){$[it][PointerInput.LeftClick]=0;var ot=DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch,nt,PointerInput.LeftClick,1,i,i._elementToAttachTo),tt=ot;tt.deviceType=DeviceType.Mouse,tt.deviceSlot=it,tt.inputIndex=PointerInput.LeftClick,tt.currentState=$[it][PointerInput.LeftClick],tt.previousState=1,i.onInputChanged(tt),i._unregisterDevice(DeviceType.Touch,it)}}for(;i._activeTouchIds.pop()!==void 0;);}},this._pointerWheelEvent=function(c){var d=DeviceType.Mouse,_=0;i._inputs[d]||(i._inputs[d]=[]),i._inputs[d][_]||(i._pointerActive=!0,i._registerDevice(d,_,a.MAX_POINTER_INPUTS));var b=i._inputs[d][_];if(b){var k=b[PointerInput.MouseWheelX],j=b[PointerInput.MouseWheelY],$=b[PointerInput.MouseWheelZ];b[PointerInput.MouseWheelX]=c.deltaX||0,b[PointerInput.MouseWheelY]=c.deltaY||c.wheelDelta||0,b[PointerInput.MouseWheelZ]=c.deltaZ||0;var _e=c;_e.deviceType=d,_e.deviceSlot=_,b[PointerInput.MouseWheelX]!==0&&(_e.inputIndex=PointerInput.MouseWheelX,_e.previousState=k,_e.currentState=b[PointerInput.MouseWheelX],i.onInputChanged(_e)),b[PointerInput.MouseWheelY]!==0&&(_e.inputIndex=PointerInput.MouseWheelY,_e.previousState=j,_e.currentState=b[PointerInput.MouseWheelY],i.onInputChanged(_e)),b[PointerInput.MouseWheelZ]!==0&&(_e.inputIndex=PointerInput.MouseWheelZ,_e.previousState=$,_e.currentState=b[PointerInput.MouseWheelZ],i.onInputChanged(_e))}},this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(function(){if(i.isDeviceAvailable(DeviceType.Mouse)){var c=i._inputs[DeviceType.Mouse][0];c[PointerInput.MouseWheelX]=0,c[PointerInput.MouseWheelY]=0,c[PointerInput.MouseWheelZ]=0,c[PointerInput.DeltaHorizontal]=0,c[PointerInput.DeltaVertical]=0}})},a.prototype._handleGamepadActions=function(){var i=this;this._gamepadConnectedEvent=function(e){i._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=function(e){if(i._gamepads){var o=i._getGamepadDeviceType(e.gamepad.id),s=e.gamepad.index;i._unregisterDevice(o,s),delete i._gamepads[s]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)},a.prototype._updateDevice=function(i,e,o){var s=navigator.getGamepads()[e];if(s&&i===this._gamepads[e]){var c=this._inputs[i][e];o>=s.buttons.length?c[o]=s.axes[o-s.buttons.length].valueOf():c[o]=s.buttons[o].value}},a.prototype._getGamepadDeviceType=function(i){return i.indexOf("054c")!==-1&&i.indexOf("0ce6")===-1?DeviceType.DualShock:i.indexOf("Xbox One")!==-1||i.search("Xbox 360")!==-1||i.search("xinput")!==-1?DeviceType.Xbox:i.indexOf("057e")!==-1?DeviceType.Switch:DeviceType.Generic},a.prototype._getPointerType=function(i){var e=DeviceType.Mouse;return(i.pointerType==="touch"||i.pointerType==="pen"||i.touches)&&(e=DeviceType.Touch),e},a.prototype._removeEvents=function(){this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._keyboardActive&&(this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent)),this._pointerActive&&(this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver))},a.MAX_KEYCODES=255,a.MAX_POINTER_INPUTS=Object.keys(PointerInput).length/2,a}(),DeviceInputSystem=function(){function a(i){var e=this;this._deviceInputSystem=i,this.onDeviceConnectedObservable=new Observable,this.onDeviceDisconnectedObservable=new Observable,this.onInputChangedObservable=new Observable,this._deviceInputSystem.onDeviceConnected=function(o,s){e.onDeviceConnectedObservable.notifyObservers({deviceType:o,deviceSlot:s})},this._deviceInputSystem.onDeviceDisconnected=function(o,s){e.onDeviceDisconnectedObservable.notifyObservers({deviceType:o,deviceSlot:s})},this._deviceInputSystem.onInputChanged=function(o){e.onInputChangedObservable.notifyObservers(o)}}return a._Create=function(i){if(!i.deviceInputSystem){var e=void 0;typeof _native!="undefined"?e=_native.DeviceInputSystem?new NativeDeviceInputSystemImpl(new _native.DeviceInputSystem):new NativeDeviceInputSystemImpl:e=new WebDeviceInputSystemImpl(i),e&&(i.deviceInputSystem=new a(e))}return i.deviceInputSystem},a.prototype.configureEvents=function(){this._deviceInputSystem.configureEvents()},a.prototype.pollInput=function(i,e,o){return this._deviceInputSystem.pollInput(i,e,o)},a.prototype.isDeviceAvailable=function(i){return this._deviceInputSystem.isDeviceAvailable(i)},a.prototype.dispose=function(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this.onInputChangedObservable.clear(),this._deviceInputSystem.dispose()},a}(),_ClickInfo=function(){function a(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}return Object.defineProperty(a.prototype,"singleClick",{get:function(){return this._singleClick},set:function(i){this._singleClick=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"doubleClick",{get:function(){return this._doubleClick},set:function(i){this._doubleClick=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasSwiped",{get:function(){return this._hasSwiped},set:function(i){this._hasSwiped=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"ignore",{get:function(){return this._ignore},set:function(i){this._ignore=i},enumerable:!1,configurable:!0}),a}(),InputManager=function(){function a(i){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new Vector2(0,0),this._previousStartingPointerPosition=new Vector2(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._scene=i}return Object.defineProperty(a.prototype,"meshUnderPointer",{get:function(){return this._pointerOverMesh},enumerable:!1,configurable:!0}),a.prototype.getMeshUnderPointerByPointerId=function(i){return this._meshUnderPointerId[i]||null},Object.defineProperty(a.prototype,"unTranslatedPointer",{get:function(){return new Vector2(this._unTranslatedPointerX,this._unTranslatedPointerY)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"pointerX",{get:function(){return this._pointerX},set:function(i){this._pointerX=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"pointerY",{get:function(){return this._pointerY},set:function(i){this._pointerY=i},enumerable:!1,configurable:!0}),a.prototype._updatePointerPosition=function(i){var e=this._scene.getEngine().getInputElementClientRect();!e||(this._pointerX=i.clientX-e.left,this._pointerY=i.clientY-e.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)},a.prototype._processPointerMove=function(i,e){var o=this._scene,s=o.getEngine(),c=s.getInputElement();c&&(c.tabIndex=s.canvasTabIndex,o.doNotHandleCursors||(c.style.cursor=o.defaultCursor));var d=!!(i&&i.hit&&i.pickedMesh);d?(o.setPointerOverMesh(i.pickedMesh,e.pointerId,i),this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.hasPointerTriggers&&!o.doNotHandleCursors&&c&&(this._pointerOverMesh.actionManager.hoverCursor?c.style.cursor=this._pointerOverMesh.actionManager.hoverCursor:c.style.cursor=o.hoverCursor)):o.setPointerOverMesh(null,e.pointerId,i);for(var _=0,b=o._pointerMoveStage;_<b.length;_++){var k=b[_];i=k.action(this._unTranslatedPointerX,this._unTranslatedPointerY,i,d,c)}if(i){var j=e.type==="wheel"||e.type==="mousewheel"||e.type==="DOMMouseScroll"?PointerEventTypes.POINTERWHEEL:PointerEventTypes.POINTERMOVE;if(o.onPointerMove&&o.onPointerMove(e,i,j),o.onPointerObservable.hasObservers()){var $=new PointerInfo(j,e,i);this._setRayOnPointerInfo($),o.onPointerObservable.notifyObservers($,j)}}},a.prototype._setRayOnPointerInfo=function(i){var e=this._scene;i.pickInfo&&!i.pickInfo._pickingUnavailable&&(i.pickInfo.ray||(i.pickInfo.ray=e.createPickingRay(i.event.offsetX,i.event.offsetY,Matrix.Identity(),e.activeCamera)))},a.prototype._checkPrePointerObservable=function(i,e,o){var s=this._scene,c=new PointerInfoPre(o,e,this._unTranslatedPointerX,this._unTranslatedPointerY);return i&&(c.ray=i.ray,i.originMesh&&(c.nearInteractionPickingInfo=i)),s.onPrePointerObservable.notifyObservers(c,o),!!c.skipOnPointerObservable},a.prototype.simulatePointerMove=function(i,e){var o=new PointerEvent("pointermove",e);this._checkPrePointerObservable(i,o,PointerEventTypes.POINTERMOVE)||this._processPointerMove(i,o)},a.prototype.simulatePointerDown=function(i,e){var o=new PointerEvent("pointerdown",e);this._checkPrePointerObservable(i,o,PointerEventTypes.POINTERDOWN)||this._processPointerDown(i,o)},a.prototype._processPointerDown=function(i,e){var o=this,s=this._scene;if(i&&i.hit&&i.pickedMesh){this._pickedDownMesh=i.pickedMesh;var c=i.pickedMesh._getActionManagerForTrigger();if(c){if(c.hasPickTriggers)switch(c.processTrigger(5,ActionEvent.CreateNew(i.pickedMesh,e)),e.button){case 0:c.processTrigger(2,ActionEvent.CreateNew(i.pickedMesh,e));break;case 1:c.processTrigger(4,ActionEvent.CreateNew(i.pickedMesh,e));break;case 2:c.processTrigger(3,ActionEvent.CreateNew(i.pickedMesh,e));break}c.hasSpecificTrigger(8)&&window.setTimeout(function(){var $=s.pick(o._unTranslatedPointerX,o._unTranslatedPointerY,function(_e){return _e.isPickable&&_e.isVisible&&_e.isReady()&&_e.actionManager&&_e.actionManager.hasSpecificTrigger(8)&&_e===o._pickedDownMesh},!1,s.cameraToUseForPointers);$&&$.hit&&$.pickedMesh&&c&&o._totalPointersPressed!==0&&Date.now()-o._startingPointerTime>a.LongPressDelay&&!o._isPointerSwiping()&&(o._startingPointerTime=0,c.processTrigger(8,ActionEvent.CreateNew($.pickedMesh,e)))},a.LongPressDelay)}}else for(var d=0,_=s._pointerDownStage;d<_.length;d++){var b=_[d];i=b.action(this._unTranslatedPointerX,this._unTranslatedPointerY,i,e)}if(i){var k=PointerEventTypes.POINTERDOWN;if(s.onPointerDown&&s.onPointerDown(e,i,k),s.onPointerObservable.hasObservers()){var j=new PointerInfo(k,e,i);this._setRayOnPointerInfo(j),s.onPointerObservable.notifyObservers(j,k)}}},a.prototype._isPointerSwiping=function(){return Math.abs(this._startingPointerPosition.x-this._pointerX)>a.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>a.DragMovementThreshold},a.prototype.simulatePointerUp=function(i,e,o){var s=new PointerEvent("pointerup",e),c=new _ClickInfo;o?c.doubleClick=!0:c.singleClick=!0,!this._checkPrePointerObservable(i,s,PointerEventTypes.POINTERUP)&&this._processPointerUp(i,s,c)},a.prototype._processPointerUp=function(i,e,o){var s=this._scene;if(i&&i&&i.pickedMesh){if(this._pickedUpMesh=i.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(e,i),o.singleClick&&!o.ignore&&s.onPointerObservable.hasObservers())){var c=PointerEventTypes.POINTERPICK,d=new PointerInfo(c,e,i);this._setRayOnPointerInfo(d),s.onPointerObservable.notifyObservers(d,c)}var _=i.pickedMesh._getActionManagerForTrigger();if(_&&!o.ignore){_.processTrigger(7,ActionEvent.CreateNew(i.pickedMesh,e,i)),!o.hasSwiped&&o.singleClick&&_.processTrigger(1,ActionEvent.CreateNew(i.pickedMesh,e,i));var b=i.pickedMesh._getActionManagerForTrigger(6);o.doubleClick&&b&&b.processTrigger(6,ActionEvent.CreateNew(i.pickedMesh,e,i))}}else if(!o.ignore)for(var k=0,j=s._pointerUpStage;k<j.length;k++){var $=j[k];i=$.action(this._unTranslatedPointerX,this._unTranslatedPointerY,i,e)}if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){var _e=this._pickedDownMesh._getActionManagerForTrigger(16);_e&&_e.processTrigger(16,ActionEvent.CreateNew(this._pickedDownMesh,e))}var et=0;if(s.onPointerObservable.hasObservers()){if(!o.ignore&&!o.hasSwiped&&(o.singleClick&&s.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)?et=PointerEventTypes.POINTERTAP:o.doubleClick&&s.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)&&(et=PointerEventTypes.POINTERDOUBLETAP),et)){var d=new PointerInfo(et,e,i);this._setRayOnPointerInfo(d),s.onPointerObservable.notifyObservers(d,et)}if(!o.ignore){et=PointerEventTypes.POINTERUP;var d=new PointerInfo(et,e,i);this._setRayOnPointerInfo(d),s.onPointerObservable.notifyObservers(d,et)}}s.onPointerUp&&!o.ignore&&s.onPointerUp(e,i,et)},a.prototype.isPointerCaptured=function(i){return i===void 0&&(i=0),this._pointerCaptures[i]},a.prototype.attachControl=function(i,e,o,s){var c=this;i===void 0&&(i=!0),e===void 0&&(e=!0),o===void 0&&(o=!0),s===void 0&&(s=null);var d=this._scene,_=d.getEngine();s||(s=_.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceInputSystem?this._deviceInputSystem.configureEvents():this._deviceInputSystem=DeviceInputSystem._Create(_),this._initActionManager=function(b,k){if(!c._meshPickProceed){var j=d.pick(c._unTranslatedPointerX,c._unTranslatedPointerY,d.pointerDownPredicate,!1,d.cameraToUseForPointers);c._currentPickResult=j,j&&(b=j.hit&&j.pickedMesh?j.pickedMesh._getActionManagerForTrigger():null),c._meshPickProceed=!0}return b},this._delayedSimpleClick=function(b,k,j){(Date.now()-c._previousStartingPointerTime>a.DoubleClickDelay&&!c._doubleClickOccured||b!==c._previousButtonPressed)&&(c._doubleClickOccured=!1,k.singleClick=!0,k.ignore=!1,j(k,c._currentPickResult))},this._initClickEvent=function(b,k,j,$){var _e=new _ClickInfo;c._currentPickResult=null;var et=null,tt=b.hasSpecificMask(PointerEventTypes.POINTERPICK)||k.hasSpecificMask(PointerEventTypes.POINTERPICK)||b.hasSpecificMask(PointerEventTypes.POINTERTAP)||k.hasSpecificMask(PointerEventTypes.POINTERTAP)||b.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)||k.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);!tt&&AbstractActionManager&&(et=c._initActionManager(et,_e),et&&(tt=et.hasPickTriggers));var rt=!1;if(tt){var it=j.button;if(_e.hasSwiped=c._isPointerSwiping(),!_e.hasSwiped){var nt=!a.ExclusiveDoubleClickMode;nt||(nt=!b.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)&&!k.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP),nt&&!AbstractActionManager.HasSpecificTrigger(6)&&(et=c._initActionManager(et,_e),et&&(nt=!et.hasSpecificTrigger(6)))),nt?(Date.now()-c._previousStartingPointerTime>a.DoubleClickDelay||it!==c._previousButtonPressed)&&(_e.singleClick=!0,$(_e,c._currentPickResult),rt=!0):(c._previousDelayedSimpleClickTimeout=c._delayedSimpleClickTimeout,c._delayedSimpleClickTimeout=window.setTimeout(c._delayedSimpleClick.bind(c,it,_e,$),a.DoubleClickDelay));var ot=b.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)||k.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);!ot&&AbstractActionManager.HasSpecificTrigger(6)&&(et=c._initActionManager(et,_e),et&&(ot=et.hasSpecificTrigger(6))),ot&&(it===c._previousButtonPressed&&Date.now()-c._previousStartingPointerTime<a.DoubleClickDelay&&!c._doubleClickOccured?(!_e.hasSwiped&&!c._isPointerSwiping()?(c._previousStartingPointerTime=0,c._doubleClickOccured=!0,_e.doubleClick=!0,_e.ignore=!1,a.ExclusiveDoubleClickMode&&c._previousDelayedSimpleClickTimeout&&clearTimeout(c._previousDelayedSimpleClickTimeout),c._previousDelayedSimpleClickTimeout=c._delayedSimpleClickTimeout,$(_e,c._currentPickResult)):(c._doubleClickOccured=!1,c._previousStartingPointerTime=c._startingPointerTime,c._previousStartingPointerPosition.x=c._startingPointerPosition.x,c._previousStartingPointerPosition.y=c._startingPointerPosition.y,c._previousButtonPressed=it,a.ExclusiveDoubleClickMode?(c._previousDelayedSimpleClickTimeout&&clearTimeout(c._previousDelayedSimpleClickTimeout),c._previousDelayedSimpleClickTimeout=c._delayedSimpleClickTimeout,$(_e,c._previousPickResult)):$(_e,c._currentPickResult)),rt=!0):(c._doubleClickOccured=!1,c._previousStartingPointerTime=c._startingPointerTime,c._previousStartingPointerPosition.x=c._startingPointerPosition.x,c._previousStartingPointerPosition.y=c._startingPointerPosition.y,c._previousButtonPressed=it))}}rt||$(_e,c._currentPickResult)},this._onPointerMove=function(b){if(b.pointerId===void 0&&(b.pointerId=0),c._updatePointerPosition(b),!c._checkPrePointerObservable(null,b,b.type==="wheel"||b.type==="mousewheel"||b.type==="DOMMouseScroll"?PointerEventTypes.POINTERWHEEL:PointerEventTypes.POINTERMOVE)&&!(!d.cameraToUseForPointers&&!d.activeCamera)){if(d.skipPointerMovePicking){c._processPointerMove(new PickingInfo,b);return}d.pointerMovePredicate||(d.pointerMovePredicate=function(j){return j.isPickable&&j.isVisible&&j.isReady()&&j.isEnabled()&&(j.enablePointerMoveEvents||d.constantlyUpdateMeshUnderPointer||j._getActionManagerForTrigger()!==null)&&(!d.cameraToUseForPointers||(d.cameraToUseForPointers.layerMask&j.layerMask)!==0)});var k=d.pick(c._unTranslatedPointerX,c._unTranslatedPointerY,d.pointerMovePredicate,!1,d.cameraToUseForPointers,d.pointerMoveTrianglePredicate);c._processPointerMove(k,b)}},this._onPointerDown=function(b){if(c._totalPointersPressed++,c._pickedDownMesh=null,c._meshPickProceed=!1,b.pointerId===void 0&&(b.pointerId=0),c._updatePointerPosition(b),d.preventDefaultOnPointerDown&&s&&(b.preventDefault(),s.focus()),c._startingPointerPosition.x=c._pointerX,c._startingPointerPosition.y=c._pointerY,c._startingPointerTime=Date.now(),!c._checkPrePointerObservable(null,b,PointerEventTypes.POINTERDOWN)&&!(!d.cameraToUseForPointers&&!d.activeCamera)){c._pointerCaptures[b.pointerId]=!0,d.pointerDownPredicate||(d.pointerDownPredicate=function(j){return j.isPickable&&j.isVisible&&j.isReady()&&j.isEnabled()&&(!d.cameraToUseForPointers||(d.cameraToUseForPointers.layerMask&j.layerMask)!==0)}),c._pickedDownMesh=null;var k=d.pick(c._unTranslatedPointerX,c._unTranslatedPointerY,d.pointerDownPredicate,!1,d.cameraToUseForPointers);c._processPointerDown(k,b)}},this._onPointerUp=function(b){c._totalPointersPressed!==0&&(c._totalPointersPressed--,c._pickedUpMesh=null,c._meshPickProceed=!1,b.pointerId===void 0&&(b.pointerId=0),c._updatePointerPosition(b),d.preventDefaultOnPointerUp&&s&&(b.preventDefault(),s.focus()),c._initClickEvent(d.onPrePointerObservable,d.onPointerObservable,b,function(k,j){d.onPrePointerObservable.hasObservers()&&!k.ignore&&(!k.hasSwiped&&(k.singleClick&&d.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)&&c._checkPrePointerObservable(null,b,PointerEventTypes.POINTERTAP)||k.doubleClick&&d.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)&&c._checkPrePointerObservable(null,b,PointerEventTypes.POINTERDOUBLETAP))||c._checkPrePointerObservable(null,b,PointerEventTypes.POINTERUP))||!c._pointerCaptures[b.pointerId]&&b.buttons>0||(c._pointerCaptures[b.pointerId]=!1,!(!d.cameraToUseForPointers&&!d.activeCamera)&&(d.pointerUpPredicate||(d.pointerUpPredicate=function($){return $.isPickable&&$.isVisible&&$.isReady()&&$.isEnabled()&&(!d.cameraToUseForPointers||(d.cameraToUseForPointers.layerMask&$.layerMask)!==0)}),!c._meshPickProceed&&(AbstractActionManager&&AbstractActionManager.HasTriggers||d.onPointerObservable.hasObservers())&&c._initActionManager(null,k),j||(j=c._currentPickResult),c._processPointerUp(j,b,k),c._previousPickResult=c._currentPickResult))}))},this._onKeyDown=function(b){var k=KeyboardEventTypes.KEYDOWN;if(d.onPreKeyboardObservable.hasObservers()){var j=new KeyboardInfoPre(k,b);if(d.onPreKeyboardObservable.notifyObservers(j,k),j.skipOnPointerObservable)return}if(d.onKeyboardObservable.hasObservers()){var j=new KeyboardInfo(k,b);d.onKeyboardObservable.notifyObservers(j,k)}d.actionManager&&d.actionManager.processTrigger(14,ActionEvent.CreateNewFromScene(d,b))},this._onKeyUp=function(b){var k=KeyboardEventTypes.KEYUP;if(d.onPreKeyboardObservable.hasObservers()){var j=new KeyboardInfoPre(k,b);if(d.onPreKeyboardObservable.notifyObservers(j,k),j.skipOnPointerObservable)return}if(d.onKeyboardObservable.hasObservers()){var j=new KeyboardInfo(k,b);d.onKeyboardObservable.notifyObservers(j,k)}d.actionManager&&d.actionManager.processTrigger(15,ActionEvent.CreateNewFromScene(d,b))},this._onInputObserver=this._deviceInputSystem.onInputChangedObservable.add(function(b){var k=b;b.deviceType===DeviceType.Keyboard&&(b.currentState===1&&c._onKeyDown(k),b.currentState===0&&c._onKeyUp(k)),(b.deviceType===DeviceType.Mouse||b.deviceType===DeviceType.Touch)&&(e&&b.inputIndex>=PointerInput.LeftClick&&b.inputIndex<=PointerInput.RightClick&&b.currentState===1&&c._onPointerDown(k),i&&b.inputIndex>=PointerInput.LeftClick&&b.inputIndex<=PointerInput.RightClick&&b.currentState===0&&c._onPointerUp(k),o&&(b.inputIndex===PointerInput.Horizontal||b.inputIndex===PointerInput.Vertical||b.inputIndex===PointerInput.DeltaHorizontal||b.inputIndex===PointerInput.DeltaVertical||b.inputIndex===PointerInput.MouseWheelX||b.inputIndex===PointerInput.MouseWheelY||b.inputIndex===PointerInput.MouseWheelZ)&&c._onPointerMove(k))}),this._alreadyAttached=!0},a.prototype.detachControl=function(){this._alreadyAttached&&(this._deviceInputSystem.onInputChangedObservable.remove(this._onInputObserver),this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1)},a.prototype.setPointerOverMesh=function(i,e,o){if(e===void 0&&(e=0),this._meshUnderPointerId[e]!==i){var s=this._meshUnderPointerId[e],c;s&&(c=s._getActionManagerForTrigger(10),c&&c.processTrigger(10,ActionEvent.CreateNew(s,void 0,{pointerId:e}))),i?(this._meshUnderPointerId[e]=i,this._pointerOverMesh=i,c=i._getActionManagerForTrigger(9),c&&c.processTrigger(9,ActionEvent.CreateNew(i,void 0,{pointerId:e,pickResult:o}))):(delete this._meshUnderPointerId[e],this._pointerOverMesh=null)}},a.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},a.prototype._invalidateMesh=function(i){this._pointerOverMesh===i&&(this._pointerOverMesh=null),this._pickedDownMesh===i&&(this._pickedDownMesh=null),this._pickedUpMesh===i&&(this._pickedUpMesh=null);for(var e in this._meshUnderPointerId)this._meshUnderPointerId[e]===i&&delete this._meshUnderPointerId[e]},a.DragMovementThreshold=10,a.LongPressDelay=500,a.DoubleClickDelay=300,a.ExclusiveDoubleClickMode=!1,a}(),UniqueIdGenerator=function(){function a(){}return Object.defineProperty(a,"UniqueId",{get:function(){var i=this._UniqueIdCounter;return this._UniqueIdCounter++,i},enumerable:!1,configurable:!0}),a._UniqueIdCounter=0,a}(),LightConstants=function(){function a(){}return a.CompareLightsPriority=function(i,e){return i.shadowEnabled!==e.shadowEnabled?(e.shadowEnabled?1:0)-(i.shadowEnabled?1:0):e.renderPriority-i.renderPriority},a.FALLOFF_DEFAULT=0,a.FALLOFF_PHYSICAL=1,a.FALLOFF_GLTF=2,a.FALLOFF_STANDARD=3,a.LIGHTMAP_DEFAULT=0,a.LIGHTMAP_SPECULAR=1,a.LIGHTMAP_SHADOWSONLY=2,a.INTENSITYMODE_AUTOMATIC=0,a.INTENSITYMODE_LUMINOUSPOWER=1,a.INTENSITYMODE_LUMINOUSINTENSITY=2,a.INTENSITYMODE_ILLUMINANCE=3,a.INTENSITYMODE_LUMINANCE=4,a.LIGHTTYPEID_POINTLIGHT=0,a.LIGHTTYPEID_DIRECTIONALLIGHT=1,a.LIGHTTYPEID_SPOTLIGHT=2,a.LIGHTTYPEID_HEMISPHERICLIGHT=3,a}(),ComputePressureObserverWrapper=function(){function a(i,e){a.IsAvailable&&(this._observer=new window.ComputePressureObserver(i,e))}return Object.defineProperty(a,"IsAvailable",{get:function(){return IsWindowObjectExist()&&"ComputePressureObserver"in window},enumerable:!1,configurable:!0}),a.prototype.observe=function(){var i,e;!((i=this._observer)===null||i===void 0)&&i.observe&&((e=this._observer)===null||e===void 0||e.observe())},a.prototype.unobserve=function(){var i,e;!((i=this._observer)===null||i===void 0)&&i.unobserve&&((e=this._observer)===null||e===void 0||e.unobserve())},a}(),_injectLTSScene=function(a){a.prototype.setActiveCameraByID=function(i){return this.setActiveCameraById(i)},a.prototype.getLastMaterialByID=function(i){return this.getLastMaterialById(i)},a.prototype.getMaterialByID=function(i){return this.getMaterialById(i)},a.prototype.getTextureByUniqueID=function(i){return this.getTextureByUniqueId(i)},a.prototype.getCameraByID=function(i){return this.getCameraById(i)},a.prototype.getCameraByUniqueID=function(i){return this.getCameraByUniqueId(i)},a.prototype.getBoneByID=function(i){return this.getBoneById(i)},a.prototype.getLightByID=function(i){return this.getLightById(i)},a.prototype.getLightByUniqueID=function(i){return this.getLightByUniqueId(i)},a.prototype.getParticleSystemByID=function(i){return this.getParticleSystemById(i)},a.prototype.getGeometryByID=function(i){return this.getGeometryById(i)},a.prototype.getMeshByID=function(i){return this.getMeshById(i)},a.prototype.getMeshesByID=function(i){return this.getMeshesById(i)},a.prototype.getTransformNodeByID=function(i){return this.getTransformNodeById(i)},a.prototype.getTransformNodeByUniqueID=function(i){return this.getTransformNodeByUniqueId(i)},a.prototype.getTransformNodesByID=function(i){return this.getTransformNodesById(i)},a.prototype.getMeshByUniqueID=function(i){return this.getMeshByUniqueId(i)},a.prototype.getLastMeshByID=function(i){return this.getLastMeshById(i)},a.prototype.getLastEntryByID=function(i){return this.getLastEntryById(i)},a.prototype.getNodeByID=function(i){return this.getNodeById(i)},a.prototype.getLastSkeletonByID=function(i){return this.getLastSkeletonById(i)}},Scene=function(a){__extends(i,a);function i(e,o){var s=a.call(this)||this;s._inputManager=new InputManager(s),s.cameraToUseForPointers=null,s._isScene=!0,s._blockEntityCollection=!1,s.autoClear=!0,s.autoClearDepthAndStencil=!0,s.clearColor=new Color4(.2,.2,.3,1),s.ambientColor=new Color3(0,0,0),s._environmentIntensity=1,s._forceWireframe=!1,s._skipFrustumClipping=!1,s._forcePointsCloud=!1,s.animationsEnabled=!0,s._animationPropertiesOverride=null,s.useConstantAnimationDeltaTime=!1,s.constantlyUpdateMeshUnderPointer=!1,s.hoverCursor="pointer",s.defaultCursor="",s.doNotHandleCursors=!1,s.preventDefaultOnPointerDown=!0,s.preventDefaultOnPointerUp=!0,s.metadata=null,s.reservedDataStore=null,s.disableOfflineSupportExceptionRules=new Array,s.onDisposeObservable=new Observable,s._onDisposeObserver=null,s.onBeforeRenderObservable=new Observable,s._onBeforeRenderObserver=null,s.onAfterRenderObservable=new Observable,s.onBeforeRunRegisterBeforeRenderObservable=new Observable,s.onAfterRunRegisterBeforeRenderObservable=new Observable,s.onBeforeRunRegisterAfterRenderObservable=new Observable,s.onAfterRunRegisterAfterRenderObservable=new Observable,s.onBeforeRTT1Observable=new Observable,s.onAfterRTT1Observable=new Observable,s.onAfterRenderCameraObservable=new Observable,s._onAfterRenderObserver=null,s.onBeforeAnimationsObservable=new Observable,s.onAfterAnimationsObservable=new Observable,s.onBeforeDrawPhaseObservable=new Observable,s.onAfterDrawPhaseObservable=new Observable,s.onReadyObservable=new Observable,s.onBeforeCameraRenderObservable=new Observable,s._onBeforeCameraRenderObserver=null,s.onAfterCameraRenderObservable=new Observable,s._onAfterCameraRenderObserver=null,s.onBeforeActiveMeshesEvaluationObservable=new Observable,s.onAfterActiveMeshesEvaluationObservable=new Observable,s.onBeforeParticlesRenderingObservable=new Observable,s.onAfterParticlesRenderingObservable=new Observable,s.onDataLoadedObservable=new Observable,s.onNewCameraAddedObservable=new Observable,s.onCameraRemovedObservable=new Observable,s.onNewLightAddedObservable=new Observable,s.onLightRemovedObservable=new Observable,s.onNewGeometryAddedObservable=new Observable,s.onGeometryRemovedObservable=new Observable,s.onNewTransformNodeAddedObservable=new Observable,s.onTransformNodeRemovedObservable=new Observable,s.onNewMeshAddedObservable=new Observable,s.onMeshRemovedObservable=new Observable,s.onNewSkeletonAddedObservable=new Observable,s.onSkeletonRemovedObservable=new Observable,s.onNewMaterialAddedObservable=new Observable,s.onNewMultiMaterialAddedObservable=new Observable,s.onMaterialRemovedObservable=new Observable,s.onMultiMaterialRemovedObservable=new Observable,s.onNewTextureAddedObservable=new Observable,s.onTextureRemovedObservable=new Observable,s.onBeforeRenderTargetsRenderObservable=new Observable,s.onAfterRenderTargetsRenderObservable=new Observable,s.onBeforeStepObservable=new Observable,s.onAfterStepObservable=new Observable,s.onActiveCameraChanged=new Observable,s.onBeforeRenderingGroupObservable=new Observable,s.onAfterRenderingGroupObservable=new Observable,s.onMeshImportedObservable=new Observable,s.onAnimationFileImportedObservable=new Observable,s._registeredForLateAnimationBindings=new SmartArrayNoDuplicate(256),s.skipPointerMovePicking=!1,s.onPrePointerObservable=new Observable,s.onPointerObservable=new Observable,s.onPreKeyboardObservable=new Observable,s.onKeyboardObservable=new Observable,s._useRightHandedSystem=!1,s._timeAccumulator=0,s._currentStepId=0,s._currentInternalStep=0,s._fogEnabled=!0,s._fogMode=i.FOGMODE_NONE,s.fogColor=new Color3(.2,.2,.3),s.fogDensity=.1,s.fogStart=0,s.fogEnd=1e3,s.needsPreviousWorldMatrices=!1,s._shadowsEnabled=!0,s._lightsEnabled=!0,s.activeCameras=new Array,s._texturesEnabled=!0,s.physicsEnabled=!0,s.particlesEnabled=!0,s.spritesEnabled=!0,s._skeletonsEnabled=!0,s.lensFlaresEnabled=!0,s.collisionsEnabled=!0,s.gravity=new Vector3(0,-9.807,0),s.postProcessesEnabled=!0,s.renderTargetsEnabled=!0,s.dumpNextRenderTargets=!1,s.customRenderTargets=new Array,s.importedMeshesFiles=new Array,s.probesEnabled=!0,s._meshesForIntersections=new SmartArrayNoDuplicate(256),s.proceduralTexturesEnabled=!0,s._totalVertices=new PerfCounter,s._activeIndices=new PerfCounter,s._activeParticles=new PerfCounter,s._activeBones=new PerfCounter,s._animationTime=0,s.animationTimeScale=1,s._renderId=0,s._frameId=0,s._executeWhenReadyTimeoutId=-1,s._intermediateRendering=!1,s._defaultFrameBufferCleared=!1,s._viewUpdateFlag=-1,s._projectionUpdateFlag=-1,s._toBeDisposed=new Array(256),s._activeRequests=new Array,s._pendingData=new Array,s._isDisposed=!1,s.dispatchAllSubMeshesOfActiveMeshes=!1,s._activeMeshes=new SmartArray(256),s._processedMaterials=new SmartArray(256),s._renderTargets=new SmartArrayNoDuplicate(256),s._activeParticleSystems=new SmartArray(256),s._activeSkeletons=new SmartArrayNoDuplicate(32),s._softwareSkinnedMeshes=new SmartArrayNoDuplicate(32),s._activeAnimatables=new Array,s._transformMatrix=Matrix.Zero(),s.requireLightSorting=!1,s._components=[],s._serializableComponents=[],s._transientComponents=[],s._beforeCameraUpdateStage=Stage.Create(),s._beforeClearStage=Stage.Create(),s._beforeRenderTargetClearStage=Stage.Create(),s._gatherRenderTargetsStage=Stage.Create(),s._gatherActiveCameraRenderTargetsStage=Stage.Create(),s._isReadyForMeshStage=Stage.Create(),s._beforeEvaluateActiveMeshStage=Stage.Create(),s._evaluateSubMeshStage=Stage.Create(),s._preActiveMeshStage=Stage.Create(),s._cameraDrawRenderTargetStage=Stage.Create(),s._beforeCameraDrawStage=Stage.Create(),s._beforeRenderTargetDrawStage=Stage.Create(),s._beforeRenderingGroupDrawStage=Stage.Create(),s._beforeRenderingMeshStage=Stage.Create(),s._afterRenderingMeshStage=Stage.Create(),s._afterRenderingGroupDrawStage=Stage.Create(),s._afterCameraDrawStage=Stage.Create(),s._afterRenderTargetDrawStage=Stage.Create(),s._afterRenderStage=Stage.Create(),s._pointerMoveStage=Stage.Create(),s._pointerDownStage=Stage.Create(),s._pointerUpStage=Stage.Create(),s.geometriesByUniqueId=null,s._defaultMeshCandidates={data:[],length:0},s._defaultSubMeshCandidates={data:[],length:0},s._preventFreeActiveMeshesAndRenderingGroups=!1,s._activeMeshesFrozen=!1,s._skipEvaluateActiveMeshesCompletely=!1,s._allowPostProcessClearColor=!0,s.getDeterministicFrameTime=function(){return s._engine.getTimeStep()},s._blockMaterialDirtyMechanism=!1,s._perfCollector=null,s.onComputePressureChanged=new Observable;var c=__assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},o);return s._engine=e||EngineStore.LastCreatedEngine,c.virtual?s._engine._virtualScenes.push(s):(EngineStore._LastCreatedScene=s,s._engine.scenes.push(s)),s._uid=null,s._renderingManager=new RenderingManager(s),PostProcessManager&&(s.postProcessManager=new PostProcessManager(s)),IsWindowObjectExist()&&s.attachControl(),s._createUbo(),ImageProcessingConfiguration&&(s._imageProcessingConfiguration=new ImageProcessingConfiguration),s.setDefaultCandidateProviders(),c.useGeometryUniqueIdsMap&&(s.geometriesByUniqueId={}),s.useMaterialMeshMap=c.useMaterialMeshMap,s.useClonedMeshMap=c.useClonedMeshMap,(!o||!o.virtual)&&s._engine.onNewSceneAddedObservable.notifyObservers(s),ComputePressureObserverWrapper.IsAvailable&&(s._computePressureObserver=new ComputePressureObserverWrapper(function(d){s.onComputePressureChanged.notifyObservers(d)},{cpuUtilizationThresholds:[.25,.5,.75,.9],cpuSpeedThresholds:[.5]}),s._computePressureObserver.observe()),s}return i.DefaultMaterialFactory=function(e){throw _WarnImport("StandardMaterial")},i.CollisionCoordinatorFactory=function(){throw _WarnImport("DefaultCollisionCoordinator")},Object.defineProperty(i.prototype,"environmentTexture",{get:function(){return this._environmentTexture},set:function(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"environmentIntensity",{get:function(){return this._environmentIntensity},set:function(e){this._environmentIntensity!==e&&(this._environmentIntensity=e,this.markAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"forceWireframe",{get:function(){return this._forceWireframe},set:function(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"skipFrustumClipping",{get:function(){return this._skipFrustumClipping},set:function(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"forcePointsCloud",{get:function(){return this._forcePointsCloud},set:function(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"beforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"afterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"beforeCameraRender",{set:function(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"afterCameraRender",{set:function(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"unTranslatedPointer",{get:function(){return this._inputManager.unTranslatedPointer},enumerable:!1,configurable:!0}),Object.defineProperty(i,"DragMovementThreshold",{get:function(){return InputManager.DragMovementThreshold},set:function(e){InputManager.DragMovementThreshold=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"LongPressDelay",{get:function(){return InputManager.LongPressDelay},set:function(e){InputManager.LongPressDelay=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"DoubleClickDelay",{get:function(){return InputManager.DoubleClickDelay},set:function(e){InputManager.DoubleClickDelay=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"ExclusiveDoubleClickMode",{get:function(){return InputManager.ExclusiveDoubleClickMode},set:function(e){InputManager.ExclusiveDoubleClickMode=e},enumerable:!1,configurable:!0}),i.prototype.bindEyePosition=function(e,o,s){var c;o===void 0&&(o="vEyePosition"),s===void 0&&(s=!1);var d=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:(c=this.activeCamera.globalPosition)!==null&&c!==void 0?c:this.activeCamera.devicePosition,_=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return TmpVectors.Vector4[0].set(d.x,d.y,d.z,_?-1:1),e&&(s?e.setFloat3(o,TmpVectors.Vector4[0].x,TmpVectors.Vector4[0].y,TmpVectors.Vector4[0].z):e.setVector4(o,TmpVectors.Vector4[0])),TmpVectors.Vector4[0]},i.prototype.finalizeSceneUbo=function(){var e=this.getSceneUniformBuffer(),o=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",o.x,o.y,o.z,o.w),e.update(),e},Object.defineProperty(i.prototype,"useRightHandedSystem",{get:function(){return this._useRightHandedSystem},set:function(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))},enumerable:!1,configurable:!0}),i.prototype.setStepId=function(e){this._currentStepId=e},i.prototype.getStepId=function(){return this._currentStepId},i.prototype.getInternalStep=function(){return this._currentInternalStep},Object.defineProperty(i.prototype,"fogEnabled",{get:function(){return this._fogEnabled},set:function(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"fogMode",{get:function(){return this._fogMode},set:function(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"prePass",{get:function(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadowsEnabled",{get:function(){return this._shadowsEnabled},set:function(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lightsEnabled",{get:function(){return this._lightsEnabled},set:function(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"activeCamera",{get:function(){return this._activeCamera},set:function(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"defaultMaterial",{get:function(){return this._defaultMaterial||(this._defaultMaterial=i.DefaultMaterialFactory(this)),this._defaultMaterial},set:function(e){this._defaultMaterial=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"texturesEnabled",{get:function(){return this._texturesEnabled},set:function(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"skeletonsEnabled",{get:function(){return this._skeletonsEnabled},set:function(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"collisionCoordinator",{get:function(){return this._collisionCoordinator||(this._collisionCoordinator=i.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"frustumPlanes",{get:function(){return this._frustumPlanes},enumerable:!1,configurable:!0}),i.prototype._registerTransientComponents=function(){if(this._transientComponents.length>0){for(var e=0,o=this._transientComponents;e<o.length;e++){var s=o[e];s.register()}this._transientComponents=[]}},i.prototype._addComponent=function(e){this._components.push(e),this._transientComponents.push(e);var o=e;o.addFromContainer&&o.serialize&&this._serializableComponents.push(o)},i.prototype._getComponent=function(e){for(var o=0,s=this._components;o<s.length;o++){var c=s[o];if(c.name===e)return c}return null},i.prototype.getClassName=function(){return"Scene"},i.prototype._getDefaultMeshCandidates=function(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates},i.prototype._getDefaultSubMeshCandidates=function(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates},i.prototype.setDefaultCandidateProviders=function(){this.getActiveMeshCandidates=this._getDefaultMeshCandidates.bind(this),this.getActiveSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getIntersectingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getCollidingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this)},Object.defineProperty(i.prototype,"meshUnderPointer",{get:function(){return this._inputManager.meshUnderPointer},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"pointerX",{get:function(){return this._inputManager.pointerX},set:function(e){this._inputManager.pointerX=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"pointerY",{get:function(){return this._inputManager.pointerY},set:function(e){this._inputManager.pointerY=e},enumerable:!1,configurable:!0}),i.prototype.getCachedMaterial=function(){return this._cachedMaterial},i.prototype.getCachedEffect=function(){return this._cachedEffect},i.prototype.getCachedVisibility=function(){return this._cachedVisibility},i.prototype.isCachedMaterialInvalid=function(e,o,s){return s===void 0&&(s=1),this._cachedEffect!==o||this._cachedMaterial!==e||this._cachedVisibility!==s},i.prototype.getEngine=function(){return this._engine},i.prototype.getTotalVertices=function(){return this._totalVertices.current},Object.defineProperty(i.prototype,"totalVerticesPerfCounter",{get:function(){return this._totalVertices},enumerable:!1,configurable:!0}),i.prototype.getActiveIndices=function(){return this._activeIndices.current},Object.defineProperty(i.prototype,"totalActiveIndicesPerfCounter",{get:function(){return this._activeIndices},enumerable:!1,configurable:!0}),i.prototype.getActiveParticles=function(){return this._activeParticles.current},Object.defineProperty(i.prototype,"activeParticlesPerfCounter",{get:function(){return this._activeParticles},enumerable:!1,configurable:!0}),i.prototype.getActiveBones=function(){return this._activeBones.current},Object.defineProperty(i.prototype,"activeBonesPerfCounter",{get:function(){return this._activeBones},enumerable:!1,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.getAnimationRatio=function(){return this._animationRatio!==void 0?this._animationRatio:1},i.prototype.getRenderId=function(){return this._renderId},i.prototype.getFrameId=function(){return this._frameId},i.prototype.incrementRenderId=function(){this._renderId++},i.prototype._createUbo=function(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())},i.prototype.simulatePointerMove=function(e,o){return this._inputManager.simulatePointerMove(e,o),this},i.prototype.simulatePointerDown=function(e,o){return this._inputManager.simulatePointerDown(e,o),this},i.prototype.simulatePointerUp=function(e,o,s){return this._inputManager.simulatePointerUp(e,o,s),this},i.prototype.isPointerCaptured=function(e){return e===void 0&&(e=0),this._inputManager.isPointerCaptured(e)},i.prototype.attachControl=function(e,o,s){e===void 0&&(e=!0),o===void 0&&(o=!0),s===void 0&&(s=!0),this._inputManager.attachControl(e,o,s)},i.prototype.detachControl=function(){this._inputManager.detachControl()},i.prototype.isReady=function(e){if(e===void 0&&(e=!0),this._isDisposed)return!1;var o,s=this.getEngine();if(!s.areAllEffectsReady()||this._pendingData.length>0)return!1;for(e&&(this._processedMaterials.reset(),this._renderTargets.reset()),o=0;o<this.meshes.length;o++){var c=this.meshes[o];if(!!c.isEnabled()&&!(!c.subMeshes||c.subMeshes.length===0)){if(!c.isReady(!0))return!1;for(var d=c.hasThinInstances||c.getClassName()==="InstancedMesh"||c.getClassName()==="InstancedLinesMesh"||s.getCaps().instancedArrays&&c.instances.length>0,_=0,b=this._isReadyForMeshStage;_<b.length;_++){var k=b[_];if(!k.action(c,d))return!1}if(!!e){var j=c.material||this.defaultMaterial;if(j)if(j._storeEffectOnSubMeshes)for(var $=0,_e=c.subMeshes;$<_e.length;$++){var et=_e[$],tt=et.getMaterial();tt&&tt.hasRenderTargetTextures&&tt.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(tt)===-1&&(this._processedMaterials.push(tt),this._renderTargets.concatWithNoDuplicate(tt.getRenderTargetTextures()))}else j.hasRenderTargetTextures&&j.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(j)===-1&&(this._processedMaterials.push(j),this._renderTargets.concatWithNoDuplicate(j.getRenderTargetTextures()))}}}if(e)for(o=0;o<this._renderTargets.length;++o){var rt=this._renderTargets.data[o];if(!rt.isReadyForRendering())return!1}for(o=0;o<this.geometries.length;o++){var it=this.geometries[o];if(it.delayLoadState===2)return!1}if(this.activeCameras&&this.activeCameras.length>0)for(var nt=0,ot=this.activeCameras;nt<ot.length;nt++){var at=ot[nt];if(!at.isReady(!0))return!1}else if(this.activeCamera&&!this.activeCamera.isReady(!0))return!1;for(var st=0,ut=this.particleSystems;st<ut.length;st++){var ft=ut[st];if(!ft.isReady())return!1}return!0},i.prototype.resetCachedMaterial=function(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null},i.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},i.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},i.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},i.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},i.prototype._executeOnceBeforeRender=function(e){var o=this,s=function(){e(),setTimeout(function(){o.unregisterBeforeRender(s)})};this.registerBeforeRender(s)},i.prototype.executeOnceBeforeRender=function(e,o){var s=this;o!==void 0?setTimeout(function(){s._executeOnceBeforeRender(e)},o):this._executeOnceBeforeRender(e)},i.prototype._addPendingData=function(e){this._pendingData.push(e)},i.prototype._removePendingData=function(e){var o=this.isLoading,s=this._pendingData.indexOf(e);s!==-1&&this._pendingData.splice(s,1),o&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)},i.prototype.getWaitingItemsCount=function(){return this._pendingData.length},Object.defineProperty(i.prototype,"isLoading",{get:function(){return this._pendingData.length>0},enumerable:!1,configurable:!0}),i.prototype.executeWhenReady=function(e,o){var s=this;o===void 0&&(o=!1),this.onReadyObservable.add(e),this._executeWhenReadyTimeoutId===-1&&(this._executeWhenReadyTimeoutId=setTimeout(function(){s._checkIsReady(o)},150))},i.prototype.whenReadyAsync=function(e){var o=this;return e===void 0&&(e=!1),new Promise(function(s){o.executeWhenReady(function(){s()},e)})},i.prototype._checkIsReady=function(e){var o=this;if(e===void 0&&(e=!1),this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=-1;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=-1;return}this._executeWhenReadyTimeoutId=setTimeout(function(){o._checkIsReady(e)},150)},Object.defineProperty(i.prototype,"animatables",{get:function(){return this._activeAnimatables},enumerable:!1,configurable:!0}),i.prototype.resetLastAnimationTimeFrame=function(){this._animationTimeLast=PrecisionDate.Now},i.prototype.getViewMatrix=function(){return this._viewMatrix},i.prototype.getProjectionMatrix=function(){return this._projectionMatrix},i.prototype.getTransformMatrix=function(){return this._transformMatrix},i.prototype.setTransformMatrix=function(e,o,s,c){this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===o.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=o.updateFlag,this._viewMatrix=e,this._projectionMatrix=o,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Frustum.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(s,c):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))},i.prototype.getSceneUniformBuffer=function(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo},i.prototype.createSceneUniformBuffer=function(e){var o=new UniformBuffer(this._engine,void 0,!1,e!=null?e:"scene");return o.addUniform("viewProjection",16),o.addUniform("view",16),o.addUniform("projection",16),o.addUniform("vEyePosition",4),o},i.prototype.setSceneUniformBuffer=function(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1},i.prototype.getUniqueId=function(){return UniqueIdGenerator.UniqueId},i.prototype.addMesh=function(e,o){var s=this;o===void 0&&(o=!1),!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),o&&e.getChildMeshes().forEach(function(c){s.addMesh(c)}))},i.prototype.removeMesh=function(e,o){var s=this;o===void 0&&(o=!1);var c=this.meshes.indexOf(e);return c!==-1&&(this.meshes[c]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),o&&e.getChildMeshes().forEach(function(d){s.removeMesh(d)}),c},i.prototype.addTransformNode=function(e){this._blockEntityCollection||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))},i.prototype.removeTransformNode=function(e){var o=e._indexInSceneTransformNodesArray;if(o!==-1){if(o!==this.transformNodes.length-1){var s=this.transformNodes[this.transformNodes.length-1];this.transformNodes[o]=s,s._indexInSceneTransformNodesArray=o}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),o},i.prototype.removeSkeleton=function(e){var o=this.skeletons.indexOf(e);return o!==-1&&(this.skeletons.splice(o,1),this.onSkeletonRemovedObservable.notifyObservers(e)),o},i.prototype.removeMorphTargetManager=function(e){var o=this.morphTargetManagers.indexOf(e);return o!==-1&&this.morphTargetManagers.splice(o,1),o},i.prototype.removeLight=function(e){var o=this.lights.indexOf(e);if(o!==-1){for(var s=0,c=this.meshes;s<c.length;s++){var d=c[s];d._removeLightSource(e,!1)}this.lights.splice(o,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),o},i.prototype.removeCamera=function(e){var o=this.cameras.indexOf(e);if(o!==-1&&(this.cameras.splice(o,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){var s=this.activeCameras.indexOf(e);s!==-1&&this.activeCameras.splice(s,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),o},i.prototype.removeParticleSystem=function(e){var o=this.particleSystems.indexOf(e);return o!==-1&&this.particleSystems.splice(o,1),o},i.prototype.removeAnimation=function(e){var o=this.animations.indexOf(e);return o!==-1&&this.animations.splice(o,1),o},i.prototype.stopAnimation=function(e,o,s){},i.prototype.removeAnimationGroup=function(e){var o=this.animationGroups.indexOf(e);return o!==-1&&this.animationGroups.splice(o,1),o},i.prototype.removeMultiMaterial=function(e){var o=this.multiMaterials.indexOf(e);return o!==-1&&this.multiMaterials.splice(o,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),o},i.prototype.removeMaterial=function(e){var o=e._indexInSceneMaterialArray;if(o!==-1&&o<this.materials.length){if(o!==this.materials.length-1){var s=this.materials[this.materials.length-1];this.materials[o]=s,s._indexInSceneMaterialArray=o}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),o},i.prototype.removeActionManager=function(e){var o=this.actionManagers.indexOf(e);return o!==-1&&this.actionManagers.splice(o,1),o},i.prototype.removeTexture=function(e){var o=this.textures.indexOf(e);return o!==-1&&this.textures.splice(o,1),this.onTextureRemovedObservable.notifyObservers(e),o},i.prototype.addLight=function(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(var o=0,s=this.meshes;o<s.length;o++){var c=s[o];c.lightSources.indexOf(e)===-1&&(c.lightSources.push(e),c._resyncLightSources())}this.onNewLightAddedObservable.notifyObservers(e)}},i.prototype.sortLightsByPriority=function(){this.requireLightSorting&&this.lights.sort(LightConstants.CompareLightsPriority)},i.prototype.addCamera=function(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())},i.prototype.addSkeleton=function(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))},i.prototype.addParticleSystem=function(e){this._blockEntityCollection||this.particleSystems.push(e)},i.prototype.addAnimation=function(e){this._blockEntityCollection||this.animations.push(e)},i.prototype.addAnimationGroup=function(e){this._blockEntityCollection||this.animationGroups.push(e)},i.prototype.addMultiMaterial=function(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))},i.prototype.addMaterial=function(e){this._blockEntityCollection||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))},i.prototype.addMorphTargetManager=function(e){this._blockEntityCollection||this.morphTargetManagers.push(e)},i.prototype.addGeometry=function(e){this._blockEntityCollection||(this.geometriesByUniqueId&&(this.geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))},i.prototype.addActionManager=function(e){this.actionManagers.push(e)},i.prototype.addTexture=function(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))},i.prototype.switchActiveCamera=function(e,o){o===void 0&&(o=!0);var s=this._engine.getInputElement();!s||(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,o&&e.attachControl())},i.prototype.setActiveCameraById=function(e){var o=this.getCameraById(e);return o?(this.activeCamera=o,o):null},i.prototype.setActiveCameraByName=function(e){var o=this.getCameraByName(e);return o?(this.activeCamera=o,o):null},i.prototype.getAnimationGroupByName=function(e){for(var o=0;o<this.animationGroups.length;o++)if(this.animationGroups[o].name===e)return this.animationGroups[o];return null},i.prototype.getMaterialByUniqueID=function(e){for(var o=0;o<this.materials.length;o++)if(this.materials[o].uniqueId===e)return this.materials[o];return null},i.prototype.getMaterialById=function(e){for(var o=0;o<this.materials.length;o++)if(this.materials[o].id===e)return this.materials[o];return null},i.prototype.getLastMaterialById=function(e){for(var o=this.materials.length-1;o>=0;o--)if(this.materials[o].id===e)return this.materials[o];return null},i.prototype.getMaterialByName=function(e){for(var o=0;o<this.materials.length;o++)if(this.materials[o].name===e)return this.materials[o];return null},i.prototype.getTextureByUniqueId=function(e){for(var o=0;o<this.textures.length;o++)if(this.textures[o].uniqueId===e)return this.textures[o];return null},i.prototype.getTextureByName=function(e){for(var o=0;o<this.textures.length;o++)if(this.textures[o].name===e)return this.textures[o];return null},i.prototype.getCameraById=function(e){for(var o=0;o<this.cameras.length;o++)if(this.cameras[o].id===e)return this.cameras[o];return null},i.prototype.getCameraByUniqueId=function(e){for(var o=0;o<this.cameras.length;o++)if(this.cameras[o].uniqueId===e)return this.cameras[o];return null},i.prototype.getCameraByName=function(e){for(var o=0;o<this.cameras.length;o++)if(this.cameras[o].name===e)return this.cameras[o];return null},i.prototype.getBoneById=function(e){for(var o=0;o<this.skeletons.length;o++)for(var s=this.skeletons[o],c=0;c<s.bones.length;c++)if(s.bones[c].id===e)return s.bones[c];return null},i.prototype.getBoneByName=function(e){for(var o=0;o<this.skeletons.length;o++)for(var s=this.skeletons[o],c=0;c<s.bones.length;c++)if(s.bones[c].name===e)return s.bones[c];return null},i.prototype.getLightByName=function(e){for(var o=0;o<this.lights.length;o++)if(this.lights[o].name===e)return this.lights[o];return null},i.prototype.getLightById=function(e){for(var o=0;o<this.lights.length;o++)if(this.lights[o].id===e)return this.lights[o];return null},i.prototype.getLightByUniqueId=function(e){for(var o=0;o<this.lights.length;o++)if(this.lights[o].uniqueId===e)return this.lights[o];return null},i.prototype.getParticleSystemById=function(e){for(var o=0;o<this.particleSystems.length;o++)if(this.particleSystems[o].id===e)return this.particleSystems[o];return null},i.prototype.getGeometryById=function(e){for(var o=0;o<this.geometries.length;o++)if(this.geometries[o].id===e)return this.geometries[o];return null},i.prototype._getGeometryByUniqueId=function(e){if(this.geometriesByUniqueId){var o=this.geometriesByUniqueId[e];if(o!==void 0)return this.geometries[o]}else for(var s=0;s<this.geometries.length;s++)if(this.geometries[s].uniqueId===e)return this.geometries[s];return null},i.prototype.pushGeometry=function(e,o){return!o&&this._getGeometryByUniqueId(e.uniqueId)?!1:(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)},i.prototype.removeGeometry=function(e){var o;if(this.geometriesByUniqueId){if(o=this.geometriesByUniqueId[e.uniqueId],o===void 0)return!1}else if(o=this.geometries.indexOf(e),o<0)return!1;if(o!==this.geometries.length-1){var s=this.geometries[this.geometries.length-1];s&&(this.geometries[o]=s,this.geometriesByUniqueId&&(this.geometriesByUniqueId[s.uniqueId]=o,this.geometriesByUniqueId[e.uniqueId]=void 0))}return this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0},i.prototype.getGeometries=function(){return this.geometries},i.prototype.getMeshById=function(e){for(var o=0;o<this.meshes.length;o++)if(this.meshes[o].id===e)return this.meshes[o];return null},i.prototype.getMeshesById=function(e){return this.meshes.filter(function(o){return o.id===e})},i.prototype.getTransformNodeById=function(e){for(var o=0;o<this.transformNodes.length;o++)if(this.transformNodes[o].id===e)return this.transformNodes[o];return null},i.prototype.getTransformNodeByUniqueId=function(e){for(var o=0;o<this.transformNodes.length;o++)if(this.transformNodes[o].uniqueId===e)return this.transformNodes[o];return null},i.prototype.getTransformNodesById=function(e){return this.transformNodes.filter(function(o){return o.id===e})},i.prototype.getMeshByUniqueId=function(e){for(var o=0;o<this.meshes.length;o++)if(this.meshes[o].uniqueId===e)return this.meshes[o];return null},i.prototype.getLastMeshById=function(e){for(var o=this.meshes.length-1;o>=0;o--)if(this.meshes[o].id===e)return this.meshes[o];return null},i.prototype.getLastEntryById=function(e){var o;for(o=this.meshes.length-1;o>=0;o--)if(this.meshes[o].id===e)return this.meshes[o];for(o=this.transformNodes.length-1;o>=0;o--)if(this.transformNodes[o].id===e)return this.transformNodes[o];for(o=this.cameras.length-1;o>=0;o--)if(this.cameras[o].id===e)return this.cameras[o];for(o=this.lights.length-1;o>=0;o--)if(this.lights[o].id===e)return this.lights[o];return null},i.prototype.getNodeById=function(e){var o=this.getMeshById(e);if(o)return o;var s=this.getTransformNodeById(e);if(s)return s;var c=this.getLightById(e);if(c)return c;var d=this.getCameraById(e);if(d)return d;var _=this.getBoneById(e);return _||null},i.prototype.getNodeByName=function(e){var o=this.getMeshByName(e);if(o)return o;var s=this.getTransformNodeByName(e);if(s)return s;var c=this.getLightByName(e);if(c)return c;var d=this.getCameraByName(e);if(d)return d;var _=this.getBoneByName(e);return _||null},i.prototype.getMeshByName=function(e){for(var o=0;o<this.meshes.length;o++)if(this.meshes[o].name===e)return this.meshes[o];return null},i.prototype.getTransformNodeByName=function(e){for(var o=0;o<this.transformNodes.length;o++)if(this.transformNodes[o].name===e)return this.transformNodes[o];return null},i.prototype.getLastSkeletonById=function(e){for(var o=this.skeletons.length-1;o>=0;o--)if(this.skeletons[o].id===e)return this.skeletons[o];return null},i.prototype.getSkeletonByUniqueId=function(e){for(var o=0;o<this.skeletons.length;o++)if(this.skeletons[o].uniqueId===e)return this.skeletons[o];return null},i.prototype.getSkeletonById=function(e){for(var o=0;o<this.skeletons.length;o++)if(this.skeletons[o].id===e)return this.skeletons[o];return null},i.prototype.getSkeletonByName=function(e){for(var o=0;o<this.skeletons.length;o++)if(this.skeletons[o].name===e)return this.skeletons[o];return null},i.prototype.getMorphTargetManagerById=function(e){for(var o=0;o<this.morphTargetManagers.length;o++)if(this.morphTargetManagers[o].uniqueId===e)return this.morphTargetManagers[o];return null},i.prototype.getMorphTargetById=function(e){for(var o=0;o<this.morphTargetManagers.length;++o)for(var s=this.morphTargetManagers[o],c=0;c<s.numTargets;++c){var d=s.getTarget(c);if(d.id===e)return d}return null},i.prototype.getMorphTargetByName=function(e){for(var o=0;o<this.morphTargetManagers.length;++o)for(var s=this.morphTargetManagers[o],c=0;c<s.numTargets;++c){var d=s.getTarget(c);if(d.name===e)return d}return null},i.prototype.getPostProcessByName=function(e){for(var o=0;o<this.postProcesses.length;++o){var s=this.postProcesses[o];if(s.name===e)return s}return null},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},Object.defineProperty(i.prototype,"uid",{get:function(){return this._uid||(this._uid=Tools.RandomId()),this._uid},enumerable:!1,configurable:!0}),i.prototype.addExternalData=function(e,o){return this._externalData||(this._externalData=new StringDictionary),this._externalData.add(e,o)},i.prototype.getExternalData=function(e){return this._externalData?this._externalData.get(e):null},i.prototype.getOrAddExternalDataWithFactory=function(e,o){return this._externalData||(this._externalData=new StringDictionary),this._externalData.getOrAddWithFactory(e,o)},i.prototype.removeExternalData=function(e){return this._externalData.remove(e)},i.prototype._evaluateSubMesh=function(e,o,s){if(s.hasInstances||s.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||o.alwaysSelectAsActiveMesh||o.subMeshes.length===1||e.isInFrustum(this._frustumPlanes)){for(var c=0,d=this._evaluateSubMeshStage;c<d.length;c++){var _=d[c];_.action(o,e)}var b=e.getMaterial();b!=null&&(b.hasRenderTargetTextures&&b.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(b)===-1&&(this._processedMaterials.push(b),this._renderTargets.concatWithNoDuplicate(b.getRenderTargetTextures())),this._renderingManager.dispatch(e,o,b))}},i.prototype.freeProcessedMaterials=function(){this._processedMaterials.dispose()},Object.defineProperty(i.prototype,"blockfreeActiveMeshesAndRenderingGroups",{get:function(){return this._preventFreeActiveMeshesAndRenderingGroups},set:function(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)},enumerable:!1,configurable:!0}),i.prototype.freeActiveMeshes=function(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(var e=0;e<this.activeCameras.length;e++){var o=this.activeCameras[e];o&&o._activeMeshes&&o._activeMeshes.dispose()}},i.prototype.freeRenderingGroups=function(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(var e=0;e<this.textures.length;e++){var o=this.textures[e];o&&o.renderList&&o.freeRenderingGroups()}},i.prototype._isInIntermediateRendering=function(){return this._intermediateRendering},i.prototype.freezeActiveMeshes=function(e,o,s,c){var d=this;return e===void 0&&(e=!1),c===void 0&&(c=!0),this.executeWhenReady(function(){if(!d.activeCamera){s&&s("No active camera found");return}if(d._frustumPlanes||d.setTransformMatrix(d.activeCamera.getViewMatrix(),d.activeCamera.getProjectionMatrix()),d._evaluateActiveMeshes(),d._activeMeshesFrozen=!0,d._skipEvaluateActiveMeshesCompletely=e,c)for(var _=0;_<d._activeMeshes.length;_++)d._activeMeshes.data[_]._freeze();o&&o()}),this},i.prototype.unfreezeActiveMeshes=function(){for(var e=0;e<this.meshes.length;e++){var o=this.meshes[e];o._internalAbstractMeshDataInfo&&(o._internalAbstractMeshDataInfo._isActive=!1)}for(var e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this},i.prototype._evaluateActiveMeshes=function(){var e;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((e=this.activeCamera)===null||e===void 0||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely)for(var o=this._activeMeshes.length,s=0;s<o;s++){var c=this._activeMeshes.data[s];c.computeWorldMatrix()}if(this._activeParticleSystems)for(var d=this._activeParticleSystems.length,s=0;s<d;s++)this._activeParticleSystems.data[s].animate();return}if(!!this.activeCamera){this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();for(var _=0,b=this._beforeEvaluateActiveMeshStage;_<b.length;_++){var k=b[_];k.action()}for(var j=this.getActiveMeshCandidates(),$=j.length,s=0;s<$;s++){var c=j.data[s];if(c._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,!c.isBlocked&&(this._totalVertices.addCount(c.getTotalVertices(),!1),!(!c.isReady()||!c.isEnabled()||c.scaling.lengthSquared()===0))){c.computeWorldMatrix(),c.actionManager&&c.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(c);var _e=this.customLODSelector?this.customLODSelector(c,this.activeCamera):c.getLOD(this.activeCamera);if(c._internalAbstractMeshDataInfo._currentLOD=_e,c._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,_e!=null&&(_e!==c&&_e.billboardMode!==0&&_e.computeWorldMatrix(),c._preActivate(),c.isVisible&&c.visibility>0&&(c.layerMask&this.activeCamera.layerMask)!==0&&(this._skipFrustumClipping||c.alwaysSelectAsActiveMesh||c.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(c),this.activeCamera._activeMeshes.push(c),_e!==c&&_e._activate(this._renderId,!1);for(var et=0,tt=this._preActiveMeshStage;et<tt.length;et++){var k=tt[et];k.action(c)}c._activate(this._renderId,!1)&&(c.isAnInstance?c._internalAbstractMeshDataInfo._actAsRegularMesh&&(_e=c):_e._internalAbstractMeshDataInfo._onlyForInstances=!1,_e._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(c,_e)),c._postActivate()}}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var rt=0;rt<this.particleSystems.length;rt++){var it=this.particleSystems[rt];if(!(!it.isStarted()||!it.emitter)){var nt=it.emitter;(!nt.position||nt.isEnabled())&&(this._activeParticleSystems.push(it),it.animate(),this._renderingManager.dispatchParticles(it))}}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}},i.prototype._activeMesh=function(e,o){if(this._skeletonsEnabled&&o.skeleton!==null&&o.skeleton!==void 0&&(this._activeSkeletons.pushNoDuplicate(o.skeleton)&&o.skeleton.prepare(),o.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(o)),o!=null&&o.subMeshes!==void 0&&o.subMeshes!==null&&o.subMeshes.length>0)for(var s=this.getActiveSubMeshCandidates(o),c=s.length,d=0;d<c;d++){var _=s.data[d];this._evaluateSubMesh(_,o,e)}},i.prototype.updateTransformMatrix=function(e){!this.activeCamera||this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))},i.prototype._bindFrameBuffer=function(e,o){o===void 0&&(o=!0),e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),o&&this._clearFrameBuffer(e)},i.prototype._clearFrameBuffer=function(e){if(!(e&&e._multiviewTexture))if(e&&e.outputRenderTarget){var o=e.outputRenderTarget;o.onClearObservable.hasObservers()?o.onClearObservable.notifyObservers(this._engine):o.skipInitialClear||(this._engine.clear(o.clearColor||this.clearColor,!o._cleared,!0,!0),o._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())},i.prototype._renderForCamera=function(e,o,s){var c,d,_;if(s===void 0&&(s=!0),!(e&&e._skipRendering)){var b=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");b.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&s&&this._bindFrameBuffer(this._activeCamera);var k=this.getEngine().getCaps().multiview&&e.outputRenderTarget&&e.outputRenderTarget.getViewCount()>1;k?this.setTransformMatrix(e._rigCameras[0].getViewMatrix(),e._rigCameras[0].getProjectionMatrix(),e._rigCameras[1].getViewMatrix(),e._rigCameras[1].getProjectionMatrix()):this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(var j=0;j<this._softwareSkinnedMeshes.length;j++){var $=this._softwareSkinnedMeshes.data[j];$.applySkeleton($.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),o&&o.customRenderTargets&&o.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(o.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(var _e=0,et=this._gatherActiveCameraRenderTargetsStage;_e<et.length;_e++){var tt=et[_e];tt.action(this._renderTargets)}var rt=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var it=0;it<this._renderTargets.length;it++){var nt=this._renderTargets.data[it];if(nt._shouldRender()){this._renderId++;var ot=nt.activeCamera&&nt.activeCamera!==this.activeCamera;nt.render(ot,this.dumpNextRenderTargets),rt=!0}}Tools.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(var at=0,st=this._cameraDrawRenderTargetStage;at<st.length;at++){var tt=st[at];rt=tt.action(this.activeCamera)||rt}this._intermediateRendering=!1}this._engine.currentRenderPassId=(_=(d=(c=e.outputRenderTarget)===null||c===void 0?void 0:c.renderPassId)!==null&&d!==void 0?d:e.renderPassId)!==null&&_!==void 0?_:0,rt&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(var ut=0,ft=this._beforeCameraDrawStage;ut<ft.length;ut++){var tt=ft[ut];tt.action(this.activeCamera)}this.onBeforeDrawPhaseObservable.notifyObservers(this),b.snapshotRendering&&b.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(var lt=0,ht=this._afterCameraDrawStage;lt<ht.length;lt++){var tt=ht[lt];tt.action(this.activeCamera)}if(this.postProcessManager&&!e._multiviewTexture){var pt=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,pt)}this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}},i.prototype._processSubCameras=function(e,o){if(o===void 0&&(o=!0),e.cameraRigMode===0||e.outputRenderTarget&&e.outputRenderTarget.getViewCount()>1&&this.getEngine().getCaps().multiview){this._renderForCamera(e,void 0,o),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(var s=0;s<e._rigCameras.length;s++)this._renderForCamera(e._rigCameras[s],e)}this._activeCamera=e,this.setTransformMatrix(this._activeCamera.getViewMatrix(),this._activeCamera.getProjectionMatrix()),this.onAfterRenderCameraObservable.notifyObservers(e)},i.prototype._checkIntersections=function(){for(var e=0;e<this._meshesForIntersections.length;e++){var o=this._meshesForIntersections.data[e];if(!!o.actionManager)for(var s=0;o.actionManager&&s<o.actionManager.actions.length;s++){var c=o.actionManager.actions[s];if(c.trigger===12||c.trigger===13){var d=c.getTriggerParameter(),_=d.mesh?d.mesh:d,b=_.intersectsMesh(o,d.usePreciseIntersection),k=o._intersectionsInProgress.indexOf(_);b&&k===-1?c.trigger===12?(c._executeCurrent(ActionEvent.CreateNew(o,void 0,_)),o._intersectionsInProgress.push(_)):c.trigger===13&&o._intersectionsInProgress.push(_):!b&&k>-1&&(c.trigger===13&&c._executeCurrent(ActionEvent.CreateNew(o,void 0,_)),(!o.actionManager.hasSpecificTrigger(13,function(j){var $=j.mesh?j.mesh:j;return _===$})||c.trigger===13)&&o._intersectionsInProgress.splice(k,1))}}}},i.prototype._advancePhysicsEngineStep=function(e){},i.prototype._animate=function(){},i.prototype.animate=function(){if(this._engine.isDeterministicLockStep()){var e=Math.max(i.MinDeltaTime,Math.min(this._engine.getDeltaTime(),i.MaxDeltaTime))+this._timeAccumulator,o=this._engine.getTimeStep(),s=1e3/o/1e3,c=0,d=this._engine.getLockstepMaxSteps(),_=Math.floor(e/o);for(_=Math.min(_,d);e>0&&c<_;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=o*s,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(o),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,c++,e-=o;this._timeAccumulator=e<0?0:e}else{var e=this.useConstantAnimationDeltaTime?16:Math.max(i.MinDeltaTime,Math.min(this._engine.getDeltaTime(),i.MaxDeltaTime));this._animationRatio=e*(60/1e3),this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}},i.prototype._clear=function(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)},i.prototype.checkCameraRenderTarget=function(e){var o;if((e==null?void 0:e.outputRenderTarget)&&!(e!=null&&e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),!((o=e==null?void 0:e.rigCameras)===null||o===void 0)&&o.length)for(var s=0;s<e.rigCameras.length;++s){var c=e.rigCameras[s].outputRenderTarget;c&&(c._cleared=!1)}},i.prototype.resetDrawCache=function(){if(!!this.meshes)for(var e=0,o=this.meshes;e<o.length;e++){var s=o[e];s.resetDrawCache()}},i.prototype.render=function(e,o){var s,c,d;if(e===void 0&&(e=!0),o===void 0&&(o=!1),!this.isDisposed){this.onReadyObservable.hasObservers()&&this._executeWhenReadyTimeoutId===-1&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this.checkCameraRenderTarget(this.activeCamera),!((s=this.activeCameras)===null||s===void 0)&&s.length&&this.activeCameras.forEach(this.checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),o||this.animate();for(var _=0,b=this._beforeCameraUpdateStage;_<b.length;_++){var k=b[_];k.action()}if(e){if(this.activeCameras&&this.activeCameras.length>0)for(var j=0;j<this.activeCameras.length;j++){var $=this.activeCameras[j];if($.update(),$.cameraRigMode!==0)for(var _e=0;_e<$._rigCameras.length;_e++)$._rigCameras[_e].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==0))for(var _e=0;_e<this.activeCamera._rigCameras.length;_e++)this.activeCamera._rigCameras[_e].update()}this.onBeforeRunRegisterBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderObservable.notifyObservers(this),this.onAfterRunRegisterBeforeRenderObservable.notifyObservers(this),this.onBeforeRTT1Observable.notifyObservers(this);var et=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);var tt=!((c=this.activeCameras)===null||c===void 0)&&c.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){Tools.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(var rt=0;rt<this.customRenderTargets.length;rt++){var it=this.customRenderTargets[rt];if(it._shouldRender()){if(this._renderId++,this.activeCamera=it.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");et.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),it.render(tt!==this.activeCamera,this.dumpNextRenderTargets)}}Tools.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(d=tt==null?void 0:tt.renderPassId)!==null&&d!==void 0?d:0,this.activeCamera=tt,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(var nt=0,ot=this._beforeClearStage;nt<ot.length;nt++){var k=ot[nt];k.action()}this._clearFrameBuffer(this.activeCamera);for(var at=0,st=this._gatherRenderTargetsStage;at<st.length;at++){var k=st[at];k.action(this._renderTargets)}if(this.onAfterRTT1Observable.notifyObservers(this),this.activeCameras&&this.activeCameras.length>0)for(var j=0;j<this.activeCameras.length;j++)this._processSubCameras(this.activeCameras[j],j>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!1)}this.onBeforeRunRegisterAfterRenderObservable.notifyObservers(this),this._checkIntersections();for(var ut=0,ft=this._afterRenderStage;ut<ft.length;ut++){var k=ft[ut];k.action()}if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this.onAfterRunRegisterAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(var _e=0;_e<this._toBeDisposed.length;_e++){var lt=this._toBeDisposed[_e];lt&&lt.dispose()}this._toBeDisposed=[]}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}},i.prototype.freezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].freeze()},i.prototype.unfreezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].unfreeze()},i.prototype.dispose=function(){var e;if(!this.isDisposed){this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons=[],this.morphTargetManagers=[],this._transientComponents=[],this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear();for(var o=0,s=this._components;o<s.length;o++){var c=s[o];c.dispose()}this.importedMeshesFiles=new Array,this.stopAllAnimations&&this.stopAllAnimations(),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed=[];for(var d=0,_=this._activeRequests;d<_.length;d++){var b=_[d];b.abort()}this.onBeforeRunRegisterBeforeRenderObservable.clear(),this.onAfterRunRegisterBeforeRenderObservable.clear(),this.onBeforeRTT1Observable.clear(),this.onAfterRTT1Observable.clear(),this.onBeforeRunRegisterAfterRenderObservable.clear(),this.onAfterRunRegisterAfterRenderObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onComputePressureChanged.clear(),(e=this._computePressureObserver)===null||e===void 0||e.unobserve(),this._computePressureObserver=void 0,this.detachControl();var k=this._engine.getInputElement();if(k){var j;for(j=0;j<this.cameras.length;j++)this.cameras[j].detachControl()}for(;this.animationGroups.length;)this.animationGroups[0].dispose();for(;this.lights.length;)this.lights[0].dispose();for(;this.meshes.length;)this.meshes[0].dispose(!0);for(;this.transformNodes.length;)this.transformNodes[0].dispose(!0);for(;this.cameras.length;)this.cameras[0].dispose();for(this._defaultMaterial&&this._defaultMaterial.dispose();this.multiMaterials.length;)this.multiMaterials[0].dispose();for(;this.materials.length;)this.materials[0].dispose();for(;this.particleSystems.length;)this.particleSystems[0].dispose();for(;this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.textures.length;)this.textures[0].dispose();for(;this.morphTargetManagers.length;)this.morphTargetManagers[0].dispose();this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),j=this._engine.scenes.indexOf(this),j>-1&&this._engine.scenes.splice(j,1),EngineStore._LastCreatedScene===this&&(this._engine.scenes.length>0?EngineStore._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:EngineStore._LastCreatedScene=null),j=this._engine._virtualScenes.indexOf(this),j>-1&&this._engine._virtualScenes.splice(j,1),this._engine.wipeCaches(!0),this._isDisposed=!0}},Object.defineProperty(i.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),i.prototype.clearCachedVertexData=function(){for(var e=0;e<this.meshes.length;e++){var o=this.meshes[e],s=o.geometry;s&&s.clearCachedData()}},i.prototype.cleanCachedTextureBuffer=function(){for(var e=0,o=this.textures;e<o.length;e++){var s=o[e],c=s._buffer;c&&(s._buffer=null)}},i.prototype.getWorldExtends=function(e){var o=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||function(){return!0},this.meshes.filter(e).forEach(function(c){if(c.computeWorldMatrix(!0),!(!c.subMeshes||c.subMeshes.length===0||c.infiniteDistance)){var d=c.getBoundingInfo(),_=d.boundingBox.minimumWorld,b=d.boundingBox.maximumWorld;Vector3.CheckExtends(_,o,s),Vector3.CheckExtends(b,o,s)}}),{min:o,max:s}},i.prototype.createPickingRay=function(e,o,s,c,d){throw _WarnImport("Ray")},i.prototype.createPickingRayToRef=function(e,o,s,c,d,_){throw _WarnImport("Ray")},i.prototype.createPickingRayInCameraSpace=function(e,o,s){throw _WarnImport("Ray")},i.prototype.createPickingRayInCameraSpaceToRef=function(e,o,s,c){throw _WarnImport("Ray")},i.prototype.pick=function(e,o,s,c,d,_){var b=new PickingInfo;return b._pickingUnavailable=!0,b},i.prototype.pickWithBoundingInfo=function(e,o,s,c,d){var _=new PickingInfo;return _._pickingUnavailable=!0,_},i.prototype.pickWithRay=function(e,o,s,c){throw _WarnImport("Ray")},i.prototype.multiPick=function(e,o,s,c,d){throw _WarnImport("Ray")},i.prototype.multiPickWithRay=function(e,o,s){throw _WarnImport("Ray")},i.prototype.setPointerOverMesh=function(e,o,s){this._inputManager.setPointerOverMesh(e,o,s)},i.prototype.getPointerOverMesh=function(){return this._inputManager.getPointerOverMesh()},i.prototype._rebuildGeometries=function(){for(var e=0,o=this.geometries;e<o.length;e++){var s=o[e];s._rebuild()}for(var c=0,d=this.meshes;c<d.length;c++){var _=d[c];_._rebuild()}this.postProcessManager&&this.postProcessManager._rebuild();for(var b=0,k=this._components;b<k.length;b++){var j=k[b];j.rebuild()}for(var $=0,_e=this.particleSystems;$<_e.length;$++){var et=_e[$];et.rebuild()}if(this.spriteManagers)for(var tt=0,rt=this.spriteManagers;tt<rt.length;tt++){var it=rt[tt];it.rebuild()}},i.prototype._rebuildTextures=function(){for(var e=0,o=this.textures;e<o.length;e++){var s=o[e];s._rebuild()}this.markAllMaterialsAsDirty(1)},i.prototype._getByTags=function(e,o,s){if(o===void 0)return e;var c=[];s=s||function(b){};for(var d in e){var _=e[d];Tags&&Tags.MatchesQuery(_,o)&&(c.push(_),s(_))}return c},i.prototype.getMeshesByTags=function(e,o){return this._getByTags(this.meshes,e,o)},i.prototype.getCamerasByTags=function(e,o){return this._getByTags(this.cameras,e,o)},i.prototype.getLightsByTags=function(e,o){return this._getByTags(this.lights,e,o)},i.prototype.getMaterialByTags=function(e,o){return this._getByTags(this.materials,e,o).concat(this._getByTags(this.multiMaterials,e,o))},i.prototype.getTransformNodesByTags=function(e,o){return this._getByTags(this.transformNodes,e,o)},i.prototype.setRenderingOrder=function(e,o,s,c){o===void 0&&(o=null),s===void 0&&(s=null),c===void 0&&(c=null),this._renderingManager.setRenderingOrder(e,o,s,c)},i.prototype.setRenderingAutoClearDepthStencil=function(e,o,s,c){s===void 0&&(s=!0),c===void 0&&(c=!0),this._renderingManager.setRenderingAutoClearDepthStencil(e,o,s,c)},i.prototype.getAutoClearDepthStencilSetup=function(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)},Object.defineProperty(i.prototype,"blockMaterialDirtyMechanism",{get:function(){return this._blockMaterialDirtyMechanism},set:function(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))},enumerable:!1,configurable:!0}),i.prototype.markAllMaterialsAsDirty=function(e,o){if(!this._blockMaterialDirtyMechanism)for(var s=0,c=this.materials;s<c.length;s++){var d=c[s];o&&!o(d)||d.markAsDirty(e)}},i.prototype._loadFile=function(e,o,s,c,d,_,b){var k=this,j=LoadFile(e,o,s,c?this.offlineProvider:void 0,d,_,b);return this._activeRequests.push(j),j.onCompleteObservable.add(function($){k._activeRequests.splice(k._activeRequests.indexOf($),1)}),j},i.prototype._loadFileAsync=function(e,o,s,c,d){var _=this;return new Promise(function(b,k){_._loadFile(e,function(j){b(j)},o,s,c,function(j,$){k($)},d)})},i.prototype._requestFile=function(e,o,s,c,d,_,b){var k=this,j=RequestFile(e,o,s,c?this.offlineProvider:void 0,d,_,b);return this._activeRequests.push(j),j.onCompleteObservable.add(function($){k._activeRequests.splice(k._activeRequests.indexOf($),1)}),j},i.prototype._requestFileAsync=function(e,o,s,c,d){var _=this;return new Promise(function(b,k){_._requestFile(e,function(j){b(j)},o,s,c,function(j){k(j)},d)})},i.prototype._readFile=function(e,o,s,c,d){var _=this,b=ReadFile(e,o,s,c,d);return this._activeRequests.push(b),b.onCompleteObservable.add(function(k){_._activeRequests.splice(_._activeRequests.indexOf(k),1)}),b},i.prototype._readFileAsync=function(e,o,s){var c=this;return new Promise(function(d,_){c._readFile(e,function(b){d(b)},o,s,function(b){_(b)})})},i.prototype.getPerfCollector=function(){throw _WarnImport("performanceViewerSceneExtension")},i.FOGMODE_NONE=0,i.FOGMODE_EXP=1,i.FOGMODE_EXP2=2,i.FOGMODE_LINEAR=3,i.MinDeltaTime=1,i.MaxDeltaTime=1e3,i}(AbstractScene);_injectLTSScene(Scene);var Size=function(){function a(i,e){this.width=i,this.height=e}return a.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},a.prototype.getClassName=function(){return"Size"},a.prototype.getHashCode=function(){var i=this.width|0;return i=i*397^(this.height|0),i},a.prototype.copyFrom=function(i){this.width=i.width,this.height=i.height},a.prototype.copyFromFloats=function(i,e){return this.width=i,this.height=e,this},a.prototype.set=function(i,e){return this.copyFromFloats(i,e)},a.prototype.multiplyByFloats=function(i,e){return new a(this.width*i,this.height*e)},a.prototype.clone=function(){return new a(this.width,this.height)},a.prototype.equals=function(i){return i?this.width===i.width&&this.height===i.height:!1},Object.defineProperty(a.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!1,configurable:!0}),a.Zero=function(){return new a(0,0)},a.prototype.add=function(i){var e=new a(this.width+i.width,this.height+i.height);return e},a.prototype.subtract=function(i){var e=new a(this.width-i.width,this.height-i.height);return e},a.Lerp=function(i,e,o){var s=i.width+(e.width-i.width)*o,c=i.height+(e.height-i.height)*o;return new a(s,c)},a}(),ThinTexture=function(){function a(i){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Size.Zero(),this._cachedBaseSize=Size.Zero(),this._initialSamplingMode=2,this._texture=i,this._texture&&(this._engine=this._texture.getEngine())}return Object.defineProperty(a.prototype,"wrapU",{get:function(){return this._wrapU},set:function(i){this._wrapU=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"wrapV",{get:function(){return this._wrapV},set:function(i){this._wrapV=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"coordinatesMode",{get:function(){return 0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isCube",{get:function(){return this._texture?this._texture.isCube:!1},set:function(i){!this._texture||(this._texture.isCube=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"is3D",{get:function(){return this._texture?this._texture.is3D:!1},set:function(i){!this._texture||(this._texture.is3D=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"is2DArray",{get:function(){return this._texture?this._texture.is2DArray:!1},set:function(i){!this._texture||(this._texture.is2DArray=i)},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"ThinTexture"},a.prototype.isReady=function(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1},a.prototype.delayLoad=function(){},a.prototype.getInternalTexture=function(){return this._texture},a.prototype.getSize=function(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize},a.prototype.getBaseSize=function(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)},Object.defineProperty(a.prototype,"samplingMode",{get:function(){return this._texture?this._texture.samplingMode:this._initialSamplingMode},enumerable:!1,configurable:!0}),a.prototype.updateSamplingMode=function(i){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(i,this._texture)},a.prototype.releaseInternalTexture=function(){this._texture&&(this._texture.dispose(),this._texture=null)},a.prototype.dispose=function(){this._texture&&(this.releaseInternalTexture(),this._engine=null)},a}(),BaseTexture=function(a){__extends(i,a);function i(e){var o=a.call(this,null)||this;return o.metadata=null,o.reservedDataStore=null,o._hasAlpha=!1,o.getAlphaFromRGB=!1,o.level=1,o.coordinatesIndex=0,o._coordinatesMode=0,o.wrapR=1,o.anisotropicFilteringLevel=i.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,o._isCube=!1,o._gammaSpace=!0,o.invertZ=!1,o.lodLevelInAlpha=!1,o.isRenderTarget=!1,o._prefiltered=!1,o._forceSerialize=!1,o.animations=new Array,o.onDisposeObservable=new Observable,o._onDisposeObserver=null,o._scene=null,o._uid=null,o._parentContainer=null,o._loadingError=!1,e?i._isScene(e)?o._scene=e:o._engine=e:o._scene=EngineStore.LastCreatedScene,o._scene&&(o.uniqueId=o._scene.getUniqueId(),o._scene.addTexture(o),o._engine=o._scene.getEngine()),o._uid=null,o}return Object.defineProperty(i.prototype,"hasAlpha",{get:function(){return this._hasAlpha},set:function(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(17))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"coordinatesMode",{get:function(){return this._coordinatesMode},set:function(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wrapU",{get:function(){return this._wrapU},set:function(e){this._wrapU=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wrapV",{get:function(){return this._wrapV},set:function(e){this._wrapV=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isCube",{get:function(){return this._texture?this._texture.isCube:this._isCube},set:function(e){this._texture?this._texture.isCube=e:this._isCube=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"is3D",{get:function(){return this._texture?this._texture.is3D:!1},set:function(e){!this._texture||(this._texture.is3D=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"is2DArray",{get:function(){return this._texture?this._texture.is2DArray:!1},set:function(e){!this._texture||(this._texture.is2DArray=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"gammaSpace",{get:function(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer},set:function(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isRGBD",{get:function(){return this._texture!=null&&this._texture._isRGBD},set:function(e){this._texture&&(this._texture._isRGBD=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"noMipmap",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lodGenerationOffset",{get:function(){return this._texture?this._texture._lodGenerationOffset:0},set:function(e){this._texture&&(this._texture._lodGenerationOffset=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lodGenerationScale",{get:function(){return this._texture?this._texture._lodGenerationScale:0},set:function(e){this._texture&&(this._texture._lodGenerationScale=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"linearSpecularLOD",{get:function(){return this._texture?this._texture._linearSpecularLOD:!1},set:function(e){this._texture&&(this._texture._linearSpecularLOD=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"irradianceTexture",{get:function(){return this._texture?this._texture._irradianceTexture:null},set:function(e){this._texture&&(this._texture._irradianceTexture=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uid",{get:function(){return this._uid||(this._uid=RandomGUID()),this._uid},enumerable:!1,configurable:!0}),i.prototype.toString=function(){return this.name},i.prototype.getClassName=function(){return"BaseTexture"},Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isBlocking",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"loadingError",{get:function(){return this._loadingError},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"errorObject",{get:function(){return this._errorObject},enumerable:!1,configurable:!0}),i.prototype.getScene=function(){return this._scene},i.prototype._getEngine=function(){return this._engine},i.prototype.checkTransformsAreIdentical=function(e){return e!==null},i.prototype.getTextureMatrix=function(){return Matrix.IdentityReadOnly},i.prototype.getReflectionTextureMatrix=function(){return Matrix.IdentityReadOnly},i.prototype.isReadyOrNotBlocking=function(){return!this.isBlocking||this.isReady()||this.loadingError},i.prototype.scale=function(e){},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!1},enumerable:!1,configurable:!0}),i.prototype._getFromCache=function(e,o,s,c,d){var _=this._getEngine();if(!_)return null;for(var b=_._getUseSRGBBuffer(!!d,o),k=_.getLoadedTexturesCache(),j=0;j<k.length;j++){var $=k[j];if((d===void 0||b===$._useSRGBBuffer)&&(c===void 0||c===$.invertY)&&$.url===e&&$.generateMipMaps===!o&&(!s||s===$.samplingMode))return $.incrementReferences(),$}return null},i.prototype._rebuild=function(){},i.prototype.clone=function(){return null},Object.defineProperty(i.prototype,"textureType",{get:function(){return this._texture&&this._texture.type!==void 0?this._texture.type:0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"textureFormat",{get:function(){return this._texture&&this._texture.format!==void 0?this._texture.format:5},enumerable:!1,configurable:!0}),i.prototype._markAllSubMeshesAsTexturesDirty=function(){var e=this.getScene();!e||e.markAllMaterialsAsDirty(1)},i.prototype.readPixels=function(e,o,s,c,d){if(e===void 0&&(e=0),o===void 0&&(o=0),s===void 0&&(s=null),c===void 0&&(c=!0),d===void 0&&(d=!1),!this._texture)return null;var _=this.getSize(),b=_.width,k=_.height,j=this._getEngine();if(!j)return null;o!=0&&(b=b/Math.pow(2,o),k=k/Math.pow(2,o),b=Math.round(b),k=Math.round(k));try{return this._texture.isCube?j._readTexturePixels(this._texture,b,k,e,o,s,c,d):j._readTexturePixels(this._texture,b,k,-1,o,s,c,d)}catch{return null}},i.prototype._readPixelsSync=function(e,o,s,c,d){if(e===void 0&&(e=0),o===void 0&&(o=0),s===void 0&&(s=null),c===void 0&&(c=!0),d===void 0&&(d=!1),!this._texture)return null;var _=this.getSize(),b=_.width,k=_.height,j=this._getEngine();if(!j)return null;o!=0&&(b=b/Math.pow(2,o),k=k/Math.pow(2,o),b=Math.round(b),k=Math.round(k));try{return this._texture.isCube?j._readTexturePixelsSync(this._texture,b,k,e,o,s,c,d):j._readTexturePixelsSync(this._texture,b,k,-1,o,s,c,d)}catch{return null}},Object.defineProperty(i.prototype,"_lodTextureHigh",{get:function(){return this._texture?this._texture._lodTextureHigh:null},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_lodTextureMid",{get:function(){return this._texture?this._texture._lodTextureMid:null},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_lodTextureLow",{get:function(){return this._texture?this._texture._lodTextureLow:null},enumerable:!1,configurable:!0}),i.prototype.dispose=function(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene._removePendingData(this);var e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){var o=this._parentContainer.textures.indexOf(this);o>-1&&this._parentContainer.textures.splice(o,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,a.prototype.dispose.call(this)},i.prototype.serialize=function(){if(!this.name)return null;var e=SerializationHelper.Serialize(this);return SerializationHelper.AppendSerializedAnimations(this,e),e},i.WhenAllReady=function(e,o){var s=e.length;if(s===0){o();return}for(var c=0;c<e.length;c++){var d=e[c];if(d.isReady())--s===0&&o();else{var _=d.onLoadObservable;_&&_.addOnce(function(){--s===0&&o()})}}},i._isScene=function(e){return e.getClassName()==="Scene"},i.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,__decorate([serialize()],i.prototype,"uniqueId",void 0),__decorate([serialize()],i.prototype,"name",void 0),__decorate([serialize()],i.prototype,"metadata",void 0),__decorate([serialize("hasAlpha")],i.prototype,"_hasAlpha",void 0),__decorate([serialize()],i.prototype,"getAlphaFromRGB",void 0),__decorate([serialize()],i.prototype,"level",void 0),__decorate([serialize()],i.prototype,"coordinatesIndex",void 0),__decorate([serialize("coordinatesMode")],i.prototype,"_coordinatesMode",void 0),__decorate([serialize()],i.prototype,"wrapU",null),__decorate([serialize()],i.prototype,"wrapV",null),__decorate([serialize()],i.prototype,"wrapR",void 0),__decorate([serialize()],i.prototype,"anisotropicFilteringLevel",void 0),__decorate([serialize()],i.prototype,"isCube",null),__decorate([serialize()],i.prototype,"is3D",null),__decorate([serialize()],i.prototype,"is2DArray",null),__decorate([serialize()],i.prototype,"gammaSpace",null),__decorate([serialize()],i.prototype,"invertZ",void 0),__decorate([serialize()],i.prototype,"lodLevelInAlpha",void 0),__decorate([serialize()],i.prototype,"lodGenerationOffset",null),__decorate([serialize()],i.prototype,"lodGenerationScale",null),__decorate([serialize()],i.prototype,"linearSpecularLOD",null),__decorate([serializeAsTexture()],i.prototype,"irradianceTexture",null),__decorate([serialize()],i.prototype,"isRenderTarget",void 0),i}(ThinTexture);function GenerateBase64StringFromPixelData(a,i,e){e===void 0&&(e=!1);var o=i.width,s=i.height;if(a instanceof Float32Array){for(var c=a.byteLength/a.BYTES_PER_ELEMENT,d=new Uint8Array(c);--c>=0;){var _=a[c];_<0?_=0:_>1&&(_=1),d[c]=_*255}a=d}var b=document.createElement("canvas");b.width=o,b.height=s;var k=b.getContext("2d");if(!k)return null;var j=k.createImageData(o,s),$=j.data;if($.set(a),k.putImageData(j,0,0),e){var _e=document.createElement("canvas");_e.width=o,_e.height=s;var et=_e.getContext("2d");return et?(et.translate(0,s),et.scale(1,-1),et.drawImage(b,0,0),_e.toDataURL("image/png")):null}return b.toDataURL("image/png")}function GenerateBase64StringFromTexture(a,i,e){i===void 0&&(i=0),e===void 0&&(e=0);var o=a.getInternalTexture();if(!o)return null;var s=a._readPixelsSync(i,e);return s?GenerateBase64StringFromPixelData(s,a.getSize(),o.invertY):null}function GenerateBase64StringFromTextureAsync(a,i,e){return i===void 0&&(i=0),e===void 0&&(e=0),__awaiter(this,void 0,void 0,function(){var o,s;return __generator(this,function(c){switch(c.label){case 0:return o=a.getInternalTexture(),o?[4,a.readPixels(i,e)]:[2,null];case 1:return s=c.sent(),s?[2,GenerateBase64StringFromPixelData(s,a.getSize(),o.invertY)]:[2,null]}})})}var Texture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$,_e,et,tt){c===void 0&&(c=!0),d===void 0&&(d=i.TRILINEAR_SAMPLINGMODE),_===void 0&&(_=null),b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=!1);var rt,it,nt,ot,at,st,ut,ft,lt=a.call(this,o)||this;lt.url=null,lt.uOffset=0,lt.vOffset=0,lt.uScale=1,lt.vScale=1,lt.uAng=0,lt.vAng=0,lt.wAng=0,lt.uRotationCenter=.5,lt.vRotationCenter=.5,lt.wRotationCenter=.5,lt.homogeneousRotationInUVTransform=!1,lt.inspectableCustomProperties=null,lt._noMipmap=!1,lt._invertY=!1,lt._rowGenerationMatrix=null,lt._cachedTextureMatrix=null,lt._projectionModeMatrix=null,lt._t0=null,lt._t1=null,lt._t2=null,lt._cachedUOffset=-1,lt._cachedVOffset=-1,lt._cachedUScale=0,lt._cachedVScale=0,lt._cachedUAng=-1,lt._cachedVAng=-1,lt._cachedWAng=-1,lt._cachedProjectionMatrixId=-1,lt._cachedURotationCenter=-1,lt._cachedVRotationCenter=-1,lt._cachedWRotationCenter=-1,lt._cachedHomogeneousRotationInUVTransform=!1,lt._cachedCoordinatesMode=-1,lt._buffer=null,lt._deleteBuffer=!1,lt._format=null,lt._delayedOnLoad=null,lt._delayedOnError=null,lt.onLoadObservable=new Observable,lt._isBlocking=!0,lt.name=e||"",lt.url=e;var ht,pt=!1;typeof s=="object"&&s!==null?(ht=(rt=s.noMipmap)!==null&&rt!==void 0?rt:!1,c=(it=s.invertY)!==null&&it!==void 0?it:!0,d=(nt=s.samplingMode)!==null&&nt!==void 0?nt:i.TRILINEAR_SAMPLINGMODE,_=(ot=s.onLoad)!==null&&ot!==void 0?ot:null,b=(at=s.onError)!==null&&at!==void 0?at:null,k=(st=s.buffer)!==null&&st!==void 0?st:null,j=(ut=s.deleteBuffer)!==null&&ut!==void 0?ut:!1,$=s.format,_e=s.mimeType,et=s.loaderOptions,tt=s.creationFlags,pt=(ft=s.useSRGBBuffer)!==null&&ft!==void 0?ft:!1):ht=!!s,lt._noMipmap=ht,lt._invertY=c,lt._initialSamplingMode=d,lt._buffer=k,lt._deleteBuffer=j,lt._mimeType=_e,lt._loaderOptions=et,lt._creationFlags=tt,lt._useSRGBBuffer=pt,$&&(lt._format=$);var mt=lt.getScene(),dt=lt._getEngine();if(!dt)return lt;dt.onBeforeTextureInitObservable.notifyObservers(lt);var gt=function(){lt._texture&&(lt._texture._invertVScale&&(lt.vScale*=-1,lt.vOffset+=1),lt._texture._cachedWrapU!==null&&(lt.wrapU=lt._texture._cachedWrapU,lt._texture._cachedWrapU=null),lt._texture._cachedWrapV!==null&&(lt.wrapV=lt._texture._cachedWrapV,lt._texture._cachedWrapV=null),lt._texture._cachedWrapR!==null&&(lt.wrapR=lt._texture._cachedWrapR,lt._texture._cachedWrapR=null)),lt.onLoadObservable.hasObservers()&&lt.onLoadObservable.notifyObservers(lt),_&&_(),!lt.isBlocking&&mt&&mt.resetCachedMaterial()},_t=function(Tt,St){lt._loadingError=!0,lt._errorObject={message:Tt,exception:St},b&&b(Tt,St),i.OnTextureLoadErrorObservable.notifyObservers(lt)};if(!lt.url)return lt._delayedOnLoad=gt,lt._delayedOnError=_t,lt;if(lt._texture=lt._getFromCache(lt.url,ht,d,c,pt),lt._texture)if(lt._texture.isReady)TimingTools.SetImmediate(function(){return gt()});else{var yt=lt._texture.onLoadedObservable.add(gt);lt._texture.onErrorObservable.add(function(Tt){var St;_t(Tt.message,Tt.exception),(St=lt._texture)===null||St===void 0||St.onLoadedObservable.remove(yt)})}else if(!mt||!mt.useDelayedTextureLoading){try{lt._texture=dt.createTexture(lt.url,ht,c,mt,d,gt,_t,lt._buffer,void 0,lt._format,null,_e,et,tt,pt)}catch(Tt){throw _t("error loading",Tt),Tt}j&&(lt._buffer=null)}else lt.delayLoadState=4,lt._delayedOnLoad=gt,lt._delayedOnError=_t;return lt}return Object.defineProperty(i.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"mimeType",{get:function(){return this._mimeType},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isBlocking",{get:function(){return this._isBlocking},set:function(e){this._isBlocking=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"invertY",{get:function(){return this._invertY},enumerable:!1,configurable:!0}),i.prototype.updateURL=function(e,o,s){o===void 0&&(o=null),this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1)),(!this.name||StartsWith(this.name,"data:"))&&(this.name=e),this.url=e,this._buffer=o,this.delayLoadState=4,s&&(this._delayedOnLoad=s),this.delayLoad()},i.prototype.delayLoad=function(){if(this.delayLoadState===4){var e=this.getScene();!e||(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer),this._texture?this._delayedOnLoad&&(this._texture.isReady?TimingTools.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,null,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}},i.prototype._prepareRowForTextureGeneration=function(e,o,s,c){e*=this._cachedUScale,o*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,o-=this.vRotationCenter*this._cachedVScale,s-=this.wRotationCenter,Vector3.TransformCoordinatesFromFloatsToRef(e,o,s,this._rowGenerationMatrix,c),c.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,c.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,c.z+=this.wRotationCenter},i.prototype.checkTransformsAreIdentical=function(e){return e!==null&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng},i.prototype.getTextureMatrix=function(e){var o=this;if(e===void 0&&(e=1),this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=Matrix.Zero(),this._rowGenerationMatrix=new Matrix,this._t0=Vector3.Zero(),this._t1=Vector3.Zero(),this._t2=Vector3.Zero()),Matrix.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(Matrix.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,TmpVectors.Matrix[0]),Matrix.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,TmpVectors.Matrix[1]),Matrix.ScalingToRef(this._cachedUScale,this._cachedVScale,0,TmpVectors.Matrix[2]),Matrix.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,TmpVectors.Matrix[3]),TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),Matrix.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));var s=this.getScene();return s?(s.markAllMaterialsAsDirty(1,function(c){return c.hasTexture(o)}),this._cachedTextureMatrix):this._cachedTextureMatrix},i.prototype.getReflectionTextureMatrix=function(){var e=this,o=this.getScene();if(!o)return this._cachedTextureMatrix;if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.coordinatesMode===this._cachedCoordinatesMode)if(this.coordinatesMode===i.PROJECTION_MODE){if(this._cachedProjectionMatrixId===o.getProjectionMatrix().updateFlag)return this._cachedTextureMatrix}else return this._cachedTextureMatrix;this._cachedTextureMatrix||(this._cachedTextureMatrix=Matrix.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=Matrix.Zero());var s=this._cachedCoordinatesMode!==this.coordinatesMode;switch(this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale,this._cachedVScale=this.vScale,this._cachedCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case i.PLANAR_MODE:Matrix.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix[0]=this.uScale,this._cachedTextureMatrix[5]=this.vScale,this._cachedTextureMatrix[12]=this.uOffset,this._cachedTextureMatrix[13]=this.vOffset;break;case i.PROJECTION_MODE:Matrix.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);var c=o.getProjectionMatrix();this._cachedProjectionMatrixId=c.updateFlag,c.multiplyToRef(this._projectionModeMatrix,this._cachedTextureMatrix);break;default:Matrix.IdentityToRef(this._cachedTextureMatrix);break}return s&&o.markAllMaterialsAsDirty(1,function(d){return d.getActiveTextures().indexOf(e)!==-1}),this._cachedTextureMatrix},i.prototype.clone=function(){var e=this,o={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return SerializationHelper.Clone(function(){return new i(e._texture?e._texture.url:null,e.getScene(),o)},this)},i.prototype.serialize=function(){var e=this.name;i.SerializeBuffers||StartsWith(this.name,"data:")&&(this.name=""),StartsWith(this.name,"data:")&&this.url===this.name&&(this.url="");var o=a.prototype.serialize.call(this);return o?((i.SerializeBuffers||i.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(o.base64String=this._buffer,o.name=o.name.replace("data:","")):this.url&&StartsWith(this.url,"data:")&&this._buffer instanceof Uint8Array?o.base64String="data:image/png;base64,"+EncodeArrayBufferToBase64(this._buffer):(i.ForceSerializeBuffers||this.url&&StartsWith(this.url,"blob:")||this._forceSerialize)&&(o.base64String=!this._engine||this._engine._features.supportSyncTextureRead?GenerateBase64StringFromTexture(this):GenerateBase64StringFromTextureAsync(this))),o.invertY=this._invertY,o.samplingMode=this.samplingMode,o._creationFlags=this._creationFlags,o._useSRGBBuffer=this._useSRGBBuffer,this.name=e,o):null},i.prototype.getClassName=function(){return"Texture"},i.prototype.dispose=function(){a.prototype.dispose.call(this),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null},i.Parse=function(e,o,s){if(e.customType){var c=InstantiationTools.Instantiate(e.customType),d=c.Parse(e,o,s);return e.samplingMode&&d.updateSamplingMode&&d._samplingMode&&d._samplingMode!==e.samplingMode&&d.updateSamplingMode(e.samplingMode),d}if(e.isCube&&!e.isRenderTarget)return i._CubeTextureParser(e,o,s);if(!e.name&&!e.isRenderTarget)return null;var _=function(){if(b&&b._texture&&(b._texture._cachedWrapU=null,b._texture._cachedWrapV=null,b._texture._cachedWrapR=null),e.samplingMode){var k=e.samplingMode;b&&b.samplingMode!==k&&b.updateSamplingMode(k)}if(b&&e.animations)for(var j=0;j<e.animations.length;j++){var $=e.animations[j],_e=GetClass("BABYLON.Animation");_e&&b.animations.push(_e.Parse($))}},b=SerializationHelper.Parse(function(){var k,j,$,_e=!0;if(e.noMipmap&&(_e=!1),e.mirrorPlane){var et=i._CreateMirror(e.name,e.renderTargetSize,o,_e);return et._waitingRenderList=e.renderList,et.mirrorPlane=Plane.FromArray(e.mirrorPlane),_(),et}else if(e.isRenderTarget){var tt=null;if(e.isCube){if(o.reflectionProbes)for(var rt=0;rt<o.reflectionProbes.length;rt++){var it=o.reflectionProbes[rt];if(it.name===e.name)return it.cubeTexture}}else tt=i._CreateRenderTargetTexture(e.name,e.renderTargetSize,o,_e,(k=e._creationFlags)!==null&&k!==void 0?k:0),tt._waitingRenderList=e.renderList;return _(),tt}else{var nt;if(e.base64String)nt=i.CreateFromBase64String(e.base64String,e.name,o,!_e,e.invertY,e.samplingMode,_,(j=e._creationFlags)!==null&&j!==void 0?j:0,($=e._useSRGBBuffer)!==null&&$!==void 0?$:!1);else{var ot=void 0;e.name&&e.name.indexOf("://")>0?ot=e.name:ot=s+e.name,(StartsWith(e.url,"data:")||i.UseSerializedUrlIfAny&&e.url)&&(ot=e.url),nt=new i(ot,o,!_e,e.invertY,e.samplingMode,_)}return nt}},e,o);return b},i.CreateFromBase64String=function(e,o,s,c,d,_,b,k,j,$){return _===void 0&&(_=i.TRILINEAR_SAMPLINGMODE),b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=5),new i("data:"+o,s,c,d,_,b,k,e,!1,j,void 0,void 0,$)},i.LoadFromDataString=function(e,o,s,c,d,_,b,k,j,$,_e){return c===void 0&&(c=!1),_===void 0&&(_=!0),b===void 0&&(b=i.TRILINEAR_SAMPLINGMODE),k===void 0&&(k=null),j===void 0&&(j=null),$===void 0&&($=5),e.substr(0,5)!=="data:"&&(e="data:"+e),new i(e,s,d,_,b,k,j,o,c,$,void 0,void 0,_e)},i.SerializeBuffers=!0,i.ForceSerializeBuffers=!1,i.OnTextureLoadErrorObservable=new Observable,i._CubeTextureParser=function(e,o,s){throw _WarnImport("CubeTexture")},i._CreateMirror=function(e,o,s,c){throw _WarnImport("MirrorTexture")},i._CreateRenderTargetTexture=function(e,o,s,c,d){throw _WarnImport("RenderTargetTexture")},i.NEAREST_SAMPLINGMODE=1,i.NEAREST_NEAREST_MIPLINEAR=8,i.BILINEAR_SAMPLINGMODE=2,i.LINEAR_LINEAR_MIPNEAREST=11,i.TRILINEAR_SAMPLINGMODE=3,i.LINEAR_LINEAR_MIPLINEAR=3,i.NEAREST_NEAREST_MIPNEAREST=4,i.NEAREST_LINEAR_MIPNEAREST=5,i.NEAREST_LINEAR_MIPLINEAR=6,i.NEAREST_LINEAR=7,i.NEAREST_NEAREST=1,i.LINEAR_NEAREST_MIPNEAREST=9,i.LINEAR_NEAREST_MIPLINEAR=10,i.LINEAR_LINEAR=2,i.LINEAR_NEAREST=12,i.EXPLICIT_MODE=0,i.SPHERICAL_MODE=1,i.PLANAR_MODE=2,i.CUBIC_MODE=3,i.PROJECTION_MODE=4,i.SKYBOX_MODE=5,i.INVCUBIC_MODE=6,i.EQUIRECTANGULAR_MODE=7,i.FIXED_EQUIRECTANGULAR_MODE=8,i.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,i.CLAMP_ADDRESSMODE=0,i.WRAP_ADDRESSMODE=1,i.MIRROR_ADDRESSMODE=2,i.UseSerializedUrlIfAny=!1,__decorate([serialize()],i.prototype,"url",void 0),__decorate([serialize()],i.prototype,"uOffset",void 0),__decorate([serialize()],i.prototype,"vOffset",void 0),__decorate([serialize()],i.prototype,"uScale",void 0),__decorate([serialize()],i.prototype,"vScale",void 0),__decorate([serialize()],i.prototype,"uAng",void 0),__decorate([serialize()],i.prototype,"vAng",void 0),__decorate([serialize()],i.prototype,"wAng",void 0),__decorate([serialize()],i.prototype,"uRotationCenter",void 0),__decorate([serialize()],i.prototype,"vRotationCenter",void 0),__decorate([serialize()],i.prototype,"wRotationCenter",void 0),__decorate([serialize()],i.prototype,"homogeneousRotationInUVTransform",void 0),__decorate([serialize()],i.prototype,"isBlocking",null),i}(BaseTexture);RegisterClass("BABYLON.Texture",Texture);SerializationHelper._TextureParser=Texture.Parse;var WebGLRenderTargetWrapper=function(a){__extends(i,a);function i(e,o,s,c,d){var _=a.call(this,e,o,s,c)||this;return _._framebuffer=null,_._depthStencilBuffer=null,_._MSAAFramebuffer=null,_._colorTextureArray=null,_._depthStencilTextureArray=null,_._context=d,_}return i.prototype._cloneRenderTargetWrapper=function(){var e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=a.prototype._cloneRenderTargetWrapper.call(this),e},i.prototype._swapRenderTargetWrapper=function(e){a.prototype._swapRenderTargetWrapper.call(this,e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null},i.prototype._shareDepth=function(e){a.prototype._shareDepth.call(this,e);var o=this._context,s=this._depthStencilBuffer,c=e._framebuffer;e._depthStencilBuffer&&o.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=this._depthStencilBuffer,this._engine._bindUnboundFramebuffer(c),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.DEPTH_ATTACHMENT,o.RENDERBUFFER,s),this._engine._bindUnboundFramebuffer(null)},i.prototype._bindTextureRenderTarget=function(e,o,s,c){if(o===void 0&&(o=0),s===void 0&&(s=-1),c===void 0&&(c=0),!!e._hardwareTexture){var d=this._context,_=this._framebuffer,b=this._engine._currentFramebuffer;this._engine._bindUnboundFramebuffer(_);var k=d[this._engine.webGLVersion>1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"],j=s!==-1?d.TEXTURE_CUBE_MAP_POSITIVE_X+s:d.TEXTURE_2D;d.framebufferTexture2D(d.FRAMEBUFFER,k,j,e._hardwareTexture.underlyingResource,c),this._engine._bindUnboundFramebuffer(b)}},i.prototype.setTexture=function(e,o,s){o===void 0&&(o=0),s===void 0&&(s=!0),a.prototype.setTexture.call(this,e,o,s),this._bindTextureRenderTarget(e,o)},i.prototype.dispose=function(e){e===void 0&&(e=!1);var o=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(o.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(o.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(o.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),a.prototype.dispose.call(this,e)},i}(RenderTargetWrapper);ThinEngine.prototype._createHardwareRenderTargetWrapper=function(a,i,e){var o=new WebGLRenderTargetWrapper(a,i,e,this,this._gl);return this._renderTargetWrapperCache.push(o),o};ThinEngine.prototype.createRenderTargetTexture=function(a,i){var e=this._createHardwareRenderTargetWrapper(!1,!1,a),o={};i!==void 0&&typeof i=="object"?(o.generateDepthBuffer=!!i.generateDepthBuffer,o.generateStencilBuffer=!!i.generateStencilBuffer):(o.generateDepthBuffer=!0,o.generateStencilBuffer=!1);var s=this._createInternalTexture(a,i,!0,InternalTextureSource.RenderTarget),c=a.width||a,d=a.height||a,_=this._currentFramebuffer,b=this._gl,k=b.createFramebuffer();return this._bindUnboundFramebuffer(k),e._depthStencilBuffer=this._setupFramebufferDepthAttachments(!!o.generateStencilBuffer,o.generateDepthBuffer,c,d),s.is2DArray||b.framebufferTexture2D(b.FRAMEBUFFER,b.COLOR_ATTACHMENT0,b.TEXTURE_2D,s._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(_),e._framebuffer=k,e._generateDepthBuffer=o.generateDepthBuffer,e._generateStencilBuffer=!!o.generateStencilBuffer,e.setTextures(s),e};ThinEngine.prototype.createDepthStencilTexture=function(a,i,e){if(i.isCube){var o=a.width||a;return this._createDepthStencilCubeTexture(o,i,e)}else return this._createDepthStencilTexture(a,i,e)};ThinEngine.prototype._createDepthStencilTexture=function(a,i,e){var o=this._gl,s=a.layers||0,c=s!==0?o.TEXTURE_2D_ARRAY:o.TEXTURE_2D,d=new InternalTexture(this,InternalTextureSource.DepthStencil);if(!this._caps.depthTextureExtension)return Logger$2.Error("Depth texture is not supported by your browser or hardware."),d;var _=__assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i);this._bindTextureDirectly(c,d,!0),this._setupDepthStencilTexture(d,a,_.generateStencil,_.comparisonFunction===0?!1:_.bilinearFiltering,_.comparisonFunction),e._depthStencilTexture=d,e._depthStencilTextureWithStencil=_.generateStencil;var b=_.generateStencil?o.UNSIGNED_INT_24_8:o.UNSIGNED_INT,k=_.generateStencil?o.DEPTH_STENCIL:o.DEPTH_COMPONENT,j=k;return this.webGLVersion>1&&(j=_.generateStencil?o.DEPTH24_STENCIL8:o.DEPTH_COMPONENT24),d.is2DArray?o.texImage3D(c,0,j,d.width,d.height,s,0,k,b,null):o.texImage2D(c,0,j,d.width,d.height,0,k,b,null),this._bindTextureDirectly(c,null),this._internalTexturesCache.push(d),d};ThinEngine.prototype.updateRenderTargetTextureSampleCount=function(a,i){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===i)return i;var e=this._gl;i=Math.min(i,this.getCaps().maxMSAASamples),a._depthStencilBuffer&&(e.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(e.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null);var o=a.texture._hardwareTexture;if(o._MSAARenderBuffer&&(e.deleteRenderbuffer(o._MSAARenderBuffer),o._MSAARenderBuffer=null),i>1&&e.renderbufferStorageMultisample){var s=e.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=s,this._bindUnboundFramebuffer(a._MSAAFramebuffer);var c=this._createRenderBuffer(a.texture.width,a.texture.height,i,-1,this._getRGBAMultiSampleBufferFormat(a.texture.type),e.COLOR_ATTACHMENT0,!1);if(!c)throw new Error("Unable to create multi sampled framebuffer");o._MSAARenderBuffer=c}else this._bindUnboundFramebuffer(a._framebuffer);return a.texture.samples=i,a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,i),this._bindUnboundFramebuffer(null),i};ThinEngine.prototype.createRenderTargetCubeTexture=function(a,i){var e=this._createHardwareRenderTargetWrapper(!1,!0,a),o=__assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},i);o.generateStencilBuffer=o.generateDepthBuffer&&o.generateStencilBuffer,(o.type===1&&!this._caps.textureFloatLinearFiltering||o.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o.samplingMode=1);var s=this._gl,c=new InternalTexture(this,InternalTextureSource.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,c,!0);var d=this._getSamplingParameters(o.samplingMode,o.generateMipMaps);o.type===1&&!this._caps.textureFloat&&(o.type=0,Logger$2.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,d.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,d.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(var _=0;_<6;_++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+_,0,this._getRGBABufferInternalSizedFormat(o.type,o.format),a,a,0,this._getInternalFormat(o.format),this._getWebGLTextureType(o.type),null);var b=s.createFramebuffer();return this._bindUnboundFramebuffer(b),e._depthStencilBuffer=this._setupFramebufferDepthAttachments(o.generateStencilBuffer,o.generateDepthBuffer,a,a),o.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),e._framebuffer=b,e._generateDepthBuffer=o.generateDepthBuffer,e._generateStencilBuffer=o.generateStencilBuffer,c.width=a,c.height=a,c.isReady=!0,c.isCube=!0,c.samples=1,c.generateMipMaps=o.generateMipMaps,c.samplingMode=o.samplingMode,c.type=o.type,c.format=o.format,this._internalTexturesCache.push(c),e.setTextures(c),e};var RenderTargetTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it){d===void 0&&(d=!0),_===void 0&&(_=0),b===void 0&&(b=!1),k===void 0&&(k=Texture.TRILINEAR_SAMPLINGMODE),j===void 0&&(j=!0),$===void 0&&($=!1),_e===void 0&&(_e=!1),et===void 0&&(et=5),tt===void 0&&(tt=!1);var nt,ot=a.call(this,null,s,!c,void 0,k,void 0,void 0,void 0,void 0,et)||this;if(ot.renderParticles=!0,ot.renderSprites=!1,ot.ignoreCameraViewport=!1,ot.onBeforeBindObservable=new Observable,ot.onAfterUnbindObservable=new Observable,ot.onBeforeRenderObservable=new Observable,ot.onAfterRenderObservable=new Observable,ot.onClearObservable=new Observable,ot.onResizeObservable=new Observable,ot._cleared=!1,ot.skipInitialClear=!1,ot._currentRefreshId=-1,ot._refreshRate=1,ot._samples=1,ot._canRescale=!0,ot._renderTarget=null,ot.boundingBoxPosition=Vector3.Zero(),s=ot.getScene(),!s)return ot;var at=ot.getScene().getEngine();return ot._coordinatesMode=Texture.PROJECTION_MODE,ot.renderList=new Array,ot.name=e,ot.isRenderTarget=!0,ot._initialSizeParameter=o,ot._renderPassIds=[],ot.__isCube=b,ot._processSizeParameter(o),ot.renderPassId=ot._renderPassIds[0],ot._resizeObserver=at.onResizeObservable.add(function(){}),ot._generateMipMaps=!!c,ot._doNotChangeAspectRatio=d,ot._renderingManager=new RenderingManager(s),ot._renderingManager._useSceneAutoClearSetup=!0,_e||(ot._renderTargetOptions={generateMipMaps:c,type:_,format:(nt=ot._format)!==null&&nt!==void 0?nt:void 0,samplingMode:ot.samplingMode,generateDepthBuffer:j,generateStencilBuffer:$,samples:rt,creationFlags:it},ot.samplingMode===Texture.NEAREST_SAMPLINGMODE&&(ot.wrapU=Texture.CLAMP_ADDRESSMODE,ot.wrapV=Texture.CLAMP_ADDRESSMODE),tt||(b?(ot._renderTarget=s.getEngine().createRenderTargetCubeTexture(ot.getRenderSize(),ot._renderTargetOptions),ot.coordinatesMode=Texture.INVCUBIC_MODE,ot._textureMatrix=Matrix.Identity()):ot._renderTarget=s.getEngine().createRenderTargetTexture(ot._size,ot._renderTargetOptions),ot._texture=ot._renderTarget.texture,rt!==void 0&&(ot.samples=rt))),ot}return Object.defineProperty(i.prototype,"renderList",{get:function(){return this._renderList},set:function(e){this._renderList=e,this._renderList&&this._hookArray(this._renderList)},enumerable:!1,configurable:!0}),i.prototype._hookArray=function(e){var o=this,s=e.push;e.push=function(){for(var d,_=[],b=0;b<arguments.length;b++)_[b]=arguments[b];var k=e.length===0,j=s.apply(e,_);return k&&((d=o.getScene())===null||d===void 0||d.meshes.forEach(function($){$._markSubMeshesAsLightDirty()})),j};var c=e.splice;e.splice=function(d,_){var b,k=c.apply(e,[d,_]);return e.length===0&&((b=o.getScene())===null||b===void 0||b.meshes.forEach(function(j){j._markSubMeshesAsLightDirty()})),k}},Object.defineProperty(i.prototype,"postProcesses",{get:function(){return this._postProcesses},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_prePassEnabled",{get:function(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onAfterUnbind",{set:function(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onClear",{set:function(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"renderPassIds",{get:function(){return this._renderPassIds},enumerable:!1,configurable:!0}),i.prototype.setMaterialForRendering=function(e,o){var s;Array.isArray(e)?s=e:s=[e];for(var c=0;c<s.length;++c)for(var d=0;d<this._renderPassIds.length;++d)s[c].setMaterialForRenderPass(this._renderPassIds[d],o!==void 0?Array.isArray(o)?o[d]:o:void 0)},Object.defineProperty(i.prototype,"renderTargetOptions",{get:function(){return this._renderTargetOptions},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"renderTarget",{get:function(){return this._renderTarget},enumerable:!1,configurable:!0}),i.prototype._onRatioRescale=function(){this._sizeRatio&&this.resize(this._initialSizeParameter)},Object.defineProperty(i.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!(this._boundingBoxSize&&this._boundingBoxSize.equals(e))){this._boundingBoxSize=e;var o=this.getScene();o&&o.markAllMaterialsAsDirty(1)}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"depthStencilTexture",{get:function(){var e,o;return(o=(e=this._renderTarget)===null||e===void 0?void 0:e._depthStencilTexture)!==null&&o!==void 0?o:null},enumerable:!1,configurable:!0}),i.prototype.createDepthStencilTexture=function(e,o,s,c){var d;e===void 0&&(e=0),o===void 0&&(o=!0),s===void 0&&(s=!1),c===void 0&&(c=1),(d=this._renderTarget)===null||d===void 0||d.createDepthStencilTexture(e,o,s,c)},i.prototype._releaseRenderPassId=function(){if(this._scene)for(var e=this._scene.getEngine(),o=0;o<this._renderPassIds.length;++o)e.releaseRenderPassId(this._renderPassIds[o]);this._renderPassIds=[]},i.prototype._createRenderPassId=function(){this._releaseRenderPassId();for(var e=this._scene.getEngine(),o=this.__isCube?6:this.getRenderLayers()||1,s=0;s<o;++s)this._renderPassIds[s]=e.createRenderPassId("RenderTargetTexture - "+this.name+"#"+s)},i.prototype._processSizeParameter=function(e){if(e.ratio){this._sizeRatio=e.ratio;var o=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(o.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(o.getRenderHeight(),this._sizeRatio)}}else this._size=e;this._createRenderPassId()},Object.defineProperty(i.prototype,"samples",{get:function(){var e,o;return(o=(e=this._renderTarget)===null||e===void 0?void 0:e.samples)!==null&&o!==void 0?o:this._samples},set:function(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))},enumerable:!1,configurable:!0}),i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!1,configurable:!0}),i.prototype.addPostProcess=function(e){if(!this._postProcessManager){var o=this.getScene();if(!o)return;this._postProcessManager=new PostProcessManager(o),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1},i.prototype.clearPostProcesses=function(e){if(e===void 0&&(e=!1),!!this._postProcesses){if(e)for(var o=0,s=this._postProcesses;o<s.length;o++){var c=s[o];c.dispose()}this._postProcesses=[]}},i.prototype.removePostProcess=function(e){if(!!this._postProcesses){var o=this._postProcesses.indexOf(e);o!==-1&&(this._postProcesses.splice(o,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}},i.prototype._shouldRender=function(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.getRenderSize=function(){return this.getRenderWidth()},i.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},i.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},i.prototype.getRenderLayers=function(){var e=this._size.layers;return e||0},i.prototype.disableRescaling=function(){this._canRescale=!1},Object.defineProperty(i.prototype,"canRescale",{get:function(){return this._canRescale},enumerable:!1,configurable:!0}),i.prototype.scale=function(e){var o=Math.max(1,this.getRenderSize()*e);this.resize(o)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:a.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e){var o,s=this.isCube;(o=this._renderTarget)===null||o===void 0||o.dispose(),this._renderTarget=null;var c=this.getScene();!c||(this._processSizeParameter(e),s?this._renderTarget=c.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=c.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))},i.prototype.render=function(e,o){e===void 0&&(e=!1),o===void 0&&(o=!1),this._render(e,o)},i.prototype.isReadyForRendering=function(){return this._render(!1,!1,!0)},i.prototype._render=function(e,o,s){var c;e===void 0&&(e=!1),o===void 0&&(o=!1),s===void 0&&(s=!1);var d=this.getScene();if(!d)return s;var _=d.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var b=0;b<this._waitingRenderList.length;b++){var k=this._waitingRenderList[b],j=d.getMeshById(k);j&&this.renderList.push(j)}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];var d=this.getScene();if(!d)return s;for(var $=d.meshes,b=0;b<$.length;b++){var _e=$[b];this.renderListPredicate(_e)&&this.renderList.push(_e)}}var et=_.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);var tt=(c=this.activeCamera)!==null&&c!==void 0?c:d.activeCamera;tt&&(tt!==d.activeCamera&&d.setTransformMatrix(tt.getViewMatrix(),tt.getProjectionMatrix(!0)),_.setViewport(tt.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;var rt=s;if(s){d.getViewMatrix()||d.updateTransformMatrix();for(var ot=this.is2DArray?this.getRenderLayers():this.isCube?6:1,it=0;it<ot&&rt;it++){var at=null,st=this.renderList?this.renderList:d.getActiveMeshes().data,ut=this.renderList?this.renderList.length:d.getActiveMeshes().length;_.currentRenderPassId=this._renderPassIds[it],this.onBeforeRenderObservable.notifyObservers(it),this.getCustomRenderList&&(at=this.getCustomRenderList(it,st,ut)),at||(at=st),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(var ft=0;ft<at.length&&rt;++ft){var lt=at[ft];if(!(!lt.isEnabled()||lt.isBlocked||!lt.isVisible||!lt.subMeshes)){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(lt,this.refreshRate)){rt=!1;break}}else if(!lt.isReady(!0)){rt=!1;break}}}this.onAfterRenderObservable.notifyObservers(it)}}else if(this.is2DArray)for(var it=0;it<this.getRenderLayers();it++)this.renderToTarget(0,e,o,it,tt),d.incrementRenderId(),d.resetCachedMaterial();else if(this.isCube)for(var nt=0;nt<6;nt++)this.renderToTarget(nt,e,o,void 0,tt),d.incrementRenderId(),d.resetCachedMaterial();else this.renderToTarget(0,e,o,void 0,tt);return this.onAfterUnbindObservable.notifyObservers(this),_.currentRenderPassId=et,d.activeCamera&&((d.getEngine().scenes.length>1||this.activeCamera&&this.activeCamera!==d.activeCamera)&&d.setTransformMatrix(d.activeCamera.getViewMatrix(),d.activeCamera.getProjectionMatrix(!0)),_.setViewport(d.activeCamera.viewport)),d.resetCachedMaterial(),rt},i.prototype._bestReflectionRenderTargetDimension=function(e,o){var s=128,c=e*o,d=Engine.NearestPOT(c+s*s/(s+c));return Math.min(Engine.FloorPOT(e),d)},i.prototype._prepareRenderingManager=function(e,o,s,c){var d=this.getScene();if(!!d){this._renderingManager.reset();for(var _=d.getRenderId(),b=0;b<o;b++){var k=e[b];if(k&&!k.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(k,this.refreshRate)){this.resetRefreshCounter();continue}}else if(!k.isReady(this.refreshRate===0)){this.resetRefreshCounter();continue}if(!k._internalAbstractMeshDataInfo._currentLODIsUpToDate&&d.activeCamera&&(k._internalAbstractMeshDataInfo._currentLOD=d.customLODSelector?d.customLODSelector(k,this.activeCamera||d.activeCamera):k.getLOD(this.activeCamera||d.activeCamera),k._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!k._internalAbstractMeshDataInfo._currentLOD)continue;var j=k._internalAbstractMeshDataInfo._currentLOD;j._preActivateForIntermediateRendering(_);var $=void 0;if(c&&s?$=(k.layerMask&s.layerMask)===0:$=!1,k.isEnabled()&&k.isVisible&&k.subMeshes&&!$&&(j!==k&&j._activate(_,!0),k._activate(_,!0)&&k.subMeshes.length)){k.isAnInstance?k._internalAbstractMeshDataInfo._actAsRegularMesh&&(j=k):j._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,j._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(var _e=0;_e<j.subMeshes.length;_e++){var et=j.subMeshes[_e];this._renderingManager.dispatch(et,j)}}}}for(var tt=0;tt<d.particleSystems.length;tt++){var rt=d.particleSystems[tt],it=rt.emitter;!rt.isStarted()||!it||!it.position||!it.isEnabled()||e.indexOf(it)>=0&&this._renderingManager.dispatchParticles(rt)}}},i.prototype._bindFrameBuffer=function(e,o){e===void 0&&(e=0),o===void 0&&(o=0);var s=this.getScene();if(!!s){var c=s.getEngine();this._renderTarget&&c.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,o)}},i.prototype.unbindFrameBuffer=function(e,o){var s=this;!this._renderTarget||e.unBindFramebuffer(this._renderTarget,this.isCube,function(){s.onAfterRenderObservable.notifyObservers(o)})},i.prototype._prepareFrame=function(e,o,s,c){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!c||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(o,s)},i.prototype.renderToTarget=function(e,o,s,c,d){var _,b,k,j;c===void 0&&(c=0),d===void 0&&(d=null);var $=this.getScene();if(!!$){var _e=$.getEngine();if(!!this._texture){(_=_e._debugPushGroup)===null||_===void 0||_.call(_e,"render to face #"+e+" layer #"+c,1),this._prepareFrame($,e,c,o),this.is2DArray?(_e.currentRenderPassId=this._renderPassIds[c],this.onBeforeRenderObservable.notifyObservers(c)):(_e.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));var et=_e.snapshotRendering&&_e.snapshotRenderingMode===1;if(et)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(_e):this.skipInitialClear||_e.clear(this.clearColor||$.clearColor,!0,!0,!0);else{var tt=null,rt=this.renderList?this.renderList:$.getActiveMeshes().data,it=this.renderList?this.renderList.length:$.getActiveMeshes().length;this.getCustomRenderList&&(tt=this.getCustomRenderList(this.is2DArray?c:e,rt,it)),tt?this._prepareRenderingManager(tt,tt.length,d,!1):(this._defaultRenderListPrepared||(this._prepareRenderingManager(rt,it,d,!this.renderList),this._defaultRenderListPrepared=!0),tt=rt);for(var nt=0,ot=$._beforeRenderTargetClearStage;nt<ot.length;nt++){var at=ot[nt];at.action(this,e,c)}this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(_e):this.skipInitialClear||_e.clear(this.clearColor||$.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||$.updateTransformMatrix(!0);for(var st=0,ut=$._beforeRenderTargetDrawStage;st<ut.length;st++){var at=ut[st];at.action(this,e,c)}this._renderingManager.render(this.customRenderFunction,tt,this.renderParticles,this.renderSprites);for(var ft=0,lt=$._afterRenderTargetDrawStage;ft<lt.length;ft++){var at=lt[ft];at.action(this,e,c)}var ht=this._texture.generateMipMaps;this._texture.generateMipMaps=!1,this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(b=this._renderTarget)!==null&&b!==void 0?b:void 0,e,this._postProcesses,this.ignoreCameraViewport):o&&$.postProcessManager._finalizeFrame(!1,(k=this._renderTarget)!==null&&k!==void 0?k:void 0,e),this._texture.generateMipMaps=ht,this._doNotChangeAspectRatio||$.updateTransformMatrix(!0),s&&Tools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),_e)}this.unbindFrameBuffer(_e,e),this.isCube&&e===5&&_e.generateMipMapsForCubemap(this._texture),(j=_e._debugPopGroup)===null||j===void 0||j.call(_e,1)}}},i.prototype.setRenderingOrder=function(e,o,s,c){o===void 0&&(o=null),s===void 0&&(s=null),c===void 0&&(c=null),this._renderingManager.setRenderingOrder(e,o,s,c)},i.prototype.setRenderingAutoClearDepthStencil=function(e,o){this._renderingManager.setRenderingAutoClearDepthStencil(e,o),this._renderingManager._useSceneAutoClearSetup=!1},i.prototype.clone=function(){var e=this.getSize(),o=new i(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return o.hasAlpha=this.hasAlpha,o.level=this.level,o.coordinatesMode=this.coordinatesMode,this.renderList&&(o.renderList=this.renderList.slice(0)),o},i.prototype.serialize=function(){if(!this.name)return null;var e=a.prototype.serialize.call(this);if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(var o=0;o<this.renderList.length;o++)e.renderList.push(this.renderList[o].id);return e},i.prototype.disposeFramebufferObjects=function(){var e;(e=this._renderTarget)===null||e===void 0||e.dispose(!0)},i.prototype.releaseInternalTexture=function(){var e;(e=this._renderTarget)===null||e===void 0||e.releaseTextures(),this._texture=null},i.prototype.dispose=function(){var e;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;var o=this.getScene();if(!!o){var s=o.customRenderTargets.indexOf(this);s>=0&&o.customRenderTargets.splice(s,1);for(var c=0,d=o.cameras;c<d.length;c++){var _=d[c];s=_.customRenderTargets.indexOf(this),s>=0&&_.customRenderTargets.splice(s,1)}(e=this._renderTarget)===null||e===void 0||e.dispose(),this._renderTarget=null,this._texture=null,a.prototype.dispose.call(this)}},i.prototype._rebuild=function(){this.refreshRate===i.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=i.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},i.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},i.prototype.getViewCount=function(){return 1},i.REFRESHRATE_RENDER_ONCE=0,i.REFRESHRATE_RENDER_ONEVERYFRAME=1,i.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i}(Texture);Texture._CreateRenderTargetTexture=function(a,i,e,o,s){return new RenderTargetTexture(a,i,e,o)};var MultiviewRenderTarget=function(a){__extends(i,a);function i(e,o){o===void 0&&(o=512);var s=a.call(this,"multiview rtt",o,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0)||this,c=e.getEngine().createMultiviewRenderTargetTexture(s.getRenderWidth(),s.getRenderHeight());return s._texture=c.texture,s._texture.isMultiview=!0,s._texture.format=5,s.samples=s._getEngine().getCaps().maxSamples||s.samples,s}return i.prototype._bindFrameBuffer=function(e){!this._renderTarget||this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)},i.prototype.getViewCount=function(){return 2},i}(RenderTargetTexture);Engine.prototype.createMultiviewRenderTargetTexture=function(a,i){var e=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";var o=this._createHardwareRenderTargetWrapper(!1,!1,{width:a,height:i});o._framebuffer=e.createFramebuffer();var s=new InternalTexture(this,InternalTextureSource.Unknown,!0);return s.width=a,s.height=i,o._colorTextureArray=e.createTexture(),e.bindTexture(e.TEXTURE_2D_ARRAY,o._colorTextureArray),e.texStorage3D(e.TEXTURE_2D_ARRAY,1,e.RGBA8,a,i,2),o._depthStencilTextureArray=e.createTexture(),e.bindTexture(e.TEXTURE_2D_ARRAY,o._depthStencilTextureArray),e.texStorage3D(e.TEXTURE_2D_ARRAY,1,e.DEPTH32F_STENCIL8,a,i,2),s.isReady=!0,o.setTextures(s),o};Engine.prototype.bindMultiviewFramebuffer=function(a){var i=a,e=this._gl,o=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(i,void 0,void 0,void 0,!0),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,i._framebuffer),i._colorTextureArray&&i._depthStencilTextureArray)this.getCaps().oculusMultiview?(o.framebufferTextureMultisampleMultiviewOVR(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,i._colorTextureArray,0,i.samples,0,2),o.framebufferTextureMultisampleMultiviewOVR(e.DRAW_FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,i._depthStencilTextureArray,0,i.samples,0,2)):(o.framebufferTextureMultiviewOVR(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,i._colorTextureArray,0,0,2),o.framebufferTextureMultiviewOVR(e.DRAW_FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,i._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"};Camera$1.prototype._useMultiviewToSingleView=!1;Camera$1.prototype._multiviewTexture=null;Camera$1.prototype._resizeOrCreateMultiviewTexture=function(a,i){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=a||this._multiviewTexture.getRenderHeight()!=i)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:a,height:i})):this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:a,height:i})};function createMultiviewUbo(a,i){var e=new UniformBuffer(a,void 0,!0,i);return e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.addUniform("view",16),e.addUniform("projection",16),e.addUniform("viewPosition",4),e}var currentCreateSceneUniformBuffer=Scene.prototype.createSceneUniformBuffer;Scene.prototype._transformMatrixR=Matrix.Zero();Scene.prototype._multiviewSceneUbo=null;Scene.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=createMultiviewUbo(this.getEngine(),"scene_multiview")};Scene.prototype.createSceneUniformBuffer=function(a){return this._multiviewSceneUbo?createMultiviewUbo(this.getEngine(),a):currentCreateSceneUniformBuffer.bind(this)(a)};Scene.prototype._updateMultiviewUbo=function(a,i){a&&i&&a.multiplyToRef(i,this._transformMatrixR),a&&i&&(a.multiplyToRef(i,TmpVectors.Matrix[0]),Frustum.GetRightPlaneToRef(TmpVectors.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))};Scene.prototype._renderMultiviewToSingleView=function(a){a._resizeOrCreateMultiviewTexture(a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.width>0?a._rigPostProcess.width:this.getEngine().getRenderWidth(!0),a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.height>0?a._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),a.outputRenderTarget=a._multiviewTexture,this._renderForCamera(a),a.outputRenderTarget=null;for(var i=0;i<a._rigCameras.length;i++){var e=this.getEngine();this._activeCamera=a._rigCameras[i],e.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};ThinEngine.prototype.updateRawTexture=function(a,i,e,o,s,c){if(s===void 0&&(s=null),c===void 0&&(c=0),!!a){var d=this._getRGBABufferInternalSizedFormat(c,e),_=this._getInternalFormat(e),b=this._getWebGLTextureType(c);this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0),this._unpackFlipY(o===void 0?!0:!!o),this._doNotHandleContextLost||(a._bufferView=i,a.format=e,a.type=c,a.invertY=o,a._compression=s),a.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&i?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],a.width,a.height,0,i):this._gl.texImage2D(this._gl.TEXTURE_2D,0,d,a.width,a.height,0,_,b,i),a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0}};ThinEngine.prototype.createRawTexture=function(a,i,e,o,s,c,d,_,b,k){_===void 0&&(_=null),b===void 0&&(b=0);var j=new InternalTexture(this,InternalTextureSource.Raw);j.baseWidth=i,j.baseHeight=e,j.width=i,j.height=e,j.format=o,j.generateMipMaps=s,j.samplingMode=d,j.invertY=c,j._compression=_,j.type=b,this._doNotHandleContextLost||(j._bufferView=a),this.updateRawTexture(j,a,o,c,_,b),this._bindTextureDirectly(this._gl.TEXTURE_2D,j,!0);var $=this._getSamplingParameters(d,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,$.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,$.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(j),j};ThinEngine.prototype.createRawCubeTexture=function(a,i,e,o,s,c,d,_){_===void 0&&(_=null);var b=this._gl,k=new InternalTexture(this,InternalTextureSource.CubeRaw);k.isCube=!0,k.format=e,k.type=o,this._doNotHandleContextLost||(k._bufferViewArray=a);var j=this._getWebGLTextureType(o),$=this._getInternalFormat(e);$===b.RGB&&($=b.RGBA),j===b.FLOAT&&!this._caps.textureFloatLinearFiltering?(s=!1,d=1,Logger$2.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):j===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,d=1,Logger$2.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):j===b.FLOAT&&!this._caps.textureFloatRender?(s=!1,Logger$2.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):j===b.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,Logger$2.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));var _e=i,et=_e;k.width=_e,k.height=et;var tt=!this.needPOTTextures||Tools.IsExponentOfTwo(k.width)&&Tools.IsExponentOfTwo(k.height);tt||(s=!1),a&&this.updateRawCubeTexture(k,a,e,o,c,_),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,k,!0),a&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);var rt=this._getSamplingParameters(d,s);return b.texParameteri(b.TEXTURE_CUBE_MAP,b.TEXTURE_MAG_FILTER,rt.mag),b.texParameteri(b.TEXTURE_CUBE_MAP,b.TEXTURE_MIN_FILTER,rt.min),b.texParameteri(b.TEXTURE_CUBE_MAP,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_CUBE_MAP,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),this._bindTextureDirectly(b.TEXTURE_CUBE_MAP,null),k.generateMipMaps=s,k.samplingMode=d,k};ThinEngine.prototype.updateRawCubeTexture=function(a,i,e,o,s,c,d){c===void 0&&(c=null),d===void 0&&(d=0),a._bufferViewArray=i,a.format=e,a.type=o,a.invertY=s,a._compression=c;var _=this._gl,b=this._getWebGLTextureType(o),k=this._getInternalFormat(e),j=this._getRGBABufferInternalSizedFormat(o),$=!1;k===_.RGB&&(k=_.RGBA,$=!0),this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,a,!0),this._unpackFlipY(s===void 0?!0:!!s),a.width%4!==0&&_.pixelStorei(_.UNPACK_ALIGNMENT,1);for(var _e=0;_e<6;_e++){var et=i[_e];c?_.compressedTexImage2D(_.TEXTURE_CUBE_MAP_POSITIVE_X+_e,d,this.getCaps().s3tc[c],a.width,a.height,0,et):($&&(et=_convertRGBtoRGBATextureData$1(et,a.width,a.height,o)),_.texImage2D(_.TEXTURE_CUBE_MAP_POSITIVE_X+_e,d,j,a.width,a.height,0,k,b,et))}var tt=!this.needPOTTextures||Tools.IsExponentOfTwo(a.width)&&Tools.IsExponentOfTwo(a.height);tt&&a.generateMipMaps&&d===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),a.isReady=!0};ThinEngine.prototype.createRawCubeTextureFromUrl=function(a,i,e,o,s,c,d,_,b,k,j,$){var _e=this;b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=3),$===void 0&&($=!1);var et=this._gl,tt=this.createRawCubeTexture(null,e,o,s,!c,$,j,null);i==null||i._addPendingData(tt),tt.url=a,this._internalTexturesCache.push(tt);var rt=function(nt,ot){i==null||i._removePendingData(tt),k&&nt&&k(nt.status+" "+nt.statusText,ot)},it=function(nt){var ot=tt.width,at=d(nt);if(!!at){if(_){var st=_e._getWebGLTextureType(s),ut=_e._getInternalFormat(o),ft=_e._getRGBABufferInternalSizedFormat(s),lt=!1;ut===et.RGB&&(ut=et.RGBA,lt=!0),_e._bindTextureDirectly(et.TEXTURE_CUBE_MAP,tt,!0),_e._unpackFlipY(!1);for(var ht=_(at),pt=0;pt<ht.length;pt++)for(var mt=ot>>pt,dt=0;dt<6;dt++){var gt=ht[pt][dt];lt&&(gt=_convertRGBtoRGBATextureData$1(gt,mt,mt,s)),et.texImage2D(dt,pt,ft,mt,mt,0,ut,st,gt)}_e._bindTextureDirectly(et.TEXTURE_CUBE_MAP,null)}else _e.updateRawCubeTexture(tt,at,o,s,$);tt.isReady=!0,i==null||i._removePendingData(tt),b&&b()}};return this._loadFile(a,function(nt){it(nt)},void 0,i==null?void 0:i.offlineProvider,!0,rt),tt};function _convertRGBtoRGBATextureData$1(a,i,e,o){var s,c=1;o===1?s=new Float32Array(i*e*4):o===2?(s=new Uint16Array(i*e*4),c=15360):o===7?s=new Uint32Array(i*e*4):s=new Uint8Array(i*e*4);for(var d=0;d<i;d++)for(var _=0;_<e;_++){var b=(_*i+d)*3,k=(_*i+d)*4;s[k+0]=a[b+0],s[k+1]=a[b+1],s[k+2]=a[b+2],s[k+3]=c}return s}function _makeCreateRawTextureFunction(a){return function(i,e,o,s,c,d,_,b,k,j){k===void 0&&(k=null),j===void 0&&(j=0);var $=a?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,_e=a?InternalTextureSource.Raw3D:InternalTextureSource.Raw2DArray,et=new InternalTexture(this,_e);et.baseWidth=e,et.baseHeight=o,et.baseDepth=s,et.width=e,et.height=o,et.depth=s,et.format=c,et.type=j,et.generateMipMaps=d,et.samplingMode=b,a?et.is3D=!0:et.is2DArray=!0,this._doNotHandleContextLost||(et._bufferView=i),a?this.updateRawTexture3D(et,i,c,_,k,j):this.updateRawTexture2DArray(et,i,c,_,k,j),this._bindTextureDirectly($,et,!0);var tt=this._getSamplingParameters(b,d);return this._gl.texParameteri($,this._gl.TEXTURE_MAG_FILTER,tt.mag),this._gl.texParameteri($,this._gl.TEXTURE_MIN_FILTER,tt.min),d&&this._gl.generateMipmap($),this._bindTextureDirectly($,null),this._internalTexturesCache.push(et),et}}ThinEngine.prototype.createRawTexture2DArray=_makeCreateRawTextureFunction(!1);ThinEngine.prototype.createRawTexture3D=_makeCreateRawTextureFunction(!0);function _makeUpdateRawTextureFunction(a){return function(i,e,o,s,c,d){c===void 0&&(c=null),d===void 0&&(d=0);var _=a?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,b=this._getWebGLTextureType(d),k=this._getInternalFormat(o),j=this._getRGBABufferInternalSizedFormat(d,o);this._bindTextureDirectly(_,i,!0),this._unpackFlipY(s===void 0?!0:!!s),this._doNotHandleContextLost||(i._bufferView=e,i.format=o,i.invertY=s,i._compression=c),i.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),c&&e?this._gl.compressedTexImage3D(_,0,this.getCaps().s3tc[c],i.width,i.height,i.depth,0,e):this._gl.texImage3D(_,0,j,i.width,i.height,i.depth,0,k,b,e),i.generateMipMaps&&this._gl.generateMipmap(_),this._bindTextureDirectly(_,null),i.isReady=!0}}ThinEngine.prototype.updateRawTexture2DArray=_makeUpdateRawTextureFunction(!1);ThinEngine.prototype.updateRawTexture3D=_makeUpdateRawTextureFunction(!0);ThinEngine.prototype.createDynamicTexture=function(a,i,e,o){var s=new InternalTexture(this,InternalTextureSource.Dynamic);return s.baseWidth=a,s.baseHeight=i,e&&(a=this.needPOTTextures?ThinEngine.GetExponentOfTwo(a,this._caps.maxTextureSize):a,i=this.needPOTTextures?ThinEngine.GetExponentOfTwo(i,this._caps.maxTextureSize):i),s.width=a,s.height=i,s.isReady=!1,s.generateMipMaps=e,s.samplingMode=o,this.updateTextureSamplingMode(o,s),this._internalTexturesCache.push(s),s};ThinEngine.prototype.updateDynamicTexture=function(a,i,e,o,s,c,d){if(o===void 0&&(o=!1),c===void 0&&(c=!1),!!a){var _=this._gl,b=_.TEXTURE_2D,k=this._bindTextureDirectly(b,a,!0,c);this._unpackFlipY(e===void 0?a.invertY:e),o&&_.pixelStorei(_.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var j=this._getWebGLTextureType(a.type),$=this._getInternalFormat(s||a.format),_e=this._getRGBABufferInternalSizedFormat(a.type,$);_.texImage2D(b,0,_e,$,j,i),a.generateMipMaps&&_.generateMipmap(b),k||this._bindTextureDirectly(b,null),o&&_.pixelStorei(_.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),a.isReady=!0}};ThinEngine.prototype.createExternalTexture=function(a){return null};ThinEngine.prototype.setExternalTexture=function(a,i){throw new Error("setExternalTexture: This engine does not support external textures!")};ThinEngine.prototype.updateVideoTexture=function(a,i,e){if(!(!a||a._isDisabled)){var o=this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0);this._unpackFlipY(!e);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,i),this._gl.getError()!==0?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,i);else{if(!a._workingCanvas){a._workingCanvas=this.createCanvas(a.width,a.height);var s=a._workingCanvas.getContext("2d");if(!s)throw new Error("Unable to get 2d context");a._workingContext=s,a._workingCanvas.width=a.width,a._workingCanvas.height=a.height}a._workingContext.clearRect(0,0,a.width,a.height),a._workingContext.drawImage(i,0,0,i.videoWidth,i.videoHeight,0,0,a.width,a.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,a._workingCanvas)}a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),o||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0}catch{a._isDisabled=!0}}};ThinEngine.prototype.restoreSingleAttachment=function(){var a=this._gl;this.bindAttachments([a.BACK])};ThinEngine.prototype.restoreSingleAttachmentForRenderTarget=function(){var a=this._gl;this.bindAttachments([a.COLOR_ATTACHMENT0])};ThinEngine.prototype.buildTextureLayout=function(a){for(var i=this._gl,e=[],o=0;o<a.length;o++)a[o]?e.push(i["COLOR_ATTACHMENT"+o]):e.push(i.NONE);return e};ThinEngine.prototype.bindAttachments=function(a){var i=this._gl;i.drawBuffers(a)};ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer=function(a,i,e){i===void 0&&(i=!1),this._currentRenderTarget=null;var o=this._gl,s=a._attachments,c=s.length;if(a._MSAAFramebuffer){o.bindFramebuffer(o.READ_FRAMEBUFFER,a._MSAAFramebuffer),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,a._framebuffer);for(var d=0;d<c;d++){for(var _=a.textures[d],b=0;b<c;b++)s[b]=o.NONE;s[d]=o[this.webGLVersion>1?"COLOR_ATTACHMENT"+d:"COLOR_ATTACHMENT"+d+"_WEBGL"],o.readBuffer(s[d]),o.drawBuffers(s),o.blitFramebuffer(0,0,_.width,_.height,0,0,_.width,_.height,o.COLOR_BUFFER_BIT,o.NEAREST)}for(var d=0;d<c;d++)s[d]=o[this.webGLVersion>1?"COLOR_ATTACHMENT"+d:"COLOR_ATTACHMENT"+d+"_WEBGL"];o.drawBuffers(s)}for(var d=0;d<c;d++){var _=a.textures[d];_.generateMipMaps&&!i&&!_.isCube&&(this._bindTextureDirectly(o.TEXTURE_2D,_,!0),o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null))}e&&(a._MSAAFramebuffer&&this._bindUnboundFramebuffer(a._framebuffer),e()),this._bindUnboundFramebuffer(null)};ThinEngine.prototype.createMultipleRenderTarget=function(a,i,e){e===void 0&&(e=!0);var o=!1,s=!0,c=!1,d=!1,_=15,b=1,k=0,j=3,$=new Array,_e=new Array,et=this._createHardwareRenderTargetWrapper(!0,!1,a);i!==void 0&&(o=i.generateMipMaps===void 0?!1:i.generateMipMaps,s=i.generateDepthBuffer===void 0?!0:i.generateDepthBuffer,c=i.generateStencilBuffer===void 0?!1:i.generateStencilBuffer,d=i.generateDepthTexture===void 0?!1:i.generateDepthTexture,b=i.textureCount||1,i.types&&($=i.types),i.samplingModes&&(_e=i.samplingModes),this.webGLVersion>1&&(i.depthTextureFormat===13||i.depthTextureFormat===16||i.depthTextureFormat===14)&&(_=i.depthTextureFormat));var tt=this._gl,rt=tt.createFramebuffer();this._bindUnboundFramebuffer(rt);var it=a.width||a,nt=a.height||a,ot=[],at=[],st=this.webGLVersion>1&&d&&i.depthTextureFormat===13,ut=this._setupFramebufferDepthAttachments(!st&&c,!d&&s,it,nt);et._framebuffer=rt,et._depthStencilBuffer=ut,et._generateDepthBuffer=!d&&s,et._generateStencilBuffer=!st&&c,et._attachments=at;for(var ft=0;ft<b;ft++){var lt=_e[ft]||j,ht=$[ft]||k;(ht===1&&!this._caps.textureFloatLinearFiltering||ht===2&&!this._caps.textureHalfFloatLinearFiltering)&&(lt=1);var pt=this._getSamplingParameters(lt,o);ht===1&&!this._caps.textureFloat&&(ht=0,Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));var mt=new InternalTexture(this,InternalTextureSource.MultiRenderTarget),dt=tt[this.webGLVersion>1?"COLOR_ATTACHMENT"+ft:"COLOR_ATTACHMENT"+ft+"_WEBGL"];ot.push(mt),at.push(dt),tt.activeTexture(tt["TEXTURE"+ft]),tt.bindTexture(tt.TEXTURE_2D,mt._hardwareTexture.underlyingResource),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_MAG_FILTER,pt.mag),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_MIN_FILTER,pt.min),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_WRAP_S,tt.CLAMP_TO_EDGE),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_WRAP_T,tt.CLAMP_TO_EDGE),tt.texImage2D(tt.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(ht),it,nt,0,tt.RGBA,this._getWebGLTextureType(ht),null),tt.framebufferTexture2D(tt.DRAW_FRAMEBUFFER,dt,tt.TEXTURE_2D,mt._hardwareTexture.underlyingResource,0),o&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(tt.TEXTURE_2D,null),mt.baseWidth=it,mt.baseHeight=nt,mt.width=it,mt.height=nt,mt.isReady=!0,mt.samples=1,mt.generateMipMaps=o,mt.samplingMode=lt,mt.type=ht,this._internalTexturesCache.push(mt)}if(d&&this._caps.depthTextureExtension){var gt=new InternalTexture(this,InternalTextureSource.Depth),_t=5,yt=tt.DEPTH_COMPONENT16,Tt=tt.DEPTH_COMPONENT,St=tt.UNSIGNED_SHORT,At=tt.DEPTH_ATTACHMENT;this.webGLVersion<2?yt=tt.DEPTH_COMPONENT:_===14?(_t=1,St=tt.FLOAT,yt=tt.DEPTH_COMPONENT32F):_===16?(_t=0,St=tt.UNSIGNED_INT,yt=tt.DEPTH_COMPONENT24,At=tt.DEPTH_ATTACHMENT):_===13&&(_t=12,St=tt.UNSIGNED_INT_24_8,yt=tt.DEPTH24_STENCIL8,Tt=tt.DEPTH_STENCIL,At=tt.DEPTH_STENCIL_ATTACHMENT),tt.activeTexture(tt.TEXTURE0),tt.bindTexture(tt.TEXTURE_2D,gt._hardwareTexture.underlyingResource),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_MAG_FILTER,tt.NEAREST),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_MIN_FILTER,tt.NEAREST),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_WRAP_S,tt.CLAMP_TO_EDGE),tt.texParameteri(tt.TEXTURE_2D,tt.TEXTURE_WRAP_T,tt.CLAMP_TO_EDGE),tt.texImage2D(tt.TEXTURE_2D,0,yt,it,nt,0,Tt,St,null),tt.framebufferTexture2D(tt.FRAMEBUFFER,At,tt.TEXTURE_2D,gt._hardwareTexture.underlyingResource,0),gt.baseWidth=it,gt.baseHeight=nt,gt.width=it,gt.height=nt,gt.isReady=!0,gt.samples=1,gt.generateMipMaps=o,gt.samplingMode=1,gt.format=_,gt.type=_t,ot.push(gt),this._internalTexturesCache.push(gt)}return et.setTextures(ot),e&&tt.drawBuffers(at),this._bindUnboundFramebuffer(null),this.resetTextureCache(),et};ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(a,i,e){if(e===void 0&&(e=!0),this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===i)return i;var o=a._attachments.length;if(o===0)return 1;var s=this._gl;i=Math.min(i,this.getCaps().maxMSAASamples),a._depthStencilBuffer&&(s.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(s.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null);for(var c=0;c<o;c++){var d=a.textures[c]._hardwareTexture;d!=null&&d._MSAARenderBuffer&&(s.deleteRenderbuffer(d._MSAARenderBuffer),d._MSAARenderBuffer=null)}if(i>1&&s.renderbufferStorageMultisample){var _=s.createFramebuffer();if(!_)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=_,this._bindUnboundFramebuffer(_);for(var b=[],c=0;c<o;c++){var k=a.textures[c],d=k._hardwareTexture,j=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+c:"COLOR_ATTACHMENT"+c+"_WEBGL"],$=this._createRenderBuffer(k.width,k.height,i,-1,this._getRGBAMultiSampleBufferFormat(k.type),j);if(!$)throw new Error("Unable to create multi sampled framebuffer");d._MSAARenderBuffer=$,k.samples=i,b.push(j)}e&&s.drawBuffers(b)}else this._bindUnboundFramebuffer(a._framebuffer);return a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,i),this._bindUnboundFramebuffer(null),i};ThinEngine.prototype._createDepthStencilCubeTexture=function(a,i,e){var o=new InternalTexture(this,InternalTextureSource.DepthStencil);if(o.isCube=!0,this.webGLVersion===1)return Logger$2.Error("Depth cube texture is not supported by WebGL 1."),o;var s=__assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},i),c=this._gl;this._bindTextureDirectly(c.TEXTURE_CUBE_MAP,o,!0),this._setupDepthStencilTexture(o,a,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),e._depthStencilTexture=o,e._depthStencilTextureWithStencil=s.generateStencil;for(var d=0;d<6;d++)s.generateStencil?c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+d,0,c.DEPTH24_STENCIL8,a,a,0,c.DEPTH_STENCIL,c.UNSIGNED_INT_24_8,null):c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+d,0,c.DEPTH_COMPONENT24,a,a,0,c.DEPTH_COMPONENT,c.UNSIGNED_INT,null);return this._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(o),o};ThinEngine.prototype._partialLoadFile=function(a,i,e,o,s){s===void 0&&(s=null);var c=function(_){e[i]=_,e._internalCount++,e._internalCount===6&&o(e)},d=function(_,b){s&&_&&s(_.status+" "+_.statusText,b)};this._loadFile(a,c,void 0,void 0,!0,d)};ThinEngine.prototype._cascadeLoadFiles=function(a,i,e,o){o===void 0&&(o=null);var s=[];s._internalCount=0;for(var c=0;c<6;c++)this._partialLoadFile(e[c],c,s,i,o)};ThinEngine.prototype._cascadeLoadImgs=function(a,i,e,o,s,c){s===void 0&&(s=null);var d=[];d._internalCount=0;for(var _=0;_<6;_++)this._partialLoadImg(o[_],_,d,a,i,e,s,c)};ThinEngine.prototype._partialLoadImg=function(a,i,e,o,s,c,d,_){d===void 0&&(d=null);var b=RandomGUID(),k=function($){e[i]=$,e._internalCount++,o&&o._removePendingData(b),e._internalCount===6&&c&&c(s,e)},j=function($,_e){o&&o._removePendingData(b),d&&d($,_e)};LoadImage(a,k,j,o?o.offlineProvider:null,_),o&&o._addPendingData(b)};ThinEngine.prototype._setCubeMapTextureParams=function(a,i){var e=this._gl;e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MIN_FILTER,i?e.LINEAR_MIPMAP_LINEAR:e.LINEAR),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),a.samplingMode=i?3:2,this._bindTextureDirectly(e.TEXTURE_CUBE_MAP,null)};ThinEngine.prototype.createCubeTextureBase=function(a,i,e,o,s,c,d,_,b,k,j,$,_e,et,tt){var rt=this;s===void 0&&(s=null),c===void 0&&(c=null),_===void 0&&(_=null),b===void 0&&(b=!1),k===void 0&&(k=0),j===void 0&&(j=0),$===void 0&&($=null),_e===void 0&&(_e=null),et===void 0&&(et=null),tt===void 0&&(tt=!1);var it=$||new InternalTexture(this,InternalTextureSource.Cube);it.isCube=!0,it.url=a,it.generateMipMaps=!o,it._lodGenerationScale=k,it._lodGenerationOffset=j,it._useSRGBBuffer=!!tt&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!o),this._doNotHandleContextLost||(it._extension=_,it._files=e);var nt=a;this._transformTextureUrl&&!$&&(a=this._transformTextureUrl(a));for(var ot=a.lastIndexOf("."),at=_||(ot>-1?a.substring(ot).toLowerCase():""),st=null,ut=0,ft=ThinEngine._TextureLoaders;ut<ft.length;ut++){var lt=ft[ut];if(lt.canLoad(at)){st=lt;break}}var ht=function(mt,dt){a===nt?c&&mt&&c(mt.status+" "+mt.statusText,dt):(Logger$2.Warn("Failed to load "+a+", falling back to the "+nt),rt.createCubeTextureBase(nt,i,e,!!o,s,c,d,_,b,k,j,it,_e,et,tt))};if(st){var pt=function(mt){_e&&_e(it,mt),st.loadCubeData(mt,it,b,s,c)};e&&e.length===6?st.supportCascades?this._cascadeLoadFiles(i,function(mt){return pt(mt.map(function(dt){return new Uint8Array(dt)}))},e,c):c?c("Textures type does not support cascades."):Logger$2.Warn("Texture loader does not support cascades."):this._loadFile(a,function(mt){return pt(new Uint8Array(mt))},void 0,void 0,!0,ht)}else{if(!e)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(i,it,function(mt,dt){et&&et(mt,dt)},e,c)}return this._internalTexturesCache.push(it),it};ThinEngine.prototype.createCubeTexture=function(a,i,e,o,s,c,d,_,b,k,j,$,_e,et){var tt=this;s===void 0&&(s=null),c===void 0&&(c=null),_===void 0&&(_=null),b===void 0&&(b=!1),k===void 0&&(k=0),j===void 0&&(j=0),$===void 0&&($=null),et===void 0&&(et=!1);var rt=this._gl;return this.createCubeTextureBase(a,i,e,!!o,s,c,d,_,b,k,j,$,function(it,nt){return tt._bindTextureDirectly(rt.TEXTURE_CUBE_MAP,it,!0)},function(it,nt){var ot=tt.needPOTTextures?ThinEngine.GetExponentOfTwo(nt[0].width,tt._caps.maxCubemapTextureSize):nt[0].width,at=ot,st=[rt.TEXTURE_CUBE_MAP_POSITIVE_X,rt.TEXTURE_CUBE_MAP_POSITIVE_Y,rt.TEXTURE_CUBE_MAP_POSITIVE_Z,rt.TEXTURE_CUBE_MAP_NEGATIVE_X,rt.TEXTURE_CUBE_MAP_NEGATIVE_Y,rt.TEXTURE_CUBE_MAP_NEGATIVE_Z];tt._bindTextureDirectly(rt.TEXTURE_CUBE_MAP,it,!0),tt._unpackFlipY(!1);var ut=d?tt._getInternalFormat(d,it._useSRGBBuffer):it._useSRGBBuffer?rt.SRGB8_ALPHA8:rt.RGBA,ft=d?tt._getInternalFormat(d):rt.RGBA;it._useSRGBBuffer&&tt.webGLVersion===1&&(ft=ut);for(var lt=0;lt<st.length;lt++)if(nt[lt].width!==ot||nt[lt].height!==at){if(tt._prepareWorkingCanvas(),!tt._workingCanvas||!tt._workingContext){Logger$2.Warn("Cannot create canvas to resize texture.");return}tt._workingCanvas.width=ot,tt._workingCanvas.height=at,tt._workingContext.drawImage(nt[lt],0,0,nt[lt].width,nt[lt].height,0,0,ot,at),rt.texImage2D(st[lt],0,ut,ft,rt.UNSIGNED_BYTE,tt._workingCanvas)}else rt.texImage2D(st[lt],0,ut,ft,rt.UNSIGNED_BYTE,nt[lt]);o||rt.generateMipmap(rt.TEXTURE_CUBE_MAP),tt._setCubeMapTextureParams(it,!o),it.width=ot,it.height=at,it.isReady=!0,d&&(it.format=d),it.onLoadedObservable.notifyObservers(it),it.onLoadedObservable.clear(),s&&s()},!!et)};ThinEngine.prototype.setTextureSampler=function(a,i){throw new Error("setTextureSampler: This engine does not support separate texture sampler objects!")};Object.defineProperty(Engine.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0});Engine.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new Observable,this.onVRRequestPresentComplete=new Observable,this.onVRRequestPresentStart=new Observable};Engine.prototype.isVRDevicePresent=function(){return!!this._vrDisplay};Engine.prototype.getVRDevice=function(){return this._vrDisplay};Engine.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable};Engine.prototype.initWebVRAsync=function(){var a=this,i=function(){var o={vrDisplay:a._vrDisplay,vrSupported:a._vrSupported};a.onVRDisplayChangedObservable.notifyObservers(o),a._webVRInitPromise=new Promise(function(s){s(o)})};if(!this._onVrDisplayConnect){this._onVrDisplayConnect=function(o){a._vrDisplay=o.display,i()},this._onVrDisplayDisconnect=function(){a._vrDisplay.cancelAnimationFrame(a._frameHandler),a._vrDisplay=void 0,a._frameHandler=Engine.QueueNewFrame(a._boundRenderFunction),i()},this._onVrDisplayPresentChange=function(){a._vrExclusivePointerMode=a._vrDisplay&&a._vrDisplay.isPresenting};var e=this.getHostWindow();e&&(e.addEventListener("vrdisplayconnect",this._onVrDisplayConnect),e.addEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),e.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange))}return this._webVRInitPromise=this._webVRInitPromise||this._getVRDisplaysAsync(),this._webVRInitPromise.then(i),this._webVRInitPromise};Engine.prototype._getVRDisplaysAsync=function(){var a=this;return new Promise(function(i){navigator.getVRDisplays?navigator.getVRDisplays().then(function(e){a._vrSupported=!0,a._vrDisplay=e[0],i({vrDisplay:a._vrDisplay,vrSupported:a._vrSupported})}):(a._vrDisplay=void 0,a._vrSupported=!1,i({vrDisplay:a._vrDisplay,vrSupported:a._vrSupported}))})};Engine.prototype.enableVR=function(a){var i=this;if(this._vrDisplay&&!this._vrDisplay.isPresenting){var e=function(){i.onVRRequestPresentComplete.notifyObservers(!0),i._onVRFullScreenTriggered()},o=function(){i.onVRRequestPresentComplete.notifyObservers(!1)};this.onVRRequestPresentStart.notifyObservers(this);var s={highRefreshRate:this.vrPresentationAttributes?this.vrPresentationAttributes.highRefreshRate:!1,foveationLevel:this.vrPresentationAttributes?this.vrPresentationAttributes.foveationLevel:1,multiview:(this.getCaps().multiview||this.getCaps().oculusMultiview)&&a.useMultiview};this._vrDisplay.requestPresent([__assign({source:this.getRenderingCanvas(),attributes:s},s)]).then(e).catch(o)}};Engine.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new Size(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();var a=this._vrDisplay.getEyeParameters("left");this.setHardwareScalingLevel(1),this.setSize(a.renderWidth*2,a.renderHeight)}else this.setHardwareScalingLevel(this._oldHardwareScaleFactor),this.setSize(this._oldSize.width,this._oldSize.height)};Engine.prototype.disableVR=function(){var a=this;this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then(function(){return a._onVRFullScreenTriggered()}).catch(function(){return a._onVRFullScreenTriggered()}),IsWindowObjectExist()&&(window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null))};Engine.prototype._connectVREvents=function(a,i){var e=this;if(this._onVRDisplayPointerRestricted=function(){a&&a.requestPointerLock()},this._onVRDisplayPointerUnrestricted=function(){if(!i){var s=e.getHostWindow();s.document&&s.document.exitPointerLock&&s.document.exitPointerLock();return}!i.exitPointerLock||i.exitPointerLock()},IsWindowObjectExist()){var o=this.getHostWindow();o.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),o.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}};Engine.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(a){Tools.Warn("webVR submitFrame has had an unexpected failure: "+a)}};Engine.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting};Engine.prototype._requestVRFrame=function(){this._frameHandler=Engine.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)};Engine.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()};Engine.prototype.registerView=function(a,i,e){var o=this;this.views||(this.views=[]);for(var s=0,c=this.views;s<c.length;s++){var d=c[s];if(d.target===a)return d}var _=this.getRenderingCanvas();_&&(a.width=_.width,a.height=_.height);var b={target:a,camera:i,clearBeforeCopy:e,enabled:!0};return this.views.push(b),i&&i.onDisposeObservable.add(function(){o.unRegisterView(a)}),b};Engine.prototype.unRegisterView=function(a){if(!this.views)return this;for(var i=0,e=this.views;i<e.length;i++){var o=e[i];if(o.target===a){var s=this.views.indexOf(o);s!==-1&&this.views.splice(s,1);break}}return this};Engine.prototype._renderViews=function(){if(!this.views)return!1;var a=this.getRenderingCanvas();if(!a)return!1;for(var i=0,e=this.views;i<e.length;i++){var o=e[i];if(!!o.enabled){var s=o.target,c=s.getContext("2d");if(!!c){var d=o.camera,_=null,b=null;if(d){if(b=d.getScene(),b.activeCameras&&b.activeCameras.length)continue;this.activeView=o,_=b.activeCamera,b.activeCamera=d}if(o.customResize)o.customResize(s);else{var k=Math.floor(s.clientWidth/this._hardwareScalingLevel),j=Math.floor(s.clientHeight/this._hardwareScalingLevel),$=k!==s.width||a.width!==s.width||j!==s.height||a.height!==s.height;s.clientWidth&&s.clientHeight&&$&&(s.width=k,s.height=j,this.setSize(k,j))}if(!a.width||!a.height)return!1;this._renderFrame(),this.flushFramebuffer(),o.clearBeforeCopy&&c.clearRect(0,0,a.width,a.height),c.drawImage(a,0,0),_&&b&&(b.activeCamera=_)}}}return this.activeView=null,!0};var ComputeBindingType;(function(a){a[a.Texture=0]="Texture",a[a.StorageTexture=1]="StorageTexture",a[a.UniformBuffer=2]="UniformBuffer",a[a.StorageBuffer=3]="StorageBuffer",a[a.TextureWithoutSampler=4]="TextureWithoutSampler",a[a.Sampler=5]="Sampler"})(ComputeBindingType||(ComputeBindingType={}));ThinEngine.prototype.createComputeEffect=function(a,i){throw new Error("createComputeEffect: This engine does not support compute shaders!")};ThinEngine.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};ThinEngine.prototype.createComputeContext=function(){};ThinEngine.prototype.computeDispatch=function(a,i,e,o,s,c,d){throw new Error("computeDispatch: This engine does not support compute shaders!")};ThinEngine.prototype.areAllComputeEffectsReady=function(){return!0};ThinEngine.prototype.releaseComputeEffects=function(){};ThinEngine.prototype._prepareComputePipelineContext=function(a,i,e,o,s){};ThinEngine.prototype._rebuildComputeEffects=function(){};ThinEngine.prototype._executeWhenComputeStateIsCompiled=function(a,i){i()};ThinEngine.prototype._releaseComputeEffect=function(a){};ThinEngine.prototype._deleteComputePipelineContext=function(a){};ThinEngine.prototype.createStorageBuffer=function(a,i){throw new Error("createStorageBuffer: Unsupported method in this engine!")};ThinEngine.prototype.updateStorageBuffer=function(a,i,e,o){};ThinEngine.prototype.readFromStorageBuffer=function(a,i,e,o){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")};ThinEngine.prototype.setStorageBuffer=function(a,i){throw new Error("setStorageBuffer: Unsupported method in this engine!")};function transformTextureUrl(a){var i=function(c){var d="\\b"+c+"\\b";return a&&(a===c||a.match(new RegExp(d,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(i))return a;var e=a.lastIndexOf("."),o=a.lastIndexOf("?"),s=o>-1?a.substring(o,a.length):"";return(e>-1?a.substring(0,e):a)+this._textureFormatInUse+s}Object.defineProperty(Engine.prototype,"texturesSupported",{get:function(){var a=new Array;return this._caps.astc&&a.push("-astc.ktx"),this._caps.s3tc&&a.push("-dxt.ktx"),this._caps.pvrtc&&a.push("-pvrtc.ktx"),this._caps.etc2&&a.push("-etc2.ktx"),this._caps.etc1&&a.push("-etc1.ktx"),a},enumerable:!0,configurable:!0});Object.defineProperty(Engine.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});Engine.prototype.setCompressedTextureExclusions=function(a){this._excludedCompressedTextures=a};Engine.prototype.setTextureFormatToUse=function(a){for(var i=this.texturesSupported,e=0,o=i.length;e<o;e++)for(var s=0,c=a.length;s<c;s++)if(i[e]===a[s].toLowerCase())return this._transformTextureUrl=transformTextureUrl.bind(this),this._textureFormatInUse=i[e];return this._textureFormatInUse="",this._transformTextureUrl=null,null};var NativeDataStream=function(){function a(){var i=this,e=new ArrayBuffer(a.DEFAULT_BUFFER_SIZE);this._uint32s=new Uint32Array(e),this._int32s=new Int32Array(e),this._float32s=new Float32Array(e),this._length=a.DEFAULT_BUFFER_SIZE/4,this._position=0,this._nativeDataStream=new _native.NativeDataStream(function(){i._flush()})}return a.prototype.writeUint32=function(i){this._flushIfNecessary(1),this._uint32s[this._position++]=i},a.prototype.writeInt32=function(i){this._flushIfNecessary(1),this._int32s[this._position++]=i},a.prototype.writeFloat32=function(i){this._flushIfNecessary(1),this._float32s[this._position++]=i},a.prototype.writeUint32Array=function(i){this._flushIfNecessary(1+i.length),this._uint32s[this._position++]=i.length,this._uint32s.set(i,this._position),this._position+=i.length},a.prototype.writeInt32Array=function(i){this._flushIfNecessary(1+i.length),this._uint32s[this._position++]=i.length,this._int32s.set(i,this._position),this._position+=i.length},a.prototype.writeFloat32Array=function(i){this._flushIfNecessary(1+i.length),this._uint32s[this._position++]=i.length,this._float32s.set(i,this._position),this._position+=i.length},a.prototype.writeNativeData=function(i){this._flushIfNecessary(i.length),this._uint32s.set(i,this._position),this._position+=i.length},a.prototype.writeBoolean=function(i){this.writeUint32(i?1:0)},a.prototype._flushIfNecessary=function(i){this._position+i>this._length&&this._flush()},a.prototype._flush=function(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0},a.DEFAULT_BUFFER_SIZE=65536,a}(),Orientation;(function(a){a[a.CW=0]="CW",a[a.CCW=1]="CCW"})(Orientation||(Orientation={}));var BezierCurve=function(){function a(){}return a.Interpolate=function(i,e,o,s,c){for(var d=1-3*s+3*e,_=3*s-6*e,b=3*e,k=i,j=0;j<5;j++){var $=k*k,_e=$*k,et=d*_e+_*$+b*k,tt=1/(3*d*$+2*_*k+b);k-=(et-i)*tt,k=Math.min(1,Math.max(0,k))}return 3*Math.pow(1-k,2)*k*o+3*(1-k)*Math.pow(k,2)*c+Math.pow(k,3)},a}(),Angle=function(){function a(i){this._radians=i,this._radians<0&&(this._radians+=2*Math.PI)}return a.prototype.degrees=function(){return this._radians*180/Math.PI},a.prototype.radians=function(){return this._radians},a.BetweenTwoPoints=function(i,e){var o=e.subtract(i),s=Math.atan2(o.y,o.x);return new a(s)},a.FromRadians=function(i){return new a(i)},a.FromDegrees=function(i){return new a(i*Math.PI/180)},a}(),Arc2=function(){function a(i,e,o){this.startPoint=i,this.midPoint=e,this.endPoint=o;var s=Math.pow(e.x,2)+Math.pow(e.y,2),c=(Math.pow(i.x,2)+Math.pow(i.y,2)-s)/2,d=(s-Math.pow(o.x,2)-Math.pow(o.y,2))/2,_=(i.x-e.x)*(e.y-o.y)-(e.x-o.x)*(i.y-e.y);this.centerPoint=new Vector2((c*(e.y-o.y)-d*(i.y-e.y))/_,((i.x-e.x)*d-(e.x-o.x)*c)/_),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Angle.BetweenTwoPoints(this.centerPoint,this.startPoint);var b=this.startAngle.degrees(),k=Angle.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),j=Angle.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();k-b>180&&(k-=360),k-b<-180&&(k+=360),j-k>180&&(j-=360),j-k<-180&&(j+=360),this.orientation=k-b<0?Orientation.CW:Orientation.CCW,this.angle=Angle.FromDegrees(this.orientation===Orientation.CW?b-j:j-b)}return a}(),Path2=function(){function a(i,e){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new Vector2(i,e))}return a.prototype.addLineTo=function(i,e){if(this.closed)return this;var o=new Vector2(i,e),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},a.prototype.addArcTo=function(i,e,o,s,c){if(c===void 0&&(c=36),this.closed)return this;var d=this._points[this._points.length-1],_=new Vector2(i,e),b=new Vector2(o,s),k=new Arc2(d,_,b),j=k.angle.radians()/c;k.orientation===Orientation.CW&&(j*=-1);for(var $=k.startAngle.radians()+j,_e=0;_e<c;_e++){var et=Math.cos($)*k.radius+k.centerPoint.x,tt=Math.sin($)*k.radius+k.centerPoint.y;this.addLineTo(et,tt),$+=j}return this},a.prototype.close=function(){return this.closed=!0,this},a.prototype.length=function(){var i=this._length;if(this.closed){var e=this._points[this._points.length-1],o=this._points[0];i+=o.subtract(e).length()}return i},a.prototype.getPoints=function(){return this._points},a.prototype.getPointAtLengthPosition=function(i){if(i<0||i>1)return Vector2.Zero();for(var e=i*this.length(),o=0,s=0;s<this._points.length;s++){var c=(s+1)%this._points.length,d=this._points[s],_=this._points[c],b=_.subtract(d),k=b.length()+o;if(e>=o&&e<=k){var j=b.normalize(),$=e-o;return new Vector2(d.x+j.x*$,d.y+j.y*$)}o=k}return Vector2.Zero()},a.StartingAt=function(i,e){return new a(i,e)},a}(),Path3D=function(){function a(i,e,o,s){e===void 0&&(e=null),s===void 0&&(s=!1),this.path=i,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:Vector3.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:Matrix.Identity()};for(var c=0;c<i.length;c++)this._curve[c]=i[c].clone();this._raw=o||!1,this._alignTangentsWithPath=s,this._compute(e,s)}return a.prototype.getCurve=function(){return this._curve},a.prototype.getPoints=function(){return this._curve},a.prototype.length=function(){return this._distances[this._distances.length-1]},a.prototype.getTangents=function(){return this._tangents},a.prototype.getNormals=function(){return this._normals},a.prototype.getBinormals=function(){return this._binormals},a.prototype.getDistances=function(){return this._distances},a.prototype.getPointAt=function(i){return this._updatePointAtData(i).point},a.prototype.getTangentAt=function(i,e){return e===void 0&&(e=!1),this._updatePointAtData(i,e),e?Vector3.TransformCoordinates(Vector3.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]},a.prototype.getNormalAt=function(i,e){return e===void 0&&(e=!1),this._updatePointAtData(i,e),e?Vector3.TransformCoordinates(Vector3.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]},a.prototype.getBinormalAt=function(i,e){return e===void 0&&(e=!1),this._updatePointAtData(i,e),e?Vector3.TransformCoordinates(Vector3.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]},a.prototype.getDistanceAt=function(i){return this.length()*i},a.prototype.getPreviousPointIndexAt=function(i){return this._updatePointAtData(i),this._pointAtData.previousPointArrayIndex},a.prototype.getSubPositionAt=function(i){return this._updatePointAtData(i),this._pointAtData.subPosition},a.prototype.getClosestPositionTo=function(i){for(var e=Number.MAX_VALUE,o=0,s=0;s<this._curve.length-1;s++){var c=this._curve[s+0],d=this._curve[s+1].subtract(c).normalize(),_=this._distances[s+1]-this._distances[s+0],b=Math.min(Math.max(Vector3.Dot(d,i.subtract(c).normalize()),0)*Vector3.Distance(c,i)/_,1),k=Vector3.Distance(c.add(d.scale(b*_)),i);k<e&&(e=k,o=(this._distances[s+0]+_*b)/this.length())}return o},a.prototype.slice=function(i,e){if(i===void 0&&(i=0),e===void 0&&(e=1),i<0&&(i=1-i*-1%1),e<0&&(e=1-e*-1%1),i>e){var o=i;i=e,e=o}var s=this.getCurve(),c=this.getPointAt(i),d=this.getPreviousPointIndexAt(i),_=this.getPointAt(e),b=this.getPreviousPointIndexAt(e)+1,k=[];return i!==0&&(d++,k.push(c)),k.push.apply(k,s.slice(d,b)),(e!==1||i===1)&&k.push(_),new a(k,this.getNormalAt(i),this._raw,this._alignTangentsWithPath)},a.prototype.update=function(i,e,o){e===void 0&&(e=null),o===void 0&&(o=!1);for(var s=0;s<i.length;s++)this._curve[s].x=i[s].x,this._curve[s].y=i[s].y,this._curve[s].z=i[s].z;return this._compute(e,o),this},a.prototype._compute=function(i,e){e===void 0&&(e=!1);var o=this._curve.length;if(!(o<2)){this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[o-1]=this._curve[o-1].subtract(this._curve[o-2]),this._raw||this._tangents[o-1].normalize();var s=this._tangents[0],c=this._normalVector(s,i);this._normals[0]=c,this._raw||this._normals[0].normalize(),this._binormals[0]=Vector3.Cross(s,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var d,_,b,k,j,$=1;$<o;$++)d=this._getLastNonNullVector($),$<o-1&&(_=this._getFirstNonNullVector($),this._tangents[$]=e?_:d.add(_),this._tangents[$].normalize()),this._distances[$]=this._distances[$-1]+this._curve[$].subtract(this._curve[$-1]).length(),b=this._tangents[$],j=this._binormals[$-1],this._normals[$]=Vector3.Cross(j,b),this._raw||(this._normals[$].length()===0?(k=this._normals[$-1],this._normals[$]=k.clone()):this._normals[$].normalize()),this._binormals[$]=Vector3.Cross(b,this._normals[$]),this._raw||this._binormals[$].normalize();this._pointAtData.id=NaN}},a.prototype._getFirstNonNullVector=function(i){for(var e=1,o=this._curve[i+e].subtract(this._curve[i]);o.length()===0&&i+e+1<this._curve.length;)e++,o=this._curve[i+e].subtract(this._curve[i]);return o},a.prototype._getLastNonNullVector=function(i){for(var e=1,o=this._curve[i].subtract(this._curve[i-e]);o.length()===0&&i>e+1;)e++,o=this._curve[i].subtract(this._curve[i-e]);return o},a.prototype._normalVector=function(i,e){var o,s=i.length();if(s===0&&(s=1),e==null){var c;Scalar.WithinEpsilon(Math.abs(i.y)/s,1,Epsilon)?Scalar.WithinEpsilon(Math.abs(i.x)/s,1,Epsilon)?Scalar.WithinEpsilon(Math.abs(i.z)/s,1,Epsilon)?c=Vector3.Zero():c=new Vector3(0,0,1):c=new Vector3(1,0,0):c=new Vector3(0,-1,0),o=Vector3.Cross(i,c)}else o=Vector3.Cross(i,e),Vector3.CrossToRef(o,i,o);return o.normalize(),o},a.prototype._updatePointAtData=function(i,e){if(e===void 0&&(e=!1),this._pointAtData.id===i)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=i;var o=this.getPoints();if(i<=0)return this._setPointAtData(0,0,o[0],0,e);if(i>=1)return this._setPointAtData(1,1,o[o.length-1],o.length-1,e);for(var s=o[0],c,d=0,_=i*this.length(),b=1;b<o.length;b++){c=o[b];var k=Vector3.Distance(s,c);if(d+=k,d===_)return this._setPointAtData(i,1,c,b,e);if(d>_){var j=d-_,$=j/k,_e=s.subtract(c),et=c.add(_e.scaleInPlace($));return this._setPointAtData(i,1-$,et,b-1,e)}s=c}return this._pointAtData},a.prototype._setPointAtData=function(i,e,o,s,c){return this._pointAtData.point=o,this._pointAtData.position=i,this._pointAtData.subPosition=e,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=c,c&&this._updateInterpolationMatrix(),this._pointAtData},a.prototype._updateInterpolationMatrix=function(){this._pointAtData.interpolationMatrix=Matrix.Identity();var i=this._pointAtData.previousPointArrayIndex;if(i!==this._tangents.length-1){var e=i+1,o=this._tangents[i].clone(),s=this._normals[i].clone(),c=this._binormals[i].clone(),d=this._tangents[e].clone(),_=this._normals[e].clone(),b=this._binormals[e].clone(),k=Quaternion.RotationQuaternionFromAxis(s,c,o),j=Quaternion.RotationQuaternionFromAxis(_,b,d),$=Quaternion.Slerp(k,j,this._pointAtData.subPosition);$.toRotationMatrix(this._pointAtData.interpolationMatrix)}},a}(),Curve3=function(){function a(i){this._length=0,this._points=i,this._length=this._computeLength(i)}return a.CreateQuadraticBezier=function(i,e,o,s){s=s>2?s:3;for(var c=new Array,d=function(b,k,j,$){var _e=(1-b)*(1-b)*k+2*b*(1-b)*j+b*b*$;return _e},_=0;_<=s;_++)c.push(new Vector3(d(_/s,i.x,e.x,o.x),d(_/s,i.y,e.y,o.y),d(_/s,i.z,e.z,o.z)));return new a(c)},a.CreateCubicBezier=function(i,e,o,s,c){c=c>3?c:4;for(var d=new Array,_=function(k,j,$,_e,et){var tt=(1-k)*(1-k)*(1-k)*j+3*k*(1-k)*(1-k)*$+3*k*k*(1-k)*_e+k*k*k*et;return tt},b=0;b<=c;b++)d.push(new Vector3(_(b/c,i.x,e.x,o.x,s.x),_(b/c,i.y,e.y,o.y,s.y),_(b/c,i.z,e.z,o.z,s.z)));return new a(d)},a.CreateHermiteSpline=function(i,e,o,s,c){for(var d=new Array,_=1/c,b=0;b<=c;b++)d.push(Vector3.Hermite(i,e,o,s,b*_));return new a(d)},a.CreateCatmullRomSpline=function(i,e,o){var s=new Array,c=1/e,d=0;if(o){for(var _=i.length,b=0;b<_;b++){d=0;for(var k=0;k<e;k++)s.push(Vector3.CatmullRom(i[b%_],i[(b+1)%_],i[(b+2)%_],i[(b+3)%_],d)),d+=c}s.push(s[0])}else{var j=new Array;j.push(i[0].clone()),Array.prototype.push.apply(j,i),j.push(i[i.length-1].clone());for(var b=0;b<j.length-3;b++){d=0;for(var k=0;k<e;k++)s.push(Vector3.CatmullRom(j[b],j[b+1],j[b+2],j[b+3],d)),d+=c}b--,s.push(Vector3.CatmullRom(j[b],j[b+1],j[b+2],j[b+3],d))}return new a(s)},a.prototype.getPoints=function(){return this._points},a.prototype.length=function(){return this._length},a.prototype.continue=function(i){for(var e=this._points[this._points.length-1],o=this._points.slice(),s=i.getPoints(),c=1;c<s.length;c++)o.push(s[c].subtract(s[0]).add(e));var d=new a(o);return d},a.prototype._computeLength=function(i){for(var e=0,o=1;o<i.length;o++)e+=i[o].subtract(i[o-1]).length();return e},a}(),PositionNormalTextureVertex=function(){function a(i,e,o){i===void 0&&(i=Vector3.Zero()),e===void 0&&(e=Vector3.Up()),o===void 0&&(o=Vector2.Zero()),this.position=i,this.normal=e,this.uv=o}return a.prototype.clone=function(){return new a(this.position.clone(),this.normal.clone(),this.uv.clone())},a}(),SH3ylmBasisConstants=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],SH3ylmBasisTrigonometricTerms=[function(a){return 1},function(a){return a.y},function(a){return a.z},function(a){return a.x},function(a){return a.x*a.y},function(a){return a.y*a.z},function(a){return 3*a.z*a.z-1},function(a){return a.x*a.z},function(a){return a.x*a.x-a.y*a.y}],applySH3=function(a,i){return SH3ylmBasisConstants[a]*SH3ylmBasisTrigonometricTerms[a](i)},SHCosKernelConvolution=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4],SphericalHarmonics=function(){function a(){this.preScaled=!1,this.l00=Vector3.Zero(),this.l1_1=Vector3.Zero(),this.l10=Vector3.Zero(),this.l11=Vector3.Zero(),this.l2_2=Vector3.Zero(),this.l2_1=Vector3.Zero(),this.l20=Vector3.Zero(),this.l21=Vector3.Zero(),this.l22=Vector3.Zero()}return a.prototype.addLight=function(i,e,o){TmpVectors.Vector3[0].set(e.r,e.g,e.b);var s=TmpVectors.Vector3[0],c=TmpVectors.Vector3[1];s.scaleToRef(o,c),c.scaleToRef(applySH3(0,i),TmpVectors.Vector3[2]),this.l00.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(1,i),TmpVectors.Vector3[2]),this.l1_1.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(2,i),TmpVectors.Vector3[2]),this.l10.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(3,i),TmpVectors.Vector3[2]),this.l11.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(4,i),TmpVectors.Vector3[2]),this.l2_2.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(5,i),TmpVectors.Vector3[2]),this.l2_1.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(6,i),TmpVectors.Vector3[2]),this.l20.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(7,i),TmpVectors.Vector3[2]),this.l21.addInPlace(TmpVectors.Vector3[2]),c.scaleToRef(applySH3(8,i),TmpVectors.Vector3[2]),this.l22.addInPlace(TmpVectors.Vector3[2])},a.prototype.scaleInPlace=function(i){this.l00.scaleInPlace(i),this.l1_1.scaleInPlace(i),this.l10.scaleInPlace(i),this.l11.scaleInPlace(i),this.l2_2.scaleInPlace(i),this.l2_1.scaleInPlace(i),this.l20.scaleInPlace(i),this.l21.scaleInPlace(i),this.l22.scaleInPlace(i)},a.prototype.convertIncidentRadianceToIrradiance=function(){this.l00.scaleInPlace(SHCosKernelConvolution[0]),this.l1_1.scaleInPlace(SHCosKernelConvolution[1]),this.l10.scaleInPlace(SHCosKernelConvolution[2]),this.l11.scaleInPlace(SHCosKernelConvolution[3]),this.l2_2.scaleInPlace(SHCosKernelConvolution[4]),this.l2_1.scaleInPlace(SHCosKernelConvolution[5]),this.l20.scaleInPlace(SHCosKernelConvolution[6]),this.l21.scaleInPlace(SHCosKernelConvolution[7]),this.l22.scaleInPlace(SHCosKernelConvolution[8])},a.prototype.convertIrradianceToLambertianRadiance=function(){this.scaleInPlace(1/Math.PI)},a.prototype.preScaleForRendering=function(){this.preScaled=!0,this.l00.scaleInPlace(SH3ylmBasisConstants[0]),this.l1_1.scaleInPlace(SH3ylmBasisConstants[1]),this.l10.scaleInPlace(SH3ylmBasisConstants[2]),this.l11.scaleInPlace(SH3ylmBasisConstants[3]),this.l2_2.scaleInPlace(SH3ylmBasisConstants[4]),this.l2_1.scaleInPlace(SH3ylmBasisConstants[5]),this.l20.scaleInPlace(SH3ylmBasisConstants[6]),this.l21.scaleInPlace(SH3ylmBasisConstants[7]),this.l22.scaleInPlace(SH3ylmBasisConstants[8])},a.prototype.updateFromArray=function(i){return Vector3.FromArrayToRef(i[0],0,this.l00),Vector3.FromArrayToRef(i[1],0,this.l1_1),Vector3.FromArrayToRef(i[2],0,this.l10),Vector3.FromArrayToRef(i[3],0,this.l11),Vector3.FromArrayToRef(i[4],0,this.l2_2),Vector3.FromArrayToRef(i[5],0,this.l2_1),Vector3.FromArrayToRef(i[6],0,this.l20),Vector3.FromArrayToRef(i[7],0,this.l21),Vector3.FromArrayToRef(i[8],0,this.l22),this},a.prototype.updateFromFloatsArray=function(i){return Vector3.FromFloatsToRef(i[0],i[1],i[2],this.l00),Vector3.FromFloatsToRef(i[3],i[4],i[5],this.l1_1),Vector3.FromFloatsToRef(i[6],i[7],i[8],this.l10),Vector3.FromFloatsToRef(i[9],i[10],i[11],this.l11),Vector3.FromFloatsToRef(i[12],i[13],i[14],this.l2_2),Vector3.FromFloatsToRef(i[15],i[16],i[17],this.l2_1),Vector3.FromFloatsToRef(i[18],i[19],i[20],this.l20),Vector3.FromFloatsToRef(i[21],i[22],i[23],this.l21),Vector3.FromFloatsToRef(i[24],i[25],i[26],this.l22),this},a.FromArray=function(i){var e=new a;return e.updateFromArray(i)},a.FromPolynomial=function(i){var e=new a;return e.l00=i.xx.scale(.376127).add(i.yy.scale(.376127)).add(i.zz.scale(.376126)),e.l1_1=i.y.scale(.977204),e.l10=i.z.scale(.977204),e.l11=i.x.scale(.977204),e.l2_2=i.xy.scale(1.16538),e.l2_1=i.yz.scale(1.16538),e.l20=i.zz.scale(1.34567).subtract(i.xx.scale(.672834)).subtract(i.yy.scale(.672834)),e.l21=i.zx.scale(1.16538),e.l22=i.xx.scale(1.16538).subtract(i.yy.scale(1.16538)),e.l1_1.scaleInPlace(-1),e.l11.scaleInPlace(-1),e.l2_1.scaleInPlace(-1),e.l21.scaleInPlace(-1),e.scaleInPlace(Math.PI),e},a}(),SphericalPolynomial=function(){function a(){this.x=Vector3.Zero(),this.y=Vector3.Zero(),this.z=Vector3.Zero(),this.xx=Vector3.Zero(),this.yy=Vector3.Zero(),this.zz=Vector3.Zero(),this.xy=Vector3.Zero(),this.yz=Vector3.Zero(),this.zx=Vector3.Zero()}return Object.defineProperty(a.prototype,"preScaledHarmonics",{get:function(){return this._harmonics||(this._harmonics=SphericalHarmonics.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics},enumerable:!1,configurable:!0}),a.prototype.addAmbient=function(i){TmpVectors.Vector3[0].copyFromFloats(i.r,i.g,i.b);var e=TmpVectors.Vector3[0];this.xx.addInPlace(e),this.yy.addInPlace(e),this.zz.addInPlace(e)},a.prototype.scaleInPlace=function(i){this.x.scaleInPlace(i),this.y.scaleInPlace(i),this.z.scaleInPlace(i),this.xx.scaleInPlace(i),this.yy.scaleInPlace(i),this.zz.scaleInPlace(i),this.yz.scaleInPlace(i),this.zx.scaleInPlace(i),this.xy.scaleInPlace(i)},a.prototype.updateFromHarmonics=function(i){return this._harmonics=i,this.x.copyFrom(i.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(i.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(i.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(i.l00),TmpVectors.Vector3[0].copyFrom(i.l20).scaleInPlace(.247708),TmpVectors.Vector3[1].copyFrom(i.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(TmpVectors.Vector3[0]).addInPlace(TmpVectors.Vector3[1]),this.yy.copyFrom(i.l00),this.yy.scaleInPlace(.886277).subtractInPlace(TmpVectors.Vector3[0]).subtractInPlace(TmpVectors.Vector3[1]),this.zz.copyFrom(i.l00),TmpVectors.Vector3[0].copyFrom(i.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(TmpVectors.Vector3[0]),this.yz.copyFrom(i.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(i.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(i.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this},a.FromHarmonics=function(i){var e=new a;return e.updateFromHarmonics(i)},a.FromArray=function(i){var e=new a;return Vector3.FromArrayToRef(i[0],0,e.x),Vector3.FromArrayToRef(i[1],0,e.y),Vector3.FromArrayToRef(i[2],0,e.z),Vector3.FromArrayToRef(i[3],0,e.xx),Vector3.FromArrayToRef(i[4],0,e.yy),Vector3.FromArrayToRef(i[5],0,e.zz),Vector3.FromArrayToRef(i[6],0,e.yz),Vector3.FromArrayToRef(i[7],0,e.zx),Vector3.FromArrayToRef(i[8],0,e.xy),e},a}(),name$2$="postprocessVertexShader",shader$2$=`
  98. attribute vec2 position;
  99. uniform vec2 scale;
  100. varying vec2 vUV;
  101. const vec2 madd=vec2(0.5,0.5);
  102. void main(void) {
  103. vUV=(position*madd+madd)*scale;
  104. gl_Position=vec4(position,0.0,1.0);
  105. }`;ShaderStore.ShadersStore[name$2$]=shader$2$;var PostProcess=function(){function a(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt){_===void 0&&(_=1),j===void 0&&(j=null),$===void 0&&($=0),_e===void 0&&(_e="postprocess"),tt===void 0&&(tt=!1),rt===void 0&&(rt=5),this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.alphaMode=0,this.animations=new Array,this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new SmartArray(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Vector2(1,1),this._texelSize=Vector2.Zero(),this.onActivateObservable=new Observable,this.onSizeChangedObservable=new Observable,this.onApplyObservable=new Observable,this.onBeforeRenderObservable=new Observable,this.onAfterRenderObservable=new Observable,this.name=i,d!=null?(this._camera=d,this._scene=d.getScene(),d.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):b&&(this._engine=b,this._engine.postProcesses.push(this)),this._options=c,this.renderTargetSamplingMode=_||1,this._reusable=k||!1,this._textureType=$,this._textureFormat=rt,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=e,this._vertexUrl=_e,this._parameters=o||[],this._parameters.push("scale"),this._indexParameters=et,this._drawWrapper=new DrawWrapper(this._engine),tt||this.updateEffect(j)}return Object.defineProperty(a.prototype,"samples",{get:function(){return this._samples},set:function(i){var e=this;this._samples=Math.min(i,this._engine.getCaps().maxMSAASamples),this._textures.forEach(function(o){o.samples!==e._samples&&e._engine.updateRenderTargetTextureSampleCount(o,e._samples)})},enumerable:!1,configurable:!0}),a.prototype.getEffectName=function(){return this._fragmentUrl},Object.defineProperty(a.prototype,"onActivate",{set:function(i){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),i&&(this._onActivateObserver=this.onActivateObservable.add(i))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onSizeChanged",{set:function(i){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onApply",{set:function(i){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onBeforeRender",{set:function(i){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onAfterRender",{set:function(i){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"inputTexture",{get:function(){return this._textures.data[this._currentRenderTextureInd]},set:function(i){this._forcedOutputTexture=i},enumerable:!1,configurable:!0}),a.prototype.restoreDefaultInputTexture=function(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())},a.prototype.getCamera=function(){return this._camera},Object.defineProperty(a.prototype,"texelSize",{get:function(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"PostProcess"},a.prototype.getEngine=function(){return this._engine},a.prototype.getEffect=function(){return this._drawWrapper.effect},a.prototype.shareOutputWith=function(i){return this._disposeTextures(),this._shareOutputWithPostProcess=i,this},a.prototype.useOwnOutput=function(){this._textures.length==0&&(this._textures=new SmartArray(2)),this._shareOutputWithPostProcess=null},a.prototype.updateEffect=function(i,e,o,s,c,d,_,b){i===void 0&&(i=null),e===void 0&&(e=null),o===void 0&&(o=null),this._postProcessDefines=i,this._drawWrapper.effect=this._engine.createEffect({vertex:_!=null?_:this._vertexUrl,fragment:b!=null?b:this._fragmentUrl},["position"],e||this._parameters,o||this._samplers,i!==null?i:"",void 0,c,d,s||this._indexParameters)},a.prototype.isReusable=function(){return this._reusable},a.prototype.markTextureDirty=function(){this.width=-1},a.prototype._createRenderTargetTexture=function(i,e,o){o===void 0&&(o=0);for(var s=0;s<this._textureCache.length;s++)if(this._textureCache[s].texture.width===i.width&&this._textureCache[s].texture.height===i.height&&this._textureCache[s].postProcessChannel===o&&this._textureCache[s].texture._generateDepthBuffer===e.generateDepthBuffer)return this._textureCache[s].texture;var c=this._engine.createRenderTargetTexture(i,e);return this._textureCache.push({texture:c,postProcessChannel:o,lastUsedRenderId:-1}),c},a.prototype._flushTextureCache=function(){for(var i=this._renderId,e=this._textureCache.length-1;e>=0;e--)if(i-this._textureCache[e].lastUsedRenderId>100){for(var o=!1,s=0;s<this._textures.length;s++)if(this._textures.data[s]===this._textureCache[e].texture){o=!0;break}o||(this._textureCache[e].texture.dispose(),this._textureCache.splice(e,1))}},a.prototype._resize=function(i,e,o,s,c){this._textures.length>0&&this._textures.reset(),this.width=i,this.height=e;for(var d=null,_=0;_<o._postProcesses.length;_++)if(o._postProcesses[_]!==null){d=o._postProcesses[_];break}var b={width:this.width,height:this.height},k={generateMipMaps:s,generateDepthBuffer:c||d===this,generateStencilBuffer:(c||d===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat};this._textures.push(this._createRenderTargetTexture(b,k,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(b,k,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)},a.prototype.activate=function(i,e,o){var s=this,c,d;e===void 0&&(e=null),i=i||this._camera;var _=i.getScene(),b=_.getEngine(),k=b.getCaps().maxTextureSize,j=(e?e.width:this._engine.getRenderWidth(!0))*this._options|0,$=(e?e.height:this._engine.getRenderHeight(!0))*this._options|0,_e=i.parent;_e&&(_e.leftCamera==i||_e.rightCamera==i)&&(j/=2);var et=this._options.width||j,tt=this._options.height||$,rt=this.renderTargetSamplingMode!==7&&this.renderTargetSamplingMode!==1&&this.renderTargetSamplingMode!==2;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){var it=b.currentViewport;it&&(et*=it.width,tt*=it.height)}(rt||this.alwaysForcePOT)&&(this._options.width||(et=b.needPOTTextures?Engine.GetExponentOfTwo(et,k,this.scaleMode):et),this._options.height||(tt=b.needPOTTextures?Engine.GetExponentOfTwo(tt,k,this.scaleMode):tt)),(this.width!==et||this.height!==tt)&&this._resize(et,tt,i,rt,o),this._textures.forEach(function(st){st.samples!==s.samples&&s._engine.updateRenderTargetTextureSampleCount(st,s.samples)}),this._flushTextureCache(),this._renderId++}var nt;if(this._shareOutputWithPostProcess)nt=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)nt=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{nt=this.inputTexture;for(var ot=void 0,at=0;at<this._textureCache.length;at++)if(this._textureCache[at].texture===nt){ot=this._textureCache[at];break}ot&&(ot.lastUsedRenderId=this._renderId)}return this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(j/et,$/tt),this._engine.bindFramebuffer(nt,0,j,$,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(nt,0,void 0,void 0,this.forceFullscreenViewport)),(d=(c=this._engine)._debugInsertMarker)===null||d===void 0||d.call(c,"post process "+this.name+" input"),this.onActivateObservable.notifyObservers(i),this.autoClear&&this.alphaMode===0&&this._engine.clear(this.clearColor?this.clearColor:_.clearColor,_._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),nt},Object.defineProperty(a.prototype,"isSupported",{get:function(){return this._drawWrapper.effect.isSupported},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"aspectRatio",{get:function(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height},enumerable:!1,configurable:!0}),a.prototype.isReady=function(){var i,e;return(e=(i=this._drawWrapper.effect)===null||i===void 0?void 0:i.isReady())!==null&&e!==void 0?e:!1},a.prototype.apply=function(){var i;if(!(!((i=this._drawWrapper.effect)===null||i===void 0)&&i.isReady()))return null;this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a);var e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),this._drawWrapper.effect},a.prototype._disposeTextures=function(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()},a.prototype._disposeTextureCache=function(){for(var i=this._textureCache.length-1;i>=0;i--)this._textureCache[i].texture.dispose();this._textureCache.length=0},a.prototype.setPrePassRenderer=function(i){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=i.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1},a.prototype.dispose=function(i){i=i||this._camera,this._disposeTextures();var e;if(this._scene&&(e=this._scene.postProcesses.indexOf(this),e!==-1&&this._scene.postProcesses.splice(e,1)),this._parentContainer){var o=this._parentContainer.postProcesses.indexOf(this);o>-1&&this._parentContainer.postProcesses.splice(o,1),this._parentContainer=null}if(e=this._engine.postProcesses.indexOf(this),e!==-1&&this._engine.postProcesses.splice(e,1),!!i){if(i.detachPostProcess(this),e=i._postProcesses.indexOf(this),e===0&&i._postProcesses.length>0){var s=this._camera._getFirstPostProcess();s&&s.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},a.prototype.serialize=function(){var i=SerializationHelper.Serialize(this),e=this.getCamera()||this._scene&&this._scene.activeCamera;return i.customType="BABYLON."+this.getClassName(),i.cameraId=e?e.id:null,i.reusable=this._reusable,i.textureType=this._textureType,i.fragmentUrl=this._fragmentUrl,i.parameters=this._parameters,i.samplers=this._samplers,i.options=this._options,i.defines=this._postProcessDefines,i.textureFormat=this._textureFormat,i.vertexUrl=this._vertexUrl,i.indexParameters=this._indexParameters,i},a.prototype.clone=function(){var i=this.serialize();i._engine=this._engine,i.cameraId=null;var e=a.Parse(i,this._scene,"");return e?(e.onActivateObservable=this.onActivateObservable.clone(),e.onSizeChangedObservable=this.onSizeChangedObservable.clone(),e.onApplyObservable=this.onApplyObservable.clone(),e.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),e.onAfterRenderObservable=this.onAfterRenderObservable.clone(),e._prePassEffectConfiguration=this._prePassEffectConfiguration,e):null},a.Parse=function(i,e,o){var s=GetClass(i.customType);if(!s||!s._Parse)return null;var c=e?e.getCameraById(i.cameraId):null;return s._Parse(i,c,e,o)},a._Parse=function(i,e,o,s){return SerializationHelper.Parse(function(){return new a(i.name,i.fragmentUrl,i.parameters,i.samplers,i.options,e,i.renderTargetSamplingMode,i._engine,i.reusable,i.defines,i.textureType,i.vertexUrl,i.indexParameters,!1,i.textureFormat)},i,o,s)},__decorate([serialize()],a.prototype,"uniqueId",void 0),__decorate([serialize()],a.prototype,"name",void 0),__decorate([serialize()],a.prototype,"width",void 0),__decorate([serialize()],a.prototype,"height",void 0),__decorate([serialize()],a.prototype,"renderTargetSamplingMode",void 0),__decorate([serializeAsColor4()],a.prototype,"clearColor",void 0),__decorate([serialize()],a.prototype,"autoClear",void 0),__decorate([serialize()],a.prototype,"alphaMode",void 0),__decorate([serialize()],a.prototype,"alphaConstants",void 0),__decorate([serialize()],a.prototype,"enablePixelPerfectMode",void 0),__decorate([serialize()],a.prototype,"forceFullscreenViewport",void 0),__decorate([serialize()],a.prototype,"scaleMode",void 0),__decorate([serialize()],a.prototype,"alwaysForcePOT",void 0),__decorate([serialize("samples")],a.prototype,"_samples",void 0),__decorate([serialize()],a.prototype,"adaptScaleToCurrentViewport",void 0),a}();RegisterClass("BABYLON.PostProcess",PostProcess);var name$2_="helperFunctions",shader$2_=`const float PI=3.1415926535897932384626433832795;
  106. const float HALF_MIN=5.96046448e-08;
  107. const float LinearEncodePowerApprox=2.2;
  108. const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;
  109. const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);
  110. const float Epsilon=0.0000001;
  111. #define saturate(x) clamp(x,0.0,1.0)
  112. #define absEps(x) abs(x)+Epsilon
  113. #define maxEps(x) max(x,Epsilon)
  114. #define saturateEps(x) clamp(x,Epsilon,1.0)
  115. mat3 transposeMat3(mat3 inMatrix) {
  116. vec3 i0=inMatrix[0];
  117. vec3 i1=inMatrix[1];
  118. vec3 i2=inMatrix[2];
  119. mat3 outMatrix=mat3(
  120. vec3(i0.x,i1.x,i2.x),
  121. vec3(i0.y,i1.y,i2.y),
  122. vec3(i0.z,i1.z,i2.z)
  123. );
  124. return outMatrix;
  125. }
  126. mat3 inverseMat3(mat3 inMatrix) {
  127. float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];
  128. float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];
  129. float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];
  130. float b01=a22*a11-a12*a21;
  131. float b11=-a22*a10+a12*a20;
  132. float b21=a21*a10-a11*a20;
  133. float det=a00*b01+a01*b11+a02*b21;
  134. return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),
  135. b11,(a22*a00-a02*a20),(-a12*a00+a02*a10),
  136. b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;
  137. }
  138. float toLinearSpace(float color)
  139. {
  140. return pow(color,LinearEncodePowerApprox);
  141. }
  142. vec3 toLinearSpace(vec3 color)
  143. {
  144. return pow(color,vec3(LinearEncodePowerApprox));
  145. }
  146. vec4 toLinearSpace(vec4 color)
  147. {
  148. return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);
  149. }
  150. vec3 toGammaSpace(vec3 color)
  151. {
  152. return pow(color,vec3(GammaEncodePowerApprox));
  153. }
  154. vec4 toGammaSpace(vec4 color)
  155. {
  156. return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);
  157. }
  158. float toGammaSpace(float color)
  159. {
  160. return pow(color,GammaEncodePowerApprox);
  161. }
  162. float square(float value)
  163. {
  164. return value*value;
  165. }
  166. float pow5(float value) {
  167. float sq=value*value;
  168. return sq*sq*value;
  169. }
  170. float getLuminance(vec3 color)
  171. {
  172. return clamp(dot(color,LuminanceEncodeApprox),0.,1.);
  173. }
  174. float getRand(vec2 seed) {
  175. return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);
  176. }
  177. float dither(vec2 seed,float varianceAmount) {
  178. float rand=getRand(seed);
  179. float dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);
  180. return dither;
  181. }
  182. const float rgbdMaxRange=255.0;
  183. vec4 toRGBD(vec3 color) {
  184. float maxRGB=maxEps(max(color.r,max(color.g,color.b)));
  185. float D=max(rgbdMaxRange/maxRGB,1.);
  186. D=clamp(floor(D)/255.0,0.,1.);
  187. vec3 rgb=color.rgb*D;
  188. rgb=toGammaSpace(rgb);
  189. return vec4(clamp(rgb,0.,1.),D);
  190. }
  191. vec3 fromRGBD(vec4 rgbd) {
  192. rgbd.rgb=toLinearSpace(rgbd.rgb);
  193. return rgbd.rgb/rgbd.a;
  194. }
  195. vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {
  196. vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;
  197. vec3 halfSize=cubeSize*0.5;
  198. vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;
  199. vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;
  200. vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);
  201. float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);
  202. vec3 intersectPositionWS=vertexPos+origVec*distance;
  203. return intersectPositionWS-cubePos;
  204. }
  205. `;ShaderStore.IncludesShadersStore[name$2_]=shader$2_;var name$2Z="rgbdDecodePixelShader",shader$2Z=`
  206. varying vec2 vUV;
  207. uniform sampler2D textureSampler;
  208. #include<helperFunctions>
  209. void main(void)
  210. {
  211. gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);
  212. }`;ShaderStore.ShadersStore[name$2Z]=shader$2Z;var name$2Y="passPixelShader",shader$2Y=`
  213. varying vec2 vUV;
  214. uniform sampler2D textureSampler;
  215. void main(void)
  216. {
  217. gl_FragColor=texture2D(textureSampler,vUV);
  218. }`;ShaderStore.ShadersStore[name$2Y]=shader$2Y;var name$2X="passCubePixelShader",shader$2X=`
  219. varying vec2 vUV;
  220. uniform samplerCube textureSampler;
  221. void main(void)
  222. {
  223. vec2 uv=vUV*2.0-1.0;
  224. #ifdef POSITIVEX
  225. gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));
  226. #endif
  227. #ifdef NEGATIVEX
  228. gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));
  229. #endif
  230. #ifdef POSITIVEY
  231. gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));
  232. #endif
  233. #ifdef NEGATIVEY
  234. gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));
  235. #endif
  236. #ifdef POSITIVEZ
  237. gl_FragColor=textureCube(textureSampler,vec3(uv,1.001));
  238. #endif
  239. #ifdef NEGATIVEZ
  240. gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));
  241. #endif
  242. }`;ShaderStore.ShadersStore[name$2X]=shader$2X;var PassPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){return s===void 0&&(s=null),b===void 0&&(b=0),k===void 0&&(k=!1),a.call(this,e,"pass",null,null,o,s,c,d,_,void 0,b,void 0,null,k)||this}return i.prototype.getClassName=function(){return"PassPostProcess"},i._Parse=function(e,o,s,c){return SerializationHelper.Parse(function(){return new i(e.name,e.options,o,e.renderTargetSamplingMode,e._engine,e.reusable)},e,s,c)},i}(PostProcess);RegisterClass("BABYLON.PassPostProcess",PassPostProcess);(function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){s===void 0&&(s=null),b===void 0&&(b=0),k===void 0&&(k=!1);var j=a.call(this,e,"passCube",null,null,o,s,c,d,_,"#define POSITIVEX",b,void 0,null,k)||this;return j._face=0,j}return Object.defineProperty(i.prototype,"face",{get:function(){return this._face},set:function(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ");break}},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"PassCubePostProcess"},i._Parse=function(e,o,s,c){return SerializationHelper.Parse(function(){return new i(e.name,e.options,o,e.renderTargetSamplingMode,e._engine,e.reusable)},e,s,c)},i})(PostProcess);Engine._RescalePostProcessFactory=function(a){return new PassPostProcess("rescale",1,null,2,a,!1,0)};function CreateResizedCopy(a,i,e,o){o===void 0&&(o=!0);var s=a.getScene(),c=s.getEngine(),d=new RenderTargetTexture("resized"+a.name,{width:i,height:e},s,!a.noMipmap,!0,a._texture.type,!1,a.samplingMode,!1);d.wrapU=a.wrapU,d.wrapV=a.wrapV,d.uOffset=a.uOffset,d.vOffset=a.vOffset,d.uScale=a.uScale,d.vScale=a.vScale,d.uAng=a.uAng,d.vAng=a.vAng,d.wAng=a.wAng,d.coordinatesIndex=a.coordinatesIndex,d.level=a.level,d.anisotropicFilteringLevel=a.anisotropicFilteringLevel,d._texture.isReady=!1,a.wrapU=Texture.CLAMP_ADDRESSMODE,a.wrapV=Texture.CLAMP_ADDRESSMODE;var _=new PassPostProcess("pass",1,null,o?Texture.BILINEAR_SAMPLINGMODE:Texture.NEAREST_SAMPLINGMODE,c,!1,0);return _.externalTextureSamplerBinding=!0,_.getEffect().executeWhenCompiled(function(){_.onApply=function(k){k.setTexture("textureSampler",a)};var b=d.renderTarget;b&&(s.postProcessManager.directRender([_],b),c.unBindFramebuffer(b),d.disposeFramebufferObjects(),_.dispose(),d.getInternalTexture().isReady=!0)}),d}function ApplyPostProcess(a,i,e,o,s,c){var d=i.getEngine();return i.isReady=!1,s=s!=null?s:i.samplingMode,o=o!=null?o:i.type,c=c!=null?c:i.format,o===-1&&(o=0),new Promise(function(_){var b=new PostProcess("postprocess",a,null,null,1,null,s,d,!1,void 0,o,void 0,null,!1,c);b.externalTextureSamplerBinding=!0;var k=d.createRenderTargetTexture({width:i.width,height:i.height},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:o,format:c});b.getEffect().executeWhenCompiled(function(){b.onApply=function(j){j._bindTexture("textureSampler",i),j.setFloat2("scale",1,1)},e.postProcessManager.directRender([b],k,!0),d.restoreDefaultFramebuffer(),d._releaseTexture(i),b&&b.dispose(),k._swapAndDie(i),i.type=o,i.format=5,i.isReady=!0,_(i)})})}var _FloatView,_Int32View;function ToHalfFloat(a){_FloatView||(_FloatView=new Float32Array(1),_Int32View=new Int32Array(_FloatView.buffer)),_FloatView[0]=a;var i=_Int32View[0],e=i>>16&32768,o=i>>12&2047,s=i>>23&255;return s<103?e:s>142?(e|=31744,e|=(s==255?0:1)&&i&8388607,e):s<113?(o|=2048,e|=(o>>114-s)+(o>>113-s&1),e):(e|=s-112<<10|o>>1,e+=o&1,e)}function FromHalfFloat(a){var i=(a&32768)>>15,e=(a&31744)>>10,o=a&1023;return e===0?(i?-1:1)*Math.pow(2,-14)*(o/Math.pow(2,10)):e==31?o?NaN:(i?-1:1)*(1/0):(i?-1:1)*Math.pow(2,e-15)*(1+o/Math.pow(2,10))}var TextureTools={CreateResizedCopy,ApplyPostProcess,ToHalfFloat,FromHalfFloat},RGBDTextureTools=function(){function a(){}return a.ExpandRGBDTexture=function(i){var e=i._texture;if(!(!e||!i.isRGBD)){var o=e.getEngine(),s=o.getCaps(),c=e.isReady,d=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(d=!0,e.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(d=!0,e.type=1),d&&(e.isReady=!1,e._isRGBD=!1,e.invertY=!1);var _=function(){if(d){var b=new PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,o,!1,void 0,e.type,void 0,null,!1);b.externalTextureSamplerBinding=!0;var k=o.createRenderTargetTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:e.samplingMode,type:e.type,format:5});b.getEffect().executeWhenCompiled(function(){b.onApply=function(j){j._bindTexture("textureSampler",e),j.setFloat2("scale",1,1)},i.getScene().postProcessManager.directRender([b],k,!0),o.restoreDefaultFramebuffer(),o._releaseTexture(e),b&&b.dispose(),k._swapAndDie(e),e.isReady=!0})}};c?_():i.onLoadObservable.addOnce(_)}},a.EncodeTextureToRGBD=function(i,e,o){return o===void 0&&(o=0),ApplyPostProcess("rgbdEncode",i,e,o,1,5)},a}(),FileFaceOrientation=function(){function a(i,e,o,s){this.name=i,this.worldAxisForNormal=e,this.worldAxisForFileX=o,this.worldAxisForFileY=s}return a}(),CubeMapToSphericalPolynomialTools=function(){function a(){}return a.ConvertCubeMapTextureToSphericalPolynomial=function(i){var e=this,o;if(!i.isCube)return null;(o=i.getScene())===null||o===void 0||o.getEngine().flushFramebuffer();var s=i.getSize().width,c=i.readPixels(0,void 0,void 0,!1),d=i.readPixels(1,void 0,void 0,!1),_,b;i.isRenderTarget?(_=i.readPixels(3,void 0,void 0,!1),b=i.readPixels(2,void 0,void 0,!1)):(_=i.readPixels(2,void 0,void 0,!1),b=i.readPixels(3,void 0,void 0,!1));var k=i.readPixels(4,void 0,void 0,!1),j=i.readPixels(5,void 0,void 0,!1),$=i.gammaSpace,_e=5,et=0;return(i.textureType==1||i.textureType==2)&&(et=1),new Promise(function(tt,rt){Promise.all([d,c,_,b,k,j]).then(function(it){var nt=it[0],ot=it[1],at=it[2],st=it[3],ut=it[4],ft=it[5],lt={size:s,right:ot,left:nt,up:at,down:st,front:ut,back:ft,format:_e,type:et,gammaSpace:$};tt(e.ConvertCubeMapToSphericalPolynomial(lt))})})},a.ConvertCubeMapToSphericalPolynomial=function(i){for(var e=new SphericalHarmonics,o=0,s=2/i.size,c=s,d=s*.5-1,_=0;_<6;_++)for(var b=this.FileFaces[_],k=i[b.name],j=d,$=i.format===5?4:3,_e=0;_e<i.size;_e++){for(var et=d,tt=0;tt<i.size;tt++){var rt=b.worldAxisForFileX.scale(et).add(b.worldAxisForFileY.scale(j)).add(b.worldAxisForNormal);rt.normalize();var it=Math.pow(1+et*et+j*j,-3/2),nt=k[_e*i.size*$+tt*$+0],ot=k[_e*i.size*$+tt*$+1],at=k[_e*i.size*$+tt*$+2];isNaN(nt)&&(nt=0),isNaN(ot)&&(ot=0),isNaN(at)&&(at=0),i.type===0&&(nt/=255,ot/=255,at/=255),i.gammaSpace&&(nt=Math.pow(Scalar.Clamp(nt),ToLinearSpace),ot=Math.pow(Scalar.Clamp(ot),ToLinearSpace),at=Math.pow(Scalar.Clamp(at),ToLinearSpace));var st=4096;nt=Scalar.Clamp(nt,0,st),ot=Scalar.Clamp(ot,0,st),at=Scalar.Clamp(at,0,st);var ut=new Color3(nt,ot,at);e.addLight(rt,ut,it),o+=it,et+=s}j+=c}var ft=4*Math.PI,lt=6,ht=ft*lt/6,pt=ht/o;return e.scaleInPlace(pt),e.convertIncidentRadianceToIrradiance(),e.convertIrradianceToLambertianRadiance(),SphericalPolynomial.FromHarmonics(e)},a.FileFaces=[new FileFaceOrientation("right",new Vector3(1,0,0),new Vector3(0,0,-1),new Vector3(0,-1,0)),new FileFaceOrientation("left",new Vector3(-1,0,0),new Vector3(0,0,1),new Vector3(0,-1,0)),new FileFaceOrientation("up",new Vector3(0,1,0),new Vector3(1,0,0),new Vector3(0,0,1)),new FileFaceOrientation("down",new Vector3(0,-1,0),new Vector3(1,0,0),new Vector3(0,0,-1)),new FileFaceOrientation("front",new Vector3(0,0,1),new Vector3(1,0,0),new Vector3(0,-1,0)),new FileFaceOrientation("back",new Vector3(0,0,-1),new Vector3(-1,0,0),new Vector3(0,-1,0))],a}();BaseTexture.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(BaseTexture.prototype,"sphericalPolynomial",{get:function(){var a=this;if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(function(i){a._texture._sphericalPolynomial=i,a._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(a){this._texture&&(this._texture._sphericalPolynomial=a)},enumerable:!0,configurable:!0});var name$2W="rgbdEncodePixelShader",shader$2W=`
  243. varying vec2 vUV;
  244. uniform sampler2D textureSampler;
  245. #include<helperFunctions>
  246. void main(void)
  247. {
  248. gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);
  249. }`;ShaderStore.ShadersStore[name$2W]=shader$2W;var defaultEnvironmentTextureImageType="image/png",currentVersion=2,_MagicBytes=[134,22,135,150,246,214,150,54];function GetEnvInfo(a){for(var i=new DataView(a.buffer,a.byteOffset,a.byteLength),e=0,o=0;o<_MagicBytes.length;o++)if(i.getUint8(e++)!==_MagicBytes[o])return Logger$2.Error("Not a babylon environment map"),null;for(var s="",c=0;c=i.getUint8(e++);)s+=String.fromCharCode(c);var d=JSON.parse(s);return d=normalizeEnvInfo(d),d.specular&&(d.specular.specularDataPosition=e,d.specular.lodGenerationScale=d.specular.lodGenerationScale||.8),d}function normalizeEnvInfo(a){if(a.version>currentVersion)throw new Error('Unsupported babylon environment map version "'+a.version+'". Latest supported version is "'+currentVersion+'".');return a.version===2||(a=__assign(__assign({},a),{version:2,imageType:defaultEnvironmentTextureImageType})),a}function CreateImageDataArrayBufferViews(a,i){i=normalizeEnvInfo(i);var e=i.specular,o=Scalar.Log2(i.width);if(o=Math.round(o)+1,e.mipmaps.length!==6*o)throw new Error('Unsupported specular mipmaps number "'+e.mipmaps.length+'"');for(var s=new Array(o),c=0;c<o;c++){s[c]=new Array(6);for(var d=0;d<6;d++){var _=e.mipmaps[c*6+d];s[c][d]=new Uint8Array(a.buffer,a.byteOffset+e.specularDataPosition+_.position,_.length)}}return s}function UploadEnvLevelsAsync(a,i,e){e=normalizeEnvInfo(e);var o=e.specular;if(!o)return Promise.resolve();a._lodGenerationScale=o.lodGenerationScale;var s=CreateImageDataArrayBufferViews(i,e);return UploadLevelsAsync(a,s,e.imageType)}function _OnImageReadyAsync(a,i,e,o,s,c,d,_,b,k,j){return new Promise(function($,_e){if(e){var et=i.createTexture(null,!0,!0,null,1,null,function(rt){_e(rt)},a);o.getEffect().executeWhenCompiled(function(){o.externalTextureSamplerBinding=!0,o.onApply=function(rt){rt._bindTexture("textureSampler",et),rt.setFloat2("scale",1,i._features.needsInvertingBitmap&&a instanceof ImageBitmap?-1:1)},i.scenes.length&&(i.scenes[0].postProcessManager.directRender([o],k,!0,c,d),i.restoreDefaultFramebuffer(),et.dispose(),URL.revokeObjectURL(s),$())})}else{if(i._uploadImageToTexture(j,a,c,d),_){var tt=b[d];tt&&i._uploadImageToTexture(tt._texture,a,c,0)}$()}})}function UploadLevelsAsync(a,i,e){if(e===void 0&&(e=defaultEnvironmentTextureImageType),!Tools.IsExponentOfTwo(a.width))throw new Error("Texture size must be a power of two");var o=Scalar.ILog2(a.width)+1,s=a.getEngine(),c=!1,d=!1,_=null,b=null,k=null,j=s.getCaps();if(a.format=5,a.type=0,a.generateMipMaps=!0,a._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,a),j.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?j.textureHalfFloatRender&&j.textureHalfFloatLinearFiltering?(c=!0,a.type=2):j.textureFloatRender&&j.textureFloatLinearFiltering&&(c=!0,a.type=1):c=!1:(c=!1,d=!0,k={}),c)_=new PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,a.type,void 0,null,!1),a._isRGBD=!1,a.invertY=!1,b=s.createRenderTargetCubeTexture(a.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:a.type,format:5});else if(a._isRGBD=!0,a.invertY=!0,d)for(var $=3,_e=a._lodGenerationScale,et=a._lodGenerationOffset,tt=0;tt<$;tt++){var rt=tt/($-1),it=1-rt,nt=et,ot=(o-1)*_e+et,at=nt+(ot-nt)*it,st=Math.round(Math.min(Math.max(at,0),ot)),ut=new InternalTexture(s,InternalTextureSource.Temp);ut.isCube=!0,ut.invertY=!0,ut.generateMipMaps=!1,s.updateTextureSamplingMode(2,ut);var ft=new BaseTexture(null);switch(ft.isCube=!0,ft._texture=ut,k[st]=ft,tt){case 0:a._lodTextureLow=ft;break;case 1:a._lodTextureMid=ft;break;case 2:a._lodTextureHigh=ft;break}}for(var lt=[],ht=function(_t){for(var yt=function(St){var At=i[_t][St],vt=new Blob([At],{type:e}),Et=URL.createObjectURL(vt),xt=void 0;if(typeof Image=="undefined"||s._features.forceBitmapOverHTMLImageElement)xt=s.createImageBitmap(vt,{premultiplyAlpha:"none"}).then(function(Mt){return _OnImageReadyAsync(Mt,s,c,_,Et,St,_t,d,k,b,a)});else{var bt=new Image;bt.src=Et,xt=new Promise(function(Mt,Rt){bt.onload=function(){_OnImageReadyAsync(bt,s,c,_,Et,St,_t,d,k,b,a).then(function(){return Mt()}).catch(function(Pt){Rt(Pt)})},bt.onerror=function(Pt){Rt(Pt)}})}lt.push(xt)},Tt=0;Tt<6;Tt++)yt(Tt)},tt=0;tt<i.length;tt++)ht(tt);if(i.length<o){var pt=void 0,mt=Math.pow(2,o-1-i.length),dt=mt*mt*4;switch(a.type){case 0:{pt=new Uint8Array(dt);break}case 2:{pt=new Uint16Array(dt);break}case 1:{pt=new Float32Array(dt);break}}for(var tt=i.length;tt<o;tt++)for(var gt=0;gt<6;gt++)s._uploadArrayBufferViewToTexture(a,pt,gt,tt)}return Promise.all(lt).then(function(){b&&(s._releaseTexture(a),b._swapAndDie(a)),_&&_.dispose(),d&&(a._lodTextureHigh&&a._lodTextureHigh._texture&&(a._lodTextureHigh._texture.isReady=!0),a._lodTextureMid&&a._lodTextureMid._texture&&(a._lodTextureMid._texture.isReady=!0),a._lodTextureLow&&a._lodTextureLow._texture&&(a._lodTextureLow._texture.isReady=!0))})}function UploadEnvSpherical(a,i){i=normalizeEnvInfo(i);var e=i.irradiance;if(!!e){var o=new SphericalPolynomial;Vector3.FromArrayToRef(e.x,0,o.x),Vector3.FromArrayToRef(e.y,0,o.y),Vector3.FromArrayToRef(e.z,0,o.z),Vector3.FromArrayToRef(e.xx,0,o.xx),Vector3.FromArrayToRef(e.yy,0,o.yy),Vector3.FromArrayToRef(e.zz,0,o.zz),Vector3.FromArrayToRef(e.yz,0,o.yz),Vector3.FromArrayToRef(e.zx,0,o.zx),Vector3.FromArrayToRef(e.xy,0,o.xy),a._sphericalPolynomial=o}}function _UpdateRGBDAsync(a,i,e,o,s){var c=a.getEngine().createRawCubeTexture(null,a.width,a.format,a.type,a.generateMipMaps,a.invertY,a.samplingMode,a._compression),d=UploadLevelsAsync(c,i).then(function(){return a});return a.onRebuildCallback=function(_){return{proxy:d,isReady:!0,isAsync:!0}},a._source=InternalTextureSource.CubeRawRGBD,a._bufferViewArrayArray=i,a._lodGenerationScale=o,a._lodGenerationOffset=s,a._sphericalPolynomial=e,UploadLevelsAsync(a,i).then(function(){return a.isReady=!0,a})}function ExtractBetweenMarkers(a,i,e,o){for(var s=o,c=0,d="";s<e.length;){var _=e.charAt(s);if(d)_===d?d==='"'||d==="'"?e.charAt(s-1)!=="\\"&&(d=""):d="":d==="*/"&&_==="*"&&s+1<e.length&&(e.charAt(s+1)==="/"&&(d=""),d===""&&s++);else switch(_){case a:c++;break;case i:c--;break;case'"':case"'":case"`":d=_;break;case"/":if(s+1<e.length){var b=e.charAt(s+1);b==="/"?d=`
  250. `:b==="*"&&(d="*/")}break}if(s++,c===0)break}return c===0?s-1:-1}function SkipWhitespaces(a,i){for(;i<a.length;){var e=a[i];if(e!==" "&&e!==`
  251. `&&e!=="\r"&&e!==" "&&e!==`
  252. `&&e!=="\xA0")break;i++}return i}function IsIdentifierChar(a){var i=a.charCodeAt(0);return i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||i==95}function RemoveComments(a){for(var i=0,e="",o=!1,s=[];i<a.length;){var c=a.charAt(i);if(e)c===e?e==='"'||e==="'"?(a.charAt(i-1)!=="\\"&&(e=""),s.push(c)):(e="",o=!1):e==="*/"&&c==="*"&&i+1<a.length?(a.charAt(i+1)==="/"&&(e=""),e===""&&(o=!1,i++)):o||s.push(c);else{switch(c){case'"':case"'":case"`":e=c;break;case"/":if(i+1<a.length){var d=a.charAt(i+1);d==="/"?(e=`
  253. `,o=!0):d==="*"&&(e="*/",o=!0)}break}o||s.push(c)}i++}return s.join("")}function FindBackward(a,i,e){for(;i>=0&&a.charAt(i)!==e;)i--;return i}function EscapeRegExp(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ShaderCodeInliner=function(){function a(i,e){e===void 0&&(e=20),this.debug=!1,this._sourceCode=i,this._numMaxIterations=e,this._functionDescr=[],this.inlineToken="#define inline"}return Object.defineProperty(a.prototype,"code",{get:function(){return this._sourceCode},enumerable:!1,configurable:!0}),a.prototype.processCode=function(){this.debug&&console.log("Start inlining process (code size="+this._sourceCode.length+")..."),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")},a.prototype._collectFunctions=function(){for(var i=0;i<this._sourceCode.length;){var e=this._sourceCode.indexOf(this.inlineToken,i);if(e<0)break;var o=this._sourceCode.indexOf("(",e+this.inlineToken.length);if(o<0){this.debug&&console.warn("Could not find the opening parenthesis after the token. startIndex="+i),i=e+this.inlineToken.length;continue}var s=a._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(e+this.inlineToken.length,o));if(!s){this.debug&&console.warn("Could not extract the name/type of the function from: "+this._sourceCode.substring(e+this.inlineToken.length,o)),i=e+this.inlineToken.length;continue}var c=[s[3],s[4]],d=c[0],_=c[1],b=ExtractBetweenMarkers("(",")",this._sourceCode,o);if(b<0){this.debug&&console.warn("Could not extract the parameters the function '"+_+"' (type="+d+"). funcParamsStartIndex="+o),i=e+this.inlineToken.length;continue}var k=this._sourceCode.substring(o+1,b),j=SkipWhitespaces(this._sourceCode,b+1);if(j===this._sourceCode.length){this.debug&&console.warn("Could not extract the body of the function '"+_+"' (type="+d+"). funcParamsEndIndex="+b),i=e+this.inlineToken.length;continue}var $=ExtractBetweenMarkers("{","}",this._sourceCode,j);if($<0){this.debug&&console.warn("Could not extract the body of the function '"+_+"' (type="+d+"). funcBodyStartIndex="+j),i=e+this.inlineToken.length;continue}for(var _e=this._sourceCode.substring(j,$+1),et=RemoveComments(k).split(","),tt=[],rt=0;rt<et.length;++rt){var it=et[rt].trim(),nt=it.lastIndexOf(" ");nt>=0&&tt.push(it.substring(nt+1))}d!=="void"&&tt.push("return"),this._functionDescr.push({name:_,type:d,parameters:tt,body:_e,callIndex:0}),i=$+1;var ot=e>0?this._sourceCode.substring(0,e):"",at=$+1<this._sourceCode.length-1?this._sourceCode.substring($+1):"";this._sourceCode=ot+at,i-=$+1-e}this.debug&&console.log("Collect functions: "+this._functionDescr.length+" functions found. functionDescr=",this._functionDescr)},a.prototype._processInlining=function(i){for(i===void 0&&(i=20);i-->=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log("numMaxIterations is "+i+" after inlining process"),i>=0},a.prototype._replaceFunctionCallsByCode=function(){for(var i=!1,e=0,o=this._functionDescr;e<o.length;e++)for(var s=o[e],c=s.name,d=s.type,_=s.parameters,b=s.body,k=0;k<this._sourceCode.length;){var j=this._sourceCode.indexOf(c,k);if(j<0)break;if(j===0||IsIdentifierChar(this._sourceCode.charAt(j-1))){k=j+c.length;continue}var $=SkipWhitespaces(this._sourceCode,j+c.length);if($===this._sourceCode.length||this._sourceCode.charAt($)!=="("){k=j+c.length;continue}var _e=ExtractBetweenMarkers("(",")",this._sourceCode,$);if(_e<0){this.debug&&console.warn("Could not extract the parameters of the function call. Function '"+c+"' (type="+d+"). callParamsStartIndex="+$),k=j+c.length;continue}var et=this._sourceCode.substring($+1,_e),tt=function(pt){for(var mt=[],dt=0,gt=0;dt<pt.length;){if(pt.charAt(dt)==="("){var _t=ExtractBetweenMarkers("(",")",pt,dt);if(_t<0)return null;dt=_t}else pt.charAt(dt)===","&&(mt.push(pt.substring(gt,dt)),gt=dt+1);dt++}return gt<dt&&mt.push(pt.substring(gt,dt)),mt},rt=tt(RemoveComments(et));if(rt===null){this.debug&&console.warn("Invalid function call: can't extract the parameters of the function call. Function '"+c+"' (type="+d+"). callParamsStartIndex="+$+", callParams="+et),k=j+c.length;continue}for(var it=[],nt=0;nt<rt.length;++nt){var ot=rt[nt].trim();it.push(ot)}var at=d!=="void"?c+"_"+s.callIndex++:null;if(at&&it.push(at+" ="),it.length!==_.length){this.debug&&console.warn("Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '"+c+"' (type="+d+"). function parameters="+_+", call parameters="+it),k=j+c.length;continue}k=_e+1;var st=this._replaceNames(b,_,it),ut=j>0?this._sourceCode.substring(0,j):"",ft=_e+1<this._sourceCode.length-1?this._sourceCode.substring(_e+1):"";if(at){var lt=FindBackward(this._sourceCode,j-1,`
  254. `);ut=this._sourceCode.substring(0,lt+1);var ht=this._sourceCode.substring(lt+1,j);this._sourceCode=ut+d+" "+at+`;
  255. `+st+`
  256. `+ht+at+ft,this.debug&&console.log("Replace function call by code. Function '"+c+"' (type="+d+"). injectDeclarationIndex="+lt+", call parameters="+it)}else this._sourceCode=ut+st+ft,k+=st.length-(_e+1-j),this.debug&&console.log("Replace function call by code. Function '"+c+"' (type="+d+"). functionCallIndex="+j+", call parameters="+it);i=!0}return i},a.prototype._replaceNames=function(i,e,o){for(var s=function(d){var _=new RegExp(EscapeRegExp(e[d]),"g"),b=e[d].length,k=o[d];i=i.replace(_,function(j){for(var $=[],_e=1;_e<arguments.length;_e++)$[_e-1]=arguments[_e];var et=$[0];return IsIdentifierChar(i.charAt(et-1))||IsIdentifierChar(i.charAt(et+b))?e[d]:k})},c=0;c<e.length;++c)s(c);return i},a._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/,a}(),NativePipelineContext=function(){function a(i){this.isAsync=!1,this.isReady=!1,this._valueCache={},this.engine=i}return a.prototype._getVertexShaderCode=function(){return null},a.prototype._getFragmentShaderCode=function(){return null},a.prototype._handlesSpectorRebuildCallback=function(i){throw new Error("Not implemented")},a.prototype._fillEffectInformation=function(i,e,o,s,c,d,_,b){var k=this.engine;if(k.supportsUniformBuffers)for(var j in e)i.bindUniformBlock(j,e[j]);var $=this.engine.getUniforms(this,o);$.forEach(function(tt,rt){s[o[rt]]=tt}),this._uniforms=s;var _e;for(_e=0;_e<c.length;_e++){var et=i.getUniform(c[_e]);et==null&&(c.splice(_e,1),_e--)}c.forEach(function(tt,rt){d[tt]=rt}),b.push.apply(b,k.getAttributes(this,_))},a.prototype.dispose=function(){this._uniforms={}},a.prototype._cacheMatrix=function(i,e){var o=this._valueCache[i],s=e.updateFlag;return o!==void 0&&o===s?!1:(this._valueCache[i]=s,!0)},a.prototype._cacheFloat2=function(i,e,o){var s=this._valueCache[i];if(!s)return s=[e,o],this._valueCache[i]=s,!0;var c=!1;return s[0]!==e&&(s[0]=e,c=!0),s[1]!==o&&(s[1]=o,c=!0),c},a.prototype._cacheFloat3=function(i,e,o,s){var c=this._valueCache[i];if(!c)return c=[e,o,s],this._valueCache[i]=c,!0;var d=!1;return c[0]!==e&&(c[0]=e,d=!0),c[1]!==o&&(c[1]=o,d=!0),c[2]!==s&&(c[2]=s,d=!0),d},a.prototype._cacheFloat4=function(i,e,o,s,c){var d=this._valueCache[i];if(!d)return d=[e,o,s,c],this._valueCache[i]=d,!0;var _=!1;return d[0]!==e&&(d[0]=e,_=!0),d[1]!==o&&(d[1]=o,_=!0),d[2]!==s&&(d[2]=s,_=!0),d[3]!==c&&(d[3]=c,_=!0),_},a.prototype.setInt=function(i,e){var o=this._valueCache[i];o!==void 0&&o===e||this.engine.setInt(this._uniforms[i],e)&&(this._valueCache[i]=e)},a.prototype.setInt2=function(i,e,o){this._cacheFloat2(i,e,o)&&(this.engine.setInt2(this._uniforms[i],e,o)||(this._valueCache[i]=null))},a.prototype.setInt3=function(i,e,o,s){this._cacheFloat3(i,e,o,s)&&(this.engine.setInt3(this._uniforms[i],e,o,s)||(this._valueCache[i]=null))},a.prototype.setInt4=function(i,e,o,s,c){this._cacheFloat4(i,e,o,s,c)&&(this.engine.setInt4(this._uniforms[i],e,o,s,c)||(this._valueCache[i]=null))},a.prototype.setIntArray=function(i,e){this._valueCache[i]=null,this.engine.setIntArray(this._uniforms[i],e)},a.prototype.setIntArray2=function(i,e){this._valueCache[i]=null,this.engine.setIntArray2(this._uniforms[i],e)},a.prototype.setIntArray3=function(i,e){this._valueCache[i]=null,this.engine.setIntArray3(this._uniforms[i],e)},a.prototype.setIntArray4=function(i,e){this._valueCache[i]=null,this.engine.setIntArray4(this._uniforms[i],e)},a.prototype.setFloatArray=function(i,e){this._valueCache[i]=null,this.engine.setFloatArray(this._uniforms[i],e)},a.prototype.setFloatArray2=function(i,e){this._valueCache[i]=null,this.engine.setFloatArray2(this._uniforms[i],e)},a.prototype.setFloatArray3=function(i,e){this._valueCache[i]=null,this.engine.setFloatArray3(this._uniforms[i],e)},a.prototype.setFloatArray4=function(i,e){this._valueCache[i]=null,this.engine.setFloatArray4(this._uniforms[i],e)},a.prototype.setArray=function(i,e){this._valueCache[i]=null,this.engine.setArray(this._uniforms[i],e)},a.prototype.setArray2=function(i,e){this._valueCache[i]=null,this.engine.setArray2(this._uniforms[i],e)},a.prototype.setArray3=function(i,e){this._valueCache[i]=null,this.engine.setArray3(this._uniforms[i],e)},a.prototype.setArray4=function(i,e){this._valueCache[i]=null,this.engine.setArray4(this._uniforms[i],e)},a.prototype.setMatrices=function(i,e){!e||(this._valueCache[i]=null,this.engine.setMatrices(this._uniforms[i],e))},a.prototype.setMatrix=function(i,e){this._cacheMatrix(i,e)&&(this.engine.setMatrices(this._uniforms[i],e.toArray())||(this._valueCache[i]=null))},a.prototype.setMatrix3x3=function(i,e){this._valueCache[i]=null,this.engine.setMatrix3x3(this._uniforms[i],e)},a.prototype.setMatrix2x2=function(i,e){this._valueCache[i]=null,this.engine.setMatrix2x2(this._uniforms[i],e)},a.prototype.setFloat=function(i,e){var o=this._valueCache[i];o!==void 0&&o===e||this.engine.setFloat(this._uniforms[i],e)&&(this._valueCache[i]=e)},a.prototype.setBool=function(i,e){var o=this._valueCache[i];o!==void 0&&o===e||this.engine.setInt(this._uniforms[i],e?1:0)&&(this._valueCache[i]=e?1:0)},a.prototype.setVector2=function(i,e){this._cacheFloat2(i,e.x,e.y)&&(this.engine.setFloat2(this._uniforms[i],e.x,e.y)||(this._valueCache[i]=null))},a.prototype.setFloat2=function(i,e,o){this._cacheFloat2(i,e,o)&&(this.engine.setFloat2(this._uniforms[i],e,o)||(this._valueCache[i]=null))},a.prototype.setVector3=function(i,e){this._cacheFloat3(i,e.x,e.y,e.z)&&(this.engine.setFloat3(this._uniforms[i],e.x,e.y,e.z)||(this._valueCache[i]=null))},a.prototype.setFloat3=function(i,e,o,s){this._cacheFloat3(i,e,o,s)&&(this.engine.setFloat3(this._uniforms[i],e,o,s)||(this._valueCache[i]=null))},a.prototype.setVector4=function(i,e){this._cacheFloat4(i,e.x,e.y,e.z,e.w)&&(this.engine.setFloat4(this._uniforms[i],e.x,e.y,e.z,e.w)||(this._valueCache[i]=null))},a.prototype.setFloat4=function(i,e,o,s,c){this._cacheFloat4(i,e,o,s,c)&&(this.engine.setFloat4(this._uniforms[i],e,o,s,c)||(this._valueCache[i]=null))},a.prototype.setColor3=function(i,e){this._cacheFloat3(i,e.r,e.g,e.b)&&(this.engine.setFloat3(this._uniforms[i],e.r,e.g,e.b)||(this._valueCache[i]=null))},a.prototype.setColor4=function(i,e,o){this._cacheFloat4(i,e.r,e.g,e.b,o)&&(this.engine.setFloat4(this._uniforms[i],e.r,e.g,e.b,o)||(this._valueCache[i]=null))},a.prototype.setDirectColor4=function(i,e){this._cacheFloat4(i,e.r,e.g,e.b,e.a)&&(this.engine.setFloat4(this._uniforms[i],e.r,e.g,e.b,e.a)||(this._valueCache[i]=null))},a}(),NativeRenderTargetWrapper=function(a){__extends(i,a);function i(e,o,s,c){var d=a.call(this,e,o,s,c)||this;return d.__framebuffer=null,d.__framebufferDepthStencil=null,d._engine=c,d}return Object.defineProperty(i.prototype,"_framebuffer",{get:function(){return this.__framebuffer},set:function(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_framebufferDepthStencil",{get:function(){return this.__framebufferDepthStencil},set:function(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e},enumerable:!1,configurable:!0}),i.prototype.dispose=function(e){e===void 0&&(e=!1),this._framebuffer=null,this._framebufferDepthStencil=null,a.prototype.dispose.call(this,e)},i}(RenderTargetWrapper),NativeDataBuffer=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i}(DataBuffer),CommandBufferEncoder=function(){function a(i){this._engine=i,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=NativeEngine._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}return a.prototype.beginCommandScope=function(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0},a.prototype.endCommandScope=function(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()},a.prototype.startEncodingCommand=function(i){this._commandStream.writeNativeData(i)},a.prototype.encodeCommandArgAsUInt32=function(i){this._commandStream.writeUint32(i)},a.prototype.encodeCommandArgAsUInt32s=function(i){this._commandStream.writeUint32Array(i)},a.prototype.encodeCommandArgAsInt32=function(i){this._commandStream.writeInt32(i)},a.prototype.encodeCommandArgAsInt32s=function(i){this._commandStream.writeInt32Array(i)},a.prototype.encodeCommandArgAsFloat32=function(i){this._commandStream.writeFloat32(i)},a.prototype.encodeCommandArgAsFloat32s=function(i){this._commandStream.writeFloat32Array(i)},a.prototype.encodeCommandArgAsNativeData=function(i){this._commandStream.writeNativeData(i),this._pending.push(i)},a.prototype.finishEncodingCommand=function(){this._isCommandBufferScopeActive||this._submit()},a.prototype._submit=function(){this._engine.submitCommands(),this._pending.length=0},a}(),NativeEngine=function(a){__extends(i,a);function i(e){e===void 0&&(e={});var o=a.call(this,null,!1,void 0,e.adaptToDeviceRatio)||this;if(o._engine=new _native.Engine,o._camera=_native.Camera?new _native.Camera:null,o._commandBufferEncoder=new CommandBufferEncoder(o._engine),o._boundBuffersVertexArray=null,o._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,o._stencilTest=!1,o._stencilMask=255,o._stencilFunc=519,o._stencilFuncRef=0,o._stencilFuncMask=255,o._stencilOpStencilFail=7680,o._stencilOpDepthFail=7680,o._stencilOpStencilDepthPass=7681,o._zOffset=0,o._zOffsetUnits=0,o._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==i.PROTOCOL_VERSION)throw new Error("Protocol version mismatch: "+_native.Engine.PROTOCOL_VERSION+" (Native) !== "+i.PROTOCOL_VERSION+" (JS)");o._webGLVersion=2,o.disableUniformBuffers=!0,o._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!0,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:1,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0},o._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,_collectUbosUpdatedInFrame:!1},Tools.Log("Babylon Native (v"+Engine.Version+") launched"),Tools.LoadScript=function(d,_,b,k){Tools.LoadFile(d,function(j){Function(j).apply(null),_&&_()},void 0,void 0,!1,function(j,$){b&&b("LoadScript Error",$)})},typeof URL=="undefined"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob=="undefined"&&(window.Blob=function(d){return d});var s=window&&window.devicePixelRatio||1;o._hardwareScalingLevel=e.adaptToDeviceRatio?s:1,o.resize();var c=o.getDepthFunction();return c&&o.setDepthFunction(c),o._shaderProcessor=new WebGL2ShaderProcessor,o.onNewSceneAddedObservable.add(function(d){var _=d.render;d.render=function(){for(var b=[],k=0;k<arguments.length;k++)b[k]=arguments[k];o._commandBufferEncoder.beginCommandScope(),_.apply(d,b),o._commandBufferEncoder.endCommandScope()}}),o}return i.prototype.getHardwareScalingLevel=function(){return this._engine.getHardwareScalingLevel()},i.prototype.setHardwareScalingLevel=function(e){this._engine.setHardwareScalingLevel(e)},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()},i._createNativeDataStream=function(){return new NativeDataStream},i.prototype._queueNewFrame=function(e,o){return o.requestAnimationFrame&&o!==window?o.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0},i.prototype._bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)},i.prototype.getHostDocument=function(){return null},i.prototype.clear=function(e,o,s,c){if(c===void 0&&(c=!1),this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(o&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(c?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.createIndexBuffer=function(e,o){var s=this._normalizeIndexData(e),c=new NativeDataBuffer;return c.references=1,c.is32Bits=s.BYTES_PER_ELEMENT===4,s.byteLength&&(c.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,c.is32Bits,o!=null?o:!1)),c},i.prototype.createVertexBuffer=function(e,o){var s=ArrayBuffer.isView(e)?e:new Float32Array(e),c=new NativeDataBuffer;return c.references=1,s.byteLength&&(c.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,o!=null?o:!1)),c},i.prototype._recordVertexArrayObject=function(e,o,s,c){s&&this._engine.recordIndexBuffer(e,s.nativeIndexBuffer);for(var d=c.getAttributesNames(),_=0;_<d.length;_++){var b=c.getAttributeLocation(_);if(b>=0){var k=d[_],j=o[k];if(j){var $=j.getBuffer();$&&this._engine.recordVertexBuffer(e,$.nativeVertexBuffer,b,j.byteOffset,j.byteStride,j.getSize(),this._getNativeAttribType(j.type),j.normalized)}}}},i.prototype.bindBuffers=function(e,o,s){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,o,s),this.bindVertexArrayObject(this._boundBuffersVertexArray)},i.prototype.recordVertexArrayObject=function(e,o,s){var c=this._engine.createVertexArray();return this._recordVertexArrayObject(c,e,o,s),c},i.prototype._deleteVertexArray=function(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.bindVertexArrayObject=function(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.releaseVertexArrayObject=function(e){this._deleteVertexArray(e)},i.prototype.getAttributes=function(e,o){var s=e;return this._engine.getAttributes(s.nativeProgram,o)},i.prototype.drawElementsType=function(e,o,s,c){this._drawCalls.addCount(1,!1),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(o),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.drawArraysType=function(e,o,s,c){this._drawCalls.addCount(1,!1),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(o),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.createPipelineContext=function(){return new NativePipelineContext(this)},i.prototype.createMaterialContext=function(){},i.prototype.createDrawContext=function(){},i.prototype._preparePipelineContext=function(e,o,s,c,d,_,b,k,j){var $=e;c?$.nativeProgram=this.createRawShaderProgram(e,o,s,void 0,j):$.nativeProgram=this.createShaderProgram(e,o,s,k,void 0,j)},i.prototype._isRenderingStateCompiled=function(e){return!0},i.prototype._executeWhenRenderingStateIsCompiled=function(e,o){o()},i.prototype.createRawShaderProgram=function(e,o,s,c,d){throw new Error("Not Supported")},i.prototype.createShaderProgram=function(e,o,s,c,d,_){this.onBeforeShaderCompilationObservable.notifyObservers(this);var b=new ShaderCodeInliner(o);b.processCode(),o=b.code;var k=new ShaderCodeInliner(s);k.processCode(),s=k.code,o=ThinEngine._ConcatenateShader(o,c),s=ThinEngine._ConcatenateShader(s,c);var j=this._engine.createProgram(o,s);return this.onAfterShaderCompilationObservable.notifyObservers(this),j},i.prototype.inlineShaderCode=function(e){var o=new ShaderCodeInliner(e);return o.debug=!1,o.processCode(),o.code},i.prototype._setProgram=function(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)},i.prototype._deletePipelineContext=function(e){var o=e;o&&o.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(o.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())},i.prototype.getUniforms=function(e,o){var s=e;return this._engine.getUniforms(s.nativeProgram,o)},i.prototype.bindUniformBlock=function(e,o,s){throw new Error("Not Implemented")},i.prototype.bindSamplers=function(e){var o=e.getPipelineContext();this._setProgram(o.nativeProgram);for(var s=e.getSamplers(),c=0;c<s.length;c++){var d=e.getUniform(s[c]);d&&(this._boundUniforms[c]=d)}this._currentEffect=null},i.prototype.setMatrix=function(e,o){if(!!e){var s=o.toArray();this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(s),this._commandBufferEncoder.finishEncodingCommand()}},i.prototype.getRenderWidth=function(e){return e===void 0&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._engine.getRenderWidth()},i.prototype.getRenderHeight=function(e){return e===void 0&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._engine.getRenderHeight()},i.prototype.setViewport=function(e,o,s){this._cachedViewport=e,this._engine.setViewPort(e.x,e.y,e.width,e.height)},i.prototype.setState=function(e,o,s,c,d,_,b){var k,j;o===void 0&&(o=0),c===void 0&&(c=!1),b===void 0&&(b=0),this._zOffset=o,this._zOffsetUnits=b,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(o),this._commandBufferEncoder.encodeCommandArgAsFloat32(b),this._commandBufferEncoder.encodeCommandArgAsUInt32(!((j=(k=this.cullBackFaces)!==null&&k!==void 0?k:d)!==null&&j!==void 0)||j?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(c?1:0),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.getInputElementClientRect=function(){var e={bottom:this.getRenderHeight(),height:this.getRenderHeight(),left:0,right:this.getRenderWidth(),top:0,width:this.getRenderWidth(),x:0,y:0,toJSON:function(){}};return e},i.prototype.setZOffset=function(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())},i.prototype.getZOffset=function(){return this._zOffset},i.prototype.setZOffsetUnits=function(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())},i.prototype.getZOffsetUnits=function(){return this._zOffsetUnits},i.prototype.setDepthBuffer=function(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.getDepthWrite=function(){return this._depthWrite},i.prototype.getDepthFunction=function(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null},i.prototype.setDepthFunction=function(e){var o=0;switch(e){case 512:o=_native.Engine.DEPTH_TEST_NEVER;break;case 519:o=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:o=_native.Engine.DEPTH_TEST_GREATER;break;case 518:o=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:o=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:o=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:o=_native.Engine.DEPTH_TEST_LESS;break;case 515:o=_native.Engine.DEPTH_TEST_LEQUAL;break}this._currentDepthTest=o,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.setDepthWrite=function(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.setColorWrite=function(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.getColorWrite=function(){return this._colorWrite},i.prototype.applyStencil=function(){this._setStencil(this._stencilMask,this._getStencilOpFail(this._stencilOpStencilFail),this._getStencilDepthFail(this._stencilOpDepthFail),this._getStencilDepthPass(this._stencilOpStencilDepthPass),this._getStencilFunc(this._stencilFunc),this._stencilFuncRef)},i.prototype._setStencil=function(e,o,s,c,d,_){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(o),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(c),this._commandBufferEncoder.encodeCommandArgAsUInt32(d),this._commandBufferEncoder.encodeCommandArgAsUInt32(_),this._commandBufferEncoder.finishEncodingCommand()},i.prototype.setStencilBuffer=function(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)},i.prototype.getStencilBuffer=function(){return this._stencilTest},i.prototype.getStencilOperationPass=function(){return this._stencilOpStencilDepthPass},i.prototype.setStencilOperationPass=function(e){this._stencilOpStencilDepthPass=e,this.applyStencil()},i.prototype.setStencilMask=function(e){this._stencilMask=e,this.applyStencil()},i.prototype.setStencilFunction=function(e){this._stencilFunc=e,this.applyStencil()},i.prototype.setStencilFunctionReference=function(e){this._stencilFuncRef=e,this.applyStencil()},i.prototype.setStencilFunctionMask=function(e){this._stencilFuncMask=e},i.prototype.setStencilOperationFail=function(e){this._stencilOpStencilFail=e,this.applyStencil()},i.prototype.setStencilOperationDepthFail=function(e){this._stencilOpDepthFail=e,this.applyStencil()},i.prototype.getStencilMask=function(){return this._stencilMask},i.prototype.getStencilFunction=function(){return this._stencilFunc},i.prototype.getStencilFunctionReference=function(){return this._stencilFuncRef},i.prototype.getStencilFunctionMask=function(){return this._stencilFuncMask},i.prototype.getStencilOperationFail=function(){return this._stencilOpStencilFail},i.prototype.getStencilOperationDepthFail=function(){return this._stencilOpDepthFail},i.prototype.setAlphaConstants=function(e,o,s,c){throw new Error("Setting alpha blend constant color not yet implemented.")},i.prototype.setAlphaMode=function(e,o){o===void 0&&(o=!1),this._alphaMode!==e&&(e=this._getNativeAlphaMode(e),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.finishEncodingCommand(),o||this.setDepthWrite(e===0),this._alphaMode=e)},i.prototype.getAlphaMode=function(){return this._alphaMode},i.prototype.setInt=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setIntArray=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setIntArray2=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setIntArray3=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setIntArray4=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloatArray=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloatArray2=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloatArray3=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloatArray4=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setArray=function(e,o){return e?this.setFloatArray(e,new Float32Array(o)):!1},i.prototype.setArray2=function(e,o){return e?(this.setFloatArray2(e,new Float32Array(o)),!0):!1},i.prototype.setArray3=function(e,o){return e?(this.setFloatArray3(e,new Float32Array(o)),!0):!1},i.prototype.setArray4=function(e,o){return e?(this.setFloatArray4(e,new Float32Array(o)),!0):!1},i.prototype.setMatrices=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setMatrix3x3=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setMatrix2x2=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloat=function(e,o){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(o),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloat2=function(e,o,s){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(o),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloat3=function(e,o,s,c){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(o),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(c),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setFloat4=function(e,o,s,c,d){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(o),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(c),this._commandBufferEncoder.encodeCommandArgAsFloat32(d),this._commandBufferEncoder.finishEncodingCommand(),!0):!1},i.prototype.setColor3=function(e,o){return e?(this.setFloat3(e,o.r,o.g,o.b),!0):!1},i.prototype.setColor4=function(e,o,s){return e?(this.setFloat4(e,o.r,o.g,o.b,s),!0):!1},i.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},i.prototype._createTexture=function(){return this._engine.createTexture()},i.prototype._deleteTexture=function(e){e&&this._engine.deleteTexture(e)},i.prototype.updateDynamicTexture=function(e,o,s,c,d){if(!!e&&!!e._hardwareTexture){var _=o.getCanvasTexture(),b=e._hardwareTexture.underlyingResource;this._engine.copyTexture(b,_),e.isReady=!0}},i.prototype.createDynamicTexture=function(e,o,s,c){return e=Math.max(e,1),o=Math.max(o,1),this.createRawTexture(new Uint8Array(e*o*4),e,o,5,!1,!1,c)},i.prototype.createVideoElement=function(e){return this._camera?this._camera.createVideo(e):null},i.prototype.updateVideoTexture=function(e,o,s){if(e&&e._hardwareTexture&&this._camera){var c=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(c,o,s)}},i.prototype.createRawTexture=function(e,o,s,c,d,_,b,k,j){k===void 0&&(k=null),j===void 0&&(j=0);var $=new InternalTexture(this,InternalTextureSource.Raw);if($.format=c,$.generateMipMaps=d,$.samplingMode=b,$.invertY=_,$.baseWidth=o,$.baseHeight=s,$.width=$.baseWidth,$.height=$.baseHeight,$._compression=k,$.type=j,this.updateRawTexture($,e,c,_,k,j),$._hardwareTexture){var _e=$._hardwareTexture.underlyingResource,et=this._getNativeSamplingMode(b);this._setTextureSampling(_e,et)}return this._internalTexturesCache.push($),$},i.prototype.updateRawTexture=function(e,o,s,c,d,_){if(_===void 0&&(_=0),!!e){if(o&&e._hardwareTexture){var b=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(b,o,e.width,e.height,this._getNativeTextureFormat(s,_),e.generateMipMaps,e.invertY)}e.isReady=!0}},i.prototype.createTexture=function(e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it){var nt=this;d===void 0&&(d=3),_===void 0&&(_=null),b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=null),$===void 0&&($=null),_e===void 0&&(_e=null),it===void 0&&(it=!1),e=e||"";var ot=e.substr(0,5)==="data:",at=ot&&e.indexOf(";base64,")!==-1,st=j||new InternalTexture(this,InternalTextureSource.Url),ut=e;this._transformTextureUrl&&!at&&!j&&!k&&(e=this._transformTextureUrl(e));for(var ft=e.lastIndexOf("."),lt=_e||(ft>-1?e.substring(ft).toLowerCase():""),ht=null,pt=0,mt=Engine._TextureLoaders;pt<mt.length;pt++){var dt=mt[pt];if(dt.canLoad(lt)){ht=dt;break}}c&&c._addPendingData(st),st.url=e,st.generateMipMaps=!o,st.samplingMode=d,st.invertY=s,st._useSRGBBuffer=this._getUseSRGBBuffer(it,o),this.doNotHandleContextLost||(st._buffer=k);var gt=null;_&&!j&&(gt=st.onLoadedObservable.add(_)),j||this._internalTexturesCache.push(st);var _t=function(Tt,St){c&&c._removePendingData(st),e===ut?(gt&&st.onLoadedObservable.remove(gt),EngineStore.UseFallbackTexture&&nt.createTexture(EngineStore.FallbackTexture,o,st.invertY,c,d,null,b,k,st),b&&b((Tt||"Unknown error")+(EngineStore.UseFallbackTexture?" - Fallback texture was used":""),St)):(Logger$2.Warn("Failed to load "+e+", falling back to "+ut),nt.createTexture(ut,o,st.invertY,c,d,_,b,k,st,$,_e,et,tt))};if(ht)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");var yt=function(Tt){if(!st._hardwareTexture){c&&c._removePendingData(st);return}var St=st._hardwareTexture.underlyingResource;nt._engine.loadTexture(St,Tt,!o,s,it,function(){st.baseWidth=nt._engine.getTextureWidth(St),st.baseHeight=nt._engine.getTextureHeight(St),st.width=st.baseWidth,st.height=st.baseHeight,st.isReady=!0;var At=nt._getNativeSamplingMode(d);nt._setTextureSampling(St,At),c&&c._removePendingData(st),st.onLoadedObservable.notifyObservers(st),st.onLoadedObservable.clear()},function(){throw new Error("Could not load a native texture.")})};if(ot&&k)if(k instanceof ArrayBuffer)yt(new Uint8Array(k));else if(ArrayBuffer.isView(k))yt(k);else if(typeof k=="string")yt(new Uint8Array(Tools.DecodeBase64(k)));else throw new Error("Unsupported buffer type");else at?yt(new Uint8Array(Tools.DecodeBase64(e))):this._loadFile(e,function(Tt){return yt(new Uint8Array(Tt))},void 0,void 0,!0,function(Tt,St){_t("Unable to load "+(Tt&&Tt.responseURL,St))});return st},i.prototype._createDepthStencilTexture=function(e,o,s){var c=s,d=new InternalTexture(this,InternalTextureSource.DepthStencil),_=e.width||e,b=e.height||e,k=this._engine.createFrameBuffer(d._hardwareTexture.underlyingResource,_,b,_native.Engine.TEXTURE_FORMAT_RGBA8,!1,!0,!1);return c._framebufferDepthStencil=k,d},i.prototype._releaseFramebufferObjects=function(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())},i.prototype.createImageBitmap=function(e,o){var s=this;return new Promise(function(c,d){if(Array.isArray(e)){var _=e;if(_.length){var b=s._engine.createImageBitmap(_[0]);if(b){c(b);return}}}d("Unsupported data for createImageBitmap.")})},i.prototype.resizeImageBitmap=function(e,o,s){return this._engine.resizeImageBitmap(e,o,s)},i.prototype.createCubeTexture=function(e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt){var it=this;d===void 0&&(d=null),_===void 0&&(_=null),k===void 0&&(k=null),$===void 0&&($=0),_e===void 0&&(_e=0),et===void 0&&(et=null),rt===void 0&&(rt=!1);var nt=et||new InternalTexture(this,InternalTextureSource.Cube);nt.isCube=!0,nt.url=e,nt.generateMipMaps=!c,nt._lodGenerationScale=$,nt._lodGenerationOffset=_e,this._doNotHandleContextLost||(nt._extension=k,nt._files=s);var ot=e.lastIndexOf("."),at=k||(ot>-1?e.substring(ot).toLowerCase():"");if(at===".env"){var st=function(lt){var ht=GetEnvInfo(lt);nt.width=ht.width,nt.height=ht.width,UploadEnvSpherical(nt,ht);var pt=ht.specular;if(!pt)throw new Error("Nothing else parsed so far");nt._lodGenerationScale=pt.lodGenerationScale;var mt=CreateImageDataArrayBufferViews(lt,ht);nt.format=5,nt.type=0,nt.generateMipMaps=!0,nt.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE,nt),nt._isRGBD=!0,nt.invertY=!0,it._engine.loadCubeTextureWithMips(nt._hardwareTexture.underlyingResource,mt,!1,rt,function(){nt.isReady=!0,d&&d()},function(){throw new Error("Could not load a native cube texture.")})};if(s&&s.length===6)throw new Error("Multi-file loading not allowed on env files.");var ut=function(lt,ht){_&&lt&&_(lt.status+" "+lt.statusText,ht)};this._loadFile(e,function(lt){return st(new Uint8Array(lt))},void 0,void 0,!0,ut)}else{if(!s||s.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");var ft=[s[0],s[3],s[1],s[4],s[2],s[5]];Promise.all(ft.map(function(lt){return Tools.LoadFileAsync(lt).then(function(ht){return new Uint8Array(ht)})})).then(function(lt){return new Promise(function(ht,pt){it._engine.loadCubeTexture(nt._hardwareTexture.underlyingResource,lt,!c,!0,rt,ht,pt)})}).then(function(){nt.isReady=!0,d&&d()},function(lt){_&&_("Failed to load cubemap: "+lt.message,lt)})}return this._internalTexturesCache.push(nt),nt},i.prototype._createHardwareRenderTargetWrapper=function(e,o,s){var c=new NativeRenderTargetWrapper(e,o,s,this);return this._renderTargetWrapperCache.push(c),c},i.prototype.createRenderTargetTexture=function(e,o){var s=this._createHardwareRenderTargetWrapper(!1,!1,e),c={};o!==void 0&&typeof o=="object"?(c.generateMipMaps=o.generateMipMaps,c.generateDepthBuffer=o.generateDepthBuffer===void 0?!0:o.generateDepthBuffer,c.generateStencilBuffer=c.generateDepthBuffer&&o.generateStencilBuffer,c.type=o.type===void 0?0:o.type,c.samplingMode=o.samplingMode===void 0?3:o.samplingMode,c.format=o.format===void 0?5:o.format):(c.generateMipMaps=o,c.generateDepthBuffer=!0,c.generateStencilBuffer=!1,c.type=0,c.samplingMode=3,c.format=5),(c.type===1&&!this._caps.textureFloatLinearFiltering||c.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(c.samplingMode=1);var d=new InternalTexture(this,InternalTextureSource.RenderTarget),_=e.width||e,b=e.height||e;c.type===1&&!this._caps.textureFloat&&(c.type=0,Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));var k=this._engine.createFrameBuffer(d._hardwareTexture.underlyingResource,_,b,this._getNativeTextureFormat(c.format,c.type),!!c.generateStencilBuffer,c.generateDepthBuffer,!!c.generateMipMaps);return s._framebuffer=k,s._generateDepthBuffer=c.generateDepthBuffer,s._generateStencilBuffer=!!c.generateStencilBuffer,d.baseWidth=_,d.baseHeight=b,d.width=_,d.height=b,d.isReady=!0,d.samples=1,d.generateMipMaps=!!c.generateMipMaps,d.samplingMode=c.samplingMode,d.type=c.type,d.format=c.format,this._internalTexturesCache.push(d),s.setTextures(d),s},i.prototype.updateTextureSamplingMode=function(e,o){if(o._hardwareTexture){var s=this._getNativeSamplingMode(e);this._setTextureSampling(o._hardwareTexture.underlyingResource,s)}o.samplingMode=e},i.prototype.bindFramebuffer=function(e,o,s,c,d){var _=e;if(o)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(s||c)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");_._framebufferDepthStencil?this._bindUnboundFramebuffer(_._framebufferDepthStencil):this._bindUnboundFramebuffer(_._framebuffer)},i.prototype.unBindFramebuffer=function(e,o,s){s&&s(),this._bindUnboundFramebuffer(null)},i.prototype.createDynamicVertexBuffer=function(e){return this.createVertexBuffer(e,!0)},i.prototype.updateDynamicIndexBuffer=function(e,o,s){s===void 0&&(s=0);var c=e,d=this._normalizeIndexData(o);c.is32Bits=d.BYTES_PER_ELEMENT===4,this._engine.updateDynamicIndexBuffer(c.nativeIndexBuffer,d.buffer,d.byteOffset,d.byteLength,s)},i.prototype.updateDynamicVertexBuffer=function(e,o,s,c){var d=e,_=ArrayBuffer.isView(o)?o:new Float32Array(o);this._engine.updateDynamicVertexBuffer(d.nativeVertexBuffer,_.buffer,_.byteOffset+(s!=null?s:0),c!=null?c:_.byteLength)},i.prototype._setTexture=function(e,o,s,c){c===void 0&&(c=!1);var d=this._boundUniforms[e];if(!d)return!1;if(!o)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._setTextureCore(d,null)),!1;if(o.video)this._activeChannel=e,o.update();else if(o.delayLoadState===4)return o.delayLoad(),!1;var _;return c?_=o.depthStencilTexture:o.isReady()?_=o.getInternalTexture():o.isCube?_=this.emptyCubeTexture:o.is3D?_=this.emptyTexture3D:o.is2DArray?_=this.emptyTexture2DArray:_=this.emptyTexture,this._activeChannel=e,!_||!_._hardwareTexture?!1:(this._setTextureWrapMode(_._hardwareTexture.underlyingResource,this._getAddressMode(o.wrapU),this._getAddressMode(o.wrapV),this._getAddressMode(o.wrapR)),this._updateAnisotropicLevel(o),this._setTextureCore(d,_._hardwareTexture.underlyingResource),!0)},i.prototype._setTextureSampling=function(e,o){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(o),this._commandBufferEncoder.finishEncodingCommand()},i.prototype._setTextureWrapMode=function(e,o,s,c){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(o),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(c),this._commandBufferEncoder.finishEncodingCommand()},i.prototype._setTextureCore=function(e,o){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(o),this._commandBufferEncoder.finishEncodingCommand()},i.prototype._updateAnisotropicLevel=function(e){var o=e.getInternalTexture(),s=e.anisotropicFilteringLevel;!o||!o._hardwareTexture||o._cachedAnisotropicFilteringLevel!==s&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(o._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand(),o._cachedAnisotropicFilteringLevel=s)},i.prototype._getAddressMode=function(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}},i.prototype._bindTexture=function(e,o){var s=this._boundUniforms[e];if(!!s&&o&&o._hardwareTexture){var c=o._hardwareTexture.underlyingResource;this._setTextureCore(s,c)}},i.prototype._deleteBuffer=function(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)},i.prototype.createCanvas=function(e,o){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");var s=new _native.Canvas;return s.width=e,s.height=o,s},i.prototype.createCanvasImage=function(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");var e=new _native.Image;return e},i.prototype._uploadCompressedDataToTextureDirectly=function(e,o,s,c,d,_,b){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")},i.prototype._uploadDataToTextureDirectly=function(e,o,s,c){throw new Error("_uploadDataToTextureDirectly not implemented.")},i.prototype._uploadArrayBufferViewToTexture=function(e,o,s,c){throw new Error("_uploadArrayBufferViewToTexture not implemented.")},i.prototype._uploadImageToTexture=function(e,o,s,c){throw new Error("_uploadArrayBufferViewToTexture not implemented.")},i.prototype._getNativeSamplingMode=function(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error("Unsupported sampling mode: "+e+".")}},i.prototype._getStencilFunc=function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error("Unsupported stencil func mode: "+e+".")}},i.prototype._getStencilOpFail=function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error("Unsupported stencil OpFail mode: "+e+".")}},i.prototype._getStencilDepthFail=function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error("Unsupported stencil depthFail mode: "+e+".")}},i.prototype._getStencilDepthPass=function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error("Unsupported stencil opPass mode: "+e+".")}},i.prototype._getNativeTextureFormat=function(e,o){if(e==4&&o==0)return _native.Engine.TEXTURE_FORMAT_RGB8;if(e==5&&o==0)return _native.Engine.TEXTURE_FORMAT_RGBA8;if(e==5&&o==1)return _native.Engine.TEXTURE_FORMAT_RGBA32F;throw new Error("Unsupported texture format or type: format "+e+", type "+o+".")},i.prototype._getNativeAlphaMode=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error("Unsupported alpha mode: "+e+".")}},i.prototype._getNativeAttribType=function(e){switch(e){case VertexBuffer.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case VertexBuffer.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case VertexBuffer.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case VertexBuffer.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case VertexBuffer.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error("Unsupported attribute type: "+e+".")}},i.prototype.getFontOffset=function(e){var o={ascent:0,height:0,descent:0};return o},i.PROTOCOL_VERSION=2,i}(Engine);NativeEngine._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new ValidatedNativeDataStream:new NativeDataStream};var ValidatedNativeDataStream=function(a){__extends(i,a);function i(){return a.call(this)||this}return i.prototype.writeUint32=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_UINT_32),a.prototype.writeUint32.call(this,e)},i.prototype.writeInt32=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_INT_32),a.prototype.writeInt32.call(this,e)},i.prototype.writeFloat32=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_FLOAT_32),a.prototype.writeFloat32.call(this,e)},i.prototype.writeUint32Array=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),a.prototype.writeUint32Array.call(this,e)},i.prototype.writeInt32Array=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_INT_32_ARRAY),a.prototype.writeInt32Array.call(this,e)},i.prototype.writeFloat32Array=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),a.prototype.writeFloat32Array.call(this,e)},i.prototype.writeNativeData=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_NATIVE_DATA),a.prototype.writeNativeData.call(this,e)},i.prototype.writeBoolean=function(e){a.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_BOOLEAN),a.prototype.writeBoolean.call(this,e)},i}(NativeDataStream),PowerPreference;(function(a){a.SRGB="srgb"})(PowerPreference||(PowerPreference={}));(function(a){a.LowPower="low-power",a.HighPerformance="high-performance"})(PowerPreference||(PowerPreference={}));var FeatureName;(function(a){a.DepthClipControl="depth-clip-control",a.Depth24UnormStencil8="depth24unorm-stencil8",a.Depth32FloatStencil8="depth32float-stencil8",a.TextureCompressionBC="texture-compression-bc",a.TextureCompressionETC2="texture-compression-etc2",a.TextureCompressionASTC="texture-compression-astc",a.TimestampQuery="timestamp-query",a.IndirectFirstInstance="indirect-first-instance"})(FeatureName||(FeatureName={}));var BufferUsage;(function(a){a[a.MapRead=1]="MapRead",a[a.MapWrite=2]="MapWrite",a[a.CopySrc=4]="CopySrc",a[a.CopyDst=8]="CopyDst",a[a.Index=16]="Index",a[a.Vertex=32]="Vertex",a[a.Uniform=64]="Uniform",a[a.Storage=128]="Storage",a[a.Indirect=256]="Indirect",a[a.QueryResolve=512]="QueryResolve"})(BufferUsage||(BufferUsage={}));var MapMode;(function(a){a[a.Read=1]="Read",a[a.Write=2]="Write"})(MapMode||(MapMode={}));var TextureDimension;(function(a){a.E1d="1d",a.E2d="2d",a.E3d="3d"})(TextureDimension||(TextureDimension={}));var TextureUsage;(function(a){a[a.CopySrc=1]="CopySrc",a[a.CopyDst=2]="CopyDst",a[a.TextureBinding=4]="TextureBinding",a[a.StorageBinding=8]="StorageBinding",a[a.RenderAttachment=16]="RenderAttachment"})(TextureUsage||(TextureUsage={}));var TextureViewDimension;(function(a){a.E1d="1d",a.E2d="2d",a.E2dArray="2d-array",a.Cube="cube",a.CubeArray="cube-array",a.E3d="3d"})(TextureViewDimension||(TextureViewDimension={}));var TextureAspect;(function(a){a.All="all",a.StencilOnly="stencil-only",a.DepthOnly="depth-only"})(TextureAspect||(TextureAspect={}));var TextureFormat;(function(a){a.R8Unorm="r8unorm",a.R8Snorm="r8snorm",a.R8Uint="r8uint",a.R8Sint="r8sint",a.R16Uint="r16uint",a.R16Sint="r16sint",a.R16Float="r16float",a.RG8Unorm="rg8unorm",a.RG8Snorm="rg8snorm",a.RG8Uint="rg8uint",a.RG8Sint="rg8sint",a.R32Uint="r32uint",a.R32Sint="r32sint",a.R32Float="r32float",a.RG16Uint="rg16uint",a.RG16Sint="rg16sint",a.RG16Float="rg16float",a.RGBA8Unorm="rgba8unorm",a.RGBA8UnormSRGB="rgba8unorm-srgb",a.RGBA8Snorm="rgba8snorm",a.RGBA8Uint="rgba8uint",a.RGBA8Sint="rgba8sint",a.BGRA8Unorm="bgra8unorm",a.BGRA8UnormSRGB="bgra8unorm-srgb",a.RGB9E5UFloat="rgb9e5ufloat",a.RGB10A2Unorm="rgb10a2unorm",a.RG11B10UFloat="rg11b10ufloat",a.RG32Uint="rg32uint",a.RG32Sint="rg32sint",a.RG32Float="rg32float",a.RGBA16Uint="rgba16uint",a.RGBA16Sint="rgba16sint",a.RGBA16Float="rgba16float",a.RGBA32Uint="rgba32uint",a.RGBA32Sint="rgba32sint",a.RGBA32Float="rgba32float",a.Stencil8="stencil8",a.Depth16Unorm="depth16unorm",a.Depth24Plus="depth24plus",a.Depth24PlusStencil8="depth24plus-stencil8",a.Depth32Float="depth32float",a.BC1RGBAUnorm="bc1-rgba-unorm",a.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",a.BC2RGBAUnorm="bc2-rgba-unorm",a.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",a.BC3RGBAUnorm="bc3-rgba-unorm",a.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",a.BC4RUnorm="bc4-r-unorm",a.BC4RSnorm="bc4-r-snorm",a.BC5RGUnorm="bc5-rg-unorm",a.BC5RGSnorm="bc5-rg-snorm",a.BC6HRGBUFloat="bc6h-rgb-ufloat",a.BC6HRGBFloat="bc6h-rgb-float",a.BC7RGBAUnorm="bc7-rgba-unorm",a.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",a.ETC2RGB8Unorm="etc2-rgb8unorm",a.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",a.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",a.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",a.ETC2RGBA8Unorm="etc2-rgba8unorm",a.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",a.EACR11Unorm="eac-r11unorm",a.EACR11Snorm="eac-r11snorm",a.EACRG11Unorm="eac-rg11unorm",a.EACRG11Snorm="eac-rg11snorm",a.ASTC4x4Unorm="astc-4x4-unorm",a.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",a.ASTC5x4Unorm="astc-5x4-unorm",a.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",a.ASTC5x5Unorm="astc-5x5-unorm",a.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",a.ASTC6x5Unorm="astc-6x5-unorm",a.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",a.ASTC6x6Unorm="astc-6x6-unorm",a.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",a.ASTC8x5Unorm="astc-8x5-unorm",a.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",a.ASTC8x6Unorm="astc-8x6-unorm",a.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",a.ASTC8x8Unorm="astc-8x8-unorm",a.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",a.ASTC10x5Unorm="astc-10x5-unorm",a.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",a.ASTC10x6Unorm="astc-10x6-unorm",a.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",a.ASTC10x8Unorm="astc-10x8-unorm",a.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",a.ASTC10x10Unorm="astc-10x10-unorm",a.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",a.ASTC12x10Unorm="astc-12x10-unorm",a.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",a.ASTC12x12Unorm="astc-12x12-unorm",a.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",a.Depth24UnormStencil8="depth24unorm-stencil8",a.Depth32FloatStencil8="depth32float-stencil8"})(TextureFormat||(TextureFormat={}));var AddressMode;(function(a){a.ClampToEdge="clamp-to-edge",a.Repeat="repeat",a.MirrorRepeat="mirror-repeat"})(AddressMode||(AddressMode={}));var FilterMode;(function(a){a.Nearest="nearest",a.Linear="linear"})(FilterMode||(FilterMode={}));var CompareFunction;(function(a){a.Never="never",a.Less="less",a.Equal="equal",a.LessEqual="less-equal",a.Greater="greater",a.NotEqual="not-equal",a.GreaterEqual="greater-equal",a.Always="always"})(CompareFunction||(CompareFunction={}));var ShaderStage;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Compute=4]="Compute"})(ShaderStage||(ShaderStage={}));var BufferBindingType;(function(a){a.Uniform="uniform",a.Storage="storage",a.ReadOnlyStorage="read-only-storage"})(BufferBindingType||(BufferBindingType={}));var SamplerBindingType;(function(a){a.Filtering="filtering",a.NonFiltering="non-filtering",a.Comparison="comparison"})(SamplerBindingType||(SamplerBindingType={}));var TextureSampleType;(function(a){a.Float="float",a.UnfilterableFloat="unfilterable-float",a.Depth="depth",a.Sint="sint",a.Uint="uint"})(TextureSampleType||(TextureSampleType={}));var StorageTextureAccess;(function(a){a.WriteOnly="write-only"})(StorageTextureAccess||(StorageTextureAccess={}));var CompilationMessageType;(function(a){a.Error="error",a.Warning="warning",a.Info="info"})(CompilationMessageType||(CompilationMessageType={}));var PrimitiveTopology;(function(a){a.PointList="point-list",a.LineList="line-list",a.LineStrip="line-strip",a.TriangleList="triangle-list",a.TriangleStrip="triangle-strip"})(PrimitiveTopology||(PrimitiveTopology={}));var FrontFace;(function(a){a.CCW="ccw",a.CW="cw"})(FrontFace||(FrontFace={}));var CullMode;(function(a){a.None="none",a.Front="front",a.Back="back"})(CullMode||(CullMode={}));var ColorWrite;(function(a){a[a.Red=1]="Red",a[a.Green=2]="Green",a[a.Blue=4]="Blue",a[a.Alpha=8]="Alpha",a[a.All=15]="All"})(ColorWrite||(ColorWrite={}));var BlendFactor;(function(a){a.Zero="zero",a.One="one",a.Src="src",a.OneMinusSrc="one-minus-src",a.SrcAlpha="src-alpha",a.OneMinusSrcAlpha="one-minus-src-alpha",a.Dst="dst",a.OneMinusDst="one-minus-dst",a.DstAlpha="dst-alpha",a.OneMinusDstAlpha="one-minus-dst-alpha",a.SrcAlphaSaturated="src-alpha-saturated",a.Constant="constant",a.OneMinusConstant="one-minus-constant"})(BlendFactor||(BlendFactor={}));var BlendOperation;(function(a){a.Add="add",a.Subtract="subtract",a.ReverseSubtract="reverse-subtract",a.Min="min",a.Max="max"})(BlendOperation||(BlendOperation={}));var StencilOperation;(function(a){a.Keep="keep",a.Zero="zero",a.Replace="replace",a.Invert="invert",a.IncrementClamp="increment-clamp",a.DecrementClamp="decrement-clamp",a.IncrementWrap="increment-wrap",a.DecrementWrap="decrement-wrap"})(StencilOperation||(StencilOperation={}));var IndexFormat;(function(a){a.Uint16="uint16",a.Uint32="uint32"})(IndexFormat||(IndexFormat={}));var VertexFormat;(function(a){a.Uint8x2="uint8x2",a.Uint8x4="uint8x4",a.Sint8x2="sint8x2",a.Sint8x4="sint8x4",a.Unorm8x2="unorm8x2",a.Unorm8x4="unorm8x4",a.Snorm8x2="snorm8x2",a.Snorm8x4="snorm8x4",a.Uint16x2="uint16x2",a.Uint16x4="uint16x4",a.Sint16x2="sint16x2",a.Sint16x4="sint16x4",a.Unorm16x2="unorm16x2",a.Unorm16x4="unorm16x4",a.Snorm16x2="snorm16x2",a.Snorm16x4="snorm16x4",a.Float16x2="float16x2",a.Float16x4="float16x4",a.Float32="float32",a.Float32x2="float32x2",a.Float32x3="float32x3",a.Float32x4="float32x4",a.Uint32="uint32",a.Uint32x2="uint32x2",a.Uint32x3="uint32x3",a.Uint32x4="uint32x4",a.Sint32="sint32",a.Sint32x2="sint32x2",a.Sint32x3="sint32x3",a.Sint32x4="sint32x4"})(VertexFormat||(VertexFormat={}));var InputStepMode;(function(a){a.Vertex="vertex",a.Instance="instance"})(InputStepMode||(InputStepMode={}));var ComputePassTimestampLocation;(function(a){a.Beginning="beginning",a.End="end"})(ComputePassTimestampLocation||(ComputePassTimestampLocation={}));var RenderPassTimestampLocation;(function(a){a.Beginning="beginning",a.End="end"})(RenderPassTimestampLocation||(RenderPassTimestampLocation={}));var LoadOp;(function(a){a.Load="load"})(LoadOp||(LoadOp={}));var StoreOp;(function(a){a.Store="store",a.Discard="discard"})(StoreOp||(StoreOp={}));var QueryType;(function(a){a.Occlusion="occlusion",a.Timestamp="timestamp"})(QueryType||(QueryType={}));var CanvasCompositingAlphaMode;(function(a){a.Opaque="opaque",a.Premultiplied="premultiplied"})(CanvasCompositingAlphaMode||(CanvasCompositingAlphaMode={}));var DeviceLostReason;(function(a){a.Destroyed="destroyed"})(DeviceLostReason||(DeviceLostReason={}));var ErrorFilter;(function(a){a.OutOfMemory="out-of-memory",a.Validation="validation"})(ErrorFilter||(ErrorFilter={}));var WebGPUShaderProcessor=function(){function a(){this.shaderLanguage=ShaderLanguage.GLSL}return a.prototype._addUniformToLeftOverUBO=function(i,e,o){var s,c=0;s=this._getArraySize(i,e,o),i=s[0],e=s[1],c=s[2];for(var d=0;d<this.webgpuProcessingContext.leftOverUniforms.length;d++)if(this.webgpuProcessingContext.leftOverUniforms[d].name===i)return;this.webgpuProcessingContext.leftOverUniforms.push({name:i,type:e,length:c})},a.prototype._buildLeftOverUBO=function(){if(!this.webgpuProcessingContext.leftOverUniforms.length)return"";var i=a.LeftOvertUBOName,e=this.webgpuProcessingContext.availableBuffers[i];return e||(e={binding:this.webgpuProcessingContext.getNextFreeUBOBinding()},this.webgpuProcessingContext.availableBuffers[i]=e,this._addBufferBindingDescription(i,e,BufferBindingType.Uniform,!0),this._addBufferBindingDescription(i,e,BufferBindingType.Uniform,!1)),this._generateLeftOverUBOCode(i,e)},a.prototype._collectBindingNames=function(){for(var i=0;i<this.webgpuProcessingContext.bindGroupLayoutEntries.length;i++){var e=this.webgpuProcessingContext.bindGroupLayoutEntries[i];if(e===void 0){this.webgpuProcessingContext.bindGroupLayoutEntries[i]=[];continue}for(var o=0;o<e.length;o++){var s=this.webgpuProcessingContext.bindGroupLayoutEntries[i][o],c=this.webgpuProcessingContext.bindGroupLayoutEntryInfo[i][s.binding].name,d=this.webgpuProcessingContext.bindGroupLayoutEntryInfo[i][s.binding].nameInArrayOfTexture;s&&(s.texture||s.externalTexture||s.storageTexture?this.webgpuProcessingContext.textureNames.push(d):s.sampler?this.webgpuProcessingContext.samplerNames.push(c):s.buffer&&this.webgpuProcessingContext.bufferNames.push(c))}}},a.prototype._preCreateBindGroupEntries=function(){for(var i=this.webgpuProcessingContext.bindGroupEntries,e=0;e<this.webgpuProcessingContext.bindGroupLayoutEntries.length;e++){for(var o=this.webgpuProcessingContext.bindGroupLayoutEntries[e],s=[],c=0;c<o.length;c++){var d=this.webgpuProcessingContext.bindGroupLayoutEntries[e][c];d.sampler||d.texture||d.storageTexture||d.externalTexture?s.push({binding:d.binding,resource:void 0}):d.buffer&&s.push({binding:d.binding,resource:{buffer:void 0,offset:0,size:0}})}i[e]=s}},a.prototype._addTextureBindingDescription=function(i,e,o,s,c,d){var _=e.textures[o],b=_.groupIndex,k=_.bindingIndex;if(this.webgpuProcessingContext.bindGroupLayoutEntries[b]||(this.webgpuProcessingContext.bindGroupLayoutEntries[b]=[],this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b]=[]),!this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b][k]){var j=void 0;s===null?j=this.webgpuProcessingContext.bindGroupLayoutEntries[b].push({binding:k,visibility:0,externalTexture:{}}):c?j=this.webgpuProcessingContext.bindGroupLayoutEntries[b].push({binding:k,visibility:0,storageTexture:{access:StorageTextureAccess.WriteOnly,format:c,viewDimension:s}}):j=this.webgpuProcessingContext.bindGroupLayoutEntries[b].push({binding:k,visibility:0,texture:{sampleType:e.sampleType,viewDimension:s,multisampled:!1}});var $=e.isTextureArray?i+o:i;this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b][k]={name:i,index:j-1,nameInArrayOfTexture:$}}k=this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b][k].index,d?this.webgpuProcessingContext.bindGroupLayoutEntries[b][k].visibility|=ShaderStage.Vertex:this.webgpuProcessingContext.bindGroupLayoutEntries[b][k].visibility|=ShaderStage.Fragment},a.prototype._addSamplerBindingDescription=function(i,e,o){var s=e.binding,c=s.groupIndex,d=s.bindingIndex;if(this.webgpuProcessingContext.bindGroupLayoutEntries[c]||(this.webgpuProcessingContext.bindGroupLayoutEntries[c]=[],this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c]=[]),!this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c][d]){var _=this.webgpuProcessingContext.bindGroupLayoutEntries[c].push({binding:d,visibility:0,sampler:{type:e.type}});this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c][d]={name:i,index:_-1}}d=this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c][d].index,o?this.webgpuProcessingContext.bindGroupLayoutEntries[c][d].visibility|=ShaderStage.Vertex:this.webgpuProcessingContext.bindGroupLayoutEntries[c][d].visibility|=ShaderStage.Fragment},a.prototype._addBufferBindingDescription=function(i,e,o,s){var c=e.binding,d=c.groupIndex,_=c.bindingIndex;if(this.webgpuProcessingContext.bindGroupLayoutEntries[d]||(this.webgpuProcessingContext.bindGroupLayoutEntries[d]=[],this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d]=[]),!this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d][_]){var b=this.webgpuProcessingContext.bindGroupLayoutEntries[d].push({binding:_,visibility:0,buffer:{type:o}});this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d][_]={name:i,index:b-1}}_=this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d][_].index,s?this.webgpuProcessingContext.bindGroupLayoutEntries[d][_].visibility|=ShaderStage.Vertex:this.webgpuProcessingContext.bindGroupLayoutEntries[d][_].visibility|=ShaderStage.Fragment},a.AutoSamplerSuffix="Sampler",a.LeftOvertUBOName="LeftOver",a.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,vec3:3,ivec3:3,vec4:4,ivec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16},a._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"},a._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"},a._GpuTextureViewDimensionByWebGPUTextureType={textureCube:TextureViewDimension.Cube,textureCubeArray:TextureViewDimension.CubeArray,texture2D:TextureViewDimension.E2d,texture2DArray:TextureViewDimension.E2dArray,texture3D:TextureViewDimension.E3d},a._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"},a._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1},a}(),WebGPUPipelineContext=function(){function a(i,e){this._name="unnamed",this.shaderProcessingContext=i,this._leftOverUniformsByName={},this.engine=e}return Object.defineProperty(a.prototype,"isAsync",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isReady",{get:function(){return!!this.stages},enumerable:!1,configurable:!0}),a.prototype._handlesSpectorRebuildCallback=function(i){},a.prototype._fillEffectInformation=function(i,e,o,s,c,d,_,b){var k=this.engine;i._fragmentSourceCode="",i._vertexSourceCode="";var j=this.shaderProcessingContext.availableTextures,$;for($=0;$<c.length;$++){var _e=c[$],et=j[c[$]];et==null||et==null?(c.splice($,1),$--):d[_e]=$}for(var tt=0,rt=k.getAttributes(this,_);tt<rt.length;tt++){var it=rt[tt];b.push(it)}this.buildUniformLayout();var nt=[],ot=[];for($=0;$<_.length;$++){var at=b[$];at>=0&&(nt.push(_[$]),ot.push(at))}this.shaderProcessingContext.attributeNamesFromEffect=nt,this.shaderProcessingContext.attributeLocationsFromEffect=ot},a.prototype.buildUniformLayout=function(){if(!!this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new UniformBuffer(this.engine,void 0,void 0,"leftOver-"+this._name);for(var i=0,e=this.shaderProcessingContext.leftOverUniforms;i<e.length;i++){var o=e[i],s=o.type.replace(/^(.*?)(<.*>)?$/,"$1"),c=WebGPUShaderProcessor.UniformSizes[s];this.uniformBuffer.addUniform(o.name,c,o.length),this._leftOverUniformsByName[o.name]=o.type}this.uniformBuffer.create()}},a.prototype.dispose=function(){this.uniformBuffer&&this.uniformBuffer.dispose()},a.prototype.setInt=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateInt(i,e)},a.prototype.setInt2=function(i,e,o){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateInt2(i,e,o)},a.prototype.setInt3=function(i,e,o,s){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateInt3(i,e,o,s)},a.prototype.setInt4=function(i,e,o,s,c){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateInt4(i,e,o,s,c)},a.prototype.setIntArray=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateIntArray(i,e)},a.prototype.setIntArray2=function(i,e){this.setIntArray(i,e)},a.prototype.setIntArray3=function(i,e){this.setIntArray(i,e)},a.prototype.setIntArray4=function(i,e){this.setIntArray(i,e)},a.prototype.setArray=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateArray(i,e)},a.prototype.setArray2=function(i,e){this.setArray(i,e)},a.prototype.setArray3=function(i,e){this.setArray(i,e)},a.prototype.setArray4=function(i,e){this.setArray(i,e)},a.prototype.setMatrices=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateMatrices(i,e)},a.prototype.setMatrix=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateMatrix(i,e)},a.prototype.setMatrix3x3=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateMatrix3x3(i,e)},a.prototype.setMatrix2x2=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateMatrix2x2(i,e)},a.prototype.setFloat=function(i,e){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateFloat(i,e)},a.prototype.setVector2=function(i,e){this.setFloat2(i,e.x,e.y)},a.prototype.setFloat2=function(i,e,o){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateFloat2(i,e,o)},a.prototype.setVector3=function(i,e){this.setFloat3(i,e.x,e.y,e.z)},a.prototype.setFloat3=function(i,e,o,s){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateFloat3(i,e,o,s)},a.prototype.setVector4=function(i,e){this.setFloat4(i,e.x,e.y,e.z,e.w)},a.prototype.setFloat4=function(i,e,o,s,c){!this.uniformBuffer||!this._leftOverUniformsByName[i]||this.uniformBuffer.updateFloat4(i,e,o,s,c)},a.prototype.setColor3=function(i,e){this.setFloat3(i,e.r,e.g,e.b)},a.prototype.setColor4=function(i,e,o){this.setFloat4(i,e.r,e.g,e.b,o)},a.prototype.setDirectColor4=function(i,e){this.setFloat4(i,e.r,e.g,e.b,e.a)},a.prototype._getVertexShaderCode=function(){var i;return(i=this.sources)===null||i===void 0?void 0:i.vertex},a.prototype._getFragmentShaderCode=function(){var i;return(i=this.sources)===null||i===void 0?void 0:i.fragment},a}(),_maxGroups=4,_maxBindingsPerGroup=1<<16,_typeToLocationSize={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4},WebGPUShaderProcessingContext=function(){function a(i){this.shaderLanguage=i,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}return Object.defineProperty(a,"KnownUBOs",{get:function(){return a._SimplifiedKnownBindings?a._SimplifiedKnownUBOs:a._KnownUBOs},enumerable:!1,configurable:!0}),a.prototype._findStartingGroupBinding=function(){var i=a.KnownUBOs,e=[];for(var o in i){var s=i[o].binding;s.groupIndex!==-1&&(e[s.groupIndex]===void 0?e[s.groupIndex]=s.bindingIndex:e[s.groupIndex]=Math.max(e[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=e.length-1,this.freeGroupIndex===0?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=e[e.length-1]+1},a.prototype.getAttributeNextLocation=function(i,e){var o;e===void 0&&(e=0);var s=this._attributeNextLocation;return this._attributeNextLocation+=((o=_typeToLocationSize[i])!==null&&o!==void 0?o:1)*(e||1),s},a.prototype.getVaryingNextLocation=function(i,e){var o;e===void 0&&(e=0);var s=this._varyingNextLocation;return this._varyingNextLocation+=((o=_typeToLocationSize[i])!==null&&o!==void 0?o:1)*(e||1),s},a.prototype.getNextFreeUBOBinding=function(){return this._getNextFreeBinding(1)},a.prototype._getNextFreeBinding=function(i){if(this.freeBindingIndex>_maxBindingsPerGroup-i&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===_maxGroups)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";var e={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=i,e},a._SimplifiedKnownBindings=!0,a._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}}},a._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}}},a}(),WebGPUShaderProcessorGLSL=function(a){__extends(i,a);function i(){var e=a!==null&&a.apply(this,arguments)||this;return e._missingVaryings=[],e._textureArrayProcessing=[],e.shaderLanguage=ShaderLanguage.GLSL,e}return i.prototype._getArraySize=function(e,o,s){var c=0,d=e.indexOf("["),_=e.indexOf("]");if(d>0&&_>0){var b=e.substring(d+1,_);c=+b,isNaN(c)&&(c=+s[b.trim()]),e=e.substr(0,d)}return[e,o,c]},i.prototype.initializeShaders=function(e){this.webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0},i.prototype.varyingProcessor=function(e,o,s,c){this._preProcessors=s;var d=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,_=d.exec(e);if(_!=null){var b=_[1],k=_[2],j;o?(j=this.webgpuProcessingContext.availableVaryings[k],this._missingVaryings[j]="",j===void 0&&Logger$2.Warn('Invalid fragment shader: The varying named "'+k+'" is not declared in the vertex shader! This declaration will be ignored.')):(j=this.webgpuProcessingContext.getVaryingNextLocation(b,this._getArraySize(k,b,s)[2]),this.webgpuProcessingContext.availableVaryings[k]=j,this._missingVaryings[j]="layout(location = "+j+") in "+b+" "+k+";"),e=e.replace(_[0],j===void 0?"":"layout(location = "+j+") "+(o?"in":"out")+" "+b+" "+k+";")}return e},i.prototype.attributeProcessor=function(e,o,s){this._preProcessors=o;var c=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,d=c.exec(e);if(d!=null){var _=d[1],b=d[2],k=this.webgpuProcessingContext.getAttributeNextLocation(_,this._getArraySize(b,_,o)[2]);this.webgpuProcessingContext.availableAttributes[b]=k,this.webgpuProcessingContext.orderedAttributes[k]=b,e=e.replace(d[0],"layout(location = "+k+") in "+_+" "+b+";")}return e},i.prototype.uniformProcessor=function(e,o,s,c){var d,_;this._preProcessors=s;var b=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,k=b.exec(e);if(k!=null){var j=k[1],$=k[2];if(j.indexOf("sampler")===0||j.indexOf("sampler")===1){var _e=0;d=this._getArraySize($,j,s),$=d[0],j=d[1],_e=d[2];var et=this.webgpuProcessingContext.availableTextures[$];if(!et){et={autoBindSampler:!0,isTextureArray:_e>0,isStorageTexture:!1,textures:[],sampleType:TextureSampleType.Float};for(var tt=0;tt<(_e||1);++tt)et.textures.push(this.webgpuProcessingContext.getNextFreeUBOBinding())}var rt=(_=WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[j])!==null&&_!==void 0?_:"sampler",it=!!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[rt],nt=it?SamplerBindingType.Comparison:SamplerBindingType.Filtering,ot=$+WebGPUShaderProcessor.AutoSamplerSuffix,at=this.webgpuProcessingContext.availableSamplers[ot];at||(at={binding:this.webgpuProcessingContext.getNextFreeUBOBinding(),type:nt});var st=j.charAt(0)==="u"?"u":j.charAt(0)==="i"?"i":"";st&&(j=j.substr(1));var ut=it?TextureSampleType.Depth:st==="u"?TextureSampleType.Uint:st==="i"?TextureSampleType.Sint:TextureSampleType.Float;et.sampleType=ut;var ft=_e>0,lt=at.binding.groupIndex,ht=at.binding.bindingIndex,pt=WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[j],mt=WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[j],dt=WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[mt];if(!ft)_e=1,e="layout(set = "+lt+", binding = "+ht+") uniform "+st+rt+" "+ot+`;
  257. layout(set = `+et.textures[0].groupIndex+", binding = "+et.textures[0].bindingIndex+") uniform "+mt+" "+$+`Texture;
  258. #define `+$+" "+st+pt+"("+$+"Texture, "+ot+")";else{var gt=[];gt.push("layout(set = "+lt+", binding = "+ht+") uniform "+st+rt+" "+ot+";"),e=`\r
  259. `;for(var tt=0;tt<_e;++tt){var _t=et.textures[tt].groupIndex,yt=et.textures[tt].bindingIndex;gt.push("layout(set = "+_t+", binding = "+yt+") uniform "+mt+" "+$+"Texture"+tt+";"),e+=(tt>0?`\r
  260. `:"")+"#define "+$+tt+" "+st+pt+"("+$+"Texture"+tt+", "+ot+")"}e=gt.join(`\r
  261. `)+e,this._textureArrayProcessing.push($)}this.webgpuProcessingContext.availableTextures[$]=et,this.webgpuProcessingContext.availableSamplers[ot]=at,this._addSamplerBindingDescription(ot,at,!o);for(var tt=0;tt<_e;++tt)this._addTextureBindingDescription($,et,tt,dt,null,!o)}else this._addUniformToLeftOverUBO($,j,s),e=""}return e},i.prototype.uniformBufferProcessor=function(e,o,s){var c=/uniform\s+(\w+)/gm,d=c.exec(e);if(d!=null){var _=d[1],b=this.webgpuProcessingContext.availableBuffers[_];if(!b){var k=WebGPUShaderProcessingContext.KnownUBOs[_],j=void 0;k&&k.binding.groupIndex!==-1?j=k.binding:j=this.webgpuProcessingContext.getNextFreeUBOBinding(),b={binding:j},this.webgpuProcessingContext.availableBuffers[_]=b}this._addBufferBindingDescription(_,b,BufferBindingType.Uniform,!o),e=e.replace("uniform","layout(set = "+b.binding.groupIndex+", binding = "+b.binding.bindingIndex+") uniform")}return e},i.prototype.postProcessor=function(e,o,s,c,d){var _=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,b=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(b,""),e=e.replace(/texture2D\s*\(/g,"texture("),s)e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(_?"":`layout(location = 0) out vec4 glFragColor;
  262. `)+"void main(");else{e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex"),e=e.replace(/gl_VertexID/g,"gl_VertexIndex");var k=o.indexOf("#define MULTIVIEW")!==-1;if(k)return`#extension GL_OVR_multiview2 : require
  263. layout (num_views = 2) in;
  264. `+e}if(!s){var j=e.lastIndexOf("}");e=e.substring(0,j),e+=`gl_Position.y *= -1.;
  265. `,d.isNDCHalfZRange||(e+=`gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;
  266. `),e+="}"}return e},i.prototype._applyTextureArrayProcessing=function(e,o){for(var s=new RegExp(o+"\\s*\\[(.+)?\\]","gm"),c=s.exec(e);c!=null;){var d=c[1],_=+d;this._preProcessors&&isNaN(_)&&(_=+this._preProcessors[d.trim()]),e=e.replace(c[0],o+_),c=s.exec(e)}return e},i.prototype._generateLeftOverUBOCode=function(e,o){for(var s="layout(set = "+o.binding.groupIndex+", binding = "+o.binding.bindingIndex+") uniform "+e+` {
  267. `,c=0,d=this.webgpuProcessingContext.leftOverUniforms;c<d.length;c++){var _=d[c];_.length>0?s+=" "+_.type+" "+_.name+"["+_.length+`];
  268. `:s+=" "+_.type+" "+_.name+`;
  269. `}return s+=`};
  270. `,s},i.prototype.finalizeShaders=function(e,o,s){for(var c=0;c<this._textureArrayProcessing.length;++c){var d=this._textureArrayProcessing[c];e=this._applyTextureArrayProcessing(e,d),o=this._applyTextureArrayProcessing(o,d)}for(var c=0;c<this._missingVaryings.length;++c){var _=this._missingVaryings[c];_&&_.length>0&&(o=_+`
  271. `+o)}var b=this._buildLeftOverUBO();return e=b+e,o=b+o,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,{vertexCode:e,fragmentCode:o}},i}(WebGPUShaderProcessor),name$2V="bonesDeclaration",shader$2V=`#if NUM_BONE_INFLUENCERS>0
  272. attribute matricesIndices : vec4<f32>;
  273. attribute matricesWeights : vec4<f32>;
  274. #if NUM_BONE_INFLUENCERS>4
  275. attribute matricesIndicesExtra : vec4<f32>;
  276. attribute matricesWeightsExtra : vec4<f32>;
  277. #endif
  278. #ifndef BAKED_VERTEX_ANIMATION_TEXTURE
  279. #ifdef BONETEXTURE
  280. var boneSampler : texture_2d<f32>;
  281. uniform boneTextureWidth : f32;
  282. #else
  283. uniform mBones : array<mat4x4,BonesPerMesh>;
  284. #ifdef BONES_VELOCITY_ENABLED
  285. uniform mPreviousBones : array<mat4x4,BonesPerMesh>;
  286. #endif
  287. #endif
  288. #ifdef BONETEXTURE
  289. fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32) -> mat4x4<f32>
  290. {
  291. let offset=i32(index)*4;
  292. let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);
  293. let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);
  294. let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);
  295. let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);
  296. return mat4x4<f32>(m0,m1,m2,m3);
  297. }
  298. #endif
  299. #endif
  300. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2V]=shader$2V;var name$2U="bonesVertex",shader$2U=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
  301. #if NUM_BONE_INFLUENCERS>0
  302. var influence : mat4x4<f32>;
  303. #ifdef BONETEXTURE
  304. influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
  305. #if NUM_BONE_INFLUENCERS>1
  306. influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
  307. #endif
  308. #if NUM_BONE_INFLUENCERS>2
  309. influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
  310. #endif
  311. #if NUM_BONE_INFLUENCERS>3
  312. influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
  313. #endif
  314. #if NUM_BONE_INFLUENCERS>4
  315. influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
  316. #endif
  317. #if NUM_BONE_INFLUENCERS>5
  318. influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
  319. #endif
  320. #if NUM_BONE_INFLUENCERS>6
  321. influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
  322. #endif
  323. #if NUM_BONE_INFLUENCERS>7
  324. influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
  325. #endif
  326. #else
  327. influence=uniforms.mBones[int(matricesIndices[0])]*matricesWeights[0];
  328. #if NUM_BONE_INFLUENCERS>1
  329. influence=influence+uniforms.mBones[int(matricesIndices[1])]*matricesWeights[1];
  330. #endif
  331. #if NUM_BONE_INFLUENCERS>2
  332. influence=influence+uniforms.mBones[int(matricesIndices[2])]*matricesWeights[2];
  333. #endif
  334. #if NUM_BONE_INFLUENCERS>3
  335. influence=influence+uniforms.mBones[int(matricesIndices[3])]*matricesWeights[3];
  336. #endif
  337. #if NUM_BONE_INFLUENCERS>4
  338. influence=influence+uniforms.mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
  339. #endif
  340. #if NUM_BONE_INFLUENCERS>5
  341. influence=influence+uniforms.mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
  342. #endif
  343. #if NUM_BONE_INFLUENCERS>6
  344. influence=influence+uniforms.mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
  345. #endif
  346. #if NUM_BONE_INFLUENCERS>7
  347. influence=influence+uniforms.mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
  348. #endif
  349. #endif
  350. finalWorld=finalWorld*influence;
  351. #endif
  352. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2U]=shader$2U;var name$2T="bakedVertexAnimationDeclaration",shader$2T=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
  353. uniform bakedVertexAnimationTime: f32;
  354. uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;
  355. uniform bakedVertexAnimationSettings: vec4<f32>;
  356. var bakedVertexAnimationTexture : texture_2d<f32>;
  357. #ifdef INSTANCES
  358. attribute bakedVertexAnimationSettingsInstanced : vec4<f32>;
  359. attribute bakedVertexAnimationTimeInstanced : f32;
  360. #endif
  361. fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32) -> mat4x4<f32>
  362. {
  363. let offset=i32(index)*4;
  364. let frameUV=i32(frame);
  365. let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);
  366. let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);
  367. let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);
  368. let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);
  369. return mat4x4<f32>(m0,m1,m2,m3);
  370. }
  371. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2T]=shader$2T;var name$2S="bakedVertexAnimation",shader$2S=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
  372. {
  373. #ifdef INSTANCES
  374. let VATStartFrame: f32=bakedVertexAnimationSettingsInstanced.x;
  375. let VATEndFrame: f32=bakedVertexAnimationSettingsInstanced.y;
  376. let VATOffsetFrame: f32=bakedVertexAnimationSettingsInstanced.z;
  377. let VATSpeed: f32=bakedVertexAnimationSettingsInstanced.w;
  378. let time: f32=bakedVertexAnimationTimeInstanced*VATSpeed/totalFrames;
  379. #else
  380. let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;
  381. let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;
  382. let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;
  383. let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;
  384. let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;
  385. #endif
  386. let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;
  387. let frameCorrection: f32=select(1.0,0.0,time<1.0);
  388. let numOfFrames: f32=totalFrames-frameCorrection;
  389. var VATFrameNum: f32=fract(time)*numOfFrames;
  390. VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;
  391. VATFrameNum=floor(VATFrameNum);
  392. VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;
  393. var VATInfluence : mat4x4<f32>;
  394. VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
  395. #if NUM_BONE_INFLUENCERS>1
  396. VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
  397. #endif
  398. #if NUM_BONE_INFLUENCERS>2
  399. VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
  400. #endif
  401. #if NUM_BONE_INFLUENCERS>3
  402. VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
  403. #endif
  404. #if NUM_BONE_INFLUENCERS>4
  405. VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
  406. #endif
  407. #if NUM_BONE_INFLUENCERS>5
  408. VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
  409. #endif
  410. #if NUM_BONE_INFLUENCERS>6
  411. VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
  412. #endif
  413. #if NUM_BONE_INFLUENCERS>7
  414. VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
  415. #endif
  416. finalWorld=finalWorld*VATInfluence;
  417. }
  418. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2S]=shader$2S;var name$2R="clipPlaneFragment",shader$2R=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
  419. if (false) {}
  420. #endif
  421. #ifdef CLIPPLANE
  422. elseif (fClipDistance>0.0)
  423. {
  424. discard;
  425. }
  426. #endif
  427. #ifdef CLIPPLANE2
  428. elseif (fClipDistance2>0.0)
  429. {
  430. discard;
  431. }
  432. #endif
  433. #ifdef CLIPPLANE3
  434. elseif (fClipDistance3>0.0)
  435. {
  436. discard;
  437. }
  438. #endif
  439. #ifdef CLIPPLANE4
  440. elseif (fClipDistance4>0.0)
  441. {
  442. discard;
  443. }
  444. #endif
  445. #ifdef CLIPPLANE5
  446. elseif (fClipDistance5>0.0)
  447. {
  448. discard;
  449. }
  450. #endif
  451. #ifdef CLIPPLANE6
  452. elseif (fClipDistance6>0.0)
  453. {
  454. discard;
  455. }
  456. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2R]=shader$2R;var name$2Q="clipPlaneFragmentDeclaration",shader$2Q=`#ifdef CLIPPLANE
  457. varying fClipDistance: f32;
  458. #endif
  459. #ifdef CLIPPLANE2
  460. varying fClipDistance2: f32;
  461. #endif
  462. #ifdef CLIPPLANE3
  463. varying fClipDistance3: f32;
  464. #endif
  465. #ifdef CLIPPLANE4
  466. varying fClipDistance4: f32;
  467. #endif
  468. #ifdef CLIPPLANE5
  469. varying fClipDistance5: f32;
  470. #endif
  471. #ifdef CLIPPLANE6
  472. varying fClipDistance6: f32;
  473. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2Q]=shader$2Q;var name$2P="clipPlaneVertex",shader$2P=`#ifdef CLIPPLANE
  474. fClipDistance=dot(worldPos,uniforms.vClipPlane);
  475. #endif
  476. #ifdef CLIPPLANE2
  477. fClipDistance2=dot(worldPos,uniforms.vClipPlane2);
  478. #endif
  479. #ifdef CLIPPLANE3
  480. fClipDistance3=dot(worldPos,uniforms.vClipPlane3);
  481. #endif
  482. #ifdef CLIPPLANE4
  483. fClipDistance4=dot(worldPos,uniforms.vClipPlane4);
  484. #endif
  485. #ifdef CLIPPLANE5
  486. fClipDistance5=dot(worldPos,uniforms.vClipPlane5);
  487. #endif
  488. #ifdef CLIPPLANE6
  489. fClipDistance6=dot(worldPos,uniforms.vClipPlane6);
  490. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2P]=shader$2P;var name$2O="clipPlaneVertexDeclaration",shader$2O=`#ifdef CLIPPLANE
  491. uniform vClipPlane: vec4<f32>;
  492. varying fClipDistance: f32;
  493. #endif
  494. #ifdef CLIPPLANE2
  495. uniform vClipPlane2: vec4<f32>;
  496. varying fClipDistance2: f32;
  497. #endif
  498. #ifdef CLIPPLANE3
  499. uniform vClipPlane3: vec4<f32>;
  500. varying fClipDistance3: f32;
  501. #endif
  502. #ifdef CLIPPLANE4
  503. uniform vClipPlane4: vec4<f32>;
  504. varying fClipDistance4: f32;
  505. #endif
  506. #ifdef CLIPPLANE5
  507. uniform vClipPlane5: vec4<f32>;
  508. varying fClipDistance5: f32;
  509. #endif
  510. #ifdef CLIPPLANE6
  511. uniform vClipPlane6: vec4<f32>;
  512. varying fClipDistance6: f32;
  513. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2O]=shader$2O;var name$2N="instancesDeclaration",shader$2N=`#ifdef INSTANCES
  514. attribute world0 : vec4<f32>;
  515. attribute world1 : vec4<f32>;
  516. attribute world2 : vec4<f32>;
  517. attribute world3 : vec4<f32>;
  518. #if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
  519. uniform world : mat4x4<f32>;
  520. #endif
  521. #if defined(VELOCITY) || defined(PREPASS_VELOCITY)
  522. attribute previousWorld0 : vec4<f32>;
  523. attribute previousWorld1 : vec4<f32>;
  524. attribute previousWorld2 : vec4<f32>;
  525. attribute previousWorld3 : vec4<f32>;
  526. #ifdef THIN_INSTANCES
  527. uniform previousWorld : mat4x4<f32>;
  528. #endif
  529. #endif
  530. #else
  531. #if !defined(WORLD_UBO)
  532. uniform world : mat4x4<f32>;
  533. #endif
  534. #if defined(VELOCITY) || defined(PREPASS_VELOCITY)
  535. uniform previousWorld : mat4x4<f32>;
  536. #endif
  537. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2N]=shader$2N;var name$2M="instancesVertex",shader$2M=`#ifdef INSTANCES
  538. var finalWorld=mat4x4<f32>(world0,world1,world2,world3);
  539. #if defined(PREPASS_VELOCITY) || defined(VELOCITY)
  540. var finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3);
  541. #endif
  542. #ifdef THIN_INSTANCES
  543. #if !defined(WORLD_UBO)
  544. finalWorld=uniforms.world*finalWorld;
  545. #else
  546. finalWorld=mesh.world*finalWorld;
  547. #endif
  548. #if defined(PREPASS_VELOCITY) || defined(VELOCITY)
  549. finalPreviousWorld=previousWorld*finalPreviousWorld;
  550. #endif
  551. #endif
  552. #else
  553. #if !defined(WORLD_UBO)
  554. var finalWorld=uniforms.world;
  555. #else
  556. var finalWorld=mesh.world;
  557. #endif
  558. #if defined(PREPASS_VELOCITY) || defined(VELOCITY)
  559. var finalPreviousWorld=previousWorld;
  560. #endif
  561. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2M]=shader$2M;var name$2L="meshUboDeclaration",shader$2L=`[[block]]
  562. struct Mesh {
  563. world : mat4x4<f32>;
  564. visibility : f32;
  565. };
  566. var<uniform> mesh : Mesh;
  567. #define WORLD_UBO
  568. `;ShaderStore.IncludesShadersStoreWGSL[name$2L]=shader$2L;var name$2K="morphTargetsVertex",shader$2K=`#ifdef MORPHTARGETS
  569. #ifdef MORPHTARGETS_TEXTURE
  570. vertexID=f32(gl_VertexID)*uniforms.morphTargetTextureInfo.x;
  571. positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-position)*uniforms.morphTargetInfluences[{X}];
  572. vertexID=vertexID+1.0;
  573. #ifdef MORPHTARGETS_NORMAL
  574. normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID)-normal)*uniforms.morphTargetInfluences[{X}];
  575. vertexID=vertexID+1.0;
  576. #endif
  577. #ifdef MORPHTARGETS_UV
  578. uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-uv)*uniforms.morphTargetInfluences[{X}];
  579. vertexID=vertexID+1.0;
  580. #endif
  581. #ifdef MORPHTARGETS_TANGENT
  582. tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID)-tangent.xyz)*uniforms.morphTargetInfluences[{X}];
  583. #endif
  584. #else
  585. positionUpdated=positionUpdated+(position{X}-position)*uniforms.morphTargetInfluences[{X}];
  586. #ifdef MORPHTARGETS_NORMAL
  587. normalUpdated+=(normal{X}-normal)*uniforms.morphTargetInfluences[{X}];
  588. #endif
  589. #ifdef MORPHTARGETS_TANGENT
  590. tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-tangent.xyz)*uniforms.morphTargetInfluences[{X}];
  591. #endif
  592. #ifdef MORPHTARGETS_UV
  593. uvUpdated=uvUpdated+(uv_{X}-uv)*uniforms.morphTargetInfluences[{X}];
  594. #endif
  595. #endif
  596. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2K]=shader$2K;var name$2J="morphTargetsVertexDeclaration",shader$2J=`#ifdef MORPHTARGETS
  597. #ifndef MORPHTARGETS_TEXTURE
  598. attribute position{X} : vec3<f32>;
  599. #ifdef MORPHTARGETS_NORMAL
  600. attribute normal{X} : vec3<f32>;
  601. #endif
  602. #ifdef MORPHTARGETS_TANGENT
  603. attribute tangent{X} : vec3<f32>;
  604. #endif
  605. #ifdef MORPHTARGETS_UV
  606. attribute uv_{X} : vec2<f32>;
  607. #endif
  608. #endif
  609. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2J]=shader$2J;var name$2I="morphTargetsVertexGlobal",shader$2I=`#ifdef MORPHTARGETS
  610. #ifdef MORPHTARGETS_TEXTURE
  611. var vertexID : f32;
  612. #endif
  613. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2I]=shader$2I;var name$2H="morphTargetsVertexGlobalDeclaration",shader$2H=`#ifdef MORPHTARGETS
  614. uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>;
  615. #ifdef MORPHTARGETS_TEXTURE
  616. uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;
  617. uniform morphTargetTextureInfo : vec3<f32>;
  618. var morphTargets : texture_2d_array<f32>;
  619. var morphTargetsSampler : sampler;
  620. fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32) -> vec3<f32>
  621. {
  622. let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);
  623. let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;
  624. let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);
  625. return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;
  626. }
  627. #endif
  628. #endif`;ShaderStore.IncludesShadersStoreWGSL[name$2H]=shader$2H;var name$2G="sceneUboDeclaration",shader$2G=`[[block]]
  629. struct Scene {
  630. viewProjection : mat4x4<f32>;
  631. #ifdef MULTIVIEW
  632. viewProjectionR : mat4x4<f32>;
  633. #endif
  634. view : mat4x4<f32>;
  635. projection : mat4x4<f32>;
  636. vEyePosition : vec4<f32>;
  637. };
  638. var<uniform> scene : Scene;
  639. `;ShaderStore.IncludesShadersStoreWGSL[name$2G]=shader$2G;var builtInName_vertex_index="gl_VertexID",builtInName_instance_index="gl_InstanceID",builtInName_position="gl_Position",builtInName_position_frag="gl_FragCoord",builtInName_front_facing="gl_FrontFacing",builtInName_frag_depth="gl_FragDepth",builtInName_FragColor="gl_FragColor",leftOverVarName="uniforms",gpuTextureViewDimensionByWebGPUTextureFunction={texture_1d:TextureViewDimension.E1d,texture_2d:TextureViewDimension.E2d,texture_2d_array:TextureViewDimension.E2dArray,texture_3d:TextureViewDimension.E3d,texture_cube:TextureViewDimension.Cube,texture_cube_array:TextureViewDimension.CubeArray,texture_multisampled_2d:TextureViewDimension.E2d,texture_depth_2d:TextureViewDimension.E2d,texture_depth_2d_array:TextureViewDimension.E2dArray,texture_depth_cube:TextureViewDimension.Cube,texture_depth_cube_array:TextureViewDimension.CubeArray,texture_depth_multisampled_2d:TextureViewDimension.E2d,texture_storage_1d:TextureViewDimension.E1d,texture_storage_2d:TextureViewDimension.E2d,texture_storage_2d_array:TextureViewDimension.E2dArray,texture_storage_3d:TextureViewDimension.E3d,texture_external:null},WebGPUShaderProcessorWGSL=function(a){__extends(i,a);function i(){var e=a!==null&&a.apply(this,arguments)||this;return e.shaderLanguage=ShaderLanguage.WGSL,e.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,e.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,e.noPrecision=!0,e}return i.prototype._getArraySize=function(e,o,s){var c=0,d=o.lastIndexOf(">");if(o.indexOf("array")>=0&&d>0){for(var _=d;_>0&&o.charAt(_)!==" "&&o.charAt(_)!==",";)_--;var b=o.substring(_+1,d);for(c=+b,isNaN(c)&&(c=+s[b.trim()]);_>0&&(o.charAt(_)===" "||o.charAt(_)===",");)_--;o=o.substring(o.indexOf("<")+1,_+1)}return[e,o,c]},i.prototype.initializeShaders=function(e){this.webgpuProcessingContext=e,this._attributesWGSL=[],this._attributesDeclWGSL=[],this._attributeNamesWGSL=[],this._varyingsWGSL=[],this._varyingsDeclWGSL=[],this._varyingNamesWGSL=[]},i.prototype.preProcessShaderCode=function(e){return RemoveComments(e)},i.prototype.varyingProcessor=function(e,o,s,c){var d=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm,_=d.exec(e);if(_!==null){var b=_[2],k=_[1],j;o?(j=this.webgpuProcessingContext.availableVaryings[k],j===void 0&&Logger$2.Warn('Invalid fragment shader: The varying named "'+k+'" is not declared in the vertex shader! This declaration will be ignored.')):(j=this.webgpuProcessingContext.getVaryingNextLocation(b,this._getArraySize(k,b,s)[2]),this.webgpuProcessingContext.availableVaryings[k]=j,this._varyingsWGSL.push("[[location("+j+")]] "+k+" : "+b+";"),this._varyingsDeclWGSL.push("var<private> "+k+" : "+b+";"),this._varyingNamesWGSL.push(k)),e=""}return e},i.prototype.attributeProcessor=function(e,o,s){var c=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm,d=c.exec(e);if(d!==null){var _=d[2],b=d[1],k=this.webgpuProcessingContext.getAttributeNextLocation(_,this._getArraySize(b,_,o)[2]);this.webgpuProcessingContext.availableAttributes[b]=k,this.webgpuProcessingContext.orderedAttributes[k]=b,this._attributesWGSL.push("[[location("+k+")]] "+b+" : "+_+";"),this._attributesDeclWGSL.push("var<private> "+b+" : "+_+";"),this._attributeNamesWGSL.push(b),e=""}return e},i.prototype.uniformProcessor=function(e,o,s,c){var d=this.uniformRegexp.exec(e);if(d!==null){var _=d[2],b=d[1];this._addUniformToLeftOverUBO(b,_,s),e=""}return e},i.prototype.textureProcessor=function(e,o,s,c){var d=this.textureRegexp.exec(e);if(d!==null){var _=d[1],b=d[2],k=!!d[3],j=d[4],$=j.indexOf("storage")>0,_e=d[6],et=$?_e.substring(0,_e.indexOf(",")).trim():null,tt=k?this._getArraySize(_,b,s)[2]:0,rt=this.webgpuProcessingContext.availableTextures[_];if(rt)tt=rt.textures.length;else{rt={isTextureArray:tt>0,isStorageTexture:$,textures:[],sampleType:TextureSampleType.Float},tt=tt||1;for(var it=0;it<tt;++it)rt.textures.push(this.webgpuProcessingContext.getNextFreeUBOBinding())}this.webgpuProcessingContext.availableTextures[_]=rt;var nt=j.indexOf("depth")>0,ot=gpuTextureViewDimensionByWebGPUTextureFunction[j],at=nt?TextureSampleType.Depth:_e==="u32"?TextureSampleType.Uint:_e==="i32"?TextureSampleType.Sint:TextureSampleType.Float;if(rt.sampleType=at,ot===void 0)throw`Can't get the texture dimension corresponding to the texture function "`+j+'"!';for(var it=0;it<tt;++it){var st=rt.textures[it],ut=st.groupIndex,ft=st.bindingIndex;it===0&&(e="[[group("+ut+"), binding("+ft+")]] "+e),this._addTextureBindingDescription(_,rt,it,ot,et,!o)}}return e},i.prototype.postProcessor=function(e,o,s,c,d){return e},i.prototype.finalizeShaders=function(e,o,s){e=this._processSamplers(e,!0),o=this._processSamplers(o,!1),e=this._processCustomBuffers(e,!0),o=this._processCustomBuffers(o,!1);var c=this._buildLeftOverUBO();e=c+e,o=c+o,e=e.replace(/#define /g,"//#define ");var d=this._varyingsDeclWGSL.join(`
  640. `)+`
  641. `,_="var<private> "+builtInName_vertex_index+` : u32;
  642. var<private> `+builtInName_instance_index+` : u32;
  643. var<private> `+builtInName_position+` : vec4<f32>;
  644. `,b=this._attributesDeclWGSL.join(`
  645. `)+`
  646. `,k=`struct VertexInputs {
  647. [[builtin(vertex_index)]] vertexIndex : u32;
  648. [[builtin(instance_index)]] instanceIndex : u32;
  649. `;this._attributesWGSL.length>0&&(k+=this._attributesWGSL.join(`
  650. `)),k+=`
  651. };
  652. `;var j=`struct FragmentInputs {
  653. [[builtin(position)]] position : vec4<f32>;
  654. `;this._varyingsWGSL.length>0&&(j+=this._varyingsWGSL.join(`
  655. `)),j+=`
  656. };
  657. `,e=_+k+b+j+d+e;for(var $=` var output : FragmentInputs;
  658. `+builtInName_vertex_index+` = input.vertexIndex;
  659. `+builtInName_instance_index+` = input.instanceIndex;
  660. `,_e=0;_e<this._attributeNamesWGSL.length;++_e){var et=this._attributeNamesWGSL[_e];$+=" "+et+" = input."+et+`;
  661. `}for(var tt=" output.position = "+builtInName_position+`;
  662. output.position.y = -output.position.y;
  663. `,_e=0;_e<this._varyingNamesWGSL.length;++_e){var rt=this._varyingNamesWGSL[_e];tt+=" output."+rt+" = "+rt+`;
  664. `}tt+=" return output;",e=this._injectStartingAndEndingCode(e,$,tt),o=o.replace(/#define /g,"//#define ");var it="var<private> "+builtInName_position_frag+` : vec4<f32>;
  665. var<private> `+builtInName_front_facing+` : bool;
  666. var<private> `+builtInName_FragColor+` : vec4<f32>;
  667. var<private> `+builtInName_frag_depth+` : f32;
  668. `,nt=`struct FragmentInputs {
  669. [[builtin(position)]] position : vec4<f32>;
  670. [[builtin(front_facing)]] frontFacing : bool;
  671. `;this._varyingsWGSL.length>0&&(nt+=this._varyingsWGSL.join(`
  672. `)),nt+=`
  673. };
  674. `;for(var ot=`struct FragmentOutputs {
  675. [[location(0)]] color : vec4<f32>;
  676. `,at=!1,st=0;!at&&(st=o.indexOf(builtInName_frag_depth,st),!(st<0));){var ut=st;for(at=!0;st>1&&o.charAt(st)!==`
  677. `;){if(o.charAt(st)==="/"&&o.charAt(st-1)==="/"){at=!1;break}st--}st=ut+12}at&&(ot+=` [[builtin(frag_depth)]] fragDepth: f32;
  678. `),ot+=`};
  679. `,o=it+nt+d+ot+o;for(var ft=` var output : FragmentOutputs;
  680. `+builtInName_position_frag+` = input.position;
  681. `+builtInName_front_facing+` = input.frontFacing;
  682. `,_e=0;_e<this._varyingNamesWGSL.length;++_e){var lt=this._varyingNamesWGSL[_e];ft+=" "+lt+" = input."+lt+`;
  683. `}var ht=" output.color = "+builtInName_FragColor+`;
  684. `;return at&&(ht+=" output.fragDepth = "+builtInName_frag_depth+`;
  685. `),ht+=" return output;",o=this._injectStartingAndEndingCode(o,ft,ht),this._collectBindingNames(),this._preCreateBindGroupEntries(),{vertexCode:e,fragmentCode:o}},i.prototype._generateLeftOverUBOCode=function(e,o){for(var s="[[block]] struct "+e+` {
  686. `,c=0,d=this.webgpuProcessingContext.leftOverUniforms;c<d.length;c++){var _=d[c],b=_.type.replace(/^(.*?)(<.*>)?$/,"$1"),k=WebGPUShaderProcessor.UniformSizes[b];_.length>0?k<=2?s+=" [[align(16)]] "+_.name+" : [[stride(16)]] array<"+_.type+", "+_.length+`>;
  687. `:s+=" "+_.name+" : array<"+_.type+", "+_.length+`>;
  688. `:s+=" "+_.name+" : "+_.type+`;
  689. `}return s+=`};
  690. `,s+="[[group("+o.binding.groupIndex+"), binding("+o.binding.bindingIndex+")]] var<uniform> "+leftOverVarName+" : "+e+`;
  691. `,s},i.prototype._injectStartingAndEndingCode=function(e,o,s){if(o){var c=e.indexOf("fn main");if(c>=0){for(;c++<e.length&&e.charAt(c)!="{";);if(c<e.length){for(;c++<e.length&&e.charAt(c)!=`
  692. `;);if(c<e.length){var d=e.substring(0,c+1),_=e.substring(c+1);e=d+o+_}}}}if(s){var b=e.lastIndexOf("}");e=e.substring(0,b),e+=s+`
  693. }`}return e},i.prototype._processSamplers=function(e,o){for(var s=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;;){var c=s.exec(e);if(c===null)break;var d=c[1],_=c[2],b=d.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)===d.length-WebGPUShaderProcessor.AutoSamplerSuffix.length?d.substring(0,d.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)):null,k=_==="sampler_comparison"?SamplerBindingType.Comparison:SamplerBindingType.Filtering;if(b){var j=this.webgpuProcessingContext.availableTextures[b];j&&(j.autoBindSampler=!0)}var $=this.webgpuProcessingContext.availableSamplers[d];$||($={binding:this.webgpuProcessingContext.getNextFreeUBOBinding(),type:k},this.webgpuProcessingContext.availableSamplers[d]=$),this._addSamplerBindingDescription(d,$,o);var _e=e.substring(0,c.index),et="[[group("+$.binding.groupIndex+"), binding("+$.binding.bindingIndex+")]] ",tt=e.substring(c.index);e=_e+et+tt,s.lastIndex+=et.length}return e},i.prototype._processCustomBuffers=function(e,o){for(var s=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;;){var c=s.exec(e);if(c===null)break;var d=c[1],_=c[3],b=c[4],k=c[5],j=this.webgpuProcessingContext.availableBuffers[b];if(!j){var $=d==="uniform"?WebGPUShaderProcessingContext.KnownUBOs[k]:null,_e=void 0;$?(b=k,_e=$.binding,_e.groupIndex===-1&&(_e=this.webgpuProcessingContext.getNextFreeUBOBinding())):_e=this.webgpuProcessingContext.getNextFreeUBOBinding(),j={binding:_e},this.webgpuProcessingContext.availableBuffers[b]=j}this._addBufferBindingDescription(b,this.webgpuProcessingContext.availableBuffers[b],_==="read_write"?BufferBindingType.Storage:d==="storage"?BufferBindingType.ReadOnlyStorage:BufferBindingType.Uniform,o);var et=j.binding.groupIndex,tt=j.binding.bindingIndex,rt=e.substring(0,c.index),it="[[group("+et+"), binding("+tt+")]] ",nt=e.substring(c.index);e=rt+it+nt,s.lastIndex+=it.length}return e},i}(WebGPUShaderProcessor),WebGPUHardwareTexture=function(){function a(i){i===void 0&&(i=null),this.format=TextureFormat.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=i,this._webgpuMSAATexture=null,this.view=null}return Object.defineProperty(a.prototype,"underlyingResource",{get:function(){return this._webgpuTexture},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"msaaTexture",{get:function(){return this._webgpuMSAATexture},set:function(i){this._webgpuMSAATexture=i},enumerable:!1,configurable:!0}),a.prototype.set=function(i){this._webgpuTexture=i},a.prototype.setMSAATexture=function(i){this._webgpuMSAATexture=i},a.prototype.setUsage=function(i,e,o,s,c){e=i===InternalTextureSource.RenderTarget?!1:e,this.createView({format:this.format,dimension:o?TextureViewDimension.Cube:TextureViewDimension.E2d,mipLevelCount:e?Scalar.ILog2(Math.max(s,c))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:o?6:1,aspect:TextureAspect.All})},a.prototype.createView=function(i){this.view=this._webgpuTexture.createView(i)},a.prototype.reset=function(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null},a.prototype.release=function(){var i,e,o;(i=this._webgpuTexture)===null||i===void 0||i.destroy(),(e=this._webgpuMSAATexture)===null||e===void 0||e.destroy(),(o=this._copyInvertYTempTexture)===null||o===void 0||o.destroy(),this.reset()},a}(),mipmapVertexSource=`
  694. const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));
  695. const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));
  696. layout(location = 0) out vec2 vTex;
  697. void main() {
  698. vTex = tex[gl_VertexIndex];
  699. gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
  700. }
  701. `,mipmapFragmentSource=`
  702. layout(set = 0, binding = 0) uniform sampler imgSampler;
  703. layout(set = 0, binding = 1) uniform texture2D img;
  704. layout(location = 0) in vec2 vTex;
  705. layout(location = 0) out vec4 outColor;
  706. void main() {
  707. outColor = texture(sampler2D(img, imgSampler), vTex);
  708. }
  709. `,invertYPreMultiplyAlphaVertexSource=`
  710. #extension GL_EXT_samplerless_texture_functions : enable
  711. const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));
  712. const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));
  713. layout(set = 0, binding = 0) uniform texture2D img;
  714. #ifdef INVERTY
  715. layout(location = 0) out flat ivec2 vTextureSize;
  716. #endif
  717. void main() {
  718. #ifdef INVERTY
  719. vTextureSize = textureSize(img, 0);
  720. #endif
  721. gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
  722. }
  723. `,invertYPreMultiplyAlphaFragmentSource=`
  724. #extension GL_EXT_samplerless_texture_functions : enable
  725. layout(set = 0, binding = 0) uniform texture2D img;
  726. #ifdef INVERTY
  727. layout(location = 0) in flat ivec2 vTextureSize;
  728. #endif
  729. layout(location = 0) out vec4 outColor;
  730. void main() {
  731. #ifdef INVERTY
  732. vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);
  733. #else
  734. vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);
  735. #endif
  736. #ifdef PREMULTIPLYALPHA
  737. color.rgb *= color.a;
  738. #endif
  739. outColor = color;
  740. }
  741. `,clearVertexSource=`
  742. const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));
  743. void main() {
  744. gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
  745. }
  746. `,clearFragmentSource=`
  747. layout(set = 0, binding = 0) uniform Uniforms {
  748. uniform vec4 color;
  749. };
  750. layout(location = 0) out vec4 outColor;
  751. void main() {
  752. outColor = color;
  753. }
  754. `,PipelineType;(function(a){a[a.MipMap=0]="MipMap",a[a.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",a[a.Clear=2]="Clear"})(PipelineType||(PipelineType={}));var shadersForPipelineType=[{vertex:mipmapVertexSource,fragment:mipmapFragmentSource},{vertex:invertYPreMultiplyAlphaVertexSource,fragment:invertYPreMultiplyAlphaFragmentSource},{vertex:clearVertexSource,fragment:clearFragmentSource}],WebGPUTextureHelper=function(){function a(i,e,o,s){this._pipelines={},this._compiledShaders=[],this._deferredReleaseTextures=[],this._device=i,this._glslang=e,this._tintWASM=o,this._bufferManager=s,this._mipmapSampler=i.createSampler({minFilter:FilterMode.Linear}),this._getPipeline(TextureFormat.RGBA8Unorm)}return a.ComputeNumMipmapLevels=function(i,e){return Scalar.ILog2(Math.max(i,e))+1},a.prototype._getPipeline=function(i,e,o){e===void 0&&(e=PipelineType.MipMap);var s=e===PipelineType.MipMap?1<<0:e===PipelineType.InvertYPremultiplyAlpha?((o.invertY?1:0)<<1)+((o.premultiplyAlpha?1:0)<<2):e===PipelineType.Clear?1<<3:0;this._pipelines[i]||(this._pipelines[i]=[]);var c=this._pipelines[i][s];if(!c){var d=`#version 450\r
  755. `;e===PipelineType.InvertYPremultiplyAlpha&&(o.invertY&&(d+=`#define INVERTY\r
  756. `),o.premultiplyAlpha&&(d+=`#define PREMULTIPLYALPHA\r
  757. `));var _=this._compiledShaders[s];if(!_){var b=this._glslang.compileGLSL(d+shadersForPipelineType[e].vertex,"vertex"),k=this._glslang.compileGLSL(d+shadersForPipelineType[e].fragment,"fragment");this._tintWASM&&(b=this._tintWASM.convertSpirV2WGSL(b),k=this._tintWASM.convertSpirV2WGSL(k));var j=this._device.createShaderModule({code:b}),$=this._device.createShaderModule({code:k});_=this._compiledShaders[s]=[j,$]}var _e=this._device.createRenderPipeline({vertex:{module:_[0],entryPoint:"main"},fragment:{module:_[1],entryPoint:"main",targets:[{format:i}]},primitive:{topology:PrimitiveTopology.TriangleStrip,stripIndexFormat:IndexFormat.Uint16}});c=this._pipelines[i][s]=[_e,_e.getBindGroupLayout(0)]}return c},a._GetTextureTypeFromFormat=function(i){switch(i){case TextureFormat.R8Unorm:case TextureFormat.R8Snorm:case TextureFormat.R8Uint:case TextureFormat.R8Sint:case TextureFormat.RG8Unorm:case TextureFormat.RG8Snorm:case TextureFormat.RG8Uint:case TextureFormat.RG8Sint:case TextureFormat.RGBA8Unorm:case TextureFormat.RGBA8UnormSRGB:case TextureFormat.RGBA8Snorm:case TextureFormat.RGBA8Uint:case TextureFormat.RGBA8Sint:case TextureFormat.BGRA8Unorm:case TextureFormat.BGRA8UnormSRGB:case TextureFormat.RGB10A2Unorm:case TextureFormat.RGB9E5UFloat:case TextureFormat.RG11B10UFloat:case TextureFormat.Depth24UnormStencil8:case TextureFormat.Depth32FloatStencil8:case TextureFormat.BC7RGBAUnorm:case TextureFormat.BC7RGBAUnormSRGB:case TextureFormat.BC6HRGBUFloat:case TextureFormat.BC6HRGBFloat:case TextureFormat.BC5RGUnorm:case TextureFormat.BC5RGSnorm:case TextureFormat.BC3RGBAUnorm:case TextureFormat.BC3RGBAUnormSRGB:case TextureFormat.BC2RGBAUnorm:case TextureFormat.BC2RGBAUnormSRGB:case TextureFormat.BC4RUnorm:case TextureFormat.BC4RSnorm:case TextureFormat.BC1RGBAUnorm:case TextureFormat.BC1RGBAUnormSRGB:case TextureFormat.ETC2RGB8Unorm:case TextureFormat.ETC2RGB8UnormSRGB:case TextureFormat.ETC2RGB8A1Unorm:case TextureFormat.ETC2RGB8A1UnormSRGB:case TextureFormat.ETC2RGBA8Unorm:case TextureFormat.ETC2RGBA8UnormSRGB:case TextureFormat.EACR11Unorm:case TextureFormat.EACR11Snorm:case TextureFormat.EACRG11Unorm:case TextureFormat.EACRG11Snorm:case TextureFormat.ASTC4x4Unorm:case TextureFormat.ASTC4x4UnormSRGB:case TextureFormat.ASTC5x4Unorm:case TextureFormat.ASTC5x4UnormSRGB:case TextureFormat.ASTC5x5Unorm:case TextureFormat.ASTC5x5UnormSRGB:case TextureFormat.ASTC6x5Unorm:case TextureFormat.ASTC6x5UnormSRGB:case TextureFormat.ASTC6x6Unorm:case TextureFormat.ASTC6x6UnormSRGB:case TextureFormat.ASTC8x5Unorm:case TextureFormat.ASTC8x5UnormSRGB:case TextureFormat.ASTC8x6Unorm:case TextureFormat.ASTC8x6UnormSRGB:case TextureFormat.ASTC8x8Unorm:case TextureFormat.ASTC8x8UnormSRGB:case TextureFormat.ASTC10x5Unorm:case TextureFormat.ASTC10x5UnormSRGB:case TextureFormat.ASTC10x6Unorm:case TextureFormat.ASTC10x6UnormSRGB:case TextureFormat.ASTC10x8Unorm:case TextureFormat.ASTC10x8UnormSRGB:case TextureFormat.ASTC10x10Unorm:case TextureFormat.ASTC10x10UnormSRGB:case TextureFormat.ASTC12x10Unorm:case TextureFormat.ASTC12x10UnormSRGB:case TextureFormat.ASTC12x12Unorm:case TextureFormat.ASTC12x12UnormSRGB:return 0;case TextureFormat.R16Uint:case TextureFormat.R16Sint:case TextureFormat.RG16Uint:case TextureFormat.RG16Sint:case TextureFormat.RGBA16Uint:case TextureFormat.RGBA16Sint:case TextureFormat.Depth16Unorm:return 5;case TextureFormat.R16Float:case TextureFormat.RG16Float:case TextureFormat.RGBA16Float:return 2;case TextureFormat.R32Uint:case TextureFormat.R32Sint:case TextureFormat.RG32Uint:case TextureFormat.RG32Sint:case TextureFormat.RGBA32Uint:case TextureFormat.RGBA32Sint:return 7;case TextureFormat.R32Float:case TextureFormat.RG32Float:case TextureFormat.RGBA32Float:case TextureFormat.Depth32Float:return 1;case TextureFormat.Stencil8:throw"No fixed size for Stencil8 format!";case TextureFormat.Depth24Plus:throw"No fixed size for Depth24Plus format!";case TextureFormat.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0},a._GetBlockInformationFromFormat=function(i){switch(i){case TextureFormat.R8Unorm:case TextureFormat.R8Snorm:case TextureFormat.R8Uint:case TextureFormat.R8Sint:return{width:1,height:1,length:1};case TextureFormat.R16Uint:case TextureFormat.R16Sint:case TextureFormat.R16Float:case TextureFormat.RG8Unorm:case TextureFormat.RG8Snorm:case TextureFormat.RG8Uint:case TextureFormat.RG8Sint:return{width:1,height:1,length:2};case TextureFormat.R32Uint:case TextureFormat.R32Sint:case TextureFormat.R32Float:case TextureFormat.RG16Uint:case TextureFormat.RG16Sint:case TextureFormat.RG16Float:case TextureFormat.RGBA8Unorm:case TextureFormat.RGBA8UnormSRGB:case TextureFormat.RGBA8Snorm:case TextureFormat.RGBA8Uint:case TextureFormat.RGBA8Sint:case TextureFormat.BGRA8Unorm:case TextureFormat.BGRA8UnormSRGB:case TextureFormat.RGB9E5UFloat:case TextureFormat.RGB10A2Unorm:case TextureFormat.RG11B10UFloat:return{width:1,height:1,length:4};case TextureFormat.RG32Uint:case TextureFormat.RG32Sint:case TextureFormat.RG32Float:case TextureFormat.RGBA16Uint:case TextureFormat.RGBA16Sint:case TextureFormat.RGBA16Float:return{width:1,height:1,length:8};case TextureFormat.RGBA32Uint:case TextureFormat.RGBA32Sint:case TextureFormat.RGBA32Float:return{width:1,height:1,length:16};case TextureFormat.Stencil8:throw"No fixed size for Stencil8 format!";case TextureFormat.Depth16Unorm:return{width:1,height:1,length:2};case TextureFormat.Depth24Plus:throw"No fixed size for Depth24Plus format!";case TextureFormat.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case TextureFormat.Depth32Float:return{width:1,height:1,length:4};case TextureFormat.Depth24UnormStencil8:return{width:1,height:1,length:4};case TextureFormat.Depth32FloatStencil8:return{width:1,height:1,length:5};case TextureFormat.BC7RGBAUnorm:case TextureFormat.BC7RGBAUnormSRGB:case TextureFormat.BC6HRGBUFloat:case TextureFormat.BC6HRGBFloat:case TextureFormat.BC5RGUnorm:case TextureFormat.BC5RGSnorm:case TextureFormat.BC3RGBAUnorm:case TextureFormat.BC3RGBAUnormSRGB:case TextureFormat.BC2RGBAUnorm:case TextureFormat.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case TextureFormat.BC4RUnorm:case TextureFormat.BC4RSnorm:case TextureFormat.BC1RGBAUnorm:case TextureFormat.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case TextureFormat.ETC2RGB8Unorm:case TextureFormat.ETC2RGB8UnormSRGB:case TextureFormat.ETC2RGB8A1Unorm:case TextureFormat.ETC2RGB8A1UnormSRGB:case TextureFormat.EACR11Unorm:case TextureFormat.EACR11Snorm:return{width:4,height:4,length:8};case TextureFormat.ETC2RGBA8Unorm:case TextureFormat.ETC2RGBA8UnormSRGB:case TextureFormat.EACRG11Unorm:case TextureFormat.EACRG11Snorm:return{width:4,height:4,length:16};case TextureFormat.ASTC4x4Unorm:case TextureFormat.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case TextureFormat.ASTC5x4Unorm:case TextureFormat.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case TextureFormat.ASTC5x5Unorm:case TextureFormat.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case TextureFormat.ASTC6x5Unorm:case TextureFormat.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case TextureFormat.ASTC6x6Unorm:case TextureFormat.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case TextureFormat.ASTC8x5Unorm:case TextureFormat.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case TextureFormat.ASTC8x6Unorm:case TextureFormat.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case TextureFormat.ASTC8x8Unorm:case TextureFormat.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case TextureFormat.ASTC10x5Unorm:case TextureFormat.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case TextureFormat.ASTC10x6Unorm:case TextureFormat.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case TextureFormat.ASTC10x8Unorm:case TextureFormat.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case TextureFormat.ASTC10x10Unorm:case TextureFormat.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case TextureFormat.ASTC12x10Unorm:case TextureFormat.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case TextureFormat.ASTC12x12Unorm:case TextureFormat.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}},a._IsHardwareTexture=function(i){return!!i.release},a._IsInternalTexture=function(i){return!!i.dispose},a.GetCompareFunction=function(i){switch(i){case 519:return CompareFunction.Always;case 514:return CompareFunction.Equal;case 516:return CompareFunction.Greater;case 518:return CompareFunction.GreaterEqual;case 513:return CompareFunction.Less;case 515:return CompareFunction.LessEqual;case 512:return CompareFunction.Never;case 517:return CompareFunction.NotEqual;default:return CompareFunction.Less}},a.IsImageBitmap=function(i){return i.close!==void 0},a.IsImageBitmapArray=function(i){return Array.isArray(i)&&i[0].close!==void 0},a.prototype.setCommandEncoder=function(i){this._commandEncoderForCreation=i},a.IsCompressedFormat=function(i){switch(i){case TextureFormat.BC7RGBAUnormSRGB:case TextureFormat.BC7RGBAUnorm:case TextureFormat.BC6HRGBFloat:case TextureFormat.BC6HRGBUFloat:case TextureFormat.BC5RGSnorm:case TextureFormat.BC5RGUnorm:case TextureFormat.BC4RSnorm:case TextureFormat.BC4RUnorm:case TextureFormat.BC3RGBAUnormSRGB:case TextureFormat.BC3RGBAUnorm:case TextureFormat.BC2RGBAUnormSRGB:case TextureFormat.BC2RGBAUnorm:case TextureFormat.BC1RGBAUnormSRGB:case TextureFormat.BC1RGBAUnorm:case TextureFormat.ETC2RGB8Unorm:case TextureFormat.ETC2RGB8UnormSRGB:case TextureFormat.ETC2RGB8A1Unorm:case TextureFormat.ETC2RGB8A1UnormSRGB:case TextureFormat.ETC2RGBA8Unorm:case TextureFormat.ETC2RGBA8UnormSRGB:case TextureFormat.EACR11Unorm:case TextureFormat.EACR11Snorm:case TextureFormat.EACRG11Unorm:case TextureFormat.EACRG11Snorm:case TextureFormat.ASTC4x4Unorm:case TextureFormat.ASTC4x4UnormSRGB:case TextureFormat.ASTC5x4Unorm:case TextureFormat.ASTC5x4UnormSRGB:case TextureFormat.ASTC5x5Unorm:case TextureFormat.ASTC5x5UnormSRGB:case TextureFormat.ASTC6x5Unorm:case TextureFormat.ASTC6x5UnormSRGB:case TextureFormat.ASTC6x6Unorm:case TextureFormat.ASTC6x6UnormSRGB:case TextureFormat.ASTC8x5Unorm:case TextureFormat.ASTC8x5UnormSRGB:case TextureFormat.ASTC8x6Unorm:case TextureFormat.ASTC8x6UnormSRGB:case TextureFormat.ASTC8x8Unorm:case TextureFormat.ASTC8x8UnormSRGB:case TextureFormat.ASTC10x5Unorm:case TextureFormat.ASTC10x5UnormSRGB:case TextureFormat.ASTC10x6Unorm:case TextureFormat.ASTC10x6UnormSRGB:case TextureFormat.ASTC10x8Unorm:case TextureFormat.ASTC10x8UnormSRGB:case TextureFormat.ASTC10x10Unorm:case TextureFormat.ASTC10x10UnormSRGB:case TextureFormat.ASTC12x10Unorm:case TextureFormat.ASTC12x10UnormSRGB:case TextureFormat.ASTC12x12Unorm:case TextureFormat.ASTC12x12UnormSRGB:return!0}return!1},a.GetWebGPUTextureFormat=function(i,e,o){switch(o===void 0&&(o=!1),e){case 15:return TextureFormat.Depth16Unorm;case 13:return TextureFormat.Depth24PlusStencil8;case 14:return TextureFormat.Depth32Float;case 36492:return o?TextureFormat.BC7RGBAUnormSRGB:TextureFormat.BC7RGBAUnorm;case 36495:return TextureFormat.BC6HRGBUFloat;case 36494:return TextureFormat.BC6HRGBFloat;case 33779:return o?TextureFormat.BC3RGBAUnormSRGB:TextureFormat.BC3RGBAUnorm;case 33778:return o?TextureFormat.BC2RGBAUnormSRGB:TextureFormat.BC2RGBAUnorm;case 33777:case 33776:return o?TextureFormat.BC1RGBAUnormSRGB:TextureFormat.BC1RGBAUnorm;case 37808:return o?TextureFormat.ASTC4x4UnormSRGB:TextureFormat.ASTC4x4Unorm;case 36196:return o?TextureFormat.ETC2RGB8UnormSRGB:TextureFormat.ETC2RGB8Unorm}switch(i){case 3:switch(e){case 6:return TextureFormat.R8Snorm;case 7:return TextureFormat.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return TextureFormat.R8Sint;case 9:return TextureFormat.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return TextureFormat.RGBA8Sint;default:return TextureFormat.RGBA8Snorm}case 0:switch(e){case 6:return TextureFormat.R8Unorm;case 7:return TextureFormat.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return o?TextureFormat.RGBA8UnormSRGB:TextureFormat.RGBA8Unorm;case 12:return o?TextureFormat.BGRA8UnormSRGB:TextureFormat.BGRA8Unorm;case 8:return TextureFormat.R8Uint;case 9:return TextureFormat.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return TextureFormat.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return TextureFormat.RGBA8Unorm}case 4:switch(e){case 8:return TextureFormat.R16Sint;case 9:return TextureFormat.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return TextureFormat.RGBA16Sint;default:return TextureFormat.RGBA16Sint}case 5:switch(e){case 8:return TextureFormat.R16Uint;case 9:return TextureFormat.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return TextureFormat.RGBA16Uint;default:return TextureFormat.RGBA16Uint}case 6:switch(e){case 8:return TextureFormat.R32Sint;case 9:return TextureFormat.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return TextureFormat.RGBA32Sint;default:return TextureFormat.RGBA32Sint}case 7:switch(e){case 8:return TextureFormat.R32Uint;case 9:return TextureFormat.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return TextureFormat.RGBA32Uint;default:return TextureFormat.RGBA32Uint}case 1:switch(e){case 6:return TextureFormat.R32Float;case 7:return TextureFormat.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return TextureFormat.RGBA32Float;default:return TextureFormat.RGBA32Float}case 2:switch(e){case 6:return TextureFormat.R16Float;case 7:return TextureFormat.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return TextureFormat.RGBA16Float;default:return TextureFormat.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:throw"TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV format not supported in WebGPU";case 14:throw"TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV format not supported in WebGPU";case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(e){case 5:return TextureFormat.RGB10A2Unorm;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV";default:return TextureFormat.RGB10A2Unorm}}return o?TextureFormat.RGBA8UnormSRGB:TextureFormat.RGBA8Unorm},a.GetNumChannelsFromWebGPUTextureFormat=function(i){switch(i){case TextureFormat.R8Unorm:case TextureFormat.R8Snorm:case TextureFormat.R8Uint:case TextureFormat.R8Sint:case TextureFormat.BC4RUnorm:case TextureFormat.BC4RSnorm:case TextureFormat.R16Uint:case TextureFormat.R16Sint:case TextureFormat.Depth16Unorm:case TextureFormat.R16Float:case TextureFormat.R32Uint:case TextureFormat.R32Sint:case TextureFormat.R32Float:case TextureFormat.Depth32Float:case TextureFormat.Stencil8:case TextureFormat.Depth24Plus:case TextureFormat.EACR11Unorm:case TextureFormat.EACR11Snorm:return 1;case TextureFormat.RG8Unorm:case TextureFormat.RG8Snorm:case TextureFormat.RG8Uint:case TextureFormat.RG8Sint:case TextureFormat.Depth24UnormStencil8:case TextureFormat.Depth32FloatStencil8:case TextureFormat.BC5RGUnorm:case TextureFormat.BC5RGSnorm:case TextureFormat.RG16Uint:case TextureFormat.RG16Sint:case TextureFormat.RG16Float:case TextureFormat.RG32Uint:case TextureFormat.RG32Sint:case TextureFormat.RG32Float:case TextureFormat.Depth24PlusStencil8:case TextureFormat.EACRG11Unorm:case TextureFormat.EACRG11Snorm:return 2;case TextureFormat.RGB9E5UFloat:case TextureFormat.RG11B10UFloat:case TextureFormat.BC6HRGBUFloat:case TextureFormat.BC6HRGBFloat:case TextureFormat.ETC2RGB8Unorm:case TextureFormat.ETC2RGB8UnormSRGB:return 3;case TextureFormat.RGBA8Unorm:case TextureFormat.RGBA8UnormSRGB:case TextureFormat.RGBA8Snorm:case TextureFormat.RGBA8Uint:case TextureFormat.RGBA8Sint:case TextureFormat.BGRA8Unorm:case TextureFormat.BGRA8UnormSRGB:case TextureFormat.RGB10A2Unorm:case TextureFormat.BC7RGBAUnorm:case TextureFormat.BC7RGBAUnormSRGB:case TextureFormat.BC3RGBAUnorm:case TextureFormat.BC3RGBAUnormSRGB:case TextureFormat.BC2RGBAUnorm:case TextureFormat.BC2RGBAUnormSRGB:case TextureFormat.BC1RGBAUnorm:case TextureFormat.BC1RGBAUnormSRGB:case TextureFormat.RGBA16Uint:case TextureFormat.RGBA16Sint:case TextureFormat.RGBA16Float:case TextureFormat.RGBA32Uint:case TextureFormat.RGBA32Sint:case TextureFormat.RGBA32Float:case TextureFormat.ETC2RGB8A1Unorm:case TextureFormat.ETC2RGB8A1UnormSRGB:case TextureFormat.ETC2RGBA8Unorm:case TextureFormat.ETC2RGBA8UnormSRGB:case TextureFormat.ASTC4x4Unorm:case TextureFormat.ASTC4x4UnormSRGB:case TextureFormat.ASTC5x4Unorm:case TextureFormat.ASTC5x4UnormSRGB:case TextureFormat.ASTC5x5Unorm:case TextureFormat.ASTC5x5UnormSRGB:case TextureFormat.ASTC6x5Unorm:case TextureFormat.ASTC6x5UnormSRGB:case TextureFormat.ASTC6x6Unorm:case TextureFormat.ASTC6x6UnormSRGB:case TextureFormat.ASTC8x5Unorm:case TextureFormat.ASTC8x5UnormSRGB:case TextureFormat.ASTC8x6Unorm:case TextureFormat.ASTC8x6UnormSRGB:case TextureFormat.ASTC8x8Unorm:case TextureFormat.ASTC8x8UnormSRGB:case TextureFormat.ASTC10x5Unorm:case TextureFormat.ASTC10x5UnormSRGB:case TextureFormat.ASTC10x6Unorm:case TextureFormat.ASTC10x6UnormSRGB:case TextureFormat.ASTC10x8Unorm:case TextureFormat.ASTC10x8UnormSRGB:case TextureFormat.ASTC10x10Unorm:case TextureFormat.ASTC10x10UnormSRGB:case TextureFormat.ASTC12x10Unorm:case TextureFormat.ASTC12x10UnormSRGB:case TextureFormat.ASTC12x12Unorm:case TextureFormat.ASTC12x12UnormSRGB:return 4}throw"Unknown format "+i+"!"},a.prototype.invertYPreMultiplyAlpha=function(i,e,o,s,c,d,_,b,k,j,$){var _e,et,tt,rt,it,nt,ot;c===void 0&&(c=!1),d===void 0&&(d=!1),_===void 0&&(_=0),b===void 0&&(b=0),k===void 0&&(k=1);var at=j===void 0,st=this._getPipeline(s,PipelineType.InvertYPremultiplyAlpha,{invertY:c,premultiplyAlpha:d}),ut=st[0],ft=st[1];_=Math.max(_,0),at&&(j=this._device.createCommandEncoder({})),(et=(_e=j).pushDebugGroup)===null||et===void 0||et.call(_e,"internal process texture - invertY="+c+" premultiplyAlpha="+d);var lt;if(a._IsHardwareTexture(i)?(lt=i.underlyingResource,c&&!d&&k===1&&_===0||(i=void 0)):(lt=i,i=void 0),!!lt){var ht=i,pt=(tt=ht==null?void 0:ht._copyInvertYTempTexture)!==null&&tt!==void 0?tt:this.createTexture({width:e,height:o,layers:1},!1,!1,!1,!1,!1,s,1,j,TextureUsage.CopySrc|TextureUsage.RenderAttachment|TextureUsage.TextureBinding),mt=(rt=ht==null?void 0:ht._copyInvertYRenderPassDescr)!==null&&rt!==void 0?rt:{colorAttachments:[{view:pt.createView({format:s,dimension:TextureViewDimension.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadValue:LoadOp.Load,storeOp:StoreOp.Store}]},dt=j.beginRenderPass(mt),gt=(it=ht==null?void 0:ht._copyInvertYBindGroupd)!==null&&it!==void 0?it:this._device.createBindGroup({layout:ft,entries:[{binding:0,resource:lt.createView({format:s,dimension:TextureViewDimension.E2d,baseMipLevel:b,mipLevelCount:1,arrayLayerCount:k,baseArrayLayer:_})}]});dt.setPipeline(ut),dt.setBindGroup(0,gt),dt.draw(4,1,0,0),dt.endPass(),j.copyTextureToTexture({texture:pt},{texture:lt,mipLevel:b,origin:{x:0,y:0,z:_}},{width:e,height:o,depthOrArrayLayers:1}),ht?(ht._copyInvertYTempTexture=pt,ht._copyInvertYRenderPassDescr=mt,ht._copyInvertYBindGroupd=gt):this._deferredReleaseTextures.push([pt,null]),(ot=(nt=j).popDebugGroup)===null||ot===void 0||ot.call(nt),at&&(this._device.queue.submit([j.finish()]),j=null)}},a.prototype.copyWithInvertY=function(i,e,o,s){var c,d,_,b,k=s===void 0,j=this._getPipeline(e,PipelineType.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1}),$=j[0],_e=j[1];k&&(s=this._device.createCommandEncoder({})),(d=(c=s).pushDebugGroup)===null||d===void 0||d.call(c,"internal copy texture with invertY");var et=s.beginRenderPass(o),tt=this._device.createBindGroup({layout:_e,entries:[{binding:0,resource:i}]});et.setPipeline($),et.setBindGroup(0,tt),et.draw(4,1,0,0),et.endPass(),(b=(_=s).popDebugGroup)===null||b===void 0||b.call(_),k&&(this._device.queue.submit([s.finish()]),s=null)},a.prototype.createTexture=function(i,e,o,s,c,d,_,b,k,j,$){e===void 0&&(e=!1),o===void 0&&(o=!1),s===void 0&&(s=!1),c===void 0&&(c=!1),d===void 0&&(d=!1),_===void 0&&(_=TextureFormat.RGBA8Unorm),b===void 0&&(b=1),j===void 0&&(j=-1),$===void 0&&($=0);var _e=i.layers||1,et={width:i.width,height:i.height,depthOrArrayLayers:_e},tt=a.IsCompressedFormat(_),rt=e?a.ComputeNumMipmapLevels(i.width,i.height):1,it=j>=0?j:TextureUsage.CopySrc|TextureUsage.CopyDst|TextureUsage.TextureBinding;$|=e&&!tt?TextureUsage.CopySrc|TextureUsage.RenderAttachment:0,tt||($|=TextureUsage.RenderAttachment|TextureUsage.CopyDst);var nt=this._device.createTexture({size:et,dimension:d?TextureDimension.E3d:TextureDimension.E2d,format:_,usage:it|$,sampleCount:b,mipLevelCount:rt});return a.IsImageBitmap(i)&&(this.updateTexture(i,nt,i.width,i.height,_e,_,0,0,s,c,0,0,k),e&&o&&this.generateMipmaps(nt,_,rt,0,k)),nt},a.prototype.createCubeTexture=function(i,e,o,s,c,d,_,b,k,j){e===void 0&&(e=!1),o===void 0&&(o=!1),s===void 0&&(s=!1),c===void 0&&(c=!1),d===void 0&&(d=TextureFormat.RGBA8Unorm),_===void 0&&(_=1),k===void 0&&(k=-1),j===void 0&&(j=0);var $=a.IsImageBitmapArray(i)?i[0].width:i.width,_e=a.IsImageBitmapArray(i)?i[0].height:i.height,et=a.IsCompressedFormat(d),tt=e?a.ComputeNumMipmapLevels($,_e):1,rt=k>=0?k:TextureUsage.CopySrc|TextureUsage.CopyDst|TextureUsage.TextureBinding;j|=e&&!et?TextureUsage.CopySrc|TextureUsage.RenderAttachment:0,et||(j|=TextureUsage.RenderAttachment|TextureUsage.CopyDst);var it=this._device.createTexture({size:{width:$,height:_e,depthOrArrayLayers:6},dimension:TextureDimension.E2d,format:d,usage:rt|j,sampleCount:_,mipLevelCount:tt});return a.IsImageBitmapArray(i)&&(this.updateCubeTextures(i,it,$,_e,d,s,c,0,0,b),e&&o&&this.generateCubeMipmaps(it,d,tt,b)),it},a.prototype.generateCubeMipmaps=function(i,e,o,s){var c,d,_,b,k=s===void 0;k&&(s=this._device.createCommandEncoder({})),(d=(c=s).pushDebugGroup)===null||d===void 0||d.call(c,"create cube mipmaps - "+o+" levels");for(var j=0;j<6;++j)this.generateMipmaps(i,e,o,j,s);(b=(_=s).popDebugGroup)===null||b===void 0||b.call(_),k&&(this._device.queue.submit([s.finish()]),s=null)},a.prototype.generateMipmaps=function(i,e,o,s,c){var d,_,b,k,j,$,_e,et;s===void 0&&(s=0);var tt=c===void 0,rt=this._getPipeline(e),it=rt[0],nt=rt[1];s=Math.max(s,0),tt&&(c=this._device.createCommandEncoder({})),(_=(d=c).pushDebugGroup)===null||_===void 0||_.call(d,"create mipmaps for face #"+s+" - "+o+" levels");var ot;if(a._IsHardwareTexture(i)?(ot=i.underlyingResource,i._mipmapGenRenderPassDescr=i._mipmapGenRenderPassDescr||[],i._mipmapGenBindGroup=i._mipmapGenBindGroup||[]):(ot=i,i=void 0),!!ot){for(var at=i,st=1;st<o;++st){var ut=(k=(b=at==null?void 0:at._mipmapGenRenderPassDescr[s])===null||b===void 0?void 0:b[st-1])!==null&&k!==void 0?k:{colorAttachments:[{view:ot.createView({format:e,dimension:TextureViewDimension.E2d,baseMipLevel:st,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:s}),loadValue:LoadOp.Load,storeOp:StoreOp.Store}]};at&&(at._mipmapGenRenderPassDescr[s]=at._mipmapGenRenderPassDescr[s]||[],at._mipmapGenRenderPassDescr[s][st-1]=ut);var ft=c.beginRenderPass(ut),lt=($=(j=at==null?void 0:at._mipmapGenBindGroup[s])===null||j===void 0?void 0:j[st-1])!==null&&$!==void 0?$:this._device.createBindGroup({layout:nt,entries:[{binding:0,resource:this._mipmapSampler},{binding:1,resource:ot.createView({format:e,dimension:TextureViewDimension.E2d,baseMipLevel:st-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:s})}]});at&&(at._mipmapGenBindGroup[s]=at._mipmapGenBindGroup[s]||[],at._mipmapGenBindGroup[s][st-1]=lt),ft.setPipeline(it),ft.setBindGroup(0,lt),ft.draw(4,1,0,0),ft.endPass()}(et=(_e=c).popDebugGroup)===null||et===void 0||et.call(_e),tt&&(this._device.queue.submit([c.finish()]),c=null)}},a.prototype.createGPUTextureForInternalTexture=function(i,e,o,s,c){i._hardwareTexture||(i._hardwareTexture=new WebGPUHardwareTexture),e===void 0&&(e=i.width),o===void 0&&(o=i.height),s===void 0&&(s=i.depth);var d=i._hardwareTexture;d.format=a.GetWebGPUTextureFormat(i.type,i.format,i._useSRGBBuffer),d.textureUsages=i._source===InternalTextureSource.RenderTarget||i.source===InternalTextureSource.MultiRenderTarget?TextureUsage.TextureBinding|TextureUsage.CopySrc|TextureUsage.RenderAttachment:i._source===InternalTextureSource.DepthStencil?TextureUsage.TextureBinding|TextureUsage.RenderAttachment:-1,d.textureAdditionalUsages=(c!=null?c:0)&1?TextureUsage.StorageBinding:0;var _=i.generateMipMaps,b=s||1;if(i.isCube){var k=this.createCubeTexture({width:e,height:o},i.generateMipMaps,i.generateMipMaps,i.invertY,!1,d.format,1,this._commandEncoderForCreation,d.textureUsages,d.textureAdditionalUsages);d.set(k),d.createView({format:d.format,dimension:TextureViewDimension.Cube,mipLevelCount:_?a.ComputeNumMipmapLevels(e,o):1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6,aspect:TextureAspect.All})}else{var k=this.createTexture({width:e,height:o,layers:b},i.generateMipMaps,i.generateMipMaps,i.invertY,!1,i.is3D,d.format,1,this._commandEncoderForCreation,d.textureUsages,d.textureAdditionalUsages);d.set(k),d.createView({format:d.format,dimension:i.is2DArray?TextureViewDimension.E2dArray:i.is3D?TextureDimension.E3d:TextureViewDimension.E2d,mipLevelCount:_?a.ComputeNumMipmapLevels(e,o):1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i.is3D?1:b,aspect:TextureAspect.All})}return i.width=i.baseWidth=e,i.height=i.baseHeight=o,i.depth=i.baseDepth=s,this.createMSAATexture(i,i.samples),d},a.prototype.createMSAATexture=function(i,e){var o=i._hardwareTexture;if(o!=null&&o.msaaTexture&&(this.releaseTexture(o.msaaTexture),o.msaaTexture=null),!(!o||(e!=null?e:1)<=1)){var s=i.width,c=i.height,d=i.depth||1;if(i.isCube){var _=this.createCubeTexture({width:s,height:c},!1,!1,i.invertY,!1,o.format,e,this._commandEncoderForCreation,o.textureUsages,o.textureAdditionalUsages);o.setMSAATexture(_)}else{var _=this.createTexture({width:s,height:c,layers:d},!1,!1,i.invertY,!1,i.is3D,o.format,e,this._commandEncoderForCreation,o.textureUsages,o.textureAdditionalUsages);o.setMSAATexture(_)}}},a.prototype.updateCubeTextures=function(i,e,o,s,c,d,_,b,k,j){d===void 0&&(d=!1),_===void 0&&(_=!1),b===void 0&&(b=0),k===void 0&&(k=0);for(var $=[0,3,1,4,2,5],_e=0;_e<$.length;++_e){var et=i[$[_e]];this.updateTexture(et,e,o,s,1,c,_e,0,d,_,b,k,j)}},a.prototype.updateTexture=function(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt){_===void 0&&(_=0),b===void 0&&(b=0),k===void 0&&(k=!1),j===void 0&&(j=!1),$===void 0&&($=0),_e===void 0&&(_e=0);var rt=a._IsInternalTexture(e)?e._hardwareTexture.underlyingResource:e,it=a._GetBlockInformationFromFormat(d),nt=a._IsInternalTexture(e)?e._hardwareTexture:e,ot={texture:rt,origin:{x:$,y:_e,z:Math.max(_,0)},mipLevel:b,premultipliedAlpha:j},at={width:Math.ceil(o/it.width)*it.width,height:Math.ceil(s/it.height)*it.height,depthOrArrayLayers:c||1};if(i.byteLength!==void 0){i=i;var st=Math.ceil(o/it.width)*it.length,ut=Math.ceil(st/256)*256===st;if(ut){var ft=et===void 0;ft&&(et=this._device.createCommandEncoder({}));var lt=this._bufferManager.createRawBuffer(i.byteLength,BufferUsage.MapWrite|BufferUsage.CopySrc,!0),ht=lt.getMappedRange();new Uint8Array(ht).set(i),lt.unmap(),et.copyBufferToTexture({buffer:lt,offset:0,bytesPerRow:st,rowsPerImage:s},ot,at),ft&&(this._device.queue.submit([et.finish()]),et=null),this._bufferManager.releaseBuffer(lt)}else this._device.queue.writeTexture(ot,i,{offset:0,bytesPerRow:st,rowsPerImage:s},at);(k||j)&&this.invertYPreMultiplyAlpha(nt,o,s,d,k,j,_,b,c||1,et,tt)}else if(i=i,k)if(ot.premultipliedAlpha=!1,a._IsInternalTexture(e)&&$===0&&_e===0&&o===e.width&&s===e.height)this._device.queue.copyExternalImageToTexture({source:i},ot,at),this.invertYPreMultiplyAlpha(nt,o,s,d,k,j,_,b,c||1,void 0,tt);else{et=this._device.createCommandEncoder({});var pt=this.createTexture({width:o,height:s,layers:1},!1,!1,!1,!1,!1,d,1,et,TextureUsage.CopySrc|TextureUsage.TextureBinding);this._deferredReleaseTextures.push([pt,null]),at.depthOrArrayLayers=1,this._device.queue.copyExternalImageToTexture({source:i},{texture:pt},at),at.depthOrArrayLayers=c||1,this.invertYPreMultiplyAlpha(pt,o,s,d,k,j,_,b,c||1,et,tt),et.copyTextureToTexture({texture:pt},ot,at),this._device.queue.submit([et.finish()]),et=null}else this._device.queue.copyExternalImageToTexture({source:i},ot,at)},a.prototype.readPixels=function(i,e,o,s,c,d,_,b,k,j){_===void 0&&(_=0),b===void 0&&(b=0),k===void 0&&(k=null),j===void 0&&(j=!1);var $=a._GetBlockInformationFromFormat(d),_e=Math.ceil(s/$.width)*$.length,et=Math.ceil(_e/256)*256,tt=et*c,rt=this._bufferManager.createRawBuffer(tt,BufferUsage.MapRead|BufferUsage.CopyDst),it=this._device.createCommandEncoder({});return it.copyTextureToBuffer({texture:i,mipLevel:b,origin:{x:e,y:o,z:Math.max(_,0)}},{buffer:rt,offset:0,bytesPerRow:et},{width:s,height:c,depthOrArrayLayers:1}),this._device.queue.submit([it.finish()]),this._bufferManager.readDataFromBuffer(rt,tt,s,c,_e,et,a._GetTextureTypeFromFormat(d),0,k,!0,j)},a.prototype.releaseTexture=function(i){if(a._IsInternalTexture(i)){var e=i._hardwareTexture,o=i._irradianceTexture;this._deferredReleaseTextures.push([e,o])}else this._deferredReleaseTextures.push([i,null])},a.prototype.destroyDeferredTextures=function(){for(var i=0;i<this._deferredReleaseTextures.length;++i){var e=this._deferredReleaseTextures[i],o=e[0],s=e[1];o&&(a._IsHardwareTexture(o)?o.release():o.destroy()),s==null||s.dispose()}this._deferredReleaseTextures.length=0},a}(),WebGPUDataBuffer=function(a){__extends(i,a);function i(e){var o=a.call(this)||this;return o._buffer=e,o}return Object.defineProperty(i.prototype,"underlyingResource",{get:function(){return this._buffer},enumerable:!1,configurable:!0}),i}(DataBuffer),WebGPUBufferManager=function(){function a(i){this._deferredReleaseBuffers=[],this._device=i}return a._IsGPUBuffer=function(i){return i.underlyingResource===void 0},a.prototype.createRawBuffer=function(i,e,o){o===void 0&&(o=!1);var s=i.byteLength!==void 0?i.byteLength+3&-4:i+3&-4,c={mappedAtCreation:o,size:s,usage:e};return this._device.createBuffer(c)},a.prototype.createBuffer=function(i,e){var o=i.byteLength!==void 0,s=this.createRawBuffer(i,e),c=new WebGPUDataBuffer(s);return c.references=1,c.capacity=o?i.byteLength:i,o&&this.setSubData(c,0,i),c},a.prototype.setRawData=function(i,e,o,s,c){this._device.queue.writeBuffer(i,e,o.buffer,s,c)},a.prototype.setSubData=function(i,e,o,s,c){s===void 0&&(s=0),c===void 0&&(c=0);var d=i.underlyingResource;c=c||o.byteLength,c=Math.min(c,i.capacity-e);var _=o.byteOffset+s,b=_+c,k=c+3&-4;if(k!==c){var j=new Uint8Array(o.buffer.slice(_,b));o=new Uint8Array(k),o.set(j),s=0,_=0,b=k,c=k}for(var $=1024*1024*15,_e=0;b-(_+_e)>$;)this._device.queue.writeBuffer(d,e+_e,o.buffer,_+_e,$),_e+=$;this._device.queue.writeBuffer(d,e+_e,o.buffer,_+_e,c-_e)},a.prototype._GetHalfFloatAsFloatRGBAArrayBuffer=function(i,e,o){o||(o=new Float32Array(i));for(var s=new Uint16Array(e);i--;)o[i]=FromHalfFloat(s[i]);return o},a.prototype.readDataFromBuffer=function(i,e,o,s,c,d,_,b,k,j,$){var _e=this;_===void 0&&(_=0),b===void 0&&(b=0),k===void 0&&(k=null),j===void 0&&(j=!0),$===void 0&&($=!1);var et=_===1?2:_===2?1:0;return new Promise(function(tt,rt){i.mapAsync(MapMode.Read,b,e).then(function(){var it=i.getMappedRange(b,e),nt=k;if($)nt===null?nt=allocateAndCopyTypedBuffer(_,e,!0,it):nt=allocateAndCopyTypedBuffer(_,nt.buffer,void 0,it);else if(nt===null)switch(et){case 0:nt=new Uint8Array(e),nt.set(new Uint8Array(it));break;case 1:nt=_e._GetHalfFloatAsFloatRGBAArrayBuffer(e/2,it);break;case 2:nt=new Float32Array(e/4),nt.set(new Float32Array(it));break}else switch(et){case 0:nt=new Uint8Array(nt.buffer),nt.set(new Uint8Array(it));break;case 1:nt=_e._GetHalfFloatAsFloatRGBAArrayBuffer(e/2,it,k);break;case 2:nt=new Float32Array(nt.buffer),nt.set(new Float32Array(it));break}if(c!==d){et===1&&!$&&(c*=2,d*=2);for(var ot=new Uint8Array(nt.buffer),at=c,st=0,ut=1;ut<s;++ut){st=ut*d;for(var ft=0;ft<c;++ft)ot[at++]=ot[st++]}et!==0&&!$?nt=new Float32Array(ot.buffer,0,at/4):nt=new Uint8Array(ot.buffer,0,at)}i.unmap(),j&&_e.releaseBuffer(i),tt(nt)},function(it){return rt(it)})})},a.prototype.releaseBuffer=function(i){return a._IsGPUBuffer(i)?(this._deferredReleaseBuffers.push(i),!0):(i.references--,i.references===0?(this._deferredReleaseBuffers.push(i.underlyingResource),!0):!1)},a.prototype.destroyDeferredBuffers=function(){for(var i=0;i<this._deferredReleaseBuffers.length;++i)this._deferredReleaseBuffers[i].destroy();this._deferredReleaseBuffers.length=0},a}(),WebGPURenderPassWrapper=function(){function a(){this.colorAttachmentGPUTextures=[],this.reset()}return a.prototype.reset=function(i){i===void 0&&(i=!1),this.renderPass=null,i&&(this.renderPassDescriptor=null,this.colorAttachmentViewDescriptor=null,this.depthAttachmentViewDescriptor=null,this.colorAttachmentGPUTextures=[],this.depthTextureFormat=void 0)},a}(),filterToBits=[0|0<<1|0<<2,0|0<<1|0<<2,1|1<<1|0<<2,1|1<<1|1<<2,0|0<<1|0<<2,0|1<<1|0<<2,0|1<<1|1<<2,0|1<<1|0<<2,0|0<<1|1<<2,1|0<<1|0<<2,1|0<<1|1<<2,1|1<<1|0<<2,1|0<<1|0<<2],comparisonFunctionToBits=[0<<3|0<<4|0<<5|0<<6,0<<3|0<<4|0<<5|1<<6,0<<3|0<<4|1<<5|0<<6,0<<3|0<<4|1<<5|1<<6,0<<3|1<<4|0<<5|0<<6,0<<3|1<<4|0<<5|1<<6,0<<3|1<<4|1<<5|0<<6,0<<3|1<<4|1<<5|1<<6,1<<3|0<<4|0<<5|0<<6],filterNoMipToBits=[0<<7,1<<7,1<<7,0<<7,0<<7,0<<7,0<<7,1<<7,0<<7,0<<7,0<<7,0<<7,1<<7],WebGPUCacheSampler=function(){function a(i){this._samplers={},this._device=i,this.disabled=!1}return a.GetSamplerHashCode=function(i){var e,o,s,c=i._cachedAnisotropicFilteringLevel&&i._cachedAnisotropicFilteringLevel>1?4:1,d=filterToBits[i.samplingMode]+comparisonFunctionToBits[(i._comparisonFunction||514)-512+1]+filterNoMipToBits[i.samplingMode]+(((e=i._cachedWrapU)!==null&&e!==void 0?e:1)<<8)+(((o=i._cachedWrapV)!==null&&o!==void 0?o:1)<<10)+(((s=i._cachedWrapR)!==null&&s!==void 0?s:1)<<12)+((i.useMipMaps?1:0)<<14)+(c<<15);return d},a._GetSamplerFilterDescriptor=function(i,e){var o,s,c,d,_,b=i.useMipMaps;switch(i.samplingMode){case 11:o=FilterMode.Linear,s=FilterMode.Linear,c=FilterMode.Nearest,b||(d=_=0);break;case 3:case 3:o=FilterMode.Linear,s=FilterMode.Linear,b?c=FilterMode.Linear:(c=FilterMode.Nearest,d=_=0);break;case 8:o=FilterMode.Nearest,s=FilterMode.Nearest,b?c=FilterMode.Linear:(c=FilterMode.Nearest,d=_=0);break;case 4:o=FilterMode.Nearest,s=FilterMode.Nearest,c=FilterMode.Nearest,b||(d=_=0);break;case 5:o=FilterMode.Nearest,s=FilterMode.Linear,c=FilterMode.Nearest,b||(d=_=0);break;case 6:o=FilterMode.Nearest,s=FilterMode.Linear,b?c=FilterMode.Linear:(c=FilterMode.Nearest,d=_=0);break;case 7:o=FilterMode.Nearest,s=FilterMode.Linear,c=FilterMode.Nearest,d=_=0;break;case 1:case 1:o=FilterMode.Nearest,s=FilterMode.Nearest,c=FilterMode.Nearest,d=_=0;break;case 9:o=FilterMode.Linear,s=FilterMode.Nearest,c=FilterMode.Nearest,b||(d=_=0);break;case 10:o=FilterMode.Linear,s=FilterMode.Nearest,b?c=FilterMode.Linear:(c=FilterMode.Nearest,d=_=0);break;case 2:case 2:o=FilterMode.Linear,s=FilterMode.Linear,c=FilterMode.Nearest,d=_=0;break;case 12:o=FilterMode.Linear,s=FilterMode.Nearest,c=FilterMode.Nearest,d=_=0;break;default:o=FilterMode.Nearest,s=FilterMode.Nearest,c=FilterMode.Nearest,d=_=0;break}return e>1&&(d!==0||_!==0)?{magFilter:FilterMode.Linear,minFilter:FilterMode.Linear,mipmapFilter:FilterMode.Linear,anisotropyEnabled:!0}:{magFilter:o,minFilter:s,mipmapFilter:c,lodMinClamp:d,lodMaxClamp:_}},a._GetWrappingMode=function(i){switch(i){case 1:return AddressMode.Repeat;case 0:return AddressMode.ClampToEdge;case 2:return AddressMode.MirrorRepeat}return AddressMode.Repeat},a._GetSamplerWrappingDescriptor=function(i){return{addressModeU:this._GetWrappingMode(i._cachedWrapU),addressModeV:this._GetWrappingMode(i._cachedWrapV),addressModeW:this._GetWrappingMode(i._cachedWrapR)}},a._GetSamplerDescriptor=function(i){var e=i.useMipMaps&&i._cachedAnisotropicFilteringLevel&&i._cachedAnisotropicFilteringLevel>1?4:1,o=this._GetSamplerFilterDescriptor(i,e);return __assign(__assign(__assign({},o),this._GetSamplerWrappingDescriptor(i)),{compare:i._comparisonFunction?WebGPUTextureHelper.GetCompareFunction(i._comparisonFunction):void 0,maxAnisotropy:o.anisotropyEnabled?e:1})},a.prototype.getSampler=function(i,e,o){if(e===void 0&&(e=!1),o===void 0&&(o=0),this.disabled)return this._device.createSampler(a._GetSamplerDescriptor(i));e?o=0:o===0&&(o=a.GetSamplerHashCode(i));var s=e?void 0:this._samplers[o];return s||(s=this._device.createSampler(a._GetSamplerDescriptor(i)),e||(this._samplers[o]=s)),s},a}(),StatePosition;(function(a){a[a.StencilReadMask=0]="StencilReadMask",a[a.StencilWriteMask=1]="StencilWriteMask",a[a.DepthBias=2]="DepthBias",a[a.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",a[a.MRTAttachments1=4]="MRTAttachments1",a[a.MRTAttachments2=5]="MRTAttachments2",a[a.DepthStencilState=6]="DepthStencilState",a[a.RasterizationState=7]="RasterizationState",a[a.ColorStates=8]="ColorStates",a[a.ShaderStage=9]="ShaderStage",a[a.TextureStage=10]="TextureStage",a[a.VertexState=11]="VertexState",a[a.NumStates=12]="NumStates"})(StatePosition||(StatePosition={}));var textureFormatToIndex={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2unorm:22,rg32uint:23,rg32sint:24,rg32float:25,rgba16uint:26,rgba16sint:27,rgba16float:28,rgba32uint:29,rgba32sint:30,rgba32float:31,stencil8:32,depth16unorm:33,depth24plus:34,"depth24plus-stencil8":35,depth32float:36,"depth24unorm-stencil8":37,"depth32float-stencil8":38},alphaBlendFactorToIndex={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},stencilOpToIndex={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},WebGPUCacheRenderPipeline=function(){function a(i,e,o){this._device=i,this._useTextureStage=o,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=e,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=i.limits.maxVertexBufferArrayStride||2048,this.reset()}return a.prototype.reset=function(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[TextureFormat.BGRA8Unorm],this.setColorFormat(TextureFormat.BGRA8Unorm),this.setMRTAttachments([],[]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(TextureFormat.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)},Object.defineProperty(a.prototype,"colorFormats",{get:function(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat},enumerable:!1,configurable:!0}),a.prototype.getRenderPipeline=function(i,e,o,s){if(s===void 0&&(s=0),this.disabled){var c=a._GetTopology(i);return this._setVertexState(e),this._parameter.pipeline=this._createRenderPipeline(e,c,o),a.NumCacheMiss++,a._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(e.uniqueId),this._setRasterizationState(i,o),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(e),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,a.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return a.NumCacheHitWithHash++,this._parameter.pipeline;var d=a._GetTopology(i);return this._parameter.pipeline=this._createRenderPipeline(e,d,o),this._setRenderPipeline(this._parameter),a.NumCacheMiss++,a._NumPipelineCreationCurrentFrame++,this._parameter.pipeline},a.prototype.endFrame=function(){a.NumPipelineCreationLastFrame=a._NumPipelineCreationCurrentFrame,a._NumPipelineCreationCurrentFrame=0},a.prototype.setAlphaToCoverage=function(i){this._alphaToCoverageEnabled=i},a.prototype.setFrontFace=function(i){this._frontFace=i},a.prototype.setCullEnabled=function(i){this._cullEnabled=i},a.prototype.setCullFace=function(i){this._cullFace=i},a.prototype.setClampDepth=function(i){this._clampDepth=i},a.prototype.resetDepthCullingState=function(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)},a.prototype.setDepthCullingState=function(i,e,o,s,c,d,_,b){this._depthWriteEnabled=_,this._depthTestEnabled=d,this._depthCompare=(b!=null?b:519)-512,this._cullFace=o,this._cullEnabled=i,this._frontFace=e,this.setDepthBiasSlopeScale(s),this.setDepthBias(c)},a.prototype.setDepthBias=function(i){this._depthBias!==i&&(this._depthBias=i,this._states[StatePosition.DepthBias]=i,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.DepthBias))},a.prototype.setDepthBiasSlopeScale=function(i){this._depthBiasSlopeScale!==i&&(this._depthBiasSlopeScale=i,this._states[StatePosition.DepthBiasSlopeScale]=i,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.DepthBiasSlopeScale))},a.prototype.setColorFormat=function(i){this._webgpuColorFormat[0]=i,this._colorFormat=textureFormatToIndex[i]},a.prototype.setMRTAttachments=function(i,e){var o;if(i.length>10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtAttachments=i,this.mrtTextureArray=e;for(var s=[0,0],c=0,d=0,_=0,b=0;b<i.length;++b){var k=i[b];if(k!==0){var j=e[k-1],$=j==null?void 0:j._hardwareTexture;this._mrtFormats[_]=(o=$==null?void 0:$.format)!==null&&o!==void 0?o:this._webgpuColorFormat[0],s[c]+=textureFormatToIndex[this._mrtFormats[_]]<<d,d+=6,_++,d>=32&&(d=0,c++)}}this._mrtFormats.length=_,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[StatePosition.MRTAttachments1]=s[0],this._states[StatePosition.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.MRTAttachments1))},a.prototype.setAlphaBlendEnabled=function(i){this._alphaBlendEnabled=i},a.prototype.setAlphaBlendFactors=function(i,e){this._alphaBlendFuncParams=i,this._alphaBlendEqParams=e},a.prototype.setWriteMask=function(i){this._writeMask=i},a.prototype.setDepthStencilFormat=function(i){this._webgpuDepthStencilFormat=i,this._depthStencilFormat=i===void 0?0:textureFormatToIndex[i]},a.prototype.setDepthTestEnabled=function(i){this._depthTestEnabled=i},a.prototype.setDepthWriteEnabled=function(i){this._depthWriteEnabled=i},a.prototype.setDepthCompare=function(i){this._depthCompare=(i!=null?i:519)-512},a.prototype.setStencilEnabled=function(i){this._stencilEnabled=i},a.prototype.setStencilCompare=function(i){this._stencilFrontCompare=(i!=null?i:519)-512},a.prototype.setStencilDepthFailOp=function(i){this._stencilFrontDepthFailOp=i===null?1:stencilOpToIndex[i]},a.prototype.setStencilPassOp=function(i){this._stencilFrontPassOp=i===null?2:stencilOpToIndex[i]},a.prototype.setStencilFailOp=function(i){this._stencilFrontFailOp=i===null?1:stencilOpToIndex[i]},a.prototype.setStencilReadMask=function(i){this._stencilReadMask!==i&&(this._stencilReadMask=i,this._states[StatePosition.StencilReadMask]=i,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.StencilReadMask))},a.prototype.setStencilWriteMask=function(i){this._stencilWriteMask!==i&&(this._stencilWriteMask=i,this._states[StatePosition.StencilWriteMask]=i,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.StencilWriteMask))},a.prototype.resetStencilState=function(){this.setStencilState(!1,519,7680,7681,7680,255,255)},a.prototype.setStencilState=function(i,e,o,s,c,d,_){this._stencilEnabled=i,this._stencilFrontCompare=(e!=null?e:519)-512,this._stencilFrontDepthFailOp=o===null?1:stencilOpToIndex[o],this._stencilFrontPassOp=s===null?2:stencilOpToIndex[s],this._stencilFrontFailOp=c===null?1:stencilOpToIndex[c],this.setStencilReadMask(d),this.setStencilWriteMask(_)},a.prototype.setBuffers=function(i,e,o){this._vertexBuffers=i,this._overrideVertexBuffers=o,this._indexBuffer=e},a._GetTopology=function(i){switch(i){case 0:return PrimitiveTopology.TriangleList;case 2:return PrimitiveTopology.PointList;case 1:return PrimitiveTopology.LineList;case 3:return PrimitiveTopology.PointList;case 4:return PrimitiveTopology.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return PrimitiveTopology.LineStrip;case 7:return PrimitiveTopology.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return PrimitiveTopology.TriangleList}},a._GetAphaBlendOperation=function(i){switch(i){case 32774:return BlendOperation.Add;case 32778:return BlendOperation.Subtract;case 32779:return BlendOperation.ReverseSubtract;case 32775:return BlendOperation.Min;case 32776:return BlendOperation.Max;default:return BlendOperation.Add}},a._GetAphaBlendFactor=function(i){switch(i){case 0:return BlendFactor.Zero;case 1:return BlendFactor.One;case 768:return BlendFactor.Src;case 769:return BlendFactor.OneMinusSrc;case 770:return BlendFactor.SrcAlpha;case 771:return BlendFactor.OneMinusSrcAlpha;case 772:return BlendFactor.DstAlpha;case 773:return BlendFactor.OneMinusDstAlpha;case 774:return BlendFactor.Dst;case 775:return BlendFactor.OneMinusDst;case 776:return BlendFactor.SrcAlphaSaturated;case 32769:return BlendFactor.Constant;case 32770:return BlendFactor.OneMinusConstant;case 32771:return BlendFactor.Constant;case 32772:return BlendFactor.OneMinusConstant;default:return BlendFactor.One}},a._GetCompareFunction=function(i){switch(i){case 0:return CompareFunction.Never;case 1:return CompareFunction.Less;case 2:return CompareFunction.Equal;case 3:return CompareFunction.LessEqual;case 4:return CompareFunction.Greater;case 5:return CompareFunction.NotEqual;case 6:return CompareFunction.GreaterEqual;case 7:return CompareFunction.Always}return CompareFunction.Never},a._GetStencilOpFunction=function(i){switch(i){case 0:return StencilOperation.Zero;case 1:return StencilOperation.Keep;case 2:return StencilOperation.Replace;case 3:return StencilOperation.IncrementClamp;case 4:return StencilOperation.DecrementClamp;case 5:return StencilOperation.Invert;case 6:return StencilOperation.IncrementWrap;case 7:return StencilOperation.DecrementWrap}return StencilOperation.Keep},a._GetVertexInputDescriptorFormat=function(i){var e=i.type,o=i.normalized,s=i.getSize();switch(e){case VertexBuffer.BYTE:switch(s){case 1:case 2:return o?VertexFormat.Snorm8x2:VertexFormat.Sint8x2;case 3:case 4:return o?VertexFormat.Snorm8x4:VertexFormat.Sint8x4}break;case VertexBuffer.UNSIGNED_BYTE:switch(s){case 1:case 2:return o?VertexFormat.Unorm8x2:VertexFormat.Uint8x2;case 3:case 4:return o?VertexFormat.Unorm8x4:VertexFormat.Uint8x4}break;case VertexBuffer.SHORT:switch(s){case 1:case 2:return o?VertexFormat.Snorm16x2:VertexFormat.Sint16x2;case 3:case 4:return o?VertexFormat.Snorm16x4:VertexFormat.Sint16x4}break;case VertexBuffer.UNSIGNED_SHORT:switch(s){case 1:case 2:return o?VertexFormat.Unorm16x2:VertexFormat.Uint16x2;case 3:case 4:return o?VertexFormat.Unorm16x4:VertexFormat.Uint16x4}break;case VertexBuffer.INT:switch(s){case 1:return VertexFormat.Sint32;case 2:return VertexFormat.Sint32x2;case 3:return VertexFormat.Sint32x3;case 4:return VertexFormat.Sint32x4}break;case VertexBuffer.UNSIGNED_INT:switch(s){case 1:return VertexFormat.Uint32;case 2:return VertexFormat.Uint32x2;case 3:return VertexFormat.Uint32x3;case 4:return VertexFormat.Uint32x4}break;case VertexBuffer.FLOAT:switch(s){case 1:return VertexFormat.Float32;case 2:return VertexFormat.Float32x2;case 3:return VertexFormat.Float32x3;case 4:return VertexFormat.Float32x4}break}throw new Error("Invalid Format '"+i.getKind()+"' - type="+e+", normalized="+o+", size="+s)},a.prototype._getAphaBlendState=function(){return this._alphaBlendEnabled?{srcFactor:a._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:a._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:a._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null},a.prototype._getColorBlendState=function(){return this._alphaBlendEnabled?{srcFactor:a._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:a._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:a._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null},a.prototype._setShaderStage=function(i){this._shaderId!==i&&(this._shaderId=i,this._states[StatePosition.ShaderStage]=i,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.ShaderStage))},a.prototype._setRasterizationState=function(i,e){var o=this._frontFace,s=this._cullEnabled?this._cullFace:0,c=this._clampDepth?1:0,d=this._alphaToCoverageEnabled?1:0,_=o-1+(s<<1)+(c<<3)+(d<<4)+(i<<5)+(e<<8);this._rasterizationState!==_&&(this._rasterizationState=_,this._states[StatePosition.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.RasterizationState))},a.prototype._setColorStates=function(){var i=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(i+=((this._alphaBlendFuncParams[0]===null?2:alphaBlendFactorToIndex[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:alphaBlendFactorToIndex[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:alphaBlendFactorToIndex[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:alphaBlendFactorToIndex[this._alphaBlendFuncParams[3]])<<12)+((this._alphaBlendEqParams[0]===null?1:this._alphaBlendEqParams[0]-32773)<<16)+((this._alphaBlendEqParams[1]===null?1:this._alphaBlendEqParams[1]-32773)<<19)),i!==this._colorStates&&(this._colorStates=i,this._states[StatePosition.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.ColorStates))},a.prototype._setDepthStencilState=function(){var i=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,e=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(i<<10);this._depthStencilState!==e&&(this._depthStencilState=e,this._states[StatePosition.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.DepthStencilState))},a.prototype._setVertexState=function(i){for(var e,o,s=this._statesLength,c=StatePosition.VertexState,d=i._pipelineContext,_=d.shaderProcessingContext.attributeNamesFromEffect,b=d.shaderProcessingContext.attributeLocationsFromEffect,k,j=0,$=0;$<_.length;$++){var _e=b[$],et=(e=this._overrideVertexBuffers&&this._overrideVertexBuffers[_[$]])!==null&&e!==void 0?e:this._vertexBuffers[_[$]];et||(et=this._emptyVertexBuffer);var tt=(o=et.getBuffer())===null||o===void 0?void 0:o.underlyingResource;if(et._validOffsetRange===void 0){var rt=et.byteOffset,it=et.getSize(!0),nt=et.byteStride;et._validOffsetRange=rt<=this._kMaxVertexBufferStride-it&&(nt===0||rt+it<=nt)}k&&k===tt&&et._validOffsetRange||(this.vertexBuffers[j++]=et,k=et._validOffsetRange?tt:null);var ot=et.hashCode+(_e<<7);this._isDirty=this._isDirty||this._states[c]!==ot,this._states[c++]=ot}this.vertexBuffers.length=j,this._statesLength=c,this._isDirty=this._isDirty||c!==s,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.VertexState))},a.prototype._setTextureState=function(i){this._textureState!==i&&(this._textureState=i,this._states[StatePosition.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,StatePosition.TextureStage))},a.prototype._createPipelineLayout=function(i){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(i);for(var e=[],o=i.shaderProcessingContext.bindGroupLayoutEntries,s=0;s<o.length;s++){var c=o[s];e[s]=this._device.createBindGroupLayout({entries:c})}return i.bindGroupLayouts=e,this._device.createPipelineLayout({bindGroupLayouts:e})},a.prototype._createPipelineLayoutWithTextureStage=function(i){for(var e,o=i.shaderProcessingContext,s=o.bindGroupLayoutEntries,c=1,d=0;d<s.length;d++)for(var _=s[d],b=0;b<_.length;b++){var k=s[d][b];if(k.texture){var j=o.bindGroupLayoutEntryInfo[d][k.binding].name,$=o.availableTextures[j],_e=$.autoBindSampler?o.availableSamplers[j+WebGPUShaderProcessor.AutoSamplerSuffix]:null,et=$.sampleType,tt=(e=_e==null?void 0:_e.type)!==null&&e!==void 0?e:SamplerBindingType.Filtering;if(this._textureState&c&&et!==TextureSampleType.Depth&&($.autoBindSampler&&(tt=SamplerBindingType.NonFiltering),et=TextureSampleType.UnfilterableFloat),k.texture.sampleType=et,_e){var rt=o.bindGroupLayoutEntryInfo[_e.binding.groupIndex][_e.binding.bindingIndex].index;s[_e.binding.groupIndex][rt].sampler.type=tt}c=c<<1}}for(var it=[],d=0;d<s.length;++d)it[d]=this._device.createBindGroupLayout({entries:s[d]});return i.bindGroupLayouts=it,this._device.createPipelineLayout({bindGroupLayouts:it})},a.prototype._getVertexInputDescriptor=function(i,e){for(var o,s,c=[],d=i._pipelineContext,_=d.shaderProcessingContext.attributeNamesFromEffect,b=d.shaderProcessingContext.attributeLocationsFromEffect,k,j,$=0;$<_.length;$++){var _e=b[$],et=(o=this._overrideVertexBuffers&&this._overrideVertexBuffers[_[$]])!==null&&o!==void 0?o:this._vertexBuffers[_[$]];et||(et=this._emptyVertexBuffer);var tt=(s=et.getBuffer())===null||s===void 0?void 0:s.underlyingResource,rt=et.byteOffset,it=!et._validOffsetRange;if(!(k&&j&&k===tt)||it){var nt={arrayStride:et.byteStride,stepMode:et.getIsInstanced()?InputStepMode.Instance:InputStepMode.Vertex,attributes:[]};c.push(nt),j=nt.attributes,it&&(rt=0,tt=null)}j.push({shaderLocation:_e,offset:rt,format:a._GetVertexInputDescriptorFormat(et)}),k=tt}return c},a.prototype._createRenderPipeline=function(i,e,o){var s=i._pipelineContext,c=this._getVertexInputDescriptor(i,e),d=this._createPipelineLayout(s),_=[],b=this._getAphaBlendState(),k=this._getColorBlendState();if(this._mrtAttachments1>0)for(var j=0;j<this._mrtFormats.length;++j){var $={format:this._mrtFormats[j],writeMask:this._writeMask};b&&k&&($.blend={alpha:b,color:k}),_.push($)}else{var $={format:this._webgpuColorFormat[0],writeMask:this._writeMask};b&&k&&($.blend={alpha:b,color:k}),_.push($)}var _e={compare:a._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:a._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:a._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:a._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)},et=void 0;return(e===PrimitiveTopology.LineStrip||e===PrimitiveTopology.TriangleStrip)&&(et=!this._indexBuffer||this._indexBuffer.is32Bits?IndexFormat.Uint32:IndexFormat.Uint16),this._device.createRenderPipeline({layout:d,vertex:{module:s.stages.vertexStage.module,entryPoint:s.stages.vertexStage.entryPoint,buffers:c},primitive:{topology:e,stripIndexFormat:et,frontFace:this._frontFace===1?FrontFace.CCW:FrontFace.CW,cullMode:this._cullEnabled?this._cullFace===2?CullMode.Front:CullMode.Back:CullMode.None},fragment:s.stages.fragmentStage?{module:s.stages.fragmentStage.module,entryPoint:s.stages.fragmentStage.entryPoint,targets:_}:void 0,multisample:{count:o},depthStencil:this._webgpuDepthStencilFormat===void 0?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?a._GetCompareFunction(this._depthCompare):CompareFunction.Always,format:this._webgpuDepthStencilFormat,stencilFront:_e,stencilBack:_e,stencilReadMask:this._stencilReadMask,stencilWriteMask:this._stencilWriteMask,depthBias:this._depthBias,depthBiasClamp:this._depthBiasClamp,depthBiasSlopeScale:this._depthBiasSlopeScale}})},a.NumCacheHitWithoutHash=0,a.NumCacheHitWithHash=0,a.NumCacheMiss=0,a.NumPipelineCreationLastFrame=0,a._NumPipelineCreationCurrentFrame=0,a}(),NodeState=function(){function a(){this.values={}}return a.prototype.count=function(){var i=0,e=this.pipeline?1:0;for(var o in this.values){var s=this.values[o],c=s.count(),d=c[0],_=c[1];i+=d,e+=_,i++}return[i,e]},a}(),WebGPUCacheRenderPipelineTree=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o,s)||this;return c._nodeStack=[],c._nodeStack[0]=i._Cache,c}return i.GetNodeCounts=function(){var e=i._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}},i._GetPipelines=function(e,o,s,c){if(e.pipeline){var d=s.slice();d.length=c,o.push(d)}for(var _ in e.values){var b=e.values[_];s[c]=parseInt(_),i._GetPipelines(b,o,s,c+1)}},i.GetPipelines=function(){var e=[];return i._GetPipelines(i._Cache,e,[],0),e},i.prototype._getRenderPipeline=function(e){for(var o=this._nodeStack[this._stateDirtyLowestIndex],s=this._stateDirtyLowestIndex;s<this._statesLength;++s){var c=o.values[this._states[s]];c||(c=new NodeState,o.values[this._states[s]]=c),o=c,this._nodeStack[s+1]=o}e.token=o,e.pipeline=o.pipeline},i.prototype._setRenderPipeline=function(e){e.token.pipeline=e.pipeline},i._Cache=new NodeState,i}(WebGPUCacheRenderPipeline),WebGPUStencilStateComposer=function(a){__extends(i,a);function i(e){var o=a.call(this,!1)||this;return o._cache=e,o.reset(),o}return Object.defineProperty(i.prototype,"func",{get:function(){return this._func},set:function(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"funcMask",{get:function(){return this._funcMask},set:function(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"opStencilFail",{get:function(){return this._opStencilFail},set:function(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"opDepthFail",{get:function(){return this._opDepthFail},set:function(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"opStencilDepthPass",{get:function(){return this._opStencilDepthPass},set:function(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"mask",{get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"enabled",{get:function(){return this._enabled},set:function(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))},enumerable:!1,configurable:!0}),i.prototype.reset=function(){a.prototype.reset.call(this),this._cache.resetStencilState()},i.prototype.apply=function(e){var o,s=(o=this.stencilMaterial)===null||o===void 0?void 0:o.enabled;this.enabled=s?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.func=s?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=s?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=s?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=s?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=s?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=s?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=s?this.stencilMaterial.mask:this.stencilGlobal.mask)},i}(StencilStateComposer),WebGPUDepthCullingState=function(a){__extends(i,a);function i(e){var o=a.call(this,!1)||this;return o._cache=e,o.reset(),o}return Object.defineProperty(i.prototype,"zOffset",{get:function(){return this._zOffset},set:function(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"zOffsetUnits",{get:function(){return this._zOffsetUnits},set:function(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cullFace",{get:function(){return this._cullFace},set:function(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(e!=null?e:1))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cull",{get:function(){return this._cull},set:function(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"depthMask",{get:function(){return this._depthMask},set:function(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"depthTest",{get:function(){return this._depthTest},set:function(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"frontFace",{get:function(){return this._frontFace},set:function(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(e!=null?e:2))},enumerable:!1,configurable:!0}),i.prototype.reset=function(){a.prototype.reset.call(this),this._cache.resetDepthCullingState()},i.prototype.apply=function(e){},i}(DepthCullingState),ExternalTexture=function(){function a(i){this.useMipMaps=!1,this.type=16,this._video=i,this.uniqueId=InternalTexture._Counter++}return a.IsExternalTexture=function(i){return i.underlyingResource!==void 0},a.prototype.getClassName=function(){return"ExternalTexture"},Object.defineProperty(a.prototype,"underlyingResource",{get:function(){return this._video},enumerable:!1,configurable:!0}),a.prototype.isReady=function(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA},a.prototype.dispose=function(){},a}(),WebGPUMaterialContext=function(){function a(){this.uniqueId=a._Counter++,this.updateId=0,this.reset()}return Object.defineProperty(a.prototype,"forceBindGroupCreation",{get:function(){return this._numExternalTextures>0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasFloatTextures",{get:function(){return this._numFloatTextures>0},enumerable:!1,configurable:!0}),a.prototype.reset=function(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatTextures=0,this._numExternalTextures=0},a.prototype.setSampler=function(i,e){var o=this.samplers[i],s=-1;o?s=o.hashCode:this.samplers[i]=o={sampler:e,hashCode:0},o.sampler=e,o.hashCode=e?WebGPUCacheSampler.GetSamplerHashCode(e):0;var c=s!==o.hashCode;c&&this.updateId++,this.isDirty||(this.isDirty=c)},a.prototype.setTexture=function(i,e){var o,s,c,d=this.textures[i],_=-1;d?_=(s=(o=d.texture)===null||o===void 0?void 0:o.uniqueId)!==null&&s!==void 0?s:-1:this.textures[i]=d={texture:e,isFloatTexture:!1,isExternalTexture:!1},d.isExternalTexture&&this._numExternalTextures--,d.isFloatTexture&&this._numFloatTextures--,e?(d.isFloatTexture=e.type===1,d.isExternalTexture=ExternalTexture.IsExternalTexture(e),d.isFloatTexture&&this._numFloatTextures++,d.isExternalTexture&&this._numExternalTextures++):(d.isFloatTexture=!1,d.isExternalTexture=!1),d.texture=e;var b=_!==((c=e==null?void 0:e.uniqueId)!==null&&c!==void 0?c:-1);b&&this.updateId++,this.isDirty||(this.isDirty=b)},a._Counter=0,a}(),WebGPUDrawContext=function(){function a(i){this._bufferManager=i,this.uniqueId=a._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}return a.prototype.isDirty=function(i){return this._isDirty||this.materialContextUpdateId!==i},a.prototype.resetIsDirty=function(i){this._isDirty=!1,this.materialContextUpdateId=i},Object.defineProperty(a.prototype,"useInstancing",{get:function(){return this._useInstancing},set:function(i){this._useInstancing!==i&&(i?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(40,BufferUsage.CopyDst|BufferUsage.Indirect),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=i,this._currentInstanceCount=-1)},enumerable:!1,configurable:!0}),a.prototype.reset=function(){this.buffers={},this._isDirty=!0,this.materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0},a.prototype.setBuffer=function(i,e){var o;this._isDirty||(this._isDirty=(e==null?void 0:e.uniqueId)!==((o=this.buffers[i])===null||o===void 0?void 0:o.uniqueId)),this.buffers[i]=e},a.prototype.setIndirectData=function(i,e,o){e===this._currentInstanceCount||!this.indirectDrawBuffer||!this._indirectDrawData||(this._currentInstanceCount=e,this._indirectDrawData[0]=i,this._indirectDrawData[1]=e,this._indirectDrawData[2]=o,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))},a.prototype.dispose=function(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0},a._Counter=0,a}(),WebGPUBindGroupCacheNode=function(){function a(){this.values={}}return a}(),WebGPUCacheBindGroups=function(){function a(i,e,o){this.disabled=!1,this._device=i,this._cacheSampler=e,this._engine=o}return Object.defineProperty(a,"Statistics",{get:function(){return{totalCreated:a.NumBindGroupsCreatedTotal,lastFrameCreated:a.NumBindGroupsCreatedLastFrame,lookupLastFrame:a.NumBindGroupsLookupLastFrame,noLookupLastFrame:a.NumBindGroupsNoLookupLastFrame}},enumerable:!1,configurable:!0}),a.prototype.endFrame=function(){a.NumBindGroupsCreatedLastFrame=a._NumBindGroupsCreatedCurrentFrame,a.NumBindGroupsLookupLastFrame=a._NumBindGroupsLookupCurrentFrame,a.NumBindGroupsNoLookupLastFrame=a._NumBindGroupsNoLookupCurrentFrame,a._NumBindGroupsCreatedCurrentFrame=0,a._NumBindGroupsLookupCurrentFrame=0,a._NumBindGroupsNoLookupCurrentFrame=0},a.prototype.getBindGroups=function(i,e,o){var s,c,d,_,b,k,j,$,_e,et,tt=void 0,rt=a._Cache,it=this.disabled||o.forceBindGroupCreation;if(!it){if(!e.isDirty(o.updateId)&&!o.isDirty)return a._NumBindGroupsNoLookupCurrentFrame++,e.bindGroups;for(var nt=0,ot=i.shaderProcessingContext.bufferNames;nt<ot.length;nt++){var at=ot[nt],st=(c=(s=e.buffers[at])===null||s===void 0?void 0:s.uniqueId)!==null&&c!==void 0?c:0,ut=rt.values[st];ut||(ut=new WebGPUBindGroupCacheNode,rt.values[st]=ut),rt=ut}for(var ft=0,lt=i.shaderProcessingContext.samplerNames;ft<lt.length;ft++){var ht=lt[ft],pt=(_=(d=o.samplers[ht])===null||d===void 0?void 0:d.hashCode)!==null&&_!==void 0?_:0,ut=rt.values[pt];ut||(ut=new WebGPUBindGroupCacheNode,rt.values[pt]=ut),rt=ut}for(var mt=0,dt=i.shaderProcessingContext.textureNames;mt<dt.length;mt++){var gt=dt[mt],_t=(j=(k=(b=o.textures[gt])===null||b===void 0?void 0:b.texture)===null||k===void 0?void 0:k.uniqueId)!==null&&j!==void 0?j:0,ut=rt.values[_t];ut||(ut=new WebGPUBindGroupCacheNode,rt.values[_t]=ut),rt=ut}tt=rt.bindGroups}if(e.resetIsDirty(o.updateId),o.isDirty=!1,tt)return e.bindGroups=tt,a._NumBindGroupsLookupCurrentFrame++,tt;tt=[],e.bindGroups=tt,it||(rt.bindGroups=tt),a.NumBindGroupsCreatedTotal++,a._NumBindGroupsCreatedCurrentFrame++;for(var yt=i.bindGroupLayouts,Tt=0;Tt<i.shaderProcessingContext.bindGroupLayoutEntries.length;Tt++){for(var St=i.shaderProcessingContext.bindGroupLayoutEntries[Tt],At=i.shaderProcessingContext.bindGroupEntries[Tt],vt=0;vt<St.length;vt++){var Et=i.shaderProcessingContext.bindGroupLayoutEntries[Tt][vt],xt=i.shaderProcessingContext.bindGroupLayoutEntryInfo[Tt][Et.binding],bt=($=xt.nameInArrayOfTexture)!==null&&$!==void 0?$:xt.name;if(Et.sampler){var Mt=o.samplers[bt];if(Mt){var Rt=Mt.sampler;if(!Rt){this._engine.dbgSanityChecks&&Logger$2.Error("Trying to bind a null sampler! entry="+JSON.stringify(Et)+", name="+bt+", bindingInfo="+JSON.stringify(Mt,function(Ft,wt){return Ft==="texture"?"<no dump>":wt})+", materialContext.uniqueId="+o.uniqueId,50);continue}At[vt].resource=this._cacheSampler.getSampler(Rt,!1,Mt.hashCode)}else Logger$2.Error('Sampler "'+bt+'" could not be bound. entry='+JSON.stringify(Et)+", materialContext="+JSON.stringify(o,function(Ft,wt){return Ft==="texture"||Ft==="sampler"?"<no dump>":wt}),50)}else if(Et.texture||Et.storageTexture){var Mt=o.textures[bt];if(Mt){if(this._engine.dbgSanityChecks&&Mt.texture===null){Logger$2.Error("Trying to bind a null texture! entry="+JSON.stringify(Et)+", bindingInfo="+JSON.stringify(Mt,function(wt,Bt){return wt==="texture"?"<no dump>":Bt})+", materialContext.uniqueId="+o.uniqueId,50);continue}var Pt=Mt.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!Pt||!Pt.view)){Logger$2.Error("Trying to bind a null gpu texture! entry="+JSON.stringify(Et)+", name="+bt+", bindingInfo="+JSON.stringify(Mt,function(wt,Bt){return wt==="texture"?"<no dump>":Bt})+", isReady="+((_e=Mt.texture)===null||_e===void 0?void 0:_e.isReady)+", materialContext.uniqueId="+o.uniqueId,50);continue}At[vt].resource=Pt.view}else Logger$2.Error('Texture "'+bt+'" could not be bound. entry='+JSON.stringify(Et)+", materialContext="+JSON.stringify(o,function(wt,Bt){return wt==="texture"||wt==="sampler"?"<no dump>":Bt}),50)}else if(Et.externalTexture){var Mt=o.textures[bt];if(Mt){if(this._engine.dbgSanityChecks&&Mt.texture===null){Logger$2.Error("Trying to bind a null external texture! entry="+JSON.stringify(Et)+", name="+bt+", bindingInfo="+JSON.stringify(Mt,function(wt,Bt){return wt==="texture"?"<no dump>":Bt})+", materialContext.uniqueId="+o.uniqueId,50);continue}var It=Mt.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!It){Logger$2.Error("Trying to bind a null gpu external texture! entry="+JSON.stringify(Et)+", name="+bt+", bindingInfo="+JSON.stringify(Mt,function(wt,Bt){return wt==="texture"?"<no dump>":Bt})+", isReady="+((et=Mt.texture)===null||et===void 0?void 0:et.isReady)+", materialContext.uniqueId="+o.uniqueId,50);continue}At[vt].resource=this._device.importExternalTexture({source:It})}else Logger$2.Error('Texture "'+bt+'" could not be bound. entry='+JSON.stringify(Et)+", materialContext="+JSON.stringify(o,function(wt,Bt){return wt==="texture"||wt==="sampler"?"<no dump>":Bt}),50)}else if(Et.buffer){var Dt=e.buffers[bt];if(Dt){var Ct=Dt.underlyingResource;At[vt].resource.buffer=Ct,At[vt].resource.size=Dt.capacity}else Logger$2.Error(`Can't find buffer "`+bt+'". entry='+JSON.stringify(Et)+", buffers="+JSON.stringify(e.buffers)+", drawContext.uniqueId="+e.uniqueId,50)}}var Ot=yt[Tt];tt[Tt]=this._device.createBindGroup({layout:Ot,entries:At})}return tt},a.NumBindGroupsCreatedTotal=0,a.NumBindGroupsCreatedLastFrame=0,a.NumBindGroupsLookupLastFrame=0,a.NumBindGroupsNoLookupLastFrame=0,a._Cache=new WebGPUBindGroupCacheNode,a._NumBindGroupsCreatedCurrentFrame=0,a._NumBindGroupsLookupCurrentFrame=0,a._NumBindGroupsNoLookupCurrentFrame=0,a}(),name$2F="clearQuadVertexShader",shader$2F=`uniform float depthValue;
  758. const vec2 pos[4]={
  759. vec2(-1.0,1.0),
  760. vec2(1.0,1.0),
  761. vec2(-1.0,-1.0),
  762. vec2(1.0,-1.0)
  763. };
  764. void main(void) {
  765. gl_Position=vec4(pos[gl_VertexID],depthValue,1.0);
  766. }
  767. `;ShaderStore.ShadersStore[name$2F]=shader$2F;var name$2E="clearQuadPixelShader",shader$2E=`uniform vec4 color;
  768. void main() {
  769. gl_FragColor=color;
  770. }
  771. `;ShaderStore.ShadersStore[name$2E]=shader$2E;var WebGPUClearQuad=function(){function a(i,e,o){this._bindGroups={},this._bundleCache={},this._device=i,this._engine=e,this._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(this._device,o,!e._caps.textureFloatLinearFiltering),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=e.createEffect("clearQuad",[],["color","depthValue"])}return a.prototype.setDepthStencilFormat=function(i){this._depthTextureFormat=i,this._cacheRenderPipeline.setDepthStencilFormat(i)},a.prototype.setColorFormat=function(i){this._cacheRenderPipeline.setColorFormat(i)},a.prototype.setMRTAttachments=function(i,e){this._cacheRenderPipeline.setMRTAttachments(i,e)},a.prototype.clear=function(i,e,o,s,c){var d,_;c===void 0&&(c=1);var b,k=null,j=0;if(i)b=i;else{if(j=(e?e.r+e.g*256+e.b*256*256+e.a*256*256*256:0)+(o?Math.pow(2,32):0)+(s?Math.pow(2,33):0)+(this._engine.useReverseDepthBuffer?Math.pow(2,34):0)+c*Math.pow(2,35),k=this._bundleCache[j],k)return k;b=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:c})}this._cacheRenderPipeline.setDepthWriteEnabled(!!o),this._cacheRenderPipeline.setStencilEnabled(!!s),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(e?15:0);var $=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,c),_e=this._effect._pipelineContext;e&&this._effect.setDirectColor4("color",e),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),(d=_e.uniformBuffer)===null||d===void 0||d.update();var et=(_=_e.uniformBuffer)===null||_===void 0?void 0:_.getBuffer(),tt=this._bindGroups[et.uniqueId];if(!tt){var rt=_e.bindGroupLayouts;tt=this._bindGroups[et.uniqueId]=[],tt.push(this._device.createBindGroup({layout:rt[0],entries:[]})),WebGPUShaderProcessingContext._SimplifiedKnownBindings||tt.push(this._device.createBindGroup({layout:rt[1],entries:[]})),tt.push(this._device.createBindGroup({layout:rt[WebGPUShaderProcessingContext._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:et.underlyingResource,size:et.capacity}}]}))}b.setPipeline($);for(var it=0;it<tt.length;++it)b.setBindGroup(it,tt[it]);return b.draw(4,1,0,0),i||(k=b.finish(),this._bundleCache[j]=k),k},a}(),WebGPURenderItemViewport=function(){function a(i,e,o,s){this.x=Math.floor(i),this.y=Math.floor(e),this.w=Math.floor(o),this.h=Math.floor(s)}return a.prototype.run=function(i){i.setViewport(this.x,this.y,this.w,this.h,0,1)},a.prototype.clone=function(){return new a(this.x,this.y,this.w,this.h)},a}(),WebGPURenderItemScissor=function(){function a(i,e,o,s){this.x=i,this.y=e,this.w=o,this.h=s}return a.prototype.run=function(i){i.setScissorRect(this.x,this.y,this.w,this.h)},a.prototype.clone=function(){return new a(this.x,this.y,this.w,this.h)},a}(),WebGPURenderItemStencilRef=function(){function a(i){this.ref=i}return a.prototype.run=function(i){i.setStencilReference(this.ref)},a.prototype.clone=function(){return new a(this.ref)},a}(),WebGPURenderItemBlendColor=function(){function a(i){this.color=i}return a.prototype.run=function(i){i.setBlendConstant(this.color)},a.prototype.clone=function(){return new a(this.color)},a}(),WebGPURenderItemBeginOcclusionQuery=function(){function a(i){this.query=i}return a.prototype.run=function(i){i.beginOcclusionQuery(this.query)},a.prototype.clone=function(){return new a(this.query)},a}(),WebGPURenderItemEndOcclusionQuery=function(){function a(){}return a.prototype.run=function(i){i.endOcclusionQuery()},a.prototype.clone=function(){return new a},a}(),WebGPURenderItemBundles=function(){function a(){this.bundles=[]}return a.prototype.run=function(i){i.executeBundles(this.bundles)},a.prototype.clone=function(){var i=new a;return i.bundles=this.bundles,i},a}(),WebGPUBundleList=function(){function a(i){this.numDrawCalls=0,this._device=i,this._list=new Array(10),this._listLength=0}return a.prototype.addBundle=function(i){if(!this._currentItemIsBundle){var e=new WebGPURenderItemBundles;this._list[this._listLength++]=e,this._currentBundleList=e.bundles,this._currentItemIsBundle=!0}i&&this._currentBundleList.push(i)},a.prototype._finishBundle=function(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)},a.prototype.addItem=function(i){this._finishBundle(),this._list[this._listLength++]=i,this._currentItemIsBundle=!1},a.prototype.getBundleEncoder=function(i,e,o){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:i,depthStencilFormat:e,sampleCount:o})),this._bundleEncoder},a.prototype.close=function(){this._finishBundle()},a.prototype.run=function(i){this.close();for(var e=0;e<this._listLength;++e)this._list[e].run(i)},a.prototype.reset=function(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0},a.prototype.clone=function(){this.close();var i=new a(this._device);i._list=new Array(this._listLength),i._listLength=this._listLength,i.numDrawCalls=this.numDrawCalls;for(var e=0;e<this._listLength;++e)i._list[e]=this._list[e].clone();return i},a}(),WebGPUQuerySet=function(){function a(i,e,o,s,c){c===void 0&&(c=!0),this._dstBuffers=[],this._device=o,this._bufferManager=s,this._count=i,this._canUseMultipleBuffers=c,this._querySet=o.createQuerySet({type:e,count:i}),this._queryBuffer=s.createRawBuffer(8*i,BufferUsage.QueryResolve|BufferUsage.CopySrc),c||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,BufferUsage.MapRead|BufferUsage.CopyDst))}return Object.defineProperty(a.prototype,"querySet",{get:function(){return this._querySet},enumerable:!1,configurable:!0}),a.prototype._getBuffer=function(i,e){if(!this._canUseMultipleBuffers&&this._dstBuffers.length===0)return null;var o=this._device.createCommandEncoder(),s;return this._dstBuffers.length===0?s=this._bufferManager.createRawBuffer(8*this._count,BufferUsage.MapRead|BufferUsage.CopyDst):(s=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),o.resolveQuerySet(this._querySet,i,e,this._queryBuffer,0),o.copyBufferToBuffer(this._queryBuffer,0,s,0,8*e),this._device.queue.submit([o.finish()]),s},a.prototype.readValues=function(i,e){return i===void 0&&(i=0),e===void 0&&(e=1),__awaiter(this,void 0,void 0,function(){var o,s;return __generator(this,function(c){switch(c.label){case 0:return o=this._getBuffer(i,e),o===null?[2,null]:[4,o.mapAsync(MapMode.Read)];case 1:return c.sent(),s=new BigUint64Array(o.getMappedRange()).slice(),o.unmap(),this._dstBuffers[this._dstBuffers.length]=o,[2,s]}})})},a.prototype.readValue=function(i){return i===void 0&&(i=0),__awaiter(this,void 0,void 0,function(){var e,o,s;return __generator(this,function(c){switch(c.label){case 0:return e=this._getBuffer(i,1),e===null?[2,null]:[4,e.mapAsync(MapMode.Read)];case 1:return c.sent(),o=new BigUint64Array(e.getMappedRange()),s=Number(o[0]),e.unmap(),this._dstBuffers[this._dstBuffers.length]=e,[2,s]}})})},a.prototype.readTwoValuesAndSubtract=function(i){return i===void 0&&(i=0),__awaiter(this,void 0,void 0,function(){var e,o,s;return __generator(this,function(c){switch(c.label){case 0:return e=this._getBuffer(i,2),e===null?[2,null]:[4,e.mapAsync(MapMode.Read)];case 1:return c.sent(),o=new BigUint64Array(e.getMappedRange()),s=Number(o[1]-o[0]),e.unmap(),this._dstBuffers[this._dstBuffers.length]=e,[2,s]}})})},a.prototype.dispose=function(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(var i=0;i<this._dstBuffers.length;++i)this._bufferManager.releaseBuffer(this._dstBuffers[i])},a}(),WebGPUTimestampQuery=function(){function a(i,e){this._enabled=!1,this._gpuFrameTimeCounter=new PerfCounter,this._measureDurationState=0,this._device=i,this._bufferManager=e}return Object.defineProperty(a.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTimeCounter},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"enable",{get:function(){return this._enabled},set:function(i){this._enabled!==i&&(this._enabled=i,this._measureDurationState=0,i?this._measureDuration=new WebGPUDurationMeasure(this._device,this._bufferManager):this._measureDuration.dispose())},enumerable:!1,configurable:!0}),a.prototype.startFrame=function(i){this._enabled&&this._measureDurationState===0&&(this._measureDuration.start(i),this._measureDurationState=1)},a.prototype.endFrame=function(i){var e=this;this._measureDurationState===1&&(this._measureDurationState=2,this._measureDuration.stop(i).then(function(o){o!==null&&o>=0&&(e._gpuFrameTimeCounter.fetchNewFrame(),e._gpuFrameTimeCounter.addCount(o,!0)),e._measureDurationState=0}))},a}(),WebGPUDurationMeasure=function(){function a(i,e){this._querySet=new WebGPUQuerySet(2,QueryType.Timestamp,i,e)}return a.prototype.start=function(i){i.writeTimestamp(this._querySet.querySet,0)},a.prototype.stop=function(i){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return i.writeTimestamp(this._querySet.querySet,1),[2,this._querySet.readTwoValuesAndSubtract(0)]})})},a.prototype.dispose=function(){this._querySet.dispose()},a}(),WebGPUOcclusionQuery=function(){function a(i,e,o,s,c){s===void 0&&(s=50),c===void 0&&(c=100),this._availableIndices=[],this._engine=i,this._device=e,this._bufferManager=o,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=c,this._allocateNewIndices(s)}return Object.defineProperty(a.prototype,"querySet",{get:function(){return this._querySet.querySet},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasQueries",{get:function(){return this._currentTotalIndices!==this._availableIndices.length},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"canBeginQuery",{get:function(){var i=this._engine._getCurrentRenderPassIndex();switch(i){case 0:return this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet!==void 0;case 1:return this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet!==void 0}return!1},enumerable:!1,configurable:!0}),a.prototype.createQuery=function(){this._availableIndices.length===0&&this._allocateNewIndices();var i=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,i},a.prototype.deleteQuery=function(i){this._availableIndices[this._availableIndices.length-1]=i},a.prototype.isQueryResultAvailable=function(i){return this._retrieveQueryBuffer(),!!this._lastBuffer&&i<this._lastBuffer.length},a.prototype.getQueryResult=function(i){var e,o;return Number((o=(e=this._lastBuffer)===null||e===void 0?void 0:e[i])!==null&&o!==void 0?o:-1)},a.prototype._retrieveQueryBuffer=function(){var i=this;this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer!==this._engine.frameId&&(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then(function(e){i._lastBuffer=e}))},a.prototype._allocateNewIndices=function(i){i=i!=null?i:this._countIncrement,this._delayQuerySetDispose();for(var e=0;e<i;++e)this._availableIndices.push(this._currentTotalIndices+e);this._currentTotalIndices+=i,this._querySet=new WebGPUQuerySet(this._currentTotalIndices,QueryType.Occlusion,this._device,this._bufferManager,!1)},a.prototype._delayQuerySetDispose=function(){var i=this._querySet;i&&setTimeout(function(){return i.dispose},1e3)},a.prototype.dispose=function(){var i;(i=this._querySet)===null||i===void 0||i.dispose(),this._availableIndices=[]},a}(),WebGPUTintWASM=function(){function a(){this._twgsl=null}return a.prototype.initTwgsl=function(i){return __awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(o){switch(o.label){case 0:return i=i||{},i=__assign(__assign({},a._twgslDefaultOptions),i),i.twgsl?(this._twgsl=i.twgsl,[2,Promise.resolve()]):i.jsPath&&i.wasmPath?IsWindowObjectExist()?[4,Tools.LoadScriptAsync(i.jsPath)]:[3,2]:[3,3];case 1:return o.sent(),[3,3];case 2:importScripts(i.jsPath),o.label=3;case 3:return self.twgsl?(e=this,[4,self.twgsl(i.wasmPath)]):[3,5];case 4:return e._twgsl=o.sent(),[2,Promise.resolve()];case 5:return[2,Promise.reject("twgsl is not available.")]}})})},a.prototype.convertSpirV2WGSL=function(i){return this._twgsl.convertSpirV2WGSL(i)},a._twgslDefaultOptions={jsPath:"https://preview.babylonjs.com/twgsl/twgsl.js",wasmPath:"https://preview.babylonjs.com/twgsl/twgsl.wasm"},a}(),WebGPUSnapshotRendering=function(){function a(i,e,o,s){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=i,this._mode=e,this._bundleList=o,this._bundleListRenderTarget=s}return Object.defineProperty(a.prototype,"enabled",{get:function(){return this._enabled},set:function(i){this._mainPassBundleList.length=0,this._record=this._enabled=i,this._play=!1,i&&(this._modeSaved=this._mode,this._mode=0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"play",{get:function(){return this._play},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"record",{get:function(){return this._record},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"mode",{get:function(){return this._mode},set:function(i){this._record?this._modeSaved=i:this._mode=i},enumerable:!1,configurable:!0}),a.prototype.endMainRenderPass=function(){this._record&&this._mainPassBundleList.push(this._bundleList.clone())},a.prototype.endRenderTargetPass=function(i,e){var o,s,c,d;if(this._play)(s=(o=e._bundleLists)===null||o===void 0?void 0:o[e._currentLayer])===null||s===void 0||s.run(i),this._mode===1&&this._engine._reportDrawCall((d=(c=e._bundleLists)===null||c===void 0?void 0:c[e._currentLayer])===null||d===void 0?void 0:d.numDrawCalls);else if(this._record)e._bundleLists||(e._bundleLists=[]),e._bundleLists[e._currentLayer]=this._bundleListRenderTarget.clone(),e._bundleLists[e._currentLayer].run(i),this._bundleListRenderTarget.reset();else return!1;return!0},a.prototype.endFrame=function(i){if(this._record&&(this._mainPassBundleList.push(this._bundleList.clone()),this._record=!1,this._play=!0,this._mode=this._modeSaved),i!==null&&this._play)for(var e=0;e<this._mainPassBundleList.length;++e)this._mainPassBundleList[e].run(i),this._mode===1&&this._engine._reportDrawCall(this._mainPassBundleList[e].numDrawCalls)},a.prototype.reset=function(){this.enabled=!1,this.enabled=!0},a}(),WebGPUEngine=function(a){__extends(i,a);function i(e,o){o===void 0&&(o={});var s,c,d,_,b=a.call(this,null)||this;if(b._uploadEncoderDescriptor={label:"upload"},b._renderEncoderDescriptor={label:"render"},b._renderTargetEncoderDescriptor={label:"renderTarget"},b._clearDepthValue=1,b._clearReverseDepthValue=0,b._clearStencilValue=0,b._defaultSampleCount=4,b._glslang=null,b._tintWASM=null,b._compiledComputeEffects={},b._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},b.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},b.numMaxUncapturedErrors=20,b._commandBuffers=[null,null,null],b._currentRenderPass=null,b._mainRenderPassWrapper=new WebGPURenderPassWrapper,b._mainRenderPassCopyWrapper=new WebGPURenderPassWrapper,b._rttRenderPassWrapper=new WebGPURenderPassWrapper,b._pendingDebugCommands=[],b._onAfterUnbindFrameBufferObservable=new Observable,b._currentOverrideVertexBuffers=null,b._currentIndexBuffer=null,b.__colorWrite=!0,b._forceEnableEffect=!1,b.dbgShowShaderCode=!1,b.dbgSanityChecks=!0,b.dbgVerboseLogsForFirstFrames=!1,b.dbgVerboseLogsNumFrames=10,b.dbgLogIfNotDrawWrapper=!0,b.dbgShowEmptyEnableEffectCalls=!0,b._viewportsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],b._scissorsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],b._scissorCached={x:0,y:0,z:0,w:0},b._stencilRefsCurrent=[-1,-1],b._blendColorsCurrent=[[null,null,null,null],[null,null,null,null]],b.isNDCHalfZRange=!0,b.hasOriginBottomLeft=!1,o.deviceDescriptor=o.deviceDescriptor||{},o.swapChainFormat=o.swapChainFormat||TextureFormat.BGRA8Unorm,o.antialiasing=o.antialiasing===void 0?!0:o.antialiasing,o.stencil=(s=o.stencil)!==null&&s!==void 0?s:!0,o.enableGPUDebugMarkers=(c=o.enableGPUDebugMarkers)!==null&&c!==void 0?c:!1,Logger$2.Log("Babylon.js v"+Engine.Version+" - "+b.description+" engine"),!navigator.gpu)return Logger$2.Error("WebGPU is not supported by your browser."),b;b._isWebGPU=!0,b._shaderPlatformName="WEBGPU",o.deterministicLockstep===void 0&&(o.deterministicLockstep=!1),o.lockstepMaxSteps===void 0&&(o.lockstepMaxSteps=4),o.audioEngine===void 0&&(o.audioEngine=!0),b._deterministicLockstep=o.deterministicLockstep,b._lockstepMaxSteps=o.lockstepMaxSteps,b._timeStep=o.timeStep||1/60,b._doNotHandleContextLost=!!o.doNotHandleContextLost,b._canvas=e,b._options=o,b.premultipliedAlpha=(d=o.premultipliedAlpha)!==null&&d!==void 0?d:!0;var k=IsWindowObjectExist()&&window.devicePixelRatio||1,j=o.limitDeviceRatio||k,$=(_=o.adaptToDeviceRatio)!==null&&_!==void 0?_:!1;return b._hardwareScalingLevel=$?1/Math.min(j,k):1,b._mainPassSampleCount=o.antialiasing?b._defaultSampleCount:1,b._isStencilEnable=o.stencil,b._sharedInit(e,!!o.doNotHandleTouchAction,o.audioEngine),b._shaderProcessor=new WebGPUShaderProcessorGLSL,b._shaderProcessorWGSL=new WebGPUShaderProcessorWGSL,b._invertYFinalFramebuffer=(!!b._options.forceCopyForInvertYFinalFramebuffer||!b._canvas.style)&&!b._options.disableCopyForInvertYFinalFramebuffer,b._invertYFinalFramebuffer||b._canvas.style&&(b._canvas.style.transform="scaleY(-1)"),b}return Object.defineProperty(i.prototype,"snapshotRenderingMode",{get:function(){return this._snapshotRendering.mode},set:function(e){this._snapshotRendering.mode=e},enumerable:!1,configurable:!0}),i.prototype.snapshotRenderingReset=function(){this._snapshotRendering.reset()},Object.defineProperty(i.prototype,"snapshotRendering",{get:function(){return this._snapshotRendering.enabled},set:function(e){this._snapshotRendering.enabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"disableCacheSamplers",{get:function(){return this._cacheSampler?this._cacheSampler.disabled:!1},set:function(e){this._cacheSampler&&(this._cacheSampler.disabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"disableCacheRenderPipelines",{get:function(){return this._cacheRenderPipeline?this._cacheRenderPipeline.disabled:!1},set:function(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"disableCacheBindGroups",{get:function(){return this._cacheBindGroups?this._cacheBindGroups.disabled:!1},set:function(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i,"IsSupportedAsync",{get:function(){return navigator.gpu?navigator.gpu.requestAdapter().then(function(e){return!!e},function(e){return!1}).catch(function(e){return!1}):Promise.resolve(!1)},enumerable:!1,configurable:!0}),Object.defineProperty(i,"IsSupported",{get:function(){return Logger$2.Warn("You must call IsSupportedAsync for WebGPU!"),!1},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"supportsUniformBuffers",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"supportedExtensions",{get:function(){return this._adapterSupportedExtensions},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"enabledExtensions",{get:function(){return this._deviceEnabledExtensions},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"name",{get:function(){return"WebGPU"},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"description",{get:function(){var e=this.name+this.version;return e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"version",{get:function(){return 1},enumerable:!1,configurable:!0}),i.prototype.getInfo=function(){return{vendor:"unknown vendor",renderer:"unknown renderer",version:"unknown version"}},Object.defineProperty(i.prototype,"compatibilityMode",{get:function(){return this._compatibilityMode},set:function(e){this._compatibilityMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"currentSampleCount",{get:function(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount},enumerable:!1,configurable:!0}),i.CreateAsync=function(e,o){o===void 0&&(o={});var s=new i(e,o);return new Promise(function(c){s.initAsync(o.glslangOptions,o.twgslOptions).then(function(){return c(s)})})},i.prototype.initAsync=function(e,o){var s=this,c;return this._initGlslang(e!=null?e:(c=this._options)===null||c===void 0?void 0:c.glslangOptions).then(function(d){var _;return s._glslang=d,s._tintWASM=i.UseTWGSL?new WebGPUTintWASM:null,s._tintWASM?s._tintWASM.initTwgsl(o!=null?o:(_=s._options)===null||_===void 0?void 0:_.twgslOptions).then(function(){return navigator.gpu.requestAdapter(s._options)},function(b){throw Logger$2.Error("Can not initialize twgsl!"),Logger$2.Error(b),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(s._options)},function(d){throw Logger$2.Error("Can not initialize glslang!"),Logger$2.Error(d),Error("WebGPU initializations stopped.")}).then(function(d){var _;if(d){s._adapter=d,s._adapterSupportedExtensions=[],(_=s._adapter.features)===null||_===void 0||_.forEach(function(tt){return s._adapterSupportedExtensions.push(tt)});var b=s._options.deviceDescriptor;if(b!=null&&b.requiredFeatures){for(var k=b.requiredFeatures,j=[],$=0,_e=k;$<_e.length;$++){var et=_e[$];s._adapterSupportedExtensions.indexOf(et)!==-1&&j.push(et)}b.requiredFeatures=j}return s._adapter.requestDevice(s._options.deviceDescriptor)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(function(d){var _,b;s._device=d,s._deviceEnabledExtensions=[],(_=s._device.features)===null||_===void 0||_.forEach(function(j){return s._deviceEnabledExtensions.push(j)});var k=-1;s._device.addEventListener("uncapturederror",function(j){++k<s.numMaxUncapturedErrors?Logger$2.Warn("WebGPU uncaptured error ("+(k+1)+"): "+j.error+" - "+j.error.message):k++===s.numMaxUncapturedErrors&&Logger$2.Warn("WebGPU uncaptured error: too many warnings ("+s.numMaxUncapturedErrors+"), no more warnings will be reported to the console for this engine.")}),s._doNotHandleContextLost||(b=s._device.lost)===null||b===void 0||b.then(function(j){s._contextWasLost=!0,Logger$2.Warn("WebGPU context lost. "+j),s.onContextLostObservable.notifyObservers(s),s._restoreEngineAfterContextLost(s.initAsync.bind(s))})},function(d){Logger$2.Error("Could not retrieve a WebGPU device."),Logger$2.Error(d)}).then(function(){s._bufferManager=new WebGPUBufferManager(s._device),s._textureHelper=new WebGPUTextureHelper(s._device,s._glslang,s._tintWASM,s._bufferManager),s._cacheSampler=new WebGPUCacheSampler(s._device),s._cacheBindGroups=new WebGPUCacheBindGroups(s._device,s._cacheSampler,s),s._timestampQuery=new WebGPUTimestampQuery(s._device,s._bufferManager),s._occlusionQuery=s._device.createQuerySet?new WebGPUOcclusionQuery(s,s._device,s._bufferManager):void 0,s._bundleList=new WebGPUBundleList(s._device),s._bundleListRenderTarget=new WebGPUBundleList(s._device),s._snapshotRendering=new WebGPUSnapshotRendering(s,s._snapshotRenderingMode,s._bundleList,s._bundleListRenderTarget),s.dbgVerboseLogsForFirstFrames&&s._count===void 0&&(s._count=0,console.log("%c frame #"+s._count+" - begin","background: #ffff00")),s._uploadEncoder=s._device.createCommandEncoder(s._uploadEncoderDescriptor),s._renderEncoder=s._device.createCommandEncoder(s._renderEncoderDescriptor),s._renderTargetEncoder=s._device.createCommandEncoder(s._renderTargetEncoderDescriptor),s._emptyVertexBuffer=new VertexBuffer(s,[0],"",!1,!1,1,!1,0,1),s._initializeLimits(),s._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(s._device,s._emptyVertexBuffer,!s._caps.textureFloatLinearFiltering),s._depthCullingState=new WebGPUDepthCullingState(s._cacheRenderPipeline),s._stencilStateComposer=new WebGPUStencilStateComposer(s._cacheRenderPipeline),s._stencilStateComposer.stencilGlobal=s._stencilState,s._depthCullingState.depthTest=!0,s._depthCullingState.depthFunc=515,s._depthCullingState.depthMask=!0,s._textureHelper.setCommandEncoder(s._uploadEncoder),s._clearQuad=new WebGPUClearQuad(s._device,s,s._emptyVertexBuffer),s._defaultDrawContext=s.createDrawContext(),s._currentDrawContext=s._defaultDrawContext,s._defaultMaterialContext=s.createMaterialContext(),s._currentMaterialContext=s._defaultMaterialContext,s._initializeContextAndSwapChain(),s._initializeMainAttachments(),s.resize()}).catch(function(d){Logger$2.Error("Can not create WebGPU Device and/or context."),Logger$2.Error(d),console.trace&&console.trace()})},i.prototype._initGlslang=function(e){return e=e||{},e=__assign(__assign({},i._glslangDefaultOptions),e),e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?IsWindowObjectExist()?Tools.LoadScriptAsync(e.jsPath).then(function(){return self.glslang(e.wasmPath)}):(importScripts(e.jsPath),self.glslang(e.wasmPath)):Promise.reject("gslang is not available.")},i.prototype._initializeLimits=function(){this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:8192,maxCubemapTextureSize:2048,maxRenderTextureSize:8192,maxVertexAttribs:16,maxVaryingVectors:15,maxFragmentUniformVectors:1024,maxVertexUniformVectors:1024,standardDerivatives:!0,astc:null,s3tc:this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:null,bptc:this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:4,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:typeof BigUint64Array!="undefined"&&this.enabledExtensions.indexOf(FeatureName.TimestampQuery)!==-1?!0:void 0,supportOcclusionQuery:typeof BigUint64Array!="undefined",canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0},this._caps.parallelShaderCompile=null,this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,_collectUbosUpdatedInFrame:!1}},i.prototype._initializeContextAndSwapChain=function(){this._context=this._canvas.getContext("webgpu"),this._configureContext(this._canvas.width,this._canvas.height),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new WebGPUHardwareTexture],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._invertYFinalFramebuffer&&(this._mainRenderPassCopyWrapper.colorAttachmentGPUTextures=[new WebGPUHardwareTexture],this._mainRenderPassCopyWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat)},i.prototype._initializeMainAttachments=function(){var e,o;this._mainTextureExtends={width:this.getRenderWidth(),height:this.getRenderHeight(),depthOrArrayLayers:1};var s;if(this._options.antialiasing){var c={size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:TextureDimension.E2d,format:this._options.swapChainFormat,usage:TextureUsage.RenderAttachment};(e=this._mainTexture)===null||e===void 0||e.destroy(),this._mainTexture=this._device.createTexture(c),s=[{view:this._mainTexture.createView(),loadValue:new Color4(0,0,0,1),storeOp:StoreOp.Store}]}else s=[{view:void 0,loadValue:new Color4(0,0,0,1),storeOp:StoreOp.Store}];if(this._invertYFinalFramebuffer){var d={size:this._mainTextureExtends,mipLevelCount:1,sampleCount:1,dimension:TextureDimension.E2d,format:this._options.swapChainFormat,usage:TextureUsage.RenderAttachment|TextureUsage.TextureBinding};(o=this._mainTextureLastCopy)===null||o===void 0||o.destroy(),this._mainTextureLastCopy=this._device.createTexture(d),this._options.antialiasing?s[0].resolveTarget=this._mainTextureLastCopy.createView():s[0].view=this._mainTextureLastCopy.createView(),this._mainRenderPassCopyWrapper.renderPassDescriptor={colorAttachments:[{view:void 0,loadValue:new Color4(0,0,0,1),storeOp:StoreOp.Store}]}}this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?TextureFormat.Depth24PlusStencil8:TextureFormat.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);var _={size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:TextureDimension.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:TextureUsage.RenderAttachment};this._depthTexture&&this._depthTexture.destroy(),this._depthTexture=this._device.createTexture(_);var b={view:this._depthTexture.createView(),depthLoadValue:this._clearDepthValue,depthStoreOp:StoreOp.Store,stencilLoadValue:this._clearStencilValue,stencilStoreOp:StoreOp.Store};this._mainRenderPassWrapper.renderPassDescriptor={colorAttachments:s,depthStencilAttachment:b},this._mainRenderPassWrapper.renderPass!==null&&this._endMainRenderPass()},i.prototype._configureContext=function(e,o){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:TextureUsage.RenderAttachment|TextureUsage.CopySrc,compositingAlphaMode:this.premultipliedAlpha?CanvasCompositingAlphaMode.Premultiplied:CanvasCompositingAlphaMode.Opaque,size:{width:e,height:o,depthOrArrayLayers:1}})},i.prototype.setSize=function(e,o,s){return s===void 0&&(s=!1),a.prototype.setSize.call(this,e,o,s)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - setSize called -",e,o)),this._configureContext(e,o),this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0):!1},i.prototype._getShaderProcessor=function(e){return e===ShaderLanguage.WGSL?this._shaderProcessorWGSL:this._shaderProcessor},i.prototype._getShaderProcessingContext=function(e){return new WebGPUShaderProcessingContext(e)},i.prototype.applyStates=function(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)},i.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames&&!e||(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=515,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(!1),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},i.prototype.setColorWrite=function(e){this.__colorWrite=e,this._cacheRenderPipeline.setWriteMask(e?15:0)},i.prototype.getColorWrite=function(){return this.__colorWrite},i.prototype._resetCurrentViewport=function(e){this._viewportsCurrent[e].x=0,this._viewportsCurrent[e].y=0,this._viewportsCurrent[e].w=0,this._viewportsCurrent[e].h=0,e===1&&(this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0)},i.prototype._mustUpdateViewport=function(e){var o=e===this._mainRenderPassWrapper.renderPass?0:1,s=this._viewportCached.x,c=this._viewportCached.y,d=this._viewportCached.z,_=this._viewportCached.w,b=this._viewportsCurrent[o].x!==s||this._viewportsCurrent[o].y!==c||this._viewportsCurrent[o].w!==d||this._viewportsCurrent[o].h!==_;return b&&(this._viewportsCurrent[o].x=this._viewportCached.x,this._viewportsCurrent[o].y=this._viewportCached.y,this._viewportsCurrent[o].w=this._viewportCached.z,this._viewportsCurrent[o].h=this._viewportCached.w),b},i.prototype._applyViewport=function(e){e.setViewport(Math.floor(this._viewportCached.x),Math.floor(this._viewportCached.y),Math.floor(this._viewportCached.z),Math.floor(this._viewportCached.w),0,1),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - viewport applied - (",this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))},i.prototype._viewport=function(e,o,s,c){this._viewportCached.x=e,this._viewportCached.y=o,this._viewportCached.z=s,this._viewportCached.w=c},i.prototype._resetCurrentScissor=function(e){this._scissorsCurrent[e].x=0,this._scissorsCurrent[e].y=0,this._scissorsCurrent[e].w=0,this._scissorsCurrent[e].h=0},i.prototype._mustUpdateScissor=function(e){var o=e===this._mainRenderPassWrapper.renderPass?0:1,s=this._scissorCached.x,c=this._scissorCached.y,d=this._scissorCached.z,_=this._scissorCached.w,b=this._scissorsCurrent[o].x!==s||this._scissorsCurrent[o].y!==c||this._scissorsCurrent[o].w!==d||this._scissorsCurrent[o].h!==_;return b&&(this._scissorsCurrent[o].x=this._scissorCached.x,this._scissorsCurrent[o].y=this._scissorCached.y,this._scissorsCurrent[o].w=this._scissorCached.z,this._scissorsCurrent[o].h=this._scissorCached.w),b},i.prototype._applyScissor=function(e){e.setScissorRect(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - scissor applied - (",this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))},i.prototype._scissorIsActive=function(){return this._scissorCached.x!==0||this._scissorCached.y!==0||this._scissorCached.z!==0||this._scissorCached.w!==0},i.prototype.enableScissor=function(e,o,s,c){this._scissorCached.x=e,this._scissorCached.y=o,this._scissorCached.z=s,this._scissorCached.w=c},i.prototype.disableScissor=function(){this._scissorCached.x=0,this._scissorCached.y=0,this._scissorCached.z=0,this._scissorCached.w=0,this._resetCurrentScissor(0),this._resetCurrentScissor(1)},i.prototype._resetCurrentStencilRef=function(e){this._stencilRefsCurrent[e]=-1},i.prototype._mustUpdateStencilRef=function(e){var o=e===this._mainRenderPassWrapper.renderPass?0:1,s=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent[o];return s&&(this._stencilRefsCurrent[o]=this._stencilStateComposer.funcRef),s},i.prototype._applyStencilRef=function(e){var o;e.setStencilReference((o=this._stencilStateComposer.funcRef)!==null&&o!==void 0?o:0)},i.prototype._resetCurrentColorBlend=function(e){this._blendColorsCurrent[e][0]=this._blendColorsCurrent[e][1]=this._blendColorsCurrent[e][2]=this._blendColorsCurrent[e][3]=null},i.prototype._mustUpdateBlendColor=function(e){var o=e===this._mainRenderPassWrapper.renderPass?0:1,s=this._alphaState._blendConstants,c=s[0]!==this._blendColorsCurrent[o][0]||s[1]!==this._blendColorsCurrent[o][1]||s[2]!==this._blendColorsCurrent[o][2]||s[3]!==this._blendColorsCurrent[o][3];return c&&(this._blendColorsCurrent[o][0]=s[0],this._blendColorsCurrent[o][1]=s[1],this._blendColorsCurrent[o][2]=s[2],this._blendColorsCurrent[o][3]=s[3]),c},i.prototype._applyBlendColor=function(e){e.setBlendConstant(this._alphaState._blendConstants)},i.prototype.clear=function(e,o,s,c){c===void 0&&(c=!1),e&&e.a===void 0&&(e.a=1);var d=this._scissorIsActive();this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - clear called - backBuffer=",o," depth=",s," stencil=",c," scissor is active=",d)),this._currentRenderTarget?d?(this._rttRenderPassWrapper.renderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,o?e:null,s,c),this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleListRenderTarget.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(o?e:null,s,c)):(this._currentRenderPass&&this._endRenderTargetRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,o?e:null,s,c)):((!this._mainRenderPassWrapper.renderPass||!d)&&this._startMainRenderPass(!d,o?e:null,s,c),d&&(this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(o?e:null,s,c)))},i.prototype._clearFullQuad=function(e,o,s){var c,d,_,b=this.compatibilityMode?this._getCurrentRenderPass():null,k=this._getCurrentRenderPassIndex(),j=k===0?this._bundleList:this._bundleListRenderTarget;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments((c=this._cacheRenderPipeline.mrtAttachments)!==null&&c!==void 0?c:[],(d=this._cacheRenderPipeline.mrtTextureArray)!==null&&d!==void 0?d:[]),this.compatibilityMode?b.setStencilReference(this._clearStencilValue):j.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));var $=this._clearQuad.clear(b,e,o,s,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(b):(j.addBundle($),j.addItem(new WebGPURenderItemStencilRef((_=this._stencilStateComposer.funcRef)!==null&&_!==void 0?_:0)),this._reportDrawCall())},i.prototype.createVertexBuffer=function(e){var o;e instanceof Array?o=new Float32Array(e):e instanceof ArrayBuffer?o=new Uint8Array(e):o=e;var s=this._bufferManager.createBuffer(o,BufferUsage.Vertex|BufferUsage.CopyDst);return s},i.prototype.createDynamicVertexBuffer=function(e){return this.createVertexBuffer(e)},i.prototype.createIndexBuffer=function(e,o){var s=!0,c;e instanceof Uint32Array||e instanceof Int32Array?c=e:e instanceof Uint16Array?(c=e,s=!1):e.length>65535?c=new Uint32Array(e):(c=new Uint16Array(e),s=!1);var d=this._bufferManager.createBuffer(c,BufferUsage.Index|BufferUsage.CopyDst);return d.is32Bits=s,d},i.prototype._createBuffer=function(e,o){var s;e instanceof Array?s=new Float32Array(e):e instanceof ArrayBuffer?s=new Uint8Array(e):s=e;var c=0;return o&1&&(c|=BufferUsage.CopySrc),o&2&&(c|=BufferUsage.CopyDst),o&4&&(c|=BufferUsage.Uniform),o&8&&(c|=BufferUsage.Vertex),o&16&&(c|=BufferUsage.Index),o&32&&(c|=BufferUsage.Storage),this._bufferManager.createBuffer(s,c)},i.prototype.bindBuffersDirectly=function(e,o,s,c,d){throw"Not implemented on WebGPU"},i.prototype.updateAndBindInstancesBuffer=function(e,o,s){throw"Not implemented on WebGPU"},i.prototype.bindBuffers=function(e,o,s,c){this._currentIndexBuffer=o,this._currentOverrideVertexBuffers=c!=null?c:null,this._cacheRenderPipeline.setBuffers(e,o,this._currentOverrideVertexBuffers)},i.prototype._releaseBuffer=function(e){return this._bufferManager.releaseBuffer(e)},i.prototype.createEffect=function(e,o,s,c,d,_,b,k,j,$){var _e;$===void 0&&($=ShaderLanguage.GLSL);var et=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,tt=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,rt=this._getGlobalDefines(),it=(_e=d!=null?d:o.defines)!==null&&_e!==void 0?_e:"";rt&&(it+=`
  772. `+rt);var nt=et+"+"+tt+"@"+it;if(this._compiledEffects[nt]){var ot=this._compiledEffects[nt];return b&&ot.isReady()&&b(ot),ot}var at=new Effect$1(e,o,s,c,this,d,_,b,k,j,nt,$);return this._compiledEffects[nt]=at,at},i.prototype._compileRawShaderToSpirV=function(e,o){return this._glslang.compileGLSL(e,o)},i.prototype._compileShaderToSpirV=function(e,o,s,c){return this._compileRawShaderToSpirV(c+(s?s+`
  773. `:"")+e,o)},i.prototype._getWGSLShader=function(e,o,s,c){return s?s="//"+s.split(`
  774. `).join(`
  775. //`)+`
  776. `:s="",s+e},i.prototype._createPipelineStageDescriptor=function(e,o,s){return this._tintWASM&&s===ShaderLanguage.GLSL&&(e=this._tintWASM.convertSpirV2WGSL(e),o=this._tintWASM.convertSpirV2WGSL(o)),{vertexStage:{module:this._device.createShaderModule({code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({code:o}),entryPoint:"main"}}},i.prototype._compileRawPipelineStageDescriptor=function(e,o,s){var c=s===ShaderLanguage.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,d=s===ShaderLanguage.GLSL?this._compileRawShaderToSpirV(o,"fragment"):o;return this._createPipelineStageDescriptor(c,d,s)},i.prototype._compilePipelineStageDescriptor=function(e,o,s,c){this.onBeforeShaderCompilationObservable.notifyObservers(this);var d=`#version 450
  777. `,_=c===ShaderLanguage.GLSL?this._compileShaderToSpirV(e,"vertex",s,d):this._getWGSLShader(e,"vertex",s,d),b=c===ShaderLanguage.GLSL?this._compileShaderToSpirV(o,"fragment",s,d):this._getWGSLShader(o,"fragment",s,d),k=this._createPipelineStageDescriptor(_,b,c);return this.onAfterShaderCompilationObservable.notifyObservers(this),k},i.prototype.createRawShaderProgram=function(e,o,s,c,d){throw"Not available on WebGPU"},i.prototype.createShaderProgram=function(e,o,s,c,d,_){throw"Not available on WebGPU"},i.prototype.inlineShaderCode=function(e){var o=new ShaderCodeInliner(e);return o.debug=!1,o.processCode(),o.code},i.prototype.createPipelineContext=function(e){return new WebGPUPipelineContext(e,this)},i.prototype.createMaterialContext=function(){return new WebGPUMaterialContext},i.prototype.createDrawContext=function(){return new WebGPUDrawContext(this._bufferManager)},i.prototype._preparePipelineContext=function(e,o,s,c,d,_,b,k,j,$){var _e=e,et=_e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(k),console.log(o),console.log(s)),_e.sources={fragment:s,vertex:o,rawVertex:d,rawFragment:_},c?_e.stages=this._compileRawPipelineStageDescriptor(o,s,et):_e.stages=this._compilePipelineStageDescriptor(o,s,k,et)},i.prototype.getAttributes=function(e,o){for(var s=new Array(o.length),c=e,d=0;d<o.length;d++){var _=o[d],b=c.shaderProcessingContext.availableAttributes[_];b!==void 0&&(s[d]=b)}return s},i.prototype.enableEffect=function(e){if(!!e){var o=!0;if(!DrawWrapper.IsWrapper(e))o=e!==this._currentEffect,this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&Logger$2.Warn("enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId="+e.uniqueId+", effect.name="+e.name+", effect.name.vertex="+e.name.vertex+", effect.name.fragment="+e.name.fragment,10);else if(!e.effect||e.effect===this._currentEffect&&e.materialContext===this._currentMaterialContext&&e.drawContext===this._currentDrawContext&&!this._forceEnableEffect){if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the effect property is empty!";return}else if(o=e.effect!==this._currentEffect,this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the materialContext property is empty!";this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=o||this._forceEnableEffect?!1:this._forceEnableEffect,o&&(this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect))}},i.prototype._releaseEffect=function(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))},i.prototype.releaseEffects=function(){for(var e in this._compiledEffects){var o=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(o)}this._compiledEffects={}},i.prototype._deletePipelineContext=function(e){var o=e;o&&e.dispose()},Object.defineProperty(i.prototype,"needPOTTextures",{get:function(){return!1},enumerable:!1,configurable:!0}),i.prototype._createHardwareTexture=function(){return new WebGPUHardwareTexture},i.prototype._releaseTexture=function(e){var o=this._internalTexturesCache.indexOf(e);o!==-1&&this._internalTexturesCache.splice(o,1),this._textureHelper.releaseTexture(e)},i.prototype._getRGBABufferInternalSizedFormat=function(e,o){return 5},i.prototype.updateTextureComparisonFunction=function(e,o){e._comparisonFunction=o},i.prototype._createInternalTexture=function(e,o,s,c){var d,_;s===void 0&&(s=!0),c===void 0&&(c=InternalTextureSource.Unknown);var b={};o!==void 0&&typeof o=="object"?(b.generateMipMaps=o.generateMipMaps,b.type=o.type===void 0?0:o.type,b.samplingMode=o.samplingMode===void 0?3:o.samplingMode,b.format=o.format===void 0?5:o.format,b.samples=(d=o.samples)!==null&&d!==void 0?d:1,b.creationFlags=(_=o.creationFlags)!==null&&_!==void 0?_:0):(b.generateMipMaps=o,b.type=0,b.samplingMode=3,b.format=5,b.samples=1,b.creationFlags=0),(b.type===1&&!this._caps.textureFloatLinearFiltering||b.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(b.samplingMode=1),b.type===1&&!this._caps.textureFloat&&(b.type=0,Logger$2.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));var k=new InternalTexture(this,c),j=e.width||e,$=e.height||e,_e=e.layers||0;return k.baseWidth=j,k.baseHeight=$,k.width=j,k.height=$,k.depth=_e,k.isReady=!0,k.samples=b.samples,k.generateMipMaps=!!b.generateMipMaps,k.samplingMode=b.samplingMode,k.type=b.type,k.format=b.format,k.is2DArray=_e>0,k._cachedWrapU=0,k._cachedWrapV=0,this._internalTexturesCache.push(k),s||this._textureHelper.createGPUTextureForInternalTexture(k,j,$,_e||1,b.creationFlags),k},i.prototype.createTexture=function(e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it){var nt=this;return d===void 0&&(d=3),_===void 0&&(_=null),b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=null),$===void 0&&($=null),_e===void 0&&(_e=null),this._createTextureBase(e,o,s,c,d,_,b,function(ot,at,st,ut,ft,lt,ht,pt,mt){var dt,gt=ut;if(ot.baseWidth=gt.width,ot.baseHeight=gt.height,ot.width=gt.width,ot.height=gt.height,ot.format=$!=null?$:-1,pt(ot.width,ot.height,gt,at,ot,function(){}),!((dt=ot._hardwareTexture)===null||dt===void 0)&&dt.underlyingResource)!lt&&!ht&&nt._generateMipmaps(ot,nt._uploadEncoder);else{var _t=nt._textureHelper.createGPUTextureForInternalTexture(ot,gt.width,gt.height,void 0,rt);WebGPUTextureHelper.IsImageBitmap(gt)&&(nt._textureHelper.updateTexture(gt,ot,gt.width,gt.height,ot.depth,_t.format,0,0,ft,!1,0,0,nt._uploadEncoder),!lt&&!ht&&nt._generateMipmaps(ot,nt._uploadEncoder))}st&&st._removePendingData(ot),ot.isReady=!0,ot.onLoadedObservable.notifyObservers(ot),ot.onLoadedObservable.clear()},function(){return!1},k,j,$,_e,et,tt,it)},i.prototype.generateMipMapsForCubemap=function(e,o){var s;if(e.generateMipMaps){var c=(s=e._hardwareTexture)===null||s===void 0?void 0:s.underlyingResource;c||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===InternalTextureSource.RenderTarget||e.source===InternalTextureSource.MultiRenderTarget?this._renderTargetEncoder:void 0)}},i.prototype.updateTextureSamplingMode=function(e,o,s){s===void 0&&(s=!1),s&&(o.generateMipMaps=!0,this._generateMipmaps(o)),o.samplingMode=e},i.prototype.updateTextureWrappingMode=function(e,o,s,c){s===void 0&&(s=null),c===void 0&&(c=null),o!==null&&(e._cachedWrapU=o),s!==null&&(e._cachedWrapV=s),(e.is2DArray||e.is3D)&&c!==null&&(e._cachedWrapR=c)},i.prototype.updateTextureDimensions=function(e,o,s,c){if(c===void 0&&(c=1),!!e._hardwareTexture&&!(e.width===o&&e.height===s&&e.depth===c)){var d=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,o,s,c,d)}},i.prototype._setInternalTexture=function(e,o,s,c){if(s=s!=null?s:e,this._currentEffect){var d=this._currentEffect._pipelineContext,_=d.shaderProcessingContext.availableTextures[s];if(this._currentMaterialContext.setTexture(e,o),_&&_.autoBindSampler){var b=s+WebGPUShaderProcessor.AutoSamplerSuffix;this._currentMaterialContext.setSampler(b,o)}}},i.prototype.setTexture=function(e,o,s,c){this._setTexture(e,s,!1,!1,c,c)},i.prototype.setTextureArray=function(e,o,s,c){for(var d=0;d<s.length;d++)this._setTexture(-1,s[d],!0,!1,c+d.toString(),c,d)},i.prototype._setTexture=function(e,o,s,c,d,_,b){if(c===void 0&&(c=!1),d===void 0&&(d=""),b===void 0&&(b=0),_=_!=null?_:d,this._currentEffect){if(!o)return this._currentMaterialContext.setTexture(d,null),!1;if(o.video)o.update();else if(o.delayLoadState===4)return o.delayLoad(),!1;var k=null;if(c?k=o.depthStencilTexture:o.isReady()?k=o.getInternalTexture():o.isCube?k=this.emptyCubeTexture:o.is3D?k=this.emptyTexture3D:o.is2DArray?k=this.emptyTexture2DArray:k=this.emptyTexture,k&&!k.isMultiview){if(k.isCube&&k._cachedCoordinatesMode!==o.coordinatesMode){k._cachedCoordinatesMode=o.coordinatesMode;var j=o.coordinatesMode!==3&&o.coordinatesMode!==5?1:0;o.wrapU=j,o.wrapV=j}k._cachedWrapU=o.wrapU,k._cachedWrapV=o.wrapV,k.is3D&&(k._cachedWrapR=o.wrapR),this._setAnisotropicLevel(0,k,o.anisotropicFilteringLevel)}this._setInternalTexture(d,k,_,b)}else this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - _setTexture called with a null _currentEffect! texture=",o));return!0},i.prototype._setAnisotropicLevel=function(e,o,s){o._cachedAnisotropicFilteringLevel!==s&&(o._cachedAnisotropicFilteringLevel=Math.min(s,this._caps.maxAnisotropy))},i.prototype._bindTexture=function(e,o,s){e!==void 0&&this._setInternalTexture(s,o)},i.prototype.generateMipmaps=function(e){this._generateMipmaps(e,this._renderTargetEncoder)},i.prototype._generateMipmaps=function(e,o){var s=e._hardwareTexture;if(!!s){o=o!=null?o:this._currentRenderTarget&&!this._currentRenderPass?this._renderTargetEncoder:this._currentRenderPass?this._uploadEncoder:this._renderEncoder;var c=e._hardwareTexture.format,d=WebGPUTextureHelper.ComputeNumMipmapLevels(e.width,e.height);this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - generate mipmaps called - width=",e.width,"height=",e.height,"isCube=",e.isCube)),e.isCube?this._textureHelper.generateCubeMipmaps(s,c,d,o):this._textureHelper.generateMipmaps(s,c,d,0,o)}},i.prototype.updateTextureData=function(e,o,s,c,d,_,b,k){var j;b===void 0&&(b=0),k===void 0&&(k=0);var $=e._hardwareTexture;!((j=e._hardwareTexture)===null||j===void 0)&&j.underlyingResource||($=this._textureHelper.createGPUTextureForInternalTexture(e));var _e=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);this._textureHelper.updateTexture(_e,e,d,_,e.depth,$.format,b,k,e.invertY,!1,s,c,this._uploadEncoder)},i.prototype._uploadCompressedDataToTextureDirectly=function(e,o,s,c,d,_,b){var k;_===void 0&&(_=0),b===void 0&&(b=0);var j=e._hardwareTexture;!((k=e._hardwareTexture)===null||k===void 0)&&k.underlyingResource||(e.format=o,j=this._textureHelper.createGPUTextureForInternalTexture(e,s,c));var $=new Uint8Array(d.buffer,d.byteOffset,d.byteLength);this._textureHelper.updateTexture($,e,s,c,e.depth,j.format,_,b,!1,!1,0,0,this._uploadEncoder)},i.prototype._uploadDataToTextureDirectly=function(e,o,s,c,d,_){var b;s===void 0&&(s=0),c===void 0&&(c=0),_===void 0&&(_=!1);var k=Math.round(Math.log(e.width)*Math.LOG2E),j=Math.round(Math.log(e.height)*Math.LOG2E),$=_?e.width:Math.pow(2,Math.max(k-c,0)),_e=_?e.height:Math.pow(2,Math.max(j-c,0)),et=e._hardwareTexture;!((b=e._hardwareTexture)===null||b===void 0)&&b.underlyingResource||(et=this._textureHelper.createGPUTextureForInternalTexture(e,$,_e));var tt=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);this._textureHelper.updateTexture(tt,e,$,_e,e.depth,et.format,s,c,e.invertY,!1,0,0,this._uploadEncoder)},i.prototype._uploadArrayBufferViewToTexture=function(e,o,s,c){s===void 0&&(s=0),c===void 0&&(c=0),this._uploadDataToTextureDirectly(e,o,s,c)},i.prototype._uploadImageToTexture=function(e,o,s,c){var d;s===void 0&&(s=0),c===void 0&&(c=0);var _=e._hardwareTexture;!((d=e._hardwareTexture)===null||d===void 0)&&d.underlyingResource||(_=this._textureHelper.createGPUTextureForInternalTexture(e));var b=o,k=Math.ceil(e.width/(1<<c)),j=Math.ceil(e.height/(1<<c));this._textureHelper.updateTexture(b,e,k,j,e.depth,_.format,s,c,e.invertY,!1,0,0,this._uploadEncoder)},i.prototype.readPixels=function(e,o,s,c,d,_){_===void 0&&(_=!0);var b=this._rttRenderPassWrapper.renderPass?this._rttRenderPassWrapper:this._mainRenderPassWrapper,k=b.colorAttachmentGPUTextures[0].underlyingResource,j=b.colorAttachmentGPUTextures[0].format;return k?(_&&this.flushFramebuffer(),this._textureHelper.readPixels(k,e,o,s,c,j)):Promise.resolve(new Uint8Array(0))},i.prototype.beginFrame=function(){a.prototype.beginFrame.call(this)},i.prototype.endFrame=function(){if(this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass),this._endMainRenderPass(),this._timestampQuery.endFrame(this._renderEncoder),this._invertYFinalFramebuffer&&this._mainRenderPassCopyWrapper.renderPassDescriptor.colorAttachments[0].view&&this._textureHelper.copyWithInvertY(this._mainTextureLastCopy.createView(),this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format,this._mainRenderPassCopyWrapper.renderPassDescriptor,this._renderEncoder),this.flushFramebuffer(!1),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - counters")),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._features._collectUbosUpdatedInFrame){if(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){var e=[];for(var o in UniformBuffer._updatedUbosInFrame)e.push(o+":"+UniformBuffer._updatedUbosInFrame[o]);console.log("frame #"+this._count+" - updated ubos -",e.join(", "))}UniformBuffer._updatedUbosInFrame={}}this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),this._pendingDebugCommands.length=0,a.prototype.endFrame.call(this),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),this._count<this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - end","background: #ffff00"),this._count<this.dbgVerboseLogsNumFrames&&(this._count++,this._count!==this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - begin","background: #ffff00")))},i.prototype.flushFramebuffer=function(e){e===void 0&&(e=!0);var o=!this._currentRenderPass,s=0;this._currentRenderPass&&this._currentRenderTarget&&(s|=1,this._endRenderTargetRenderPass()),this._mainRenderPassWrapper.renderPass&&(s|=2,this._endMainRenderPass()),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderTargetEncoder.finish(),this._commandBuffers[2]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset(),this._bundleListRenderTarget.reset(),e&&(s&2&&this._startMainRenderPass(!1),s&1&&this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1),o&&this._currentRenderTarget&&(this._currentRenderPass=null))},i.prototype._currentFrameBufferIsDefaultFrameBuffer=function(){return this._currentRenderTarget===null},i.prototype._startRenderTargetRenderPass=function(e,o,s,c,d){var _,b,k,j=e._depthStencilTexture,$=j==null?void 0:j._hardwareTexture,_e=$==null?void 0:$.underlyingResource,et=$==null?void 0:$.msaaTexture,tt=_e==null?void 0:_e.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),rt=et==null?void 0:et.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),it=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();var nt=o&&s||LoadOp.Load,ot=o&&c?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:LoadOp.Load,at=o&&d?this._clearStencilValue:LoadOp.Load;if(e._attachments&&e.isMulti){(!this._mrtAttachments||this._mrtAttachments.length===0)&&(this._mrtAttachments=e._attachments);for(var st=0;st<this._mrtAttachments.length;++st){var ut=this._mrtAttachments[st];if(ut!==0){var ft=e.textures[ut-1],lt=ft==null?void 0:ft._hardwareTexture,ht=lt==null?void 0:lt.underlyingResource;if(lt&&ht){var pt=__assign(__assign({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{format:lt.format}),mt=lt.msaaTexture,dt=ht.createView(pt),gt=mt==null?void 0:mt.createView(pt);it.push({view:gt||dt,resolveTarget:mt?dt:void 0,loadValue:nt,storeOp:StoreOp.Store})}}}this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments,e.textures)}else{var _t=e.texture,yt=_t._hardwareTexture,Tt=yt.underlyingResource,mt=yt.msaaTexture,dt=Tt.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),gt=mt==null?void 0:mt.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);it.push({view:gt||dt,resolveTarget:mt?dt:void 0,loadValue:nt,storeOp:StoreOp.Store})}if((_=this._debugPushGroup)===null||_===void 0||_.call(this,"render target pass",1),this._rttRenderPassWrapper.renderPassDescriptor={colorAttachments:it,depthStencilAttachment:j&&_e?{view:rt||tt,depthLoadValue:ot,depthStoreOp:StoreOp.Store,stencilLoadValue:e._depthStencilTextureWithStencil?at:LoadOp.Load,stencilStoreOp:StoreOp.Store}:void 0,occlusionQuerySet:!((b=this._occlusionQuery)===null||b===void 0)&&b.hasQueries?this._occlusionQuery.querySet:void 0},this._rttRenderPassWrapper.renderPass=this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){var _t=e.texture;console.log("frame #"+this._count+" - render target begin pass - internalTexture.uniqueId=",_t.uniqueId,"width=",_t.width,"height=",_t.height,this._rttRenderPassWrapper.renderPassDescriptor)}this._currentRenderPass=this._rttRenderPassWrapper.renderPass,(k=this._debugFlushPendingCommands)===null||k===void 0||k.call(this),this._resetCurrentViewport(1),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1)},i.prototype._endRenderTargetRenderPass=function(){var e,o,s;if(this._currentRenderPass){var c=this._currentRenderTarget.texture._hardwareTexture;!this._snapshotRendering.endRenderTargetPass(this._currentRenderPass,c)&&!this.compatibilityMode&&(this._bundleListRenderTarget.run(this._currentRenderPass),this._bundleListRenderTarget.reset()),this._currentRenderPass.endPass(),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - render target end pass - internalTexture.uniqueId=",(o=(e=this._currentRenderTarget)===null||e===void 0?void 0:e.texture)===null||o===void 0?void 0:o.uniqueId)),(s=this._debugPopGroup)===null||s===void 0||s.call(this,1),this._resetCurrentViewport(1),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),this._currentRenderPass=null,this._rttRenderPassWrapper.reset()}},i.prototype._getCurrentRenderPass=function(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass},i.prototype._getCurrentRenderPassIndex=function(){return this._currentRenderPass===null?-1:this._currentRenderPass===this._mainRenderPassWrapper.renderPass?0:1},i.prototype._startMainRenderPass=function(e,o,s,c){var d,_,b;this._mainRenderPassWrapper.renderPass&&this._endMainRenderPass(),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();var k=e&&o||LoadOp.Load,j=e&&s?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:LoadOp.Load,$=e&&c?this._clearStencilValue:LoadOp.Load;this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadValue=k,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadValue=j,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadValue=$,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=!((d=this._occlusionQuery)===null||d===void 0)&&d.hasQueries?this._occlusionQuery.querySet:void 0;var _e=this._invertYFinalFramebuffer?this._mainRenderPassCopyWrapper:this._mainRenderPassWrapper;this._swapChainTexture=this._context.getCurrentTexture(),_e.colorAttachmentGPUTextures[0].set(this._swapChainTexture),this._options.antialiasing?this._invertYFinalFramebuffer?_e.renderPassDescriptor.colorAttachments[0].view=this._swapChainTexture.createView():_e.renderPassDescriptor.colorAttachments[0].resolveTarget=this._swapChainTexture.createView():_e.renderPassDescriptor.colorAttachments[0].view=this._swapChainTexture.createView(),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main begin pass - texture width="+this._mainTextureExtends.width," height="+this._mainTextureExtends.height,this._mainRenderPassWrapper.renderPassDescriptor)),(_=this._debugPushGroup)===null||_===void 0||_.call(this,"main pass",0),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._mainRenderPassWrapper.renderPass=this._currentRenderPass,(b=this._debugFlushPendingCommands)===null||b===void 0||b.call(this),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0)},i.prototype._endMainRenderPass=function(){var e;this._mainRenderPassWrapper.renderPass!==null&&(this._snapshotRendering.endMainRenderPass(),!this.compatibilityMode&&!this._snapshotRendering.play&&(this._bundleList.run(this._mainRenderPassWrapper.renderPass),this._bundleList.reset()),this._mainRenderPassWrapper.renderPass.endPass(),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main end pass")),(e=this._debugPopGroup)===null||e===void 0||e.call(this,0),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._mainRenderPassWrapper.renderPass===this._currentRenderPass&&(this._currentRenderPass=null),this._mainRenderPassWrapper.reset(!1))},i.prototype.bindFramebuffer=function(e,o,s,c,d,_,b){var k,j;o===void 0&&(o=0),_===void 0&&(_=0),b===void 0&&(b=0);var $=(k=e.texture)===null||k===void 0?void 0:k._hardwareTexture;if(!$){this.dbgSanityChecks&&console.error("bindFramebuffer: Trying to bind a texture that does not have a hardware texture!",e,$);return}this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,$._currentLayer=e.isCube?b*6+o:b,this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=$,this._rttRenderPassWrapper.depthTextureFormat=this._currentRenderTarget._depthStencilTexture?WebGPUTextureHelper.GetWebGPUTextureFormat(-1,this._currentRenderTarget._depthStencilTexture.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={format:this._colorFormat,dimension:TextureViewDimension.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?b*6+o:b,baseMipLevel:_,arrayLayerCount:1,aspect:TextureAspect.All},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={format:this._depthTextureFormat,dimension:TextureViewDimension.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?b*6+o:b,baseMipLevel:0,arrayLayerCount:1,aspect:TextureAspect.All},this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - bindFramebuffer called - internalTexture.uniqueId=",(j=e.texture)===null||j===void 0?void 0:j.uniqueId,"face=",o,"lodLevel=",_,"layer=",b,this._rttRenderPassWrapper.colorAttachmentViewDescriptor,this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),this._currentRenderPass=null,this.snapshotRendering&&this.snapshotRenderingMode===1&&this._getCurrentRenderPass(),this._cachedViewport&&!d?this.setViewport(this._cachedViewport,s,c):(s||(s=e.width,_&&(s=s/Math.pow(2,_))),c||(c=e.height,_&&(c=c/Math.pow(2,_))),this._viewport(0,0,s,c)),this.wipeCaches()},i.prototype.unBindFramebuffer=function(e,o,s){var c,d;o===void 0&&(o=!1);var _=this._currentRenderTarget;this._currentRenderTarget=null,s&&s(),this._currentRenderTarget=_,this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass(),((c=e.texture)===null||c===void 0?void 0:c.generateMipMaps)&&!o&&!e.isCube&&this._generateMipmaps(e.texture),this._currentRenderTarget=null,this._onAfterUnbindFrameBufferObservable.notifyObservers(this),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - unBindFramebuffer called - internalTexture.uniqueId=",(d=e.texture)===null||d===void 0?void 0:d.uniqueId)),this._mrtAttachments=[],this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments,[]),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)},i.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):(this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)),this._currentRenderPass&&this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()},i.prototype._setColorFormat=function(e){var o=e.colorAttachmentGPUTextures[0].format;this._cacheRenderPipeline.setColorFormat(o),this._colorFormat!==o&&(this._colorFormat=o)},i.prototype._setDepthTextureFormat=function(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)},i.prototype.setDitheringState=function(e){},i.prototype.setRasterizerState=function(e){},i.prototype.setState=function(e,o,s,c,d,_,b){var k,j;o===void 0&&(o=0),c===void 0&&(c=!1),b===void 0&&(b=0),(this._depthCullingState.cull!==e||s)&&(this._depthCullingState.cull=e);var $=!((j=(k=this.cullBackFaces)!==null&&k!==void 0?k:d)!==null&&j!==void 0)||j?1:2;(this._depthCullingState.cullFace!==$||s)&&(this._depthCullingState.cullFace=$),this.setZOffset(o),this.setZOffsetUnits(b);var _e=c?1:2;(this._depthCullingState.frontFace!==_e||s)&&(this._depthCullingState.frontFace=_e),this._stencilStateComposer.stencilMaterial=_},i.prototype._applyRenderPassChanges=function(e,o){var s,c=this._mustUpdateViewport(e),d=this._mustUpdateScissor(e),_=this._stencilStateComposer.enabled?this._mustUpdateStencilRef(e):!1,b=this._alphaState.alphaBlend?this._mustUpdateBlendColor(e):!1;o?(c&&o.addItem(new WebGPURenderItemViewport(this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w)),d&&o.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),_&&o.addItem(new WebGPURenderItemStencilRef((s=this._stencilStateComposer.funcRef)!==null&&s!==void 0?s:0)),b&&o.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()))):(c&&this._applyViewport(e),d&&this._applyScissor(e),_&&this._applyStencilRef(e),b&&this._applyBlendColor(e))},i.prototype._draw=function(e,o,s,c,d){var _,b=this._getCurrentRenderPass(),k=this._getCurrentRenderPassIndex(),j=k===0?this._bundleList:this._bundleListRenderTarget;this.applyStates();var $=this._currentEffect._pipelineContext;if($.uniformBuffer&&($.uniformBuffer.update(),this.bindUniformBufferBase($.uniformBuffer.getBuffer(),0,WebGPUShaderProcessor.LeftOvertUBOName)),this._snapshotRendering.play){this._reportDrawCall();return}!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);var _e=!this.compatibilityMode&&this._currentDrawContext.fastBundle,et=b;if(_e||this._snapshotRendering.record){if(this._applyRenderPassChanges(b,j),!this._snapshotRendering.record){this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(c,d||1,s),j.addBundle(this._currentDrawContext.fastBundle),this._reportDrawCall();return}et=j.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),j.numDrawCalls++}var tt=0;if(!this._caps.textureFloatLinearFiltering&&this._currentMaterialContext.hasFloatTextures)for(var rt=1,it=0;it<$.shaderProcessingContext.textureNames.length;++it){var nt=$.shaderProcessingContext.textureNames[it],ot=(_=this._currentMaterialContext.textures[nt])===null||_===void 0?void 0:_.texture;(ot==null?void 0:ot.type)===1&&(tt|=rt),rt=rt<<1}var at=this._cacheRenderPipeline.getRenderPipeline(o,this._currentEffect,this.currentSampleCount,tt),st=this._cacheBindGroups.getBindGroups($,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(b,this.compatibilityMode?null:j),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,et=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:this.currentSampleCount}))),et.setPipeline(at),this._currentIndexBuffer&&et.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?IndexFormat.Uint32:IndexFormat.Uint16,0);for(var ut=this._cacheRenderPipeline.vertexBuffers,ft=0;ft<ut.length;ft++){var lt=ut[ft],ht=lt.getBuffer();ht&&et.setVertexBuffer(ft,ht.underlyingResource,lt._validOffsetRange?0:lt.byteOffset)}for(var it=0;it<st.length;it++)et.setBindGroup(it,st[it]);var pt=!this.compatibilityMode&&!this._snapshotRendering.record;pt&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(c,d||1,s),e===0?et.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):et.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):e===0?et.drawIndexed(c,d||1,s,0,0):et.draw(c,d||1,s,0),pt&&(this._currentDrawContext.fastBundle=et.finish(),j.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()},i.prototype.drawElementsType=function(e,o,s,c){c===void 0&&(c=1),this._draw(0,e,o,s,c)},i.prototype.drawArraysType=function(e,o,s,c){c===void 0&&(c=1),this._currentIndexBuffer=null,this._draw(1,e,o,s,c)},i.prototype.dispose=function(){var e,o,s;(e=this._mainTexture)===null||e===void 0||e.destroy(),(o=this._mainTextureLastCopy)===null||o===void 0||o.destroy(),(s=this._depthTexture)===null||s===void 0||s.destroy(),a.prototype.dispose.call(this)},i.prototype.getRenderWidth=function(e){return e===void 0&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._canvas.width},i.prototype.getRenderHeight=function(e){return e===void 0&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._canvas.height},i.prototype.getRenderingCanvas=function(){return this._canvas},i.prototype.getError=function(){return 0},i.prototype.bindSamplers=function(e){},i.prototype._bindTextureDirectly=function(e,o,s,c){return!1},i.prototype.areAllEffectsReady=function(){return!0},i.prototype._executeWhenRenderingStateIsCompiled=function(e,o){o()},i.prototype._isRenderingStateCompiled=function(e){return!0},i.prototype._getUnpackAlignement=function(){return 1},i.prototype._unpackFlipY=function(e){},i.prototype._bindUnboundFramebuffer=function(e){throw"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"},i.prototype._getSamplingParameters=function(e,o){throw"_getSamplingParameters is not available in WebGPU"},i.prototype.getUniforms=function(e,o){return[]},i.prototype.setIntArray=function(e,o){return!1},i.prototype.setIntArray2=function(e,o){return!1},i.prototype.setIntArray3=function(e,o){return!1},i.prototype.setIntArray4=function(e,o){return!1},i.prototype.setArray=function(e,o){return!1},i.prototype.setArray2=function(e,o){return!1},i.prototype.setArray3=function(e,o){return!1},i.prototype.setArray4=function(e,o){return!1},i.prototype.setMatrices=function(e,o){return!1},i.prototype.setMatrix3x3=function(e,o){return!1},i.prototype.setMatrix2x2=function(e,o){return!1},i.prototype.setFloat=function(e,o){return!1},i.prototype.setFloat2=function(e,o,s){return!1},i.prototype.setFloat3=function(e,o,s,c){return!1},i.prototype.setFloat4=function(e,o,s,c,d){return!1},i._glslangDefaultOptions={jsPath:"https://preview.babylonjs.com/glslang/glslang.js",wasmPath:"https://preview.babylonjs.com/glslang/glslang.wasm"},i.UseTWGSL=!0,i}(Engine);WebGPUEngine.prototype.setAlphaMode=function(a,i){if(i===void 0&&(i=!1),!(this._alphaMode===a&&(a===0&&!this._alphaState.alphaBlend||a!==0&&this._alphaState.alphaBlend))){switch(a){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0;break}i||(this.setDepthWrite(a===Engine.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(a===Engine.ALPHA_DISABLE)),this._alphaMode=a,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)}};WebGPUEngine.prototype.setAlphaEquation=function(a){Engine.prototype.setAlphaEquation.call(this,a),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};var ComputeEffect=function(){function a(i,e,o,s){var c=this;s===void 0&&(s="");var d,_;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new Observable,this.onErrorObservable=new Observable,this.onBindObservable=new Observable,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=ShaderLanguage.WGSL,this.name=i,this._key=s,this._engine=o,this.uniqueId=a._uniqueIdSeed++,this.defines=(d=e.defines)!==null&&d!==void 0?d:"",this.onError=e.onError,this.onCompiled=e.onCompiled,this._entryPoint=(_=e.entryPoint)!==null&&_!==void 0?_:"main",this._shaderStore=ShaderStore.GetShadersStore(this._shaderLanguage),this._shaderRepository=ShaderStore.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=ShaderStore.GetIncludesShadersStore(this._shaderLanguage);var b,k=IsWindowObjectExist()?this._engine.getHostDocument():null;i.computeSource?b="source:"+i.computeSource:i.computeElement?(b=k?k.getElementById(i.computeElement):null,b||(b=i.computeElement)):b=i.compute||i;var j={defines:this.defines.split(`
  778. `),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(b,"Compute","",function($){ShaderProcessor.Initialize(j),ShaderProcessor.PreProcess($,j,function(_e){c._rawComputeSourceCode=$,e.processFinalCode&&(_e=e.processFinalCode(_e));var et=ShaderProcessor.Finalize(_e,"",j);c._useFinalCode(et.vertexCode,i)},c._engine)})}return a.prototype._useFinalCode=function(i,e){if(e){var o=e.computeElement||e.compute||e.spectorName||e;this._computeSourceCode="//#define SHADER_NAME compute:"+o+`
  779. `+i}else this._computeSourceCode=i;this._prepareEffect()},Object.defineProperty(a.prototype,"key",{get:function(){return this._key},enumerable:!1,configurable:!0}),a.prototype.isReady=function(){try{return this._isReadyInternal()}catch{return!1}},a.prototype._isReadyInternal=function(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1},a.prototype.getEngine=function(){return this._engine},a.prototype.getPipelineContext=function(){return this._pipelineContext},a.prototype.getCompilationError=function(){return this._compilationError},a.prototype.executeWhenCompiled=function(i){var e=this;if(this.isReady()){i(this);return}this.onCompileObservable.add(function(o){i(o)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(function(){e._checkIsReady(null)},16)},a.prototype._checkIsReady=function(i){var e=this;try{if(this._isReadyInternal())return}catch(o){this._processCompilationErrors(o,i);return}setTimeout(function(){e._checkIsReady(i)},16)},a.prototype._loadShader=function(i,e,o,s){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement){var c=GetDOMTextContent(i);s(c);return}if(i.substr(0,7)==="source:"){s(i.substr(7));return}if(i.substr(0,7)==="base64:"){var d=window.atob(i.substr(7));s(d);return}if(this._shaderStore[i+e+"Shader"]){s(this._shaderStore[i+e+"Shader"]);return}if(o&&this._shaderStore[i+o+"Shader"]){s(this._shaderStore[i+o+"Shader"]);return}var _;i[0]==="."||i[0]==="/"||i.indexOf("http")>-1?_=i:_=this._shaderRepository+i,this._engine._loadFile(_+"."+e.toLowerCase()+".fx",s)},Object.defineProperty(a.prototype,"computeSourceCode",{get:function(){var i,e;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:(e=(i=this._pipelineContext)===null||i===void 0?void 0:i._getComputeShaderCode())!==null&&e!==void 0?e:this._computeSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rawComputeSourceCode",{get:function(){return this._rawComputeSourceCode},enumerable:!1,configurable:!0}),a.prototype._prepareEffect=function(){var i=this,e=this.defines,o=this._pipelineContext;this._isReady=!1;try{var s=this._engine;this._pipelineContext=s.createComputePipelineContext(),this._pipelineContext._name=this._key,s._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),s._executeWhenComputeStateIsCompiled(this._pipelineContext,function(){i._compilationError="",i._isReady=!0,i.onCompiled&&i.onCompiled(i),i.onCompileObservable.notifyObservers(i),i.onCompileObservable.clear(),o&&i.getEngine()._deleteComputePipelineContext(o)}),this._pipelineContext.isAsync&&this._checkIsReady(o)}catch(c){this._processCompilationErrors(c,o)}},a.prototype._getShaderCodeAndErrorLine=function(i,e){var o=/COMPUTE SHADER ERROR: 0:(\d+?):/,s=null;if(e&&i){var c=e.match(o);if(c&&c.length===2){var d=parseInt(c[1]),_=i.split(`
  780. `,-1);_.length>=d&&(s="Offending line ["+d+"] in compute code: "+_[d-1])}}return[i,s]},a.prototype._processCompilationErrors=function(i,e){var o,s;if(e===void 0&&(e=null),this._compilationError=i.message,Logger$2.Error("Unable to compile compute effect:"),Logger$2.Error(`Defines:\r
  781. `+this.defines),a.LogShaderCodeOnCompilationError){var c=null,d=null;!((s=this._pipelineContext)===null||s===void 0)&&s._getComputeShaderCode()&&(o=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),d=o[0],c=o[1],d&&(Logger$2.Error("Compute code:"),Logger$2.Error(d))),c&&Logger$2.Error(c)}Logger$2.Error("Error: "+this._compilationError),e&&(this._pipelineContext=e,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))},a.prototype.dispose=function(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)},a.RegisterShader=function(i,e){ShaderStore.GetShadersStore(ShaderLanguage.WGSL)[i+"ComputeShader"]=e},a._uniqueIdSeed=0,a.LogShaderCodeOnCompilationError=!0,a}(),WebGPUComputeContext=function(){function a(i,e){this._device=i,this._cacheSampler=e,this.uniqueId=a._Counter++,this._bindGroupEntries=[],this.clear()}return a.prototype.getBindGroups=function(i,e,o){if(!o)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(this._bindGroups.length===0){var s=this._bindGroupEntries.length>0;for(var c in i){var d=i[c],_=o[c],b=_.group,k=_.binding,j=d.type,$=d.object,_e=d.indexInGroupEntries,et=this._bindGroupEntries[b];switch(et||(et=this._bindGroupEntries[b]=[]),j){case ComputeBindingType.Sampler:{var tt=$;_e!==void 0&&s?et[_e].resource=this._cacheSampler.getSampler(tt):(d.indexInGroupEntries=et.length,et.push({binding:k,resource:this._cacheSampler.getSampler(tt)}));break}case ComputeBindingType.Texture:case ComputeBindingType.TextureWithoutSampler:{var rt=$,it=rt._texture._hardwareTexture;_e!==void 0&&s?(j===ComputeBindingType.Texture&&(et[_e++].resource=this._cacheSampler.getSampler(rt._texture)),et[_e].resource=it.view):(d.indexInGroupEntries=et.length,j===ComputeBindingType.Texture&&et.push({binding:k-1,resource:this._cacheSampler.getSampler(rt._texture)}),et.push({binding:k,resource:it.view}));break}case ComputeBindingType.StorageTexture:{var rt=$,it=rt._texture._hardwareTexture;(it.textureAdditionalUsages&TextureUsage.StorageBinding)===0&&Logger$2.Error("computeDispatch: The texture (name="+rt.name+", uniqueId="+rt.uniqueId+") is not a storage texture!",50),_e!==void 0&&s?et[_e].resource=it.view:(d.indexInGroupEntries=et.length,et.push({binding:k,resource:it.view}));break}case ComputeBindingType.UniformBuffer:case ComputeBindingType.StorageBuffer:{var nt=(j===ComputeBindingType.UniformBuffer,$),ot=nt.getBuffer(),at=ot.underlyingResource;_e!==void 0&&s?(et[_e].resource.buffer=at,et[_e].resource.size=ot.capacity):(d.indexInGroupEntries=et.length,et.push({binding:k,resource:{buffer:at,offset:0,size:ot.capacity}}));break}}}for(var st=0;st<this._bindGroupEntries.length;++st){var et=this._bindGroupEntries[st];if(!et){this._bindGroups[st]=void 0;continue}this._bindGroups[st]=this._device.createBindGroup({layout:e.getBindGroupLayout(st),entries:et})}this._bindGroups.length=this._bindGroupEntries.length}return this._bindGroups},a.prototype.clear=function(){this._bindGroups=[]},a._Counter=0,a}(),WebGPUComputePipelineContext=function(){function a(i){this._name="unnamed",this.engine=i}return Object.defineProperty(a.prototype,"isAsync",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isReady",{get:function(){return!!this.stage},enumerable:!1,configurable:!0}),a.prototype._getComputeShaderCode=function(){var i;return(i=this.sources)===null||i===void 0?void 0:i.compute},a.prototype.dispose=function(){},a}();WebGPUEngine.prototype.createComputeContext=function(){return new WebGPUComputeContext(this._device,this._cacheSampler)};WebGPUEngine.prototype.createComputeEffect=function(a,i){var e=a.computeElement||a.compute||a.computeToken||a.computeSource||a,o=e+"@"+i.defines;if(this._compiledComputeEffects[o]){var s=this._compiledComputeEffects[o];return i.onCompiled&&s.isReady()&&i.onCompiled(s),s}var c=new ComputeEffect(a,i,this,o);return this._compiledComputeEffects[o]=c,c};WebGPUEngine.prototype.createComputePipelineContext=function(){return new WebGPUComputePipelineContext(this)};WebGPUEngine.prototype.areAllComputeEffectsReady=function(){for(var a in this._compiledComputeEffects){var i=this._compiledComputeEffects[a];if(!i.isReady())return!1}return!0};WebGPUEngine.prototype.computeDispatch=function(a,i,e,o,s,c,d){var _=this;if(this._currentRenderTarget){this._onAfterUnbindFrameBufferObservable.addOnce(function(){_.computeDispatch(a,i,e,o,s,c,d)});return}var b=a._pipelineContext,k=i;b.computePipeline||(b.computePipeline=this._device.createComputePipeline({compute:b.stage}));var j=this._renderTargetEncoder,$=j.beginComputePass();$.setPipeline(b.computePipeline);for(var _e=k.getBindGroups(e,b.computePipeline,d),et=0;et<_e.length;++et){var tt=_e[et];!tt||$.setBindGroup(et,tt)}$.dispatch(o,s,c),$.endPass()};WebGPUEngine.prototype.releaseComputeEffects=function(){for(var a in this._compiledComputeEffects){var i=this._compiledComputeEffects[a].getPipelineContext();this._deleteComputePipelineContext(i)}this._compiledComputeEffects={}};WebGPUEngine.prototype._prepareComputePipelineContext=function(a,i,e,o,s){var c=a;this.dbgShowShaderCode&&(console.log(o),console.log(i)),c.sources={compute:i,rawCompute:e},c.stage=this._createComputePipelineStageDescriptor(i,o,s)};WebGPUEngine.prototype._releaseComputeEffect=function(a){this._compiledComputeEffects[a._key]&&(delete this._compiledComputeEffects[a._key],this._deleteComputePipelineContext(a.getPipelineContext()))};WebGPUEngine.prototype._rebuildComputeEffects=function(){for(var a in this._compiledComputeEffects){var i=this._compiledComputeEffects[a];i._pipelineContext=null,i._wasPreviouslyReady=!1,i._prepareEffect()}};WebGPUEngine.prototype._deleteComputePipelineContext=function(a){var i=a;i&&a.dispose()};WebGPUEngine.prototype._createComputePipelineStageDescriptor=function(a,i,e){return i?i="//"+i.split(`
  782. `).join(`
  783. //`)+`
  784. `:i="",{module:this._device.createShaderModule({code:i+a}),entryPoint:e}};WebGPUEngine.prototype._createDepthStencilCubeTexture=function(a,i){var e=new InternalTexture(this,InternalTextureSource.DepthStencil);e.isCube=!0;var o=__assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},i);return e.format=o.generateStencil?13:14,this._setupDepthStencilTexture(e,a,o.generateStencil,o.bilinearFiltering,o.comparisonFunction,o.samples),this._textureHelper.createGPUTextureForInternalTexture(e),this._internalTexturesCache.push(e),e};WebGPUEngine.prototype.createCubeTexture=function(a,i,e,o,s,c,d,_,b,k,j,$,_e){var et=this;return s===void 0&&(s=null),c===void 0&&(c=null),_===void 0&&(_=null),b===void 0&&(b=!1),k===void 0&&(k=0),j===void 0&&(j=0),$===void 0&&($=null),_e===void 0&&(_e=!1),this.createCubeTextureBase(a,i,e,!!o,s,c,d,_,b,k,j,$,null,function(tt,rt){var it=rt,nt=it[0].width,ot=nt;et._setCubeMapTextureParams(tt,!o),tt.format=d!=null?d:-1;var at=et._textureHelper.createGPUTextureForInternalTexture(tt,nt,ot);et._textureHelper.updateCubeTextures(it,at.underlyingResource,nt,ot,at.format,!1,!1,0,0,et._uploadEncoder),o||et._generateMipmaps(tt,et._uploadEncoder),tt.isReady=!0,tt.onLoadedObservable.notifyObservers(tt),tt.onLoadedObservable.clear(),s&&s()},!!_e)};WebGPUEngine.prototype._setCubeMapTextureParams=function(a,i){a.samplingMode=i?3:2,a._cachedWrapU=0,a._cachedWrapV=0};WebGPUEngine.prototype._debugPushGroup=function(a,i){if(!!this._options.enableGPUDebugMarkers)if(i===0||i===1){var e=i===0?this._renderEncoder:this._renderTargetEncoder;e.pushDebugGroup(a)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(a):this._pendingDebugCommands.push(["push",a])};WebGPUEngine.prototype._debugPopGroup=function(a){if(!!this._options.enableGPUDebugMarkers)if(a===0||a===1){var i=a===0?this._renderEncoder:this._renderTargetEncoder;i.popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])};WebGPUEngine.prototype._debugInsertMarker=function(a,i){if(!!this._options.enableGPUDebugMarkers)if(i===0||i===1){var e=i===0?this._renderEncoder:this._renderTargetEncoder;e.insertDebugMarker(a)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(a):this._pendingDebugCommands.push(["insert",a])};WebGPUEngine.prototype._debugFlushPendingCommands=function(){for(var a=0;a<this._pendingDebugCommands.length;++a){var i=this._pendingDebugCommands[a],e=i[0],o=i[1];switch(e){case"push":this._debugPushGroup(o);break;case"pop":this._debugPopGroup();break;case"insert":this._debugInsertMarker(o);break}}this._pendingDebugCommands.length=0};WebGPUEngine.prototype.updateDynamicIndexBuffer=function(a,i,e){e===void 0&&(e=0);var o=a,s;i instanceof Uint16Array?a.is32Bits?s=Uint32Array.from(i):s=i:i instanceof Uint32Array?a.is32Bits?s=i:s=Uint16Array.from(i):a.is32Bits?s=new Uint32Array(i):s=new Uint16Array(i),this._bufferManager.setSubData(o,e,s)};WebGPUEngine.prototype.updateDynamicVertexBuffer=function(a,i,e,o){var s=a;e===void 0&&(e=0);var c;o===void 0?(i instanceof Array?c=new Float32Array(i):i instanceof ArrayBuffer?c=new Uint8Array(i):c=i,o=c.byteLength):i instanceof Array?c=new Float32Array(i):i instanceof ArrayBuffer?c=new Uint8Array(i):c=i,this._bufferManager.setSubData(s,e,c,0,o)};WebGPUEngine.prototype.updateDynamicTexture=function(a,i,e,o,s,c,d){var _;if(o===void 0&&(o=!1),!!a){var b=i.width,k=i.height,j=a._hardwareTexture;!((_=a._hardwareTexture)===null||_===void 0)&&_.underlyingResource||(j=this._textureHelper.createGPUTextureForInternalTexture(a,b,k)),this._textureHelper.updateTexture(i,a,b,k,a.depth,j.format,0,0,e,o,0,0,this._uploadEncoder,d),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder),a.isReady=!0}};var WebGPUExternalTexture=function(a){__extends(i,a);function i(e){return a.call(this,e)||this}return i}(ExternalTexture);Effect$1.prototype.setExternalTexture=function(a,i){this._engine.setExternalTexture(a,i)};WebGPUEngine.prototype.createExternalTexture=function(a){var i=new WebGPUExternalTexture(a);return i};WebGPUEngine.prototype.setExternalTexture=function(a,i){if(!i){this._currentMaterialContext.setTexture(a,null);return}this._setInternalTexture(a,i)};WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer=function(a,i,e){i===void 0&&(i=!1),e&&e();var o=a._attachments,s=o.length;this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass();for(var c=0;c<s;c++){var d=a.textures[c];d.generateMipMaps&&!i&&!d.isCube&&this._generateMipmaps(d)}this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments,[]),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)};WebGPUEngine.prototype.createMultipleRenderTarget=function(a,i,e){var o,s=!1,c=!0,d=!1,_=!1,b=15,k=1,j=0,$=3,_e=new Array,et=new Array,tt=this._createHardwareRenderTargetWrapper(!0,!1,a);i!==void 0&&(s=i.generateMipMaps===void 0?!1:i.generateMipMaps,c=i.generateDepthBuffer===void 0?!0:i.generateDepthBuffer,d=i.generateStencilBuffer===void 0?!1:i.generateStencilBuffer,_=i.generateDepthTexture===void 0?!1:i.generateDepthTexture,k=i.textureCount||1,b=(o=i.depthTextureFormat)!==null&&o!==void 0?o:15,i.types&&(_e=i.types),i.samplingModes&&(et=i.samplingModes));var rt=a.width||a,it=a.height||a,nt=null;(c||d||_)&&(nt=tt.createDepthStencilTexture(0,!1,d,1,b));var ot=[],at=[];tt._generateDepthBuffer=c,tt._generateStencilBuffer=d,tt._attachments=at;for(var st=0;st<k;st++){var ut=et[st]||$,ft=_e[st]||j;(ft===1&&!this._caps.textureFloatLinearFiltering||ft===2&&!this._caps.textureHalfFloatLinearFiltering)&&(ut=1),ft===1&&!this._caps.textureFloat&&(ft=0,Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));var lt=new InternalTexture(this,InternalTextureSource.MultiRenderTarget);ot.push(lt),at.push(st+1),lt.baseWidth=rt,lt.baseHeight=it,lt.width=rt,lt.height=it,lt.isReady=!0,lt.samples=1,lt.generateMipMaps=s,lt.samplingMode=ut,lt.type=ft,lt._cachedWrapU=0,lt._cachedWrapV=0,this._internalTexturesCache.push(lt),this._textureHelper.createGPUTextureForInternalTexture(lt)}return nt&&(nt.incrementReferences(),ot.push(nt),this._internalTexturesCache.push(nt)),tt.setTextures(ot),tt};WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(a,i){if(!a||!a.textures||a.textures[0].samples===i)return i;var e=a._attachments.length;if(e===0)return 1;i=Math.min(i,this.getCaps().maxMSAASamples);for(var o=0;o<e;++o){var s=a.textures[o];this._textureHelper.createMSAATexture(s,i),s.samples=i}return a._depthStencilTexture&&a._depthStencilTexture!==a.textures[a.textures.length-1]&&(this._textureHelper.createMSAATexture(a._depthStencilTexture,i),a._depthStencilTexture.samples=i),i};WebGPUEngine.prototype.bindAttachments=function(a){a.length===0||!this._currentRenderTarget||(this._mrtAttachments=a)};WebGPUEngine.prototype.buildTextureLayout=function(a){for(var i=[],e=0;e<a.length;e++)a[e]?i.push(e+1):i.push(0);return i};WebGPUEngine.prototype.restoreSingleAttachment=function(){};WebGPUEngine.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter};WebGPUEngine.prototype.captureGPUFrameTime=function(a){this._timestampQuery.enable=a&&!!this._caps.timerQuery};WebGPUEngine.prototype.createQuery=function(){return this._occlusionQuery.createQuery()};WebGPUEngine.prototype.deleteQuery=function(a){return this._occlusionQuery.deleteQuery(a),this};WebGPUEngine.prototype.isQueryResultAvailable=function(a){return this._occlusionQuery.isQueryResultAvailable(a)};WebGPUEngine.prototype.getQueryResult=function(a){return this._occlusionQuery.getQueryResult(a)};WebGPUEngine.prototype.beginOcclusionQuery=function(a,i){var e;if(this.compatibilityMode){if(this._occlusionQuery.canBeginQuery)return(e=this._currentRenderPass)===null||e===void 0||e.beginOcclusionQuery(i),!0}else{var o=this._getCurrentRenderPassIndex(),s=o===0?this._bundleList:this._bundleListRenderTarget;return s.addItem(new WebGPURenderItemBeginOcclusionQuery(i)),!0}return!1};WebGPUEngine.prototype.endOcclusionQuery=function(a){var i;if(this.compatibilityMode)(i=this._currentRenderPass)===null||i===void 0||i.endOcclusionQuery();else{var e=this._getCurrentRenderPassIndex(),o=e===0?this._bundleList:this._bundleListRenderTarget;o.addItem(new WebGPURenderItemEndOcclusionQuery)}return this};WebGPUEngine.prototype.createRawTexture=function(a,i,e,o,s,c,d,_,b,k){_===void 0&&(_=null),b===void 0&&(b=0),k===void 0&&(k=0);var j=new InternalTexture(this,InternalTextureSource.Raw);return j.baseWidth=i,j.baseHeight=e,j.width=i,j.height=e,j.format=o,j.generateMipMaps=s,j.samplingMode=d,j.invertY=c,j._compression=_,j.type=b,this._doNotHandleContextLost||(j._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(j,i,e,void 0,k),this.updateRawTexture(j,a,o,c,_,b),this._internalTexturesCache.push(j),j};WebGPUEngine.prototype.updateRawTexture=function(a,i,e,o,s,c){if(s===void 0&&(s=null),c===void 0&&(c=0),!!a){if(this._doNotHandleContextLost||(a._bufferView=i,a.invertY=o,a._compression=s),i){var d=a._hardwareTexture,_=e===4;_&&(i=_convertRGBtoRGBATextureData(i,a.width,a.height,c));var b=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);this._textureHelper.updateTexture(b,a,a.width,a.height,a.depth,d.format,0,0,o,!1,0,0,this._uploadEncoder),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0}};WebGPUEngine.prototype.createRawCubeTexture=function(a,i,e,o,s,c,d,_){_===void 0&&(_=null);var b=new InternalTexture(this,InternalTextureSource.CubeRaw);return o===1&&!this._caps.textureFloatLinearFiltering?(s=!1,d=1,Logger$2.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):o===2&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,d=1,Logger$2.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):o===1&&!this._caps.textureFloatRender?(s=!1,Logger$2.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):o===2&&!this._caps.colorBufferFloat&&(s=!1,Logger$2.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")),b.isCube=!0,b.format=e===4?5:e,b.type=o,b.generateMipMaps=s,b.width=i,b.height=i,b.samplingMode=d,this._doNotHandleContextLost||(b._bufferViewArray=a),b._cachedWrapU=0,b._cachedWrapV=0,this._textureHelper.createGPUTextureForInternalTexture(b),a&&this.updateRawCubeTexture(b,a,e,o,c,_),b};WebGPUEngine.prototype.updateRawCubeTexture=function(a,i,e,o,s,c,d){c===void 0&&(c=null),a._bufferViewArray=i,a.invertY=s,a._compression=c;for(var _=a._hardwareTexture,b=e===4,k=[],j=0;j<i.length;++j){var $=i[j];b&&($=_convertRGBtoRGBATextureData(i[j],a.width,a.height,o)),k.push(new Uint8Array($.buffer,$.byteOffset,$.byteLength))}this._textureHelper.updateCubeTextures(k,_.underlyingResource,a.width,a.height,_.format,s,!1,0,0,this._uploadEncoder),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder),a.isReady=!0};WebGPUEngine.prototype.createRawCubeTextureFromUrl=function(a,i,e,o,s,c,d,_,b,k,j,$){var _e=this;b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=3),$===void 0&&($=!1);var et=this.createRawCubeTexture(null,e,o,s,!c,$,j,null);i==null||i._addPendingData(et),et.url=a,this._internalTexturesCache.push(et);var tt=function(it,nt){i==null||i._removePendingData(et),k&&it&&k(it.status+" "+it.statusText,nt)},rt=function(it){var nt=et.width,ot=d(it);if(!!ot){var at=[0,2,4,1,3,5];if(_)for(var st=o===4,ut=_(ot),ft=et._hardwareTexture,lt=[0,1,2,3,4,5],ht=0;ht<ut.length;ht++){for(var pt=nt>>ht,mt=[],dt=0;dt<6;dt++){var gt=ut[ht][lt[dt]];st&&(gt=_convertRGBtoRGBATextureData(gt,pt,pt,s)),mt.push(new Uint8Array(gt.buffer,gt.byteOffset,gt.byteLength))}_e._textureHelper.updateCubeTextures(mt,ft.underlyingResource,pt,pt,ft.format,$,!1,0,0,_e._uploadEncoder)}else{for(var mt=[],dt=0;dt<6;dt++)mt.push(ot[at[dt]]);_e.updateRawCubeTexture(et,mt,o,s,$)}et.isReady=!0,i==null||i._removePendingData(et),b&&b()}};return this._loadFile(a,function(it){rt(it)},void 0,i==null?void 0:i.offlineProvider,!0,tt),et};WebGPUEngine.prototype.createRawTexture3D=function(a,i,e,o,s,c,d,_,b,k,j){b===void 0&&(b=null),k===void 0&&(k=0),j===void 0&&(j=0);var $=InternalTextureSource.Raw3D,_e=new InternalTexture(this,$);return _e.baseWidth=i,_e.baseHeight=e,_e.baseDepth=o,_e.width=i,_e.height=e,_e.depth=o,_e.format=s,_e.type=k,_e.generateMipMaps=c,_e.samplingMode=_,_e.is3D=!0,this._doNotHandleContextLost||(_e._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(_e,i,e,void 0,j),this.updateRawTexture3D(_e,a,s,d,b,k),this._internalTexturesCache.push(_e),_e};WebGPUEngine.prototype.updateRawTexture3D=function(a,i,e,o,s,c){if(s===void 0&&(s=null),c===void 0&&(c=0),this._doNotHandleContextLost||(a._bufferView=i,a.format=e,a.invertY=o,a._compression=s),i){var d=a._hardwareTexture,_=e===4;_&&(i=_convertRGBtoRGBATextureData(i,a.width,a.height,c));var b=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);this._textureHelper.updateTexture(b,a,a.width,a.height,a.depth,d.format,0,0,o,!1,0,0,this._uploadEncoder),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};WebGPUEngine.prototype.createRawTexture2DArray=function(a,i,e,o,s,c,d,_,b,k,j){b===void 0&&(b=null),k===void 0&&(k=0),j===void 0&&(j=0);var $=InternalTextureSource.Raw2DArray,_e=new InternalTexture(this,$);return _e.baseWidth=i,_e.baseHeight=e,_e.baseDepth=o,_e.width=i,_e.height=e,_e.depth=o,_e.format=s,_e.type=k,_e.generateMipMaps=c,_e.samplingMode=_,_e.is2DArray=!0,this._doNotHandleContextLost||(_e._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(_e,i,e,o,j),this.updateRawTexture2DArray(_e,a,s,d,b,k),this._internalTexturesCache.push(_e),_e};WebGPUEngine.prototype.updateRawTexture2DArray=function(a,i,e,o,s,c){if(s===void 0&&(s=null),c===void 0&&(c=0),this._doNotHandleContextLost||(a._bufferView=i,a.format=e,a.invertY=o,a._compression=s),i){var d=a._hardwareTexture,_=e===4;_&&(i=_convertRGBtoRGBATextureData(i,a.width,a.height,c));var b=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);this._textureHelper.updateTexture(b,a,a.width,a.height,a.depth,d.format,0,0,o,!1,0,0,this._uploadEncoder),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};function _convertRGBtoRGBATextureData(a,i,e,o){var s,c=1;o===1?s=new Float32Array(i*e*4):o===2?(s=new Uint16Array(i*e*4),c=15360):o===7?s=new Uint32Array(i*e*4):s=new Uint8Array(i*e*4);for(var d=0;d<i;d++)for(var _=0;_<e;_++){var b=(_*i+d)*3,k=(_*i+d)*4;s[k+0]=a[b+0],s[k+1]=a[b+1],s[k+2]=a[b+2],s[k+3]=c}return s}WebGPUEngine.prototype._readTexturePixels=function(a,i,e,o,s,c,d,_){o===void 0&&(o=-1),s===void 0&&(s=0),c===void 0&&(c=null),d===void 0&&(d=!0),_===void 0&&(_=!1);var b=a._hardwareTexture;return d&&this.flushFramebuffer(),this._textureHelper.readPixels(b.underlyingResource,0,0,i,e,b.format,o,s,c,_)};WebGPUEngine.prototype._readTexturePixelsSync=function(a,i,e,o,s,c,d,_){throw"_readTexturePixelsSync is unsupported in WebGPU!"};WebGPUEngine.prototype._createHardwareRenderTargetWrapper=function(a,i,e){var o=new RenderTargetWrapper(a,i,e,this);return this._renderTargetWrapperCache.push(o),o};WebGPUEngine.prototype.createRenderTargetTexture=function(a,i){var e=this._createHardwareRenderTargetWrapper(!1,!1,a),o={};i!==void 0&&typeof i=="object"?(o.generateDepthBuffer=i.generateDepthBuffer===void 0?!0:i.generateDepthBuffer,o.generateStencilBuffer=o.generateDepthBuffer&&i.generateStencilBuffer):(o.generateDepthBuffer=!0,o.generateStencilBuffer=!1);var s=this._createInternalTexture(a,i,!0,InternalTextureSource.RenderTarget);return e._generateDepthBuffer=o.generateDepthBuffer,e._generateStencilBuffer=!!o.generateStencilBuffer,e.setTextures(s),(e._generateDepthBuffer||e._generateStencilBuffer)&&e.createDepthStencilTexture(0,o.samplingMode===void 0||o.samplingMode===2||o.samplingMode===2||o.samplingMode===3||o.samplingMode===3||o.samplingMode===5||o.samplingMode===6||o.samplingMode===7||o.samplingMode===11,e._generateStencilBuffer,e.samples),i!==void 0&&typeof i=="object"&&i.createMipMaps&&!o.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s,void 0,void 0,void 0,o.creationFlags),i!==void 0&&typeof i=="object"&&i.createMipMaps&&!o.generateMipMaps&&(s.generateMipMaps=!1),e};WebGPUEngine.prototype._createDepthStencilTexture=function(a,i,e){var o=new InternalTexture(this,InternalTextureSource.DepthStencil),s=__assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:15},i);return o.format=s.generateStencil?13:s.depthTextureFormat===15?14:s.depthTextureFormat,this._setupDepthStencilTexture(o,a,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(o),this._internalTexturesCache.push(o),o};WebGPUEngine.prototype._setupDepthStencilTexture=function(a,i,e,o,s,c){c===void 0&&(c=1);var d=i.width||i,_=i.height||i,b=i.layers||0;a.baseWidth=d,a.baseHeight=_,a.width=d,a.height=_,a.is2DArray=b>0,a.depth=b,a.isReady=!0,a.samples=c,a.generateMipMaps=!1,a.samplingMode=o?2:1,a.type=1,a._comparisonFunction=s,a._cachedWrapU=0,a._cachedWrapV=0};WebGPUEngine.prototype.updateRenderTargetTextureSampleCount=function(a,i){return!a||!a.texture||a.samples===i||(i=Math.min(i,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(a.texture,i),a._depthStencilTexture&&(this._textureHelper.createMSAATexture(a._depthStencilTexture,i),a._depthStencilTexture.samples=i),a.texture.samples=i),i};WebGPUEngine.prototype.createRenderTargetCubeTexture=function(a,i){var e=this._createHardwareRenderTargetWrapper(!1,!0,a),o=__assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},i);o.generateStencilBuffer=o.generateDepthBuffer&&o.generateStencilBuffer,e._generateDepthBuffer=o.generateDepthBuffer,e._generateStencilBuffer=o.generateStencilBuffer;var s=new InternalTexture(this,InternalTextureSource.RenderTarget);return s.width=a,s.height=a,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=o.samples,s.generateMipMaps=o.generateMipMaps,s.samplingMode=o.samplingMode,s.type=o.type,s.format=o.format,this._internalTexturesCache.push(s),e.setTextures(s),(e._generateDepthBuffer||e._generateStencilBuffer)&&e.createDepthStencilTexture(0,o.samplingMode===void 0||o.samplingMode===2||o.samplingMode===2||o.samplingMode===3||o.samplingMode===3||o.samplingMode===5||o.samplingMode===6||o.samplingMode===7||o.samplingMode===11,e._generateStencilBuffer,e.samples),i&&i.createMipMaps&&!o.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),i&&i.createMipMaps&&!o.generateMipMaps&&(s.generateMipMaps=!1),e};Effect$1.prototype.setTextureSampler=function(a,i){this._engine.setTextureSampler(a,i)};WebGPUEngine.prototype.setTextureSampler=function(a,i){var e;(e=this._currentMaterialContext)===null||e===void 0||e.setSampler(a,i)};Effect$1.prototype.setStorageBuffer=function(a,i){this._engine.setStorageBuffer(a,i)};WebGPUEngine.prototype.createStorageBuffer=function(a,i){return this._createBuffer(a,i|32)};WebGPUEngine.prototype.updateStorageBuffer=function(a,i,e,o){var s=a;e===void 0&&(e=0);var c;o===void 0?(i instanceof Array?c=new Float32Array(i):i instanceof ArrayBuffer?c=new Uint8Array(i):c=i,o=c.byteLength):i instanceof Array?c=new Float32Array(i):i instanceof ArrayBuffer?c=new Uint8Array(i):c=i,this._bufferManager.setSubData(s,e,c,0,o)};WebGPUEngine.prototype.readFromStorageBuffer=function(a,i,e,o){var s=this;e=e||a.capacity;var c=this._bufferManager.createRawBuffer(e,BufferUsage.MapRead|BufferUsage.CopyDst);return this._renderTargetEncoder.copyBufferToBuffer(a.underlyingResource,i!=null?i:0,c,0,e),new Promise(function(d,_){s.onEndFrameObservable.addOnce(function(){c.mapAsync(MapMode.Read,0,e).then(function(){var b=c.getMappedRange(0,e),k=o;if(k===void 0)k=new Uint8Array(e),k.set(new Uint8Array(b));else{var j=k.constructor;k=new j(k.buffer),k.set(new j(b))}c.unmap(),s._bufferManager.releaseBuffer(c),d(k)},function(b){return _(b)})})})};WebGPUEngine.prototype.setStorageBuffer=function(a,i){var e,o;(e=this._currentDrawContext)===null||e===void 0||e.setBuffer(a,(o=i==null?void 0:i.getBuffer())!==null&&o!==void 0?o:null)};WebGPUEngine.prototype.createUniformBuffer=function(a){var i;a instanceof Array?i=new Float32Array(a):i=a;var e=this._bufferManager.createBuffer(i,BufferUsage.Uniform|BufferUsage.CopyDst);return e};WebGPUEngine.prototype.createDynamicUniformBuffer=function(a){return this.createUniformBuffer(a)};WebGPUEngine.prototype.updateUniformBuffer=function(a,i,e,o){e===void 0&&(e=0);var s=a,c;o===void 0?(i instanceof Float32Array?c=i:c=new Float32Array(i),o=c.byteLength):i instanceof Float32Array?c=i:c=new Float32Array(i),this._bufferManager.setSubData(s,e,c,0,o)};WebGPUEngine.prototype.bindUniformBufferBase=function(a,i,e){this._currentDrawContext.setBuffer(e,a)};WebGPUEngine.prototype.bindUniformBlock=function(a,i,e){};WebGPUEngine.prototype.updateVideoTexture=function(a,i,e){var o=this,s;if(!(!a||a._isDisabled)){this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);var c=a._hardwareTexture;!((s=a._hardwareTexture)===null||s===void 0)&&s.underlyingResource||(c=this._textureHelper.createGPUTextureForInternalTexture(a)),this.createImageBitmap(i).then(function(d){o._textureHelper.updateTexture(d,a,a.width,a.height,a.depth,c.format,0,0,!e,!1,0,0,o._uploadEncoder),a.generateMipMaps&&o._generateMipmaps(a,o._uploadEncoder),a.isReady=!0}).catch(function(d){a.isReady=!0})}};var SceneLoaderFlags=function(){function a(){}return Object.defineProperty(a,"ForceFullSceneLoadingForIncremental",{get:function(){return a._ForceFullSceneLoadingForIncremental},set:function(i){a._ForceFullSceneLoadingForIncremental=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ShowLoadingScreen",{get:function(){return a._ShowLoadingScreen},set:function(i){a._ShowLoadingScreen=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"loggingLevel",{get:function(){return a._loggingLevel},set:function(i){a._loggingLevel=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"CleanBoneMatrixWeights",{get:function(){return a._CleanBoneMatrixWeights},set:function(i){a._CleanBoneMatrixWeights=i},enumerable:!1,configurable:!0}),a._ForceFullSceneLoadingForIncremental=!1,a._ShowLoadingScreen=!0,a._CleanBoneMatrixWeights=!1,a._loggingLevel=0,a}(),SceneLoaderAnimationGroupLoadingMode;(function(a){a[a.Clean=0]="Clean",a[a.Stop=1]="Stop",a[a.Sync=2]="Sync",a[a.NoSync=3]="NoSync"})(SceneLoaderAnimationGroupLoadingMode||(SceneLoaderAnimationGroupLoadingMode={}));var SceneLoader=function(){function a(){}return Object.defineProperty(a,"ForceFullSceneLoadingForIncremental",{get:function(){return SceneLoaderFlags.ForceFullSceneLoadingForIncremental},set:function(i){SceneLoaderFlags.ForceFullSceneLoadingForIncremental=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ShowLoadingScreen",{get:function(){return SceneLoaderFlags.ShowLoadingScreen},set:function(i){SceneLoaderFlags.ShowLoadingScreen=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"loggingLevel",{get:function(){return SceneLoaderFlags.loggingLevel},set:function(i){SceneLoaderFlags.loggingLevel=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"CleanBoneMatrixWeights",{get:function(){return SceneLoaderFlags.CleanBoneMatrixWeights},set:function(i){SceneLoaderFlags.CleanBoneMatrixWeights=i},enumerable:!1,configurable:!0}),a.GetDefaultPlugin=function(){return a._registeredPlugins[".babylon"]},a._GetPluginForExtension=function(i){var e=a._registeredPlugins[i];return e||(Logger$2.Warn("Unable to find a plugin to load "+i+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/how_to/load_from_any_file_type"),a.GetDefaultPlugin())},a._GetPluginForDirectLoad=function(i){for(var e in a._registeredPlugins){var o=a._registeredPlugins[e].plugin;if(o.canDirectLoad&&o.canDirectLoad(i))return a._registeredPlugins[e]}return a.GetDefaultPlugin()},a._GetPluginForFilename=function(i){var e=i.indexOf("?");e!==-1&&(i=i.substring(0,e));var o=i.lastIndexOf("."),s=i.substring(o,i.length).toLowerCase();return a._GetPluginForExtension(s)},a._GetDirectLoad=function(i){return i.substr(0,5)==="data:"?i.substr(5):null},a._FormatErrorMessage=function(i,e,o){var s="Unable to load from "+i.url;return e?s+=": "+e:o&&(s+=": "+o),s},a._LoadData=function(i,e,o,s,c,d,_){var b=a._GetDirectLoad(i.url),k=_?a._GetPluginForExtension(_):b?a._GetPluginForDirectLoad(i.url):a._GetPluginForFilename(i.url),j;if(k.plugin.createPlugin!==void 0?j=k.plugin.createPlugin():j=k.plugin,!j)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(a.OnPluginActivatedObservable.notifyObservers(j),b&&(j.canDirectLoad&&j.canDirectLoad(i.url)||!IsBase64DataUrl(i.url))){if(j.directLoad){var $=j.directLoad(e,b);$.then?$.then(function(ht){o(j,ht)}).catch(function(ht){c("Error in directLoad of _loadData: "+ht,ht)}):o(j,$)}else o(j,b);return j}var _e=k.isBinary,et=function(ht,pt){if(e.isDisposed){c("Scene has been disposed");return}o(j,ht,pt)},tt=null,rt=!1,it=j.onDisposeObservable;it&&it.add(function(){rt=!0,tt&&(tt.abort(),tt=null),d()});var nt=function(){if(!rt){var ht=function(mt,dt){c(mt==null?void 0:mt.statusText,dt)},pt=i.file||i.url;tt=j.loadFile?j.loadFile(e,pt,et,s,_e,ht):e._loadFile(pt,et,s,!0,_e,ht)}},ot=e.getEngine(),at=ot.enableOfflineSupport;if(at){for(var st=!1,ut=0,ft=e.disableOfflineSupportExceptionRules;ut<ft.length;ut++){var lt=ft[ut];if(lt.test(i.url)){st=!0;break}}at=!st}return at&&Engine.OfflineProviderFactory?e.offlineProvider=Engine.OfflineProviderFactory(i.url,nt,ot.disableManifestCheck):nt(),j},a._GetFileInfo=function(i,e){var o,s,c=null;if(!e)o=i,s=Tools.GetFilename(i),i=Tools.GetFolderPath(i);else if(e.name){var d=e;o="file:"+d.name,s=d.name,c=d}else if(typeof e=="string"&&StartsWith(e,"data:"))o=e,s="";else{var _=e;if(_.substr(0,1)==="/")return Tools.Error("Wrong sceneFilename parameter"),null;o=i+_,s=_}return{url:o,rootUrl:i,name:s,file:c}},a.GetPluginForExtension=function(i){return a._GetPluginForExtension(i).plugin},a.IsPluginForExtensionAvailable=function(i){return!!a._registeredPlugins[i]},a.RegisterPlugin=function(i){if(typeof i.extensions=="string"){var e=i.extensions;a._registeredPlugins[e.toLowerCase()]={plugin:i,isBinary:!1}}else{var o=i.extensions;Object.keys(o).forEach(function(s){a._registeredPlugins[s.toLowerCase()]={plugin:i,isBinary:o[s].isBinary}})}},a.ImportMesh=function(i,e,o,s,c,d,_,b){if(o===void 0&&(o=""),s===void 0&&(s=EngineStore.LastCreatedScene),c===void 0&&(c=null),d===void 0&&(d=null),_===void 0&&(_=null),b===void 0&&(b=null),!s)return Logger$2.Error("No scene available to import mesh to"),null;var k=a._GetFileInfo(e,o);if(!k)return null;var j={};s._addPendingData(j);var $=function(){s._removePendingData(j)},_e=function(rt,it){var nt=a._FormatErrorMessage(k,rt,it);_?_(s,nt,new Error(nt)):Logger$2.Error(nt),$()},et=d?function(rt){try{d(rt)}catch(it){_e("Error in onProgress callback: "+it,it)}}:void 0,tt=function(rt,it,nt,ot,at,st,ut){if(s.importedMeshesFiles.push(k.url),c)try{c(rt,it,nt,ot,at,st,ut)}catch(ft){_e("Error in onSuccess callback: "+ft,ft)}s._removePendingData(j)};return a._LoadData(k,s,function(rt,it,nt){if(rt.rewriteRootURL&&(k.rootUrl=rt.rewriteRootURL(k.rootUrl,nt)),rt.importMesh){var ot=rt,at=new Array,st=new Array,ut=new Array;if(!ot.importMesh(i,s,it,k.rootUrl,at,st,ut,_e))return;s.loadingPluginName=rt.name,tt(at,st,ut,[],[],[],[])}else{var ft=rt;ft.importMeshAsync(i,s,it,k.rootUrl,et,k.name).then(function(lt){s.loadingPluginName=rt.name,tt(lt.meshes,lt.particleSystems,lt.skeletons,lt.animationGroups,lt.transformNodes,lt.geometries,lt.lights)}).catch(function(lt){_e(lt.message,lt)})}},et,_e,$,b)},a.ImportMeshAsync=function(i,e,o,s,c,d){return o===void 0&&(o=""),s===void 0&&(s=EngineStore.LastCreatedScene),c===void 0&&(c=null),d===void 0&&(d=null),new Promise(function(_,b){a.ImportMesh(i,e,o,s,function(k,j,$,_e,et,tt,rt){_({meshes:k,particleSystems:j,skeletons:$,animationGroups:_e,transformNodes:et,geometries:tt,lights:rt})},c,function(k,j,$){b($||new Error(j))},d)})},a.Load=function(i,e,o,s,c,d,_){return e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedEngine),s===void 0&&(s=null),c===void 0&&(c=null),d===void 0&&(d=null),_===void 0&&(_=null),o?a.Append(i,e,new Scene(o),s,c,d,_):(Tools.Error("No engine available"),null)},a.LoadAsync=function(i,e,o,s,c){return e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedEngine),s===void 0&&(s=null),c===void 0&&(c=null),new Promise(function(d,_){a.Load(i,e,o,function(b){d(b)},s,function(b,k,j){_(j||new Error(k))},c)})},a.Append=function(i,e,o,s,c,d,_){var b=this;if(e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedScene),s===void 0&&(s=null),c===void 0&&(c=null),d===void 0&&(d=null),_===void 0&&(_=null),!o)return Logger$2.Error("No scene available to append to"),null;var k=a._GetFileInfo(i,e);if(!k)return null;a.ShowLoadingScreen&&!this._showingLoadingScreen&&(this._showingLoadingScreen=!0,o.getEngine().displayLoadingUI(),o.executeWhenReady(function(){o.getEngine().hideLoadingUI(),b._showingLoadingScreen=!1}));var j={};o._addPendingData(j);var $=function(){o._removePendingData(j)},_e=function(rt,it){var nt=a._FormatErrorMessage(k,rt,it);d?d(o,nt,new Error(nt)):Logger$2.Error(nt),$()},et=c?function(rt){try{c(rt)}catch(it){_e("Error in onProgress callback",it)}}:void 0,tt=function(){if(s)try{s(o)}catch(rt){_e("Error in onSuccess callback",rt)}o._removePendingData(j)};return a._LoadData(k,o,function(rt,it){if(rt.load){var nt=rt;if(!nt.load(o,it,k.rootUrl,_e))return;o.loadingPluginName=rt.name,tt()}else{var ot=rt;ot.loadAsync(o,it,k.rootUrl,et,k.name).then(function(){o.loadingPluginName=rt.name,tt()}).catch(function(at){_e(at.message,at)})}},et,_e,$,_)},a.AppendAsync=function(i,e,o,s,c){return e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedScene),s===void 0&&(s=null),c===void 0&&(c=null),new Promise(function(d,_){a.Append(i,e,o,function(b){d(b)},s,function(b,k,j){_(j||new Error(k))},c)})},a.LoadAssetContainer=function(i,e,o,s,c,d,_){if(e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedScene),s===void 0&&(s=null),c===void 0&&(c=null),d===void 0&&(d=null),_===void 0&&(_=null),!o)return Logger$2.Error("No scene available to load asset container to"),null;var b=a._GetFileInfo(i,e);if(!b)return null;var k={};o._addPendingData(k);var j=function(){o._removePendingData(k)},$=function(tt,rt){var it=a._FormatErrorMessage(b,tt,rt);d?d(o,it,new Error(it)):Logger$2.Error(it),j()},_e=c?function(tt){try{c(tt)}catch(rt){$("Error in onProgress callback",rt)}}:void 0,et=function(tt){if(s)try{s(tt)}catch(rt){$("Error in onSuccess callback",rt)}o._removePendingData(k)};return a._LoadData(b,o,function(tt,rt){if(tt.loadAssetContainer){var it=tt,nt=it.loadAssetContainer(o,rt,b.rootUrl,$);if(!nt)return;o.loadingPluginName=tt.name,et(nt)}else if(tt.loadAssetContainerAsync){var ot=tt;ot.loadAssetContainerAsync(o,rt,b.rootUrl,_e,b.name).then(function(at){o.loadingPluginName=tt.name,et(at)}).catch(function(at){$(at.message,at)})}else $("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},_e,$,j,_)},a.LoadAssetContainerAsync=function(i,e,o,s,c){return e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedScene),s===void 0&&(s=null),c===void 0&&(c=null),new Promise(function(d,_){a.LoadAssetContainer(i,e,o,function(b){d(b)},s,function(b,k,j){_(j||new Error(k))},c)})},a.ImportAnimations=function(i,e,o,s,c,d,_,b,k,j){if(e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedScene),s===void 0&&(s=!0),c===void 0&&(c=SceneLoaderAnimationGroupLoadingMode.Clean),d===void 0&&(d=null),_===void 0&&(_=null),b===void 0&&(b=null),k===void 0&&(k=null),j===void 0&&(j=null),!o){Logger$2.Error("No scene available to load animations to");return}if(s){for(var $=0,_e=o.animatables;$<_e.length;$++){var et=_e[$];et.reset()}o.stopAllAnimations(),o.animationGroups.slice().forEach(function(nt){nt.dispose()});var tt=o.getNodes();tt.forEach(function(nt){nt.animations&&(nt.animations=[])})}else switch(c){case SceneLoaderAnimationGroupLoadingMode.Clean:o.animationGroups.slice().forEach(function(nt){nt.dispose()});break;case SceneLoaderAnimationGroupLoadingMode.Stop:o.animationGroups.forEach(function(nt){nt.stop()});break;case SceneLoaderAnimationGroupLoadingMode.Sync:o.animationGroups.forEach(function(nt){nt.reset(),nt.restart()});break;case SceneLoaderAnimationGroupLoadingMode.NoSync:break;default:Logger$2.Error("Unknown animation group loading mode value '"+c+"'");return}var rt=o.animatables.length,it=function(nt){nt.mergeAnimationsTo(o,o.animatables.slice(rt),d),nt.dispose(),o.onAnimationFileImportedObservable.notifyObservers(o),_&&_(o)};this.LoadAssetContainer(i,e,o,it,b,k,j)},a.ImportAnimationsAsync=function(i,e,o,s,c,d,_,b,k,j){return e===void 0&&(e=""),o===void 0&&(o=EngineStore.LastCreatedScene),s===void 0&&(s=!0),c===void 0&&(c=SceneLoaderAnimationGroupLoadingMode.Clean),d===void 0&&(d=null),b===void 0&&(b=null),j===void 0&&(j=null),new Promise(function($,_e){a.ImportAnimations(i,e,o,s,c,d,function(et){$(et)},b,function(et,tt,rt){_e(rt||new Error(tt))},j)})},a.NO_LOGGING=0,a.MINIMAL_LOGGING=1,a.SUMMARY_LOGGING=2,a.DETAILED_LOGGING=3,a.OnPluginActivatedObservable=new Observable,a._registeredPlugins={},a._showingLoadingScreen=!1,a}(),AnimationKeyInterpolation;(function(a){a[a.NONE=0]="NONE",a[a.STEP=1]="STEP"})(AnimationKeyInterpolation||(AnimationKeyInterpolation={}));var AnimationRange=function(){function a(i,e,o){this.name=i,this.from=e,this.to=o}return a.prototype.clone=function(){return new a(this.name,this.from,this.to)},a}(),Animation=function(){function a(i,e,o,s,c,d){this.name=i,this.targetProperty=e,this.framePerSecond=o,this.dataType=s,this.loopMode=c,this.enableBlending=d,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=e.split("."),this.dataType=s,this.loopMode=c===void 0?a.ANIMATIONLOOPMODE_CYCLE:c,this.uniqueId=a._UniqueIdGenerator++}return a._PrepareAnimation=function(i,e,o,s,c,d,_,b){var k=void 0;if(!isNaN(parseFloat(c))&&isFinite(c)?k=a.ANIMATIONTYPE_FLOAT:c instanceof Quaternion?k=a.ANIMATIONTYPE_QUATERNION:c instanceof Vector3?k=a.ANIMATIONTYPE_VECTOR3:c instanceof Vector2?k=a.ANIMATIONTYPE_VECTOR2:c instanceof Color3?k=a.ANIMATIONTYPE_COLOR3:c instanceof Color4?k=a.ANIMATIONTYPE_COLOR4:c instanceof Size&&(k=a.ANIMATIONTYPE_SIZE),k==null)return null;var j=new a(i,e,o,k,_),$=[{frame:0,value:c},{frame:s,value:d}];return j.setKeys($),b!==void 0&&j.setEasingFunction(b),j},a.CreateAnimation=function(i,e,o,s){var c=new a(i+"Animation",i,o,e,a.ANIMATIONLOOPMODE_CONSTANT);return c.setEasingFunction(s),c},a.CreateAndStartAnimation=function(i,e,o,s,c,d,_,b,k,j,$){var _e=a._PrepareAnimation(i,o,s,c,d,_,b,k);return!_e||(e.getScene&&($=e.getScene()),!$)?null:$.beginDirectAnimation(e,[_e],0,c,_e.loopMode===1,1,j)},a.CreateAndStartHierarchyAnimation=function(i,e,o,s,c,d,_,b,k,j,$){var _e=a._PrepareAnimation(i,s,c,d,_,b,k,j);if(!_e)return null;var et=e.getScene();return et.beginDirectHierarchyAnimation(e,o,[_e],0,d,_e.loopMode===1,1,$)},a.CreateMergeAndStartAnimation=function(i,e,o,s,c,d,_,b,k,j){var $=a._PrepareAnimation(i,o,s,c,d,_,b,k);return $?(e.animations.push($),e.getScene().beginAnimation(e,0,c,$.loopMode===1,1,j)):null},a.MakeAnimationAdditive=function(i,e,o,s,c){e===void 0&&(e=0),s===void 0&&(s=!1);var d=i;if(s&&(d=i.clone(),d.name=c||d.name),!d._keys.length)return d;e=e>=0?e:0;var _=0,b=d._keys[0],k=d._keys.length-1,j=d._keys[k],$={referenceValue:b.value,referencePosition:TmpVectors.Vector3[0],referenceQuaternion:TmpVectors.Quaternion[0],referenceScaling:TmpVectors.Vector3[1],keyPosition:TmpVectors.Vector3[2],keyQuaternion:TmpVectors.Quaternion[1],keyScaling:TmpVectors.Vector3[3]},_e=!1,et=b.frame,tt=j.frame;if(o){var rt=d.getRange(o);rt&&(et=rt.from,tt=rt.to)}var it=b.frame===et,nt=j.frame===tt;if(d._keys.length===1){var ot=d._getKeyValue(d._keys[0]);$.referenceValue=ot.clone?ot.clone():ot,_e=!0}else if(e<=b.frame){var ot=d._getKeyValue(b.value);$.referenceValue=ot.clone?ot.clone():ot,_e=!0}else if(e>=j.frame){var ot=d._getKeyValue(j.value);$.referenceValue=ot.clone?ot.clone():ot,_e=!0}for(var at=0;!_e||!it||!nt&&at<d._keys.length-1;){var st=d._keys[at],ut=d._keys[at+1];if(!_e&&e>=st.frame&&e<=ut.frame){var ot=void 0;if(e===st.frame)ot=d._getKeyValue(st.value);else if(e===ut.frame)ot=d._getKeyValue(ut.value);else{var ft={key:at,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};ot=d._interpolate(e,ft)}$.referenceValue=ot.clone?ot.clone():ot,_e=!0}if(!it&&et>=st.frame&&et<=ut.frame){if(et===st.frame)_=at;else if(et===ut.frame)_=at+1;else{var ft={key:at,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},ot=d._interpolate(et,ft),lt={frame:et,value:ot.clone?ot.clone():ot};d._keys.splice(at+1,0,lt),_=at+1}it=!0}if(!nt&&tt>=st.frame&&tt<=ut.frame){if(tt===st.frame)k=at;else if(tt===ut.frame)k=at+1;else{var ft={key:at,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},ot=d._interpolate(tt,ft),lt={frame:tt,value:ot.clone?ot.clone():ot};d._keys.splice(at+1,0,lt),k=at+1}nt=!0}at++}d.dataType===a.ANIMATIONTYPE_QUATERNION?$.referenceValue.normalize().conjugateInPlace():d.dataType===a.ANIMATIONTYPE_MATRIX&&($.referenceValue.decompose($.referenceScaling,$.referenceQuaternion,$.referencePosition),$.referenceQuaternion.normalize().conjugateInPlace());for(var at=_;at<=k;at++){var lt=d._keys[at];if(!(at&&d.dataType!==a.ANIMATIONTYPE_FLOAT&&lt.value===b.value))switch(d.dataType){case a.ANIMATIONTYPE_MATRIX:lt.value.decompose($.keyScaling,$.keyQuaternion,$.keyPosition),$.keyPosition.subtractInPlace($.referencePosition),$.keyScaling.divideInPlace($.referenceScaling),$.referenceQuaternion.multiplyToRef($.keyQuaternion,$.keyQuaternion),Matrix.ComposeToRef($.keyScaling,$.keyQuaternion,$.keyPosition,lt.value);break;case a.ANIMATIONTYPE_QUATERNION:$.referenceValue.multiplyToRef(lt.value,lt.value);break;case a.ANIMATIONTYPE_VECTOR2:case a.ANIMATIONTYPE_VECTOR3:case a.ANIMATIONTYPE_COLOR3:case a.ANIMATIONTYPE_COLOR4:lt.value.subtractToRef($.referenceValue,lt.value);break;case a.ANIMATIONTYPE_SIZE:lt.value.width-=$.referenceValue.width,lt.value.height-=$.referenceValue.height;break;default:lt.value-=$.referenceValue}}return d},a.TransitionTo=function(i,e,o,s,c,d,_,b){if(b===void 0&&(b=null),_<=0)return o[i]=e,b&&b(),null;var k=c*(_/1e3);d.setKeys([{frame:0,value:o[i].clone?o[i].clone():o[i]},{frame:k,value:e}]),o.animations||(o.animations=[]),o.animations.push(d);var j=s.beginAnimation(o,0,k,!1);return j.onAnimationEnd=b,j},Object.defineProperty(a.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var i=0,e=this._runtimeAnimations;i<e.length;i++){var o=e[i];if(!o.isStopped())return!0}return!1},enumerable:!1,configurable:!0}),a.prototype.toString=function(i){var e="Name: "+this.name+", property: "+this.targetProperty;if(e+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],e+=", nKeys: "+(this._keys?this._keys.length:"none"),e+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),i){e+=", Ranges: {";var o=!0;for(var s in this._ranges)o&&(e+=", ",o=!1),e+=s;e+="}"}return e},a.prototype.addEvent=function(i){this._events.push(i),this._events.sort(function(e,o){return e.frame-o.frame})},a.prototype.removeEvents=function(i){for(var e=0;e<this._events.length;e++)this._events[e].frame===i&&(this._events.splice(e,1),e--)},a.prototype.getEvents=function(){return this._events},a.prototype.createRange=function(i,e,o){this._ranges[i]||(this._ranges[i]=new AnimationRange(i,e,o))},a.prototype.deleteRange=function(i,e){e===void 0&&(e=!0);var o=this._ranges[i];if(!!o){if(e)for(var s=o.from,c=o.to,d=this._keys.length-1;d>=0;d--)this._keys[d].frame>=s&&this._keys[d].frame<=c&&this._keys.splice(d,1);this._ranges[i]=null}},a.prototype.getRange=function(i){return this._ranges[i]},a.prototype.getKeys=function(){return this._keys},a.prototype.getHighestFrame=function(){for(var i=0,e=0,o=this._keys.length;e<o;e++)i<this._keys[e].frame&&(i=this._keys[e].frame);return i},a.prototype.getEasingFunction=function(){return this._easingFunction},a.prototype.setEasingFunction=function(i){this._easingFunction=i},a.prototype.floatInterpolateFunction=function(i,e,o){return Scalar.Lerp(i,e,o)},a.prototype.floatInterpolateFunctionWithTangents=function(i,e,o,s,c){return Scalar.Hermite(i,e,o,s,c)},a.prototype.quaternionInterpolateFunction=function(i,e,o){return Quaternion.Slerp(i,e,o)},a.prototype.quaternionInterpolateFunctionWithTangents=function(i,e,o,s,c){return Quaternion.Hermite(i,e,o,s,c).normalize()},a.prototype.vector3InterpolateFunction=function(i,e,o){return Vector3.Lerp(i,e,o)},a.prototype.vector3InterpolateFunctionWithTangents=function(i,e,o,s,c){return Vector3.Hermite(i,e,o,s,c)},a.prototype.vector2InterpolateFunction=function(i,e,o){return Vector2.Lerp(i,e,o)},a.prototype.vector2InterpolateFunctionWithTangents=function(i,e,o,s,c){return Vector2.Hermite(i,e,o,s,c)},a.prototype.sizeInterpolateFunction=function(i,e,o){return Size.Lerp(i,e,o)},a.prototype.color3InterpolateFunction=function(i,e,o){return Color3.Lerp(i,e,o)},a.prototype.color3InterpolateFunctionWithTangents=function(i,e,o,s,c){return Color3.Hermite(i,e,o,s,c)},a.prototype.color4InterpolateFunction=function(i,e,o){return Color4.Lerp(i,e,o)},a.prototype.color4InterpolateFunctionWithTangents=function(i,e,o,s,c){return Color4.Hermite(i,e,o,s,c)},a.prototype._getKeyValue=function(i){return typeof i=="function"?i():i},a.prototype.evaluate=function(i){return this._interpolate(i,{key:0,repeatCount:0,loopMode:a.ANIMATIONLOOPMODE_CONSTANT})},a.prototype._interpolate=function(i,e){if(e.loopMode===a.ANIMATIONLOOPMODE_CONSTANT&&e.repeatCount>0)return e.highLimitValue.clone?e.highLimitValue.clone():e.highLimitValue;var o=this._keys;if(o.length===1)return this._getKeyValue(o[0].value);var s=e.key;if(o[s].frame>=i)for(;s-1>=0&&o[s].frame>=i;)s--;for(var c=s;c<o.length-1;c++){var d=o[c+1];if(d.frame>=i){e.key=c;var _=o[c],b=this._getKeyValue(_.value),k=this._getKeyValue(d.value);if(_.interpolation===AnimationKeyInterpolation.STEP)return d.frame>i?b:k;var j=_.outTangent!==void 0&&d.inTangent!==void 0,$=d.frame-_.frame,_e=(i-_.frame)/$,et=this.getEasingFunction();switch(et!=null&&(_e=et.ease(_e)),this.dataType){case a.ANIMATIONTYPE_FLOAT:var tt=j?this.floatInterpolateFunctionWithTangents(b,_.outTangent*$,k,d.inTangent*$,_e):this.floatInterpolateFunction(b,k,_e);switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:return tt;case a.ANIMATIONLOOPMODE_RELATIVE:return e.offsetValue*e.repeatCount+tt}break;case a.ANIMATIONTYPE_QUATERNION:var rt=j?this.quaternionInterpolateFunctionWithTangents(b,_.outTangent.scale($),k,d.inTangent.scale($),_e):this.quaternionInterpolateFunction(b,k,_e);switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:return rt;case a.ANIMATIONLOOPMODE_RELATIVE:return rt.addInPlace(e.offsetValue.scale(e.repeatCount))}return rt;case a.ANIMATIONTYPE_VECTOR3:var it=j?this.vector3InterpolateFunctionWithTangents(b,_.outTangent.scale($),k,d.inTangent.scale($),_e):this.vector3InterpolateFunction(b,k,_e);switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:return it;case a.ANIMATIONLOOPMODE_RELATIVE:return it.add(e.offsetValue.scale(e.repeatCount))}case a.ANIMATIONTYPE_VECTOR2:var nt=j?this.vector2InterpolateFunctionWithTangents(b,_.outTangent.scale($),k,d.inTangent.scale($),_e):this.vector2InterpolateFunction(b,k,_e);switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:return nt;case a.ANIMATIONLOOPMODE_RELATIVE:return nt.add(e.offsetValue.scale(e.repeatCount))}case a.ANIMATIONTYPE_SIZE:switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(b,k,_e);case a.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(b,k,_e).add(e.offsetValue.scale(e.repeatCount))}case a.ANIMATIONTYPE_COLOR3:var ot=j?this.color3InterpolateFunctionWithTangents(b,_.outTangent.scale($),k,d.inTangent.scale($),_e):this.color3InterpolateFunction(b,k,_e);switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:return ot;case a.ANIMATIONLOOPMODE_RELATIVE:return ot.add(e.offsetValue.scale(e.repeatCount))}case a.ANIMATIONTYPE_COLOR4:var at=j?this.color4InterpolateFunctionWithTangents(b,_.outTangent.scale($),k,d.inTangent.scale($),_e):this.color4InterpolateFunction(b,k,_e);switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:return at;case a.ANIMATIONLOOPMODE_RELATIVE:return at.add(e.offsetValue.scale(e.repeatCount))}case a.ANIMATIONTYPE_MATRIX:switch(e.loopMode){case a.ANIMATIONLOOPMODE_CYCLE:case a.ANIMATIONLOOPMODE_CONSTANT:if(a.AllowMatricesInterpolation)return this.matrixInterpolateFunction(b,k,_e,e.workValue);case a.ANIMATIONLOOPMODE_RELATIVE:return b}}break}}return this._getKeyValue(o[o.length-1].value)},a.prototype.matrixInterpolateFunction=function(i,e,o,s){return a.AllowMatrixDecomposeForInterpolation?s?(Matrix.DecomposeLerpToRef(i,e,o,s),s):Matrix.DecomposeLerp(i,e,o):s?(Matrix.LerpToRef(i,e,o,s),s):Matrix.Lerp(i,e,o)},a.prototype.clone=function(){var i=new a(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(i.enableBlending=this.enableBlending,i.blendingSpeed=this.blendingSpeed,this._keys&&i.setKeys(this._keys),this._ranges){i._ranges={};for(var e in this._ranges){var o=this._ranges[e];!o||(i._ranges[e]=o.clone())}}return i},a.prototype.setKeys=function(i){this._keys=i.slice(0)},a.prototype.serialize=function(){var i={};i.name=this.name,i.property=this.targetProperty,i.framePerSecond=this.framePerSecond,i.dataType=this.dataType,i.loopBehavior=this.loopMode,i.enableBlending=this.enableBlending,i.blendingSpeed=this.blendingSpeed;var e=this.dataType;i.keys=[];for(var o=this.getKeys(),s=0;s<o.length;s++){var c=o[s],d={};switch(d.frame=c.frame,e){case a.ANIMATIONTYPE_FLOAT:d.values=[c.value],c.inTangent!==void 0&&d.values.push(c.inTangent),c.outTangent!==void 0&&(c.inTangent===void 0&&d.values.push(void 0),d.values.push(c.outTangent));break;case a.ANIMATIONTYPE_QUATERNION:case a.ANIMATIONTYPE_MATRIX:case a.ANIMATIONTYPE_VECTOR3:case a.ANIMATIONTYPE_COLOR3:case a.ANIMATIONTYPE_COLOR4:d.values=c.value.asArray(),c.inTangent!=null&&d.values.push(c.inTangent.asArray()),c.outTangent!=null&&(c.inTangent===void 0&&d.values.push(void 0),d.values.push(c.outTangent.asArray()));break}i.keys.push(d)}i.ranges=[];for(var _ in this._ranges){var b=this._ranges[_];if(!!b){var k={};k.name=_,k.from=b.from,k.to=b.to,i.ranges.push(k)}}return i},a._UniversalLerp=function(i,e,o){var s=i.constructor;return s.Lerp?s.Lerp(i,e,o):s.Slerp?s.Slerp(i,e,o):i.toFixed?i*(1-o)+o*e:e},a.Parse=function(i){var e=new a(i.name,i.property,i.framePerSecond,i.dataType,i.loopBehavior),o=i.dataType,s=[],c,d;for(i.enableBlending&&(e.enableBlending=i.enableBlending),i.blendingSpeed&&(e.blendingSpeed=i.blendingSpeed),d=0;d<i.keys.length;d++){var _=i.keys[d],b=void 0,k=void 0;switch(o){case a.ANIMATIONTYPE_FLOAT:c=_.values[0],_.values.length>=1&&(b=_.values[1]),_.values.length>=2&&(k=_.values[2]);break;case a.ANIMATIONTYPE_QUATERNION:if(c=Quaternion.FromArray(_.values),_.values.length>=8){var j=Quaternion.FromArray(_.values.slice(4,8));j.equals(Quaternion.Zero())||(b=j)}if(_.values.length>=12){var $=Quaternion.FromArray(_.values.slice(8,12));$.equals(Quaternion.Zero())||(k=$)}break;case a.ANIMATIONTYPE_MATRIX:c=Matrix.FromArray(_.values);break;case a.ANIMATIONTYPE_COLOR3:c=Color3.FromArray(_.values),_.values[3]&&(b=Color3.FromArray(_.values[3])),_.values[4]&&(k=Color3.FromArray(_.values[4]));break;case a.ANIMATIONTYPE_COLOR4:c=Color4.FromArray(_.values),_.values[4]&&(b=Color4.FromArray(_.values[4])),_.values[5]&&(k=Color4.FromArray(_.values[5]));break;case a.ANIMATIONTYPE_VECTOR3:default:c=Vector3.FromArray(_.values),_.values[3]&&(b=Vector3.FromArray(_.values[3])),_.values[4]&&(k=Vector3.FromArray(_.values[4]));break}var _e={};_e.frame=_.frame,_e.value=c,b!=null&&(_e.inTangent=b),k!=null&&(_e.outTangent=k),s.push(_e)}if(e.setKeys(s),i.ranges)for(d=0;d<i.ranges.length;d++)c=i.ranges[d],e.createRange(c.name,c.from,c.to);return e},a.AppendSerializedAnimations=function(i,e){SerializationHelper.AppendSerializedAnimations(i,e)},a.ParseFromFileAsync=function(i,e){var o=this;return new Promise(function(s,c){var d=new WebRequest;d.addEventListener("readystatechange",function(){if(d.readyState==4)if(d.status==200){var _=JSON.parse(d.responseText);if(_.length){for(var b=new Array,k=0,j=_;k<j.length;k++){var $=j[k];b.push(o.Parse($))}s(b)}else{var b=o.Parse(_);i&&(b.name=i),s(b)}}else c("Unable to load the animation")}),d.open("GET",e),d.send()})},a.CreateFromSnippetAsync=function(i){var e=this;return new Promise(function(o,s){var c=new WebRequest;c.addEventListener("readystatechange",function(){if(c.readyState==4)if(c.status==200){var d=JSON.parse(JSON.parse(c.responseText).jsonPayload);if(d.animations){for(var _=JSON.parse(d.animations),b=new Array,k=0,j=_.animations;k<j.length;k++){var $=j[k],_e=e.Parse($);_e.snippetId=i,b.push(_e)}o(b)}else{var _=JSON.parse(d.animation),_e=e.Parse(_);_e.snippetId=i,o(_e)}}else s("Unable to load the snippet "+i)}),c.open("GET",e.SnippetUrl+"/"+i.replace(/#/g,"/")),c.send()})},a._UniqueIdGenerator=0,a.AllowMatricesInterpolation=!1,a.AllowMatrixDecomposeForInterpolation=!0,a.SnippetUrl="https://snippet.babylonjs.com",a.ANIMATIONTYPE_FLOAT=0,a.ANIMATIONTYPE_VECTOR3=1,a.ANIMATIONTYPE_QUATERNION=2,a.ANIMATIONTYPE_MATRIX=3,a.ANIMATIONTYPE_COLOR3=4,a.ANIMATIONTYPE_COLOR4=7,a.ANIMATIONTYPE_VECTOR2=5,a.ANIMATIONTYPE_SIZE=6,a.ANIMATIONLOOPMODE_RELATIVE=0,a.ANIMATIONLOOPMODE_CYCLE=1,a.ANIMATIONLOOPMODE_CONSTANT=2,a}();RegisterClass("BABYLON.Animation",Animation);Node$2._AnimationRangeFactory=function(a,i,e){return new AnimationRange(a,i,e)};var _staticOffsetValueQuaternion=Object.freeze(new Quaternion(0,0,0,0)),_staticOffsetValueVector3=Object.freeze(Vector3.Zero()),_staticOffsetValueVector2=Object.freeze(Vector2.Zero()),_staticOffsetValueSize=Object.freeze(Size.Zero()),_staticOffsetValueColor3=Object.freeze(Color3.Black()),RuntimeAnimation=function(){function a(i,e,o,s){var c=this;if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._targetIsArray=!1,this._animation=e,this._target=i,this._scene=o,this._host=s,this._activeTargets=[],e._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Animation.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=Matrix.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,this._minFrame!==0){var d={frame:0,value:this._minValue};this._keys.splice(0,0,d)}if(this._target instanceof Array){for(var _=0,b=0,k=this._target;b<k.length;b++){var j=k[b];this._preparePath(j,_),this._getOriginalValues(_),_++}this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];var $=e.getEvents();$&&$.length>0&&$.forEach(function(_e){c._events.push(_e._clone())}),this._enableBlending=i&&i.animationPropertiesOverride?i.animationPropertiesOverride.enableBlending:this._animation.enableBlending}return Object.defineProperty(a.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"weight",{get:function(){return this._weight},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"target",{get:function(){return this._currentActiveTarget},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isAdditive",{get:function(){return this._host&&this._host.isAdditive},enumerable:!1,configurable:!0}),a.prototype._preparePath=function(i,e){e===void 0&&(e=0);var o=this._animation.targetPropertyPath;if(o.length>1){for(var s=i[o[0]],c=1;c<o.length-1;c++)s=s[o[c]];this._targetPath=o[o.length-1],this._activeTargets[e]=s}else this._targetPath=o[0],this._activeTargets[e]=i},Object.defineProperty(a.prototype,"animation",{get:function(){return this._animation},enumerable:!1,configurable:!0}),a.prototype.reset=function(i){if(i===void 0&&(i=!1),i)if(this._target instanceof Array)for(var e=0,o=0,s=this._target;o<s.length;o++){var c=s[o];this._originalValue[e]!==void 0&&this._setValue(c,this._activeTargets[e],this._originalValue[e],-1,e),e++}else this._originalValue[0]!==void 0&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(var e=0;e<this._events.length;e++)this._events[e].isDone=!1},a.prototype.isStopped=function(){return this._stopped},a.prototype.dispose=function(){var i=this._animation.runtimeAnimations.indexOf(this);i>-1&&this._animation.runtimeAnimations.splice(i,1)},a.prototype.setValue=function(i,e){if(this._targetIsArray){for(var o=0;o<this._target.length;o++){var s=this._target[o];this._setValue(s,this._activeTargets[o],i,e,o)}return}this._setValue(this._target,this._directTarget,i,e,0)},a.prototype._getOriginalValues=function(i){i===void 0&&(i=0);var e,o=this._activeTargets[i];o.getRestPose&&this._targetPath==="_matrix"?e=o.getRestPose():e=o[this._targetPath],e&&e.clone?this._originalValue[i]=e.clone():this._originalValue[i]=e},a.prototype._setValue=function(i,e,o,s,c){if(this._currentActiveTarget=e,this._weight=s,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){var d=e[this._targetPath];d.clone?this._originalBlendValue=d.clone():this._originalBlendValue=d}this._originalBlendValue.m?Animation.AllowMatrixDecomposeForInterpolation?this._currentValue?Matrix.DecomposeLerpToRef(this._originalBlendValue,o,this._blendingFactor,this._currentValue):this._currentValue=Matrix.DecomposeLerp(this._originalBlendValue,o,this._blendingFactor):this._currentValue?Matrix.LerpToRef(this._originalBlendValue,o,this._blendingFactor,this._currentValue):this._currentValue=Matrix.Lerp(this._originalBlendValue,o,this._blendingFactor):this._currentValue=Animation._UniversalLerp(this._originalBlendValue,o,this._blendingFactor);var _=i&&i.animationPropertiesOverride?i.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=_}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(o):this._currentValue=o:o!=null&&o.clone?this._currentValue=o.clone():this._currentValue=o;s!==-1?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[c]):e[this._targetPath]=this._currentValue,i.markAsDirty&&i.markAsDirty(this._animation.targetProperty)},a.prototype._getCorrectLoopMode=function(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode},a.prototype.goToFrame=function(i){var e=this._animation.getKeys();i<e[0].frame?i=e[0].frame:i>e[e.length-1].frame&&(i=e[e.length-1].frame);var o=this._events;if(o.length)for(var s=0;s<o.length;s++)o[s].onlyOnce||(o[s].isDone=o[s].frame<i);this._currentFrame=i;var c=this._animation._interpolate(i,this._animationState);this.setValue(c,-1)},a.prototype._prepareForSpeedRatioChange=function(i){var e=this._previousDelay*(this._animation.framePerSecond*i)/1e3;this._ratioOffset=this._previousRatio-e},a.prototype.animate=function(i,e,o,s,c,d){d===void 0&&(d=-1);var _=this._animation,b=_.targetPropertyPath;if(!b||b.length<1)return this._stopped=!0,!1;var k=!0;(e<this._minFrame||e>this._maxFrame)&&(e=this._minFrame),(o<this._minFrame||o>this._maxFrame)&&(o=this._maxFrame);var j=o-e,$,_e=i*(_.framePerSecond*c)/1e3+this._ratioOffset,et=0;if(this._previousDelay=i,this._previousRatio=_e,!s&&o>=e&&_e>=j)k=!1,et=_._getKeyValue(this._maxValue);else if(!s&&e>=o&&_e<=j)k=!1,et=_._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Animation.ANIMATIONLOOPMODE_CYCLE){var tt=o.toString()+e.toString();if(!this._offsetsCache[tt]){this._animationState.repeatCount=0,this._animationState.loopMode=Animation.ANIMATIONLOOPMODE_CYCLE;var rt=_._interpolate(e,this._animationState),it=_._interpolate(o,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),_.dataType){case Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[tt]=it-rt;break;case Animation.ANIMATIONTYPE_QUATERNION:this._offsetsCache[tt]=it.subtract(rt);break;case Animation.ANIMATIONTYPE_VECTOR3:this._offsetsCache[tt]=it.subtract(rt);break;case Animation.ANIMATIONTYPE_VECTOR2:this._offsetsCache[tt]=it.subtract(rt);break;case Animation.ANIMATIONTYPE_SIZE:this._offsetsCache[tt]=it.subtract(rt);break;case Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[tt]=it.subtract(rt);break}this._highLimitsCache[tt]=it}et=this._highLimitsCache[tt],$=this._offsetsCache[tt]}if($===void 0)switch(_.dataType){case Animation.ANIMATIONTYPE_FLOAT:$=0;break;case Animation.ANIMATIONTYPE_QUATERNION:$=_staticOffsetValueQuaternion;break;case Animation.ANIMATIONTYPE_VECTOR3:$=_staticOffsetValueVector3;break;case Animation.ANIMATIONTYPE_VECTOR2:$=_staticOffsetValueVector2;break;case Animation.ANIMATIONTYPE_SIZE:$=_staticOffsetValueSize;break;case Animation.ANIMATIONTYPE_COLOR3:$=_staticOffsetValueColor3}var nt;if(this._host&&this._host.syncRoot){var ot=this._host.syncRoot,at=(ot.masterFrame-ot.fromFrame)/(ot.toFrame-ot.fromFrame);nt=e+(o-e)*at}else _e>0&&e>o||_e<0&&e<o?nt=k&&j!==0?o+_e%j:e:nt=k&&j!==0?e+_e%j:o;var st=this._events;if((c>0&&this.currentFrame>nt||c<0&&this.currentFrame<nt)&&(this._onLoop(),st.length))for(var ut=0;ut<st.length;ut++)st[ut].onlyOnce||(st[ut].isDone=!1);this._currentFrame=nt,this._animationState.repeatCount=j===0?0:_e/j>>0,this._animationState.highLimitValue=et,this._animationState.offsetValue=$;var ft=_._interpolate(nt,this._animationState);if(this.setValue(ft,d),st.length){for(var ut=0;ut<st.length;ut++)if(j>0&&nt>=st[ut].frame&&st[ut].frame>=e||j<0&&nt<=st[ut].frame&&st[ut].frame<=e){var lt=st[ut];lt.isDone||(lt.onlyOnce&&(st.splice(ut,1),ut--),lt.isDone=!0,lt.action(nt))}}return k||(this._stopped=!0),k},a}(),Bone=function(a){__extends(i,a);function i(e,o,s,c,d,_,b){s===void 0&&(s=null),c===void 0&&(c=null),d===void 0&&(d=null),_===void 0&&(_=null),b===void 0&&(b=null);var k=a.call(this,e,o.getScene())||this;return k.name=e,k.children=new Array,k.animations=new Array,k._index=null,k._absoluteTransform=new Matrix,k._invertedAbsoluteTransform=new Matrix,k._scalingDeterminant=1,k._worldTransform=new Matrix,k._needToDecompose=!0,k._needToCompose=!1,k._linkedTransformNode=null,k._waitingTransformNodeId=null,k._skeleton=o,k._localMatrix=c?c.clone():Matrix.Identity(),k._restPose=d||k._localMatrix.clone(),k._baseMatrix=_||k._localMatrix.clone(),k._index=b,o.bones.push(k),k.setParent(s,!1),(_||c)&&k._updateDifferenceMatrix(),k}return Object.defineProperty(i.prototype,"_matrix",{get:function(){return this._compose(),this._localMatrix},set:function(e){this._needToCompose=!1,e.updateFlag!==this._localMatrix.updateFlag&&(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"Bone"},i.prototype.getSkeleton=function(){return this._skeleton},i.prototype.getParent=function(){return this._parent},i.prototype.getChildren=function(){return this.children},i.prototype.getIndex=function(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index},i.prototype.setParent=function(e,o){if(o===void 0&&(o=!0),this._parent!==e){if(this._parent){var s=this._parent.children.indexOf(this);s!==-1&&this._parent.children.splice(s,1)}this._parent=e,this._parent&&this._parent.children.push(this),o&&this._updateDifferenceMatrix(),this.markAsDirty()}},i.prototype.getLocalMatrix=function(){return this._compose(),this._localMatrix},i.prototype.getBaseMatrix=function(){return this._baseMatrix},i.prototype.getRestPose=function(){return this._restPose},i.prototype.setRestPose=function(e){this._restPose.copyFrom(e)},i.prototype.getBindPose=function(){return this._baseMatrix},i.prototype.setBindPose=function(e){this.updateMatrix(e)},i.prototype.getWorldMatrix=function(){return this._worldTransform},i.prototype.returnToRest=function(){var e;if(this._linkedTransformNode){var o=TmpVectors.Vector3[0],s=TmpVectors.Quaternion[0],c=TmpVectors.Vector3[1];this.getRestPose().decompose(o,s,c),this._linkedTransformNode.position.copyFrom(c),this._linkedTransformNode.rotationQuaternion=(e=this._linkedTransformNode.rotationQuaternion)!==null&&e!==void 0?e:Quaternion.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(s),this._linkedTransformNode.scaling.copyFrom(o)}else this._matrix=this._restPose},i.prototype.getInvertedAbsoluteTransform=function(){return this._invertedAbsoluteTransform},i.prototype.getAbsoluteTransform=function(){return this._absoluteTransform},i.prototype.linkTransformNode=function(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++},i.prototype.getTransformNode=function(){return this._linkedTransformNode},Object.defineProperty(i.prototype,"position",{get:function(){return this._decompose(),this._localPosition},set:function(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rotation",{get:function(){return this.getRotation()},set:function(e){this.setRotation(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._decompose(),this._localRotation},set:function(e){this.setRotationQuaternion(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this.getScale()},set:function(e){this.setScale(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"animationPropertiesOverride",{get:function(){return this._skeleton.animationPropertiesOverride},enumerable:!1,configurable:!0}),i.prototype._decompose=function(){!this._needToDecompose||(this._needToDecompose=!1,this._localScaling||(this._localScaling=Vector3.Zero(),this._localRotation=Quaternion.Zero(),this._localPosition=Vector3.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))},i.prototype._compose=function(){if(!!this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,Matrix.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}},i.prototype.updateMatrix=function(e,o,s){o===void 0&&(o=!0),s===void 0&&(s=!0),this._baseMatrix.copyFrom(e),o&&this._updateDifferenceMatrix(),s?this._matrix=e:this.markAsDirty()},i.prototype._updateDifferenceMatrix=function(e,o){if(o===void 0&&(o=!0),e||(e=this._baseMatrix),this._parent?e.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),o)for(var s=0;s<this.children.length;s++)this.children[s]._updateDifferenceMatrix();this._scalingDeterminant=this._absoluteTransform.determinant()<0?-1:1},i.prototype.markAsDirty=function(e){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this},i.prototype._markAsDirtyAndCompose=function(){this.markAsDirty(),this._needToCompose=!0},i.prototype._markAsDirtyAndDecompose=function(){this.markAsDirty(),this._needToDecompose=!0},i.prototype.translate=function(e,o,s){o===void 0&&(o=Space.LOCAL);var c=this.getLocalMatrix();if(o==Space.LOCAL)c.addAtIndex(12,e.x),c.addAtIndex(13,e.y),c.addAtIndex(14,e.z);else{var d=null;s&&(d=s.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var _=i._tmpMats[0],b=i._tmpVecs[0];this._parent?s&&d?(_.copyFrom(this._parent.getAbsoluteTransform()),_.multiplyToRef(d,_)):_.copyFrom(this._parent.getAbsoluteTransform()):Matrix.IdentityToRef(_),_.setTranslationFromFloats(0,0,0),_.invert(),Vector3.TransformCoordinatesToRef(e,_,b),c.addAtIndex(12,b.x),c.addAtIndex(13,b.y),c.addAtIndex(14,b.z)}this._markAsDirtyAndDecompose()},i.prototype.setPosition=function(e,o,s){o===void 0&&(o=Space.LOCAL);var c=this.getLocalMatrix();if(o==Space.LOCAL)c.setTranslationFromFloats(e.x,e.y,e.z);else{var d=null;s&&(d=s.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var _=i._tmpMats[0],b=i._tmpVecs[0];this._parent?(s&&d?(_.copyFrom(this._parent.getAbsoluteTransform()),_.multiplyToRef(d,_)):_.copyFrom(this._parent.getAbsoluteTransform()),_.invert()):Matrix.IdentityToRef(_),Vector3.TransformCoordinatesToRef(e,_,b),c.setTranslationFromFloats(b.x,b.y,b.z)}this._markAsDirtyAndDecompose()},i.prototype.setAbsolutePosition=function(e,o){this.setPosition(e,Space.WORLD,o)},i.prototype.scale=function(e,o,s,c){c===void 0&&(c=!1);var d=this.getLocalMatrix(),_=i._tmpMats[0];Matrix.ScalingToRef(e,o,s,_),_.multiplyToRef(d,d),_.invert();for(var b=0,k=this.children;b<k.length;b++){var j=k[b],$=j.getLocalMatrix();$.multiplyToRef(_,$),$.multiplyAtIndex(12,e),$.multiplyAtIndex(13,o),$.multiplyAtIndex(14,s),j._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),c)for(var _e=0,et=this.children;_e<et.length;_e++){var j=et[_e];j.scale(e,o,s,c)}},i.prototype.setScale=function(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()},i.prototype.getScale=function(){return this._decompose(),this._localScaling},i.prototype.getScaleToRef=function(e){this._decompose(),e.copyFrom(this._localScaling)},i.prototype.setYawPitchRoll=function(e,o,s,c,d){if(c===void 0&&(c=Space.LOCAL),c===Space.LOCAL){var _=i._tmpQuat;Quaternion.RotationYawPitchRollToRef(e,o,s,_),this.setRotationQuaternion(_,c,d);return}var b=i._tmpMats[0];if(!!this._getNegativeRotationToRef(b,d)){var k=i._tmpMats[1];Matrix.RotationYawPitchRollToRef(e,o,s,k),b.multiplyToRef(k,k),this._rotateWithMatrix(k,c,d)}},i.prototype.rotate=function(e,o,s,c){s===void 0&&(s=Space.LOCAL);var d=i._tmpMats[0];d.setTranslationFromFloats(0,0,0),Matrix.RotationAxisToRef(e,o,d),this._rotateWithMatrix(d,s,c)},i.prototype.setAxisAngle=function(e,o,s,c){if(s===void 0&&(s=Space.LOCAL),s===Space.LOCAL){var d=i._tmpQuat;Quaternion.RotationAxisToRef(e,o,d),this.setRotationQuaternion(d,s,c);return}var _=i._tmpMats[0];if(!!this._getNegativeRotationToRef(_,c)){var b=i._tmpMats[1];Matrix.RotationAxisToRef(e,o,b),_.multiplyToRef(b,b),this._rotateWithMatrix(b,s,c)}},i.prototype.setRotation=function(e,o,s){o===void 0&&(o=Space.LOCAL),this.setYawPitchRoll(e.y,e.x,e.z,o,s)},i.prototype.setRotationQuaternion=function(e,o,s){if(o===void 0&&(o=Space.LOCAL),o===Space.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}var c=i._tmpMats[0];if(!!this._getNegativeRotationToRef(c,s)){var d=i._tmpMats[1];Matrix.FromQuaternionToRef(e,d),c.multiplyToRef(d,d),this._rotateWithMatrix(d,o,s)}},i.prototype.setRotationMatrix=function(e,o,s){if(o===void 0&&(o=Space.LOCAL),o===Space.LOCAL){var c=i._tmpQuat;Quaternion.FromRotationMatrixToRef(e,c),this.setRotationQuaternion(c,o,s);return}var d=i._tmpMats[0];if(!!this._getNegativeRotationToRef(d,s)){var _=i._tmpMats[1];_.copyFrom(e),d.multiplyToRef(e,_),this._rotateWithMatrix(_,o,s)}},i.prototype._rotateWithMatrix=function(e,o,s){o===void 0&&(o=Space.LOCAL);var c=this.getLocalMatrix(),d=c.m[12],_=c.m[13],b=c.m[14],k=this.getParent(),j=i._tmpMats[3],$=i._tmpMats[4];k&&o==Space.WORLD?(s?(j.copyFrom(s.getWorldMatrix()),k.getAbsoluteTransform().multiplyToRef(j,j)):j.copyFrom(k.getAbsoluteTransform()),$.copyFrom(j),$.invert(),c.multiplyToRef(j,c),c.multiplyToRef(e,c),c.multiplyToRef($,c)):o==Space.WORLD&&s?(j.copyFrom(s.getWorldMatrix()),$.copyFrom(j),$.invert(),c.multiplyToRef(j,c),c.multiplyToRef(e,c),c.multiplyToRef($,c)):c.multiplyToRef(e,c),c.setTranslationFromFloats(d,_,b),this.computeAbsoluteTransforms(),this._markAsDirtyAndDecompose()},i.prototype._getNegativeRotationToRef=function(e,o){var s=i._tmpMats[2];return e.copyFrom(this.getAbsoluteTransform()),o&&(e.multiplyToRef(o.getWorldMatrix(),e),Matrix.ScalingToRef(o.scaling.x,o.scaling.y,o.scaling.z,s)),e.invert(),isNaN(e.m[0])?!1:(s.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(s,e),!0)},i.prototype.getPosition=function(e,o){e===void 0&&(e=Space.LOCAL),o===void 0&&(o=null);var s=Vector3.Zero();return this.getPositionToRef(e,o,s),s},i.prototype.getPositionToRef=function(e,o,s){if(e===void 0&&(e=Space.LOCAL),e==Space.LOCAL){var c=this.getLocalMatrix();s.x=c.m[12],s.y=c.m[13],s.z=c.m[14]}else{var d=null;o&&(d=o.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var _=i._tmpMats[0];o&&d?(_.copyFrom(this.getAbsoluteTransform()),_.multiplyToRef(d,_)):_=this.getAbsoluteTransform(),s.x=_.m[12],s.y=_.m[13],s.z=_.m[14]}},i.prototype.getAbsolutePosition=function(e){e===void 0&&(e=null);var o=Vector3.Zero();return this.getPositionToRef(Space.WORLD,e,o),o},i.prototype.getAbsolutePositionToRef=function(e,o){this.getPositionToRef(Space.WORLD,e,o)},i.prototype.computeAbsoluteTransforms=function(){if(this._compose(),this._parent)this._localMatrix.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform);else{this._absoluteTransform.copyFrom(this._localMatrix);var e=this._skeleton.getPoseMatrix();e&&this._absoluteTransform.multiplyToRef(e,this._absoluteTransform)}for(var o=this.children,s=o.length,c=0;c<s;c++)o[c].computeAbsoluteTransforms()},i.prototype.getDirection=function(e,o){o===void 0&&(o=null);var s=Vector3.Zero();return this.getDirectionToRef(e,o,s),s},i.prototype.getDirectionToRef=function(e,o,s){o===void 0&&(o=null);var c=null;o&&(c=o.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var d=i._tmpMats[0];d.copyFrom(this.getAbsoluteTransform()),o&&c&&d.multiplyToRef(c,d),Vector3.TransformNormalToRef(e,d,s),s.normalize()},i.prototype.getRotation=function(e,o){e===void 0&&(e=Space.LOCAL),o===void 0&&(o=null);var s=Vector3.Zero();return this.getRotationToRef(e,o,s),s},i.prototype.getRotationToRef=function(e,o,s){e===void 0&&(e=Space.LOCAL),o===void 0&&(o=null);var c=i._tmpQuat;this.getRotationQuaternionToRef(e,o,c),c.toEulerAnglesToRef(s)},i.prototype.getRotationQuaternion=function(e,o){e===void 0&&(e=Space.LOCAL),o===void 0&&(o=null);var s=Quaternion.Identity();return this.getRotationQuaternionToRef(e,o,s),s},i.prototype.getRotationQuaternionToRef=function(e,o,s){if(e===void 0&&(e=Space.LOCAL),o===void 0&&(o=null),e==Space.LOCAL)this._decompose(),s.copyFrom(this._localRotation);else{var c=i._tmpMats[0],d=this.getAbsoluteTransform();o?d.multiplyToRef(o.getWorldMatrix(),c):c.copyFrom(d),c.multiplyAtIndex(0,this._scalingDeterminant),c.multiplyAtIndex(1,this._scalingDeterminant),c.multiplyAtIndex(2,this._scalingDeterminant),c.decompose(void 0,s,void 0)}},i.prototype.getRotationMatrix=function(e,o){e===void 0&&(e=Space.LOCAL);var s=Matrix.Identity();return this.getRotationMatrixToRef(e,o,s),s},i.prototype.getRotationMatrixToRef=function(e,o,s){if(e===void 0&&(e=Space.LOCAL),e==Space.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(s);else{var c=i._tmpMats[0],d=this.getAbsoluteTransform();o?d.multiplyToRef(o.getWorldMatrix(),c):c.copyFrom(d),c.multiplyAtIndex(0,this._scalingDeterminant),c.multiplyAtIndex(1,this._scalingDeterminant),c.multiplyAtIndex(2,this._scalingDeterminant),c.getRotationMatrixToRef(s)}},i.prototype.getAbsolutePositionFromLocal=function(e,o){o===void 0&&(o=null);var s=Vector3.Zero();return this.getAbsolutePositionFromLocalToRef(e,o,s),s},i.prototype.getAbsolutePositionFromLocalToRef=function(e,o,s){o===void 0&&(o=null);var c=null;o&&(c=o.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var d=i._tmpMats[0];o&&c?(d.copyFrom(this.getAbsoluteTransform()),d.multiplyToRef(c,d)):d=this.getAbsoluteTransform(),Vector3.TransformCoordinatesToRef(e,d,s)},i.prototype.getLocalPositionFromAbsolute=function(e,o){o===void 0&&(o=null);var s=Vector3.Zero();return this.getLocalPositionFromAbsoluteToRef(e,o,s),s},i.prototype.getLocalPositionFromAbsoluteToRef=function(e,o,s){o===void 0&&(o=null);var c=null;o&&(c=o.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();var d=i._tmpMats[0];d.copyFrom(this.getAbsoluteTransform()),o&&c&&d.multiplyToRef(c,d),d.invert(),Vector3.TransformCoordinatesToRef(e,d,s)},i.prototype.setCurrentPoseAsRest=function(){this.setRestPose(this.getLocalMatrix())},i._tmpVecs=ArrayTools.BuildArray(2,Vector3.Zero),i._tmpQuat=Quaternion.Identity(),i._tmpMats=ArrayTools.BuildArray(5,Matrix.Identity),i}(Node$2),Animatable=function(){function a(i,e,o,s,c,d,_,b,k,j){o===void 0&&(o=0),s===void 0&&(s=100),c===void 0&&(c=!1),d===void 0&&(d=1),j===void 0&&(j=!1),this.target=e,this.fromFrame=o,this.toFrame=s,this.loopAnimation=c,this.onAnimationEnd=_,this.onAnimationLoop=k,this.isAdditive=j,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=0,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new Observable,this.onAnimationLoopObservable=new Observable,this._scene=i,b&&this.appendAnimations(e,b),this._speedRatio=d,i._activeAnimatables.push(this)}return Object.defineProperty(a.prototype,"syncRoot",{get:function(){return this._syncRoot},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"masterFrame",{get:function(){return this._runtimeAnimations.length===0?0:this._runtimeAnimations[0].currentFrame},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"weight",{get:function(){return this._weight},set:function(i){if(i===-1){this._weight=-1;return}this._weight=Math.min(Math.max(i,0),1)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(i){for(var e=0;e<this._runtimeAnimations.length;e++){var o=this._runtimeAnimations[e];o._prepareForSpeedRatioChange(i)}this._speedRatio=i},enumerable:!1,configurable:!0}),a.prototype.syncWith=function(i){if(this._syncRoot=i,i){var e=this._scene._activeAnimatables.indexOf(this);e>-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this},a.prototype.getAnimations=function(){return this._runtimeAnimations},a.prototype.appendAnimations=function(i,e){for(var o=this,s=0;s<e.length;s++){var c=e[s],d=new RuntimeAnimation(i,c,this._scene,this);d._onLoop=function(){o.onAnimationLoopObservable.notifyObservers(o),o.onAnimationLoop&&o.onAnimationLoop()},this._runtimeAnimations.push(d)}},a.prototype.getAnimationByTargetProperty=function(i){for(var e=this._runtimeAnimations,o=0;o<e.length;o++)if(e[o].animation.targetProperty===i)return e[o].animation;return null},a.prototype.getRuntimeAnimationByTargetProperty=function(i){for(var e=this._runtimeAnimations,o=0;o<e.length;o++)if(e[o].animation.targetProperty===i)return e[o];return null},a.prototype.reset=function(){for(var i=this._runtimeAnimations,e=0;e<i.length;e++)i[e].reset(!0);this._localDelayOffset=null,this._pausedDelay=null},a.prototype.enableBlending=function(i){for(var e=this._runtimeAnimations,o=0;o<e.length;o++)e[o].animation.enableBlending=!0,e[o].animation.blendingSpeed=i},a.prototype.disableBlending=function(){for(var i=this._runtimeAnimations,e=0;e<i.length;e++)i[e].animation.enableBlending=!1},a.prototype.goToFrame=function(i){var e,o=this._runtimeAnimations;if(o[0]){var s=o[0].animation.framePerSecond;this._frameToSyncFromJump=(e=this._frameToSyncFromJump)!==null&&e!==void 0?e:o[0].currentFrame;var c=this.speedRatio===0?0:(i-this._frameToSyncFromJump)/s*1e3/this.speedRatio;this._manualJumpDelay=-c}for(var d=0;d<o.length;d++)o[d].goToFrame(i)},a.prototype.pause=function(){this._paused||(this._paused=!0)},a.prototype.restart=function(){this._paused=!1},a.prototype._raiseOnAnimationEnd=function(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)},a.prototype.stop=function(i,e){if(i||e){var o=this._scene._activeAnimatables.indexOf(this);if(o>-1){for(var s=this._runtimeAnimations,c=s.length-1;c>=0;c--){var d=s[c];i&&d.animation.name!=i||e&&!e(d.target)||(d.dispose(),s.splice(c,1))}s.length==0&&(this._scene._activeAnimatables.splice(o,1),this._raiseOnAnimationEnd())}}else{var c=this._scene._activeAnimatables.indexOf(this);if(c>-1){this._scene._activeAnimatables.splice(c,1);for(var s=this._runtimeAnimations,c=0;c<s.length;c++)s[c].dispose();this._raiseOnAnimationEnd()}}},a.prototype.waitAsync=function(){var i=this;return new Promise(function(e,o){i.onAnimationEndObservable.add(function(){e(i)},void 0,void 0,i,!0)})},a.prototype._animate=function(i){if(this._paused)return this.animationStarted=!1,this._pausedDelay===null&&(this._pausedDelay=i),!0;if(this._localDelayOffset===null?(this._localDelayOffset=i,this._pausedDelay=null):this._pausedDelay!==null&&(this._localDelayOffset+=i-this._pausedDelay,this._pausedDelay=null),this._manualJumpDelay!==null&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._weight===0)return!0;var e=!1,o=this._runtimeAnimations,s;for(s=0;s<o.length;s++){var c=o[s],d=c.animate(i-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);e=e||d}if(this.animationStarted=e,!e){if(this.disposeOnEnd)for(s=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(s,1),s=0;s<o.length;s++)o[s].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return e},a}();Scene.prototype._animate=function(){if(!!this.animationsEnabled){var a=PrecisionDate.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=a}this.deltaTime=this.useConstantAnimationDeltaTime?16:(a-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=a;var i=this._activeAnimatables;if(i.length!==0){this._animationTime+=this.deltaTime;for(var e=this._animationTime,o=0;o<i.length;o++){var s=i[o];!s._animate(e)&&s.disposeOnEnd&&o--}this._processLateAnimationBindings()}}};Scene.prototype.beginWeightedAnimation=function(a,i,e,o,s,c,d,_,b,k,j){o===void 0&&(o=1),c===void 0&&(c=1),j===void 0&&(j=!1);var $=this.beginAnimation(a,i,e,s,c,d,_,!1,b,k,j);return $.weight=o,$};Scene.prototype.beginAnimation=function(a,i,e,o,s,c,d,_,b,k,j){s===void 0&&(s=1),_===void 0&&(_=!0),j===void 0&&(j=!1),i>e&&s>0&&(s*=-1),_&&this.stopAnimation(a,void 0,b),d||(d=new Animatable(this,a,i,e,o,s,c,void 0,k,j));var $=b?b(a):!0;if(a.animations&&$&&d.appendAnimations(a,a.animations),a.getAnimatables)for(var _e=a.getAnimatables(),et=0;et<_e.length;et++)this.beginAnimation(_e[et],i,e,o,s,c,d,_,b,k);return d.reset(),d};Scene.prototype.beginHierarchyAnimation=function(a,i,e,o,s,c,d,_,b,k,j,$){c===void 0&&(c=1),b===void 0&&(b=!0),$===void 0&&($=!1);var _e=a.getDescendants(i),et=[];et.push(this.beginAnimation(a,e,o,s,c,d,_,b,k,void 0,$));for(var tt=0,rt=_e;tt<rt.length;tt++){var it=rt[tt];et.push(this.beginAnimation(it,e,o,s,c,d,_,b,k,void 0,$))}return et};Scene.prototype.beginDirectAnimation=function(a,i,e,o,s,c,d,_,b){if(b===void 0&&(b=!1),c===void 0&&(c=1),e>o&&c>0)c*=-1;else if(o>e&&c<0){var k=o;o=e,e=k}var j=new Animatable(this,a,e,o,s,c,d,i,_,b);return j};Scene.prototype.beginDirectHierarchyAnimation=function(a,i,e,o,s,c,d,_,b,k){k===void 0&&(k=!1);var j=a.getDescendants(i),$=[];$.push(this.beginDirectAnimation(a,e,o,s,c,d,_,b,k));for(var _e=0,et=j;_e<et.length;_e++){var tt=et[_e];$.push(this.beginDirectAnimation(tt,e,o,s,c,d,_,b,k))}return $};Scene.prototype.getAnimatableByTarget=function(a){for(var i=0;i<this._activeAnimatables.length;i++)if(this._activeAnimatables[i].target===a)return this._activeAnimatables[i];return null};Scene.prototype.getAllAnimatablesByTarget=function(a){for(var i=[],e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].target===a&&i.push(this._activeAnimatables[e]);return i};Scene.prototype.stopAnimation=function(a,i,e){for(var o=this.getAllAnimatablesByTarget(a),s=0,c=o;s<c.length;s++){var d=c[s];d.stop(i,e)}};Scene.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(var a=0;a<this._activeAnimatables.length;a++)this._activeAnimatables[a].stop();this._activeAnimatables=[]}for(var i=0,e=this.animationGroups;i<e.length;i++){var o=e[i];o.stop()}};Scene.prototype._registerTargetForLateAnimationBinding=function(a,i){var e=a.target;this._registeredForLateAnimationBindings.pushNoDuplicate(e),e._lateAnimationHolders||(e._lateAnimationHolders={}),e._lateAnimationHolders[a.targetPath]||(e._lateAnimationHolders[a.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:i}),a.isAdditive?(e._lateAnimationHolders[a.targetPath].additiveAnimations.push(a),e._lateAnimationHolders[a.targetPath].totalAdditiveWeight+=a.weight):(e._lateAnimationHolders[a.targetPath].animations.push(a),e._lateAnimationHolders[a.targetPath].totalWeight+=a.weight)};Scene.prototype._processLateAnimationBindingsForMatrices=function(a){if(a.totalWeight===0&&a.totalAdditiveWeight===0)return a.originalValue;var i=1,e=TmpVectors.Vector3[0],o=TmpVectors.Vector3[1],s=TmpVectors.Quaternion[0],c=0,d=a.animations[0],_=a.originalValue,b=1,k=!1;if(a.totalWeight<1)b=1-a.totalWeight,_.decompose(o,s,e);else{if(c=1,i=a.totalWeight,b=d.weight/i,b==1)if(a.totalAdditiveWeight)k=!0;else return d.currentValue;d.currentValue.decompose(o,s,e)}if(!k){o.scaleInPlace(b),e.scaleInPlace(b),s.scaleInPlace(b);for(var j=c;j<a.animations.length;j++){var $=a.animations[j];if($.weight!==0){var b=$.weight/i,_e=TmpVectors.Vector3[2],et=TmpVectors.Vector3[3],tt=TmpVectors.Quaternion[1];$.currentValue.decompose(et,tt,_e),et.scaleAndAddToRef(b,o),tt.scaleAndAddToRef(b,s),_e.scaleAndAddToRef(b,e)}}}for(var rt=0;rt<a.additiveAnimations.length;rt++){var $=a.additiveAnimations[rt];if($.weight!==0){var _e=TmpVectors.Vector3[2],et=TmpVectors.Vector3[3],tt=TmpVectors.Quaternion[1];$.currentValue.decompose(et,tt,_e),et.multiplyToRef(o,et),Vector3.LerpToRef(o,et,$.weight,o),s.multiplyToRef(tt,tt),Quaternion.SlerpToRef(s,tt,$.weight,s),_e.scaleAndAddToRef($.weight,e)}}var it=d?d._animationState.workValue:TmpVectors.Matrix[0].clone();return Matrix.ComposeToRef(o,s,e,it),it};Scene.prototype._processLateAnimationBindingsForQuaternions=function(a,i){if(a.totalWeight===0&&a.totalAdditiveWeight===0)return i;var e=a.animations[0],o=a.originalValue,s=i;if(a.totalWeight===0&&a.totalAdditiveWeight>0)s.copyFrom(o);else if(a.animations.length===1){if(Quaternion.SlerpToRef(o,e.currentValue,Math.min(1,a.totalWeight),s),a.totalAdditiveWeight===0)return s}else if(a.animations.length>1){var c=1,d=void 0,_=void 0;if(a.totalWeight<1){var b=1-a.totalWeight;d=[],_=[],d.push(o),_.push(b)}else{if(a.animations.length===2&&(Quaternion.SlerpToRef(a.animations[0].currentValue,a.animations[1].currentValue,a.animations[1].weight/a.totalWeight,i),a.totalAdditiveWeight===0))return i;d=[],_=[],c=a.totalWeight}for(var k=0;k<a.animations.length;k++){var j=a.animations[k];d.push(j.currentValue),_.push(j.weight/c)}for(var $=0,_e=0;_e<d.length;){if(!_e){Quaternion.SlerpToRef(d[_e],d[_e+1],_[_e+1]/(_[_e]+_[_e+1]),i),s=i,$=_[_e]+_[_e+1],_e+=2;continue}$+=_[_e],Quaternion.SlerpToRef(s,d[_e],_[_e]/$,s),_e++}}for(var et=0;et<a.additiveAnimations.length;et++){var j=a.additiveAnimations[et];j.weight!==0&&(s.multiplyToRef(j.currentValue,TmpVectors.Quaternion[0]),Quaternion.SlerpToRef(s,TmpVectors.Quaternion[0],j.weight,s))}return s};Scene.prototype._processLateAnimationBindings=function(){if(!!this._registeredForLateAnimationBindings.length){for(var a=0;a<this._registeredForLateAnimationBindings.length;a++){var i=this._registeredForLateAnimationBindings.data[a];for(var e in i._lateAnimationHolders){var o=i._lateAnimationHolders[e],s=o.animations[0],c=o.originalValue,d=Animation.AllowMatrixDecomposeForInterpolation&&c.m,_=i[e];if(d)_=this._processLateAnimationBindingsForMatrices(o);else{var b=c.w!==void 0;if(b)_=this._processLateAnimationBindingsForQuaternions(o,_||Quaternion.Identity());else{var k=0,j=1;if(o.totalWeight<1)s&&c.scale?_=c.scale(1-o.totalWeight):s?_=c*(1-o.totalWeight):c.clone?_=c.clone():_=c;else if(s){j=o.totalWeight;var $=s.weight/j;$!==1?s.currentValue.scale?_=s.currentValue.scale($):_=s.currentValue*$:_=s.currentValue,k=1}for(var _e=k;_e<o.animations.length;_e++){var et=o.animations[_e],tt=et.weight/j;if(tt)et.currentValue.scaleAndAddToRef?et.currentValue.scaleAndAddToRef(tt,_):_+=et.currentValue*tt;else continue}for(var rt=0;rt<o.additiveAnimations.length;rt++){var et=o.additiveAnimations[rt],tt=et.weight;if(tt)et.currentValue.scaleAndAddToRef?et.currentValue.scaleAndAddToRef(tt,_):_+=et.currentValue*tt;else continue}}}i[e]=_}i._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}};Bone.prototype.copyAnimationRange=function(a,i,e,o,s){o===void 0&&(o=!1),s===void 0&&(s=null),this.animations.length===0&&(this.animations.push(new Animation(this.name,"_matrix",a.animations[0].framePerSecond,Animation.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));var c=a.animations[0].getRange(i);if(!c)return!1;for(var d=c.from,_=c.to,b=a.animations[0].getKeys(),k=a.length,j=a.getParent(),$=this.getParent(),_e=o&&j&&k&&this.length&&k!==this.length,et=_e&&$&&j?$.length/j.length:1,tt=o&&!$&&s&&(s.x!==1||s.y!==1||s.z!==1),rt=this.animations[0].getKeys(),it,nt,ot,at=0,st=b.length;at<st;at++)it=b[at],it.frame>=d&&it.frame<=_&&(o?(ot=it.value.clone(),_e?(nt=ot.getTranslation(),ot.setTranslation(nt.scaleInPlace(et))):tt&&s?(nt=ot.getTranslation(),ot.setTranslation(nt.multiplyInPlace(s))):ot=it.value):ot=it.value,rt.push({frame:it.frame+e,value:ot}));return this.animations[0].createRange(i,d+e,_+e),!0};var TargetedAnimation=function(){function a(){}return a.prototype.getClassName=function(){return"TargetedAnimation"},a.prototype.serialize=function(){var i={};return i.animation=this.animation.serialize(),i.targetId=this.target.id,i},a}(),AnimationGroup=function(){function a(i,e){e===void 0&&(e=null),this.name=i,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._parentContainer=null,this.onAnimationEndObservable=new Observable,this.onAnimationLoopObservable=new Observable,this.onAnimationGroupLoopObservable=new Observable,this.onAnimationGroupEndObservable=new Observable,this.onAnimationGroupPauseObservable=new Observable,this.onAnimationGroupPlayObservable=new Observable,this.metadata=null,this._scene=e||EngineStore.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}return Object.defineProperty(a.prototype,"from",{get:function(){return this._from},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"to",{get:function(){return this._to},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isStarted",{get:function(){return this._isStarted},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isPlaying",{get:function(){return this._isStarted&&!this._isPaused},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(i){if(this._speedRatio!==i){this._speedRatio=i;for(var e=0;e<this._animatables.length;e++){var o=this._animatables[e];o.speedRatio=this._speedRatio}}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"loopAnimation",{get:function(){return this._loopAnimation},set:function(i){if(this._loopAnimation!==i){this._loopAnimation=i;for(var e=0;e<this._animatables.length;e++){var o=this._animatables[e];o.loopAnimation=this._loopAnimation}}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isAdditive",{get:function(){return this._isAdditive},set:function(i){if(this._isAdditive!==i){this._isAdditive=i;for(var e=0;e<this._animatables.length;e++){var o=this._animatables[e];o.isAdditive=this._isAdditive}}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"targetedAnimations",{get:function(){return this._targetedAnimations},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"animatables",{get:function(){return this._animatables},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"children",{get:function(){return this._targetedAnimations},enumerable:!1,configurable:!0}),a.prototype.addTargetedAnimation=function(i,e){var o=new TargetedAnimation;o.animation=i,o.target=e;var s=i.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to<s[s.length-1].frame&&(this._to=s[s.length-1].frame),this._targetedAnimations.push(o),o},a.prototype.normalize=function(i,e){i===void 0&&(i=null),e===void 0&&(e=null),i==null&&(i=this._from),e==null&&(e=this._to);for(var o=0;o<this._targetedAnimations.length;o++){var s=this._targetedAnimations[o],c=s.animation.getKeys(),d=c[0],_=c[c.length-1];if(d.frame>i){var b={frame:i,value:d.value,inTangent:d.inTangent,outTangent:d.outTangent,interpolation:d.interpolation};c.splice(0,0,b)}if(_.frame<e){var b={frame:e,value:_.value,inTangent:_.inTangent,outTangent:_.outTangent,interpolation:_.interpolation};c.push(b)}}return this._from=i,this._to=e,this},a.prototype._processLoop=function(i,e,o){var s=this;i.onAnimationLoop=function(){s.onAnimationLoopObservable.notifyObservers(e),!s._animationLoopFlags[o]&&(s._animationLoopFlags[o]=!0,s._animationLoopCount++,s._animationLoopCount===s._targetedAnimations.length&&(s.onAnimationGroupLoopObservable.notifyObservers(s),s._animationLoopCount=0,s._animationLoopFlags=[]))}},a.prototype.start=function(i,e,o,s,c){var d=this;if(i===void 0&&(i=!1),e===void 0&&(e=1),this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=i,this._animationLoopCount=0,this._animationLoopFlags=[];for(var _=function(){var j=b._targetedAnimations[k],$=b._scene.beginDirectAnimation(j.target,[j.animation],o!==void 0?o:b._from,s!==void 0?s:b._to,i,e,void 0,void 0,c!==void 0?c:b._isAdditive);$.onAnimationEnd=function(){d.onAnimationEndObservable.notifyObservers(j),d._checkAnimationGroupEnded($)},b._processLoop($,j,k),b._animatables.push($)},b=this,k=0;k<this._targetedAnimations.length;k++)_();return this._speedRatio=e,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this},a.prototype.pause=function(){if(!this._isStarted)return this;this._isPaused=!0;for(var i=0;i<this._animatables.length;i++){var e=this._animatables[i];e.pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this},a.prototype.play=function(i){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(i!==void 0&&(this.loopAnimation=i),this.restart()):(this.stop(),this.start(i,this._speedRatio)),this._isPaused=!1,this},a.prototype.reset=function(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(var i=0;i<this._animatables.length;i++){var e=this._animatables[i];e.reset()}return this},a.prototype.restart=function(){if(!this._isStarted)return this;for(var i=0;i<this._animatables.length;i++){var e=this._animatables[i];e.restart()}return this.onAnimationGroupPlayObservable.notifyObservers(this),this},a.prototype.stop=function(){if(!this._isStarted)return this;for(var i=this._animatables.slice(),e=0;e<i.length;e++)i[e].stop();return this._isStarted=!1,this},a.prototype.setWeightForAllAnimatables=function(i){for(var e=0;e<this._animatables.length;e++){var o=this._animatables[e];o.weight=i}return this},a.prototype.syncAllAnimationsWith=function(i){for(var e=0;e<this._animatables.length;e++){var o=this._animatables[e];o.syncWith(i)}return this},a.prototype.goToFrame=function(i){if(!this._isStarted)return this;for(var e=0;e<this._animatables.length;e++){var o=this._animatables[e];o.goToFrame(i)}return this},a.prototype.dispose=function(){this._targetedAnimations=[],this._animatables=[];var i=this._scene.animationGroups.indexOf(this);if(i>-1&&this._scene.animationGroups.splice(i,1),this._parentContainer){var e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()},a.prototype._checkAnimationGroupEnded=function(i){var e=this._animatables.indexOf(i);e>-1&&this._animatables.splice(e,1),this._animatables.length===0&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},a.prototype.clone=function(i,e,o){o===void 0&&(o=!1);for(var s=new a(i||this.name,this._scene),c=0,d=this._targetedAnimations;c<d.length;c++){var _=d[c];s.addTargetedAnimation(o?_.animation.clone():_.animation,e?e(_.target):_.target)}return s},a.prototype.serialize=function(){var i={};i.name=this.name,i.from=this.from,i.to=this.to,i.targetedAnimations=[];for(var e=0;e<this.targetedAnimations.length;e++){var o=this.targetedAnimations[e];i.targetedAnimations[e]=o.serialize()}return Tags&&Tags.HasTags(this)&&(i.tags=Tags.GetTags(this)),this.metadata&&(i.metadata=this.metadata),i},a.Parse=function(i,e){for(var o=new a(i.name,e),s=0;s<i.targetedAnimations.length;s++){var c=i.targetedAnimations[s],d=Animation.Parse(c.animation),_=c.targetId;if(c.animation.property==="influence"){var b=e.getMorphTargetById(_);b&&o.addTargetedAnimation(d,b)}else{var k=e.getNodeById(_);k!=null&&o.addTargetedAnimation(d,k)}}return i.from!==null&&i.to!==null&&o.normalize(i.from,i.to),Tags&&Tags.AddTagsTo(o,i.tags),i.metadata!==void 0&&(o.metadata=i.metadata),o},a.MakeAnimationAdditive=function(i,e,o,s,c){e===void 0&&(e=0),s===void 0&&(s=!1);var d=i;s&&(d=i.clone(c||d.name));for(var _=d.targetedAnimations,b=0;b<_.length;b++){var k=_[b];Animation.MakeAnimationAdditive(k.animation,e,o)}return d.isAdditive=!0,d},a.prototype.getClassName=function(){return"AnimationGroup"},a.prototype.toString=function(i){var e="Name: "+this.name;return e+=", type: "+this.getClassName(),i&&(e+=", from: "+this._from,e+=", to: "+this._to,e+=", isStarted: "+this._isStarted,e+=", speedRatio: "+this._speedRatio,e+=", targetedAnimations length: "+this._targetedAnimations.length,e+=", animatables length: "+this._animatables),e},a}(),RawTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$){_===void 0&&(_=!0),b===void 0&&(b=!1),k===void 0&&(k=3),j===void 0&&(j=0);var _e=a.call(this,null,d,!_,b,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,$)||this;return _e.format=c,_e._engine&&(!_e._engine._caps.textureFloatLinearFiltering&&j===1&&(k=1),!_e._engine._caps.textureHalfFloatLinearFiltering&&j===2&&(k=1),_e._texture=_e._engine.createRawTexture(e,o,s,c,_,b,k,null,j,$!=null?$:0),_e.wrapU=Texture.CLAMP_ADDRESSMODE,_e.wrapV=Texture.CLAMP_ADDRESSMODE),_e}return i.prototype.update=function(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},i.CreateLuminanceTexture=function(e,o,s,c,d,_,b){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=3),new i(e,o,s,1,c,d,_,b)},i.CreateLuminanceAlphaTexture=function(e,o,s,c,d,_,b){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=3),new i(e,o,s,2,c,d,_,b)},i.CreateAlphaTexture=function(e,o,s,c,d,_,b){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=3),new i(e,o,s,0,c,d,_,b)},i.CreateRGBTexture=function(e,o,s,c,d,_,b,k){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=3),k===void 0&&(k=0),new i(e,o,s,4,c,d,_,b,k)},i.CreateRGBATexture=function(e,o,s,c,d,_,b,k){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=3),k===void 0&&(k=0),new i(e,o,s,5,c,d,_,b,k)},i.CreateRGBAStorageTexture=function(e,o,s,c,d,_,b,k){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=3),k===void 0&&(k=0),new i(e,o,s,5,c,d,_,b,k,1)},i.CreateRTexture=function(e,o,s,c,d,_,b,k){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=Texture.TRILINEAR_SAMPLINGMODE),k===void 0&&(k=1),new i(e,o,s,6,c,d,_,b,k)},i.CreateRStorageTexture=function(e,o,s,c,d,_,b,k){return d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=Texture.TRILINEAR_SAMPLINGMODE),k===void 0&&(k=1),new i(e,o,s,6,c,d,_,b,k,1)},i}(Texture),Skeleton=function(){function a(i,e,o){this.name=i,this.id=e,this.bones=new Array,this.needInitialSkinMatrix=!1,this.overrideMesh=null,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=Matrix.Identity(),this._ranges={},this._lastAbsoluteTransformsUpdateId=-1,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._waitingOverrideMeshId=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new Observable,this.bones=[],this._scene=o||EngineStore.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;var s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}return Object.defineProperty(a.prototype,"useTextureToStoreBoneMatrices",{get:function(){return this._useTextureToStoreBoneMatrices},set:function(i){this._useTextureToStoreBoneMatrices=i,this._markAsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(i){this._animationPropertiesOverride=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isUsingTextureForMatrices",{get:function(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"Skeleton"},a.prototype.getChildren=function(){return this.bones.filter(function(i){return!i.getParent()})},a.prototype.getTransformMatrices=function(i){return this.needInitialSkinMatrix&&i._bonesTransformMatrices?i._bonesTransformMatrices:(this._transformMatrices||this.prepare(),this._transformMatrices)},a.prototype.getTransformMatrixTexture=function(i){return this.needInitialSkinMatrix&&i._transformMatrixTexture?i._transformMatrixTexture:this._transformMatrixTexture},a.prototype.getScene=function(){return this._scene},a.prototype.toString=function(i){var e="Name: "+this.name+", nBones: "+this.bones.length;if(e+=", nAnimationRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),i){e+=", Ranges: {";var o=!0;for(var s in this._ranges)o&&(e+=", ",o=!1),e+=s;e+="}"}return e},a.prototype.getBoneIndexByName=function(i){for(var e=0,o=this.bones.length;e<o;e++)if(this.bones[e].name===i)return e;return-1},a.prototype.createAnimationRange=function(i,e,o){if(!this._ranges[i]){this._ranges[i]=new AnimationRange(i,e,o);for(var s=0,c=this.bones.length;s<c;s++)this.bones[s].animations[0]&&this.bones[s].animations[0].createRange(i,e,o)}},a.prototype.deleteAnimationRange=function(i,e){e===void 0&&(e=!0);for(var o=0,s=this.bones.length;o<s;o++)this.bones[o].animations[0]&&this.bones[o].animations[0].deleteRange(i,e);this._ranges[i]=null},a.prototype.getAnimationRange=function(i){return this._ranges[i]||null},a.prototype.getAnimationRanges=function(){var i=[],e;for(e in this._ranges)i.push(this._ranges[e]);return i},a.prototype.copyAnimationRange=function(i,e,o){if(o===void 0&&(o=!1),this._ranges[e]||!i.getAnimationRange(e))return!1;var s=!0,c=this._getHighestAnimationFrame()+1,d={},_=i.bones,b,k;for(k=0,b=_.length;k<b;k++)d[_[k].name]=_[k];this.bones.length!==_.length&&(Logger$2.Warn("copyAnimationRange: this rig has "+this.bones.length+" bones, while source as "+_.length),s=!1);var j=o&&this.dimensionsAtRest&&i.dimensionsAtRest?this.dimensionsAtRest.divide(i.dimensionsAtRest):null;for(k=0,b=this.bones.length;k<b;k++){var $=this.bones[k].name,_e=d[$];_e?s=s&&this.bones[k].copyAnimationRange(_e,e,c,o,j):(Logger$2.Warn("copyAnimationRange: not same rig, missing source bone "+$),s=!1)}var et=i.getAnimationRange(e);return et&&(this._ranges[e]=new AnimationRange(e,et.from+c,et.to+c)),s},a.prototype.returnToRest=function(){for(var i=0,e=this.bones;i<e.length;i++){var o=e[i];o._index!==-1&&o.returnToRest()}},a.prototype._getHighestAnimationFrame=function(){for(var i=0,e=0,o=this.bones.length;e<o;e++)if(this.bones[e].animations[0]){var s=this.bones[e].animations[0].getHighestFrame();i<s&&(i=s)}return i},a.prototype.beginAnimation=function(i,e,o,s){var c=this.getAnimationRange(i);return c?this._scene.beginAnimation(this,c.from,c.to,e,o,s):null},a.MakeAnimationAdditive=function(i,e,o){e===void 0&&(e=0);var s=i.getAnimationRange(o);if(!s)return null;for(var c=i._scene.getAllAnimatablesByTarget(i),d=null,_=0;_<c.length;_++){var b=c[_];if(b.fromFrame===(s==null?void 0:s.from)&&b.toFrame===(s==null?void 0:s.to)){d=b;break}}for(var k=i.getAnimatables(),_=0;_<k.length;_++){var j=k[_],$=j.animations;if(!!$)for(var _e=0;_e<$.length;_e++)Animation.MakeAnimationAdditive($[_e],e,o)}return d&&(d.isAdditive=!0),i},a.prototype._markAsDirty=function(){this._isDirty=!0},a.prototype._registerMeshWithPoseMatrix=function(i){this._meshesWithPoseMatrix.push(i)},a.prototype._unregisterMeshWithPoseMatrix=function(i){var e=this._meshesWithPoseMatrix.indexOf(i);e>-1&&this._meshesWithPoseMatrix.splice(e,1)},a.prototype._computeTransformMatrices=function(i,e){this.onBeforeComputeObservable.notifyObservers(this);for(var o=0;o<this.bones.length;o++){var s=this.bones[o];s._childUpdateId++;var c=s.getParent();if(c?s.getLocalMatrix().multiplyToRef(c.getWorldMatrix(),s.getWorldMatrix()):e?s.getLocalMatrix().multiplyToRef(e,s.getWorldMatrix()):s.getWorldMatrix().copyFrom(s.getLocalMatrix()),s._index!==-1){var d=s._index===null?o:s._index;s.getInvertedAbsoluteTransform().multiplyToArray(s.getWorldMatrix(),i,d*16)}}this._identity.copyToArray(i,this.bones.length*16)},a.prototype.prepare=function(){if(this._numBonesWithLinkedTransformNode>0)for(var i=0,e=this.bones;i<e.length;i++){var o=e[i];o._linkedTransformNode&&(o._linkedTransformNode.computeWorldMatrix(),o._matrix=o._linkedTransformNode._localMatrix)}if(!!this._isDirty){if(this.needInitialSkinMatrix)for(var s=0;s<this._meshesWithPoseMatrix.length;s++){var c=this._meshesWithPoseMatrix[s],d=c.getPoseMatrix();if((!c._bonesTransformMatrices||c._bonesTransformMatrices.length!==16*(this.bones.length+1))&&(c._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1))),this._synchronizedWithMesh!==c){this._synchronizedWithMesh=c;for(var _=0;_<this.bones.length;_++){var b=this.bones[_];if(!b.getParent()){var k=b.getBaseMatrix();k.multiplyToRef(d,TmpVectors.Matrix[1]),b._updateDifferenceMatrix(TmpVectors.Matrix[1])}}if(this.isUsingTextureForMatrices){var j=(this.bones.length+1)*4;(!c._transformMatrixTexture||c._transformMatrixTexture.getSize().width!==j)&&(c._transformMatrixTexture&&c._transformMatrixTexture.dispose(),c._transformMatrixTexture=RawTexture.CreateRGBATexture(c._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(c._bonesTransformMatrices,d),this.isUsingTextureForMatrices&&c._transformMatrixTexture&&c._transformMatrixTexture.update(c._bonesTransformMatrices)}else(!this._transformMatrices||this._transformMatrices.length!==16*(this.bones.length+1))&&(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=RawTexture.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices);this._isDirty=!1,this._scene._activeBones.addCount(this.bones.length,!1)}},a.prototype.getAnimatables=function(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(var i=0;i<this.bones.length;i++)this._animatables.push(this.bones[i])}return this._animatables},a.prototype.clone=function(i,e){var o=new a(i,e||i,this._scene);o.needInitialSkinMatrix=this.needInitialSkinMatrix,o.overrideMesh=this.overrideMesh;for(var s=0;s<this.bones.length;s++){var c=this.bones[s],d=null,_=c.getParent();if(_){var b=this.bones.indexOf(_);d=o.bones[b]}var k=new Bone(c.name,o,d,c.getBaseMatrix().clone(),c.getRestPose().clone());k._index=c._index,c._linkedTransformNode&&k.linkTransformNode(c._linkedTransformNode),DeepCopier.DeepCopy(c.animations,k.animations)}if(this._ranges){o._ranges={};for(var j in this._ranges){var $=this._ranges[j];$&&(o._ranges[j]=$.clone())}}return this._isDirty=!0,o},a.prototype.enableBlending=function(i){i===void 0&&(i=.01),this.bones.forEach(function(e){e.animations.forEach(function(o){o.enableBlending=!0,o.blendingSpeed=i})})},a.prototype.dispose=function(){if(this._meshesWithPoseMatrix=[],this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){var i=this._parentContainer.skeletons.indexOf(this);i>-1&&this._parentContainer.skeletons.splice(i,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)},a.prototype.serialize=function(){var i,e,o={};o.name=this.name,o.id=this.id,this.dimensionsAtRest&&(o.dimensionsAtRest=this.dimensionsAtRest.asArray()),o.bones=[],o.needInitialSkinMatrix=this.needInitialSkinMatrix,o.overrideMeshId=(i=this.overrideMesh)===null||i===void 0?void 0:i.id;for(var s=0;s<this.bones.length;s++){var c=this.bones[s],d=c.getParent(),_={parentBoneIndex:d?this.bones.indexOf(d):-1,index:c.getIndex(),name:c.name,id:c.id,matrix:c.getBaseMatrix().toArray(),rest:c.getRestPose().toArray(),linkedTransformNodeId:(e=c.getTransformNode())===null||e===void 0?void 0:e.id};o.bones.push(_),c.length&&(_.length=c.length),c.metadata&&(_.metadata=c.metadata),c.animations&&c.animations.length>0&&(_.animation=c.animations[0].serialize()),o.ranges=[];for(var b in this._ranges){var k=this._ranges[b];if(!!k){var j={};j.name=b,j.from=k.from,j.to=k.to,o.ranges.push(j)}}}return o},a.Parse=function(i,e){var o=new a(i.name,i.id,e);i.dimensionsAtRest&&(o.dimensionsAtRest=Vector3.FromArray(i.dimensionsAtRest)),o.needInitialSkinMatrix=i.needInitialSkinMatrix,i.overrideMeshId&&(o._hasWaitingData=!0,o._waitingOverrideMeshId=i.overrideMeshId);var s;for(s=0;s<i.bones.length;s++){var c=i.bones[s],d=i.bones[s].index,_=null;c.parentBoneIndex>-1&&(_=o.bones[c.parentBoneIndex]);var b=c.rest?Matrix.FromArray(c.rest):null,k=new Bone(c.name,o,_,Matrix.FromArray(c.matrix),b,null,d);c.id!==void 0&&c.id!==null&&(k.id=c.id),c.length&&(k.length=c.length),c.metadata&&(k.metadata=c.metadata),c.animation&&k.animations.push(Animation.Parse(c.animation)),c.linkedTransformNodeId!==void 0&&c.linkedTransformNodeId!==null&&(o._hasWaitingData=!0,k._waitingTransformNodeId=c.linkedTransformNodeId)}if(i.ranges)for(s=0;s<i.ranges.length;s++){var j=i.ranges[s];o.createAnimationRange(j.name,j.from,j.to)}return o},a.prototype.computeAbsoluteTransforms=function(i){i===void 0&&(i=!1);var e=this._scene.getRenderId();(this._lastAbsoluteTransformsUpdateId!=e||i)&&(this.bones[0].computeAbsoluteTransforms(),this._lastAbsoluteTransformsUpdateId=e)},a.prototype.getPoseMatrix=function(){var i=null;return this._meshesWithPoseMatrix.length>0&&(i=this._meshesWithPoseMatrix[0].getPoseMatrix()),i},a.prototype.sortBones=function(){for(var i=new Array,e=new Array(this.bones.length),o=0;o<this.bones.length;o++)this._sortBones(o,i,e);this.bones=i},a.prototype._sortBones=function(i,e,o){if(!o[i]){o[i]=!0;var s=this.bones[i];s._index===void 0&&(s._index=i);var c=s.getParent();c&&this._sortBones(this.bones.indexOf(c),e,o),e.push(s)}},a.prototype.setCurrentPoseAsRest=function(){this.bones.forEach(function(i){i.setCurrentPoseAsRest()})},a}(),IntersectionInfo=function(){function a(i,e,o){this.bu=i,this.bv=e,this.distance=o,this.faceId=0,this.subMeshId=0}return a}(),SubMesh=function(){function a(i,e,o,s,c,d,_,b,k){b===void 0&&(b=!0),k===void 0&&(k=!0),this.materialIndex=i,this.verticesStart=e,this.verticesCount=o,this.indexStart=s,this.indexCount=c,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=d,this._renderingMesh=_||d,k&&d.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=d.subMeshes.length-1,b&&(this.refreshBoundingInfo(),d.computeWorldMatrix(!0))}return Object.defineProperty(a.prototype,"materialDefines",{get:function(){var i;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(i=this._getDrawWrapper())===null||i===void 0?void 0:i.defines},set:function(i){var e,o=(e=this._mainDrawWrapperOverride)!==null&&e!==void 0?e:this._getDrawWrapper(void 0,!0);o.defines=i},enumerable:!1,configurable:!0}),a.prototype._getDrawWrapper=function(i,e){e===void 0&&(e=!1),i=i!=null?i:this._engine.currentRenderPassId;var o=this._drawWrappers[i];return!o&&e&&(this._drawWrappers[i]=o=new DrawWrapper(this._mesh.getScene().getEngine())),o},a.prototype._removeDrawWrapper=function(i,e){var o;e===void 0&&(e=!0),e&&((o=this._drawWrappers[i])===null||o===void 0||o.dispose()),this._drawWrappers[i]=void 0},Object.defineProperty(a.prototype,"effect",{get:function(){var i,e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(e=(i=this._getDrawWrapper())===null||i===void 0?void 0:i.effect)!==null&&e!==void 0?e:null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"_drawWrapper",{get:function(){var i;return(i=this._mainDrawWrapperOverride)!==null&&i!==void 0?i:this._getDrawWrapper(void 0,!0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"_drawWrapperOverride",{get:function(){return this._mainDrawWrapperOverride},enumerable:!1,configurable:!0}),a.prototype._setMainDrawWrapperOverride=function(i){this._mainDrawWrapperOverride=i},a.prototype.setEffect=function(i,e,o,s){e===void 0&&(e=null),s===void 0&&(s=!0);var c=this._drawWrapper;c.setEffect(i,e,s),o!==void 0&&(c.materialContext=o),i||(c.defines=null,c.materialContext=void 0)},a.prototype.resetDrawCache=function(){if(this._drawWrappers)for(var i=0,e=this._drawWrappers;i<e.length;i++){var o=e[i];o==null||o.dispose()}this._drawWrappers=[]},a.AddToMesh=function(i,e,o,s,c,d,_,b){return b===void 0&&(b=!0),new a(i,e,o,s,c,d,_,b)},Object.defineProperty(a.prototype,"IsGlobal",{get:function(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()},enumerable:!1,configurable:!0}),a.prototype.getBoundingInfo=function(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo},a.prototype.setBoundingInfo=function(i){return this._boundingInfo=i,this},a.prototype.getMesh=function(){return this._mesh},a.prototype.getRenderingMesh=function(){return this._renderingMesh},a.prototype.getReplacementMesh=function(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null},a.prototype.getEffectiveMesh=function(){var i=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return i||this._renderingMesh},a.prototype.getMaterial=function(){var i,e=(i=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!==null&&i!==void 0?i:this._renderingMesh.material;if(e==null)return this._mesh.getScene().defaultMaterial;if(this._IsMultiMaterial(e)){var o=e.getSubMaterial(this.materialIndex);return this._currentMaterial!==o&&(this._currentMaterial=o,this.resetDrawCache()),o}return e},a.prototype._IsMultiMaterial=function(i){return i.getSubMaterial!==void 0},a.prototype.refreshBoundingInfo=function(i){if(i===void 0&&(i=null),this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(i||(i=this._renderingMesh.getVerticesData(VertexBuffer.PositionKind)),!i)return this._boundingInfo=this._mesh.getBoundingInfo(),this;var e=this._renderingMesh.getIndices(),o;if(this.indexStart===0&&this.indexCount===e.length){var s=this._renderingMesh.getBoundingInfo();o={minimum:s.minimum.clone(),maximum:s.maximum.clone()}}else o=extractMinAndMaxIndexed(i,e,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(o.minimum,o.maximum):this._boundingInfo=new BoundingInfo(o.minimum,o.maximum),this},a.prototype._checkCollision=function(i){var e=this.getBoundingInfo();return e._checkCollision(i)},a.prototype.updateBoundingInfo=function(i){var e=this.getBoundingInfo();return e||(this.refreshBoundingInfo(),e=this.getBoundingInfo()),e&&e.update(i),this},a.prototype.isInFrustum=function(i){var e=this.getBoundingInfo();return e?e.isInFrustum(i,this._mesh.cullingStrategy):!1},a.prototype.isCompletelyInFrustum=function(i){var e=this.getBoundingInfo();return e?e.isCompletelyInFrustum(i):!1},a.prototype.render=function(i){return this._renderingMesh.render(this,i,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this},a.prototype._getLinesIndexBuffer=function(i,e){if(!this._linesIndexBuffer){for(var o=[],s=this.indexStart;s<this.indexStart+this.indexCount;s+=3)o.push(i[s],i[s+1],i[s+1],i[s+2],i[s+2],i[s]);this._linesIndexBuffer=e.createIndexBuffer(o),this._linesIndexCount=o.length}return this._linesIndexBuffer},a.prototype.canIntersects=function(i){var e=this.getBoundingInfo();return e?i.intersectsBox(e.boundingBox):!1},a.prototype.intersects=function(i,e,o,s,c){var d=this.getMaterial();if(!d)return null;var _=3,b=!1;switch(d.fillMode){case 3:case 4:case 5:case 6:case 8:return null;case 7:_=1,b=!0;break}return this._mesh.getClassName()==="InstancedLinesMesh"||this._mesh.getClassName()==="LinesMesh"?o.length?this._intersectLines(i,e,o,this._mesh.intersectionThreshold,s):this._intersectUnIndexedLines(i,e,o,this._mesh.intersectionThreshold,s):!o.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(i,e,o,s,c):this._intersectTriangles(i,e,o,_,b,s,c)},a.prototype._intersectLines=function(i,e,o,s,c){for(var d=null,_=this.indexStart;_<this.indexStart+this.indexCount;_+=2){var b=e[o[_]],k=e[o[_+1]],j=i.intersectionSegment(b,k,s);if(!(j<0)&&(c||!d||j<d.distance)&&(d=new IntersectionInfo(null,null,j),d.faceId=_/2,c))break}return d},a.prototype._intersectUnIndexedLines=function(i,e,o,s,c){for(var d=null,_=this.verticesStart;_<this.verticesStart+this.verticesCount;_+=2){var b=e[_],k=e[_+1],j=i.intersectionSegment(b,k,s);if(!(j<0)&&(c||!d||j<d.distance)&&(d=new IntersectionInfo(null,null,j),d.faceId=_/2,c))break}return d},a.prototype._intersectTriangles=function(i,e,o,s,c,d,_){for(var b=null,k=-1,j=this.indexStart;j<this.indexStart+this.indexCount-(3-s);j+=s){k++;var $=o[j],_e=o[j+1],et=o[j+2];if(c&&et===4294967295){j+=2;continue}var tt=e[$],rt=e[_e],it=e[et];if(!(!tt||!rt||!it)&&!(_&&!_(tt,rt,it,i))){var nt=i.intersectsTriangle(tt,rt,it);if(nt){if(nt.distance<0)continue;if((d||!b||nt.distance<b.distance)&&(b=nt,b.faceId=k,d))break}}}return b},a.prototype._intersectUnIndexedTriangles=function(i,e,o,s,c){for(var d=null,_=this.verticesStart;_<this.verticesStart+this.verticesCount;_+=3){var b=e[_],k=e[_+1],j=e[_+2];if(!(c&&!c(b,k,j,i))){var $=i.intersectsTriangle(b,k,j);if($){if($.distance<0)continue;if((s||!d||$.distance<d.distance)&&(d=$,d.faceId=_/3,s))break}}}return d},a.prototype._rebuild=function(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)},a.prototype.clone=function(i,e){var o=new a(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,i,e,!1);if(!this.IsGlobal){var s=this.getBoundingInfo();if(!s)return o;o._boundingInfo=new BoundingInfo(s.minimum,s.maximum)}return o},a.prototype.dispose=function(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);var i=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(i,1),this.resetDrawCache()},a.prototype.getClassName=function(){return"SubMesh"},a.CreateFromIndices=function(i,e,o,s,c,d){d===void 0&&(d=!0);for(var _=Number.MAX_VALUE,b=-Number.MAX_VALUE,k=c||s,j=k.getIndices(),$=e;$<e+o;$++){var _e=j[$];_e<_&&(_=_e),_e>b&&(b=_e)}return new a(i,_,b-_+1,e,o,s,c,d)},a}(),Geometry=function(){function a(i,e,o,s,c){s===void 0&&(s=!1),c===void 0&&(c=null),this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this.id=i,this.uniqueId=e.getUniqueId(),this._engine=e.getEngine(),this._meshes=[],this._scene=e,this._vertexBuffers={},this._indices=[],this._updatable=s,o?this.setAllVerticesData(o,s):(this._totalVertices=0,this._indices=[]),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),c&&(this.applyToMesh(c),c.computeWorldMatrix(!0))}return Object.defineProperty(a.prototype,"boundingBias",{get:function(){return this._boundingBias},set:function(i){this._boundingBias?this._boundingBias.copyFrom(i):this._boundingBias=i.clone(),this._updateBoundingInfo(!0,null)},enumerable:!1,configurable:!0}),a.CreateGeometryForMesh=function(i){var e=new a(a.RandomId(),i.getScene());return e.applyToMesh(i),e},Object.defineProperty(a.prototype,"meshes",{get:function(){return this._meshes},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"extend",{get:function(){return this._extend},enumerable:!1,configurable:!0}),a.prototype.getScene=function(){return this._scene},a.prototype.getEngine=function(){return this._engine},a.prototype.isReady=function(){return this.delayLoadState===1||this.delayLoadState===0},Object.defineProperty(a.prototype,"doNotSerialize",{get:function(){for(var i=0;i<this._meshes.length;i++)if(!this._meshes[i].doNotSerialize)return!1;return!0},enumerable:!1,configurable:!0}),a.prototype._rebuild=function(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable));for(var i in this._vertexBuffers){var e=this._vertexBuffers[i];e._rebuild()}},a.prototype.setAllVerticesData=function(i,e){i.applyToGeometry(this,e),this.notifyUpdate()},a.prototype.setVerticesData=function(i,e,o,s){o===void 0&&(o=!1),o&&Array.isArray(e)&&(e=new Float32Array(e));var c=new VertexBuffer(this._engine,e,i,o,this._meshes.length===0,s);this.setVerticesBuffer(c)},a.prototype.removeVerticesData=function(i){this._vertexBuffers[i]&&(this._vertexBuffers[i].dispose(),delete this._vertexBuffers[i]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()},a.prototype.setVerticesBuffer=function(i,e,o){e===void 0&&(e=null),o===void 0&&(o=!0);var s=i.getKind();this._vertexBuffers[s]&&o&&this._vertexBuffers[s].dispose(),i._buffer&&i._buffer._increaseReferences(),this._vertexBuffers[s]=i;var c=this._meshes,d=c.length;if(s===VertexBuffer.PositionKind){var _=i.getData();e!=null?this._totalVertices=e:_!=null&&(this._totalVertices=_.length/(i.type===VertexBuffer.BYTE?i.byteStride:i.byteStride/4)),this._updateExtend(_),this._resetPointsArrayCache();for(var b=0;b<d;b++){var k=c[b];k.buildBoundingInfo(this._extend.minimum,this._extend.maximum),k._createGlobalSubMesh(!1),k.computeWorldMatrix(!0),k.synchronizeInstances()}}this.notifyUpdate(s)},a.prototype.updateVerticesDataDirectly=function(i,e,o,s){s===void 0&&(s=!1);var c=this.getVertexBuffer(i);!c||(c.updateDirectly(e,o,s),this.notifyUpdate(i))},a.prototype.updateVerticesData=function(i,e,o){o===void 0&&(o=!1);var s=this.getVertexBuffer(i);!s||(s.update(e),i===VertexBuffer.PositionKind&&this._updateBoundingInfo(o,e),this.notifyUpdate(i))},a.prototype._updateBoundingInfo=function(i,e){if(i&&this._updateExtend(e),this._resetPointsArrayCache(),i)for(var o=this._meshes,s=0,c=o;s<c.length;s++){var d=c[s];d.hasBoundingInfo?d.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):d.buildBoundingInfo(this._extend.minimum,this._extend.maximum);for(var _=d.subMeshes,b=0,k=_;b<k.length;b++){var j=k[b];j.refreshBoundingInfo()}}},a.prototype._bind=function(i,e,o,s){if(!!i){e===void 0&&(e=this._indexBuffer);var c=this.getVertexBuffers();if(!!c){if(e!=this._indexBuffer||!this._vertexArrayObjects&&!s){this._engine.bindBuffers(c,e,i,o);return}var d=s||this._vertexArrayObjects;d[i.key]||(d[i.key]=this._engine.recordVertexArrayObject(c,e,i,o)),this._engine.bindVertexArrayObject(d[i.key],e)}}},a.prototype.getTotalVertices=function(){return this.isReady()?this._totalVertices:0},a.prototype.getVerticesData=function(i,e,o){var s=this.getVertexBuffer(i);return s?s.getFloatData(this._totalVertices,o||e&&this._meshes.length!==1):null},a.prototype.isVertexBufferUpdatable=function(i){var e=this._vertexBuffers[i];return e?e.isUpdatable():!1},a.prototype.getVertexBuffer=function(i){return this.isReady()?this._vertexBuffers[i]:null},a.prototype.getVertexBuffers=function(){return this.isReady()?this._vertexBuffers:null},a.prototype.isVerticesDataPresent=function(i){return this._vertexBuffers?this._vertexBuffers[i]!==void 0:this._delayInfo?this._delayInfo.indexOf(i)!==-1:!1},a.prototype.getVerticesDataKinds=function(){var i=[],e;if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)i.push(e);else for(e in this._vertexBuffers)i.push(e);return i},a.prototype.updateIndices=function(i,e,o){if(o===void 0&&(o=!1),!!this._indexBuffer)if(!this._indexBufferIsUpdatable)this.setIndices(i,null,!0);else{var s=i.length!==this._indices.length;if(o||(this._indices=i.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,i,e),s)for(var c=0,d=this._meshes;c<d.length;c++){var _=d[c];_._createGlobalSubMesh(!0)}}},a.prototype.setIndices=function(i,e,o){e===void 0&&(e=null),o===void 0&&(o=!1),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=i,this._indexBufferIsUpdatable=o,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,o)),e!=null&&(this._totalVertices=e);for(var s=0,c=this._meshes;s<c.length;s++){var d=c[s];d._createGlobalSubMesh(!0),d.synchronizeInstances()}this.notifyUpdate()},a.prototype.getTotalIndices=function(){return this.isReady()?this._indices.length:0},a.prototype.getIndices=function(i,e){if(!this.isReady())return null;var o=this._indices;return!e&&(!i||this._meshes.length===1)?o:Tools.Slice(o)},a.prototype.getIndexBuffer=function(){return this.isReady()?this._indexBuffer:null},a.prototype._releaseVertexArrayObject=function(i){i===void 0&&(i=null),!(!i||!this._vertexArrayObjects)&&this._vertexArrayObjects[i.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[i.key]),delete this._vertexArrayObjects[i.key])},a.prototype.releaseForMesh=function(i,e){var o=this._meshes,s=o.indexOf(i);s!==-1&&(o.splice(s,1),this._vertexArrayObjects&&i._invalidateInstanceVertexArrayObject(),i._geometry=null,o.length===0&&e&&this.dispose())},a.prototype.applyToMesh=function(i){if(i._geometry!==this){var e=i._geometry;e&&e.releaseForMesh(i),this._vertexArrayObjects&&i._invalidateInstanceVertexArrayObject();var o=this._meshes;i._geometry=this,i._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),o.push(i),this.isReady()?this._applyToMesh(i):this._boundingInfo&&i.setBoundingInfo(this._boundingInfo)}},a.prototype._updateExtend=function(i){i===void 0&&(i=null),this.useBoundingInfoFromGeometry&&this._boundingInfo?this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()}:(i||(i=this.getVerticesData(VertexBuffer.PositionKind)),this._extend=extractMinAndMax(i,0,this._totalVertices,this.boundingBias,3))},a.prototype._applyToMesh=function(i){var e=this._meshes.length;for(var o in this._vertexBuffers)e===1&&this._vertexBuffers[o].create(),o===VertexBuffer.PositionKind&&(this._extend||this._updateExtend(),i.buildBoundingInfo(this._extend.minimum,this._extend.maximum),i._createGlobalSubMesh(!1),i._updateBoundingInfo());e===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),i._syncGeometryWithMorphTargetManager(),i.synchronizeInstances()},a.prototype.notifyUpdate=function(i){this.onGeometryUpdated&&this.onGeometryUpdated(this,i),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(var e=0,o=this._meshes;e<o.length;e++){var s=o[e];s._markSubMeshesAsAttributesDirty()}},a.prototype.load=function(i,e){if(this.delayLoadState!==2){if(this.isReady()){e&&e();return}this.delayLoadState=2,this._queueLoad(i,e)}},a.prototype._queueLoad=function(i,e){var o=this;!this.delayLoadingFile||(i._addPendingData(this),i._loadFile(this.delayLoadingFile,function(s){if(!!o._delayLoadingFunction){o._delayLoadingFunction(JSON.parse(s),o),o.delayLoadState=1,o._delayInfo=[],i._removePendingData(o);for(var c=o._meshes,d=c.length,_=0;_<d;_++)o._applyToMesh(c[_]);e&&e()}},void 0,!0))},a.prototype.toLeftHanded=function(){var i=this.getIndices(!1);if(i!=null&&i.length>0){for(var e=0;e<i.length;e+=3){var o=i[e+0];i[e+0]=i[e+2],i[e+2]=o}this.setIndices(i)}var s=this.getVerticesData(VertexBuffer.PositionKind,!1);if(s!=null&&s.length>0){for(var e=0;e<s.length;e+=3)s[e+2]=-s[e+2];this.setVerticesData(VertexBuffer.PositionKind,s,!1)}var c=this.getVerticesData(VertexBuffer.NormalKind,!1);if(c!=null&&c.length>0){for(var e=0;e<c.length;e+=3)c[e+2]=-c[e+2];this.setVerticesData(VertexBuffer.NormalKind,c,!1)}},a.prototype._resetPointsArrayCache=function(){this._positions=null},a.prototype._generatePointsArray=function(){if(this._positions)return!0;var i=this.getVerticesData(VertexBuffer.PositionKind);if(!i||i.length===0)return!1;for(var e=this._positionsCache.length*3,o=this._positionsCache.length;e<i.length;e+=3,++o)this._positionsCache[o]=Vector3.FromArray(i,e);for(var e=0,o=0;e<i.length;e+=3,++o)this._positionsCache[o].set(i[0+e],i[1+e],i[2+e]);return this._positionsCache.length=i.length/3,this._positions=this._positionsCache,!0},a.prototype.isDisposed=function(){return this._isDisposed},a.prototype._disposeVertexArrayObjects=function(){if(this._vertexArrayObjects){for(var i in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[i]);this._vertexArrayObjects={};for(var e=this._meshes,o=e.length,s=0;s<o;s++)e[s]._invalidateInstanceVertexArrayObject()}},a.prototype.dispose=function(){var i=this._meshes,e=i.length,o;for(o=0;o<e;o++)this.releaseForMesh(i[o]);this._meshes=[],this._disposeVertexArrayObjects();for(var s in this._vertexBuffers)this._vertexBuffers[s].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){var c=this._parentContainer.geometries.indexOf(this);c>-1&&this._parentContainer.geometries.splice(c,1),this._parentContainer=null}this._isDisposed=!0},a.prototype.copy=function(i){var e=new VertexData;e.indices=[];var o=this.getIndices();if(o)for(var s=0;s<o.length;s++)e.indices.push(o[s]);var c=!1,d=!1,_;for(_ in this._vertexBuffers){var b=this.getVerticesData(_);if(b&&(b instanceof Float32Array?e.set(new Float32Array(b),_):e.set(b.slice(0),_),!d)){var k=this.getVertexBuffer(_);k&&(c=k.isUpdatable(),d=!c)}}var j=new a(i,this._scene,e,c);j.delayLoadState=this.delayLoadState,j.delayLoadingFile=this.delayLoadingFile,j._delayLoadingFunction=this._delayLoadingFunction;for(_ in this._delayInfo)j._delayInfo=j._delayInfo||[],j._delayInfo.push(_);return j._boundingInfo=new BoundingInfo(this._extend.minimum,this._extend.maximum),j},a.prototype.serialize=function(){var i={};return i.id=this.id,i.uniqueId=this.uniqueId,i.updatable=this._updatable,Tags&&Tags.HasTags(this)&&(i.tags=Tags.GetTags(this)),i},a.prototype.toNumberArray=function(i){return Array.isArray(i)?i:Array.prototype.slice.call(i)},a.prototype.clearCachedData=function(){this._indices=[],this._resetPointsArrayCache();for(var i in this._vertexBuffers)!this._vertexBuffers.hasOwnProperty(i)||(this._vertexBuffers[i]._buffer._data=null)},a.prototype.serializeVerticeData=function(){var i=this.serialize();return this.isVerticesDataPresent(VertexBuffer.PositionKind)&&(i.positions=this.toNumberArray(this.getVerticesData(VertexBuffer.PositionKind)),this.isVertexBufferUpdatable(VertexBuffer.PositionKind)&&(i.positions._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.NormalKind)&&(i.normals=this.toNumberArray(this.getVerticesData(VertexBuffer.NormalKind)),this.isVertexBufferUpdatable(VertexBuffer.NormalKind)&&(i.normals._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.TangentKind)&&(i.tangents=this.toNumberArray(this.getVerticesData(VertexBuffer.TangentKind)),this.isVertexBufferUpdatable(VertexBuffer.TangentKind)&&(i.tangents._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.UVKind)&&(i.uvs=this.toNumberArray(this.getVerticesData(VertexBuffer.UVKind)),this.isVertexBufferUpdatable(VertexBuffer.UVKind)&&(i.uvs._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.UV2Kind)&&(i.uv2s=this.toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind)),this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)&&(i.uv2s._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.UV3Kind)&&(i.uv3s=this.toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind)),this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)&&(i.uv3s._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.UV4Kind)&&(i.uv4s=this.toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind)),this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)&&(i.uv4s._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.UV5Kind)&&(i.uv5s=this.toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind)),this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)&&(i.uv5s._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.UV6Kind)&&(i.uv6s=this.toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind)),this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)&&(i.uv6s._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.ColorKind)&&(i.colors=this.toNumberArray(this.getVerticesData(VertexBuffer.ColorKind)),this.isVertexBufferUpdatable(VertexBuffer.ColorKind)&&(i.colors._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)&&(i.matricesIndices=this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind)),i.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)&&(i.matricesIndices._updatable=!0)),this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)&&(i.matricesWeights=this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind)),this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)&&(i.matricesWeights._updatable=!0)),i.indices=this.toNumberArray(this.getIndices()),i},a.ExtractFromMesh=function(i,e){var o=i._geometry;return o?o.copy(e):null},a.RandomId=function(){return Tools.RandomId()},a._GetGeometryByLoadedUniqueId=function(i,e){for(var o=0;o<e.geometries.length;o++)if(e.geometries[o]._loadedUniqueId===i)return e.geometries[o];return null},a._ImportGeometry=function(i,e){var o=e.getScene(),s=i.geometryUniqueId,c=i.geometryId;if(s||c){var d=s?this._GetGeometryByLoadedUniqueId(s,o):o.getGeometryById(c);d&&d.applyToMesh(e)}else if(i instanceof ArrayBuffer){var _=e._binaryInfo;if(_.positionsAttrDesc&&_.positionsAttrDesc.count>0){var b=new Float32Array(i,_.positionsAttrDesc.offset,_.positionsAttrDesc.count);e.setVerticesData(VertexBuffer.PositionKind,b,!1)}if(_.normalsAttrDesc&&_.normalsAttrDesc.count>0){var k=new Float32Array(i,_.normalsAttrDesc.offset,_.normalsAttrDesc.count);e.setVerticesData(VertexBuffer.NormalKind,k,!1)}if(_.tangetsAttrDesc&&_.tangetsAttrDesc.count>0){var j=new Float32Array(i,_.tangetsAttrDesc.offset,_.tangetsAttrDesc.count);e.setVerticesData(VertexBuffer.TangentKind,j,!1)}if(_.uvsAttrDesc&&_.uvsAttrDesc.count>0){var $=new Float32Array(i,_.uvsAttrDesc.offset,_.uvsAttrDesc.count);e.setVerticesData(VertexBuffer.UVKind,$,!1)}if(_.uvs2AttrDesc&&_.uvs2AttrDesc.count>0){var _e=new Float32Array(i,_.uvs2AttrDesc.offset,_.uvs2AttrDesc.count);e.setVerticesData(VertexBuffer.UV2Kind,_e,!1)}if(_.uvs3AttrDesc&&_.uvs3AttrDesc.count>0){var et=new Float32Array(i,_.uvs3AttrDesc.offset,_.uvs3AttrDesc.count);e.setVerticesData(VertexBuffer.UV3Kind,et,!1)}if(_.uvs4AttrDesc&&_.uvs4AttrDesc.count>0){var tt=new Float32Array(i,_.uvs4AttrDesc.offset,_.uvs4AttrDesc.count);e.setVerticesData(VertexBuffer.UV4Kind,tt,!1)}if(_.uvs5AttrDesc&&_.uvs5AttrDesc.count>0){var rt=new Float32Array(i,_.uvs5AttrDesc.offset,_.uvs5AttrDesc.count);e.setVerticesData(VertexBuffer.UV5Kind,rt,!1)}if(_.uvs6AttrDesc&&_.uvs6AttrDesc.count>0){var it=new Float32Array(i,_.uvs6AttrDesc.offset,_.uvs6AttrDesc.count);e.setVerticesData(VertexBuffer.UV6Kind,it,!1)}if(_.colorsAttrDesc&&_.colorsAttrDesc.count>0){var nt=new Float32Array(i,_.colorsAttrDesc.offset,_.colorsAttrDesc.count);e.setVerticesData(VertexBuffer.ColorKind,nt,!1,_.colorsAttrDesc.stride)}if(_.matricesIndicesAttrDesc&&_.matricesIndicesAttrDesc.count>0){for(var ot=new Int32Array(i,_.matricesIndicesAttrDesc.offset,_.matricesIndicesAttrDesc.count),at=[],st=0;st<ot.length;st++){var ut=ot[st];at.push(ut&255),at.push((ut&65280)>>8),at.push((ut&16711680)>>16),at.push(ut>>24&255)}e.setVerticesData(VertexBuffer.MatricesIndicesKind,at,!1)}if(_.matricesIndicesExtraAttrDesc&&_.matricesIndicesExtraAttrDesc.count>0){for(var ot=new Int32Array(i,_.matricesIndicesExtraAttrDesc.offset,_.matricesIndicesExtraAttrDesc.count),at=[],st=0;st<ot.length;st++){var ut=ot[st];at.push(ut&255),at.push((ut&65280)>>8),at.push((ut&16711680)>>16),at.push(ut>>24&255)}e.setVerticesData(VertexBuffer.MatricesIndicesExtraKind,at,!1)}if(_.matricesWeightsAttrDesc&&_.matricesWeightsAttrDesc.count>0){var ft=new Float32Array(i,_.matricesWeightsAttrDesc.offset,_.matricesWeightsAttrDesc.count);e.setVerticesData(VertexBuffer.MatricesWeightsKind,ft,!1)}if(_.indicesAttrDesc&&_.indicesAttrDesc.count>0){var lt=new Int32Array(i,_.indicesAttrDesc.offset,_.indicesAttrDesc.count);e.setIndices(lt,null)}if(_.subMeshesAttrDesc&&_.subMeshesAttrDesc.count>0){var ht=new Int32Array(i,_.subMeshesAttrDesc.offset,_.subMeshesAttrDesc.count*5);e.subMeshes=[];for(var st=0;st<_.subMeshesAttrDesc.count;st++){var pt=ht[st*5+0],mt=ht[st*5+1],dt=ht[st*5+2],gt=ht[st*5+3],_t=ht[st*5+4];SubMesh.AddToMesh(pt,mt,dt,gt,_t,e)}}}else if(i.positions&&i.normals&&i.indices){if(e.setVerticesData(VertexBuffer.PositionKind,i.positions,i.positions._updatable),e.setVerticesData(VertexBuffer.NormalKind,i.normals,i.normals._updatable),i.tangents&&e.setVerticesData(VertexBuffer.TangentKind,i.tangents,i.tangents._updatable),i.uvs&&e.setVerticesData(VertexBuffer.UVKind,i.uvs,i.uvs._updatable),i.uvs2&&e.setVerticesData(VertexBuffer.UV2Kind,i.uvs2,i.uvs2._updatable),i.uvs3&&e.setVerticesData(VertexBuffer.UV3Kind,i.uvs3,i.uvs3._updatable),i.uvs4&&e.setVerticesData(VertexBuffer.UV4Kind,i.uvs4,i.uvs4._updatable),i.uvs5&&e.setVerticesData(VertexBuffer.UV5Kind,i.uvs5,i.uvs5._updatable),i.uvs6&&e.setVerticesData(VertexBuffer.UV6Kind,i.uvs6,i.uvs6._updatable),i.colors&&e.setVerticesData(VertexBuffer.ColorKind,Color4.CheckColors4(i.colors,i.positions.length/3),i.colors._updatable),i.matricesIndices)if(i.matricesIndices._isExpanded)delete i.matricesIndices._isExpanded,e.setVerticesData(VertexBuffer.MatricesIndicesKind,i.matricesIndices,i.matricesIndices._updatable);else{for(var at=[],st=0;st<i.matricesIndices.length;st++){var yt=i.matricesIndices[st];at.push(yt&255),at.push((yt&65280)>>8),at.push((yt&16711680)>>16),at.push(yt>>24&255)}e.setVerticesData(VertexBuffer.MatricesIndicesKind,at,i.matricesIndices._updatable)}if(i.matricesIndicesExtra)if(i.matricesIndicesExtra._isExpanded)delete i.matricesIndices._isExpanded,e.setVerticesData(VertexBuffer.MatricesIndicesExtraKind,i.matricesIndicesExtra,i.matricesIndicesExtra._updatable);else{for(var at=[],st=0;st<i.matricesIndicesExtra.length;st++){var yt=i.matricesIndicesExtra[st];at.push(yt&255),at.push((yt&65280)>>8),at.push((yt&16711680)>>16),at.push(yt>>24&255)}e.setVerticesData(VertexBuffer.MatricesIndicesExtraKind,at,i.matricesIndicesExtra._updatable)}i.matricesWeights&&(a._CleanMatricesWeights(i,e),e.setVerticesData(VertexBuffer.MatricesWeightsKind,i.matricesWeights,i.matricesWeights._updatable)),i.matricesWeightsExtra&&e.setVerticesData(VertexBuffer.MatricesWeightsExtraKind,i.matricesWeightsExtra,i.matricesWeights._updatable),e.setIndices(i.indices,null)}if(i.subMeshes){e.subMeshes=[];for(var Tt=0;Tt<i.subMeshes.length;Tt++){var St=i.subMeshes[Tt];SubMesh.AddToMesh(St.materialIndex,St.verticesStart,St.verticesCount,St.indexStart,St.indexCount,e)}}e._shouldGenerateFlatShading&&(e.convertToFlatShadedMesh(),e._shouldGenerateFlatShading=!1),e.computeWorldMatrix(!0),o.onMeshImportedObservable.notifyObservers(e)},a._CleanMatricesWeights=function(i,e){var o=.001;if(!!SceneLoaderFlags.CleanBoneMatrixWeights){var s=0;if(i.skeletonId>-1){var c=e.getScene().getLastSkeletonById(i.skeletonId);if(!c)return;s=c.bones.length}else return;for(var d=e.getVerticesData(VertexBuffer.MatricesIndicesKind),_=e.getVerticesData(VertexBuffer.MatricesIndicesExtraKind),b=i.matricesWeights,k=i.matricesWeightsExtra,j=i.numBoneInfluencer,$=b.length,_e=0;_e<$;_e+=4){for(var et=0,tt=-1,rt=0;rt<4;rt++){var it=b[_e+rt];et+=it,it<o&&tt<0&&(tt=rt)}if(k)for(var rt=0;rt<4;rt++){var it=k[_e+rt];et+=it,it<o&&tt<0&&(tt=rt+4)}if((tt<0||tt>j-1)&&(tt=j-1),et>o){for(var nt=1/et,rt=0;rt<4;rt++)b[_e+rt]*=nt;if(k)for(var rt=0;rt<4;rt++)k[_e+rt]*=nt}else tt>=4?(k[_e+tt-4]=1-et,_[_e+tt-4]=s):(b[_e+tt]=1-et,d[_e+tt]=s)}e.setVerticesData(VertexBuffer.MatricesIndicesKind,d),i.matricesWeightsExtra&&e.setVerticesData(VertexBuffer.MatricesIndicesExtraKind,_)}},a.Parse=function(i,e,o){var s=new a(i.id,e,void 0,i.updatable);return s._loadedUniqueId=i.uniqueId,Tags&&Tags.AddTagsTo(s,i.tags),i.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=o+i.delayLoadingFile,s._boundingInfo=new BoundingInfo(Vector3.FromArray(i.boundingBoxMinimum),Vector3.FromArray(i.boundingBoxMaximum)),s._delayInfo=[],i.hasUVs&&s._delayInfo.push(VertexBuffer.UVKind),i.hasUVs2&&s._delayInfo.push(VertexBuffer.UV2Kind),i.hasUVs3&&s._delayInfo.push(VertexBuffer.UV3Kind),i.hasUVs4&&s._delayInfo.push(VertexBuffer.UV4Kind),i.hasUVs5&&s._delayInfo.push(VertexBuffer.UV5Kind),i.hasUVs6&&s._delayInfo.push(VertexBuffer.UV6Kind),i.hasColors&&s._delayInfo.push(VertexBuffer.ColorKind),i.hasMatricesIndices&&s._delayInfo.push(VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&s._delayInfo.push(VertexBuffer.MatricesWeightsKind),s._delayLoadingFunction=VertexData.ImportVertexData):VertexData.ImportVertexData(i,s),e.pushGeometry(s,!0),s},a}(),Light=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s.diffuse=new Color3(1,1,1),s.specular=new Color3(1,1,1),s.falloffType=i.FALLOFF_DEFAULT,s.intensity=1,s._range=Number.MAX_VALUE,s._inverseSquaredRange=0,s._photometricScale=1,s._intensityMode=i.INTENSITYMODE_AUTOMATIC,s._radius=1e-5,s.renderPriority=0,s._shadowEnabled=!0,s._excludeWithLayerMask=0,s._includeOnlyWithLayerMask=0,s._lightmapMode=0,s._excludedMeshesIds=new Array,s._includedOnlyMeshesIds=new Array,s._isLight=!0,s.getScene().addLight(s),s._uniformBuffer=new UniformBuffer(s.getScene().getEngine(),void 0,void 0,e),s._buildUniformLayout(),s.includedOnlyMeshes=new Array,s.excludedMeshes=new Array,s._resyncMeshes(),s}return Object.defineProperty(i.prototype,"range",{get:function(){return this._range},set:function(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"intensityMode",{get:function(){return this._intensityMode},set:function(e){this._intensityMode=e,this._computePhotometricScale()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._computePhotometricScale()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadowEnabled",{get:function(){return this._shadowEnabled},set:function(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"includedOnlyMeshes",{get:function(){return this._includedOnlyMeshes},set:function(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"excludedMeshes",{get:function(){return this._excludedMeshes},set:function(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"excludeWithLayerMask",{get:function(){return this._excludeWithLayerMask},set:function(e){this._excludeWithLayerMask=e,this._resyncMeshes()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"includeOnlyWithLayerMask",{get:function(){return this._includeOnlyWithLayerMask},set:function(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lightmapMode",{get:function(){return this._lightmapMode},set:function(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),i.prototype.transferTexturesToEffect=function(e,o){return this},i.prototype._bindLight=function(e,o,s,c,d){d===void 0&&(d=!0);var _=e.toString(),b=!1;if(this._uniformBuffer.bindToEffect(s,"Light"+_),this._renderId!==o.getRenderId()||!this._uniformBuffer.useUbo){this._renderId=o.getRenderId();var k=this.getScaledIntensity();this.transferToEffect(s,_),this.diffuse.scaleToRef(k,TmpColors.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",TmpColors.Color3[0],this.range,_),c&&(this.specular.scaleToRef(k,TmpColors.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",TmpColors.Color3[1],this.radius,_)),b=!0}if(this.transferTexturesToEffect(s,_),o.shadowsEnabled&&this.shadowEnabled&&d){var j=this.getShadowGenerator();j&&(j.bindShadowLight(_,s),b=!0)}b?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()},i.prototype.getClassName=function(){return"Light"},i.prototype.toString=function(e){var o="Name: "+this.name;if(o+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(var s=0;s<this.animations.length;s++)o+=", animation[0]: "+this.animations[s].toString(e);return o},i.prototype._syncParentEnabledState=function(){a.prototype._syncParentEnabledState.call(this),this.isDisposed()||this._resyncMeshes()},i.prototype.setEnabled=function(e){a.prototype.setEnabled.call(this,e),this._resyncMeshes()},i.prototype.getShadowGenerator=function(){return this._shadowGenerator},i.prototype.getAbsolutePosition=function(){return Vector3.Zero()},i.prototype.canAffectMesh=function(e){return e?!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&(this.includeOnlyWithLayerMask&e.layerMask)===0||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0},i.prototype.dispose=function(e,o){if(o===void 0&&(o=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this),this._parentContainer){var s=this._parentContainer.lights.indexOf(this);s>-1&&this._parentContainer.lights.splice(s,1),this._parentContainer=null}for(var c=0,d=this.getScene().meshes;c<d.length;c++){var _=d[c];_._removeLightSource(this,!0)}this._uniformBuffer.dispose(),this.getScene().removeLight(this),a.prototype.dispose.call(this,e,o)},i.prototype.getTypeID=function(){return 0},i.prototype.getScaledIntensity=function(){return this._photometricScale*this.intensity},i.prototype.clone=function(e,o){o===void 0&&(o=null);var s=i.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!s)return null;var c=SerializationHelper.Clone(s,this);return e&&(c.name=e),o&&(c.parent=o),c.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(c),c},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&(e.parentId=this.parent.uniqueId),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach(function(o){e.excludedMeshesIds.push(o.id)})),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach(function(o){e.includedOnlyMeshesIds.push(o.id)})),SerializationHelper.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e},i.GetConstructorFromName=function(e,o,s){var c=Node$2.Construct("Light_Type_"+e,o,s);return c||null},i.Parse=function(e,o){var s=i.GetConstructorFromName(e.type,e.name,o);if(!s)return null;var c=SerializationHelper.Parse(s,e,o);if(e.excludedMeshesIds&&(c._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(c._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId&&(c._waitingParentId=e.parentId),e.falloffType!==void 0&&(c.falloffType=e.falloffType),e.lightmapMode!==void 0&&(c.lightmapMode=e.lightmapMode),e.animations){for(var d=0;d<e.animations.length;d++){var _=e.animations[d],b=GetClass("BABYLON.Animation");b&&c.animations.push(b.Parse(_))}Node$2.ParseAnimationRanges(c,e,o)}return e.autoAnimate&&o.beginAnimation(c,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&c.setEnabled(e.isEnabled),c},i.prototype._hookArrayForExcluded=function(e){var o=this,s=e.push;e.push=function(){for(var k=[],j=0;j<arguments.length;j++)k[j]=arguments[j];for(var $=s.apply(e,k),_e=0,et=k;_e<et.length;_e++){var tt=et[_e];tt._resyncLightSource(o)}return $};var c=e.splice;e.splice=function(k,j){for(var $=c.apply(e,[k,j]),_e=0,et=$;_e<et.length;_e++){var tt=et[_e];tt._resyncLightSource(o)}return $};for(var d=0,_=e;d<_.length;d++){var b=_[d];b._resyncLightSource(this)}},i.prototype._hookArrayForIncludedOnly=function(e){var o=this,s=e.push;e.push=function(){for(var d=[],_=0;_<arguments.length;_++)d[_]=arguments[_];var b=s.apply(e,d);return o._resyncMeshes(),b};var c=e.splice;e.splice=function(d,_){var b=c.apply(e,[d,_]);return o._resyncMeshes(),b},this._resyncMeshes()},i.prototype._resyncMeshes=function(){for(var e=0,o=this.getScene().meshes;e<o.length;e++){var s=o[e];s._resyncLightSource(this)}},i.prototype._markMeshesAsLightDirty=function(){for(var e=0,o=this.getScene().meshes;e<o.length;e++){var s=o[e];s.lightSources.indexOf(this)!==-1&&s._markSubMeshesAsLightDirty()}},i.prototype._computePhotometricScale=function(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()},i.prototype._getPhotometricScale=function(){var e=0,o=this.getTypeID(),s=this.intensityMode;switch(s===i.INTENSITYMODE_AUTOMATIC&&(o===i.LIGHTTYPEID_DIRECTIONALLIGHT?s=i.INTENSITYMODE_ILLUMINANCE:s=i.INTENSITYMODE_LUMINOUSINTENSITY),o){case i.LIGHTTYPEID_POINTLIGHT:case i.LIGHTTYPEID_SPOTLIGHT:switch(s){case i.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case i.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case i.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case i.LIGHTTYPEID_DIRECTIONALLIGHT:switch(s){case i.INTENSITYMODE_ILLUMINANCE:e=1;break;case i.INTENSITYMODE_LUMINANCE:var c=this.radius;c=Math.max(c,.001);var d=2*Math.PI*(1-Math.cos(c));e=d;break}break;case i.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e},i.prototype._reorderLightsInScene=function(){var e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()},i.FALLOFF_DEFAULT=LightConstants.FALLOFF_DEFAULT,i.FALLOFF_PHYSICAL=LightConstants.FALLOFF_PHYSICAL,i.FALLOFF_GLTF=LightConstants.FALLOFF_GLTF,i.FALLOFF_STANDARD=LightConstants.FALLOFF_STANDARD,i.LIGHTMAP_DEFAULT=LightConstants.LIGHTMAP_DEFAULT,i.LIGHTMAP_SPECULAR=LightConstants.LIGHTMAP_SPECULAR,i.LIGHTMAP_SHADOWSONLY=LightConstants.LIGHTMAP_SHADOWSONLY,i.INTENSITYMODE_AUTOMATIC=LightConstants.INTENSITYMODE_AUTOMATIC,i.INTENSITYMODE_LUMINOUSPOWER=LightConstants.INTENSITYMODE_LUMINOUSPOWER,i.INTENSITYMODE_LUMINOUSINTENSITY=LightConstants.INTENSITYMODE_LUMINOUSINTENSITY,i.INTENSITYMODE_ILLUMINANCE=LightConstants.INTENSITYMODE_ILLUMINANCE,i.INTENSITYMODE_LUMINANCE=LightConstants.INTENSITYMODE_LUMINANCE,i.LIGHTTYPEID_POINTLIGHT=LightConstants.LIGHTTYPEID_POINTLIGHT,i.LIGHTTYPEID_DIRECTIONALLIGHT=LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT,i.LIGHTTYPEID_SPOTLIGHT=LightConstants.LIGHTTYPEID_SPOTLIGHT,i.LIGHTTYPEID_HEMISPHERICLIGHT=LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT,__decorate([serializeAsColor3()],i.prototype,"diffuse",void 0),__decorate([serializeAsColor3()],i.prototype,"specular",void 0),__decorate([serialize()],i.prototype,"falloffType",void 0),__decorate([serialize()],i.prototype,"intensity",void 0),__decorate([serialize()],i.prototype,"range",null),__decorate([serialize()],i.prototype,"intensityMode",null),__decorate([serialize()],i.prototype,"radius",null),__decorate([serialize()],i.prototype,"_renderPriority",void 0),__decorate([expandToProperty("_reorderLightsInScene")],i.prototype,"renderPriority",void 0),__decorate([serialize("shadowEnabled")],i.prototype,"_shadowEnabled",void 0),__decorate([serialize("excludeWithLayerMask")],i.prototype,"_excludeWithLayerMask",void 0),__decorate([serialize("includeOnlyWithLayerMask")],i.prototype,"_includeOnlyWithLayerMask",void 0),__decorate([serialize("lightmapMode")],i.prototype,"_lightmapMode",void 0),i}(Node$2),ThinMaterialHelper=function(){function a(){}return a.BindClipPlane=function(i,e){if(e.clipPlane){var o=e.clipPlane;i.setFloat4("vClipPlane",o.normal.x,o.normal.y,o.normal.z,o.d)}if(e.clipPlane2){var o=e.clipPlane2;i.setFloat4("vClipPlane2",o.normal.x,o.normal.y,o.normal.z,o.d)}if(e.clipPlane3){var o=e.clipPlane3;i.setFloat4("vClipPlane3",o.normal.x,o.normal.y,o.normal.z,o.d)}if(e.clipPlane4){var o=e.clipPlane4;i.setFloat4("vClipPlane4",o.normal.x,o.normal.y,o.normal.z,o.d)}if(e.clipPlane5){var o=e.clipPlane5;i.setFloat4("vClipPlane5",o.normal.x,o.normal.y,o.normal.z,o.d)}if(e.clipPlane6){var o=e.clipPlane6;i.setFloat4("vClipPlane6",o.normal.x,o.normal.y,o.normal.z,o.d)}},a}(),MaterialHelper=function(){function a(){}return a.BindSceneUniformBuffer=function(i,e){e.bindToEffect(i,"Scene")},a.PrepareDefinesForMergedUV=function(i,e,o){e._needUVs=!0,e[o]=!0,i.getTextureMatrix().isIdentityAs3x2()?(e[o+"DIRECTUV"]=i.coordinatesIndex+1,e["MAINUV"+(i.coordinatesIndex+1)]=!0):e[o+"DIRECTUV"]=0},a.BindTextureMatrix=function(i,e,o){var s=i.getTextureMatrix();e.updateMatrix(o+"Matrix",s)},a.GetFogState=function(i,e){return e.fogEnabled&&i.applyFog&&e.fogMode!==Scene.FOGMODE_NONE},a.PrepareDefinesForMisc=function(i,e,o,s,c,d,_){_._areMiscDirty&&(_.LOGARITHMICDEPTH=o,_.POINTSIZE=s,_.FOG=c&&this.GetFogState(i,e),_.NONUNIFORMSCALING=i.nonUniformScaling,_.ALPHATEST=d)},a.PrepareDefinesForFrameBoundValues=function(i,e,o,s,c,d){c===void 0&&(c=null),d===void 0&&(d=!1);var _=!1,b=!1,k=!1,j=!1,$=!1,_e=!1,et=!1;b=c==null?i.clipPlane!==void 0&&i.clipPlane!==null:c,k=c==null?i.clipPlane2!==void 0&&i.clipPlane2!==null:c,j=c==null?i.clipPlane3!==void 0&&i.clipPlane3!==null:c,$=c==null?i.clipPlane4!==void 0&&i.clipPlane4!==null:c,_e=c==null?i.clipPlane5!==void 0&&i.clipPlane5!==null:c,et=c==null?i.clipPlane6!==void 0&&i.clipPlane6!==null:c,o.CLIPPLANE!==b&&(o.CLIPPLANE=b,_=!0),o.CLIPPLANE2!==k&&(o.CLIPPLANE2=k,_=!0),o.CLIPPLANE3!==j&&(o.CLIPPLANE3=j,_=!0),o.CLIPPLANE4!==$&&(o.CLIPPLANE4=$,_=!0),o.CLIPPLANE5!==_e&&(o.CLIPPLANE5=_e,_=!0),o.CLIPPLANE6!==et&&(o.CLIPPLANE6=et,_=!0),o.DEPTHPREPASS!==!e.getColorWrite()&&(o.DEPTHPREPASS=!o.DEPTHPREPASS,_=!0),o.INSTANCES!==s&&(o.INSTANCES=s,_=!0),o.THIN_INSTANCES!==d&&(o.THIN_INSTANCES=d,_=!0),_&&o.markAsUnprocessed()},a.PrepareDefinesForBones=function(i,e){if(i.useBones&&i.computeBonesUsingShaders&&i.skeleton){e.NUM_BONE_INFLUENCERS=i.numBoneInfluencers;var o=e.BONETEXTURE!==void 0;if(i.skeleton.isUsingTextureForMatrices&&o)e.BONETEXTURE=!0;else{e.BonesPerMesh=i.skeleton.bones.length+1,e.BONETEXTURE=o?!1:void 0;var s=i.getScene().prePassRenderer;if(s&&s.enabled){var c=s.excludedSkinnedMesh.indexOf(i)===-1;e.BONES_VELOCITY_ENABLED=c}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0},a.PrepareDefinesForMorphTargets=function(i,e){var o=i.morphTargetManager;o?(e.MORPHTARGETS_UV=o.supportsUVs&&e.UV1,e.MORPHTARGETS_TANGENT=o.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=o.supportsNormals&&e.NORMAL,e.MORPHTARGETS=o.numInfluencers>0,e.NUM_MORPH_INFLUENCERS=o.numInfluencers,e.MORPHTARGETS_TEXTURE=o.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)},a.PrepareDefinesForBakedVertexAnimation=function(i,e){var o=i.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(o&&o.isEnabled)},a.PrepareDefinesForAttributes=function(i,e,o,s,c,d,_){if(c===void 0&&(c=!1),d===void 0&&(d=!0),_===void 0&&(_=!0),!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&i.isVerticesDataPresent(VertexBuffer.NormalKind),e._needNormals&&i.isVerticesDataPresent(VertexBuffer.TangentKind)&&(e.TANGENT=!0);for(var b=1;b<=6;++b)e["UV"+b]=e._needUVs?i.isVerticesDataPresent("uv"+(b===1?"":b)):!1;if(o){var k=i.useVertexColors&&i.isVerticesDataPresent(VertexBuffer.ColorKind);e.VERTEXCOLOR=k,e.VERTEXALPHA=i.hasVertexAlpha&&k&&d}return s&&this.PrepareDefinesForBones(i,e),c&&this.PrepareDefinesForMorphTargets(i,e),_&&this.PrepareDefinesForBakedVertexAnimation(i,e),!0},a.PrepareDefinesForMultiview=function(i,e){if(i.activeCamera){var o=e.MULTIVIEW;e.MULTIVIEW=i.activeCamera.outputRenderTarget!==null&&i.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=o&&e.markAsUnprocessed()}},a.PrepareDefinesForOIT=function(i,e,o){var s=e.ORDER_INDEPENDENT_TRANSPARENCY,c=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=i.useOrderIndependentTransparency&&o,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!i.getEngine().getCaps().textureFloatLinearFiltering,(s!==e.ORDER_INDEPENDENT_TRANSPARENCY||c!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()},a.PrepareDefinesForPrePass=function(i,e,o){var s=e.PREPASS;if(!!e._arePrePassDirty){var c=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(i.prePassRenderer&&i.prePassRenderer.enabled&&o){e.PREPASS=!0,e.SCENE_MRT_COUNT=i.prePassRenderer.mrtCount;for(var d=0;d<c.length;d++){var _=i.prePassRenderer.getIndex(c[d].type);_!==-1?(e[c[d].define]=!0,e[c[d].index]=_):e[c[d].define]=!1}}else{e.PREPASS=!1;for(var d=0;d<c.length;d++)e[c[d].define]=!1}e.PREPASS!=s&&(e.markAsUnprocessed(),e.markAsImageProcessingDirty())}},a.PrepareDefinesForLight=function(i,e,o,s,c,d,_){switch(_.needNormals=!0,c["LIGHT"+s]===void 0&&(_.needRebuild=!0),c["LIGHT"+s]=!0,c["SPOTLIGHT"+s]=!1,c["HEMILIGHT"+s]=!1,c["POINTLIGHT"+s]=!1,c["DIRLIGHT"+s]=!1,o.prepareLightSpecificDefines(c,s),c["LIGHT_FALLOFF_PHYSICAL"+s]=!1,c["LIGHT_FALLOFF_GLTF"+s]=!1,c["LIGHT_FALLOFF_STANDARD"+s]=!1,o.falloffType){case Light.FALLOFF_GLTF:c["LIGHT_FALLOFF_GLTF"+s]=!0;break;case Light.FALLOFF_PHYSICAL:c["LIGHT_FALLOFF_PHYSICAL"+s]=!0;break;case Light.FALLOFF_STANDARD:c["LIGHT_FALLOFF_STANDARD"+s]=!0;break}if(d&&!o.specular.equalsFloats(0,0,0)&&(_.specularEnabled=!0),c["SHADOW"+s]=!1,c["SHADOWCSM"+s]=!1,c["SHADOWCSMDEBUG"+s]=!1,c["SHADOWCSMNUM_CASCADES"+s]=!1,c["SHADOWCSMUSESHADOWMAXZ"+s]=!1,c["SHADOWCSMNOBLEND"+s]=!1,c["SHADOWCSM_RIGHTHANDED"+s]=!1,c["SHADOWPCF"+s]=!1,c["SHADOWPCSS"+s]=!1,c["SHADOWPOISSON"+s]=!1,c["SHADOWESM"+s]=!1,c["SHADOWCLOSEESM"+s]=!1,c["SHADOWCUBE"+s]=!1,c["SHADOWLOWQUALITY"+s]=!1,c["SHADOWMEDIUMQUALITY"+s]=!1,e&&e.receiveShadows&&i.shadowsEnabled&&o.shadowEnabled){var b=o.getShadowGenerator();if(b){var k=b.getShadowMap();k&&k.renderList&&k.renderList.length>0&&(_.shadowEnabled=!0,b.prepareDefines(c,s))}}o.lightmapMode!=Light.LIGHTMAP_DEFAULT?(_.lightmapMode=!0,c["LIGHTMAPEXCLUDED"+s]=!0,c["LIGHTMAPNOSPECULAR"+s]=o.lightmapMode==Light.LIGHTMAP_SHADOWSONLY):(c["LIGHTMAPEXCLUDED"+s]=!1,c["LIGHTMAPNOSPECULAR"+s]=!1)},a.PrepareDefinesForLights=function(i,e,o,s,c,d){if(c===void 0&&(c=4),d===void 0&&(d=!1),!o._areLightsDirty)return o._needNormals;var _=0,b={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(i.lightsEnabled&&!d)for(var k=0,j=e.lightSources;k<j.length;k++){var $=j[k];if(this.PrepareDefinesForLight(i,e,$,_,o,s,b),_++,_===c)break}o.SPECULARTERM=b.specularEnabled,o.SHADOWS=b.shadowEnabled;for(var _e=_;_e<c;_e++)o["LIGHT"+_e]!==void 0&&(o["LIGHT"+_e]=!1,o["HEMILIGHT"+_e]=!1,o["POINTLIGHT"+_e]=!1,o["DIRLIGHT"+_e]=!1,o["SPOTLIGHT"+_e]=!1,o["SHADOW"+_e]=!1,o["SHADOWCSM"+_e]=!1,o["SHADOWCSMDEBUG"+_e]=!1,o["SHADOWCSMNUM_CASCADES"+_e]=!1,o["SHADOWCSMUSESHADOWMAXZ"+_e]=!1,o["SHADOWCSMNOBLEND"+_e]=!1,o["SHADOWCSM_RIGHTHANDED"+_e]=!1,o["SHADOWPCF"+_e]=!1,o["SHADOWPCSS"+_e]=!1,o["SHADOWPOISSON"+_e]=!1,o["SHADOWESM"+_e]=!1,o["SHADOWCLOSEESM"+_e]=!1,o["SHADOWCUBE"+_e]=!1,o["SHADOWLOWQUALITY"+_e]=!1,o["SHADOWMEDIUMQUALITY"+_e]=!1);var et=i.getEngine().getCaps();return o.SHADOWFLOAT===void 0&&(b.needRebuild=!0),o.SHADOWFLOAT=b.shadowEnabled&&(et.textureFloatRender&&et.textureFloatLinearFiltering||et.textureHalfFloatRender&&et.textureHalfFloatLinearFiltering),o.LIGHTMAPEXCLUDED=b.lightmapMode,b.needRebuild&&o.rebuild(),b.needNormals},a.PrepareUniformsAndSamplersForLight=function(i,e,o,s,c,d){c===void 0&&(c=null),d===void 0&&(d=!1),c&&c.push("Light"+i),!d&&(e.push("vLightData"+i,"vLightDiffuse"+i,"vLightSpecular"+i,"vLightDirection"+i,"vLightFalloff"+i,"vLightGround"+i,"lightMatrix"+i,"shadowsInfo"+i,"depthValues"+i),o.push("shadowSampler"+i),o.push("depthSampler"+i),e.push("viewFrustumZ"+i,"cascadeBlendFactor"+i,"lightSizeUVCorrection"+i,"depthCorrection"+i,"penumbraDarkness"+i,"frustumLengths"+i),s&&(o.push("projectionLightSampler"+i),e.push("textureProjectionMatrix"+i)))},a.PrepareUniformsAndSamplersList=function(i,e,o,s){s===void 0&&(s=4);var c,d=null;if(i.uniformsNames){var _=i;c=_.uniformsNames,d=_.uniformBuffersNames,e=_.samplers,o=_.defines,s=_.maxSimultaneousLights||0}else c=i,e||(e=[]);for(var b=0;b<s&&o["LIGHT"+b];b++)this.PrepareUniformsAndSamplersForLight(b,c,e,o["PROJECTEDLIGHTTEXTURE"+b],d);o.NUM_MORPH_INFLUENCERS&&c.push("morphTargetInfluences"),o.BAKED_VERTEX_ANIMATION_TEXTURE&&(c.push("bakedVertexAnimationSettings"),c.push("bakedVertexAnimationTextureSizeInverted"),c.push("bakedVertexAnimationTime"),e.push("bakedVertexAnimationTexture"))},a.HandleFallbacksForShadows=function(i,e,o,s){o===void 0&&(o=4),s===void 0&&(s=0);for(var c=0,d=0;d<o&&i["LIGHT"+d];d++)d>0&&(c=s+d,e.addFallback(c,"LIGHT"+d)),i.SHADOWS||(i["SHADOW"+d]&&e.addFallback(s,"SHADOW"+d),i["SHADOWPCF"+d]&&e.addFallback(s,"SHADOWPCF"+d),i["SHADOWPCSS"+d]&&e.addFallback(s,"SHADOWPCSS"+d),i["SHADOWPOISSON"+d]&&e.addFallback(s,"SHADOWPOISSON"+d),i["SHADOWESM"+d]&&e.addFallback(s,"SHADOWESM"+d),i["SHADOWCLOSEESM"+d]&&e.addFallback(s,"SHADOWCLOSEESM"+d));return c++},a.PrepareAttributesForMorphTargetsInfluencers=function(i,e,o){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=o,this.PrepareAttributesForMorphTargets(i,e,this._TmpMorphInfluencers)},a.PrepareAttributesForMorphTargets=function(i,e,o){var s=o.NUM_MORPH_INFLUENCERS;if(s>0&&EngineStore.LastCreatedEngine){var c=EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs,d=e.morphTargetManager;if(d!=null&&d.isUsingTextureForTargets)return;for(var _=d&&d.supportsNormals&&o.NORMAL,b=d&&d.supportsTangents&&o.TANGENT,k=d&&d.supportsUVs&&o.UV1,j=0;j<s;j++)i.push(VertexBuffer.PositionKind+j),_&&i.push(VertexBuffer.NormalKind+j),b&&i.push(VertexBuffer.TangentKind+j),k&&i.push(VertexBuffer.UVKind+"_"+j),i.length>c&&Logger$2.Error("Cannot add more vertex attributes for mesh "+e.name)}},a.PrepareAttributesForBakedVertexAnimation=function(i,e,o){var s=o.BAKED_VERTEX_ANIMATION_TEXTURE&&o.INSTANCES;s&&(i.push("bakedVertexAnimationSettingsInstanced"),i.push("bakedVertexAnimationTimeInstanced"))},a.PrepareAttributesForBones=function(i,e,o,s){o.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,e),i.push(VertexBuffer.MatricesIndicesKind),i.push(VertexBuffer.MatricesWeightsKind),o.NUM_BONE_INFLUENCERS>4&&(i.push(VertexBuffer.MatricesIndicesExtraKind),i.push(VertexBuffer.MatricesWeightsExtraKind)))},a.PrepareAttributesForInstances=function(i,e){(e.INSTANCES||e.THIN_INSTANCES)&&this.PushAttributesForInstances(i,!!e.PREPASS_VELOCITY)},a.PushAttributesForInstances=function(i,e){e===void 0&&(e=!1),i.push("world0"),i.push("world1"),i.push("world2"),i.push("world3"),e&&(i.push("previousWorld0"),i.push("previousWorld1"),i.push("previousWorld2"),i.push("previousWorld3"))},a.BindLightProperties=function(i,e,o){i.transferToEffect(e,o+"")},a.BindLight=function(i,e,o,s,c,d){d===void 0&&(d=!0),i._bindLight(e,o,s,c,d)},a.BindLights=function(i,e,o,s,c){c===void 0&&(c=4);for(var d=Math.min(e.lightSources.length,c),_=0;_<d;_++){var b=e.lightSources[_];this.BindLight(b,_,i,o,typeof s=="boolean"?s:s.SPECULARTERM,e.receiveShadows)}},a.BindFogParameters=function(i,e,o,s){s===void 0&&(s=!1),i.fogEnabled&&e.applyFog&&i.fogMode!==Scene.FOGMODE_NONE&&(o.setFloat4("vFogInfos",i.fogMode,i.fogStart,i.fogEnd,i.fogDensity),s?(i.fogColor.toLinearSpaceToRef(this._tempFogColor),o.setColor3("vFogColor",this._tempFogColor)):o.setColor3("vFogColor",i.fogColor))},a.BindBonesParameters=function(i,e,o){if(!(!e||!i)&&(i.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(i.computeBonesUsingShaders=!1),i.useBones&&i.computeBonesUsingShaders&&i.skeleton)){var s=i.skeleton;if(s.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){var c=s.getTransformMatrixTexture(i);e.setTexture("boneSampler",c),e.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{var d=s.getTransformMatrices(i);d&&(e.setMatrices("mBones",d),o&&i.getScene().prePassRenderer&&i.getScene().prePassRenderer.getIndex(2)&&(o.previousBones[i.uniqueId]||(o.previousBones[i.uniqueId]=d.slice()),e.setMatrices("mPreviousBones",o.previousBones[i.uniqueId]),a._CopyBonesTransformationMatrices(d,o.previousBones[i.uniqueId])))}}},a._CopyBonesTransformationMatrices=function(i,e){return e.set(i),e},a.BindMorphTargetParameters=function(i,e){var o=i.morphTargetManager;!i||!o||e.setFloatArray("morphTargetInfluences",o.influences)},a.BindLogDepth=function(i,e,o){if(!i||i.LOGARITHMICDEPTH){var s=o.activeCamera;s.mode===Camera$1.ORTHOGRAPHIC_CAMERA&&Logger$2.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(s.maxZ+1)/Math.LN2))}},a.BindClipPlane=function(i,e){ThinMaterialHelper.BindClipPlane(i,e)},a._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},a._tempFogColor=Color3.Black(),a}(),MaterialStencilState=function(){function a(){this.reset()}return a.prototype.reset=function(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681},Object.defineProperty(a.prototype,"func",{get:function(){return this._func},set:function(i){this._func=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"funcRef",{get:function(){return this._funcRef},set:function(i){this._funcRef=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"funcMask",{get:function(){return this._funcMask},set:function(i){this._funcMask=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"opStencilFail",{get:function(){return this._opStencilFail},set:function(i){this._opStencilFail=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"opDepthFail",{get:function(){return this._opDepthFail},set:function(i){this._opDepthFail=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"opStencilDepthPass",{get:function(){return this._opStencilDepthPass},set:function(i){this._opStencilDepthPass=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"mask",{get:function(){return this._mask},set:function(i){this._mask=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"enabled",{get:function(){return this._enabled},set:function(i){this._enabled=i},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"MaterialStencilState"},a.prototype.copyTo=function(i){SerializationHelper.Clone(function(){return i},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.prototype.parse=function(i,e,o){var s=this;SerializationHelper.Parse(function(){return s},i,e,o)},__decorate([serialize()],a.prototype,"func",null),__decorate([serialize()],a.prototype,"funcRef",null),__decorate([serialize()],a.prototype,"funcMask",null),__decorate([serialize()],a.prototype,"opStencilFail",null),__decorate([serialize()],a.prototype,"opDepthFail",null),__decorate([serialize()],a.prototype,"opStencilDepthPass",null),__decorate([serialize()],a.prototype,"mask",null),__decorate([serialize()],a.prototype,"enabled",null),a}(),Material=function(){function a(i,e,o){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new Observable,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new MaterialStencilState,this._useUBO=!1,this._fillMode=a.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=i,this._scene=e||EngineStore.LastCreatedScene,this.id=i||Tools.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new DrawWrapper(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=a.ClockWiseSideOrientation:this.sideOrientation=a.CounterClockWiseSideOrientation,this._uniformBuffer=new UniformBuffer(this._scene.getEngine(),void 0,void 0,i),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,o||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={})}return Object.defineProperty(a.prototype,"canRenderToMRT",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"alpha",{get:function(){return this._alpha},set:function(i){this._alpha!==i&&(this._alpha=i,this.markAsDirty(a.MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"backFaceCulling",{get:function(){return this._backFaceCulling},set:function(i){this._backFaceCulling!==i&&(this._backFaceCulling=i,this.markAsDirty(a.TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"cullBackFaces",{get:function(){return this._cullBackFaces},set:function(i){this._cullBackFaces!==i&&(this._cullBackFaces=i,this.markAsDirty(a.TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasRenderTargetTextures",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onDispose",{set:function(i){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new Observable),this._onBindObservable},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onBind",{set:function(i){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onUnBindObservable",{get:function(){return this._onUnBindObservable||(this._onUnBindObservable=new Observable),this._onUnBindObservable},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onEffectCreatedObservable",{get:function(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new Observable),this._onEffectCreatedObservable},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"alphaMode",{get:function(){return this._alphaMode},set:function(i){this._alphaMode!==i&&(this._alphaMode=i,this.markAsDirty(a.TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"needDepthPrePass",{get:function(){return this._needDepthPrePass},set:function(i){this._needDepthPrePass!==i&&(this._needDepthPrePass=i,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isPrePassCapable",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"fogEnabled",{get:function(){return this._fogEnabled},set:function(i){this._fogEnabled!==i&&(this._fogEnabled=i,this.markAsDirty(a.MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"wireframe",{get:function(){switch(this._fillMode){case a.WireFrameFillMode:case a.LineListDrawMode:case a.LineLoopDrawMode:case a.LineStripDrawMode:return!0}return this._scene.forceWireframe},set:function(i){this.fillMode=i?a.WireFrameFillMode:a.TriangleFillMode},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"pointsCloud",{get:function(){switch(this._fillMode){case a.PointFillMode:case a.PointListDrawMode:return!0}return this._scene.forcePointsCloud},set:function(i){this.fillMode=i?a.PointFillMode:a.TriangleFillMode},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"fillMode",{get:function(){return this._fillMode},set:function(i){this._fillMode!==i&&(this._fillMode=i,this.markAsDirty(a.MiscDirtyFlag))},enumerable:!1,configurable:!0}),a.prototype._getDrawWrapper=function(){return this._drawWrapper},a.prototype._setDrawWrapper=function(i){this._drawWrapper=i},a.prototype.toString=function(i){var e="Name: "+this.name;return e},a.prototype.getClassName=function(){return"Material"},Object.defineProperty(a.prototype,"isFrozen",{get:function(){return this.checkReadyOnlyOnce},enumerable:!1,configurable:!0}),a.prototype.freeze=function(){this.markDirty(),this.checkReadyOnlyOnce=!0},a.prototype.unfreeze=function(){this.markDirty(),this.checkReadyOnlyOnce=!1},a.prototype.isReady=function(i,e){return!0},a.prototype.isReadyForSubMesh=function(i,e,o){return!1},a.prototype.getEffect=function(){return this._drawWrapper.effect},a.prototype.getScene=function(){return this._scene},Object.defineProperty(a.prototype,"transparencyMode",{get:function(){return this._transparencyMode},set:function(i){this._transparencyMode!==i&&(this._transparencyMode=i,this._forceAlphaTest=i===a.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"_disableAlphaBlending",{get:function(){return this._transparencyMode===a.MATERIAL_OPAQUE||this._transparencyMode===a.MATERIAL_ALPHATEST},enumerable:!1,configurable:!0}),a.prototype.needAlphaBlending=function(){return this._disableAlphaBlending?!1:this.alpha<1},a.prototype.needAlphaBlendingForMesh=function(i){return this._disableAlphaBlending&&i.visibility>=1?!1:this.needAlphaBlending()||i.visibility<1||i.hasVertexAlpha},a.prototype.needAlphaTesting=function(){return!!this._forceAlphaTest},a.prototype._shouldTurnAlphaTestOn=function(i){return!this.needAlphaBlendingForMesh(i)&&this.needAlphaTesting()},a.prototype.getAlphaTestTexture=function(){return null},a.prototype.markDirty=function(){for(var i=this.getScene().meshes,e=0,o=i;e<o.length;e++){var s=o[e];if(!!s.subMeshes)for(var c=0,d=s.subMeshes;c<d.length;c++){var _=d[c];_.getMaterial()===this&&(!_.effect||(_.effect._wasPreviouslyReady=!1))}}},a.prototype._preBind=function(i,e){e===void 0&&(e=null);var o=this._scene.getEngine(),s=e==null?this.sideOrientation:e,c=s===a.ClockWiseSideOrientation;return o.enableEffect(i||this._getDrawWrapper()),o.setState(this.backFaceCulling,this.zOffset,!1,c,this.cullBackFaces,this.stencil,this.zOffsetUnits),c},a.prototype.bind=function(i,e){},a.prototype.bindForSubMesh=function(i,e,o){},a.prototype.bindOnlyWorldMatrix=function(i){},a.prototype.bindView=function(i){this._useUBO?this._needToBindSceneUbo=!0:i.setMatrix("view",this.getScene().getViewMatrix())},a.prototype.bindViewProjection=function(i){this._useUBO?this._needToBindSceneUbo=!0:(i.setMatrix("viewProjection",this.getScene().getTransformMatrix()),i.setMatrix("projection",this.getScene().getProjectionMatrix()))},a.prototype.bindEyePosition=function(i,e){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(i,e)},a.prototype._afterBind=function(i,e){if(e===void 0&&(e=null),this._scene._cachedMaterial=this,this._needToBindSceneUbo&&e&&(this._needToBindSceneUbo=!1,MaterialHelper.BindSceneUniformBuffer(e,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),i?this._scene._cachedVisibility=i.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&i&&this._onBindObservable.notifyObservers(i),this.disableDepthWrite){var o=this._scene.getEngine();this._cachedDepthWriteState=o.getDepthWrite(),o.setDepthWrite(!1)}if(this.disableColorWrite){var o=this._scene.getEngine();this._cachedColorWriteState=o.getColorWrite(),o.setColorWrite(!1)}if(this.depthFunction!==0){var o=this._scene.getEngine();this._cachedDepthFunctionState=o.getDepthFunction()||0,o.setDepthFunction(this.depthFunction)}},a.prototype.unbind=function(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0){var i=this._scene.getEngine();i.setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){var i=this._scene.getEngine();i.setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){var i=this._scene.getEngine();i.setColorWrite(this._cachedColorWriteState)}},a.prototype.getActiveTextures=function(){return[]},a.prototype.hasTexture=function(i){return!1},a.prototype.clone=function(i){return null},a.prototype.getBindedMeshes=function(){var i=this;if(this.meshMap){var e=new Array;for(var o in this.meshMap){var s=this.meshMap[o];s&&e.push(s)}return e}else{var c=this._scene.meshes;return c.filter(function(d){return d.material===i})}},a.prototype.forceCompilation=function(i,e,o,s){var c=this,d=__assign({clipPlane:!1,useInstances:!1},o),_=this.getScene(),b=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;var k=function(){if(!(!c._scene||!c._scene.getEngine())){var j=_.clipPlane;if(d.clipPlane&&(_.clipPlane=new Plane(0,0,0,1)),c._storeEffectOnSubMeshes){var $=!0,_e=null;if(i.subMeshes){var et=new SubMesh(0,0,0,0,0,i,void 0,!1,!1);et.materialDefines&&(et.materialDefines._renderId=-1),c.isReadyForSubMesh(i,et,d.useInstances)||(et.effect&&et.effect.getCompilationError()&&et.effect.allFallbacksProcessed()?_e=et.effect.getCompilationError():($=!1,setTimeout(k,16)))}$&&(c.allowShaderHotSwapping=b,_e&&s&&s(_e),e&&e(c))}else c.isReady()?(c.allowShaderHotSwapping=b,e&&e(c)):setTimeout(k,16);d.clipPlane&&(_.clipPlane=j)}};k()},a.prototype.forceCompilationAsync=function(i,e){var o=this;return new Promise(function(s,c){o.forceCompilation(i,function(){s()},e,function(d){c(d)})})},a.prototype.markAsDirty=function(i){this.getScene().blockMaterialDirtyMechanism||(a._DirtyCallbackArray.length=0,i&a.TextureDirtyFlag&&a._DirtyCallbackArray.push(a._TextureDirtyCallBack),i&a.LightDirtyFlag&&a._DirtyCallbackArray.push(a._LightsDirtyCallBack),i&a.FresnelDirtyFlag&&a._DirtyCallbackArray.push(a._FresnelDirtyCallBack),i&a.AttributesDirtyFlag&&a._DirtyCallbackArray.push(a._AttributeDirtyCallBack),i&a.MiscDirtyFlag&&a._DirtyCallbackArray.push(a._MiscDirtyCallBack),i&a.PrePassDirtyFlag&&a._DirtyCallbackArray.push(a._PrePassDirtyCallBack),a._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(a._RunDirtyCallBacks),this.getScene().resetCachedMaterial())},a.prototype._markAllSubMeshesAsDirty=function(i){if(!this.getScene().blockMaterialDirtyMechanism)for(var e=this.getScene().meshes,o=0,s=e;o<s.length;o++){var c=s[o];if(!!c.subMeshes)for(var d=0,_=c.subMeshes;d<_.length;d++){var b=_[d];if(b.getMaterial()===this)for(var k=0,j=b._drawWrappers;k<j.length;k++){var $=j[k];!$||!$.defines||!$.defines.markAllAsDirty||this._materialContext===$.materialContext&&i($.defines)}}}},a.prototype._markScenePrePassDirty=function(){if(!this.getScene().blockMaterialDirtyMechanism){var i=this.getScene().enablePrePassRenderer();i&&i.markAsDirty()}},a.prototype._markAllSubMeshesAsAllDirty=function(){this._markAllSubMeshesAsDirty(a._AllDirtyCallBack)},a.prototype._markAllSubMeshesAsImageProcessingDirty=function(){this._markAllSubMeshesAsDirty(a._ImageProcessingDirtyCallBack)},a.prototype._markAllSubMeshesAsTexturesDirty=function(){this._markAllSubMeshesAsDirty(a._TextureDirtyCallBack)},a.prototype._markAllSubMeshesAsFresnelDirty=function(){this._markAllSubMeshesAsDirty(a._FresnelDirtyCallBack)},a.prototype._markAllSubMeshesAsFresnelAndMiscDirty=function(){this._markAllSubMeshesAsDirty(a._FresnelAndMiscDirtyCallBack)},a.prototype._markAllSubMeshesAsLightsDirty=function(){this._markAllSubMeshesAsDirty(a._LightsDirtyCallBack)},a.prototype._markAllSubMeshesAsAttributesDirty=function(){this._markAllSubMeshesAsDirty(a._AttributeDirtyCallBack)},a.prototype._markAllSubMeshesAsMiscDirty=function(){this._markAllSubMeshesAsDirty(a._MiscDirtyCallBack)},a.prototype._markAllSubMeshesAsPrePassDirty=function(){this._markAllSubMeshesAsDirty(a._MiscDirtyCallBack)},a.prototype._markAllSubMeshesAsTexturesAndMiscDirty=function(){this._markAllSubMeshesAsDirty(a._TextureAndMiscDirtyCallBack)},a.prototype.setPrePassRenderer=function(i){return!1},a.prototype.dispose=function(i,e,o){var s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._parentContainer){var c=this._parentContainer.materials.indexOf(this);c>-1&&this._parentContainer.materials.splice(c,1),this._parentContainer=null}if(o!==!0)if(this.meshMap)for(var d in this.meshMap){var _=this.meshMap[d];_&&(_.material=null,this.releaseVertexArrayObject(_,i))}else for(var b=s.meshes,k=0,j=b;k<j.length;k++){var _=j[k];_.material===this&&!_.sourceMesh&&(_.material=null,this.releaseVertexArrayObject(_,i))}this._uniformBuffer.dispose(),i&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear()},a.prototype.releaseVertexArrayObject=function(i,e){if(i.geometry){var o=i.geometry;if(this._storeEffectOnSubMeshes)for(var s=0,c=i.subMeshes;s<c.length;s++){var d=c[s];o._releaseVertexArrayObject(d.effect),e&&d.effect&&d.effect.dispose()}else o._releaseVertexArrayObject(this._drawWrapper.effect)}},a.prototype.serialize=function(){var i=SerializationHelper.Serialize(this);return i.stencil=this.stencil.serialize(),i},a.Parse=function(i,e,o){if(!i.customType)i.customType="BABYLON.StandardMaterial";else if(i.customType==="BABYLON.PBRMaterial"&&i.overloadedAlbedo&&(i.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return Logger$2.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;var s=Tools.Instantiate(i.customType);return s.Parse(i,e,o)},a.TriangleFillMode=0,a.WireFrameFillMode=1,a.PointFillMode=2,a.PointListDrawMode=3,a.LineListDrawMode=4,a.LineLoopDrawMode=5,a.LineStripDrawMode=6,a.TriangleStripDrawMode=7,a.TriangleFanDrawMode=8,a.ClockWiseSideOrientation=0,a.CounterClockWiseSideOrientation=1,a.TextureDirtyFlag=1,a.LightDirtyFlag=2,a.FresnelDirtyFlag=4,a.AttributesDirtyFlag=8,a.MiscDirtyFlag=16,a.PrePassDirtyFlag=32,a.AllDirtyFlag=63,a.MATERIAL_OPAQUE=0,a.MATERIAL_ALPHATEST=1,a.MATERIAL_ALPHABLEND=2,a.MATERIAL_ALPHATESTANDBLEND=3,a.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,a.MATERIAL_NORMALBLENDMETHOD_RNM=1,a._AllDirtyCallBack=function(i){return i.markAllAsDirty()},a._ImageProcessingDirtyCallBack=function(i){return i.markAsImageProcessingDirty()},a._TextureDirtyCallBack=function(i){return i.markAsTexturesDirty()},a._FresnelDirtyCallBack=function(i){return i.markAsFresnelDirty()},a._MiscDirtyCallBack=function(i){return i.markAsMiscDirty()},a._PrePassDirtyCallBack=function(i){return i.markAsPrePassDirty()},a._LightsDirtyCallBack=function(i){return i.markAsLightDirty()},a._AttributeDirtyCallBack=function(i){return i.markAsAttributesDirty()},a._FresnelAndMiscDirtyCallBack=function(i){a._FresnelDirtyCallBack(i),a._MiscDirtyCallBack(i)},a._TextureAndMiscDirtyCallBack=function(i){a._TextureDirtyCallBack(i),a._MiscDirtyCallBack(i)},a._DirtyCallbackArray=[],a._RunDirtyCallBacks=function(i){for(var e=0,o=a._DirtyCallbackArray;e<o.length;e++){var s=o[e];s(i)}},__decorate([serialize()],a.prototype,"id",void 0),__decorate([serialize()],a.prototype,"uniqueId",void 0),__decorate([serialize()],a.prototype,"name",void 0),__decorate([serialize()],a.prototype,"metadata",void 0),__decorate([serialize()],a.prototype,"checkReadyOnEveryCall",void 0),__decorate([serialize()],a.prototype,"checkReadyOnlyOnce",void 0),__decorate([serialize()],a.prototype,"state",void 0),__decorate([serialize("alpha")],a.prototype,"_alpha",void 0),__decorate([serialize("backFaceCulling")],a.prototype,"_backFaceCulling",void 0),__decorate([serialize("cullBackFaces")],a.prototype,"_cullBackFaces",void 0),__decorate([serialize()],a.prototype,"sideOrientation",void 0),__decorate([serialize("alphaMode")],a.prototype,"_alphaMode",void 0),__decorate([serialize()],a.prototype,"_needDepthPrePass",void 0),__decorate([serialize()],a.prototype,"disableDepthWrite",void 0),__decorate([serialize()],a.prototype,"disableColorWrite",void 0),__decorate([serialize()],a.prototype,"forceDepthWrite",void 0),__decorate([serialize()],a.prototype,"depthFunction",void 0),__decorate([serialize()],a.prototype,"separateCullingPass",void 0),__decorate([serialize("fogEnabled")],a.prototype,"_fogEnabled",void 0),__decorate([serialize()],a.prototype,"pointSize",void 0),__decorate([serialize()],a.prototype,"zOffset",void 0),__decorate([serialize()],a.prototype,"zOffsetUnits",void 0),__decorate([serialize()],a.prototype,"pointsCloud",null),__decorate([serialize()],a.prototype,"fillMode",null),__decorate([serialize()],a.prototype,"transparencyMode",null),a}(),MultiMaterial=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o,!0)||this;return o.multiMaterials.push(s),s.subMaterials=new Array,s._storeEffectOnSubMeshes=!0,s}return Object.defineProperty(i.prototype,"subMaterials",{get:function(){return this._subMaterials},set:function(e){this._subMaterials=e,this._hookArray(e)},enumerable:!1,configurable:!0}),i.prototype.getChildren=function(){return this.subMaterials},i.prototype._hookArray=function(e){var o=this,s=e.push;e.push=function(){for(var d=[],_=0;_<arguments.length;_++)d[_]=arguments[_];var b=s.apply(e,d);return o._markAllSubMeshesAsTexturesDirty(),b};var c=e.splice;e.splice=function(d,_){var b=c.apply(e,[d,_]);return o._markAllSubMeshesAsTexturesDirty(),b}},i.prototype.getSubMaterial=function(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.getActiveTextures=function(){var e;return(e=a.prototype.getActiveTextures.call(this)).concat.apply(e,this.subMaterials.map(function(o){return o?o.getActiveTextures():[]}))},i.prototype.hasTexture=function(e){var o;if(a.prototype.hasTexture.call(this,e))return!0;for(var s=0;s<this.subMaterials.length;s++)if(!((o=this.subMaterials[s])===null||o===void 0)&&o.hasTexture(e))return!0;return!1},i.prototype.getClassName=function(){return"MultiMaterial"},i.prototype.isReadyForSubMesh=function(e,o,s){for(var c=0;c<this.subMaterials.length;c++){var d=this.subMaterials[c];if(d){if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(e,o,s))return!1;continue}if(!d.isReady(e))return!1}}return!0},i.prototype.clone=function(e,o){for(var s=new i(e,this.getScene()),c=0;c<this.subMaterials.length;c++){var d=null,_=this.subMaterials[c];o&&_?d=_.clone(e+"-"+_.name):d=this.subMaterials[c],s.subMaterials.push(d)}return s},i.prototype.serialize=function(){var e={};e.name=this.name,e.id=this.id,Tags&&(e.tags=Tags.GetTags(this)),e.materials=[];for(var o=0;o<this.subMaterials.length;o++){var s=this.subMaterials[o];s?e.materials.push(s.id):e.materials.push(null)}return e},i.prototype.dispose=function(e,o,s){var c=this.getScene();if(!!c){if(s)for(var _=0;_<this.subMaterials.length;_++){var d=this.subMaterials[_];d&&d.dispose(e,o)}var _=c.multiMaterials.indexOf(this);_>=0&&c.multiMaterials.splice(_,1),a.prototype.dispose.call(this,e,o)}},i.ParseMultiMaterial=function(e,o){var s=new i(e.name,o);s.id=e.id,Tags&&Tags.AddTagsTo(s,e.tags);for(var c=0;c<e.materials.length;c++){var d=e.materials[c];d?s.subMaterials.push(o.getLastMaterialById(d)):s.subMaterials.push(null)}return s},i}(Material);RegisterClass("BABYLON.MultiMaterial",MultiMaterial);var MeshLODLevel=function(){function a(i,e){this.distanceOrScreenCoverage=i,this.mesh=e}return a}(),_injectLTSMesh=function(a){a.prototype.setMaterialByID=function(i){return this.setMaterialById(i)},a.CreateDisc=a.CreateDisc||function(){throw _WarnImport("MeshBuilder")},a.CreateBox=a.CreateBox||function(){throw _WarnImport("MeshBuilder")},a.CreateSphere=a.CreateSphere||function(){throw _WarnImport("MeshBuilder")},a.CreateCylinder=a.CreateCylinder||function(){throw _WarnImport("MeshBuilder")},a.CreateTorusKnot=a.CreateTorusKnot||function(){throw _WarnImport("MeshBuilder")},a.CreateTorus=a.CreateTorus||function(){throw _WarnImport("MeshBuilder")},a.CreatePlane=a.CreatePlane||function(){throw _WarnImport("MeshBuilder")},a.CreateGround=a.CreateGround||function(){throw _WarnImport("MeshBuilder")},a.CreateTiledGround=a.CreateTiledGround||function(){throw _WarnImport("MeshBuilder")},a.CreateGroundFromHeightMap=a.CreateGroundFromHeightMap||function(){throw _WarnImport("MeshBuilder")},a.CreateTube=a.CreateTube||function(){throw _WarnImport("MeshBuilder")},a.CreatePolyhedron=a.CreatePolyhedron||function(){throw _WarnImport("MeshBuilder")},a.CreateIcoSphere=a.CreateIcoSphere||function(){throw _WarnImport("MeshBuilder")},a.CreateDecal=a.CreateDecal||function(){throw _WarnImport("MeshBuilder")},a.CreateCapsule=a.CreateCapsule||function(){throw _WarnImport("MeshBuilder")},a.ExtendToGoldberg=a.ExtendToGoldberg||function(){throw _WarnImport("MeshBuilder")}},_CreationDataStorage=function(){function a(){}return a}(),_InstanceDataStorage=function(){function a(){this.visibleInstances={},this.batchCache=new _InstancesBatch,this.batchCacheReplacementModeInFrozenMode=new _InstancesBatch,this.instancesBufferSize=32*16*4}return a}(),_InstancesBatch=function(){function a(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array}return a}(),_ThinInstanceDataStorage=function(){function a(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}return a}(),_InternalMeshDataInfo=function(){function a(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0}return a}(),Mesh=function(a){__extends(i,a);function i(e,o,s,c,d,_){o===void 0&&(o=null),s===void 0&&(s=null),c===void 0&&(c=null),_===void 0&&(_=!0);var b=a.call(this,e,o)||this;if(b._internalMeshDataInfo=new _InternalMeshDataInfo,b.delayLoadState=0,b.instances=new Array,b._creationDataStorage=null,b._geometry=null,b._instanceDataStorage=new _InstanceDataStorage,b._thinInstanceDataStorage=new _ThinInstanceDataStorage,b._shouldGenerateFlatShading=!1,b._originalBuilderSideOrientation=i.DEFAULTSIDE,b.overrideMaterialSideOrientation=null,b.ignoreCameraMaxZ=!1,o=b.getScene(),c){if(c._geometry&&c._geometry.applyToMesh(b),DeepCopier.DeepCopy(c,b,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","source","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo"],["_poseMatrix"]),b._internalMeshDataInfo._source=c,o.useClonedMeshMap&&(c._internalMeshDataInfo.meshMap||(c._internalMeshDataInfo.meshMap={}),c._internalMeshDataInfo.meshMap[b.uniqueId]=b),b._originalBuilderSideOrientation=c._originalBuilderSideOrientation,b._creationDataStorage=c._creationDataStorage,c._ranges){var k=c._ranges;for(var e in k)!k.hasOwnProperty(e)||!k[e]||b.createAnimationRange(e,k[e].from,k[e].to)}c.metadata&&c.metadata.clone?b.metadata=c.metadata.clone():b.metadata=c.metadata,Tags&&Tags.HasTags(c)&&Tags.AddTagsTo(b,Tags.GetTags(c,!0)),b.setEnabled(c.isEnabled()),b.parent=c.parent,b.setPivotMatrix(c.getPivotMatrix()),b.id=e+"."+c.id,b.material=c.material;var j;if(!d)for(var $=c.getDescendants(!0),_e=0;_e<$.length;_e++){var et=$[_e];et.clone&&et.clone(e+"."+et.name,b)}if(c.morphTargetManager&&(b.morphTargetManager=c.morphTargetManager),o.getPhysicsEngine){var tt=o.getPhysicsEngine();if(_&&tt){var rt=tt.getImpostorForPhysicsObject(c);rt&&(b.physicsImpostor=rt.clone(b))}}for(j=0;j<o.particleSystems.length;j++){var it=o.particleSystems[j];it.emitter===c&&it.clone(it.name,b)}b.refreshBoundingInfo(),b.computeWorldMatrix(!0)}return s!==null&&(b.parent=s),b._instanceDataStorage.hardwareInstancedRendering=b.getEngine().getCaps().instancedArrays,b._internalMeshDataInfo._onMeshReadyObserverAdded=function(nt){nt.unregisterOnNextCall=!0,b.isReady(!0)?b.onMeshReadyObservable.notifyObservers(b):b._internalMeshDataInfo._checkReadinessObserver||(b._internalMeshDataInfo._checkReadinessObserver=b._scene.onBeforeRenderObservable.add(function(){b.isReady(!0)&&(b._scene.onBeforeRenderObservable.remove(b._internalMeshDataInfo._checkReadinessObserver),b._internalMeshDataInfo._checkReadinessObserver=null,b.onMeshReadyObservable.notifyObservers(b))}))},b.onMeshReadyObservable=new Observable(b._internalMeshDataInfo._onMeshReadyObserverAdded),c&&c.onClonedObservable.notifyObservers(b),b}return i._GetDefaultSideOrientation=function(e){return e||i.FRONTSIDE},Object.defineProperty(i.prototype,"useLODScreenCoverage",{get:function(){return this._internalMeshDataInfo._useLODScreenCoverage},set:function(e){this._internalMeshDataInfo._useLODScreenCoverage=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"computeBonesUsingShaders",{get:function(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders},set:function(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(VertexBuffer.PositionKind,this._internalMeshDataInfo._sourcePositions.slice(),!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(VertexBuffer.NormalKind,this._internalMeshDataInfo._sourceNormals.slice(),!0)),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeRenderObservable",{get:function(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new Observable),this._internalMeshDataInfo._onBeforeRenderObservable},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeBindObservable",{get:function(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new Observable),this._internalMeshDataInfo._onBeforeBindObservable},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onAfterRenderObservable",{get:function(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new Observable),this._internalMeshDataInfo._onAfterRenderObservable},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onBetweenPassObservable",{get:function(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new Observable),this._internalMeshDataInfo._onBetweenPassObservable},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeDrawObservable",{get:function(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new Observable),this._internalMeshDataInfo._onBeforeDrawObservable},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeDraw",{set:function(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasInstances",{get:function(){return this.instances.length>0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasThinInstances",{get:function(){var e;return((e=this._thinInstanceDataStorage.instancesCount)!==null&&e!==void 0?e:0)>0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"forcedInstanceCount",{get:function(){return this._internalMeshDataInfo._forcedInstanceCount},set:function(e){this._internalMeshDataInfo._forcedInstanceCount=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"source",{get:function(){return this._internalMeshDataInfo._source},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cloneMeshMap",{get:function(){return this._internalMeshDataInfo.meshMap},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isUnIndexed",{get:function(){return this._unIndexed},set:function(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.instancesData},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"previousWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.instancesPreviousData},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"manualUpdateOfWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.manualUpdate},set:function(e){this._instanceDataStorage.manualUpdate=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"manualUpdateOfPreviousWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.previousManualUpdate},set:function(e){this._instanceDataStorage.previousManualUpdate=e},enumerable:!1,configurable:!0}),i.prototype.instantiateHierarchy=function(e,o,s){e===void 0&&(e=null);var c=this.getTotalVertices()>0&&(!o||!o.doNotInstantiate)?this.createInstance("instance of "+(this.name||this.id)):this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);c&&(c.parent=e||this.parent,c.position=this.position.clone(),c.scaling=this.scaling.clone(),this.rotationQuaternion?c.rotationQuaternion=this.rotationQuaternion.clone():c.rotation=this.rotation.clone(),s&&s(this,c));for(var d=0,_=this.getChildTransformNodes(!0);d<_.length;d++){var b=_[d];b.instantiateHierarchy(c,o,s)}return c},i.prototype.getClassName=function(){return"Mesh"},Object.defineProperty(i.prototype,"_isMesh",{get:function(){return!0},enumerable:!1,configurable:!0}),i.prototype.toString=function(e){var o=a.prototype.toString.call(this,e);if(o+=", n vertices: "+this.getTotalVertices(),o+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(var s=0;s<this.animations.length;s++)o+=", animation[0]: "+this.animations[s].toString(e);if(e)if(this._geometry){var c=this.getIndices(),d=this.getVerticesData(VertexBuffer.PositionKind);d&&c&&(o+=", flat shading: "+(d.length/3===c.length?"YES":"NO"))}else o+=", flat shading: UNKNOWN";return o},i.prototype._unBindEffect=function(){a.prototype._unBindEffect.call(this);for(var e=0,o=this.instances;e<o.length;e++){var s=o[e];s._unBindEffect()}},Object.defineProperty(i.prototype,"hasLODLevels",{get:function(){return this._internalMeshDataInfo._LODLevels.length>0},enumerable:!1,configurable:!0}),i.prototype.getLODLevels=function(){return this._internalMeshDataInfo._LODLevels},i.prototype._sortLODLevels=function(){var e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(function(o,s){return o.distanceOrScreenCoverage<s.distanceOrScreenCoverage?e:o.distanceOrScreenCoverage>s.distanceOrScreenCoverage?-e:0})},i.prototype.addLODLevel=function(e,o){if(o&&o._masterMesh)return Logger$2.Warn("You cannot use a mesh as LOD level twice"),this;var s=new MeshLODLevel(e,o);return this._internalMeshDataInfo._LODLevels.push(s),o&&(o._masterMesh=this),this._sortLODLevels(),this},i.prototype.getLODLevelAtDistance=function(e){for(var o=this._internalMeshDataInfo,s=0;s<o._LODLevels.length;s++){var c=o._LODLevels[s];if(c.distanceOrScreenCoverage===e)return c.mesh}return null},i.prototype.removeLODLevel=function(e){for(var o=this._internalMeshDataInfo,s=0;s<o._LODLevels.length;s++)o._LODLevels[s].mesh===e&&(o._LODLevels.splice(s,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this},i.prototype.getLOD=function(e,o){var s=this._internalMeshDataInfo;if(!s._LODLevels||s._LODLevels.length===0)return this;var c;if(o)c=o;else{var d=this.getBoundingInfo();c=d.boundingSphere}var _=c.centerWorld.subtract(e.globalPosition).length(),b=s._useLODScreenCoverage,k=_,j=1;if(b){var $=e.screenArea,_e=c.radiusWorld*e.minZ/_;_e=_e*_e*Math.PI,k=_e/$,j=-1}if(j*s._LODLevels[s._LODLevels.length-1].distanceOrScreenCoverage>j*k)return this.onLODLevelSelection&&this.onLODLevelSelection(k,this,this),this;for(var et=0;et<s._LODLevels.length;et++){var tt=s._LODLevels[et];if(j*tt.distanceOrScreenCoverage<j*k){if(tt.mesh){if(tt.mesh.delayLoadState===4)return tt.mesh._checkDelayState(),this;if(tt.mesh.delayLoadState===2)return this;tt.mesh._preActivate(),tt.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(k,this,tt.mesh),tt.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(k,this,this),this},Object.defineProperty(i.prototype,"geometry",{get:function(){return this._geometry},enumerable:!1,configurable:!0}),i.prototype.getTotalVertices=function(){return this._geometry===null||this._geometry===void 0?0:this._geometry.getTotalVertices()},i.prototype.getVerticesData=function(e,o,s){var c,d;if(!this._geometry)return null;var _=(d=(c=this._userInstancedBuffersStorage)===null||c===void 0?void 0:c.vertexBuffers[e])===null||d===void 0?void 0:d.getFloatData(this._geometry.getTotalVertices(),s||o&&this._geometry.meshes.length!==1);return _||(_=this._geometry.getVerticesData(e,o,s)),_},i.prototype.getVertexBuffer=function(e){var o,s;return this._geometry?(s=(o=this._userInstancedBuffersStorage)===null||o===void 0?void 0:o.vertexBuffers[e])!==null&&s!==void 0?s:this._geometry.getVertexBuffer(e):null},i.prototype.isVerticesDataPresent=function(e){var o;return this._geometry?((o=this._userInstancedBuffersStorage)===null||o===void 0?void 0:o.vertexBuffers[e])!==void 0||this._geometry.isVerticesDataPresent(e):this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1},i.prototype.isVertexBufferUpdatable=function(e){var o,s;return this._geometry?((s=(o=this._userInstancedBuffersStorage)===null||o===void 0?void 0:o.vertexBuffers[e])===null||s===void 0?void 0:s.isUpdatable())||this._geometry.isVertexBufferUpdatable(e):this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1},i.prototype.getVerticesDataKinds=function(){if(!this._geometry){var e=new Array;return this._delayInfo&&this._delayInfo.forEach(function(c){e.push(c)}),e}var o=this._geometry.getVerticesDataKinds();if(this._userInstancedBuffersStorage)for(var s in this._userInstancedBuffersStorage.vertexBuffers)o.push(s);return o},i.prototype.getTotalIndices=function(){return this._geometry?this._geometry.getTotalIndices():0},i.prototype.getIndices=function(e,o){return this._geometry?this._geometry.getIndices(e,o):[]},Object.defineProperty(i.prototype,"isBlocked",{get:function(){return this._masterMesh!==null&&this._masterMesh!==void 0},enumerable:!1,configurable:!0}),i.prototype.isReady=function(e,o){var s,c,d,_,b,k;if(e===void 0&&(e=!1),o===void 0&&(o=!1),this.delayLoadState===2||!a.prototype.isReady.call(this,e))return!1;if(!this.subMeshes||this.subMeshes.length===0||!e)return!0;var j=this.getEngine(),$=this.getScene(),_e=o||j.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();var et=this.material||$.defaultMaterial;if(et){if(et._storeEffectOnSubMeshes)for(var tt=0,rt=this.subMeshes;tt<rt.length;tt++){var it=rt[tt],nt=it.getMaterial();if(nt){if(nt._storeEffectOnSubMeshes){if(!nt.isReadyForSubMesh(this,it,_e))return!1}else if(!nt.isReady(this,_e))return!1}}else if(!et.isReady(this,_e))return!1}for(var ot=j.currentRenderPassId,at=0,st=this.lightSources;at<st.length;at++){var ut=st[at],ft=ut.getShadowGenerator();if(ft&&(!(!((s=ft.getShadowMap())===null||s===void 0)&&s.renderList)||((c=ft.getShadowMap())===null||c===void 0?void 0:c.renderList)&&((_=(d=ft.getShadowMap())===null||d===void 0?void 0:d.renderList)===null||_===void 0?void 0:_.indexOf(this))!==-1)){ft.getShadowMap()&&(j.currentRenderPassId=ft.getShadowMap().renderPassId);for(var lt=0,ht=this.subMeshes;lt<ht.length;lt++){var it=ht[lt];if(!ft.isReady(it,_e,(k=(b=it.getMaterial())===null||b===void 0?void 0:b.needAlphaBlendingForMesh(this))!==null&&k!==void 0?k:!1))return j.currentRenderPassId=ot,!1}j.currentRenderPassId=ot}}for(var pt=0,mt=this._internalMeshDataInfo._LODLevels;pt<mt.length;pt++){var dt=mt[pt];if(dt.mesh&&!dt.mesh.isReady(_e))return!1}return!0},Object.defineProperty(i.prototype,"areNormalsFrozen",{get:function(){return this._internalMeshDataInfo._areNormalsFrozen},enumerable:!1,configurable:!0}),i.prototype.freezeNormals=function(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this},i.prototype.unfreezeNormals=function(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this},Object.defineProperty(i.prototype,"overridenInstanceCount",{set:function(e){this._instanceDataStorage.overridenInstanceCount=e},enumerable:!1,configurable:!0}),i.prototype._preActivate=function(){var e=this._internalMeshDataInfo,o=this.getScene().getRenderId();return e._preActivateId===o?this:(e._preActivateId=o,this._instanceDataStorage.visibleInstances=null,this)},i.prototype._preActivateForIntermediateRendering=function(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this},i.prototype._registerInstanceForRenderId=function(e,o){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:o,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[o]||(this._instanceDataStorage.previousRenderId!==void 0&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=o,this._instanceDataStorage.visibleInstances[o]=new Array),this._instanceDataStorage.visibleInstances[o].push(e),this},i.prototype._afterComputeWorldMatrix=function(){a.prototype._afterComputeWorldMatrix.call(this),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))},i.prototype._postActivate=function(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))},i.prototype.refreshBoundingInfo=function(e,o){if(e===void 0&&(e=!1),o===void 0&&(o=!0),this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;var s=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,o),s),this},i.prototype._createGlobalSubMesh=function(e){var o=this.getTotalVertices();if(!o||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){var s=this.getIndices();if(!s)return null;var c=s.length,d=!1;if(e)d=!0;else for(var _=0,b=this.subMeshes;_<b.length;_++){var k=b[_];if(k.indexStart+k.indexCount>c){d=!0;break}if(k.verticesStart+k.verticesCount>o){d=!0;break}}if(!d)return this.subMeshes[0]}return this.releaseSubMeshes(),new SubMesh(0,0,o,0,this.getTotalIndices(),this)},i.prototype.subdivide=function(e){if(!(e<1)){for(var o=this.getTotalIndices(),s=o/e|0,c=0;s%3!==0;)s++;this.releaseSubMeshes();for(var d=0;d<e&&!(c>=o);d++)SubMesh.CreateFromIndices(0,c,d===e-1?o-c:s,this),c+=s;this.synchronizeInstances()}},i.prototype.setVerticesData=function(e,o,s,c){if(s===void 0&&(s=!1),this._geometry)this._geometry.setVerticesData(e,o,s,c);else{var d=new VertexData;d.set(o,e);var _=this.getScene();new Geometry(Geometry.RandomId(),_,d,s,this)}return this},i.prototype.removeVerticesData=function(e){!this._geometry||this._geometry.removeVerticesData(e)},i.prototype.markVerticesDataAsUpdatable=function(e,o){o===void 0&&(o=!0);var s=this.getVertexBuffer(e);!s||s.isUpdatable()===o||this.setVerticesData(e,this.getVerticesData(e),o)},i.prototype.setVerticesBuffer=function(e,o){return o===void 0&&(o=!0),this._geometry||(this._geometry=Geometry.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,o),this},i.prototype.updateVerticesData=function(e,o,s,c){return this._geometry?(c?(this.makeGeometryUnique(),this.updateVerticesData(e,o,s,!1)):this._geometry.updateVerticesData(e,o,s),this):this},i.prototype.updateMeshPositions=function(e,o){o===void 0&&(o=!0);var s=this.getVerticesData(VertexBuffer.PositionKind);if(!s)return this;if(e(s),this.updateVerticesData(VertexBuffer.PositionKind,s,!1,!1),o){var c=this.getIndices(),d=this.getVerticesData(VertexBuffer.NormalKind);if(!d)return this;VertexData.ComputeNormals(s,c,d),this.updateVerticesData(VertexBuffer.NormalKind,d,!1,!1)}return this},i.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;var e=this._geometry,o=this._geometry.copy(Geometry.RandomId());return e.releaseForMesh(this,!0),o.applyToMesh(this),this},i.prototype.setIndices=function(e,o,s){if(o===void 0&&(o=null),s===void 0&&(s=!1),this._geometry)this._geometry.setIndices(e,o,s);else{var c=new VertexData;c.indices=e;var d=this.getScene();new Geometry(Geometry.RandomId(),d,c,s,this)}return this},i.prototype.updateIndices=function(e,o,s){return s===void 0&&(s=!1),this._geometry?(this._geometry.updateIndices(e,o,s),this):this},i.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},i.prototype._bind=function(e,o,s){if(!this._geometry)return this;var c=this.getScene().getEngine();this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(o);var d;if(this._unIndexed)d=null;else switch(s){case Material.PointFillMode:d=null;break;case Material.WireFrameFillMode:d=e._getLinesIndexBuffer(this.getIndices(),c);break;default:case Material.TriangleFillMode:d=this._geometry.getIndexBuffer();break}return!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(o,d):this._geometry._bind(o,d,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),this},i.prototype._draw=function(e,o,s){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);var c=this.getScene(),d=c.getEngine();return this._unIndexed||o==Material.PointFillMode?d.drawArraysType(o,e.verticesStart,e.verticesCount,this.forcedInstanceCount||s):o==Material.WireFrameFillMode?d.drawElementsType(o,0,e._linesIndexCount,this.forcedInstanceCount||s):d.drawElementsType(o,e.indexStart,e.indexCount,this.forcedInstanceCount||s),this},i.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},i.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},i.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},i.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},i.prototype._getInstancesRenderList=function(e,o){if(o===void 0&&(o=!1),this._instanceDataStorage.isFrozen){if(o)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}var s=this.getScene(),c=s._isInIntermediateRendering(),d=c?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,_=this._instanceDataStorage.batchCache;if(_.mustReturn=!1,_.renderSelf[e]=o||!d&&this.isEnabled()&&this.isVisible,_.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!o){var b=this._instanceDataStorage.visibleInstances,k=s.getRenderId(),j=c?b.intermediateDefaultRenderId:b.defaultRenderId;_.visibleInstances[e]=b[k],!_.visibleInstances[e]&&j&&(_.visibleInstances[e]=b[j])}return _.hardwareInstancedRendering[e]=!o&&this._instanceDataStorage.hardwareInstancedRendering&&_.visibleInstances[e]!==null&&_.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=_,_},i.prototype._renderWithInstances=function(e,o,s,c,d){var _,b=s.visibleInstances[e._id];if(!b)return this;for(var k=this._instanceDataStorage,j=k.instancesBufferSize,$=k.instancesBuffer,_e=k.instancesPreviousBuffer,et=b.length+1,tt=et*16*4;k.instancesBufferSize<tt;)k.instancesBufferSize*=2;(!k.instancesData||j!=k.instancesBufferSize)&&(k.instancesData=new Float32Array(k.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!k.instancesPreviousData||j!=k.instancesBufferSize)&&(k.instancesPreviousData=new Float32Array(k.instancesBufferSize/4));var rt=0,it=0,nt=s.renderSelf[e._id],ot=!$||j!==k.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!k.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!k.isFrozen||ot)){var at=this._effectiveMesh.getWorldMatrix();if(nt&&(this._scene.needsPreviousWorldMatrices&&(k.masterMeshPreviousWorldMatrix?(k.masterMeshPreviousWorldMatrix.copyToArray(k.instancesPreviousData,rt),k.masterMeshPreviousWorldMatrix.copyFrom(at)):(k.masterMeshPreviousWorldMatrix=at.clone(),k.masterMeshPreviousWorldMatrix.copyToArray(k.instancesPreviousData,rt))),at.copyToArray(k.instancesData,rt),rt+=16,it++),b){if(i.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&((_=e.getMaterial())===null||_===void 0?void 0:_.needAlphaBlendingForMesh(e.getRenderingMesh()))){for(var st=this._scene.activeCamera.globalPosition,ut=0;ut<b.length;ut++){var ft=b[ut];ft._distanceToCamera=Vector3.Distance(ft.getBoundingInfo().boundingSphere.centerWorld,st)}b.sort(function(mt,dt){return mt._distanceToCamera>dt._distanceToCamera?-1:mt._distanceToCamera<dt._distanceToCamera?1:0})}for(var lt=0;lt<b.length;lt++){var ht=b[lt],pt=ht.getWorldMatrix();pt.copyToArray(k.instancesData,rt),this._scene.needsPreviousWorldMatrices&&(ht._previousWorldMatrix?(ht._previousWorldMatrix.copyToArray(k.instancesPreviousData,rt),ht._previousWorldMatrix.copyFrom(pt)):(ht._previousWorldMatrix=pt.clone(),ht._previousWorldMatrix.copyToArray(k.instancesPreviousData,rt))),rt+=16,it++}}}else it=(nt?1:0)+b.length;return ot?($&&$.dispose(),_e&&_e.dispose(),$=new Buffer(d,k.instancesData,!0,16,!1,!0),k.instancesBuffer=$,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=$.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=$.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=$.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=$.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(_e=new Buffer(d,k.instancesPreviousData,!0,16,!1,!0),k.instancesPreviousBuffer=_e,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=_e.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=_e.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=_e.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=_e.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):this._instanceDataStorage.isFrozen||($.updateDirectly(k.instancesData,0,it),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&_e.updateDirectly(k.instancesPreviousData,0,it)),this._processInstancedBuffers(b,nt),this.getScene()._activeIndices.addCount(e.indexCount*it,!1),d._currentDrawContext&&(d._currentDrawContext.useInstancing=!0),this._bind(e,c,o),this._draw(e,o,it),this._scene.needsPreviousWorldMatrices&&!ot&&this._instanceDataStorage.manualUpdate&&!this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.previousManualUpdate&&_e.updateDirectly(k.instancesData,0,it),d.unbindInstanceAttributes(),this},i.prototype._renderWithThinInstances=function(e,o,s,c){var d,_,b=(_=(d=this._thinInstanceDataStorage)===null||d===void 0?void 0:d.instancesCount)!==null&&_!==void 0?_:0;this.getScene()._activeIndices.addCount(e.indexCount*b,!1),c._currentDrawContext&&(c._currentDrawContext.useInstancing=!0),this._bind(e,s,o),this._draw(e,o,b),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,b):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),c.unbindInstanceAttributes()},i.prototype._processInstancedBuffers=function(e,o){},i.prototype._processRendering=function(e,o,s,c,d,_,b,k){var j=this.getScene(),$=j.getEngine();if(_&&o.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(o,c,s,$),this;if(_)this._renderWithInstances(o,c,d,s,$);else{$._currentDrawContext&&($._currentDrawContext.useInstancing=!1);var _e=0;d.renderSelf[o._id]&&(b&&b(!1,e._effectiveMesh.getWorldMatrix(),k,e._effectiveMesh),_e++,this._draw(o,c,this._instanceDataStorage.overridenInstanceCount));var et=d.visibleInstances[o._id];if(et){var tt=et.length;_e+=tt;for(var rt=0;rt<tt;rt++){var it=et[rt],nt=it.getWorldMatrix();b&&b(!0,nt,k),this._draw(o,c)}}j._activeIndices.addCount(o.indexCount*_e,!1)}return this},i.prototype._rebuild=function(e){if(e===void 0&&(e=!1),this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(var o in this._userInstancedBuffersStorage.vertexBuffers){var s=this._userInstancedBuffersStorage.vertexBuffers[o];s&&(e&&s.dispose(),this._userInstancedBuffersStorage.vertexBuffers[o]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,a.prototype._rebuild.call(this,e)},i.prototype._freeze=function(){if(!!this.subMeshes){for(var e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}},i.prototype._unFreeze=function(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null},i.prototype.render=function(e,o,s){var c,d,_,b=this.getScene();if(this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1,this._checkOcclusionQuery())return this;var k=this._getInstancesRenderList(e._id,!!s);if(k.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;var j=b.getEngine(),$=0,_e=null;this.ignoreCameraMaxZ&&b.activeCamera&&!b._isInIntermediateRendering()&&($=b.activeCamera.maxZ,_e=b.activeCamera,b.activeCamera.maxZ=0,b.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);var et=k.hardwareInstancedRendering[e._id]||e.getRenderingMesh().hasThinInstances,tt=this._instanceDataStorage,rt=e.getMaterial();if(!rt)return _e&&(_e.maxZ=$,b.updateTransformMatrix(!0)),this;if(!tt.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==rt){if(rt._storeEffectOnSubMeshes){if(!rt.isReadyForSubMesh(this,e,et))return _e&&(_e.maxZ=$,b.updateTransformMatrix(!0)),this}else if(!rt.isReady(this,et))return _e&&(_e.maxZ=$,b.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=rt}else if(rt._storeEffectOnSubMeshes&&!(!((c=e.effect)===null||c===void 0)&&c._wasPreviouslyReady)||!rt._storeEffectOnSubMeshes&&!(!((d=rt.getEffect())===null||d===void 0)&&d._wasPreviouslyReady))return _e&&(_e.maxZ=$,b.updateTransformMatrix(!0)),this;o&&j.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);var it;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?it=e._drawWrapper:it=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();for(var nt=(_=it==null?void 0:it.effect)!==null&&_!==void 0?_:null,ot=0,at=b._beforeRenderingMeshStage;ot<at.length;ot++){var st=at[ot];st.action(this,e,k,nt)}if(!it||!nt)return _e&&(_e.maxZ=$,b.updateTransformMatrix(!0)),this;var ut=s||this._effectiveMesh,ft;if(!tt.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null)){var lt=ut._getWorldMatrixDeterminant();ft=this.overrideMaterialSideOrientation,ft==null&&(ft=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),lt<0&&(ft=ft===Material.ClockWiseSideOrientation?Material.CounterClockWiseSideOrientation:Material.ClockWiseSideOrientation),tt.sideOrientation=ft}else ft=tt.sideOrientation;var ht=this._internalMeshDataInfo._effectiveMaterial._preBind(it,ft);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&j.setDepthWrite(!0);var pt=b.forcePointsCloud?Material.PointFillMode:b.forceWireframe?Material.WireFrameFillMode:this._internalMeshDataInfo._effectiveMaterial.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),et||this._bind(e,nt,pt);var mt=this._internalMeshDataInfo._effectiveMaterial,dt=ut.getWorldMatrix();mt._storeEffectOnSubMeshes?mt.bindForSubMesh(dt,this,e):mt.bind(dt,this),!mt.backFaceCulling&&mt.separateCullingPass&&(j.setState(!0,mt.zOffset,!1,!ht,mt.cullBackFaces,mt.stencil,mt.zOffsetUnits),this._processRendering(this,e,nt,pt,k,et,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),j.setState(!0,mt.zOffset,!1,ht,mt.cullBackFaces,mt.stencil,mt.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,nt,pt,k,et,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(var gt=0,_t=b._afterRenderingMeshStage;gt<_t.length;gt++){var st=_t[gt];st.action(this,e,k,nt)}return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),_e&&(_e.maxZ=$,b.updateTransformMatrix(!0)),this},i.prototype._onBeforeDraw=function(e,o,s){e&&s&&s.bindOnlyWorldMatrix(o)},i.prototype.cleanMatrixWeights=function(){this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)&&(this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)?this.normalizeSkinWeightsAndExtra():this.normalizeSkinFourWeights())},i.prototype.normalizeSkinFourWeights=function(){for(var e=this.getVerticesData(VertexBuffer.MatricesWeightsKind),o=e.length,s=0;s<o;s+=4){var c=e[s]+e[s+1]+e[s+2]+e[s+3];if(c===0)e[s]=1;else{var d=1/c;e[s]*=d,e[s+1]*=d,e[s+2]*=d,e[s+3]*=d}}this.setVerticesData(VertexBuffer.MatricesWeightsKind,e)},i.prototype.normalizeSkinWeightsAndExtra=function(){for(var e=this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind),o=this.getVerticesData(VertexBuffer.MatricesWeightsKind),s=o.length,c=0;c<s;c+=4){var d=o[c]+o[c+1]+o[c+2]+o[c+3];if(d+=e[c]+e[c+1]+e[c+2]+e[c+3],d===0)o[c]=1;else{var _=1/d;o[c]*=_,o[c+1]*=_,o[c+2]*=_,o[c+3]*=_,e[c]*=_,e[c+1]*=_,e[c+2]*=_,e[c+3]*=_}}this.setVerticesData(VertexBuffer.MatricesWeightsKind,o),this.setVerticesData(VertexBuffer.MatricesWeightsKind,e)},i.prototype.validateSkinning=function(){var e=this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind),o=this.getVerticesData(VertexBuffer.MatricesWeightsKind);if(o===null||this.skeleton==null)return{skinned:!1,valid:!0,report:"not skinned"};for(var s=o.length,c=0,d=0,_=0,b=0,k=e===null?4:8,j=new Array,$=0;$<=k;$++)j[$]=0;for(var _e=.001,$=0;$<s;$+=4){for(var et=o[$],tt=et,rt=tt===0?0:1,it=1;it<k;it++){var nt=it<4?o[$+it]:e[$+it-4];nt>et&&c++,nt!==0&&rt++,tt+=nt,et=nt}if(j[rt]++,rt>_&&(_=rt),tt===0)d++;else{var ot=1/tt,at=0;for(it=0;it<k;it++)it<4?at+=Math.abs(o[$+it]-o[$+it]*ot):at+=Math.abs(e[$+it-4]-e[$+it-4]*ot);at>_e&&b++}}for(var st=this.skeleton.bones.length,ut=this.getVerticesData(VertexBuffer.MatricesIndicesKind),ft=this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind),lt=0,$=0;$<s;$+=4)for(var it=0;it<k;it++){var ht=it<4?ut[$+it]:ft[$+it-4];(ht>=st||ht<0)&&lt++}var pt="Number of Weights = "+s/4+`
  785. Maximum influences = `+_+`
  786. Missing Weights = `+d+`
  787. Not Sorted = `+c+`
  788. Not Normalized = `+b+`
  789. WeightCounts = [`+j+`]
  790. Number of bones = `+st+`
  791. Bad Bone Indices = `+lt;return{skinned:!0,valid:d===0&&b===0&&lt===0,report:pt}},i.prototype._checkDelayState=function(){var e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this},i.prototype._queueLoad=function(e){var o=this;e._addPendingData(this);var s=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return Tools.LoadFile(this.delayLoadingFile,function(c){c instanceof ArrayBuffer?o._delayLoadingFunction(c,o):o._delayLoadingFunction(JSON.parse(c),o),o.instances.forEach(function(d){d.refreshBoundingInfo(),d._syncSubMeshes()}),o.delayLoadState=1,e._removePendingData(o)},function(){},e.offlineProvider,s),this},i.prototype.isInFrustum=function(e){return this.delayLoadState===2||!a.prototype.isInFrustum.call(this,e)?!1:(this._checkDelayState(),!0)},i.prototype.setMaterialById=function(e){var o=this.getScene().materials,s;for(s=o.length-1;s>-1;s--)if(o[s].id===e)return this.material=o[s],this;var c=this.getScene().multiMaterials;for(s=c.length-1;s>-1;s--)if(c[s].id===e)return this.material=c[s],this;return this},i.prototype.getAnimatables=function(){var e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},i.prototype.bakeTransformIntoVertices=function(e){if(!this.isVerticesDataPresent(VertexBuffer.PositionKind))return this;var o=this.subMeshes.splice(0);this._resetPointsArrayCache();var s=this.getVerticesData(VertexBuffer.PositionKind),c=new Array,d;for(d=0;d<s.length;d+=3)Vector3.TransformCoordinates(Vector3.FromArray(s,d),e).toArray(c,d);if(this.setVerticesData(VertexBuffer.PositionKind,c,this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()),this.isVerticesDataPresent(VertexBuffer.NormalKind)){for(s=this.getVerticesData(VertexBuffer.NormalKind),c=[],d=0;d<s.length;d+=3)Vector3.TransformNormal(Vector3.FromArray(s,d),e).normalize().toArray(c,d);this.setVerticesData(VertexBuffer.NormalKind,c,this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=o,this},i.prototype.bakeCurrentTransformIntoVertices=function(e){return e===void 0&&(e=!0),this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this},Object.defineProperty(i.prototype,"_positions",{get:function(){return this._internalAbstractMeshDataInfo._positions?this._internalAbstractMeshDataInfo._positions:this._geometry?this._geometry._positions:null},enumerable:!1,configurable:!0}),i.prototype._resetPointsArrayCache=function(){return this._geometry&&this._geometry._resetPointsArrayCache(),this},i.prototype._generatePointsArray=function(){return this._geometry?this._geometry._generatePointsArray():!1},i.prototype.clone=function(e,o,s,c){return e===void 0&&(e=""),o===void 0&&(o=null),c===void 0&&(c=!0),new i(e,this.getScene(),o,this,s,c)},i.prototype.dispose=function(e,o){o===void 0&&(o=!1),this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);var s=this._internalMeshDataInfo;if(s._onBeforeDrawObservable&&s._onBeforeDrawObservable.clear(),s._onBeforeBindObservable&&s._onBeforeBindObservable.clear(),s._onBeforeRenderObservable&&s._onBeforeRenderObservable.clear(),s._onAfterRenderObservable&&s._onAfterRenderObservable.clear(),s._onBetweenPassObservable&&s._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(s.meshMap)for(var c in s.meshMap){var d=s.meshMap[c];d&&(d._internalMeshDataInfo._source=null,s.meshMap[c]=void 0)}s._source&&s._source._internalMeshDataInfo.meshMap&&(s._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else for(var _=this.getScene().meshes,b=0,k=_;b<k.length;b++){var j=k[b],d=j;d._internalMeshDataInfo&&d._internalMeshDataInfo._source&&d._internalMeshDataInfo._source===this&&(d._internalMeshDataInfo._source=null)}s._source=null,this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),a.prototype.dispose.call(this,e,o)},i.prototype._disposeInstanceSpecificData=function(){},i.prototype._disposeThinInstanceSpecificData=function(){},i.prototype._invalidateInstanceVertexArrayObject=function(){},i.prototype.applyDisplacementMap=function(e,o,s,c,d,_,b){var k=this;b===void 0&&(b=!1);var j=this.getScene(),$=function(_e){var et=_e.width,tt=_e.height,rt=k.getEngine().createCanvas(et,tt),it=rt.getContext("2d");it.drawImage(_e,0,0);var nt=it.getImageData(0,0,et,tt).data;k.applyDisplacementMapFromBuffer(nt,et,tt,o,s,d,_,b),c&&c(k)};return Tools.LoadImage(e,$,function(){},j.offlineProvider),this},i.prototype.applyDisplacementMapFromBuffer=function(e,o,s,c,d,_,b,k){if(k===void 0&&(k=!1),!this.isVerticesDataPresent(VertexBuffer.PositionKind)||!this.isVerticesDataPresent(VertexBuffer.NormalKind)||!this.isVerticesDataPresent(VertexBuffer.UVKind))return Logger$2.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;var j=this.getVerticesData(VertexBuffer.PositionKind,!0,!0),$=this.getVerticesData(VertexBuffer.NormalKind),_e=this.getVerticesData(VertexBuffer.UVKind),et=Vector3.Zero(),tt=Vector3.Zero(),rt=Vector2.Zero();_=_||Vector2.Zero(),b=b||new Vector2(1,1);for(var it=0;it<j.length;it+=3){Vector3.FromArrayToRef(j,it,et),Vector3.FromArrayToRef($,it,tt),Vector2.FromArrayToRef(_e,it/3*2,rt);var nt=Math.abs(rt.x*b.x+_.x%1)*(o-1)%o|0,ot=Math.abs(rt.y*b.y+_.y%1)*(s-1)%s|0,at=(nt+ot*o)*4,st=e[at]/255,ut=e[at+1]/255,ft=e[at+2]/255,lt=st*.3+ut*.59+ft*.11;tt.normalize(),tt.scaleInPlace(c+(d-c)*lt),et=et.add(tt),et.toArray(j,it)}return VertexData.ComputeNormals(j,this.getIndices(),$),k?(this.setVerticesData(VertexBuffer.PositionKind,j),this.setVerticesData(VertexBuffer.NormalKind,$),this.setVerticesData(VertexBuffer.UVKind,_e)):(this.updateVerticesData(VertexBuffer.PositionKind,j),this.updateVerticesData(VertexBuffer.NormalKind,$)),this},i.prototype.convertToFlatShadedMesh=function(){var e=this.getVerticesDataKinds(),o={},s={},c={},d=!1,_,b;for(_=0;_<e.length;_++){b=e[_];var k=this.getVertexBuffer(b);if(b===VertexBuffer.NormalKind){d=k.isUpdatable(),e.splice(_,1),_--;continue}o[b]=k,s[b]=this.getVerticesData(b),c[b]=[]}var j=this.subMeshes.slice(0),$=this.getIndices(),_e=this.getTotalIndices(),et;for(et=0;et<_e;et++){var tt=$[et];for(_=0;_<e.length;_++){b=e[_];for(var rt=o[b].getStrideSize(),it=0;it<rt;it++)c[b].push(s[b][tt*rt+it])}}var nt=[],ot=c[VertexBuffer.PositionKind],at=this.getScene().useRightHandedSystem,st;for(at?st=this.overrideMaterialSideOrientation===1:st=this.overrideMaterialSideOrientation===0,et=0;et<_e;et+=3){$[et]=et,$[et+1]=et+1,$[et+2]=et+2;var ut=Vector3.FromArray(ot,et*3),ft=Vector3.FromArray(ot,(et+1)*3),lt=Vector3.FromArray(ot,(et+2)*3),ht=ut.subtract(ft),pt=lt.subtract(ft),mt=Vector3.Normalize(Vector3.Cross(ht,pt));st&&mt.scaleInPlace(-1);for(var dt=0;dt<3;dt++)nt.push(mt.x),nt.push(mt.y),nt.push(mt.z)}for(this.setIndices($),this.setVerticesData(VertexBuffer.NormalKind,nt,d),_=0;_<e.length;_++)b=e[_],this.setVerticesData(b,c[b],o[b].isUpdatable());this.releaseSubMeshes();for(var gt=0;gt<j.length;gt++){var _t=j[gt];SubMesh.AddToMesh(_t.materialIndex,_t.indexStart,_t.indexCount,_t.indexStart,_t.indexCount,this)}return this.synchronizeInstances(),this},i.prototype.convertToUnIndexedMesh=function(){var e=this.getVerticesDataKinds(),o={},s={},c={},d,_;for(d=0;d<e.length;d++){_=e[d];var b=this.getVertexBuffer(_);o[_]=b,s[_]=o[_].getData(),c[_]=[]}var k=this.subMeshes.slice(0),j=this.getIndices(),$=this.getTotalIndices(),_e;for(_e=0;_e<$;_e++){var et=j[_e];for(d=0;d<e.length;d++){_=e[d];for(var tt=o[_].getStrideSize(),rt=0;rt<tt;rt++)c[_].push(s[_][et*tt+rt])}}for(_e=0;_e<$;_e+=3)j[_e]=_e,j[_e+1]=_e+1,j[_e+2]=_e+2;for(this.setIndices(j),d=0;d<e.length;d++)_=e[d],this.setVerticesData(_,c[_],o[_].isUpdatable());this.releaseSubMeshes();for(var it=0;it<k.length;it++){var nt=k[it];SubMesh.AddToMesh(nt.materialIndex,nt.indexStart,nt.indexCount,nt.indexStart,nt.indexCount,this)}return this._unIndexed=!0,this.synchronizeInstances(),this},i.prototype.flipFaces=function(e){e===void 0&&(e=!1);var o=VertexData.ExtractFromMesh(this),s;if(e&&this.isVerticesDataPresent(VertexBuffer.NormalKind)&&o.normals)for(s=0;s<o.normals.length;s++)o.normals[s]*=-1;if(o.indices){var c;for(s=0;s<o.indices.length;s+=3)c=o.indices[s+1],o.indices[s+1]=o.indices[s+2],o.indices[s+2]=c}return o.applyToMesh(this,this.isVertexBufferUpdatable(VertexBuffer.PositionKind)),this},i.prototype.increaseVertices=function(e){var o=VertexData.ExtractFromMesh(this),s=o.uvs&&!Array.isArray(o.uvs)&&Array.from?Array.from(o.uvs):o.uvs,c=o.indices&&!Array.isArray(o.indices)&&Array.from?Array.from(o.indices):o.indices,d=o.positions&&!Array.isArray(o.positions)&&Array.from?Array.from(o.positions):o.positions,_=o.normals&&!Array.isArray(o.normals)&&Array.from?Array.from(o.normals):o.normals;if(!c||!d||!_||!s)Logger$2.Warn("VertexData contains null entries");else{o.indices=c,o.positions=d,o.normals=_,o.uvs=s;for(var b=e+1,k=new Array,j=0;j<b+1;j++)k[j]=new Array;for(var $,_e,et=new Vector3(0,0,0),tt=new Vector3(0,0,0),rt=new Vector2(0,0),it=new Array,nt=new Array,ot=new Array,at,st=d.length,ut=s.length,j=0;j<c.length;j+=3){nt[0]=c[j],nt[1]=c[j+1],nt[2]=c[j+2];for(var ft=0;ft<3;ft++)if($=nt[ft],_e=nt[(ft+1)%3],ot[$]===void 0&&ot[_e]===void 0?(ot[$]=new Array,ot[_e]=new Array):(ot[$]===void 0&&(ot[$]=new Array),ot[_e]===void 0&&(ot[_e]=new Array)),ot[$][_e]===void 0&&ot[_e][$]===void 0){ot[$][_e]=[],et.x=(d[3*_e]-d[3*$])/b,et.y=(d[3*_e+1]-d[3*$+1])/b,et.z=(d[3*_e+2]-d[3*$+2])/b,tt.x=(_[3*_e]-_[3*$])/b,tt.y=(_[3*_e+1]-_[3*$+1])/b,tt.z=(_[3*_e+2]-_[3*$+2])/b,rt.x=(s[2*_e]-s[2*$])/b,rt.y=(s[2*_e+1]-s[2*$+1])/b,ot[$][_e].push($);for(var lt=1;lt<b;lt++)ot[$][_e].push(d.length/3),d[st]=d[3*$]+lt*et.x,_[st++]=_[3*$]+lt*tt.x,d[st]=d[3*$+1]+lt*et.y,_[st++]=_[3*$+1]+lt*tt.y,d[st]=d[3*$+2]+lt*et.z,_[st++]=_[3*$+2]+lt*tt.z,s[ut++]=s[2*$]+lt*rt.x,s[ut++]=s[2*$+1]+lt*rt.y;ot[$][_e].push(_e),ot[_e][$]=new Array,at=ot[$][_e].length;for(var ht=0;ht<at;ht++)ot[_e][$][ht]=ot[$][_e][at-1-ht]}k[0][0]=c[j],k[1][0]=ot[c[j]][c[j+1]][1],k[1][1]=ot[c[j]][c[j+2]][1];for(var lt=2;lt<b;lt++){k[lt][0]=ot[c[j]][c[j+1]][lt],k[lt][lt]=ot[c[j]][c[j+2]][lt],et.x=(d[3*k[lt][lt]]-d[3*k[lt][0]])/lt,et.y=(d[3*k[lt][lt]+1]-d[3*k[lt][0]+1])/lt,et.z=(d[3*k[lt][lt]+2]-d[3*k[lt][0]+2])/lt,tt.x=(_[3*k[lt][lt]]-_[3*k[lt][0]])/lt,tt.y=(_[3*k[lt][lt]+1]-_[3*k[lt][0]+1])/lt,tt.z=(_[3*k[lt][lt]+2]-_[3*k[lt][0]+2])/lt,rt.x=(s[2*k[lt][lt]]-s[2*k[lt][0]])/lt,rt.y=(s[2*k[lt][lt]+1]-s[2*k[lt][0]+1])/lt;for(var ft=1;ft<lt;ft++)k[lt][ft]=d.length/3,d[st]=d[3*k[lt][0]]+ft*et.x,_[st++]=_[3*k[lt][0]]+ft*tt.x,d[st]=d[3*k[lt][0]+1]+ft*et.y,_[st++]=_[3*k[lt][0]+1]+ft*tt.y,d[st]=d[3*k[lt][0]+2]+ft*et.z,_[st++]=_[3*k[lt][0]+2]+ft*tt.z,s[ut++]=s[2*k[lt][0]]+ft*rt.x,s[ut++]=s[2*k[lt][0]+1]+ft*rt.y}k[b]=ot[c[j+1]][c[j+2]],it.push(k[0][0],k[1][0],k[1][1]);for(var lt=1;lt<b;lt++){for(var ft=0;ft<lt;ft++)it.push(k[lt][ft],k[lt+1][ft],k[lt+1][ft+1]),it.push(k[lt][ft],k[lt+1][ft+1],k[lt][ft+1]);it.push(k[lt][ft],k[lt+1][ft],k[lt+1][ft+1])}}o.indices=it,o.applyToMesh(this,this.isVertexBufferUpdatable(VertexBuffer.PositionKind))}},i.prototype.forceSharedVertices=function(){var e=VertexData.ExtractFromMesh(this),o=e.uvs,s=e.indices,c=e.positions,d=e.colors;if(s===void 0||c===void 0||s===null||c===null)Logger$2.Warn("VertexData contains empty entries");else{for(var _=new Array,b=new Array,k=new Array,j=new Array,$=new Array,_e=0,et={},tt,rt,it=0;it<s.length;it+=3){rt=[s[it],s[it+1],s[it+2]],$=new Array;for(var nt=0;nt<3;nt++){$[nt]="";for(var ot=0;ot<3;ot++)Math.abs(c[3*rt[nt]+ot])<1e-8&&(c[3*rt[nt]+ot]=0),$[nt]+=c[3*rt[nt]+ot]+"|"}if(!($[0]==$[1]||$[0]==$[2]||$[1]==$[2]))for(var nt=0;nt<3;nt++){if(tt=et[$[nt]],tt===void 0){et[$[nt]]=_e,tt=_e++;for(var ot=0;ot<3;ot++)_.push(c[3*rt[nt]+ot]);if(d!=null)for(var ot=0;ot<4;ot++)j.push(d[4*rt[nt]+ot]);if(o!=null)for(var ot=0;ot<2;ot++)k.push(o[2*rt[nt]+ot])}b.push(tt)}}var at=new Array;VertexData.ComputeNormals(_,b,at),e.positions=_,e.indices=b,e.normals=at,o!=null&&(e.uvs=k),d!=null&&(e.colors=j),e.applyToMesh(this,this.isVertexBufferUpdatable(VertexBuffer.PositionKind))}},i._instancedMeshFactory=function(e,o){throw _WarnImport("InstancedMesh")},i._PhysicsImpostorParser=function(e,o,s){throw _WarnImport("PhysicsImpostor")},i.prototype.createInstance=function(e){return i._instancedMeshFactory(e,this)},i.prototype.synchronizeInstances=function(){for(var e=0;e<this.instances.length;e++){var o=this.instances[e];o._syncSubMeshes()}return this},i.prototype.optimizeIndices=function(e){var o=this,s=this.getIndices(),c=this.getVerticesData(VertexBuffer.PositionKind);if(!c||!s)return this;for(var d=new Array,_=0;_<c.length;_=_+3)d.push(Vector3.FromArray(c,_));var b=new Array;return AsyncLoop.SyncAsyncForLoop(d.length,40,function(k){for(var j=d.length-1-k,$=d[j],_e=0;_e<j;++_e){var et=d[_e];if($.equals(et)){b[j]=_e;break}}},function(){for(var k=0;k<s.length;++k)s[k]=b[s[k]]||s[k];var j=o.subMeshes.slice(0);o.setIndices(s),o.subMeshes=j,e&&e(o)}),this},i.prototype.serialize=function(e){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),Tags&&Tags.HasTags(this)&&(e.tags=Tags.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.checkCollisions=this.checkCollisions,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&(e.parentId=this.parent.uniqueId),e.isUnIndexed=this.isUnIndexed;var o=this._geometry;if(o&&this.subMeshes){e.geometryUniqueId=o.uniqueId,e.geometryId=o.id,e.subMeshes=[];for(var s=0;s<this.subMeshes.length;s++){var c=this.subMeshes[s];e.subMeshes.push({materialIndex:c.materialIndex,verticesStart:c.verticesStart,verticesCount:c.verticesCount,indexStart:c.indexStart,indexCount:c.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialId=this.material.id):(this.material=null,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)){var d=this.getPhysicsImpostor();d&&(e.physicsMass=d.getParam("mass"),e.physicsFriction=d.getParam("friction"),e.physicsRestitution=d.getParam("mass"),e.physicsImpostor=d.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(var _=0;_<this.instances.length;_++){var b=this.instances[_];if(!b.doNotSerialize){var k={name:b.name,id:b.id,isEnabled:b.isEnabled(!1),isVisible:b.isVisible,isPickable:b.isPickable,checkCollisions:b.checkCollisions,position:b.position.asArray(),scaling:b.scaling.asArray()};if(b.parent&&(k.parentId=b.parent.uniqueId),b.rotationQuaternion?k.rotationQuaternion=b.rotationQuaternion.asArray():b.rotation&&(k.rotation=b.rotation.asArray()),this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)){var d=b.getPhysicsImpostor();d&&(k.physicsMass=d.getParam("mass"),k.physicsFriction=d.getParam("friction"),k.physicsRestitution=d.getParam("mass"),k.physicsImpostor=d.type)}b.metadata&&(k.metadata=b.metadata),e.instances.push(k),SerializationHelper.AppendSerializedAnimations(b,k),k.ranges=b.serializeAnimationRanges()}}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Tools.SliceToArray(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){var j={data:{},sizes:{},strides:{}};for(var $ in this._userThinInstanceBuffersStorage.data)j.data[$]=Tools.SliceToArray(this._userThinInstanceBuffersStorage.data[$]),j.sizes[$]=this._userThinInstanceBuffersStorage.sizes[$],j.strides[$]=this._userThinInstanceBuffersStorage.strides[$];e.thinInstances.userThinInstance=j}SerializationHelper.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name))},i.prototype._syncGeometryWithMorphTargetManager=function(){if(!!this.geometry){this._markSubMeshesAsAttributesDirty();var e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices()){Logger$2.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),this.morphTargetManager=null;return}if(e.isUsingTextureForTargets)return;for(var o=0;o<e.numInfluencers;o++){var s=e.getActiveTarget(o),c=s.getPositions();if(!c){Logger$2.Error("Invalid morph target. Target must have positions.");return}this.geometry.setVerticesData(VertexBuffer.PositionKind+o,c,!1,3);var d=s.getNormals();d&&this.geometry.setVerticesData(VertexBuffer.NormalKind+o,d,!1,3);var _=s.getTangents();_&&this.geometry.setVerticesData(VertexBuffer.TangentKind+o,_,!1,3);var b=s.getUVs();b&&this.geometry.setVerticesData(VertexBuffer.UVKind+"_"+o,b,!1,2)}}else for(var o=0;this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind+o);)this.geometry.removeVerticesData(VertexBuffer.PositionKind+o),this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind+o)&&this.geometry.removeVerticesData(VertexBuffer.NormalKind+o),this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind+o)&&this.geometry.removeVerticesData(VertexBuffer.TangentKind+o),this.geometry.isVerticesDataPresent(VertexBuffer.UVKind+o)&&this.geometry.removeVerticesData(VertexBuffer.UVKind+"_"+o),o++}},i.Parse=function(e,o,s){var c;if(e.type&&e.type==="LinesMesh"?c=i._LinesMeshParser(e,o):e.type&&e.type==="GroundMesh"?c=i._GroundMeshParser(e,o):c=new i(e.name,o),c.id=e.id,Tags&&Tags.AddTagsTo(c,e.tags),c.position=Vector3.FromArray(e.position),e.metadata!==void 0&&(c.metadata=e.metadata),e.rotationQuaternion?c.rotationQuaternion=Quaternion.FromArray(e.rotationQuaternion):e.rotation&&(c.rotation=Vector3.FromArray(e.rotation)),c.scaling=Vector3.FromArray(e.scaling),e.localMatrix?c.setPreTransformMatrix(Matrix.FromArray(e.localMatrix)):e.pivotMatrix&&c.setPivotMatrix(Matrix.FromArray(e.pivotMatrix)),c.setEnabled(e.isEnabled),c.isVisible=e.isVisible,c.infiniteDistance=e.infiniteDistance,c.showBoundingBox=e.showBoundingBox,c.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,e.applyFog!==void 0&&(c.applyFog=e.applyFog),e.pickable!==void 0&&(c.isPickable=e.pickable),e.alphaIndex!==void 0&&(c.alphaIndex=e.alphaIndex),c.receiveShadows=e.receiveShadows,c.billboardMode=e.billboardMode,e.visibility!==void 0&&(c.visibility=e.visibility),c.checkCollisions=e.checkCollisions,c.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation,e.isBlocker!==void 0&&(c.isBlocker=e.isBlocker),c._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(c._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),e.parentId&&(c._waitingParentId=e.parentId),e.actions!==void 0&&(c._waitingData.actions=e.actions),e.overlayAlpha!==void 0&&(c.overlayAlpha=e.overlayAlpha),e.overlayColor!==void 0&&(c.overlayColor=Color3.FromArray(e.overlayColor)),e.renderOverlay!==void 0&&(c.renderOverlay=e.renderOverlay),c.isUnIndexed=!!e.isUnIndexed,c.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(c.delayLoadState=4,c.delayLoadingFile=s+e.delayLoadingFile,c.buildBoundingInfo(Vector3.FromArray(e.boundingBoxMinimum),Vector3.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(c._binaryInfo=e._binaryInfo),c._delayInfo=[],e.hasUVs&&c._delayInfo.push(VertexBuffer.UVKind),e.hasUVs2&&c._delayInfo.push(VertexBuffer.UV2Kind),e.hasUVs3&&c._delayInfo.push(VertexBuffer.UV3Kind),e.hasUVs4&&c._delayInfo.push(VertexBuffer.UV4Kind),e.hasUVs5&&c._delayInfo.push(VertexBuffer.UV5Kind),e.hasUVs6&&c._delayInfo.push(VertexBuffer.UV6Kind),e.hasColors&&c._delayInfo.push(VertexBuffer.ColorKind),e.hasMatricesIndices&&c._delayInfo.push(VertexBuffer.MatricesIndicesKind),e.hasMatricesWeights&&c._delayInfo.push(VertexBuffer.MatricesWeightsKind),c._delayLoadingFunction=Geometry._ImportGeometry,SceneLoaderFlags.ForceFullSceneLoadingForIncremental&&c._checkDelayState()):Geometry._ImportGeometry(e,c),e.materialId?c.setMaterialById(e.materialId):c.material=null,e.morphTargetManagerId>-1&&(c.morphTargetManager=o.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(c.skeleton=o.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(c.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(var d=0;d<e.animations.length;d++){var _=e.animations[d],b=GetClass("BABYLON.Animation");b&&c.animations.push(b.Parse(_))}Node$2.ParseAnimationRanges(c,e,o)}if(e.autoAnimate&&o.beginAnimation(c,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?c.layerMask=Math.abs(parseInt(e.layerMask)):c.layerMask=268435455,e.physicsImpostor&&i._PhysicsImpostorParser(o,c,e),e.lodMeshIds&&(c._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(var k=0;k<e.instances.length;k++){var j=e.instances[k],$=c.createInstance(j.name);if(j.id&&($.id=j.id),Tags&&(j.tags?Tags.AddTagsTo($,j.tags):Tags.AddTagsTo($,e.tags)),$.position=Vector3.FromArray(j.position),j.metadata!==void 0&&($.metadata=j.metadata),j.parentId&&($._waitingParentId=j.parentId),j.isEnabled!==void 0&&j.isEnabled!==null&&$.setEnabled(j.isEnabled),j.isVisible!==void 0&&j.isVisible!==null&&($.isVisible=j.isVisible),j.isPickable!==void 0&&j.isPickable!==null&&($.isPickable=j.isPickable),j.rotationQuaternion?$.rotationQuaternion=Quaternion.FromArray(j.rotationQuaternion):j.rotation&&($.rotation=Vector3.FromArray(j.rotation)),$.scaling=Vector3.FromArray(j.scaling),j.checkCollisions!=null&&j.checkCollisions!=null&&($.checkCollisions=j.checkCollisions),j.pickable!=null&&j.pickable!=null&&($.isPickable=j.pickable),j.showBoundingBox!=null&&j.showBoundingBox!=null&&($.showBoundingBox=j.showBoundingBox),j.showSubMeshesBoundingBox!=null&&j.showSubMeshesBoundingBox!=null&&($.showSubMeshesBoundingBox=j.showSubMeshesBoundingBox),j.alphaIndex!=null&&j.showSubMeshesBoundingBox!=null&&($.alphaIndex=j.alphaIndex),j.physicsImpostor&&i._PhysicsImpostorParser(o,$,j),j.animations){for(d=0;d<j.animations.length;d++){_=j.animations[d];var b=GetClass("BABYLON.Animation");b&&$.animations.push(b.Parse(_))}Node$2.ParseAnimationRanges($,j,o),j.autoAnimate&&o.beginAnimation($,j.autoAnimateFrom,j.autoAnimateTo,j.autoAnimateLoop,j.autoAnimateSpeed||1)}}if(e.thinInstances){var _e=e.thinInstances;if(c.thinInstanceEnablePicking=!!_e.enablePicking,_e.matrixData?(c.thinInstanceSetBuffer("matrix",new Float32Array(_e.matrixData),16,!1),c._thinInstanceDataStorage.matrixBufferSize=_e.matrixBufferSize,c._thinInstanceDataStorage.instancesCount=_e.instancesCount):c._thinInstanceDataStorage.matrixBufferSize=_e.matrixBufferSize,e.thinInstances.userThinInstance){var et=e.thinInstances.userThinInstance;for(var tt in et.data)c.thinInstanceSetBuffer(tt,new Float32Array(et.data[tt]),et.strides[tt],!1),c._userThinInstanceBuffersStorage.sizes[tt]=et.sizes[tt]}}return c},i.prototype.setPositionsForCPUSkinning=function(){var e=this._internalMeshDataInfo;if(!e._sourcePositions){var o=this.getVerticesData(VertexBuffer.PositionKind);if(!o)return e._sourcePositions;e._sourcePositions=new Float32Array(o),this.isVertexBufferUpdatable(VertexBuffer.PositionKind)||this.setVerticesData(VertexBuffer.PositionKind,o,!0)}return e._sourcePositions},i.prototype.setNormalsForCPUSkinning=function(){var e=this._internalMeshDataInfo;if(!e._sourceNormals){var o=this.getVerticesData(VertexBuffer.NormalKind);if(!o)return e._sourceNormals;e._sourceNormals=new Float32Array(o),this.isVertexBufferUpdatable(VertexBuffer.NormalKind)||this.setVerticesData(VertexBuffer.NormalKind,o,!0)}return e._sourceNormals},i.prototype.applySkeleton=function(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(VertexBuffer.PositionKind))return this;if(!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind))return this;var o=this.isVerticesDataPresent(VertexBuffer.NormalKind),s=this._internalMeshDataInfo;if(!s._sourcePositions){var c=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=c}o&&!s._sourceNormals&&this.setNormalsForCPUSkinning();var d=this.getVerticesData(VertexBuffer.PositionKind);if(!d)return this;d instanceof Float32Array||(d=new Float32Array(d));var _=this.getVerticesData(VertexBuffer.NormalKind);if(o){if(!_)return this;_ instanceof Float32Array||(_=new Float32Array(_))}var b=this.getVerticesData(VertexBuffer.MatricesIndicesKind),k=this.getVerticesData(VertexBuffer.MatricesWeightsKind);if(!k||!b)return this;for(var j=this.numBoneInfluencers>4,$=j?this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind):null,_e=j?this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind):null,et=e.getTransformMatrices(this),tt=Vector3.Zero(),rt=new Matrix,it=new Matrix,nt=0,ot,at=0;at<d.length;at+=3,nt+=4){var st;for(ot=0;ot<4;ot++)st=k[nt+ot],st>0&&(Matrix.FromFloat32ArrayToRefScaled(et,Math.floor(b[nt+ot]*16),st,it),rt.addToSelf(it));if(j)for(ot=0;ot<4;ot++)st=_e[nt+ot],st>0&&(Matrix.FromFloat32ArrayToRefScaled(et,Math.floor($[nt+ot]*16),st,it),rt.addToSelf(it));Vector3.TransformCoordinatesFromFloatsToRef(s._sourcePositions[at],s._sourcePositions[at+1],s._sourcePositions[at+2],rt,tt),tt.toArray(d,at),o&&(Vector3.TransformNormalFromFloatsToRef(s._sourceNormals[at],s._sourceNormals[at+1],s._sourceNormals[at+2],rt,tt),tt.toArray(_,at)),rt.reset()}return this.updateVerticesData(VertexBuffer.PositionKind,d),o&&this.updateVerticesData(VertexBuffer.NormalKind,_),this},i.MinMax=function(e){var o=null,s=null;return e.forEach(function(c){var d=c.getBoundingInfo(),_=d.boundingBox;!o||!s?(o=_.minimumWorld,s=_.maximumWorld):(o.minimizeInPlace(_.minimumWorld),s.maximizeInPlace(_.maximumWorld))}),!o||!s?{min:Vector3.Zero(),max:Vector3.Zero()}:{min:o,max:s}},i.Center=function(e){var o=e instanceof Array?i.MinMax(e):e;return Vector3.Center(o.min,o.max)},i.MergeMeshes=function(e,o,s,c,d,_){return o===void 0&&(o=!0),runCoroutineSync(i._MergeMeshesCoroutine(e,o,s,c,d,_,!1))},i.MergeMeshesAsync=function(e,o,s,c,d,_){return o===void 0&&(o=!0),runCoroutineAsync(i._MergeMeshesCoroutine(e,o,s,c,d,_,!0),createYieldingScheduler())},i._MergeMeshesCoroutine=function(e,o,s,c,d,_,b){var k,j,$,_e,et,tt,rt,it,nt,ot,at,st,ut,ft,lt,ht,pt,mt,dt,gt,_t,yt,Tt,St;return o===void 0&&(o=!0),__generator(this,function(At){switch(At.label){case 0:if(e=e.filter(Boolean),e.length===0)return[2,null];if(!s){for(j=0,k=0;k<e.length;k++)if(j+=e[k].getTotalVertices(),j>=65536)return Logger$2.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),[2,null]}for(_&&($=null,d=!1),tt=new Array,rt=new Array,it=new Array,k=0;k<e.length;k++){if(nt=e[k],nt.isAnInstance)return Logger$2.Warn("Cannot merge instance meshes."),[2,null];if(d&&it.push(nt.getTotalIndices()),_)if(nt.material)if(ot=nt.material,ot instanceof MultiMaterial){for(et=0;et<ot.subMaterials.length;et++)tt.indexOf(ot.subMaterials[et])<0&&tt.push(ot.subMaterials[et]);for(_e=0;_e<nt.subMeshes.length;_e++)rt.push(tt.indexOf(ot.subMaterials[nt.subMeshes[_e].materialIndex])),it.push(nt.subMeshes[_e].indexCount)}else for(tt.indexOf(ot)<0&&tt.push(ot),_e=0;_e<nt.subMeshes.length;_e++)rt.push(tt.indexOf(ot)),it.push(nt.subMeshes[_e].indexCount);else for(_e=0;_e<nt.subMeshes.length;_e++)rt.push(0),it.push(nt.subMeshes[_e].indexCount)}return at=e[0],st=function(vt){var Et=vt.computeWorldMatrix(!0),xt=VertexData.ExtractFromMesh(vt,!0,!0);return xt.transform(Et),xt},ut=st(at),b?[4]:[3,2];case 1:At.sent(),At.label=2;case 2:ft=new Array(e.length-1),lt=1,At.label=3;case 3:return lt<e.length?(ft[lt-1]=st(e[lt]),b?[4]:[3,5]):[3,6];case 4:At.sent(),At.label=5;case 5:return lt++,[3,3];case 6:ht=ut._mergeCoroutine(ft,s,b),pt=ht.next(),At.label=7;case 7:return pt.done?[3,10]:b?[4]:[3,9];case 8:At.sent(),At.label=9;case 9:return pt=ht.next(),[3,7];case 10:mt=pt.value,c||(c=new i(at.name+"_merged",at.getScene())),dt=mt._applyToCoroutine(c,void 0,b),gt=dt.next(),At.label=11;case 11:return gt.done?[3,14]:b?[4]:[3,13];case 12:At.sent(),At.label=13;case 13:return gt=dt.next(),[3,11];case 14:if(c.checkCollisions=at.checkCollisions,c.overrideMaterialSideOrientation=at.overrideMaterialSideOrientation,o)for(k=0;k<e.length;k++)e[k].dispose();if(d||_){for(c.releaseSubMeshes(),k=0,_t=0;k<it.length;)SubMesh.CreateFromIndices(0,_t,it[k],c,void 0,!1),_t+=it[k],k++;for(yt=0,Tt=c.subMeshes;yt<Tt.length;yt++)St=Tt[yt],St.refreshBoundingInfo();c.computeWorldMatrix(!0)}if(_){for($=new MultiMaterial(at.name+"_merged",at.getScene()),$.subMaterials=tt,_e=0;_e<c.subMeshes.length;_e++)c.subMeshes[_e].materialIndex=rt[_e];c.material=$}else c.material=at.material;return[2,c]}})},i.prototype.addInstance=function(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)},i.prototype.removeInstance=function(e){var o=e._indexInSourceMeshInstanceArray;if(o!=-1){if(o!==this.instances.length-1){var s=this.instances[this.instances.length-1];this.instances[o]=s,s._indexInSourceMeshInstanceArray=o}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}},i.FRONTSIDE=VertexData.FRONTSIDE,i.BACKSIDE=VertexData.BACKSIDE,i.DOUBLESIDE=VertexData.DOUBLESIDE,i.DEFAULTSIDE=VertexData.DEFAULTSIDE,i.NO_CAP=0,i.CAP_START=1,i.CAP_END=2,i.CAP_ALL=3,i.NO_FLIP=0,i.FLIP_TILE=1,i.ROTATE_TILE=2,i.FLIP_ROW=3,i.ROTATE_ROW=4,i.FLIP_N_ROTATE_TILE=5,i.FLIP_N_ROTATE_ROW=6,i.CENTER=0,i.LEFT=1,i.RIGHT=2,i.TOP=3,i.BOTTOM=4,i.INSTANCEDMESH_SORT_TRANSPARENT=!1,i._GroundMeshParser=function(e,o){throw _WarnImport("GroundMesh")},i._LinesMeshParser=function(e,o){throw _WarnImport("LinesMesh")},i}(AbstractMesh);RegisterClass("BABYLON.Mesh",Mesh);_injectLTSMesh(Mesh);var AutoRotationBehavior=function(){function a(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}return Object.defineProperty(a.prototype,"name",{get:function(){return"AutoRotation"},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(i){this._zoomStopsAnimation=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"idleRotationSpeed",{get:function(){return this._idleRotationSpeed},set:function(i){this._idleRotationSpeed=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"idleRotationWaitTime",{get:function(){return this._idleRotationWaitTime},set:function(i){this._idleRotationWaitTime=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"idleRotationSpinupTime",{get:function(){return this._idleRotationSpinupTime},set:function(i){this._idleRotationSpinupTime=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rotationInProgress",{get:function(){return Math.abs(this._cameraRotationSpeed)>0},enumerable:!1,configurable:!0}),a.prototype.init=function(){},a.prototype.attach=function(i){var e=this;this._attachedCamera=i;var o=this._attachedCamera.getScene();this._onPrePointerObservableObserver=o.onPrePointerObservable.add(function(s){if(s.type===PointerEventTypes.POINTERDOWN){e._isPointerDown=!0;return}s.type===PointerEventTypes.POINTERUP&&(e._isPointerDown=!1)}),this._onAfterCheckInputsObserver=i.onAfterCheckInputsObservable.add(function(){var s=PrecisionDate.Now,c=0;e._lastFrameTime!=null&&(c=s-e._lastFrameTime),e._lastFrameTime=s,e._applyUserInteraction();var d=s-e._lastInteractionTime-e._idleRotationWaitTime,_=Math.max(Math.min(d/e._idleRotationSpinupTime,1),0);e._cameraRotationSpeed=e._idleRotationSpeed*_,e._attachedCamera&&(e._attachedCamera.alpha-=e._cameraRotationSpeed*(c/1e3))})},a.prototype.detach=function(){if(!!this._attachedCamera){var i=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&i.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},a.prototype.resetLastInteractionTime=function(i){this._lastInteractionTime=i!=null?i:PrecisionDate.Now},a.prototype._userIsZooming=function(){return this._attachedCamera?this._attachedCamera.inertialRadiusOffset!==0:!1},a.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var i=!1;return this._lastFrameRadius===this._attachedCamera.radius&&this._attachedCamera.inertialRadiusOffset!==0&&(i=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?i:this._userIsZooming()},a.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=PrecisionDate.Now)},a.prototype._userIsMoving=function(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1},a}(),EasingFunction=function(){function a(){this._easingMode=a.EASINGMODE_EASEIN}return a.prototype.setEasingMode=function(i){var e=Math.min(Math.max(i,0),2);this._easingMode=e},a.prototype.getEasingMode=function(){return this._easingMode},a.prototype.easeInCore=function(i){throw new Error("You must implement this method")},a.prototype.ease=function(i){switch(this._easingMode){case a.EASINGMODE_EASEIN:return this.easeInCore(i);case a.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-i)}return i>=.5?(1-this.easeInCore((1-i)*2))*.5+.5:this.easeInCore(i*2)*.5},a.EASINGMODE_EASEIN=0,a.EASINGMODE_EASEOUT=1,a.EASINGMODE_EASEINOUT=2,a}(),CircleEase=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},i}(EasingFunction),BackEase=function(a){__extends(i,a);function i(e){e===void 0&&(e=1);var o=a.call(this)||this;return o.amplitude=e,o}return i.prototype.easeInCore=function(e){var o=Math.max(0,this.amplitude);return Math.pow(e,3)-e*o*Math.sin(3.141592653589793*e)},i}(EasingFunction);(function(a){__extends(i,a);function i(e,o){e===void 0&&(e=3),o===void 0&&(o=2);var s=a.call(this)||this;return s.bounces=e,s.bounciness=o,s}return i.prototype.easeInCore=function(e){var o=Math.max(0,this.bounces),s=this.bounciness;s<=1&&(s=1.001);var c=Math.pow(s,o),d=1-s,_=(1-c)/d+c*.5,b=e*_,k=Math.log(-b*(1-s)+1)/Math.log(s),j=Math.floor(k),$=j+1,_e=(1-Math.pow(s,j))/(d*_),et=(1-Math.pow(s,$))/(d*_),tt=(_e+et)*.5,rt=e-tt,it=tt-_e;return-Math.pow(1/s,o-j)/(it*it)*(rt-it)*(rt+it)},i})(EasingFunction);(function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.easeInCore=function(e){return e*e*e},i})(EasingFunction);(function(a){__extends(i,a);function i(e,o){e===void 0&&(e=3),o===void 0&&(o=3);var s=a.call(this)||this;return s.oscillations=e,s.springiness=o,s}return i.prototype.easeInCore=function(e){var o,s=Math.max(0,this.oscillations),c=Math.max(0,this.springiness);return c==0?o=e:o=(Math.exp(c*e)-1)/(Math.exp(c)-1),o*Math.sin((6.283185307179586*s+1.5707963267948966)*e)},i})(EasingFunction);var ExponentialEase=function(a){__extends(i,a);function i(e){e===void 0&&(e=2);var o=a.call(this)||this;return o.exponent=e,o}return i.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},i}(EasingFunction);(function(a){__extends(i,a);function i(e){e===void 0&&(e=2);var o=a.call(this)||this;return o.power=e,o}return i.prototype.easeInCore=function(e){var o=Math.max(0,this.power);return Math.pow(e,o)},i})(EasingFunction);(function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.easeInCore=function(e){return e*e},i})(EasingFunction);(function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.easeInCore=function(e){return e*e*e*e},i})(EasingFunction);(function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.easeInCore=function(e){return e*e*e*e*e},i})(EasingFunction);var SineEase=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},i}(EasingFunction);(function(a){__extends(i,a);function i(e,o,s,c){e===void 0&&(e=0),o===void 0&&(o=0),s===void 0&&(s=1),c===void 0&&(c=1);var d=a.call(this)||this;return d.x1=e,d.y1=o,d.x2=s,d.y2=c,d}return i.prototype.easeInCore=function(e){return BezierCurve.Interpolate(e,this.x1,this.y1,this.x2,this.y2)},i})(EasingFunction);var BouncingBehavior=function(){function a(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(a.prototype,"name",{get:function(){return"Bouncing"},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(i){var e=this;if(this._autoTransitionRange!==i){this._autoTransitionRange=i;var o=this._attachedCamera;!o||(i?this._onMeshTargetChangedObserver=o.onMeshTargetChangedObservable.add(function(s){if(!!s){s.computeWorldMatrix(!0);var c=s.getBoundingInfo().diagonalLength;e.lowerRadiusTransitionRange=c*.05,e.upperRadiusTransitionRange=c*.05}}):this._onMeshTargetChangedObserver&&o.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!1,configurable:!0}),a.prototype.init=function(){},a.prototype.attach=function(i){var e=this;this._attachedCamera=i,this._onAfterCheckInputsObserver=i.onAfterCheckInputsObservable.add(function(){!e._attachedCamera||(e._isRadiusAtLimit(e._attachedCamera.lowerRadiusLimit)&&e._applyBoundRadiusAnimation(e.lowerRadiusTransitionRange),e._isRadiusAtLimit(e._attachedCamera.upperRadiusLimit)&&e._applyBoundRadiusAnimation(e.upperRadiusTransitionRange))})},a.prototype.detach=function(){!this._attachedCamera||(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},a.prototype._isRadiusAtLimit=function(i){return this._attachedCamera?this._attachedCamera.radius===i&&!this._radiusIsAnimating:!1},a.prototype._applyBoundRadiusAnimation=function(i){var e=this;if(!!this._attachedCamera){this._radiusBounceTransition||(a.EasingFunction.setEasingMode(a.EasingMode),this._radiusBounceTransition=Animation.CreateAnimation("radius",Animation.ANIMATIONTYPE_FLOAT,60,a.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var o=Animation.TransitionTo("radius",this._attachedCamera.radius+i,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,function(){return e._clearAnimationLocks()});o&&this._animatables.push(o)}},a.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},a.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},a.EasingFunction=new BackEase(.3),a.EasingMode=EasingFunction.EASINGMODE_EASEOUT,a}(),FramingBehavior=function(){function a(){this.onTargetFramingAnimationEndObservable=new Observable,this._mode=a.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}return Object.defineProperty(a.prototype,"name",{get:function(){return"Framing"},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"mode",{get:function(){return this._mode},set:function(i){this._mode=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"radiusScale",{get:function(){return this._radiusScale},set:function(i){this._radiusScale=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"positionScale",{get:function(){return this._positionScale},set:function(i){this._positionScale=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"defaultElevation",{get:function(){return this._defaultElevation},set:function(i){this._defaultElevation=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"elevationReturnTime",{get:function(){return this._elevationReturnTime},set:function(i){this._elevationReturnTime=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"elevationReturnWaitTime",{get:function(){return this._elevationReturnWaitTime},set:function(i){this._elevationReturnWaitTime=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(i){this._zoomStopsAnimation=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"framingTime",{get:function(){return this._framingTime},set:function(i){this._framingTime=i},enumerable:!1,configurable:!0}),a.prototype.init=function(){},a.prototype.attach=function(i){var e=this;this._attachedCamera=i;var o=this._attachedCamera.getScene();a.EasingFunction.setEasingMode(a.EasingMode),this._onPrePointerObservableObserver=o.onPrePointerObservable.add(function(s){if(s.type===PointerEventTypes.POINTERDOWN){e._isPointerDown=!0;return}s.type===PointerEventTypes.POINTERUP&&(e._isPointerDown=!1)}),this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add(function(s){s&&e.zoomOnMesh(s,void 0,function(){e.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=i.onAfterCheckInputsObservable.add(function(){e._applyUserInteraction(),e._maintainCameraAboveGround()})},a.prototype.detach=function(){if(!!this._attachedCamera){var i=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&i.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}},a.prototype.zoomOnMesh=function(i,e,o){e===void 0&&(e=!1),o===void 0&&(o=null),i.computeWorldMatrix(!0);var s=i.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,e,o)},a.prototype.zoomOnMeshHierarchy=function(i,e,o){e===void 0&&(e=!1),o===void 0&&(o=null),i.computeWorldMatrix(!0);var s=i.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,e,o)},a.prototype.zoomOnMeshesHierarchy=function(i,e,o){e===void 0&&(e=!1),o===void 0&&(o=null);for(var s=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),c=new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),d=0;d<i.length;d++){var _=i[d].getHierarchyBoundingVectors(!0);Vector3.CheckExtends(_.min,s,c),Vector3.CheckExtends(_.max,s,c)}this.zoomOnBoundingInfo(s,c,e,o)},a.prototype.zoomOnBoundingInfo=function(i,e,o,s){var c=this;o===void 0&&(o=!1),s===void 0&&(s=null);var d;if(!!this._attachedCamera){var _=i.y,b=e.y,k=_+(b-_)*this._positionScale,j=e.subtract(i).scale(.5);if(o)d=new Vector3(0,k,0);else{var $=i.add(j);d=new Vector3($.x,k,$.z)}this._vectorTransition||(this._vectorTransition=Animation.CreateAnimation("target",Animation.ANIMATIONTYPE_VECTOR3,60,a.EasingFunction)),this._betaIsAnimating=!0;var _e=Animation.TransitionTo("target",d,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);_e&&this._animatables.push(_e);var et=0;if(this._mode===a.FitFrustumSidesMode){var tt=this._calculateLowerRadiusFromModelBoundingSphere(i,e);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=j.length()+this._attachedCamera.minZ),et=tt}else this._mode===a.IgnoreBoundsSizeMode&&(et=this._calculateLowerRadiusFromModelBoundingSphere(i,e),this.autoCorrectCameraLimitsAndSensibility&&this._attachedCamera.lowerRadiusLimit===null&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){var rt=e.subtract(i).length();this._attachedCamera.panningSensibility=5e3/rt,this._attachedCamera.wheelPrecision=100/et}this._radiusTransition||(this._radiusTransition=Animation.CreateAnimation("radius",Animation.ANIMATIONTYPE_FLOAT,60,a.EasingFunction)),_e=Animation.TransitionTo("radius",et,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,function(){c.stopAllAnimations(),s&&s(),c._attachedCamera&&c._attachedCamera.useInputToRestoreState&&c._attachedCamera.storeState()}),_e&&this._animatables.push(_e)}},a.prototype._calculateLowerRadiusFromModelBoundingSphere=function(i,e){var o=e.subtract(i),s=o.length(),c=this._getFrustumSlope(),d=s*.5,_=d*this._radiusScale,b=_*Math.sqrt(1+1/(c.x*c.x)),k=_*Math.sqrt(1+1/(c.y*c.y)),j=Math.max(b,k),$=this._attachedCamera;return $?($.lowerRadiusLimit&&this._mode===a.IgnoreBoundsSizeMode&&(j=j<$.lowerRadiusLimit?$.lowerRadiusLimit:j),$.upperRadiusLimit&&(j=j>$.upperRadiusLimit?$.upperRadiusLimit:j),j):0},a.prototype._maintainCameraAboveGround=function(){var i=this;if(!(this._elevationReturnTime<0)){var e=PrecisionDate.Now-this._lastInteractionTime,o=Math.PI*.5-this._defaultElevation,s=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>s&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Animation.CreateAnimation("beta",Animation.ANIMATIONTYPE_FLOAT,60,a.EasingFunction));var c=Animation.TransitionTo("beta",o,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,function(){i._clearAnimationLocks(),i.stopAllAnimations()});c&&this._animatables.push(c)}}},a.prototype._getFrustumSlope=function(){var i=this._attachedCamera;if(!i)return Vector2.Zero();var e=i.getScene().getEngine(),o=e.getAspectRatio(i),s=Math.tan(i.fov/2),c=s*o;return new Vector2(c,s)},a.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},a.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=PrecisionDate.Now,this.stopAllAnimations(),this._clearAnimationLocks())},a.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(a.prototype,"isUserIsMoving",{get:function(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1},enumerable:!1,configurable:!0}),a.EasingFunction=new ExponentialEase,a.EasingMode=EasingFunction.EASINGMODE_EASEINOUT,a.IgnoreBoundsSizeMode=0,a.FitFrustumSidesMode=1,a}(),TargetCamera=function(a){__extends(i,a);function i(e,o,s,c){c===void 0&&(c=!0);var d=a.call(this,e,o,s,c)||this;return d._tmpUpVector=Vector3.Zero(),d._tmpTargetVector=Vector3.Zero(),d.cameraDirection=new Vector3(0,0,0),d.cameraRotation=new Vector2(0,0),d.ignoreParentScaling=!1,d.updateUpVectorFromRotation=!1,d._tmpQuaternion=new Quaternion,d.rotation=new Vector3(0,0,0),d.speed=2,d.noRotationConstraint=!1,d.invertRotation=!1,d.inverseRotationSpeed=.2,d.lockedTarget=null,d._currentTarget=Vector3.Zero(),d._initialFocalDistance=1,d._viewMatrix=Matrix.Zero(),d._camMatrix=Matrix.Zero(),d._cameraTransformMatrix=Matrix.Zero(),d._cameraRotationMatrix=Matrix.Zero(),d._referencePoint=new Vector3(0,0,1),d._transformedReferencePoint=Vector3.Zero(),d._defaultUp=Vector3.Up(),d._cachedRotationZ=0,d._cachedQuaternionRotationZ=0,d}return i.prototype.getFrontPosition=function(e){this.getWorldMatrix();var o=this.getTarget().subtract(this.position);return o.normalize(),o.scaleInPlace(e),this.globalPosition.add(o)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),a.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return a.prototype._restoreStateValues.call(this)?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1},i.prototype._initCache=function(){a.prototype._initCache.call(this),this._cache.lockedTarget=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||a.prototype._updateCache.call(this);var o=this._getLockedTargetPosition();o?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(o):this._cache.lockedTarget=o.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!a.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))},i.prototype.setTarget=function(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=Epsilon),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),Matrix.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var o=e.subtract(this.position);o.x>=0?this.rotation.y=-Math.atan(o.z/o.x)+Math.PI/2:this.rotation.y=-Math.atan(o.z/o.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},Object.defineProperty(i.prototype,"target",{get:function(){return this.getTarget()},set:function(e){this.setTarget(e)},enumerable:!1,configurable:!0}),i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){if(this.parent){this.parent.getWorldMatrix().invertToRef(TmpVectors.Matrix[0]),Vector3.TransformNormalToRef(this.cameraDirection,TmpVectors.Matrix[0],TmpVectors.Vector3[0]),this.position.addInPlace(TmpVectors.Vector3[0]);return}this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var e=this.invertRotation?-this.inverseRotationSpeed:1,o=this._decideIfNeedsToMove(),s=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(o&&this._updatePosition(),s){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this.rotation),this.rotation.x+=this.cameraRotation.x*e,this.rotation.y+=this.cameraRotation.y*e,!this.noRotationConstraint){var c=1.570796;this.rotation.x>c&&(this.rotation.x=c),this.rotation.x<-c&&(this.rotation.x=-c)}if(this.rotationQuaternion){var d=this.rotation.lengthSquared();d&&Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}}o&&(Math.abs(this.cameraDirection.x)<this.speed*Epsilon&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*Epsilon&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*Epsilon&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),s&&(Math.abs(this.cameraRotation.x)<this.speed*Epsilon&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*Epsilon&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),a.prototype._checkInputs.call(this)},i.prototype._updateCameraRotationMatrix=function(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)},i.prototype._rotateUpVectorWithCameraRotationMatrix=function(){return Vector3.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this},i.prototype._getViewMatrix=function(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(Quaternion.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix},i.prototype._computeViewMatrix=function(e,o,s){if(this.ignoreParentScaling){if(this.parent){var c=this.parent.getWorldMatrix();Vector3.TransformCoordinatesToRef(e,c,this._globalPosition),Vector3.TransformCoordinatesToRef(o,c,this._tmpTargetVector),Vector3.TransformNormalToRef(s,c,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(o),this._tmpUpVector.copyFrom(s);this.getScene().useRightHandedSystem?Matrix.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):Matrix.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix);return}if(this.getScene().useRightHandedSystem?Matrix.LookAtRHToRef(e,o,s,this._viewMatrix):Matrix.LookAtLHToRef(e,o,s,this._viewMatrix),this.parent){var c=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(c,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)},i.prototype.createRigCamera=function(e,o){if(this.cameraRigMode!==Camera$1.RIG_MODE_NONE){var s=new i(e,this.position.clone(),this.getScene());return s.isRigCamera=!0,s.rigParent=this,(this.cameraRigMode===Camera$1.RIG_MODE_VR||this.cameraRigMode===Camera$1.RIG_MODE_WEBVR)&&(this.rotationQuaternion||(this.rotationQuaternion=new Quaternion),s._cameraRigParams={},s.rotationQuaternion=new Quaternion),s}return null},i.prototype._updateRigCameras=function(){var e=this._rigCameras[0],o=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case Camera$1.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case Camera$1.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Camera$1.RIG_MODE_STEREOSCOPIC_INTERLACED:var s=this.cameraRigMode===Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,c=this.cameraRigMode===Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*s,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*c,o);break;case Camera$1.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),o.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),o.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),o.position.copyFrom(this.position);break}a.prototype._updateRigCameras.call(this)},i.prototype._getRigCamPositionAndTarget=function(e,o){var s=this.getTarget();s.subtractToRef(this.position,i._TargetFocalPoint),i._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);var c=i._TargetFocalPoint.addInPlace(this.position);Matrix.TranslationToRef(-c.x,-c.y,-c.z,i._TargetTransformMatrix),i._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(o.upVector,e),i._RigCamTransformMatrix),Matrix.TranslationToRef(c.x,c.y,c.z,i._TargetTransformMatrix),i._RigCamTransformMatrix.multiplyToRef(i._TargetTransformMatrix,i._RigCamTransformMatrix),Vector3.TransformCoordinatesToRef(this.position,i._RigCamTransformMatrix,o.position),o.setTarget(c)},i.prototype.getClassName=function(){return"TargetCamera"},i._RigCamTransformMatrix=new Matrix,i._TargetTransformMatrix=new Matrix,i._TargetFocalPoint=new Vector3,__decorate([serializeAsVector3()],i.prototype,"rotation",void 0),__decorate([serialize()],i.prototype,"speed",void 0),__decorate([serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i}(Camera$1),CameraInputTypes={},CameraInputsManager=function(){function a(i){this.attachedToElement=!1,this.attached={},this.camera=i,this.checkInputs=function(){}}return a.prototype.add=function(i){var e=i.getSimpleName();if(this.attached[e]){Logger$2.Warn("camera input of type "+e+" already exists on camera");return}this.attached[e]=i,i.camera=this.camera,i.checkInputs&&(this.checkInputs=this._addCheckInputs(i.checkInputs.bind(i))),this.attachedToElement&&i.attachControl()},a.prototype.remove=function(i){for(var e in this.attached){var o=this.attached[e];o===i&&(o.detachControl(),o.camera=null,delete this.attached[e],this.rebuildInputCheck())}},a.prototype.removeByType=function(i){for(var e in this.attached){var o=this.attached[e];o.getClassName()===i&&(o.detachControl(),o.camera=null,delete this.attached[e],this.rebuildInputCheck())}},a.prototype._addCheckInputs=function(i){var e=this.checkInputs;return function(){e(),i()}},a.prototype.attachInput=function(i){this.attachedToElement&&i.attachControl(this.noPreventDefault)},a.prototype.attachElement=function(i){if(i===void 0&&(i=!1),!this.attachedToElement){i=Camera$1.ForceAttachControlToAlwaysPreventDefault?!1:i,this.attachedToElement=!0,this.noPreventDefault=i;for(var e in this.attached)this.attached[e].attachControl(i)}},a.prototype.detachElement=function(i){i===void 0&&(i=!1);for(var e in this.attached)this.attached[e].detachControl(),i&&(this.attached[e].camera=null);this.attachedToElement=!1},a.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var i in this.attached){var e=this.attached[i];e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e)))}},a.prototype.clear=function(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=function(){}},a.prototype.serialize=function(i){var e={};for(var o in this.attached){var s=this.attached[o],c=SerializationHelper.Serialize(s);e[s.getClassName()]=c}i.inputsmgr=e},a.prototype.parse=function(i){var e=i.inputsmgr;if(e){this.clear();for(var o in e){var s=CameraInputTypes[o];if(s){var c=e[o],d=SerializationHelper.Parse(function(){return new s},c,null);this.add(d)}}}else for(var o in this.attached){var s=CameraInputTypes[this.attached[o].getClassName()];if(s){var d=SerializationHelper.Parse(function(){return new s},i,null);this.remove(this.attached[o]),this.add(d)}}},a}(),BaseCameraPointersInput=function(){function a(){this._currentActiveButton=-1,this.buttons=[0,1,2]}return a.prototype.attachControl=function(i){var e=this;i=Tools.BackCompatCameraNoPreventDefault(arguments);var o=this.camera.getEngine(),s=o.getInputElement(),c=0,d=null;this.pointA=null,this.pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=function(b,k){var j=b.event,$=j.pointerType==="touch";if(!o.isInVRExclusivePointerMode&&!(b.type!==PointerEventTypes.POINTERMOVE&&e.buttons.indexOf(j.button)===-1)){var _e=j.srcElement||j.target;if(e._altKey=j.altKey,e._ctrlKey=j.ctrlKey,e._metaKey=j.metaKey,e._shiftKey=j.shiftKey,e._buttonsPressed=j.buttons,o.isPointerLock){var et=j.movementX||j.mozMovementX||j.webkitMovementX||j.msMovementX||0,tt=j.movementY||j.mozMovementY||j.webkitMovementY||j.msMovementY||0;e.onTouch(null,et,tt),e.pointA=null,e.pointB=null}else if(b.type===PointerEventTypes.POINTERDOWN&&(e._currentActiveButton===-1||$)){try{_e==null||_e.setPointerCapture(j.pointerId)}catch{}e.pointA===null?e.pointA={x:j.clientX,y:j.clientY,pointerId:j.pointerId,type:j.pointerType}:e.pointB===null&&(e.pointB={x:j.clientX,y:j.clientY,pointerId:j.pointerId,type:j.pointerType}),e._currentActiveButton===-1&&!$&&(e._currentActiveButton=j.button),e.onButtonDown(j),i||(j.preventDefault(),s&&s.focus())}else if(b.type===PointerEventTypes.POINTERDOUBLETAP)e.onDoubleTap(j.pointerType);else if(b.type===PointerEventTypes.POINTERUP&&(e._currentActiveButton===j.button||$)){try{_e==null||_e.releasePointerCapture(j.pointerId)}catch{}$||(e.pointB=null),o._badOS?e.pointA=e.pointB=null:e.pointB&&e.pointA&&e.pointA.pointerId==j.pointerId?(e.pointA=e.pointB,e.pointB=null):e.pointA&&e.pointB&&e.pointB.pointerId==j.pointerId?e.pointB=null:e.pointA=e.pointB=null,(c!==0||d)&&(e.onMultiTouch(e.pointA,e.pointB,c,0,d,null),c=0,d=null),e._currentActiveButton=-1,e.onButtonUp(j),i||j.preventDefault()}else if(b.type===PointerEventTypes.POINTERMOVE){if(i||j.preventDefault(),e.pointA&&e.pointB===null){var et=j.clientX-e.pointA.x,tt=j.clientY-e.pointA.y;e.onTouch(e.pointA,et,tt),e.pointA.x=j.clientX,e.pointA.y=j.clientY}else if(e.pointA&&e.pointB){var rt=e.pointA.pointerId===j.pointerId?e.pointA:e.pointB;rt.x=j.clientX,rt.y=j.clientY;var it=e.pointA.x-e.pointB.x,nt=e.pointA.y-e.pointB.y,ot=it*it+nt*nt,at={x:(e.pointA.x+e.pointB.x)/2,y:(e.pointA.y+e.pointB.y)/2,pointerId:j.pointerId,type:b.type};e.onMultiTouch(e.pointA,e.pointB,c,ot,d,at),d=at,c=ot}}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,PointerEventTypes.POINTERDOWN|PointerEventTypes.POINTERUP|PointerEventTypes.POINTERMOVE|PointerEventTypes.POINTERDOUBLETAP),this._onLostFocus=function(){e.pointA=e.pointB=null,c=0,d=null,e.onLostFocus()},s&&s.addEventListener("contextmenu",this.onContextMenu.bind(this),!1);var _=this.camera.getScene().getEngine().getHostWindow();_&&Tools.RegisterTopRootEvents(_,[{name:"blur",handler:this._onLostFocus}])},a.prototype.detachControl=function(i){if(this._onLostFocus){var e=this.camera.getScene().getEngine().getHostWindow();e&&Tools.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this.onContextMenu){var o=this.camera.getScene().getEngine().getInputElement();o&&o.removeEventListener("contextmenu",this.onContextMenu)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0},a.prototype.getClassName=function(){return"BaseCameraPointersInput"},a.prototype.getSimpleName=function(){return"pointers"},a.prototype.onDoubleTap=function(i){},a.prototype.onTouch=function(i,e,o){},a.prototype.onMultiTouch=function(i,e,o,s,c,d){},a.prototype.onContextMenu=function(i){i.preventDefault()},a.prototype.onButtonDown=function(i){},a.prototype.onButtonUp=function(i){},a.prototype.onLostFocus=function(){},__decorate([serialize()],a.prototype,"buttons",void 0),a}(),ArcRotateCameraPointersInput=function(a){__extends(i,a);function i(){var e=a!==null&&a.apply(this,arguments)||this;return e.buttons=[0,1,2],e.angularSensibilityX=1e3,e.angularSensibilityY=1e3,e.pinchPrecision=12,e.pinchDeltaPercentage=0,e.useNaturalPinchZoom=!1,e.pinchZoom=!0,e.panningSensibility=1e3,e.multiTouchPanning=!0,e.multiTouchPanAndZoom=!0,e.pinchInwards=!0,e._isPanClick=!1,e._twoFingerActivityCount=0,e._isPinching=!1,e}return i.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},i.prototype._computeMultiTouchPanning=function(e,o){if(this.panningSensibility!==0&&e&&o){var s=o.x-e.x,c=o.y-e.y;this.camera.inertialPanningX+=-s/this.panningSensibility,this.camera.inertialPanningY+=c/this.panningSensibility}},i.prototype._computePinchZoom=function(e,o){var s=this.camera.radius||i.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=s*Math.sqrt(e)/Math.sqrt(o):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(o-e)*.001*s*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(o-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)},i.prototype.onTouch=function(e,o,s){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-o/this.panningSensibility,this.camera.inertialPanningY+=s/this.panningSensibility):(this.camera.inertialAlphaOffset-=o/this.angularSensibilityX,this.camera.inertialBetaOffset-=s/this.angularSensibilityY)},i.prototype.onDoubleTap=function(e){this.camera.useInputToRestoreState&&this.camera.restoreState()},i.prototype.onMultiTouch=function(e,o,s,c,d,_){s===0&&d===null||c===0&&_===null||(this.multiTouchPanAndZoom?(this._computePinchZoom(s,c),this._computeMultiTouchPanning(d,_)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(c)-Math.sqrt(s))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(s,c),this._isPinching=!0):this._computeMultiTouchPanning(d,_)):this.multiTouchPanning?this._computeMultiTouchPanning(d,_):this.pinchZoom&&this._computePinchZoom(s,c))},i.prototype.onButtonDown=function(e){this._isPanClick=e.button===this.camera._panningMouseButton},i.prototype.onButtonUp=function(e){this._twoFingerActivityCount=0,this._isPinching=!1},i.prototype.onLostFocus=function(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1},i.MinimumRadiusForPinch=.001,__decorate([serialize()],i.prototype,"buttons",void 0),__decorate([serialize()],i.prototype,"angularSensibilityX",void 0),__decorate([serialize()],i.prototype,"angularSensibilityY",void 0),__decorate([serialize()],i.prototype,"pinchPrecision",void 0),__decorate([serialize()],i.prototype,"pinchDeltaPercentage",void 0),__decorate([serialize()],i.prototype,"useNaturalPinchZoom",void 0),__decorate([serialize()],i.prototype,"pinchZoom",void 0),__decorate([serialize()],i.prototype,"panningSensibility",void 0),__decorate([serialize()],i.prototype,"multiTouchPanning",void 0),__decorate([serialize()],i.prototype,"multiTouchPanAndZoom",void 0),i}(BaseCameraPointersInput);CameraInputTypes.ArcRotateCameraPointersInput=ArcRotateCameraPointersInput;var ArcRotateCameraKeyboardMoveInput=function(){function a(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}return a.prototype.attachControl=function(i){var e=this;i=Tools.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){e._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(o){var s=o.event;if(!s.metaKey){if(o.type===KeyboardEventTypes.KEYDOWN){if(e._ctrlPressed=s.ctrlKey,e._altPressed=s.altKey,e.keysUp.indexOf(s.keyCode)!==-1||e.keysDown.indexOf(s.keyCode)!==-1||e.keysLeft.indexOf(s.keyCode)!==-1||e.keysRight.indexOf(s.keyCode)!==-1||e.keysReset.indexOf(s.keyCode)!==-1){var c=e._keys.indexOf(s.keyCode);c===-1&&e._keys.push(s.keyCode),s.preventDefault&&(i||s.preventDefault())}}else if(e.keysUp.indexOf(s.keyCode)!==-1||e.keysDown.indexOf(s.keyCode)!==-1||e.keysLeft.indexOf(s.keyCode)!==-1||e.keysRight.indexOf(s.keyCode)!==-1||e.keysReset.indexOf(s.keyCode)!==-1){var c=e._keys.indexOf(s.keyCode);c>=0&&e._keys.splice(c,1),s.preventDefault&&(i||s.preventDefault())}}}))},a.prototype.detachControl=function(i){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},a.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var i=this.camera,e=0;e<this._keys.length;e++){var o=this._keys[e];this.keysLeft.indexOf(o)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?i.inertialPanningX-=1/this.panningSensibility:i.inertialAlphaOffset-=this.angularSpeed:this.keysUp.indexOf(o)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?i.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?i.inertialRadiusOffset+=1/this.zoomingSensibility:i.inertialBetaOffset-=this.angularSpeed:this.keysRight.indexOf(o)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?i.inertialPanningX+=1/this.panningSensibility:i.inertialAlphaOffset+=this.angularSpeed:this.keysDown.indexOf(o)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?i.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?i.inertialRadiusOffset-=1/this.zoomingSensibility:i.inertialBetaOffset+=this.angularSpeed:this.keysReset.indexOf(o)!==-1&&i.useInputToRestoreState&&i.restoreState()}},a.prototype.getClassName=function(){return"ArcRotateCameraKeyboardMoveInput"},a.prototype.getSimpleName=function(){return"keyboard"},__decorate([serialize()],a.prototype,"keysUp",void 0),__decorate([serialize()],a.prototype,"keysDown",void 0),__decorate([serialize()],a.prototype,"keysLeft",void 0),__decorate([serialize()],a.prototype,"keysRight",void 0),__decorate([serialize()],a.prototype,"keysReset",void 0),__decorate([serialize()],a.prototype,"panningSensibility",void 0),__decorate([serialize()],a.prototype,"zoomingSensibility",void 0),__decorate([serialize()],a.prototype,"useAltToZoom",void 0),__decorate([serialize()],a.prototype,"angularSpeed",void 0),a}();CameraInputTypes.ArcRotateCameraKeyboardMoveInput=ArcRotateCameraKeyboardMoveInput;var ffMultiplier=40,ArcRotateCameraMouseWheelInput=function(){function a(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._inertialPanning=Vector3.Zero()}return a.prototype.computeDeltaFromMouseWheelLegacyEvent=function(i,e){var o=0,s=i*.01*this.wheelDeltaPercentage*e;return i>0?o=s/(1+this.wheelDeltaPercentage):o=s*(1+this.wheelDeltaPercentage),o},a.prototype.attachControl=function(i){var e=this;i=Tools.BackCompatCameraNoPreventDefault(arguments),this._wheel=function(o,s){if(o.type===PointerEventTypes.POINTERWHEEL){var c=o.event,d=0,_=c,b=0,k=c.deltaMode===EventConstants.DOM_DELTA_LINE?ffMultiplier:1;if(c.deltaY!==void 0?b=-(c.deltaY*k):c.wheelDeltaY!==void 0?b=-(c.wheelDeltaY*k):b=_.wheelDelta,e.customComputeDeltaFromMouseWheel)d=e.customComputeDeltaFromMouseWheel(b,e,c);else if(e.wheelDeltaPercentage){if(d=e.computeDeltaFromMouseWheelLegacyEvent(b,e.camera.radius),d>0){for(var j=e.camera.radius,$=e.camera.inertialRadiusOffset+d,_e=0;_e<20&&Math.abs($)>.001;_e++)j-=$,$*=e.camera.inertia;j=Scalar.Clamp(j,0,Number.MAX_VALUE),d=e.computeDeltaFromMouseWheelLegacyEvent(b,j)}}else d=b/(e.wheelPrecision*40);d&&(e.zoomToMouseLocation&&e._hitPlane?e._zoomToMouse(d):e.camera.inertialRadiusOffset+=d),c.preventDefault&&(i||c.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,PointerEventTypes.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)},a.prototype.detachControl=function(i){this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},a.prototype.checkInputs=function(){if(!!this.zoomToMouseLocation){var i=this.camera,e=0+i.inertialAlphaOffset+i.inertialBetaOffset+i.inertialRadiusOffset;e&&(this._updateHitPlane(),i.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(i.inertia),this._zeroIfClose(this._inertialPanning))}},a.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},a.prototype.getSimpleName=function(){return"mousewheel"},a.prototype._updateHitPlane=function(){var i=this.camera,e=i.target.subtract(i.position);this._hitPlane=Plane.FromPositionAndNormal(Vector3.Zero(),e)},a.prototype._getPosition=function(){var i,e=this.camera,o=e.getScene(),s=o.createPickingRay(o.pointerX,o.pointerY,Matrix.Identity(),e,!1),c=0;return this._hitPlane&&(c=(i=s.intersectsPlane(this._hitPlane))!==null&&i!==void 0?i:0),s.origin.addInPlace(s.direction.scaleInPlace(c))},a.prototype._zoomToMouse=function(i){var e,o,s=this.camera,c=1-s.inertia;if(s.lowerRadiusLimit){var d=(e=s.lowerRadiusLimit)!==null&&e!==void 0?e:0;s.radius-(s.inertialRadiusOffset+i)/c<d&&(i=(s.radius-d)*c-s.inertialRadiusOffset)}if(s.upperRadiusLimit){var _=(o=s.upperRadiusLimit)!==null&&o!==void 0?o:0;s.radius-(s.inertialRadiusOffset+i)/c>_&&(i=(s.radius-_)*c-s.inertialRadiusOffset)}var b=i/c,k=b/s.radius,j=this._getPosition(),$=j.subtract(s.target),_e=$.scale(k);_e.scaleInPlace(c),this._inertialPanning.addInPlace(_e),s.inertialRadiusOffset+=i},a.prototype._zeroIfClose=function(i){Math.abs(i.x)<Epsilon&&(i.x=0),Math.abs(i.y)<Epsilon&&(i.y=0),Math.abs(i.z)<Epsilon&&(i.z=0)},__decorate([serialize()],a.prototype,"wheelPrecision",void 0),__decorate([serialize()],a.prototype,"zoomToMouseLocation",void 0),__decorate([serialize()],a.prototype,"wheelDeltaPercentage",void 0),a}();CameraInputTypes.ArcRotateCameraMouseWheelInput=ArcRotateCameraMouseWheelInput;var ArcRotateCameraInputsManager=function(a){__extends(i,a);function i(e){return a.call(this,e)||this}return i.prototype.addMouseWheel=function(){return this.add(new ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new ArcRotateCameraKeyboardMoveInput),this},i}(CameraInputsManager);Node$2.AddNodeConstructor("ArcRotateCamera",function(a,i){return function(){return new ArcRotateCamera(a,0,0,1,Vector3.Zero(),i)}});var ArcRotateCamera=function(a){__extends(i,a);function i(e,o,s,c,d,_,b){b===void 0&&(b=!0);var k=a.call(this,e,Vector3.Zero(),_,b)||this;return k.inertialAlphaOffset=0,k.inertialBetaOffset=0,k.inertialRadiusOffset=0,k.lowerAlphaLimit=null,k.upperAlphaLimit=null,k.lowerBetaLimit=.01,k.upperBetaLimit=Math.PI-.01,k.lowerRadiusLimit=null,k.upperRadiusLimit=null,k.inertialPanningX=0,k.inertialPanningY=0,k.pinchToPanMaxDistance=20,k.panningDistanceLimit=null,k.panningOriginTarget=Vector3.Zero(),k.panningInertia=.9,k.zoomOnFactor=1,k.targetScreenOffset=Vector2.Zero(),k.allowUpsideDown=!0,k.useInputToRestoreState=!0,k._viewMatrix=new Matrix,k.panningAxis=new Vector3(1,1,0),k._transformedDirection=new Vector3,k.mapPanning=!1,k.onMeshTargetChangedObservable=new Observable,k.checkCollisions=!1,k.collisionRadius=new Vector3(.5,.5,.5),k._previousPosition=Vector3.Zero(),k._collisionVelocity=Vector3.Zero(),k._newPosition=Vector3.Zero(),k._computationVector=Vector3.Zero(),k._onCollisionPositionChange=function(j,$,_e){_e===void 0&&(_e=null),_e?(k.setPosition($),k.onCollide&&k.onCollide(_e)):k._previousPosition.copyFrom(k._position);var et=Math.cos(k.alpha),tt=Math.sin(k.alpha),rt=Math.cos(k.beta),it=Math.sin(k.beta);it===0&&(it=1e-4);var nt=k._getTargetPosition();k._computationVector.copyFromFloats(k.radius*et*it,k.radius*rt,k.radius*tt*it),nt.addToRef(k._computationVector,k._newPosition),k._position.copyFrom(k._newPosition);var ot=k.upVector;k.allowUpsideDown&&k.beta<0&&(ot=ot.clone(),ot=ot.negate()),k._computeViewMatrix(k._position,nt,ot),k._viewMatrix.addAtIndex(12,k.targetScreenOffset.x),k._viewMatrix.addAtIndex(13,k.targetScreenOffset.y),k._collisionTriggered=!1},k._target=Vector3.Zero(),d&&k.setTarget(d),k.alpha=o,k.beta=s,k.radius=c,k.getViewMatrix(),k.inputs=new ArcRotateCameraInputsManager(k),k.inputs.addKeyboard().addMouseWheel().addPointers(),k}return Object.defineProperty(i.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"targetHost",{get:function(){return this._targetHost},set:function(e){e&&this.setTarget(e)},enumerable:!1,configurable:!0}),i.prototype.getTarget=function(){return this.target},Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this.setPosition(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"upVector",{get:function(){return this._upVector},set:function(e){this._upToYMatrix||(this._YToUpMatrix=new Matrix,this._upToYMatrix=new Matrix,this._upVector=Vector3.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()},enumerable:!1,configurable:!0}),i.prototype.setMatUp=function(){Matrix.RotationAlignToRef(Vector3.UpReadOnly,this._upVector,this._YToUpMatrix),Matrix.RotationAlignToRef(this._upVector,Vector3.UpReadOnly,this._upToYMatrix)},Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var o=this.inputs.attached.pointers;o&&(o.angularSensibilityX=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var o=this.inputs.attached.pointers;o&&(o.angularSensibilityY=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var o=this.inputs.attached.pointers;o&&(o.pinchPrecision=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var o=this.inputs.attached.pointers;o&&(o.pinchDeltaPercentage=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"useNaturalPinchZoom",{get:function(){var e=this.inputs.attached.pointers;return e?e.useNaturalPinchZoom:!1},set:function(e){var o=this.inputs.attached.pointers;o&&(o.useNaturalPinchZoom=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var o=this.inputs.attached.pointers;o&&(o.panningSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysRight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var o=this.inputs.attached.mousewheel;o&&(o.wheelPrecision=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"zoomToMouseLocation",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.zoomToMouseLocation:!1},set:function(e){var o=this.inputs.attached.mousewheel;o&&(o.zoomToMouseLocation=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var o=this.inputs.attached.mousewheel;o&&(o.wheelDeltaPercentage=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"useBouncingBehavior",{get:function(){return this._bouncingBehavior!=null},set:function(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new BouncingBehavior,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"useFramingBehavior",{get:function(){return this._framingBehavior!=null},set:function(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new FramingBehavior,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"useAutoRotationBehavior",{get:function(){return this._autoRotationBehavior!=null},set:function(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!1,configurable:!0}),i.prototype._initCache=function(){a.prototype._initCache.call(this),this._cache._target=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=Vector2.Zero()},i.prototype._updateCache=function(e){e||a.prototype._updateCache.call(this),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}var o=this._getLockedTargetPosition();return o||this._target},i.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),a.prototype.storeState.call(this)},i.prototype._restoreStateValues=function(){return a.prototype._restoreStateValues.call(this)?(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!1},i.prototype._isSynchronizedViewMatrix=function(){return a.prototype._isSynchronizedViewMatrix.call(this)?this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset):!1},i.prototype.attachControl=function(e,o,s,c){var d=this;s===void 0&&(s=!0),c===void 0&&(c=2),o=Tools.BackCompatCameraNoPreventDefault(arguments),this._useCtrlForPanning=s,this._panningMouseButton=c,typeof arguments[0]=="boolean"&&(arguments.length>1&&(this._useCtrlForPanning=arguments[1]),arguments.length>2&&(this._panningMouseButton=arguments[2])),this.inputs.attachElement(o),this._reset=function(){d.inertialAlphaOffset=0,d.inertialBetaOffset=0,d.inertialRadiusOffset=0,d.inertialPanningX=0,d.inertialPanningY=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(),this._reset&&this._reset()},i.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){var e=this.inertialAlphaOffset;this.beta<=0&&(e*=-1),this.getScene().useRightHandedSystem&&(e*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),this.alpha+=e,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<Epsilon&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<Epsilon&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*Epsilon&&(this.inertialRadiusOffset=0)}if(this.inertialPanningX!==0||this.inertialPanningY!==0){var o=new Vector3(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),o.multiplyInPlace(this.panningAxis),Vector3.TransformNormalToRef(o,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning&&(this._transformedDirection.y=0),!this._targetHost)if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);var s=Vector3.DistanceSquared(this._transformedDirection,this.panningOriginTarget);s<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else this._target.addInPlace(this._transformedDirection);this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*Epsilon&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*Epsilon&&(this.inertialPanningY=0)}this._checkLimits(),a.prototype._checkInputs.call(this)}},i.prototype._checkLimits=function(){this.lowerBetaLimit===null||this.lowerBetaLimit===void 0?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),this.upperBetaLimit===null||this.upperBetaLimit===void 0?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),this.upperAlphaLimit!==null&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),this.upperRadiusLimit!==null&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)},i.prototype.rebuildAnglesAndRadius=function(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&Vector3.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);var e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);var o=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=o*2*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,o,s){if(o===void 0&&(o=!1),s===void 0&&(s=!1),e.getBoundingInfo)o?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var c=e,d=this._getTargetPosition();if(d&&!s&&d.equals(c))return;this._targetHost=null,this._target=c,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},i.prototype._getViewMatrix=function(){var e=Math.cos(this.alpha),o=Math.sin(this.alpha),s=Math.cos(this.beta),c=Math.sin(this.beta);c===0&&(c=1e-4),this.radius===0&&(this.radius=1e-4);var d=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*c,this.radius*s,this.radius*o*c),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&Vector3.TransformCoordinatesToRef(this._computationVector,this._YToUpMatrix,this._computationVector),d.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){var _=this.getScene().collisionCoordinator;this._collider||(this._collider=_.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,_.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);var b=this.upVector;this.allowUpsideDown&&c<0&&(b=b.negate()),this._computeViewMatrix(this._position,d,b),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=d,this._viewMatrix},i.prototype.zoomOn=function(e,o){o===void 0&&(o=!1),e=e||this.getScene().meshes;var s=Mesh.MinMax(e),c=Vector3.Distance(s.min,s.max);this.radius=c*this.zoomOnFactor,this.focusOn({min:s.min,max:s.max,distance:c},o)},i.prototype.focusOn=function(e,o){o===void 0&&(o=!1);var s,c;if(e.min===void 0){var d=e||this.getScene().meshes;s=Mesh.MinMax(d),c=Vector3.Distance(s.min,s.max)}else{var _=e;s=_,c=_.distance}this._target=Mesh.Center(s),o||(this.maxZ=c*2)},i.prototype.createRigCamera=function(e,o){var s=0;switch(this.cameraRigMode){case Camera$1.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Camera$1.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Camera$1.RIG_MODE_STEREOSCOPIC_INTERLACED:case Camera$1.RIG_MODE_VR:s=this._cameraRigParams.stereoHalfAngle*(o===0?1:-1);break;case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:s=this._cameraRigParams.stereoHalfAngle*(o===0?-1:1);break}var c=new i(e,this.alpha+s,this.beta,this.radius,this._target,this.getScene());return c._cameraRigParams={},c.isRigCamera=!0,c.rigParent=this,c.upVector=this.upVector,c},i.prototype._updateRigCameras=function(){var e=this._rigCameras[0],o=this._rigCameras[1];switch(e.beta=o.beta=this.beta,this.cameraRigMode){case Camera$1.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Camera$1.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Camera$1.RIG_MODE_STEREOSCOPIC_INTERLACED:case Camera$1.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,o.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,o.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}a.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),a.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"ArcRotateCamera"},__decorate([serialize()],i.prototype,"alpha",void 0),__decorate([serialize()],i.prototype,"beta",void 0),__decorate([serialize()],i.prototype,"radius",void 0),__decorate([serializeAsVector3("target")],i.prototype,"_target",void 0),__decorate([serializeAsMeshReference("targetHost")],i.prototype,"_targetHost",void 0),__decorate([serialize()],i.prototype,"inertialAlphaOffset",void 0),__decorate([serialize()],i.prototype,"inertialBetaOffset",void 0),__decorate([serialize()],i.prototype,"inertialRadiusOffset",void 0),__decorate([serialize()],i.prototype,"lowerAlphaLimit",void 0),__decorate([serialize()],i.prototype,"upperAlphaLimit",void 0),__decorate([serialize()],i.prototype,"lowerBetaLimit",void 0),__decorate([serialize()],i.prototype,"upperBetaLimit",void 0),__decorate([serialize()],i.prototype,"lowerRadiusLimit",void 0),__decorate([serialize()],i.prototype,"upperRadiusLimit",void 0),__decorate([serialize()],i.prototype,"inertialPanningX",void 0),__decorate([serialize()],i.prototype,"inertialPanningY",void 0),__decorate([serialize()],i.prototype,"pinchToPanMaxDistance",void 0),__decorate([serialize()],i.prototype,"panningDistanceLimit",void 0),__decorate([serializeAsVector3()],i.prototype,"panningOriginTarget",void 0),__decorate([serialize()],i.prototype,"panningInertia",void 0),__decorate([serialize()],i.prototype,"zoomToMouseLocation",null),__decorate([serialize()],i.prototype,"zoomOnFactor",void 0),__decorate([serialize()],i.prototype,"targetScreenOffset",void 0),__decorate([serialize()],i.prototype,"allowUpsideDown",void 0),__decorate([serialize()],i.prototype,"useInputToRestoreState",void 0),i}(TargetCamera),FreeCameraKeyboardMoveInput=function(){function a(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this._keys=new Array}return a.prototype.attachControl=function(i){var e=this;i=Tools.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){e._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(o){var s=o.event;if(!s.metaKey){if(o.type===KeyboardEventTypes.KEYDOWN){if(e.keysUp.indexOf(s.keyCode)!==-1||e.keysDown.indexOf(s.keyCode)!==-1||e.keysLeft.indexOf(s.keyCode)!==-1||e.keysRight.indexOf(s.keyCode)!==-1||e.keysUpward.indexOf(s.keyCode)!==-1||e.keysDownward.indexOf(s.keyCode)!==-1||e.keysRotateLeft.indexOf(s.keyCode)!==-1||e.keysRotateRight.indexOf(s.keyCode)!==-1){var c=e._keys.indexOf(s.keyCode);c===-1&&e._keys.push(s.keyCode),i||s.preventDefault()}}else if(e.keysUp.indexOf(s.keyCode)!==-1||e.keysDown.indexOf(s.keyCode)!==-1||e.keysLeft.indexOf(s.keyCode)!==-1||e.keysRight.indexOf(s.keyCode)!==-1||e.keysUpward.indexOf(s.keyCode)!==-1||e.keysDownward.indexOf(s.keyCode)!==-1||e.keysRotateLeft.indexOf(s.keyCode)!==-1||e.keysRotateRight.indexOf(s.keyCode)!==-1){var c=e._keys.indexOf(s.keyCode);c>=0&&e._keys.splice(c,1),i||s.preventDefault()}}}))},a.prototype.detachControl=function(i){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys=[]},a.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var i=this.camera,e=0;e<this._keys.length;e++){var o=this._keys[e],s=i._computeLocalCameraSpeed();this.keysLeft.indexOf(o)!==-1?i._localDirection.copyFromFloats(-s,0,0):this.keysUp.indexOf(o)!==-1?i._localDirection.copyFromFloats(0,0,s):this.keysRight.indexOf(o)!==-1?i._localDirection.copyFromFloats(s,0,0):this.keysDown.indexOf(o)!==-1?i._localDirection.copyFromFloats(0,0,-s):this.keysUpward.indexOf(o)!==-1?i._localDirection.copyFromFloats(0,s,0):this.keysDownward.indexOf(o)!==-1?i._localDirection.copyFromFloats(0,-s,0):this.keysRotateLeft.indexOf(o)!==-1?(i._localDirection.copyFromFloats(0,0,0),i.cameraRotation.y-=this._getLocalRotation()):this.keysRotateRight.indexOf(o)!==-1&&(i._localDirection.copyFromFloats(0,0,0),i.cameraRotation.y+=this._getLocalRotation()),i.getScene().useRightHandedSystem&&(i._localDirection.z*=-1),i.getViewMatrix().invertToRef(i._cameraTransformMatrix),Vector3.TransformNormalToRef(i._localDirection,i._cameraTransformMatrix,i._transformedDirection),i.cameraDirection.addInPlace(i._transformedDirection)}},a.prototype.getClassName=function(){return"FreeCameraKeyboardMoveInput"},a.prototype._onLostFocus=function(){this._keys=[]},a.prototype.getSimpleName=function(){return"keyboard"},a.prototype._getLocalRotation=function(){var i=this.rotationSpeed*this._engine.getDeltaTime()/1e3;return this.camera.getScene().useRightHandedSystem&&(i*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(i*=-1),i},__decorate([serialize()],a.prototype,"keysUp",void 0),__decorate([serialize()],a.prototype,"keysUpward",void 0),__decorate([serialize()],a.prototype,"keysDown",void 0),__decorate([serialize()],a.prototype,"keysDownward",void 0),__decorate([serialize()],a.prototype,"keysLeft",void 0),__decorate([serialize()],a.prototype,"keysRight",void 0),__decorate([serialize()],a.prototype,"rotationSpeed",void 0),__decorate([serialize()],a.prototype,"keysRotateLeft",void 0),__decorate([serialize()],a.prototype,"keysRotateRight",void 0),a}();CameraInputTypes.FreeCameraKeyboardMoveInput=FreeCameraKeyboardMoveInput;var FreeCameraMouseInput=function(){function a(i){i===void 0&&(i=!0),this.touchEnabled=i,this.buttons=[0,1,2],this.angularSensibility=2e3,this.previousPosition=null,this.onPointerMovedObservable=new Observable,this._allowCameraRotation=!0,this._currentActiveButton=-1}return a.prototype.attachControl=function(i){var e=this;i=Tools.BackCompatCameraNoPreventDefault(arguments);var o=this.camera.getEngine(),s=o.getInputElement();this._pointerInput||(this._pointerInput=function(c){var d=c.event,_=d.pointerType==="touch";if(!o.isInVRExclusivePointerMode&&!(!e.touchEnabled&&_)&&!(c.type!==PointerEventTypes.POINTERMOVE&&e.buttons.indexOf(d.button)===-1)){var b=d.srcElement||d.target;if(c.type===PointerEventTypes.POINTERDOWN&&(e._currentActiveButton===-1||_)){try{b==null||b.setPointerCapture(d.pointerId)}catch{}e._currentActiveButton===-1&&(e._currentActiveButton=d.button),e.previousPosition={x:d.clientX,y:d.clientY},i||(d.preventDefault(),s&&s.focus()),o.isPointerLock&&e._onMouseMove&&e._onMouseMove(c.event)}else if(c.type===PointerEventTypes.POINTERUP&&(e._currentActiveButton===d.button||_)){try{b==null||b.releasePointerCapture(d.pointerId)}catch{}e._currentActiveButton=-1,e.previousPosition=null,i||d.preventDefault()}else if(c.type===PointerEventTypes.POINTERMOVE){if(o.isPointerLock&&e._onMouseMove)e._onMouseMove(c.event);else if(e.previousPosition){var k=d.clientX-e.previousPosition.x,j=d.clientY-e.previousPosition.y;e.camera.getScene().useRightHandedSystem&&(k*=-1),e.camera.parent&&e.camera.parent._getWorldMatrixDeterminant()<0&&(k*=-1),e._allowCameraRotation&&(e.camera.cameraRotation.y+=k/e.angularSensibility,e.camera.cameraRotation.x+=j/e.angularSensibility),e.onPointerMovedObservable.notifyObservers({offsetX:k,offsetY:j}),e.previousPosition={x:d.clientX,y:d.clientY},i||d.preventDefault()}}}}),this._onMouseMove=function(c){if(!!o.isPointerLock&&!o.isInVRExclusivePointerMode){var d=c.movementX||c.mozMovementX||c.webkitMovementX||c.msMovementX||0;e.camera.getScene().useRightHandedSystem&&(d*=-1),e.camera.parent&&e.camera.parent._getWorldMatrixDeterminant()<0&&(d*=-1),e.camera.cameraRotation.y+=d/e.angularSensibility;var _=c.movementY||c.mozMovementY||c.webkitMovementY||c.msMovementY||0;e.camera.cameraRotation.x+=_/e.angularSensibility,e.previousPosition=null,i||c.preventDefault()}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,PointerEventTypes.POINTERDOWN|PointerEventTypes.POINTERUP|PointerEventTypes.POINTERMOVE),s&&s.addEventListener("contextmenu",this.onContextMenu.bind(this),!1)},a.prototype.onContextMenu=function(i){i.preventDefault()},a.prototype.detachControl=function(i){if(this._observer){if(this.camera.getScene().onPointerObservable.remove(this._observer),this.onContextMenu){var e=this.camera.getEngine(),o=e.getInputElement();o&&o.removeEventListener("contextmenu",this.onContextMenu)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this.previousPosition=null}},a.prototype.getClassName=function(){return"FreeCameraMouseInput"},a.prototype.getSimpleName=function(){return"mouse"},__decorate([serialize()],a.prototype,"buttons",void 0),__decorate([serialize()],a.prototype,"angularSensibility",void 0),a}();CameraInputTypes.FreeCameraMouseInput=FreeCameraMouseInput;var BaseCameraMouseWheelInput=function(){function a(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new Observable,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}return a.prototype.attachControl=function(i){var e=this;i=Tools.BackCompatCameraNoPreventDefault(arguments),this._wheel=function(o){if(o.type===PointerEventTypes.POINTERWHEEL){var s=o.event,c=s.deltaMode===EventConstants.DOM_DELTA_LINE?e._ffMultiplier:1;s.deltaY!==void 0?(e._wheelDeltaX+=e.wheelPrecisionX*c*s.deltaX/e._normalize,e._wheelDeltaY-=e.wheelPrecisionY*c*s.deltaY/e._normalize,e._wheelDeltaZ+=e.wheelPrecisionZ*c*s.deltaZ/e._normalize):s.wheelDeltaY!==void 0?(e._wheelDeltaX+=e.wheelPrecisionX*c*s.wheelDeltaX/e._normalize,e._wheelDeltaY-=e.wheelPrecisionY*c*s.wheelDeltaY/e._normalize,e._wheelDeltaZ+=e.wheelPrecisionZ*c*s.wheelDeltaZ/e._normalize):s.wheelDelta&&(e._wheelDeltaY-=e.wheelPrecisionY*s.wheelDelta/e._normalize),s.preventDefault&&(i||s.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,PointerEventTypes.POINTERWHEEL)},a.prototype.detachControl=function(i){this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()},a.prototype.checkInputs=function(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0},a.prototype.getClassName=function(){return"BaseCameraMouseWheelInput"},a.prototype.getSimpleName=function(){return"mousewheel"},__decorate([serialize()],a.prototype,"wheelPrecisionX",void 0),__decorate([serialize()],a.prototype,"wheelPrecisionY",void 0),__decorate([serialize()],a.prototype,"wheelPrecisionZ",void 0),a}(),_CameraProperty;(function(a){a[a.MoveRelative=0]="MoveRelative",a[a.RotateRelative=1]="RotateRelative",a[a.MoveScene=2]="MoveScene"})(_CameraProperty||(_CameraProperty={}));var FreeCameraMouseWheelInput=function(a){__extends(i,a);function i(){var e=a!==null&&a.apply(this,arguments)||this;return e._moveRelative=Vector3.Zero(),e._rotateRelative=Vector3.Zero(),e._moveScene=Vector3.Zero(),e._wheelXAction=_CameraProperty.MoveRelative,e._wheelXActionCoordinate=Coordinate.X,e._wheelYAction=_CameraProperty.MoveRelative,e._wheelYActionCoordinate=Coordinate.Z,e._wheelZAction=null,e._wheelZActionCoordinate=null,e}return i.prototype.getClassName=function(){return"FreeCameraMouseWheelInput"},Object.defineProperty(i.prototype,"wheelXMoveRelative",{get:function(){return this._wheelXAction!==_CameraProperty.MoveRelative?null:this._wheelXActionCoordinate},set:function(e){e===null&&this._wheelXAction!==_CameraProperty.MoveRelative||(this._wheelXAction=_CameraProperty.MoveRelative,this._wheelXActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelYMoveRelative",{get:function(){return this._wheelYAction!==_CameraProperty.MoveRelative?null:this._wheelYActionCoordinate},set:function(e){e===null&&this._wheelYAction!==_CameraProperty.MoveRelative||(this._wheelYAction=_CameraProperty.MoveRelative,this._wheelYActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelZMoveRelative",{get:function(){return this._wheelZAction!==_CameraProperty.MoveRelative?null:this._wheelZActionCoordinate},set:function(e){e===null&&this._wheelZAction!==_CameraProperty.MoveRelative||(this._wheelZAction=_CameraProperty.MoveRelative,this._wheelZActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelXRotateRelative",{get:function(){return this._wheelXAction!==_CameraProperty.RotateRelative?null:this._wheelXActionCoordinate},set:function(e){e===null&&this._wheelXAction!==_CameraProperty.RotateRelative||(this._wheelXAction=_CameraProperty.RotateRelative,this._wheelXActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelYRotateRelative",{get:function(){return this._wheelYAction!==_CameraProperty.RotateRelative?null:this._wheelYActionCoordinate},set:function(e){e===null&&this._wheelYAction!==_CameraProperty.RotateRelative||(this._wheelYAction=_CameraProperty.RotateRelative,this._wheelYActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelZRotateRelative",{get:function(){return this._wheelZAction!==_CameraProperty.RotateRelative?null:this._wheelZActionCoordinate},set:function(e){e===null&&this._wheelZAction!==_CameraProperty.RotateRelative||(this._wheelZAction=_CameraProperty.RotateRelative,this._wheelZActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelXMoveScene",{get:function(){return this._wheelXAction!==_CameraProperty.MoveScene?null:this._wheelXActionCoordinate},set:function(e){e===null&&this._wheelXAction!==_CameraProperty.MoveScene||(this._wheelXAction=_CameraProperty.MoveScene,this._wheelXActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelYMoveScene",{get:function(){return this._wheelYAction!==_CameraProperty.MoveScene?null:this._wheelYActionCoordinate},set:function(e){e===null&&this._wheelYAction!==_CameraProperty.MoveScene||(this._wheelYAction=_CameraProperty.MoveScene,this._wheelYActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"wheelZMoveScene",{get:function(){return this._wheelZAction!==_CameraProperty.MoveScene?null:this._wheelZActionCoordinate},set:function(e){e===null&&this._wheelZAction!==_CameraProperty.MoveScene||(this._wheelZAction=_CameraProperty.MoveScene,this._wheelZActionCoordinate=e)},enumerable:!1,configurable:!0}),i.prototype.checkInputs=function(){if(!(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)){this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);var e=Matrix.Zero();this.camera.getViewMatrix().invertToRef(e);var o=Vector3.Zero();Vector3.TransformNormalToRef(this._moveRelative,e,o),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(o),this.camera.cameraDirection.addInPlace(this._moveScene),a.prototype.checkInputs.call(this)}},i.prototype._updateCamera=function(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)},i.prototype._updateCameraProperty=function(e,o,s){if(e!==0&&!(o===null||s===null)){var c=null;switch(o){case _CameraProperty.MoveRelative:c=this._moveRelative;break;case _CameraProperty.RotateRelative:c=this._rotateRelative;break;case _CameraProperty.MoveScene:c=this._moveScene;break}switch(s){case Coordinate.X:c.set(e,0,0);break;case Coordinate.Y:c.set(0,e,0);break;case Coordinate.Z:c.set(0,0,e);break}}},__decorate([serialize()],i.prototype,"wheelXMoveRelative",null),__decorate([serialize()],i.prototype,"wheelYMoveRelative",null),__decorate([serialize()],i.prototype,"wheelZMoveRelative",null),__decorate([serialize()],i.prototype,"wheelXRotateRelative",null),__decorate([serialize()],i.prototype,"wheelYRotateRelative",null),__decorate([serialize()],i.prototype,"wheelZRotateRelative",null),__decorate([serialize()],i.prototype,"wheelXMoveScene",null),__decorate([serialize()],i.prototype,"wheelYMoveScene",null),__decorate([serialize()],i.prototype,"wheelZMoveScene",null),i}(BaseCameraMouseWheelInput);CameraInputTypes.FreeCameraMouseWheelInput=FreeCameraMouseWheelInput;var FreeCameraTouchInput=function(){function a(i){i===void 0&&(i=!1),this.allowMouse=i,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array}return a.prototype.attachControl=function(i){var e=this;i=Tools.BackCompatCameraNoPreventDefault(arguments);var o=null;if(this._pointerInput===void 0&&(this._onLostFocus=function(){e._offsetX=null,e._offsetY=null},this._pointerInput=function(d){var _=d.event,b=!e.camera.getEngine().hostInformation.isMobile&&_ instanceof MouseEvent;if(!(!e.allowMouse&&(_.pointerType==="mouse"||b))){if(d.type===PointerEventTypes.POINTERDOWN){if(i||_.preventDefault(),e._pointerPressed.push(_.pointerId),e._pointerPressed.length!==1)return;o={x:_.clientX,y:_.clientY}}else if(d.type===PointerEventTypes.POINTERUP){i||_.preventDefault();var k=e._pointerPressed.indexOf(_.pointerId);if(k===-1||(e._pointerPressed.splice(k,1),k!=0))return;o=null,e._offsetX=null,e._offsetY=null}else if(d.type===PointerEventTypes.POINTERMOVE){if(i||_.preventDefault(),!o)return;var k=e._pointerPressed.indexOf(_.pointerId);if(k!=0)return;e._offsetX=_.clientX-o.x,e._offsetY=-(_.clientY-o.y)}}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,PointerEventTypes.POINTERDOWN|PointerEventTypes.POINTERUP|PointerEventTypes.POINTERMOVE),this._onLostFocus){var s=this.camera.getEngine(),c=s.getInputElement();c&&c.addEventListener("blur",this._onLostFocus)}},a.prototype.detachControl=function(i){if(this._pointerInput){if(this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null),this._onLostFocus){var e=this.camera.getEngine(),o=e.getInputElement();o&&o.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed=[],this._offsetX=null,this._offsetY=null}},a.prototype.checkInputs=function(){if(!(this._offsetX===null||this._offsetY===null)&&!(this._offsetX===0&&this._offsetY===0)){var i=this.camera;i.cameraRotation.y=this._offsetX/this.touchAngularSensibility;var e=this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1;if(e)i.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{var o=i._computeLocalCameraSpeed(),s=new Vector3(0,0,o*this._offsetY/this.touchMoveSensibility);Matrix.RotationYawPitchRollToRef(i.rotation.y,i.rotation.x,0,i._cameraRotationMatrix),i.cameraDirection.addInPlace(Vector3.TransformCoordinates(s,i._cameraRotationMatrix))}}},a.prototype.getClassName=function(){return"FreeCameraTouchInput"},a.prototype.getSimpleName=function(){return"touch"},__decorate([serialize()],a.prototype,"touchAngularSensibility",void 0),__decorate([serialize()],a.prototype,"touchMoveSensibility",void 0),a}();CameraInputTypes.FreeCameraTouchInput=FreeCameraTouchInput;var FreeCameraInputsManager=function(a){__extends(i,a);function i(e){var o=a.call(this,e)||this;return o._mouseInput=null,o._mouseWheelInput=null,o}return i.prototype.addKeyboard=function(){return this.add(new FreeCameraKeyboardMoveInput),this},i.prototype.addMouse=function(e){return e===void 0&&(e=!0),this._mouseInput||(this._mouseInput=new FreeCameraMouseInput(e),this.add(this._mouseInput)),this},i.prototype.removeMouse=function(){return this._mouseInput&&this.remove(this._mouseInput),this},i.prototype.addMouseWheel=function(){return this._mouseWheelInput||(this._mouseWheelInput=new FreeCameraMouseWheelInput,this.add(this._mouseWheelInput)),this},i.prototype.removeMouseWheel=function(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this},i.prototype.addTouch=function(){return this.add(new FreeCameraTouchInput),this},i.prototype.clear=function(){a.prototype.clear.call(this),this._mouseInput=null},i}(CameraInputsManager),FreeCamera=function(a){__extends(i,a);function i(e,o,s,c){c===void 0&&(c=!0);var d=a.call(this,e,o,s,c)||this;return d.ellipsoid=new Vector3(.5,1,.5),d.ellipsoidOffset=new Vector3(0,0,0),d.checkCollisions=!1,d.applyGravity=!1,d._needMoveForGravity=!1,d._oldPosition=Vector3.Zero(),d._diffPosition=Vector3.Zero(),d._newPosition=Vector3.Zero(),d._collisionMask=-1,d._onCollisionPositionChange=function(_,b,k){k===void 0&&(k=null);var j=function($){d._newPosition.copyFrom($),d._newPosition.subtractToRef(d._oldPosition,d._diffPosition),d._diffPosition.length()>Engine.CollisionsEpsilon&&(d.position.addInPlace(d._diffPosition),d.onCollide&&k&&d.onCollide(k))};j(b)},d.inputs=new FreeCameraInputsManager(d),d.inputs.addKeyboard().addMouse(),d}return Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var o=this.inputs.attached.mouse;o&&(o.angularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysUpward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUpward:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysUpward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysDownward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDownward:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysDownward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysRight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysRotateLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysRotateLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"keysRotateRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]},set:function(e){var o=this.inputs.attached.keyboard;o&&(o.keysRotateRight=e)},enumerable:!1,configurable:!0}),i.prototype.attachControl=function(e,o){o=Tools.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(o)},i.prototype.detachControl=function(e){this.inputs.detachElement(),this.cameraDirection=new Vector3(0,0,0),this.cameraRotation=new Vector2(0,0)},Object.defineProperty(i.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),i.prototype._collideWithWorld=function(e){var o;this.parent?o=Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):o=this.position,o.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var s=this.getScene().collisionCoordinator;this._collider||(this._collider=s.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var c=e;this.applyGravity&&(c=e.add(this.getScene().gravity)),s.getNewPosition(this._oldPosition,c,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=Vector3.Zero(),this._transformedDirection=Vector3.Zero()),this.inputs.checkInputs(),a.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):a.prototype._updatePosition.call(this)},i.prototype.dispose=function(){this.inputs.clear(),a.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"FreeCamera"},__decorate([serializeAsVector3()],i.prototype,"ellipsoid",void 0),__decorate([serializeAsVector3()],i.prototype,"ellipsoidOffset",void 0),__decorate([serialize()],i.prototype,"checkCollisions",void 0),__decorate([serialize()],i.prototype,"applyGravity",void 0),i}(TargetCamera),ShadowLight=function(a){__extends(i,a);function i(){var e=a!==null&&a.apply(this,arguments)||this;return e._needProjectionMatrixCompute=!0,e}return i.prototype._setPosition=function(e){this._position=e},Object.defineProperty(i.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!1,configurable:!0}),i.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),i.prototype.computeTransformedInformation=function(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=Vector3.Zero()),Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=Vector3.Zero()),Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1},i.prototype.getDepthScale=function(){return 50},i.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(e){return this.direction=Vector3.Normalize(e.subtract(this.position)),this.direction},i.prototype.getRotation=function(){this.direction.normalize();var e=Vector3.Cross(this.direction,Axis.Y),o=Vector3.Cross(e,this.direction);return Vector3.RotationFromAxis(e,o,this.direction)},i.prototype.needCube=function(){return!1},i.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},i.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},i.prototype._initCache=function(){a.prototype._initCache.call(this),this._cache.position=Vector3.Zero()},i.prototype._isSynchronized=function(){return!!this._cache.position.equals(this.position)},i.prototype.computeWorldMatrix=function(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=Matrix.Identity()),Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)},i.prototype.getDepthMinZ=function(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ},i.prototype.getDepthMaxZ=function(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ},i.prototype.setShadowProjectionMatrix=function(e,o,s){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(o,s,e):this._setDefaultShadowProjectionMatrix(e,o,s),this},__decorate([serializeAsVector3()],i.prototype,"position",null),__decorate([serializeAsVector3()],i.prototype,"direction",null),__decorate([serialize()],i.prototype,"shadowMinZ",null),__decorate([serialize()],i.prototype,"shadowMaxZ",null),i}(Light);Node$2.AddNodeConstructor("Light_Type_1",function(a,i){return function(){return new DirectionalLight(a,Vector3.Zero(),i)}});var DirectionalLight=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,s)||this;return c._shadowFrustumSize=0,c._shadowOrthoScale=.1,c.autoUpdateExtends=!0,c.autoCalcShadowZBounds=!1,c._orthoLeft=Number.MAX_VALUE,c._orthoRight=Number.MIN_VALUE,c._orthoTop=Number.MIN_VALUE,c._orthoBottom=Number.MAX_VALUE,c.position=o.scale(-1),c.direction=o,c}return Object.defineProperty(i.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"orthoLeft",{get:function(){return this._orthoLeft},set:function(e){this._orthoLeft=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"orthoRight",{get:function(){return this._orthoRight},set:function(e){this._orthoRight=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"orthoTop",{get:function(){return this._orthoTop},set:function(e){this._orthoTop=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"orthoBottom",{get:function(){return this._orthoBottom},set:function(e){this._orthoBottom=e},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"DirectionalLight"},i.prototype.getTypeID=function(){return Light.LIGHTTYPEID_DIRECTIONALLIGHT},i.prototype._setDefaultShadowProjectionMatrix=function(e,o,s){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,o,s)},i.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(e){var o=this.getScene().activeCamera;!o||Matrix.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:o.minZ,this.shadowMaxZ!==void 0?this.shadowMaxZ:o.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)},i.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(e,o,s){var c=this.getScene().activeCamera;if(!!c){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var d=Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var _=Number.MAX_VALUE,b=Number.MIN_VALUE,k=0;k<s.length;k++){var j=s[k];if(!!j)for(var $=j.getBoundingInfo(),_e=$.boundingBox,et=0;et<_e.vectorsWorld.length;et++)Vector3.TransformCoordinatesToRef(_e.vectorsWorld[et],o,d),d.x<this._orthoLeft&&(this._orthoLeft=d.x),d.y<this._orthoBottom&&(this._orthoBottom=d.y),d.x>this._orthoRight&&(this._orthoRight=d.x),d.y>this._orthoTop&&(this._orthoTop=d.y),this.autoCalcShadowZBounds&&(d.z<_&&(_=d.z),d.z>b&&(b=d.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=_,this._shadowMaxZ=b)}var tt=this._orthoRight-this._orthoLeft,rt=this._orthoTop-this._orthoBottom,it=this.shadowMinZ!==void 0?this.shadowMinZ:c.minZ,nt=this.shadowMaxZ!==void 0?this.shadowMaxZ:c.maxZ,ot=this.getScene().getEngine().useReverseDepthBuffer;Matrix.OrthoOffCenterLHToRef(this._orthoLeft-tt*this.shadowOrthoScale,this._orthoRight+tt*this.shadowOrthoScale,this._orthoBottom-rt*this.shadowOrthoScale,this._orthoTop+rt*this.shadowOrthoScale,ot?nt:it,ot?it:nt,e,this.getScene().getEngine().isNDCHalfZRange)}},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,o){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,o),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,o),this)},i.prototype.transferToNodeMaterialEffect=function(e,o){return this.computeTransformedInformation()?(e.setFloat3(o,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(o,this.direction.x,this.direction.y,this.direction.z),this)},i.prototype.getDepthMinZ=function(e){var o=this._scene.getEngine();return!o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1},i.prototype.getDepthMaxZ=function(e){var o=this._scene.getEngine();return o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1},i.prototype.prepareLightSpecificDefines=function(e,o){e["DIRLIGHT"+o]=!0},__decorate([serialize()],i.prototype,"shadowFrustumSize",null),__decorate([serialize()],i.prototype,"shadowOrthoScale",null),__decorate([serialize()],i.prototype,"autoUpdateExtends",void 0),__decorate([serialize()],i.prototype,"autoCalcShadowZBounds",void 0),__decorate([serialize("orthoLeft")],i.prototype,"_orthoLeft",void 0),__decorate([serialize("orthoRight")],i.prototype,"_orthoRight",void 0),__decorate([serialize("orthoTop")],i.prototype,"_orthoTop",void 0),__decorate([serialize("orthoBottom")],i.prototype,"_orthoBottom",void 0),i}(ShadowLight);Node$2.AddNodeConstructor("Light_Type_3",function(a,i){return function(){return new HemisphericLight(a,Vector3.Zero(),i)}});var HemisphericLight=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,s)||this;return c.groundColor=new Color3(0,0,0),c.direction=o||Vector3.Up(),c}return i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.getClassName=function(){return"HemisphericLight"},i.prototype.setDirectionToTarget=function(e){return this.direction=Vector3.Normalize(e.subtract(Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(e,o){var s=Vector3.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",s.x,s.y,s.z,0,o),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),o),this},i.prototype.transferToNodeMaterialEffect=function(e,o){var s=Vector3.Normalize(this.direction);return e.setFloat3(o,s.x,s.y,s.z),this},i.prototype.computeWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return Light.LIGHTTYPEID_HEMISPHERICLIGHT},i.prototype.prepareLightSpecificDefines=function(e,o){e["HEMILIGHT"+o]=!0},__decorate([serializeAsColor3()],i.prototype,"groundColor",void 0),__decorate([serializeAsVector3()],i.prototype,"direction",void 0),i}(Light),name$2D="kernelBlurVaryingDeclaration",shader$2D="varying vec2 sampleCoord{X};";ShaderStore.IncludesShadersStore[name$2D]=shader$2D;var name$2C="packingFunctions",shader$2C=`vec4 pack(float depth)
  792. {
  793. const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);
  794. const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);
  795. vec4 res=fract(depth*bit_shift);
  796. res-=res.xxyz*bit_mask;
  797. return res;
  798. }
  799. float unpack(vec4 color)
  800. {
  801. const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);
  802. return dot(color,bit_shift);
  803. }`;ShaderStore.IncludesShadersStore[name$2C]=shader$2C;var name$2B="kernelBlurFragment",shader$2B=`#ifdef DOF
  804. factor=sampleCoC(sampleCoord{X});
  805. computedWeight=KERNEL_WEIGHT{X}*factor;
  806. sumOfWeights+=computedWeight;
  807. #else
  808. computedWeight=KERNEL_WEIGHT{X};
  809. #endif
  810. #ifdef PACKEDFLOAT
  811. blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;
  812. #else
  813. blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;
  814. #endif`;ShaderStore.IncludesShadersStore[name$2B]=shader$2B;var name$2A="kernelBlurFragment2",shader$2A=`#ifdef DOF
  815. factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});
  816. computedWeight=KERNEL_DEP_WEIGHT{X}*factor;
  817. sumOfWeights+=computedWeight;
  818. #else
  819. computedWeight=KERNEL_DEP_WEIGHT{X};
  820. #endif
  821. #ifdef PACKEDFLOAT
  822. blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
  823. #else
  824. blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;
  825. #endif`;ShaderStore.IncludesShadersStore[name$2A]=shader$2A;var name$2z="kernelBlurPixelShader",shader$2z=`
  826. uniform sampler2D textureSampler;
  827. uniform vec2 delta;
  828. varying vec2 sampleCenter;
  829. #ifdef DOF
  830. uniform sampler2D circleOfConfusionSampler;
  831. uniform vec2 cameraMinMaxZ;
  832. float sampleDistance(in vec2 offset) {
  833. float depth=texture2D(circleOfConfusionSampler,offset).g;
  834. return cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth;
  835. }
  836. float sampleCoC(in vec2 offset) {
  837. float coc=texture2D(circleOfConfusionSampler,offset).r;
  838. return coc;
  839. }
  840. #endif
  841. #include<kernelBlurVaryingDeclaration>[0..varyingCount]
  842. #ifdef PACKEDFLOAT
  843. #include<packingFunctions>
  844. #endif
  845. void main(void)
  846. {
  847. float computedWeight=0.0;
  848. #ifdef PACKEDFLOAT
  849. float blend=0.;
  850. #else
  851. vec4 blend=vec4(0.);
  852. #endif
  853. #ifdef DOF
  854. float sumOfWeights=CENTER_WEIGHT;
  855. float factor=0.0;
  856. #ifdef PACKEDFLOAT
  857. blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;
  858. #else
  859. blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;
  860. #endif
  861. #endif
  862. #include<kernelBlurFragment>[0..varyingCount]
  863. #include<kernelBlurFragment2>[0..depCount]
  864. #ifdef PACKEDFLOAT
  865. gl_FragColor=pack(blend);
  866. #else
  867. gl_FragColor=blend;
  868. #endif
  869. #ifdef DOF
  870. gl_FragColor/=sumOfWeights;
  871. #endif
  872. }`;ShaderStore.ShadersStore[name$2z]=shader$2z;var name$2y="kernelBlurVertex",shader$2y="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";ShaderStore.IncludesShadersStore[name$2y]=shader$2y;var name$2x="kernelBlurVertexShader",shader$2x=`
  873. attribute vec2 position;
  874. uniform vec2 delta;
  875. varying vec2 sampleCenter;
  876. #include<kernelBlurVaryingDeclaration>[0..varyingCount]
  877. const vec2 madd=vec2(0.5,0.5);
  878. void main(void) {
  879. sampleCenter=(position*madd+madd);
  880. #include<kernelBlurVertex>[0..varyingCount]
  881. gl_Position=vec4(position,0.0,1.0);
  882. }`;ShaderStore.ShadersStore[name$2x]=shader$2x;var BlurPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$,_e){_===void 0&&(_=Texture.BILINEAR_SAMPLINGMODE),j===void 0&&(j=0),$===void 0&&($=""),_e===void 0&&(_e=!1);var et=a.call(this,e,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],c,d,_,b,k,null,j,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return et.blockCompilation=_e,et._packedFloat=!1,et._staticDefines="",et._staticDefines=$,et.direction=o,et.onApplyObservable.add(function(tt){et._outputTexture?tt.setFloat2("delta",1/et._outputTexture.width*et.direction.x,1/et._outputTexture.height*et.direction.y):tt.setFloat2("delta",1/et.width*et.direction.x,1/et.height*et.direction.y)}),et.kernel=s,et}return Object.defineProperty(i.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.blockCompilation||this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this.blockCompilation||this._updateParameters())},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"BlurPostProcess"},i.prototype.updateEffect=function(e,o,s,c,d,_){this._updateParameters(d,_)},i.prototype._updateParameters=function(e,o){for(var s=this._kernel,c=(s-1)/2,d=[],_=[],b=0,k=0;k<s;k++){var j=k/(s-1),$=this._gaussianWeight(j*2-1);d[k]=k-c,_[k]=$,b+=$}for(var k=0;k<_.length;k++)_[k]/=b;for(var _e=[],et=[],tt=[],k=0;k<=c;k+=2){var rt=Math.min(k+1,Math.floor(c)),it=k===rt;if(it)tt.push({o:d[k],w:_[k]});else{var nt=rt===c,ot=_[k]+_[rt]*(nt?.5:1),at=d[k]+1/(1+_[k]/_[rt]);at===0?(tt.push({o:d[k],w:_[k]}),tt.push({o:d[k+1],w:_[k+1]})):(tt.push({o:at,w:ot}),tt.push({o:-at,w:ot}))}}for(var k=0;k<tt.length;k++)et[k]=tt[k].o,_e[k]=tt[k].w;d=et,_=_e;var st=this.getEngine().getCaps().maxVaryingVectors,ut=Math.max(st,0)-1,ft=Math.min(d.length,ut),lt="";lt+=this._staticDefines,this._staticDefines.indexOf("DOF")!=-1&&(lt+="#define CENTER_WEIGHT "+this._glslFloat(_[ft-1])+`\r
  883. `,ft--);for(var k=0;k<ft;k++)lt+="#define KERNEL_OFFSET"+k+" "+this._glslFloat(d[k])+`\r
  884. `,lt+="#define KERNEL_WEIGHT"+k+" "+this._glslFloat(_[k])+`\r
  885. `;for(var ht=0,k=ut;k<d.length;k++)lt+="#define KERNEL_DEP_OFFSET"+ht+" "+this._glslFloat(d[k])+`\r
  886. `,lt+="#define KERNEL_DEP_WEIGHT"+ht+" "+this._glslFloat(_[k])+`\r
  887. `,ht++;this.packedFloat&&(lt+="#define PACKEDFLOAT 1"),this.blockCompilation=!1,a.prototype.updateEffect.call(this,lt,null,null,{varyingCount:ft,depCount:ht},e,o)},i.prototype._nearestBestKernel=function(e){for(var o=Math.round(e),s=0,c=[o,o-1,o+1,o-2,o+2];s<c.length;s++){var d=c[s];if(d%2!==0&&Math.floor(d/2)%2===0&&d>0)return Math.max(d,3)}return Math.max(o,3)},i.prototype._gaussianWeight=function(e){var o=.3333333333333333,s=Math.sqrt(2*Math.PI)*o,c=-(e*e/(2*o*o)),d=1/s*Math.exp(c);return d},i.prototype._glslFloat=function(e,o){return o===void 0&&(o=8),e.toFixed(o).replace(/0+$/,"")},i._Parse=function(e,o,s,c){return SerializationHelper.Parse(function(){return new i(e.name,e.direction,e.kernel,e.options,o,e.renderTargetSamplingMode,s.getEngine(),e.reusable,e.textureType,void 0,!1)},e,s,c)},__decorate([serialize("kernel")],i.prototype,"_kernel",void 0),__decorate([serialize("packedFloat")],i.prototype,"_packedFloat",void 0),__decorate([serializeAsVector2()],i.prototype,"direction",void 0),i}(PostProcess);RegisterClass("BABYLON.BlurPostProcess",BlurPostProcess);var EffectFallbacks=function(){function a(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}return a.prototype.unBindMesh=function(){this._mesh=null},a.prototype.addFallback=function(i,e){this._defines[i]||(i<this._currentRank&&(this._currentRank=i),i>this._maxRank&&(this._maxRank=i),this._defines[i]=new Array),this._defines[i].push(e)},a.prototype.addCPUSkinningFallback=function(i,e){this._mesh=e,i<this._currentRank&&(this._currentRank=i),i>this._maxRank&&(this._maxRank=i)},Object.defineProperty(a.prototype,"hasMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!1,configurable:!0}),a.prototype.reduce=function(i,e){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,i=i.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),e._bonesComputationForcedToCPU=!0;for(var o=this._mesh.getScene(),s=0;s<o.meshes.length;s++){var c=o.meshes[s];if(!c.material){!this._mesh.material&&c.computeBonesUsingShaders&&c.numBoneInfluencers>0&&(c.computeBonesUsingShaders=!1);continue}if(!(!c.computeBonesUsingShaders||c.numBoneInfluencers===0)){if(c.material.getEffect()===e)c.computeBonesUsingShaders=!1;else if(c.subMeshes)for(var d=0,_=c.subMeshes;d<_.length;d++){var b=_[d],k=b.effect;if(k===e){c.computeBonesUsingShaders=!1;break}}}}}else{var j=this._defines[this._currentRank];if(j)for(var s=0;s<j.length;s++)i=i.replace("#define "+j[s],"");this._currentRank++}return i},a}(),name$2w="bayerDitherFunctions",shader$2w=`
  888. float bayerDither2(vec2 _P) {
  889. return mod(2.0*_P.y+_P.x+1.0,4.0);
  890. }
  891. float bayerDither4(vec2 _P) {
  892. vec2 P1=mod(_P,2.0);
  893. vec2 P2=floor(0.5*mod(_P,4.0));
  894. return 4.0*bayerDither2(P1)+bayerDither2(P2);
  895. }
  896. float bayerDither8(vec2 _P) {
  897. vec2 P1=mod(_P,2.0);
  898. vec2 P2=floor(0.5*mod(_P,4.0));
  899. vec2 P4=floor(0.25*mod(_P,8.0));
  900. return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);
  901. }
  902. `;ShaderStore.IncludesShadersStore[name$2w]=shader$2w;var name$2v="shadowMapFragmentExtraDeclaration",shader$2v=`#if SM_FLOAT == 0
  903. #include<packingFunctions>
  904. #endif
  905. #if SM_SOFTTRANSPARENTSHADOW == 1
  906. #include<bayerDitherFunctions>
  907. uniform float softTransparentShadowSM;
  908. #endif
  909. varying float vDepthMetricSM;
  910. #if SM_USEDISTANCE == 1
  911. uniform vec3 lightDataSM;
  912. varying vec3 vPositionWSM;
  913. #endif
  914. uniform vec3 biasAndScaleSM;
  915. uniform vec2 depthValuesSM;
  916. #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
  917. varying float zSM;
  918. #endif
  919. `;ShaderStore.IncludesShadersStore[name$2v]=shader$2v;var name$2u="clipPlaneFragmentDeclaration",shader$2u=`#ifdef CLIPPLANE
  920. varying float fClipDistance;
  921. #endif
  922. #ifdef CLIPPLANE2
  923. varying float fClipDistance2;
  924. #endif
  925. #ifdef CLIPPLANE3
  926. varying float fClipDistance3;
  927. #endif
  928. #ifdef CLIPPLANE4
  929. varying float fClipDistance4;
  930. #endif
  931. #ifdef CLIPPLANE5
  932. varying float fClipDistance5;
  933. #endif
  934. #ifdef CLIPPLANE6
  935. varying float fClipDistance6;
  936. #endif`;ShaderStore.IncludesShadersStore[name$2u]=shader$2u;var name$2t="clipPlaneFragment",shader$2t=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
  937. if (false) {}
  938. #endif
  939. #ifdef CLIPPLANE
  940. else if (fClipDistance>0.0)
  941. {
  942. discard;
  943. }
  944. #endif
  945. #ifdef CLIPPLANE2
  946. else if (fClipDistance2>0.0)
  947. {
  948. discard;
  949. }
  950. #endif
  951. #ifdef CLIPPLANE3
  952. else if (fClipDistance3>0.0)
  953. {
  954. discard;
  955. }
  956. #endif
  957. #ifdef CLIPPLANE4
  958. else if (fClipDistance4>0.0)
  959. {
  960. discard;
  961. }
  962. #endif
  963. #ifdef CLIPPLANE5
  964. else if (fClipDistance5>0.0)
  965. {
  966. discard;
  967. }
  968. #endif
  969. #ifdef CLIPPLANE6
  970. else if (fClipDistance6>0.0)
  971. {
  972. discard;
  973. }
  974. #endif`;ShaderStore.IncludesShadersStore[name$2t]=shader$2t;var name$2s="shadowMapFragment",shader$2s=` float depthSM=vDepthMetricSM;
  975. #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
  976. #if SM_USEDISTANCE == 1
  977. depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
  978. #else
  979. #ifdef USE_REVERSE_DEPTHBUFFER
  980. depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
  981. #else
  982. depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
  983. #endif
  984. #endif
  985. #ifdef USE_REVERSE_DEPTHBUFFER
  986. gl_FragDepth=clamp(1.0-depthSM,0.0,1.0);
  987. #else
  988. gl_FragDepth=clamp(depthSM,0.0,1.0);
  989. #endif
  990. #elif SM_USEDISTANCE == 1
  991. depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
  992. #endif
  993. #if SM_ESM == 1
  994. depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);
  995. #endif
  996. #if SM_FLOAT == 1
  997. gl_FragColor=vec4(depthSM,1.0,1.0,1.0);
  998. #else
  999. gl_FragColor=pack(depthSM);
  1000. #endif
  1001. return;`;ShaderStore.IncludesShadersStore[name$2s]=shader$2s;var name$2r="shadowMapPixelShader",shader$2r=`#include<shadowMapFragmentExtraDeclaration>
  1002. #ifdef ALPHATEST
  1003. varying vec2 vUV;
  1004. uniform sampler2D diffuseSampler;
  1005. #endif
  1006. #include<clipPlaneFragmentDeclaration>
  1007. void main(void)
  1008. {
  1009. #include<clipPlaneFragment>
  1010. #ifdef ALPHATEST
  1011. float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;
  1012. if (alphaFromAlphaTexture<0.4)
  1013. discard;
  1014. #endif
  1015. #if SM_SOFTTRANSPARENTSHADOW == 1
  1016. #ifdef ALPHATEST
  1017. if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard;
  1018. #else
  1019. if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;
  1020. #endif
  1021. #endif
  1022. #include<shadowMapFragment>
  1023. }`;ShaderStore.ShadersStore[name$2r]=shader$2r;var name$2q="bonesDeclaration",shader$2q=`#if NUM_BONE_INFLUENCERS>0
  1024. attribute vec4 matricesIndices;
  1025. attribute vec4 matricesWeights;
  1026. #if NUM_BONE_INFLUENCERS>4
  1027. attribute vec4 matricesIndicesExtra;
  1028. attribute vec4 matricesWeightsExtra;
  1029. #endif
  1030. #ifndef BAKED_VERTEX_ANIMATION_TEXTURE
  1031. #ifdef BONETEXTURE
  1032. uniform sampler2D boneSampler;
  1033. uniform float boneTextureWidth;
  1034. #else
  1035. uniform mat4 mBones[BonesPerMesh];
  1036. #ifdef BONES_VELOCITY_ENABLED
  1037. uniform mat4 mPreviousBones[BonesPerMesh];
  1038. #endif
  1039. #endif
  1040. #ifdef BONETEXTURE
  1041. #define inline
  1042. mat4 readMatrixFromRawSampler(sampler2D smp,float index)
  1043. {
  1044. float offset=index*4.0;
  1045. float dx=1.0/boneTextureWidth;
  1046. vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));
  1047. vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));
  1048. vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));
  1049. vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));
  1050. return mat4(m0,m1,m2,m3);
  1051. }
  1052. #endif
  1053. #endif
  1054. #endif`;ShaderStore.IncludesShadersStore[name$2q]=shader$2q;var name$2p="bakedVertexAnimationDeclaration",shader$2p=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
  1055. uniform float bakedVertexAnimationTime;
  1056. uniform vec2 bakedVertexAnimationTextureSizeInverted;
  1057. uniform vec4 bakedVertexAnimationSettings;
  1058. uniform sampler2D bakedVertexAnimationTexture;
  1059. #ifdef INSTANCES
  1060. attribute vec4 bakedVertexAnimationSettingsInstanced;
  1061. attribute float bakedVertexAnimationTimeInstanced;
  1062. #endif
  1063. #define inline
  1064. mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)
  1065. {
  1066. float offset=index*4.0;
  1067. float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;
  1068. float dx=bakedVertexAnimationTextureSizeInverted.x;
  1069. vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));
  1070. vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));
  1071. vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));
  1072. vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));
  1073. return mat4(m0,m1,m2,m3);
  1074. }
  1075. #endif`;ShaderStore.IncludesShadersStore[name$2p]=shader$2p;var name$2o="morphTargetsVertexGlobalDeclaration",shader$2o=`#ifdef MORPHTARGETS
  1076. uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];
  1077. #ifdef MORPHTARGETS_TEXTURE
  1078. precision mediump sampler2DArray;
  1079. uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];
  1080. uniform vec3 morphTargetTextureInfo;
  1081. uniform sampler2DArray morphTargets;
  1082. vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)
  1083. {
  1084. float y=floor(vertexIndex/morphTargetTextureInfo.y);
  1085. float x=vertexIndex-y*morphTargetTextureInfo.y;
  1086. vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);
  1087. return texture(morphTargets,textureUV).xyz;
  1088. }
  1089. #endif
  1090. #endif`;ShaderStore.IncludesShadersStore[name$2o]=shader$2o;var name$2n="morphTargetsVertexDeclaration",shader$2n=`#ifdef MORPHTARGETS
  1091. #ifndef MORPHTARGETS_TEXTURE
  1092. attribute vec3 position{X};
  1093. #ifdef MORPHTARGETS_NORMAL
  1094. attribute vec3 normal{X};
  1095. #endif
  1096. #ifdef MORPHTARGETS_TANGENT
  1097. attribute vec3 tangent{X};
  1098. #endif
  1099. #ifdef MORPHTARGETS_UV
  1100. attribute vec2 uv_{X};
  1101. #endif
  1102. #endif
  1103. #endif`;ShaderStore.IncludesShadersStore[name$2n]=shader$2n;var name$2m="sceneVertexDeclaration",shader$2m=`uniform mat4 viewProjection;
  1104. #ifdef MULTIVIEW
  1105. uniform mat4 viewProjectionR;
  1106. #endif
  1107. uniform mat4 view;
  1108. uniform mat4 projection;
  1109. uniform vec4 vEyePosition;
  1110. `;ShaderStore.IncludesShadersStore[name$2m]=shader$2m;var name$2l="meshVertexDeclaration",shader$2l=`uniform mat4 world;
  1111. uniform float visibility;
  1112. `;ShaderStore.IncludesShadersStore[name$2l]=shader$2l;var name$2k="shadowMapVertexDeclaration",shader$2k=`#include<sceneVertexDeclaration>
  1113. #include<meshVertexDeclaration>
  1114. `;ShaderStore.IncludesShadersStore[name$2k]=shader$2k;var name$2j="sceneUboDeclaration",shader$2j=`layout(std140,column_major) uniform;
  1115. uniform Scene {
  1116. mat4 viewProjection;
  1117. #ifdef MULTIVIEW
  1118. mat4 viewProjectionR;
  1119. #endif
  1120. mat4 view;
  1121. mat4 projection;
  1122. vec4 vEyePosition;
  1123. };
  1124. `;ShaderStore.IncludesShadersStore[name$2j]=shader$2j;var name$2i="meshUboDeclaration",shader$2i=`layout(std140,column_major) uniform;
  1125. uniform Mesh
  1126. {
  1127. mat4 world;
  1128. float visibility;
  1129. };
  1130. #define WORLD_UBO`;ShaderStore.IncludesShadersStore[name$2i]=shader$2i;var name$2h="shadowMapUboDeclaration",shader$2h=`layout(std140,column_major) uniform;
  1131. #include<sceneUboDeclaration>
  1132. #include<meshUboDeclaration>
  1133. `;ShaderStore.IncludesShadersStore[name$2h]=shader$2h;var name$2g="shadowMapVertexExtraDeclaration",shader$2g=`#if SM_NORMALBIAS == 1
  1134. uniform vec3 lightDataSM;
  1135. #endif
  1136. uniform vec3 biasAndScaleSM;
  1137. uniform vec2 depthValuesSM;
  1138. varying float vDepthMetricSM;
  1139. #if SM_USEDISTANCE == 1
  1140. varying vec3 vPositionWSM;
  1141. #endif
  1142. #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
  1143. varying float zSM;
  1144. #endif
  1145. `;ShaderStore.IncludesShadersStore[name$2g]=shader$2g;var name$2f="clipPlaneVertexDeclaration",shader$2f=`#ifdef CLIPPLANE
  1146. uniform vec4 vClipPlane;
  1147. varying float fClipDistance;
  1148. #endif
  1149. #ifdef CLIPPLANE2
  1150. uniform vec4 vClipPlane2;
  1151. varying float fClipDistance2;
  1152. #endif
  1153. #ifdef CLIPPLANE3
  1154. uniform vec4 vClipPlane3;
  1155. varying float fClipDistance3;
  1156. #endif
  1157. #ifdef CLIPPLANE4
  1158. uniform vec4 vClipPlane4;
  1159. varying float fClipDistance4;
  1160. #endif
  1161. #ifdef CLIPPLANE5
  1162. uniform vec4 vClipPlane5;
  1163. varying float fClipDistance5;
  1164. #endif
  1165. #ifdef CLIPPLANE6
  1166. uniform vec4 vClipPlane6;
  1167. varying float fClipDistance6;
  1168. #endif`;ShaderStore.IncludesShadersStore[name$2f]=shader$2f;var name$2e="morphTargetsVertexGlobal",shader$2e=`#ifdef MORPHTARGETS
  1169. #ifdef MORPHTARGETS_TEXTURE
  1170. float vertexID;
  1171. #endif
  1172. #endif`;ShaderStore.IncludesShadersStore[name$2e]=shader$2e;var name$2d="morphTargetsVertex",shader$2d=`#ifdef MORPHTARGETS
  1173. #ifdef MORPHTARGETS_TEXTURE
  1174. vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;
  1175. positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];
  1176. vertexID+=1.0;
  1177. #ifdef MORPHTARGETS_NORMAL
  1178. normalUpdated+=(readVector3FromRawSampler({X},vertexID)-normal)*morphTargetInfluences[{X}];
  1179. vertexID+=1.0;
  1180. #endif
  1181. #ifdef MORPHTARGETS_UV
  1182. uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];
  1183. vertexID+=1.0;
  1184. #endif
  1185. #ifdef MORPHTARGETS_TANGENT
  1186. tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID)-tangent.xyz)*morphTargetInfluences[{X}];
  1187. #endif
  1188. #else
  1189. positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];
  1190. #ifdef MORPHTARGETS_NORMAL
  1191. normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];
  1192. #endif
  1193. #ifdef MORPHTARGETS_TANGENT
  1194. tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];
  1195. #endif
  1196. #ifdef MORPHTARGETS_UV
  1197. uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];
  1198. #endif
  1199. #endif
  1200. #endif`;ShaderStore.IncludesShadersStore[name$2d]=shader$2d;var name$2c="instancesVertex",shader$2c=`#ifdef INSTANCES
  1201. mat4 finalWorld=mat4(world0,world1,world2,world3);
  1202. #if defined(PREPASS_VELOCITY) || defined(VELOCITY)
  1203. mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);
  1204. #endif
  1205. #ifdef THIN_INSTANCES
  1206. finalWorld=world*finalWorld;
  1207. #if defined(PREPASS_VELOCITY) || defined(VELOCITY)
  1208. finalPreviousWorld=previousWorld*finalPreviousWorld;
  1209. #endif
  1210. #endif
  1211. #else
  1212. mat4 finalWorld=world;
  1213. #if defined(PREPASS_VELOCITY) || defined(VELOCITY)
  1214. mat4 finalPreviousWorld=previousWorld;
  1215. #endif
  1216. #endif`;ShaderStore.IncludesShadersStore[name$2c]=shader$2c;var name$2b="bonesVertex",shader$2b=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
  1217. #if NUM_BONE_INFLUENCERS>0
  1218. mat4 influence;
  1219. #ifdef BONETEXTURE
  1220. influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
  1221. #if NUM_BONE_INFLUENCERS>1
  1222. influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
  1223. #endif
  1224. #if NUM_BONE_INFLUENCERS>2
  1225. influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
  1226. #endif
  1227. #if NUM_BONE_INFLUENCERS>3
  1228. influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
  1229. #endif
  1230. #if NUM_BONE_INFLUENCERS>4
  1231. influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
  1232. #endif
  1233. #if NUM_BONE_INFLUENCERS>5
  1234. influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
  1235. #endif
  1236. #if NUM_BONE_INFLUENCERS>6
  1237. influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
  1238. #endif
  1239. #if NUM_BONE_INFLUENCERS>7
  1240. influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
  1241. #endif
  1242. #else
  1243. influence=mBones[int(matricesIndices[0])]*matricesWeights[0];
  1244. #if NUM_BONE_INFLUENCERS>1
  1245. influence+=mBones[int(matricesIndices[1])]*matricesWeights[1];
  1246. #endif
  1247. #if NUM_BONE_INFLUENCERS>2
  1248. influence+=mBones[int(matricesIndices[2])]*matricesWeights[2];
  1249. #endif
  1250. #if NUM_BONE_INFLUENCERS>3
  1251. influence+=mBones[int(matricesIndices[3])]*matricesWeights[3];
  1252. #endif
  1253. #if NUM_BONE_INFLUENCERS>4
  1254. influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
  1255. #endif
  1256. #if NUM_BONE_INFLUENCERS>5
  1257. influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
  1258. #endif
  1259. #if NUM_BONE_INFLUENCERS>6
  1260. influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
  1261. #endif
  1262. #if NUM_BONE_INFLUENCERS>7
  1263. influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
  1264. #endif
  1265. #endif
  1266. finalWorld=finalWorld*influence;
  1267. #endif
  1268. #endif`;ShaderStore.IncludesShadersStore[name$2b]=shader$2b;var name$2a="bakedVertexAnimation",shader$2a=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
  1269. {
  1270. #ifdef INSTANCES
  1271. #define BVASNAME bakedVertexAnimationSettingsInstanced
  1272. #else
  1273. #define BVASNAME bakedVertexAnimationSettings
  1274. #endif
  1275. float VATStartFrame=BVASNAME.x;
  1276. float VATEndFrame=BVASNAME.y;
  1277. float VATOffsetFrame=BVASNAME.z;
  1278. float VATSpeed=BVASNAME.w;
  1279. float totalFrames=VATEndFrame-VATStartFrame+1.0;
  1280. #ifdef INSTANCES
  1281. float time=bakedVertexAnimationTimeInstanced*VATSpeed/totalFrames;
  1282. #else
  1283. float time=bakedVertexAnimationTime*VATSpeed/totalFrames;
  1284. #endif
  1285. float frameCorrection=time<1.0 ? 0.0 : 1.0;
  1286. float numOfFrames=totalFrames-frameCorrection;
  1287. float VATFrameNum=fract(time)*numOfFrames;
  1288. VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);
  1289. VATFrameNum=floor(VATFrameNum);
  1290. VATFrameNum+=VATStartFrame+frameCorrection;
  1291. mat4 VATInfluence;
  1292. VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
  1293. #if NUM_BONE_INFLUENCERS>1
  1294. VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
  1295. #endif
  1296. #if NUM_BONE_INFLUENCERS>2
  1297. VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
  1298. #endif
  1299. #if NUM_BONE_INFLUENCERS>3
  1300. VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
  1301. #endif
  1302. #if NUM_BONE_INFLUENCERS>4
  1303. VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
  1304. #endif
  1305. #if NUM_BONE_INFLUENCERS>5
  1306. VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
  1307. #endif
  1308. #if NUM_BONE_INFLUENCERS>6
  1309. VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
  1310. #endif
  1311. #if NUM_BONE_INFLUENCERS>7
  1312. VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
  1313. #endif
  1314. finalWorld=finalWorld*VATInfluence;
  1315. }
  1316. #endif`;ShaderStore.IncludesShadersStore[name$2a]=shader$2a;var name$29="shadowMapVertexNormalBias",shader$29=`
  1317. #if SM_NORMALBIAS == 1
  1318. #if SM_DIRECTIONINLIGHTDATA == 1
  1319. vec3 worldLightDirSM=normalize(-lightDataSM.xyz);
  1320. #else
  1321. vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;
  1322. vec3 worldLightDirSM=normalize(directionToLightSM);
  1323. #endif
  1324. float ndlSM=dot(vNormalW,worldLightDirSM);
  1325. float sinNLSM=sqrt(1.0-ndlSM*ndlSM);
  1326. float normalBiasSM=biasAndScaleSM.y*sinNLSM;
  1327. worldPos.xyz-=vNormalW*normalBiasSM;
  1328. #endif
  1329. `;ShaderStore.IncludesShadersStore[name$29]=shader$29;var name$28="shadowMapVertexMetric",shader$28=`#if SM_USEDISTANCE == 1
  1330. vPositionWSM=worldPos.xyz;
  1331. #endif
  1332. #if SM_DEPTHTEXTURE == 1
  1333. #ifdef IS_NDC_HALF_ZRANGE
  1334. #define BIASFACTOR 0.5
  1335. #else
  1336. #define BIASFACTOR 1.0
  1337. #endif
  1338. #ifdef USE_REVERSE_DEPTHBUFFER
  1339. gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
  1340. #else
  1341. gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
  1342. #endif
  1343. #endif
  1344. #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
  1345. zSM=gl_Position.z;
  1346. gl_Position.z=0.0;
  1347. #elif SM_USEDISTANCE == 0
  1348. #ifdef USE_REVERSE_DEPTHBUFFER
  1349. vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
  1350. #else
  1351. vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
  1352. #endif
  1353. #endif
  1354. `;ShaderStore.IncludesShadersStore[name$28]=shader$28;var name$27="clipPlaneVertex",shader$27=`#ifdef CLIPPLANE
  1355. fClipDistance=dot(worldPos,vClipPlane);
  1356. #endif
  1357. #ifdef CLIPPLANE2
  1358. fClipDistance2=dot(worldPos,vClipPlane2);
  1359. #endif
  1360. #ifdef CLIPPLANE3
  1361. fClipDistance3=dot(worldPos,vClipPlane3);
  1362. #endif
  1363. #ifdef CLIPPLANE4
  1364. fClipDistance4=dot(worldPos,vClipPlane4);
  1365. #endif
  1366. #ifdef CLIPPLANE5
  1367. fClipDistance5=dot(worldPos,vClipPlane5);
  1368. #endif
  1369. #ifdef CLIPPLANE6
  1370. fClipDistance6=dot(worldPos,vClipPlane6);
  1371. #endif`;ShaderStore.IncludesShadersStore[name$27]=shader$27;var name$26="shadowMapVertexShader",shader$26=`
  1372. attribute vec3 position;
  1373. #ifdef NORMAL
  1374. attribute vec3 normal;
  1375. #endif
  1376. #include<bonesDeclaration>
  1377. #include<bakedVertexAnimationDeclaration>
  1378. #include<morphTargetsVertexGlobalDeclaration>
  1379. #include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
  1380. #ifdef INSTANCES
  1381. attribute vec4 world0;
  1382. attribute vec4 world1;
  1383. attribute vec4 world2;
  1384. attribute vec4 world3;
  1385. #endif
  1386. #include<helperFunctions>
  1387. #include<__decl__shadowMapVertex>
  1388. #ifdef ALPHATEST
  1389. varying vec2 vUV;
  1390. uniform mat4 diffuseMatrix;
  1391. #ifdef UV1
  1392. attribute vec2 uv;
  1393. #endif
  1394. #ifdef UV2
  1395. attribute vec2 uv2;
  1396. #endif
  1397. #endif
  1398. #include<shadowMapVertexExtraDeclaration>
  1399. #include<clipPlaneVertexDeclaration>
  1400. void main(void)
  1401. {
  1402. vec3 positionUpdated=position;
  1403. #ifdef UV1
  1404. vec2 uvUpdated=uv;
  1405. #endif
  1406. #ifdef NORMAL
  1407. vec3 normalUpdated=normal;
  1408. #endif
  1409. #include<morphTargetsVertexGlobal>
  1410. #include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
  1411. #include<instancesVertex>
  1412. #include<bonesVertex>
  1413. #include<bakedVertexAnimation>
  1414. vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
  1415. #ifdef NORMAL
  1416. mat3 normWorldSM=mat3(finalWorld);
  1417. #if defined(INSTANCES) && defined(THIN_INSTANCES)
  1418. vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));
  1419. vNormalW=normalize(normWorldSM*vNormalW);
  1420. #else
  1421. #ifdef NONUNIFORMSCALING
  1422. normWorldSM=transposeMat3(inverseMat3(normWorldSM));
  1423. #endif
  1424. vec3 vNormalW=normalize(normWorldSM*normalUpdated);
  1425. #endif
  1426. #endif
  1427. #include<shadowMapVertexNormalBias>
  1428. gl_Position=viewProjection*worldPos;
  1429. #include<shadowMapVertexMetric>
  1430. #ifdef ALPHATEST
  1431. #ifdef UV1
  1432. vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
  1433. #endif
  1434. #ifdef UV2
  1435. vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
  1436. #endif
  1437. #endif
  1438. #include<clipPlaneVertex>
  1439. }`;ShaderStore.ShadersStore[name$26]=shader$26;var name$25="depthBoxBlurPixelShader",shader$25=`
  1440. varying vec2 vUV;
  1441. uniform sampler2D textureSampler;
  1442. uniform vec2 screenSize;
  1443. void main(void)
  1444. {
  1445. vec4 colorDepth=vec4(0.0);
  1446. for (int x=-OFFSET; x<=OFFSET; x++)
  1447. for (int y=-OFFSET; y<=OFFSET; y++)
  1448. colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);
  1449. gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));
  1450. }`;ShaderStore.ShadersStore[name$25]=shader$25;var name$24="shadowMapFragmentSoftTransparentShadow",shader$24=`#if SM_SOFTTRANSPARENTSHADOW == 1
  1451. if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;
  1452. #endif
  1453. `;ShaderStore.IncludesShadersStore[name$24]=shader$24;var ShadowGenerator=function(){function a(i,e,o){this.onBeforeShadowMapRenderObservable=new Observable,this.onAfterShadowMapRenderObservable=new Observable,this.onBeforeShadowMapRenderMeshObservable=new Observable,this.onAfterShadowMapRenderMeshObservable=new Observable,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=a.FILTER_NONE,this._filteringQuality=a.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=Vector3.Zero(),this._viewMatrix=Matrix.Zero(),this._projectionMatrix=Matrix.Zero(),this._transformMatrix=Matrix.Zero(),this._cachedPosition=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=Matrix.Identity(),this._mapSize=i,this._light=e,this._scene=e.getScene(),e._shadowGenerator=this,this.id=e.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer('Scene for Shadow Generator (light "'+this._light.name+'")'))),a._SceneComponentInitialization(this._scene);var s=this._scene.getEngine().getCaps();o?s.textureFloatRender&&s.textureFloatLinearFiltering?this._textureType=1:s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?this._textureType=2:s.textureFloatRender&&s.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}return Object.defineProperty(a.prototype,"bias",{get:function(){return this._bias},set:function(i){this._bias=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"normalBias",{get:function(){return this._normalBias},set:function(i){this._normalBias=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(i){this._blurBoxOffset!==i&&(this._blurBoxOffset=i,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"blurScale",{get:function(){return this._blurScale},set:function(i){this._blurScale!==i&&(this._blurScale=i,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"blurKernel",{get:function(){return this._blurKernel},set:function(i){this._blurKernel!==i&&(this._blurKernel=i,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useKernelBlur",{get:function(){return this._useKernelBlur},set:function(i){this._useKernelBlur!==i&&(this._useKernelBlur=i,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"depthScale",{get:function(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()},set:function(i){this._depthScale=i},enumerable:!1,configurable:!0}),a.prototype._validateFilter=function(i){return i},Object.defineProperty(a.prototype,"filter",{get:function(){return this._filter},set:function(i){if(i=this._validateFilter(i),this._light.needCube()){if(i===a.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(i===a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(i===a.FILTER_PCF||i===a.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((i===a.FILTER_PCF||i===a.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==i&&(this._filter=i,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"usePoissonSampling",{get:function(){return this.filter===a.FILTER_POISSONSAMPLING},set:function(i){var e=this._validateFilter(a.FILTER_POISSONSAMPLING);!i&&this.filter!==a.FILTER_POISSONSAMPLING||(this.filter=i?e:a.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useExponentialShadowMap",{get:function(){return this.filter===a.FILTER_EXPONENTIALSHADOWMAP},set:function(i){var e=this._validateFilter(a.FILTER_EXPONENTIALSHADOWMAP);!i&&this.filter!==a.FILTER_EXPONENTIALSHADOWMAP||(this.filter=i?e:a.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useBlurExponentialShadowMap",{get:function(){return this.filter===a.FILTER_BLUREXPONENTIALSHADOWMAP},set:function(i){var e=this._validateFilter(a.FILTER_BLUREXPONENTIALSHADOWMAP);!i&&this.filter!==a.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=i?e:a.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useCloseExponentialShadowMap",{get:function(){return this.filter===a.FILTER_CLOSEEXPONENTIALSHADOWMAP},set:function(i){var e=this._validateFilter(a.FILTER_CLOSEEXPONENTIALSHADOWMAP);!i&&this.filter!==a.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=i?e:a.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useBlurCloseExponentialShadowMap",{get:function(){return this.filter===a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP},set:function(i){var e=this._validateFilter(a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!i&&this.filter!==a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=i?e:a.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"usePercentageCloserFiltering",{get:function(){return this.filter===a.FILTER_PCF},set:function(i){var e=this._validateFilter(a.FILTER_PCF);!i&&this.filter!==a.FILTER_PCF||(this.filter=i?e:a.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"filteringQuality",{get:function(){return this._filteringQuality},set:function(i){this._filteringQuality!==i&&(this._filteringQuality=i,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useContactHardeningShadow",{get:function(){return this.filter===a.FILTER_PCSS},set:function(i){var e=this._validateFilter(a.FILTER_PCSS);!i&&this.filter!==a.FILTER_PCSS||(this.filter=i?e:a.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"contactHardeningLightSizeUVRatio",{get:function(){return this._contactHardeningLightSizeUVRatio},set:function(i){this._contactHardeningLightSizeUVRatio=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"darkness",{get:function(){return this._darkness},set:function(i){this.setDarkness(i)},enumerable:!1,configurable:!0}),a.prototype.getDarkness=function(){return this._darkness},a.prototype.setDarkness=function(i){return i>=1?this._darkness=1:i<=0?this._darkness=0:this._darkness=i,this},Object.defineProperty(a.prototype,"transparencyShadow",{get:function(){return this._transparencyShadow},set:function(i){this.setTransparencyShadow(i)},enumerable:!1,configurable:!0}),a.prototype.setTransparencyShadow=function(i){return this._transparencyShadow=i,this},a.prototype.getShadowMap=function(){return this._shadowMap},a.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},a.prototype.getClassName=function(){return a.CLASSNAME},a.prototype.addShadowCaster=function(i,e){if(e===void 0&&(e=!0),!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i),e)for(var o=0,s=i.getChildMeshes();o<s.length;o++){var c=s[o];this._shadowMap.renderList.indexOf(c)===-1&&this._shadowMap.renderList.push(c)}return this},a.prototype.removeShadowCaster=function(i,e){if(e===void 0&&(e=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var o=this._shadowMap.renderList.indexOf(i);if(o!==-1&&this._shadowMap.renderList.splice(o,1),e)for(var s=0,c=i.getChildren();s<c.length;s++){var d=c[s];this.removeShadowCaster(d)}return this},a.prototype.getLight=function(){return this._light},Object.defineProperty(a.prototype,"mapSize",{get:function(){return this._mapSize},set:function(i){this._mapSize=i,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()},enumerable:!1,configurable:!0}),a.prototype._initializeGenerator=function(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()},a.prototype._createTargetRenderTexture=function(){var i=this._scene.getEngine();i._features.supportDepthStencilTexture?(this._shadowMap=new RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(i.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube())},a.prototype._initializeShadowMap=function(){var i=this;if(this._createTargetRenderTexture(),this._shadowMap!==null){this._shadowMap.wrapU=Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.customIsReadyFunction=function(d,_){return!0};var e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(function(){var d;i._currentSceneUBO=i._scene.getSceneUniformBuffer(),(d=e._debugPushGroup)===null||d===void 0||d.call(e,"shadow map generation for pass id "+e.currentRenderPassId,1)}),this._shadowMap.onBeforeRenderObservable.add(function(d){i._sceneUBOs&&i._scene.setSceneUniformBuffer(i._sceneUBOs[0]),i._currentFaceIndex=d,i._filter===a.FILTER_PCF&&e.setColorWrite(!1),i.getTransformMatrix(),i._scene.setTransformMatrix(i._viewMatrix,i._projectionMatrix),i._useUBO&&(i._scene.getSceneUniformBuffer().unbindEffect(),i._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(function(){var d,_;if(i._sceneUBOs&&i._scene.setSceneUniformBuffer(i._currentSceneUBO),i._scene.updateTransformMatrix(),i._filter===a.FILTER_PCF&&e.setColorWrite(!0),!i.useBlurExponentialShadowMap&&!i.useBlurCloseExponentialShadowMap){(d=e._debugPopGroup)===null||d===void 0||d.call(e,1);return}var b=i.getShadowMapForRendering();b&&(i._scene.postProcessManager.directRender(i._blurPostProcesses,b.renderTarget,!0),e.unBindFramebuffer(b.renderTarget,!0),(_=e._debugPopGroup)===null||_===void 0||_.call(e,1))});var o=new Color4(0,0,0,0),s=new Color4(1,1,1,1);this._shadowMap.onClearObservable.add(function(d){i._filter===a.FILTER_PCF?d.clear(s,!1,!0,!1):i.useExponentialShadowMap||i.useBlurExponentialShadowMap?d.clear(o,!0,!0,!1):d.clear(s,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(function(d){i._storedUniqueId=i._shadowMap.uniqueId,i._mapSize=d.getRenderSize(),i._light._markMeshesAsLightDirty(),i.recreateShadowMap()});for(var c=RenderingManager.MIN_RENDERINGGROUPS;c<RenderingManager.MAX_RENDERINGGROUPS;c++)this._shadowMap.setRenderingAutoClearDepthStencil(c,!1)}},a.prototype._initializeBlurRTTAndPostProcesses=function(){var i=this,e=this._scene.getEngine(),o=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new RenderTargetTexture(this._light.name+"_shadowMap2",o,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=Texture.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=Texture.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new BlurPostProcess(this._light.name+"KernelBlurX",new Vector2(1,0),this.blurKernel,1,null,Texture.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=o,this._kernelBlurXPostprocess.height=o,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(function(s){s.setTexture("textureSampler",i._shadowMap)}),this._kernelBlurYPostprocess=new BlurPostProcess(this._light.name+"KernelBlurY",new Vector2(0,1),this.blurKernel,1,null,Texture.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Texture.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(function(s){s.setFloat2("screenSize",o,o),s.setTexture("textureSampler",i._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},a.prototype._renderForShadowMap=function(i,e,o,s){var c;if(s.length)for(c=0;c<s.length;c++)this._renderSubMeshForShadowMap(s.data[c]);for(c=0;c<i.length;c++)this._renderSubMeshForShadowMap(i.data[c]);for(c=0;c<e.length;c++)this._renderSubMeshForShadowMap(e.data[c]);if(this._transparencyShadow)for(c=0;c<o.length;c++)this._renderSubMeshForShadowMap(o.data[c],!0);else for(c=0;c<o.length;c++)o.data[c].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1},a.prototype._bindCustomEffectForRenderSubMeshForShadowMap=function(i,e,o){e.setMatrix("viewProjection",this.getTransformMatrix())},a.prototype._renderSubMeshForShadowMap=function(i,e){var o,s;e===void 0&&(e=!1);var c=i.getRenderingMesh(),d=i.getEffectiveMesh(),_=this._scene,b=_.getEngine(),k=i.getMaterial();if(d._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!(!k||i.verticesCount===0||i._renderId===_.getRenderId())){var j=d._getWorldMatrixDeterminant()<0,$=(o=c.overrideMaterialSideOrientation)!==null&&o!==void 0?o:k.sideOrientation;(_.useRightHandedSystem&&!j||!_.useRightHandedSystem&&j)&&($=$===0?1:0);var _e=$===0;b.setState(k.backFaceCulling,void 0,void 0,_e,k.cullBackFaces);var et=c._getInstancesRenderList(i._id,!!i.getReplacementMesh());if(!et.mustReturn){var tt=b.getCaps().instancedArrays&&(et.visibleInstances[i._id]!==null&&et.visibleInstances[i._id]!==void 0||c.hasThinInstances);if(!(this.customAllowRendering&&!this.customAllowRendering(i)))if(this.isReady(i,tt,e)){i._renderId=_.getRenderId();var rt=k.shadowDepthWrapper,it=(s=rt==null?void 0:rt.getEffect(i,this,b.currentRenderPassId))!==null&&s!==void 0?s:i._getDrawWrapper(),nt=DrawWrapper.GetEffect(it);if(b.enableEffect(it),tt||c._bind(i,nt,k.fillMode),this.getTransformMatrix(),nt.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===Light.LIGHTTYPEID_DIRECTIONALLIGHT?nt.setVector3("lightDataSM",this._cachedDirection):nt.setVector3("lightDataSM",this._cachedPosition),_.activeCamera&&nt.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(_.activeCamera),this.getLight().getDepthMinZ(_.activeCamera)+this.getLight().getDepthMaxZ(_.activeCamera)),e&&this.enableSoftTransparentShadow&&nt.setFloat("softTransparentShadowSM",d.visibility*k.alpha),rt)i._setMainDrawWrapperOverride(it),rt.standalone?rt.baseMaterial.bindForSubMesh(d.getWorldMatrix(),c,i):k.bindForSubMesh(d.getWorldMatrix(),c,i),i._setMainDrawWrapperOverride(null);else{if(k&&k.needAlphaTesting()){var ot=k.getAlphaTestTexture();ot&&(nt.setTexture("diffuseSampler",ot),nt.setMatrix("diffuseMatrix",ot.getTextureMatrix()||this._defaultTextureMatrix))}if(c.useBones&&c.computeBonesUsingShaders&&c.skeleton){var at=c.skeleton;if(at.isUsingTextureForMatrices){var st=at.getTransformMatrixTexture(c);if(!st)return;nt.setTexture("boneSampler",st),nt.setFloat("boneTextureWidth",4*(at.bones.length+1))}else nt.setMatrices("mBones",at.getTransformMatrices(c))}MaterialHelper.BindMorphTargetParameters(c,nt),c.morphTargetManager&&c.morphTargetManager.isUsingTextureForTargets&&c.morphTargetManager._bind(nt),MaterialHelper.BindClipPlane(nt,_)}!this._useUBO&&!rt&&this._bindCustomEffectForRenderSubMeshForShadowMap(i,nt,d),MaterialHelper.BindSceneUniformBuffer(nt,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();var ut=d.getWorldMatrix();tt&&(d.getMeshUniformBuffer().bindToEffect(nt,"Mesh"),d.transferToEffect(ut)),this.forceBackFacesOnly&&b.setState(!0,0,!1,!0,k.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(c),this.onBeforeShadowMapRenderObservable.notifyObservers(nt),c._processRendering(d,i,nt,k.fillMode,et,tt,function(ft,lt,ht,pt){pt&&d!==pt?(pt.getMeshUniformBuffer().bindToEffect(nt,"Mesh"),pt.transferToEffect(lt)):(d.getMeshUniformBuffer().bindToEffect(nt,"Mesh"),d.transferToEffect(ut))}),this.forceBackFacesOnly&&b.setState(!0,0,!1,!1,k.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(nt),this.onAfterShadowMapRenderMeshObservable.notifyObservers(c)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}},a.prototype._applyFilterValues=function(){!this._shadowMap||(this.filter===a.FILTER_NONE||this.filter===a.FILTER_PCSS?this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE))},a.prototype.forceCompilation=function(i,e){var o=this,s=__assign({useInstances:!1},e),c=this.getShadowMap();if(!c){i&&i(this);return}var d=c.renderList;if(!d){i&&i(this);return}for(var _=new Array,b=0,k=d;b<k.length;b++){var j=k[b];_.push.apply(_,j.subMeshes)}if(_.length===0){i&&i(this);return}var $=0,_e=function(){var et,tt;if(!(!o._scene||!o._scene.getEngine())){for(;o.isReady(_[$],s.useInstances,(tt=(et=_[$].getMaterial())===null||et===void 0?void 0:et.needAlphaBlendingForMesh(_[$].getMesh()))!==null&&tt!==void 0?tt:!1);)if($++,$>=_.length){i&&i(o);return}setTimeout(_e,16)}};_e()},a.prototype.forceCompilationAsync=function(i){var e=this;return new Promise(function(o){e.forceCompilation(function(){o()},i)})},a.prototype._isReadyCustomDefines=function(i,e,o){},a.prototype._prepareShadowDefines=function(i,e,o,s){o.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),o.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),o.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));var c=i.getMesh();return o.push("#define SM_NORMALBIAS "+(this.normalBias&&c.isVerticesDataPresent(VertexBuffer.NormalKind)?"1":"0")),o.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Light.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),o.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),o.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(o,i,e),o},a.prototype.isReady=function(i,e,o){var s=i.getMaterial(),c=s==null?void 0:s.shadowDepthWrapper,d=[];if(this._prepareShadowDefines(i,e,d,o),c){if(!c.isReadyForSubMesh(i,d,this,e,this._scene.getEngine().currentRenderPassId))return!1}else{var _=i._getDrawWrapper(void 0,!0),b=_.effect,k=_.defines,j=[VertexBuffer.PositionKind],$=i.getMesh();if(this.normalBias&&$.isVerticesDataPresent(VertexBuffer.NormalKind)&&(j.push(VertexBuffer.NormalKind),d.push("#define NORMAL"),$.nonUniformScaling&&d.push("#define NONUNIFORMSCALING")),s&&s.needAlphaTesting()){var _e=s.getAlphaTestTexture();if(_e){if(!_e.isReady())return!1;d.push("#define ALPHATEST"),$.isVerticesDataPresent(VertexBuffer.UVKind)&&(j.push(VertexBuffer.UVKind),d.push("#define UV1")),$.isVerticesDataPresent(VertexBuffer.UV2Kind)&&_e.coordinatesIndex===1&&(j.push(VertexBuffer.UV2Kind),d.push("#define UV2"))}}var et=new EffectFallbacks;if($.useBones&&$.computeBonesUsingShaders&&$.skeleton){j.push(VertexBuffer.MatricesIndicesKind),j.push(VertexBuffer.MatricesWeightsKind),$.numBoneInfluencers>4&&(j.push(VertexBuffer.MatricesIndicesExtraKind),j.push(VertexBuffer.MatricesWeightsExtraKind));var tt=$.skeleton;d.push("#define NUM_BONE_INFLUENCERS "+$.numBoneInfluencers),$.numBoneInfluencers>0&&et.addCPUSkinningFallback(0,$),tt.isUsingTextureForMatrices?d.push("#define BONETEXTURE"):d.push("#define BonesPerMesh "+(tt.bones.length+1))}else d.push("#define NUM_BONE_INFLUENCERS 0");var rt=$.morphTargetManager,it=0;rt&&rt.numInfluencers>0&&(d.push("#define MORPHTARGETS"),it=rt.numInfluencers,d.push("#define NUM_MORPH_INFLUENCERS "+it),rt.isUsingTextureForTargets&&d.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(j,$,it));var nt=this._scene;if(nt.clipPlane&&d.push("#define CLIPPLANE"),nt.clipPlane2&&d.push("#define CLIPPLANE2"),nt.clipPlane3&&d.push("#define CLIPPLANE3"),nt.clipPlane4&&d.push("#define CLIPPLANE4"),nt.clipPlane5&&d.push("#define CLIPPLANE5"),nt.clipPlane6&&d.push("#define CLIPPLANE6"),e&&(d.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(j),i.getRenderingMesh().hasThinInstances&&d.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(var ot=0,at=this.customShaderOptions.defines;ot<at.length;ot++){var st=at[ot];d.indexOf(st)===-1&&d.push(st)}var ut=d.join(`
  1454. `);if(k!==ut){k=ut;var ft="shadowMap",lt=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],ht=["diffuseSampler","boneSampler","morphTargets"],pt=["Scene","Mesh"];if(this.customShaderOptions){if(ft=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(var mt=0,dt=this.customShaderOptions.attributes;mt<dt.length;mt++){var gt=dt[mt];j.indexOf(gt)===-1&&j.push(gt)}if(this.customShaderOptions.uniforms)for(var _t=0,yt=this.customShaderOptions.uniforms;_t<yt.length;_t++){var Tt=yt[_t];lt.indexOf(Tt)===-1&&lt.push(Tt)}if(this.customShaderOptions.samplers)for(var St=0,At=this.customShaderOptions.samplers;St<At.length;St++){var vt=At[St];ht.indexOf(vt)===-1&&ht.push(vt)}}var Et=this._scene.getEngine();b=Et.createEffect(ft,{attributes:j,uniformsNames:lt,uniformBuffersNames:pt,samplers:ht,defines:ut,fallbacks:et,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:it}},Et),_.setEffect(b,k)}if(!b.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())},a.prototype.prepareDefines=function(i,e){var o=this._scene,s=this._light;!o.shadowsEnabled||!s.shadowEnabled||(i["SHADOW"+e]=!0,this.useContactHardeningShadow?(i["SHADOWPCSS"+e]=!0,this._filteringQuality===a.QUALITY_LOW?i["SHADOWLOWQUALITY"+e]=!0:this._filteringQuality===a.QUALITY_MEDIUM&&(i["SHADOWMEDIUMQUALITY"+e]=!0)):this.usePercentageCloserFiltering?(i["SHADOWPCF"+e]=!0,this._filteringQuality===a.QUALITY_LOW?i["SHADOWLOWQUALITY"+e]=!0:this._filteringQuality===a.QUALITY_MEDIUM&&(i["SHADOWMEDIUMQUALITY"+e]=!0)):this.usePoissonSampling?i["SHADOWPOISSON"+e]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?i["SHADOWESM"+e]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(i["SHADOWCLOSEESM"+e]=!0),s.needCube()&&(i["SHADOWCUBE"+e]=!0))},a.prototype.bindShadowLight=function(i,e){var o=this._light,s=this._scene;if(!(!s.shadowsEnabled||!o.shadowEnabled)){var c=s.activeCamera;if(!!c){var d=this.getShadowMap();!d||(o.needCube()||e.setMatrix("lightMatrix"+i,this.getTransformMatrix()),this._filter===a.FILTER_PCF?(e.setDepthStencilTexture("shadowSampler"+i,this.getShadowMapForRendering()),o._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),d.getSize().width,1/d.getSize().width,this.frustumEdgeFalloff,i)):this._filter===a.FILTER_PCSS?(e.setDepthStencilTexture("shadowSampler"+i,this.getShadowMapForRendering()),e.setTexture("depthSampler"+i,this.getShadowMapForRendering()),o._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/d.getSize().width,this._contactHardeningLightSizeUVRatio*d.getSize().width,this.frustumEdgeFalloff,i)):(e.setTexture("shadowSampler"+i,this.getShadowMapForRendering()),o._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/d.getSize().width,this.depthScale,this.frustumEdgeFalloff,i)),o._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(c),this.getLight().getDepthMinZ(c)+this.getLight().getDepthMaxZ(c),i))}}},a.prototype.getTransformMatrix=function(){var i=this._scene;if(this._currentRenderId===i.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=i.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var e=this._light.position;if(this._light.computeTransformedInformation()&&(e=this._light.transformedPosition),Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(Vector3.Dot(this._lightDirection,Vector3.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!e.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(e),this._cachedDirection.copyFrom(this._lightDirection),Matrix.LookAtLHToRef(e,e.add(this._lightDirection),Vector3.Up(),this._viewMatrix);var o=this.getShadowMap();if(o){var s=o.renderList;s&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,s)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix},a.prototype.recreateShadowMap=function(){var i=this._shadowMap;if(!!i){var e=i.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this.filter,this._applyFilterValues(),e){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(var o=0,s=e;o<s.length;o++){var c=s[o];this._shadowMap.renderList.push(c)}}else this._shadowMap.renderList=null}},a.prototype._disposeBlurPostProcesses=function(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]},a.prototype._disposeRTTandPostProcesses=function(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()},a.prototype._disposeSceneUBOs=function(){if(this._sceneUBOs){for(var i=0,e=this._sceneUBOs;i<e.length;i++){var o=e[i];o.dispose()}this._sceneUBOs=[]}},a.prototype.dispose=function(){this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light&&(this._light._shadowGenerator=null,this._light._markMeshesAsLightDirty()),this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()},a.prototype.serialize=function(){var i={},e=this.getShadowMap();if(!e)return i;if(i.className=this.getClassName(),i.lightId=this._light.id,i.id=this.id,i.mapSize=e.getRenderSize(),i.forceBackFacesOnly=this.forceBackFacesOnly,i.darkness=this.getDarkness(),i.transparencyShadow=this._transparencyShadow,i.frustumEdgeFalloff=this.frustumEdgeFalloff,i.bias=this.bias,i.normalBias=this.normalBias,i.usePercentageCloserFiltering=this.usePercentageCloserFiltering,i.useContactHardeningShadow=this.useContactHardeningShadow,i.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,i.filteringQuality=this.filteringQuality,i.useExponentialShadowMap=this.useExponentialShadowMap,i.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,i.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,i.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,i.usePoissonSampling=this.usePoissonSampling,i.depthScale=this.depthScale,i.blurBoxOffset=this.blurBoxOffset,i.blurKernel=this.blurKernel,i.blurScale=this.blurScale,i.useKernelBlur=this.useKernelBlur,i.renderList=[],e.renderList)for(var o=0;o<e.renderList.length;o++){var s=e.renderList[o];i.renderList.push(s.id)}return i},a.Parse=function(i,e,o){for(var s=e.getLightById(i.lightId),c=o?o(i.mapSize,s):new a(i.mapSize,s),d=c.getShadowMap(),_=0;_<i.renderList.length;_++){var b=e.getMeshesById(i.renderList[_]);b.forEach(function(k){!d||(d.renderList||(d.renderList=[]),d.renderList.push(k))})}return i.id!==void 0&&(c.id=i.id),c.forceBackFacesOnly=!!i.forceBackFacesOnly,i.darkness!==void 0&&c.setDarkness(i.darkness),i.transparencyShadow&&c.setTransparencyShadow(!0),i.frustumEdgeFalloff!==void 0&&(c.frustumEdgeFalloff=i.frustumEdgeFalloff),i.bias!==void 0&&(c.bias=i.bias),i.normalBias!==void 0&&(c.normalBias=i.normalBias),i.usePercentageCloserFiltering?c.usePercentageCloserFiltering=!0:i.useContactHardeningShadow?c.useContactHardeningShadow=!0:i.usePoissonSampling?c.usePoissonSampling=!0:i.useExponentialShadowMap?c.useExponentialShadowMap=!0:i.useBlurExponentialShadowMap?c.useBlurExponentialShadowMap=!0:i.useCloseExponentialShadowMap?c.useCloseExponentialShadowMap=!0:i.useBlurCloseExponentialShadowMap?c.useBlurCloseExponentialShadowMap=!0:i.useVarianceShadowMap?c.useExponentialShadowMap=!0:i.useBlurVarianceShadowMap&&(c.useBlurExponentialShadowMap=!0),i.contactHardeningLightSizeUVRatio!==void 0&&(c.contactHardeningLightSizeUVRatio=i.contactHardeningLightSizeUVRatio),i.filteringQuality!==void 0&&(c.filteringQuality=i.filteringQuality),i.depthScale&&(c.depthScale=i.depthScale),i.blurScale&&(c.blurScale=i.blurScale),i.blurBoxOffset&&(c.blurBoxOffset=i.blurBoxOffset),i.useKernelBlur&&(c.useKernelBlur=i.useKernelBlur),i.blurKernel&&(c.blurKernel=i.blurKernel),c},a.CLASSNAME="ShadowGenerator",a.FILTER_NONE=0,a.FILTER_EXPONENTIALSHADOWMAP=1,a.FILTER_POISSONSAMPLING=2,a.FILTER_BLUREXPONENTIALSHADOWMAP=3,a.FILTER_CLOSEEXPONENTIALSHADOWMAP=4,a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5,a.FILTER_PCF=6,a.FILTER_PCSS=7,a.QUALITY_HIGH=0,a.QUALITY_MEDIUM=1,a.QUALITY_LOW=2,a._SceneComponentInitialization=function(i){throw _WarnImport("ShadowGeneratorSceneComponent")},a}(),PushMaterial=function(a){__extends(i,a);function i(e,o,s){s===void 0&&(s=!0);var c=a.call(this,e,o)||this;return c._normalMatrix=new Matrix,c._storeEffectOnSubMeshes=s,c}return i.prototype.getEffect=function(){return this._storeEffectOnSubMeshes?this._activeEffect:a.prototype.getEffect.call(this)},i.prototype.isReady=function(e,o){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],o):!1},i.prototype._isReadyForSubMesh=function(e){var o=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&o&&o._renderId===this.getScene().getRenderId())},i.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},i.prototype.bindOnlyNormalMatrix=function(e){this._activeEffect.setMatrix("normalMatrix",e)},i.prototype.bind=function(e,o){!o||this.bindForSubMesh(e,o,o.subMeshes[0])},i.prototype._afterBind=function(e,o){o===void 0&&(o=null),a.prototype._afterBind.call(this,e,o),this.getScene()._cachedEffect=o},i.prototype._mustRebind=function(e,o,s){return s===void 0&&(s=1),e.isCachedMaterialInvalid(this,o,s)},i}(Material),onCreatedEffectParameters$3={effect:null,subMesh:null},ShaderMaterial=function(a){__extends(i,a);function i(e,o,s,c,d){c===void 0&&(c={}),d===void 0&&(d=!0);var _=a.call(this,e,o,d)||this;return _._textures={},_._textureArrays={},_._externalTextures={},_._floats={},_._ints={},_._floatsArrays={},_._colors3={},_._colors3Arrays={},_._colors4={},_._colors4Arrays={},_._vectors2={},_._vectors3={},_._vectors4={},_._matrices={},_._matrixArrays={},_._matrices3x3={},_._matrices2x2={},_._vectors2Arrays={},_._vectors3Arrays={},_._vectors4Arrays={},_._uniformBuffers={},_._textureSamplers={},_._storageBuffers={},_._cachedWorldViewMatrix=new Matrix,_._cachedWorldViewProjectionMatrix=new Matrix,_._multiview=!1,_._shaderPath=s,_._options=__assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},c),_}return Object.defineProperty(i.prototype,"shaderPath",{get:function(){return this._shaderPath},set:function(e){this._shaderPath=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"ShaderMaterial"},i.prototype.needAlphaBlending=function(){return this.alpha<1||this._options.needAlphaBlending},i.prototype.needAlphaTesting=function(){return this._options.needAlphaTesting},i.prototype._checkUniform=function(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)},i.prototype.setTexture=function(e,o){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=o,this},i.prototype.setTextureArray=function(e,o){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=o,this},i.prototype.setExternalTexture=function(e,o){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=o,this},i.prototype.setFloat=function(e,o){return this._checkUniform(e),this._floats[e]=o,this},i.prototype.setInt=function(e,o){return this._checkUniform(e),this._ints[e]=o,this},i.prototype.setFloats=function(e,o){return this._checkUniform(e),this._floatsArrays[e]=o,this},i.prototype.setColor3=function(e,o){return this._checkUniform(e),this._colors3[e]=o,this},i.prototype.setColor3Array=function(e,o){return this._checkUniform(e),this._colors3Arrays[e]=o.reduce(function(s,c){return c.toArray(s,s.length),s},[]),this},i.prototype.setColor4=function(e,o){return this._checkUniform(e),this._colors4[e]=o,this},i.prototype.setColor4Array=function(e,o){return this._checkUniform(e),this._colors4Arrays[e]=o.reduce(function(s,c){return c.toArray(s,s.length),s},[]),this},i.prototype.setVector2=function(e,o){return this._checkUniform(e),this._vectors2[e]=o,this},i.prototype.setVector3=function(e,o){return this._checkUniform(e),this._vectors3[e]=o,this},i.prototype.setVector4=function(e,o){return this._checkUniform(e),this._vectors4[e]=o,this},i.prototype.setMatrix=function(e,o){return this._checkUniform(e),this._matrices[e]=o,this},i.prototype.setMatrices=function(e,o){this._checkUniform(e);for(var s=new Float32Array(o.length*16),c=0;c<o.length;c++){var d=o[c];d.copyToArray(s,c*16)}return this._matrixArrays[e]=s,this},i.prototype.setMatrix3x3=function(e,o){return this._checkUniform(e),this._matrices3x3[e]=o,this},i.prototype.setMatrix2x2=function(e,o){return this._checkUniform(e),this._matrices2x2[e]=o,this},i.prototype.setArray2=function(e,o){return this._checkUniform(e),this._vectors2Arrays[e]=o,this},i.prototype.setArray3=function(e,o){return this._checkUniform(e),this._vectors3Arrays[e]=o,this},i.prototype.setArray4=function(e,o){return this._checkUniform(e),this._vectors4Arrays[e]=o,this},i.prototype.setUniformBuffer=function(e,o){return this._options.uniformBuffers.indexOf(e)===-1&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=o,this},i.prototype.setTextureSampler=function(e,o){return this._options.samplerObjects.indexOf(e)===-1&&this._options.samplerObjects.push(e),this._textureSamplers[e]=o,this},i.prototype.setStorageBuffer=function(e,o){return this._options.storageBuffers.indexOf(e)===-1&&this._options.storageBuffers.push(e),this._storageBuffers[e]=o,this},i.prototype.isReadyForSubMesh=function(e,o,s){return this.isReady(e,s,o)},i.prototype.isReady=function(e,o,s){var c,d,_,b,k=s&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(k){if(s.effect&&s.effect._wasPreviouslyReady)return!0}else{var j=this._drawWrapper.effect;if(j&&j._wasPreviouslyReady&&this._effectUsesInstances===o)return!0}var $=this.getScene(),_e=$.getEngine(),et=[],tt=[],rt=new EffectFallbacks,it=this._shaderPath,nt=this._options.uniforms,ot=this._options.uniformBuffers,at=this._options.samplers;_e.getCaps().multiview&&$.activeCamera&&$.activeCamera.outputRenderTarget&&$.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,et.push("#define MULTIVIEW"),this._options.uniforms.indexOf("viewProjection")!==-1&&this._options.uniforms.indexOf("viewProjectionR")===-1&&this._options.uniforms.push("viewProjectionR"));for(var st=0;st<this._options.defines.length;st++){var ut=this._options.defines[st].indexOf("#define")===0?this._options.defines[st]:"#define "+this._options.defines[st];et.push(ut)}for(var st=0;st<this._options.attributes.length;st++)tt.push(this._options.attributes[st]);if(e&&e.isVerticesDataPresent(VertexBuffer.ColorKind)&&(tt.push(VertexBuffer.ColorKind),et.push("#define VERTEXCOLOR")),o&&(et.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(tt),e!=null&&e.hasThinInstances&&et.push("#define THIN_INSTANCES")),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){tt.push(VertexBuffer.MatricesIndicesKind),tt.push(VertexBuffer.MatricesWeightsKind),e.numBoneInfluencers>4&&(tt.push(VertexBuffer.MatricesIndicesExtraKind),tt.push(VertexBuffer.MatricesWeightsExtraKind));var ft=e.skeleton;et.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),rt.addCPUSkinningFallback(0,e),ft.isUsingTextureForMatrices?(et.push("#define BONETEXTURE"),this._options.uniforms.indexOf("boneTextureWidth")===-1&&this._options.uniforms.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(et.push("#define BonesPerMesh "+(ft.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else et.push("#define NUM_BONE_INFLUENCERS 0");var lt=0,ht=e?e.morphTargetManager:null;if(ht){var pt=ht.supportsUVs&&et.indexOf("#define UV1")!==-1,mt=ht.supportsTangents&&et.indexOf("#define TANGENT")!==-1,dt=ht.supportsNormals&&et.indexOf("#define NORMAL")!==-1;lt=ht.numInfluencers,pt&&et.push("#define MORPHTARGETS_UV"),mt&&et.push("#define MORPHTARGETS_TANGENT"),dt&&et.push("#define MORPHTARGETS_NORMAL"),lt>0&&et.push("#define MORPHTARGETS"),ht.isUsingTextureForTargets&&(et.push("#define MORPHTARGETS_TEXTURE"),this._options.uniforms.indexOf("morphTargetTextureIndices")===-1&&this._options.uniforms.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),et.push("#define NUM_MORPH_INFLUENCERS "+lt);for(var st=0;st<lt;st++)tt.push(VertexBuffer.PositionKind+st),dt&&tt.push(VertexBuffer.NormalKind+st),mt&&tt.push(VertexBuffer.TangentKind+st),pt&&tt.push(VertexBuffer.UVKind+"_"+st);lt>0&&(nt=nt.slice(),nt.push("morphTargetInfluences"),nt.push("morphTargetTextureInfo"),nt.push("morphTargetTextureIndices"))}else et.push("#define NUM_MORPH_INFLUENCERS 0");if(e){var gt=e.bakedVertexAnimationManager;gt&&gt.isEnabled&&(et.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),this._options.uniforms.indexOf("bakedVertexAnimationSettings")===-1&&this._options.uniforms.push("bakedVertexAnimationSettings"),this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),this._options.uniforms.indexOf("bakedVertexAnimationTime")===-1&&this._options.uniforms.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),MaterialHelper.PrepareAttributesForBakedVertexAnimation(tt,e,et)}for(var _t in this._textures)if(!this._textures[_t].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&et.push("#define ALPHATEST"),(this._options.useClipPlane===null&&!!$.clipPlane||this._options.useClipPlane)&&(et.push("#define CLIPPLANE"),nt.indexOf("vClipPlane")===-1&&nt.push("vClipPlane")),(this._options.useClipPlane===null&&!!$.clipPlane2||this._options.useClipPlane)&&(et.push("#define CLIPPLANE2"),nt.indexOf("vClipPlane2")===-1&&nt.push("vClipPlane2")),(this._options.useClipPlane===null&&!!$.clipPlane3||this._options.useClipPlane)&&(et.push("#define CLIPPLANE3"),nt.indexOf("vClipPlane3")===-1&&nt.push("vClipPlane3")),(this._options.useClipPlane===null&&!!$.clipPlane4||this._options.useClipPlane)&&(et.push("#define CLIPPLANE4"),nt.indexOf("vClipPlane4")===-1&&nt.push("vClipPlane4")),(this._options.useClipPlane===null&&!!$.clipPlane5||this._options.useClipPlane)&&(et.push("#define CLIPPLANE5"),nt.indexOf("vClipPlane5")===-1&&nt.push("vClipPlane5")),(this._options.useClipPlane===null&&!!$.clipPlane6||this._options.useClipPlane)&&(et.push("#define CLIPPLANE6"),nt.indexOf("vClipPlane6")===-1&&nt.push("vClipPlane6")),this.customShaderNameResolve&&(nt=nt.slice(),ot=ot.slice(),at=at.slice(),it=this.customShaderNameResolve(it,nt,ot,at,et,tt));var yt=k?s._getDrawWrapper():this._drawWrapper,Tt=(c=yt==null?void 0:yt.effect)!==null&&c!==void 0?c:null,St=(d=yt==null?void 0:yt.defines)!==null&&d!==void 0?d:null,At=et.join(`
  1455. `),vt=Tt;return St!==At&&(vt=_e.createEffect(it,{attributes:tt,uniformsNames:nt,uniformBuffersNames:ot,samplers:at,defines:At,fallbacks:rt,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:lt},shaderLanguage:this._options.shaderLanguage},_e),k?s.setEffect(vt,At,this._materialContext):yt&&yt.setEffect(vt,At),this._onEffectCreatedObservable&&(onCreatedEffectParameters$3.effect=vt,onCreatedEffectParameters$3.subMesh=(_=s!=null?s:e==null?void 0:e.subMeshes[0])!==null&&_!==void 0?_:null,this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$3))),this._effectUsesInstances=!!o,!((b=!(vt!=null&&vt.isReady()))!==null&&b!==void 0)||b?!1:(Tt!==vt&&$.resetCachedMaterial(),vt._wasPreviouslyReady=!0,!0)},i.prototype.bindOnlyWorldMatrix=function(e,o){var s=this.getScene(),c=o!=null?o:this.getEffect();!c||(this._options.uniforms.indexOf("world")!==-1&&c.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(s.getViewMatrix(),this._cachedWorldViewMatrix),c.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(s.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),c.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))},i.prototype.bindForSubMesh=function(e,o,s){var c;this.bind(e,o,(c=s._drawWrapperOverride)===null||c===void 0?void 0:c.effect,s)},i.prototype.bind=function(e,o,s,c){var d,_=c&&this._storeEffectOnSubMeshes,b=s!=null?s:_?c.effect:this.getEffect();if(!!b){this._activeEffect=b,this.bindOnlyWorldMatrix(e,s);var k=this._options.uniformBuffers,j=!1;if(b&&k&&k.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(var $=0;$<k.length;++$){var _e=k[$];switch(_e){case"Mesh":o&&(o.getMeshUniformBuffer().bindToEffect(b,"Mesh"),o.transferToEffect(e));break;case"Scene":MaterialHelper.BindSceneUniformBuffer(b,this.getScene().getSceneUniformBuffer()),this.getScene().finalizeSceneUbo(),j=!0;break}}var et=o&&_?this._mustRebind(this.getScene(),b,o.visibility):this.getScene().getCachedMaterial()!==this;if(b&&et){!j&&this._options.uniforms.indexOf("view")!==-1&&b.setMatrix("view",this.getScene().getViewMatrix()),!j&&this._options.uniforms.indexOf("projection")!==-1&&b.setMatrix("projection",this.getScene().getProjectionMatrix()),!j&&this._options.uniforms.indexOf("viewProjection")!==-1&&(b.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&b.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&this._options.uniforms.indexOf("cameraPosition")!==-1&&b.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),MaterialHelper.BindBonesParameters(o,b),MaterialHelper.BindClipPlane(b,this.getScene());var tt;for(tt in this._textures)b.setTexture(tt,this._textures[tt]);for(tt in this._textureArrays)b.setTextureArray(tt,this._textureArrays[tt]);for(tt in this._externalTextures)b.setExternalTexture(tt,this._externalTextures[tt]);for(tt in this._ints)b.setInt(tt,this._ints[tt]);for(tt in this._floats)b.setFloat(tt,this._floats[tt]);for(tt in this._floatsArrays)b.setArray(tt,this._floatsArrays[tt]);for(tt in this._colors3)b.setColor3(tt,this._colors3[tt]);for(tt in this._colors3Arrays)b.setArray3(tt,this._colors3Arrays[tt]);for(tt in this._colors4){var rt=this._colors4[tt];b.setFloat4(tt,rt.r,rt.g,rt.b,rt.a)}for(tt in this._colors4Arrays)b.setArray4(tt,this._colors4Arrays[tt]);for(tt in this._vectors2)b.setVector2(tt,this._vectors2[tt]);for(tt in this._vectors3)b.setVector3(tt,this._vectors3[tt]);for(tt in this._vectors4)b.setVector4(tt,this._vectors4[tt]);for(tt in this._matrices)b.setMatrix(tt,this._matrices[tt]);for(tt in this._matrixArrays)b.setMatrices(tt,this._matrixArrays[tt]);for(tt in this._matrices3x3)b.setMatrix3x3(tt,this._matrices3x3[tt]);for(tt in this._matrices2x2)b.setMatrix2x2(tt,this._matrices2x2[tt]);for(tt in this._vectors2Arrays)b.setArray2(tt,this._vectors2Arrays[tt]);for(tt in this._vectors3Arrays)b.setArray3(tt,this._vectors3Arrays[tt]);for(tt in this._vectors4Arrays)b.setArray4(tt,this._vectors4Arrays[tt]);for(tt in this._uniformBuffers){var it=this._uniformBuffers[tt].getBuffer();it&&b.bindUniformBuffer(it,tt)}for(tt in this._textureSamplers)b.setTextureSampler(tt,this._textureSamplers[tt]);for(tt in this._storageBuffers)b.setStorageBuffer(tt,this._storageBuffers[tt])}if(b&&o&&(et||!this.isFrozen)){var nt=o.morphTargetManager;nt&&nt.numInfluencers>0&&MaterialHelper.BindMorphTargetParameters(o,b);var ot=o.bakedVertexAnimationManager;ot&&ot.isEnabled&&((d=o.bakedVertexAnimationManager)===null||d===void 0||d.bind(b,this._effectUsesInstances))}this._afterBind(o,b)}},i.prototype.getActiveTextures=function(){var e=a.prototype.getActiveTextures.call(this);for(var o in this._textures)e.push(this._textures[o]);for(var o in this._textureArrays)for(var s=this._textureArrays[o],c=0;c<s.length;c++)e.push(s[c]);return e},i.prototype.hasTexture=function(e){if(a.prototype.hasTexture.call(this,e))return!0;for(var o in this._textures)if(this._textures[o]===e)return!0;for(var o in this._textureArrays)for(var s=this._textureArrays[o],c=0;c<s.length;c++)if(s[c]===e)return!0;return!1},i.prototype.clone=function(e){var o=this,s=SerializationHelper.Clone(function(){return new i(e,o.getScene(),o._shaderPath,o._options,o._storeEffectOnSubMeshes)},this);s.name=e,s.id=e,typeof s._shaderPath=="object"&&(s._shaderPath=__assign({},s._shaderPath)),this._options=__assign({},this._options),Object.keys(this._options).forEach(function(d){var _=o._options[d];Array.isArray(_)&&(o._options[d]=_.slice(0))}),this.stencil.copyTo(s.stencil);for(var c in this._textures)s.setTexture(c,this._textures[c]);for(var c in this._textureArrays)s.setTextureArray(c,this._textureArrays[c]);for(var c in this._externalTextures)s.setExternalTexture(c,this._externalTextures[c]);for(var c in this._ints)s.setInt(c,this._ints[c]);for(var c in this._floats)s.setFloat(c,this._floats[c]);for(var c in this._floatsArrays)s.setFloats(c,this._floatsArrays[c]);for(var c in this._colors3)s.setColor3(c,this._colors3[c]);for(var c in this._colors3Arrays)s._colors3Arrays[c]=this._colors3Arrays[c];for(var c in this._colors4)s.setColor4(c,this._colors4[c]);for(var c in this._colors4Arrays)s._colors4Arrays[c]=this._colors4Arrays[c];for(var c in this._vectors2)s.setVector2(c,this._vectors2[c]);for(var c in this._vectors3)s.setVector3(c,this._vectors3[c]);for(var c in this._vectors4)s.setVector4(c,this._vectors4[c]);for(var c in this._matrices)s.setMatrix(c,this._matrices[c]);for(var c in this._matrixArrays)s._matrixArrays[c]=this._matrixArrays[c].slice();for(var c in this._matrices3x3)s.setMatrix3x3(c,this._matrices3x3[c]);for(var c in this._matrices2x2)s.setMatrix2x2(c,this._matrices2x2[c]);for(var c in this._vectors2Arrays)s.setArray2(c,this._vectors2Arrays[c]);for(var c in this._vectors3Arrays)s.setArray3(c,this._vectors3Arrays[c]);for(var c in this._vectors4Arrays)s.setArray4(c,this._vectors4Arrays[c]);for(var c in this._uniformBuffers)s.setUniformBuffer(c,this._uniformBuffers[c]);for(var c in this._textureSamplers)s.setTextureSampler(c,this._textureSamplers[c]);for(var c in this._storageBuffers)s.setStorageBuffer(c,this._storageBuffers[c]);return s},i.prototype.dispose=function(e,o,s){if(o){var c;for(c in this._textures)this._textures[c].dispose();for(c in this._textureArrays)for(var d=this._textureArrays[c],_=0;_<d.length;_++)d[_].dispose()}this._textures={},a.prototype.dispose.call(this,e,o,s)},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);e.customType="BABYLON.ShaderMaterial",e.options=this._options,e.shaderPath=this._shaderPath,e.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes;var o;e.stencil=this.stencil.serialize(),e.textures={};for(o in this._textures)e.textures[o]=this._textures[o].serialize();e.textureArrays={};for(o in this._textureArrays){e.textureArrays[o]=[];for(var s=this._textureArrays[o],c=0;c<s.length;c++)e.textureArrays[o].push(s[c].serialize())}e.ints={};for(o in this._ints)e.ints[o]=this._ints[o];e.floats={};for(o in this._floats)e.floats[o]=this._floats[o];e.FloatArrays={};for(o in this._floatsArrays)e.FloatArrays[o]=this._floatsArrays[o];e.colors3={};for(o in this._colors3)e.colors3[o]=this._colors3[o].asArray();e.colors3Arrays={};for(o in this._colors3Arrays)e.colors3Arrays[o]=this._colors3Arrays[o];e.colors4={};for(o in this._colors4)e.colors4[o]=this._colors4[o].asArray();e.colors4Arrays={};for(o in this._colors4Arrays)e.colors4Arrays[o]=this._colors4Arrays[o];e.vectors2={};for(o in this._vectors2)e.vectors2[o]=this._vectors2[o].asArray();e.vectors3={};for(o in this._vectors3)e.vectors3[o]=this._vectors3[o].asArray();e.vectors4={};for(o in this._vectors4)e.vectors4[o]=this._vectors4[o].asArray();e.matrices={};for(o in this._matrices)e.matrices[o]=this._matrices[o].asArray();e.matrixArray={};for(o in this._matrixArrays)e.matrixArray[o]=this._matrixArrays[o];e.matrices3x3={};for(o in this._matrices3x3)e.matrices3x3[o]=this._matrices3x3[o];e.matrices2x2={};for(o in this._matrices2x2)e.matrices2x2[o]=this._matrices2x2[o];e.vectors2Arrays={};for(o in this._vectors2Arrays)e.vectors2Arrays[o]=this._vectors2Arrays[o];e.vectors3Arrays={};for(o in this._vectors3Arrays)e.vectors3Arrays[o]=this._vectors3Arrays[o];e.vectors4Arrays={};for(o in this._vectors4Arrays)e.vectors4Arrays[o]=this._vectors4Arrays[o];return e},i.Parse=function(e,o,s){var c=SerializationHelper.Parse(function(){return new i(e.name,o,e.shaderPath,e.options,e.storeEffectOnSubMeshes)},e,o,s),d;e.stencil&&c.stencil.parse(e.stencil,o,s);for(d in e.textures)c.setTexture(d,Texture.Parse(e.textures[d],o,s));for(d in e.textureArrays){for(var _=e.textureArrays[d],b=new Array,k=0;k<_.length;k++)b.push(Texture.Parse(_[k],o,s));c.setTextureArray(d,b)}for(d in e.ints)c.setInt(d,e.ints[d]);for(d in e.floats)c.setFloat(d,e.floats[d]);for(d in e.floatsArrays)c.setFloats(d,e.floatsArrays[d]);for(d in e.colors3)c.setColor3(d,Color3.FromArray(e.colors3[d]));for(d in e.colors3Arrays){var j=e.colors3Arrays[d].reduce(function($,_e,et){return et%3===0?$.push([_e]):$[$.length-1].push(_e),$},[]).map(function($){return Color3.FromArray($)});c.setColor3Array(d,j)}for(d in e.colors4)c.setColor4(d,Color4.FromArray(e.colors4[d]));for(d in e.colors4Arrays){var j=e.colors4Arrays[d].reduce(function(_e,et,tt){return tt%4===0?_e.push([et]):_e[_e.length-1].push(et),_e},[]).map(function(_e){return Color4.FromArray(_e)});c.setColor4Array(d,j)}for(d in e.vectors2)c.setVector2(d,Vector2.FromArray(e.vectors2[d]));for(d in e.vectors3)c.setVector3(d,Vector3.FromArray(e.vectors3[d]));for(d in e.vectors4)c.setVector4(d,Vector4.FromArray(e.vectors4[d]));for(d in e.matrices)c.setMatrix(d,Matrix.FromArray(e.matrices[d]));for(d in e.matrixArray)c._matrixArrays[d]=new Float32Array(e.matrixArray[d]);for(d in e.matrices3x3)c.setMatrix3x3(d,e.matrices3x3[d]);for(d in e.matrices2x2)c.setMatrix2x2(d,e.matrices2x2[d]);for(d in e.vectors2Arrays)c.setArray2(d,e.vectors2Arrays[d]);for(d in e.vectors3Arrays)c.setArray3(d,e.vectors3Arrays[d]);for(d in e.vectors4Arrays)c.setArray4(d,e.vectors4Arrays[d]);return c},i.ParseFromFileAsync=function(e,o,s,c){var d=this;return c===void 0&&(c=""),new Promise(function(_,b){var k=new WebRequest;k.addEventListener("readystatechange",function(){if(k.readyState==4)if(k.status==200){var j=JSON.parse(k.responseText),$=d.Parse(j,s||Engine.LastCreatedScene,c);e&&($.name=e),_($)}else b("Unable to load the ShaderMaterial")}),k.open("GET",o),k.send()})},i.CreateFromSnippetAsync=function(e,o,s){var c=this;return s===void 0&&(s=""),new Promise(function(d,_){var b=new WebRequest;b.addEventListener("readystatechange",function(){if(b.readyState==4)if(b.status==200){var k=JSON.parse(JSON.parse(b.responseText).jsonPayload),j=JSON.parse(k.shaderMaterial),$=c.Parse(j,o||Engine.LastCreatedScene,s);$.snippetId=e,d($)}else _("Unable to load the snippet "+e)}),b.open("GET",c.SnippetUrl+"/"+e.replace(/#/g,"/")),b.send()})},i.SnippetUrl="https://snippet.babylonjs.com",i}(PushMaterial);RegisterClass("BABYLON.ShaderMaterial",ShaderMaterial);var PrePassConfiguration=function(){function a(){this.previousWorldMatrices={},this.previousBones={}}return a.AddUniforms=function(i){i.push("previousWorld","previousViewProjection","mPreviousBones")},a.AddSamplers=function(i){},a.prototype.bindForSubMesh=function(i,e,o,s,c){if(e.prePassRenderer&&e.prePassRenderer.enabled&&e.prePassRenderer.currentRTisSceneRT&&e.prePassRenderer.getIndex(2)!==-1){this.previousWorldMatrices[o.uniqueId]||(this.previousWorldMatrices[o.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=e.getTransformMatrix().clone(),this.currentViewProjection=e.getTransformMatrix().clone());var d=e.getEngine();this.currentViewProjection.updateFlag!==e.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=d.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(e.getTransformMatrix())):this._lastUpdateFrameId!==d.frameId&&(this._lastUpdateFrameId=d.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),i.setMatrix("previousWorld",this.previousWorldMatrices[o.uniqueId]),i.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[o.uniqueId]=s.clone()}},a}(),MaterialFlags=function(){function a(){}return Object.defineProperty(a,"DiffuseTextureEnabled",{get:function(){return this._DiffuseTextureEnabled},set:function(i){this._DiffuseTextureEnabled!==i&&(this._DiffuseTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"DetailTextureEnabled",{get:function(){return this._DetailTextureEnabled},set:function(i){this._DetailTextureEnabled!==i&&(this._DetailTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"AmbientTextureEnabled",{get:function(){return this._AmbientTextureEnabled},set:function(i){this._AmbientTextureEnabled!==i&&(this._AmbientTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"OpacityTextureEnabled",{get:function(){return this._OpacityTextureEnabled},set:function(i){this._OpacityTextureEnabled!==i&&(this._OpacityTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ReflectionTextureEnabled",{get:function(){return this._ReflectionTextureEnabled},set:function(i){this._ReflectionTextureEnabled!==i&&(this._ReflectionTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"EmissiveTextureEnabled",{get:function(){return this._EmissiveTextureEnabled},set:function(i){this._EmissiveTextureEnabled!==i&&(this._EmissiveTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"SpecularTextureEnabled",{get:function(){return this._SpecularTextureEnabled},set:function(i){this._SpecularTextureEnabled!==i&&(this._SpecularTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"BumpTextureEnabled",{get:function(){return this._BumpTextureEnabled},set:function(i){this._BumpTextureEnabled!==i&&(this._BumpTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"LightmapTextureEnabled",{get:function(){return this._LightmapTextureEnabled},set:function(i){this._LightmapTextureEnabled!==i&&(this._LightmapTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"RefractionTextureEnabled",{get:function(){return this._RefractionTextureEnabled},set:function(i){this._RefractionTextureEnabled!==i&&(this._RefractionTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ColorGradingTextureEnabled",{get:function(){return this._ColorGradingTextureEnabled},set:function(i){this._ColorGradingTextureEnabled!==i&&(this._ColorGradingTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"FresnelEnabled",{get:function(){return this._FresnelEnabled},set:function(i){this._FresnelEnabled!==i&&(this._FresnelEnabled=i,Engine.MarkAllMaterialsAsDirty(4))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ClearCoatTextureEnabled",{get:function(){return this._ClearCoatTextureEnabled},set:function(i){this._ClearCoatTextureEnabled!==i&&(this._ClearCoatTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ClearCoatBumpTextureEnabled",{get:function(){return this._ClearCoatBumpTextureEnabled},set:function(i){this._ClearCoatBumpTextureEnabled!==i&&(this._ClearCoatBumpTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ClearCoatTintTextureEnabled",{get:function(){return this._ClearCoatTintTextureEnabled},set:function(i){this._ClearCoatTintTextureEnabled!==i&&(this._ClearCoatTintTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"SheenTextureEnabled",{get:function(){return this._SheenTextureEnabled},set:function(i){this._SheenTextureEnabled!==i&&(this._SheenTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"AnisotropicTextureEnabled",{get:function(){return this._AnisotropicTextureEnabled},set:function(i){this._AnisotropicTextureEnabled!==i&&(this._AnisotropicTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"ThicknessTextureEnabled",{get:function(){return this._ThicknessTextureEnabled},set:function(i){this._ThicknessTextureEnabled!==i&&(this._ThicknessTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"RefractionIntensityTextureEnabled",{get:function(){return this._ThicknessTextureEnabled},set:function(i){this._RefractionIntensityTextureEnabled!==i&&(this._RefractionIntensityTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),Object.defineProperty(a,"TranslucencyIntensityTextureEnabled",{get:function(){return this._ThicknessTextureEnabled},set:function(i){this._TranslucencyIntensityTextureEnabled!==i&&(this._TranslucencyIntensityTextureEnabled=i,Engine.MarkAllMaterialsAsDirty(1))},enumerable:!1,configurable:!0}),a._DiffuseTextureEnabled=!0,a._DetailTextureEnabled=!0,a._AmbientTextureEnabled=!0,a._OpacityTextureEnabled=!0,a._ReflectionTextureEnabled=!0,a._EmissiveTextureEnabled=!0,a._SpecularTextureEnabled=!0,a._BumpTextureEnabled=!0,a._LightmapTextureEnabled=!0,a._RefractionTextureEnabled=!0,a._ColorGradingTextureEnabled=!0,a._FresnelEnabled=!0,a._ClearCoatTextureEnabled=!0,a._ClearCoatBumpTextureEnabled=!0,a._ClearCoatTintTextureEnabled=!0,a._SheenTextureEnabled=!0,a._AnisotropicTextureEnabled=!0,a._ThicknessTextureEnabled=!0,a._RefractionIntensityTextureEnabled=!0,a._TranslucencyIntensityTextureEnabled=!0,a}(),name$23="defaultFragmentDeclaration",shader$23=`uniform vec4 vEyePosition;
  1456. uniform vec4 vDiffuseColor;
  1457. #ifdef SPECULARTERM
  1458. uniform vec4 vSpecularColor;
  1459. #endif
  1460. uniform vec3 vEmissiveColor;
  1461. uniform vec3 vAmbientColor;
  1462. uniform float visibility;
  1463. #ifdef DIFFUSE
  1464. uniform vec2 vDiffuseInfos;
  1465. #endif
  1466. #ifdef AMBIENT
  1467. uniform vec2 vAmbientInfos;
  1468. #endif
  1469. #ifdef OPACITY
  1470. uniform vec2 vOpacityInfos;
  1471. #endif
  1472. #ifdef EMISSIVE
  1473. uniform vec2 vEmissiveInfos;
  1474. #endif
  1475. #ifdef LIGHTMAP
  1476. uniform vec2 vLightmapInfos;
  1477. #endif
  1478. #ifdef BUMP
  1479. uniform vec3 vBumpInfos;
  1480. uniform vec2 vTangentSpaceParams;
  1481. #endif
  1482. #ifdef ALPHATEST
  1483. uniform float alphaCutOff;
  1484. #endif
  1485. #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)
  1486. uniform mat4 view;
  1487. #endif
  1488. #ifdef REFRACTION
  1489. uniform vec4 vRefractionInfos;
  1490. #ifndef REFRACTIONMAP_3D
  1491. uniform mat4 refractionMatrix;
  1492. #endif
  1493. #ifdef REFRACTIONFRESNEL
  1494. uniform vec4 refractionLeftColor;
  1495. uniform vec4 refractionRightColor;
  1496. #endif
  1497. #if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)
  1498. uniform vec3 vRefractionPosition;
  1499. uniform vec3 vRefractionSize;
  1500. #endif
  1501. #endif
  1502. #if defined(SPECULAR) && defined(SPECULARTERM)
  1503. uniform vec2 vSpecularInfos;
  1504. #endif
  1505. #ifdef DIFFUSEFRESNEL
  1506. uniform vec4 diffuseLeftColor;
  1507. uniform vec4 diffuseRightColor;
  1508. #endif
  1509. #ifdef OPACITYFRESNEL
  1510. uniform vec4 opacityParts;
  1511. #endif
  1512. #ifdef EMISSIVEFRESNEL
  1513. uniform vec4 emissiveLeftColor;
  1514. uniform vec4 emissiveRightColor;
  1515. #endif
  1516. #ifdef REFLECTION
  1517. uniform vec2 vReflectionInfos;
  1518. #if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)
  1519. uniform mat4 reflectionMatrix;
  1520. #endif
  1521. #ifndef REFLECTIONMAP_SKYBOX
  1522. #if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
  1523. uniform vec3 vReflectionPosition;
  1524. uniform vec3 vReflectionSize;
  1525. #endif
  1526. #endif
  1527. #ifdef REFLECTIONFRESNEL
  1528. uniform vec4 reflectionLeftColor;
  1529. uniform vec4 reflectionRightColor;
  1530. #endif
  1531. #endif
  1532. #ifdef DETAIL
  1533. uniform vec4 vDetailInfos;
  1534. #endif`;ShaderStore.IncludesShadersStore[name$23]=shader$23;var name$22="defaultUboDeclaration",shader$22=`layout(std140,column_major) uniform;
  1535. uniform Material
  1536. {
  1537. vec4 diffuseLeftColor;
  1538. vec4 diffuseRightColor;
  1539. vec4 opacityParts;
  1540. vec4 reflectionLeftColor;
  1541. vec4 reflectionRightColor;
  1542. vec4 refractionLeftColor;
  1543. vec4 refractionRightColor;
  1544. vec4 emissiveLeftColor;
  1545. vec4 emissiveRightColor;
  1546. vec2 vDiffuseInfos;
  1547. vec2 vAmbientInfos;
  1548. vec2 vOpacityInfos;
  1549. vec2 vReflectionInfos;
  1550. vec3 vReflectionPosition;
  1551. vec3 vReflectionSize;
  1552. vec2 vEmissiveInfos;
  1553. vec2 vLightmapInfos;
  1554. vec2 vSpecularInfos;
  1555. vec3 vBumpInfos;
  1556. mat4 diffuseMatrix;
  1557. mat4 ambientMatrix;
  1558. mat4 opacityMatrix;
  1559. mat4 reflectionMatrix;
  1560. mat4 emissiveMatrix;
  1561. mat4 lightmapMatrix;
  1562. mat4 specularMatrix;
  1563. mat4 bumpMatrix;
  1564. vec2 vTangentSpaceParams;
  1565. float pointSize;
  1566. float alphaCutOff;
  1567. mat4 refractionMatrix;
  1568. vec4 vRefractionInfos;
  1569. vec3 vRefractionPosition;
  1570. vec3 vRefractionSize;
  1571. vec4 vSpecularColor;
  1572. vec3 vEmissiveColor;
  1573. vec4 vDiffuseColor;
  1574. vec3 vAmbientColor;
  1575. vec4 vDetailInfos;
  1576. mat4 detailMatrix;
  1577. };
  1578. #include<sceneUboDeclaration>
  1579. #include<meshUboDeclaration>
  1580. `;ShaderStore.IncludesShadersStore[name$22]=shader$22;var name$21="prePassDeclaration",shader$21=`#ifdef PREPASS
  1581. #extension GL_EXT_draw_buffers : require
  1582. layout(location=0) out highp vec4 glFragData[{X}];
  1583. highp vec4 gl_FragColor;
  1584. #ifdef PREPASS_DEPTH
  1585. varying highp vec3 vViewPos;
  1586. #endif
  1587. #ifdef PREPASS_VELOCITY
  1588. varying highp vec4 vCurrentPosition;
  1589. varying highp vec4 vPreviousPosition;
  1590. #endif
  1591. #endif
  1592. `;ShaderStore.IncludesShadersStore[name$21]=shader$21;var name$20="oitDeclaration",shader$20=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
  1593. #extension GL_EXT_draw_buffers : require
  1594. layout(location=0) out vec2 depth;
  1595. layout(location=1) out vec4 frontColor;
  1596. layout(location=2) out vec4 backColor;
  1597. #define MAX_DEPTH 99999.0
  1598. highp vec4 gl_FragColor;
  1599. uniform sampler2D oitDepthSampler;
  1600. uniform sampler2D oitFrontColorSampler;
  1601. #endif
  1602. `;ShaderStore.IncludesShadersStore[name$20]=shader$20;var name$1$="mainUVVaryingDeclaration",shader$1$=`#ifdef MAINUV{X}
  1603. varying vec2 vMainUV{X};
  1604. #endif
  1605. `;ShaderStore.IncludesShadersStore[name$1$]=shader$1$;var name$1_="lightFragmentDeclaration",shader$1_=`#ifdef LIGHT{X}
  1606. uniform vec4 vLightData{X};
  1607. uniform vec4 vLightDiffuse{X};
  1608. #ifdef SPECULARTERM
  1609. uniform vec4 vLightSpecular{X};
  1610. #else
  1611. vec4 vLightSpecular{X}=vec4(0.);
  1612. #endif
  1613. #ifdef SHADOW{X}
  1614. #ifdef SHADOWCSM{X}
  1615. uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
  1616. uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];
  1617. uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];
  1618. uniform float cascadeBlendFactor{X};
  1619. varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
  1620. varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
  1621. varying vec4 vPositionFromCamera{X};
  1622. #if defined(SHADOWPCSS{X})
  1623. uniform highp sampler2DArrayShadow shadowSampler{X};
  1624. uniform highp sampler2DArray depthSampler{X};
  1625. uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
  1626. uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
  1627. uniform float penumbraDarkness{X};
  1628. #elif defined(SHADOWPCF{X})
  1629. uniform highp sampler2DArrayShadow shadowSampler{X};
  1630. #else
  1631. uniform highp sampler2DArray shadowSampler{X};
  1632. #endif
  1633. #ifdef SHADOWCSMDEBUG{X}
  1634. const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
  1635. (
  1636. vec3 ( 1.5,0.0,0.0 ),
  1637. vec3 ( 0.0,1.5,0.0 ),
  1638. vec3 ( 0.0,0.0,5.5 ),
  1639. vec3 ( 1.5,0.0,5.5 ),
  1640. vec3 ( 1.5,1.5,0.0 ),
  1641. vec3 ( 1.0,1.0,1.0 ),
  1642. vec3 ( 0.0,1.0,5.5 ),
  1643. vec3 ( 0.5,3.5,0.75 )
  1644. );
  1645. vec3 shadowDebug{X};
  1646. #endif
  1647. #ifdef SHADOWCSMUSESHADOWMAXZ{X}
  1648. int index{X}=-1;
  1649. #else
  1650. int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
  1651. #endif
  1652. float diff{X}=0.;
  1653. #elif defined(SHADOWCUBE{X})
  1654. uniform samplerCube shadowSampler{X};
  1655. #else
  1656. varying vec4 vPositionFromLight{X};
  1657. varying float vDepthMetric{X};
  1658. #if defined(SHADOWPCSS{X})
  1659. uniform highp sampler2DShadow shadowSampler{X};
  1660. uniform highp sampler2D depthSampler{X};
  1661. #elif defined(SHADOWPCF{X})
  1662. uniform highp sampler2DShadow shadowSampler{X};
  1663. #else
  1664. uniform sampler2D shadowSampler{X};
  1665. #endif
  1666. uniform mat4 lightMatrix{X};
  1667. #endif
  1668. uniform vec4 shadowsInfo{X};
  1669. uniform vec2 depthValues{X};
  1670. #endif
  1671. #ifdef SPOTLIGHT{X}
  1672. uniform vec4 vLightDirection{X};
  1673. uniform vec4 vLightFalloff{X};
  1674. #elif defined(POINTLIGHT{X})
  1675. uniform vec4 vLightFalloff{X};
  1676. #elif defined(HEMILIGHT{X})
  1677. uniform vec3 vLightGround{X};
  1678. #endif
  1679. #ifdef PROJECTEDLIGHTTEXTURE{X}
  1680. uniform mat4 textureProjectionMatrix{X};
  1681. uniform sampler2D projectionLightSampler{X};
  1682. #endif
  1683. #endif`;ShaderStore.IncludesShadersStore[name$1_]=shader$1_;var name$1Z="lightUboDeclaration",shader$1Z=`#ifdef LIGHT{X}
  1684. uniform Light{X}
  1685. {
  1686. vec4 vLightData;
  1687. vec4 vLightDiffuse;
  1688. vec4 vLightSpecular;
  1689. #ifdef SPOTLIGHT{X}
  1690. vec4 vLightDirection;
  1691. vec4 vLightFalloff;
  1692. #elif defined(POINTLIGHT{X})
  1693. vec4 vLightFalloff;
  1694. #elif defined(HEMILIGHT{X})
  1695. vec3 vLightGround;
  1696. #endif
  1697. vec4 shadowsInfo;
  1698. vec2 depthValues;
  1699. } light{X};
  1700. #ifdef PROJECTEDLIGHTTEXTURE{X}
  1701. uniform mat4 textureProjectionMatrix{X};
  1702. uniform sampler2D projectionLightSampler{X};
  1703. #endif
  1704. #ifdef SHADOW{X}
  1705. #ifdef SHADOWCSM{X}
  1706. uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
  1707. uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];
  1708. uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];
  1709. uniform float cascadeBlendFactor{X};
  1710. varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
  1711. varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
  1712. varying vec4 vPositionFromCamera{X};
  1713. #if defined(SHADOWPCSS{X})
  1714. uniform highp sampler2DArrayShadow shadowSampler{X};
  1715. uniform highp sampler2DArray depthSampler{X};
  1716. uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
  1717. uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
  1718. uniform float penumbraDarkness{X};
  1719. #elif defined(SHADOWPCF{X})
  1720. uniform highp sampler2DArrayShadow shadowSampler{X};
  1721. #else
  1722. uniform highp sampler2DArray shadowSampler{X};
  1723. #endif
  1724. #ifdef SHADOWCSMDEBUG{X}
  1725. const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
  1726. (
  1727. vec3 ( 1.5,0.0,0.0 ),
  1728. vec3 ( 0.0,1.5,0.0 ),
  1729. vec3 ( 0.0,0.0,5.5 ),
  1730. vec3 ( 1.5,0.0,5.5 ),
  1731. vec3 ( 1.5,1.5,0.0 ),
  1732. vec3 ( 1.0,1.0,1.0 ),
  1733. vec3 ( 0.0,1.0,5.5 ),
  1734. vec3 ( 0.5,3.5,0.75 )
  1735. );
  1736. vec3 shadowDebug{X};
  1737. #endif
  1738. #ifdef SHADOWCSMUSESHADOWMAXZ{X}
  1739. int index{X}=-1;
  1740. #else
  1741. int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
  1742. #endif
  1743. float diff{X}=0.;
  1744. #elif defined(SHADOWCUBE{X})
  1745. uniform samplerCube shadowSampler{X};
  1746. #else
  1747. varying vec4 vPositionFromLight{X};
  1748. varying float vDepthMetric{X};
  1749. #if defined(SHADOWPCSS{X})
  1750. uniform highp sampler2DShadow shadowSampler{X};
  1751. uniform highp sampler2D depthSampler{X};
  1752. #elif defined(SHADOWPCF{X})
  1753. uniform highp sampler2DShadow shadowSampler{X};
  1754. #else
  1755. uniform sampler2D shadowSampler{X};
  1756. #endif
  1757. uniform mat4 lightMatrix{X};
  1758. #endif
  1759. #endif
  1760. #endif`;ShaderStore.IncludesShadersStore[name$1Z]=shader$1Z;var name$1Y="lightsFragmentFunctions",shader$1Y=`
  1761. struct lightingInfo
  1762. {
  1763. vec3 diffuse;
  1764. #ifdef SPECULARTERM
  1765. vec3 specular;
  1766. #endif
  1767. #ifdef NDOTL
  1768. float ndl;
  1769. #endif
  1770. };
  1771. lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {
  1772. lightingInfo result;
  1773. vec3 lightVectorW;
  1774. float attenuation=1.0;
  1775. if (lightData.w == 0.)
  1776. {
  1777. vec3 direction=lightData.xyz-vPositionW;
  1778. attenuation=max(0.,1.0-length(direction)/range);
  1779. lightVectorW=normalize(direction);
  1780. }
  1781. else
  1782. {
  1783. lightVectorW=normalize(-lightData.xyz);
  1784. }
  1785. float ndl=max(0.,dot(vNormal,lightVectorW));
  1786. #ifdef NDOTL
  1787. result.ndl=ndl;
  1788. #endif
  1789. result.diffuse=ndl*diffuseColor*attenuation;
  1790. #ifdef SPECULARTERM
  1791. vec3 angleW=normalize(viewDirectionW+lightVectorW);
  1792. float specComp=max(0.,dot(vNormal,angleW));
  1793. specComp=pow(specComp,max(1.,glossiness));
  1794. result.specular=specComp*specularColor*attenuation;
  1795. #endif
  1796. return result;
  1797. }
  1798. lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {
  1799. lightingInfo result;
  1800. vec3 direction=lightData.xyz-vPositionW;
  1801. vec3 lightVectorW=normalize(direction);
  1802. float attenuation=max(0.,1.0-length(direction)/range);
  1803. float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));
  1804. if (cosAngle>=lightDirection.w)
  1805. {
  1806. cosAngle=max(0.,pow(cosAngle,lightData.w));
  1807. attenuation*=cosAngle;
  1808. float ndl=max(0.,dot(vNormal,lightVectorW));
  1809. #ifdef NDOTL
  1810. result.ndl=ndl;
  1811. #endif
  1812. result.diffuse=ndl*diffuseColor*attenuation;
  1813. #ifdef SPECULARTERM
  1814. vec3 angleW=normalize(viewDirectionW+lightVectorW);
  1815. float specComp=max(0.,dot(vNormal,angleW));
  1816. specComp=pow(specComp,max(1.,glossiness));
  1817. result.specular=specComp*specularColor*attenuation;
  1818. #endif
  1819. return result;
  1820. }
  1821. result.diffuse=vec3(0.);
  1822. #ifdef SPECULARTERM
  1823. result.specular=vec3(0.);
  1824. #endif
  1825. #ifdef NDOTL
  1826. result.ndl=0.;
  1827. #endif
  1828. return result;
  1829. }
  1830. lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {
  1831. lightingInfo result;
  1832. float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;
  1833. #ifdef NDOTL
  1834. result.ndl=ndl;
  1835. #endif
  1836. result.diffuse=mix(groundColor,diffuseColor,ndl);
  1837. #ifdef SPECULARTERM
  1838. vec3 angleW=normalize(viewDirectionW+lightData.xyz);
  1839. float specComp=max(0.,dot(vNormal,angleW));
  1840. specComp=pow(specComp,max(1.,glossiness));
  1841. result.specular=specComp*specularColor;
  1842. #endif
  1843. return result;
  1844. }
  1845. #define inline
  1846. vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){
  1847. vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);
  1848. strq/=strq.w;
  1849. vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;
  1850. return textureColor;
  1851. }`;ShaderStore.IncludesShadersStore[name$1Y]=shader$1Y;var name$1X="shadowsFragmentFunctions",shader$1X=`#ifdef SHADOWS
  1852. #ifndef SHADOWFLOAT
  1853. float unpack(vec4 color)
  1854. {
  1855. const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);
  1856. return dot(color,bit_shift);
  1857. }
  1858. #endif
  1859. float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)
  1860. {
  1861. float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));
  1862. return mix(value,1.0,mask);
  1863. }
  1864. #define inline
  1865. float computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)
  1866. {
  1867. vec3 directionToLight=vPositionW-lightPosition;
  1868. float depth=length(directionToLight);
  1869. depth=(depth+depthValues.x)/(depthValues.y);
  1870. depth=clamp(depth,0.,1.0);
  1871. directionToLight=normalize(directionToLight);
  1872. directionToLight.y=-directionToLight.y;
  1873. #ifndef SHADOWFLOAT
  1874. float shadow=unpack(textureCube(shadowSampler,directionToLight));
  1875. #else
  1876. float shadow=textureCube(shadowSampler,directionToLight).x;
  1877. #endif
  1878. return depth>shadow ? darkness : 1.0;
  1879. }
  1880. #define inline
  1881. float computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)
  1882. {
  1883. vec3 directionToLight=vPositionW-lightPosition;
  1884. float depth=length(directionToLight);
  1885. depth=(depth+depthValues.x)/(depthValues.y);
  1886. depth=clamp(depth,0.,1.0);
  1887. directionToLight=normalize(directionToLight);
  1888. directionToLight.y=-directionToLight.y;
  1889. float visibility=1.;
  1890. vec3 poissonDisk[4];
  1891. poissonDisk[0]=vec3(-1.0,1.0,-1.0);
  1892. poissonDisk[1]=vec3(1.0,-1.0,-1.0);
  1893. poissonDisk[2]=vec3(-1.0,-1.0,-1.0);
  1894. poissonDisk[3]=vec3(1.0,-1.0,1.0);
  1895. #ifndef SHADOWFLOAT
  1896. if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;
  1897. if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;
  1898. if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;
  1899. if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;
  1900. #else
  1901. if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;
  1902. if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;
  1903. if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;
  1904. if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;
  1905. #endif
  1906. return min(1.0,visibility+darkness);
  1907. }
  1908. #define inline
  1909. float computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
  1910. {
  1911. vec3 directionToLight=vPositionW-lightPosition;
  1912. float depth=length(directionToLight);
  1913. depth=(depth+depthValues.x)/(depthValues.y);
  1914. float shadowPixelDepth=clamp(depth,0.,1.0);
  1915. directionToLight=normalize(directionToLight);
  1916. directionToLight.y=-directionToLight.y;
  1917. #ifndef SHADOWFLOAT
  1918. float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
  1919. #else
  1920. float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
  1921. #endif
  1922. float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);
  1923. return esm;
  1924. }
  1925. #define inline
  1926. float computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
  1927. {
  1928. vec3 directionToLight=vPositionW-lightPosition;
  1929. float depth=length(directionToLight);
  1930. depth=(depth+depthValues.x)/(depthValues.y);
  1931. float shadowPixelDepth=clamp(depth,0.,1.0);
  1932. directionToLight=normalize(directionToLight);
  1933. directionToLight.y=-directionToLight.y;
  1934. #ifndef SHADOWFLOAT
  1935. float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
  1936. #else
  1937. float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
  1938. #endif
  1939. float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);
  1940. return esm;
  1941. }
  1942. #if defined(WEBGL2) || defined(WEBGPU)
  1943. #define inline
  1944. float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)
  1945. {
  1946. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  1947. vec2 uv=0.5*clipSpace.xy+vec2(0.5);
  1948. vec3 uvLayer=vec3(uv.x,uv.y,layer);
  1949. float shadowPixelDepth=clamp(depthMetric,0.,1.0);
  1950. #ifndef SHADOWFLOAT
  1951. float shadow=unpack(texture2D(shadowSampler,uvLayer));
  1952. #else
  1953. float shadow=texture2D(shadowSampler,uvLayer).x;
  1954. #endif
  1955. return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;
  1956. }
  1957. #endif
  1958. #define inline
  1959. float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)
  1960. {
  1961. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  1962. vec2 uv=0.5*clipSpace.xy+vec2(0.5);
  1963. if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
  1964. {
  1965. return 1.0;
  1966. }
  1967. else
  1968. {
  1969. float shadowPixelDepth=clamp(depthMetric,0.,1.0);
  1970. #ifndef SHADOWFLOAT
  1971. float shadow=unpack(texture2D(shadowSampler,uv));
  1972. #else
  1973. float shadow=texture2D(shadowSampler,uv).x;
  1974. #endif
  1975. return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;
  1976. }
  1977. }
  1978. #define inline
  1979. float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)
  1980. {
  1981. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  1982. vec2 uv=0.5*clipSpace.xy+vec2(0.5);
  1983. if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
  1984. {
  1985. return 1.0;
  1986. }
  1987. else
  1988. {
  1989. float shadowPixelDepth=clamp(depthMetric,0.,1.0);
  1990. float visibility=1.;
  1991. vec2 poissonDisk[4];
  1992. poissonDisk[0]=vec2(-0.94201624,-0.39906216);
  1993. poissonDisk[1]=vec2(0.94558609,-0.76890725);
  1994. poissonDisk[2]=vec2(-0.094184101,-0.92938870);
  1995. poissonDisk[3]=vec2(0.34495938,0.29387760);
  1996. #ifndef SHADOWFLOAT
  1997. if (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;
  1998. if (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;
  1999. if (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;
  2000. if (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;
  2001. #else
  2002. if (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;
  2003. if (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;
  2004. if (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;
  2005. if (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;
  2006. #endif
  2007. return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);
  2008. }
  2009. }
  2010. #define inline
  2011. float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
  2012. {
  2013. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2014. vec2 uv=0.5*clipSpace.xy+vec2(0.5);
  2015. if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
  2016. {
  2017. return 1.0;
  2018. }
  2019. else
  2020. {
  2021. float shadowPixelDepth=clamp(depthMetric,0.,1.0);
  2022. #ifndef SHADOWFLOAT
  2023. float shadowMapSample=unpack(texture2D(shadowSampler,uv));
  2024. #else
  2025. float shadowMapSample=texture2D(shadowSampler,uv).x;
  2026. #endif
  2027. float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);
  2028. return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);
  2029. }
  2030. }
  2031. #define inline
  2032. float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
  2033. {
  2034. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2035. vec2 uv=0.5*clipSpace.xy+vec2(0.5);
  2036. if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
  2037. {
  2038. return 1.0;
  2039. }
  2040. else
  2041. {
  2042. float shadowPixelDepth=clamp(depthMetric,0.,1.0);
  2043. #ifndef SHADOWFLOAT
  2044. float shadowMapSample=unpack(texture2D(shadowSampler,uv));
  2045. #else
  2046. float shadowMapSample=texture2D(shadowSampler,uv).x;
  2047. #endif
  2048. float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);
  2049. return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);
  2050. }
  2051. }
  2052. #ifdef IS_NDC_HALF_ZRANGE
  2053. #define ZINCLIP clipSpace.z
  2054. #else
  2055. #define ZINCLIP uvDepth.z
  2056. #endif
  2057. #if defined(WEBGL2) || defined(WEBGPU)
  2058. #define GREATEST_LESS_THAN_ONE 0.99999994
  2059. #define inline
  2060. float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)
  2061. {
  2062. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2063. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2064. uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
  2065. vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);
  2066. float shadow=texture2D(shadowSampler,uvDepthLayer);
  2067. shadow=mix(darkness,1.,shadow);
  2068. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2069. }
  2070. #define inline
  2071. float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
  2072. {
  2073. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2074. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2075. uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
  2076. vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
  2077. uv+=0.5;
  2078. vec2 st=fract(uv);
  2079. vec2 base_uv=floor(uv)-0.5;
  2080. base_uv*=shadowMapSizeAndInverse.y;
  2081. vec2 uvw0=3.-2.*st;
  2082. vec2 uvw1=1.+2.*st;
  2083. vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;
  2084. vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;
  2085. float shadow=0.;
  2086. shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));
  2087. shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));
  2088. shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));
  2089. shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));
  2090. shadow=shadow/16.;
  2091. shadow=mix(darkness,1.,shadow);
  2092. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2093. }
  2094. #define inline
  2095. float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
  2096. {
  2097. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2098. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2099. uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
  2100. vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
  2101. uv+=0.5;
  2102. vec2 st=fract(uv);
  2103. vec2 base_uv=floor(uv)-0.5;
  2104. base_uv*=shadowMapSizeAndInverse.y;
  2105. vec2 uvw0=4.-3.*st;
  2106. vec2 uvw1=vec2(7.);
  2107. vec2 uvw2=1.+3.*st;
  2108. vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;
  2109. vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;
  2110. float shadow=0.;
  2111. shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));
  2112. shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));
  2113. shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));
  2114. shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));
  2115. shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));
  2116. shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));
  2117. shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));
  2118. shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));
  2119. shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));
  2120. shadow=shadow/144.;
  2121. shadow=mix(darkness,1.,shadow);
  2122. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2123. }
  2124. #define inline
  2125. float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)
  2126. {
  2127. if (depthMetric>1.0 || depthMetric<0.0) {
  2128. return 1.0;
  2129. }
  2130. else
  2131. {
  2132. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2133. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2134. uvDepth.z=ZINCLIP;
  2135. float shadow=texture2D(shadowSampler,uvDepth);
  2136. shadow=mix(darkness,1.,shadow);
  2137. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2138. }
  2139. }
  2140. #define inline
  2141. float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
  2142. {
  2143. if (depthMetric>1.0 || depthMetric<0.0) {
  2144. return 1.0;
  2145. }
  2146. else
  2147. {
  2148. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2149. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2150. uvDepth.z=ZINCLIP;
  2151. vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
  2152. uv+=0.5;
  2153. vec2 st=fract(uv);
  2154. vec2 base_uv=floor(uv)-0.5;
  2155. base_uv*=shadowMapSizeAndInverse.y;
  2156. vec2 uvw0=3.-2.*st;
  2157. vec2 uvw1=1.+2.*st;
  2158. vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;
  2159. vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;
  2160. float shadow=0.;
  2161. shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));
  2162. shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));
  2163. shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));
  2164. shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));
  2165. shadow=shadow/16.;
  2166. shadow=mix(darkness,1.,shadow);
  2167. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2168. }
  2169. }
  2170. #define inline
  2171. float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
  2172. {
  2173. if (depthMetric>1.0 || depthMetric<0.0) {
  2174. return 1.0;
  2175. }
  2176. else
  2177. {
  2178. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2179. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2180. uvDepth.z=ZINCLIP;
  2181. vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
  2182. uv+=0.5;
  2183. vec2 st=fract(uv);
  2184. vec2 base_uv=floor(uv)-0.5;
  2185. base_uv*=shadowMapSizeAndInverse.y;
  2186. vec2 uvw0=4.-3.*st;
  2187. vec2 uvw1=vec2(7.);
  2188. vec2 uvw2=1.+3.*st;
  2189. vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;
  2190. vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;
  2191. float shadow=0.;
  2192. shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));
  2193. shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));
  2194. shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));
  2195. shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));
  2196. shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));
  2197. shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));
  2198. shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));
  2199. shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));
  2200. shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));
  2201. shadow=shadow/144.;
  2202. shadow=mix(darkness,1.,shadow);
  2203. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2204. }
  2205. }
  2206. const vec3 PoissonSamplers32[64]=vec3[64](
  2207. vec3(0.06407013,0.05409927,0.),
  2208. vec3(0.7366577,0.5789394,0.),
  2209. vec3(-0.6270542,-0.5320278,0.),
  2210. vec3(-0.4096107,0.8411095,0.),
  2211. vec3(0.6849564,-0.4990818,0.),
  2212. vec3(-0.874181,-0.04579735,0.),
  2213. vec3(0.9989998,0.0009880066,0.),
  2214. vec3(-0.004920578,-0.9151649,0.),
  2215. vec3(0.1805763,0.9747483,0.),
  2216. vec3(-0.2138451,0.2635818,0.),
  2217. vec3(0.109845,0.3884785,0.),
  2218. vec3(0.06876755,-0.3581074,0.),
  2219. vec3(0.374073,-0.7661266,0.),
  2220. vec3(0.3079132,-0.1216763,0.),
  2221. vec3(-0.3794335,-0.8271583,0.),
  2222. vec3(-0.203878,-0.07715034,0.),
  2223. vec3(0.5912697,0.1469799,0.),
  2224. vec3(-0.88069,0.3031784,0.),
  2225. vec3(0.5040108,0.8283722,0.),
  2226. vec3(-0.5844124,0.5494877,0.),
  2227. vec3(0.6017799,-0.1726654,0.),
  2228. vec3(-0.5554981,0.1559997,0.),
  2229. vec3(-0.3016369,-0.3900928,0.),
  2230. vec3(-0.5550632,-0.1723762,0.),
  2231. vec3(0.925029,0.2995041,0.),
  2232. vec3(-0.2473137,0.5538505,0.),
  2233. vec3(0.9183037,-0.2862392,0.),
  2234. vec3(0.2469421,0.6718712,0.),
  2235. vec3(0.3916397,-0.4328209,0.),
  2236. vec3(-0.03576927,-0.6220032,0.),
  2237. vec3(-0.04661255,0.7995201,0.),
  2238. vec3(0.4402924,0.3640312,0.),
  2239. vec3(0.,0.,0.),
  2240. vec3(0.,0.,0.),
  2241. vec3(0.,0.,0.),
  2242. vec3(0.,0.,0.),
  2243. vec3(0.,0.,0.),
  2244. vec3(0.,0.,0.),
  2245. vec3(0.,0.,0.),
  2246. vec3(0.,0.,0.),
  2247. vec3(0.,0.,0.),
  2248. vec3(0.,0.,0.),
  2249. vec3(0.,0.,0.),
  2250. vec3(0.,0.,0.),
  2251. vec3(0.,0.,0.),
  2252. vec3(0.,0.,0.),
  2253. vec3(0.,0.,0.),
  2254. vec3(0.,0.,0.),
  2255. vec3(0.,0.,0.),
  2256. vec3(0.,0.,0.),
  2257. vec3(0.,0.,0.),
  2258. vec3(0.,0.,0.),
  2259. vec3(0.,0.,0.),
  2260. vec3(0.,0.,0.),
  2261. vec3(0.,0.,0.),
  2262. vec3(0.,0.,0.),
  2263. vec3(0.,0.,0.),
  2264. vec3(0.,0.,0.),
  2265. vec3(0.,0.,0.),
  2266. vec3(0.,0.,0.),
  2267. vec3(0.,0.,0.),
  2268. vec3(0.,0.,0.),
  2269. vec3(0.,0.,0.),
  2270. vec3(0.,0.,0.)
  2271. );
  2272. const vec3 PoissonSamplers64[64]=vec3[64](
  2273. vec3(-0.613392,0.617481,0.),
  2274. vec3(0.170019,-0.040254,0.),
  2275. vec3(-0.299417,0.791925,0.),
  2276. vec3(0.645680,0.493210,0.),
  2277. vec3(-0.651784,0.717887,0.),
  2278. vec3(0.421003,0.027070,0.),
  2279. vec3(-0.817194,-0.271096,0.),
  2280. vec3(-0.705374,-0.668203,0.),
  2281. vec3(0.977050,-0.108615,0.),
  2282. vec3(0.063326,0.142369,0.),
  2283. vec3(0.203528,0.214331,0.),
  2284. vec3(-0.667531,0.326090,0.),
  2285. vec3(-0.098422,-0.295755,0.),
  2286. vec3(-0.885922,0.215369,0.),
  2287. vec3(0.566637,0.605213,0.),
  2288. vec3(0.039766,-0.396100,0.),
  2289. vec3(0.751946,0.453352,0.),
  2290. vec3(0.078707,-0.715323,0.),
  2291. vec3(-0.075838,-0.529344,0.),
  2292. vec3(0.724479,-0.580798,0.),
  2293. vec3(0.222999,-0.215125,0.),
  2294. vec3(-0.467574,-0.405438,0.),
  2295. vec3(-0.248268,-0.814753,0.),
  2296. vec3(0.354411,-0.887570,0.),
  2297. vec3(0.175817,0.382366,0.),
  2298. vec3(0.487472,-0.063082,0.),
  2299. vec3(-0.084078,0.898312,0.),
  2300. vec3(0.488876,-0.783441,0.),
  2301. vec3(0.470016,0.217933,0.),
  2302. vec3(-0.696890,-0.549791,0.),
  2303. vec3(-0.149693,0.605762,0.),
  2304. vec3(0.034211,0.979980,0.),
  2305. vec3(0.503098,-0.308878,0.),
  2306. vec3(-0.016205,-0.872921,0.),
  2307. vec3(0.385784,-0.393902,0.),
  2308. vec3(-0.146886,-0.859249,0.),
  2309. vec3(0.643361,0.164098,0.),
  2310. vec3(0.634388,-0.049471,0.),
  2311. vec3(-0.688894,0.007843,0.),
  2312. vec3(0.464034,-0.188818,0.),
  2313. vec3(-0.440840,0.137486,0.),
  2314. vec3(0.364483,0.511704,0.),
  2315. vec3(0.034028,0.325968,0.),
  2316. vec3(0.099094,-0.308023,0.),
  2317. vec3(0.693960,-0.366253,0.),
  2318. vec3(0.678884,-0.204688,0.),
  2319. vec3(0.001801,0.780328,0.),
  2320. vec3(0.145177,-0.898984,0.),
  2321. vec3(0.062655,-0.611866,0.),
  2322. vec3(0.315226,-0.604297,0.),
  2323. vec3(-0.780145,0.486251,0.),
  2324. vec3(-0.371868,0.882138,0.),
  2325. vec3(0.200476,0.494430,0.),
  2326. vec3(-0.494552,-0.711051,0.),
  2327. vec3(0.612476,0.705252,0.),
  2328. vec3(-0.578845,-0.768792,0.),
  2329. vec3(-0.772454,-0.090976,0.),
  2330. vec3(0.504440,0.372295,0.),
  2331. vec3(0.155736,0.065157,0.),
  2332. vec3(0.391522,0.849605,0.),
  2333. vec3(-0.620106,-0.328104,0.),
  2334. vec3(0.789239,-0.419965,0.),
  2335. vec3(-0.545396,0.538133,0.),
  2336. vec3(-0.178564,-0.596057,0.)
  2337. );
  2338. #define inline
  2339. float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
  2340. {
  2341. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2342. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2343. uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
  2344. vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);
  2345. float blockerDepth=0.0;
  2346. float sumBlockerDepth=0.0;
  2347. float numBlocker=0.0;
  2348. for (int i=0; i<searchTapCount; i ++) {
  2349. blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;
  2350. if (blockerDepth<depthMetric) {
  2351. sumBlockerDepth+=blockerDepth;
  2352. numBlocker++;
  2353. }
  2354. }
  2355. if (numBlocker<1.0) {
  2356. return 1.0;
  2357. }
  2358. else
  2359. {
  2360. float avgBlockerDepth=sumBlockerDepth/numBlocker;
  2361. float AAOffset=shadowMapSizeInverse*10.;
  2362. float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);
  2363. vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);
  2364. float random=getRand(vPositionFromLight.xy);
  2365. float rotationAngle=random*3.1415926;
  2366. vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));
  2367. float shadow=0.;
  2368. for (int i=0; i<pcfTapCount; i++) {
  2369. vec4 offset=vec4(poissonSamplers[i],0.);
  2370. offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);
  2371. shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);
  2372. }
  2373. shadow/=float(pcfTapCount);
  2374. shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));
  2375. shadow=mix(darkness,1.,shadow);
  2376. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2377. }
  2378. }
  2379. #define inline
  2380. float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)
  2381. {
  2382. if (depthMetric>1.0 || depthMetric<0.0) {
  2383. return 1.0;
  2384. }
  2385. else
  2386. {
  2387. vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
  2388. vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
  2389. uvDepth.z=ZINCLIP;
  2390. float blockerDepth=0.0;
  2391. float sumBlockerDepth=0.0;
  2392. float numBlocker=0.0;
  2393. for (int i=0; i<searchTapCount; i ++) {
  2394. blockerDepth=texture2D(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;
  2395. if (blockerDepth<depthMetric) {
  2396. sumBlockerDepth+=blockerDepth;
  2397. numBlocker++;
  2398. }
  2399. }
  2400. if (numBlocker<1.0) {
  2401. return 1.0;
  2402. }
  2403. else
  2404. {
  2405. float avgBlockerDepth=sumBlockerDepth/numBlocker;
  2406. float AAOffset=shadowMapSizeInverse*10.;
  2407. float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);
  2408. float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;
  2409. float random=getRand(vPositionFromLight.xy);
  2410. float rotationAngle=random*3.1415926;
  2411. vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));
  2412. float shadow=0.;
  2413. for (int i=0; i<pcfTapCount; i++) {
  2414. vec3 offset=poissonSamplers[i];
  2415. offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);
  2416. shadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);
  2417. }
  2418. shadow/=float(pcfTapCount);
  2419. shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);
  2420. shadow=mix(darkness,1.,shadow);
  2421. return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
  2422. }
  2423. }
  2424. }
  2425. #define inline
  2426. float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
  2427. {
  2428. return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);
  2429. }
  2430. #define inline
  2431. float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
  2432. {
  2433. return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);
  2434. }
  2435. #define inline
  2436. float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
  2437. {
  2438. return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);
  2439. }
  2440. #define inline
  2441. float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
  2442. {
  2443. return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);
  2444. }
  2445. #define inline
  2446. float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
  2447. {
  2448. return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);
  2449. }
  2450. #define inline
  2451. float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
  2452. {
  2453. return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);
  2454. }
  2455. #endif
  2456. #endif
  2457. `;ShaderStore.IncludesShadersStore[name$1X]=shader$1X;var name$1W="samplerFragmentDeclaration",shader$1W=`#ifdef _DEFINENAME_
  2458. #if _DEFINENAME_DIRECTUV == 1
  2459. #define v_VARYINGNAME_UV vMainUV1
  2460. #elif _DEFINENAME_DIRECTUV == 2
  2461. #define v_VARYINGNAME_UV vMainUV2
  2462. #elif _DEFINENAME_DIRECTUV == 3
  2463. #define v_VARYINGNAME_UV vMainUV3
  2464. #elif _DEFINENAME_DIRECTUV == 4
  2465. #define v_VARYINGNAME_UV vMainUV4
  2466. #elif _DEFINENAME_DIRECTUV == 5
  2467. #define v_VARYINGNAME_UV vMainUV5
  2468. #elif _DEFINENAME_DIRECTUV == 6
  2469. #define v_VARYINGNAME_UV vMainUV6
  2470. #else
  2471. varying vec2 v_VARYINGNAME_UV;
  2472. #endif
  2473. uniform sampler2D _SAMPLERNAME_Sampler;
  2474. #endif
  2475. `;ShaderStore.IncludesShadersStore[name$1W]=shader$1W;var name$1V="fresnelFunction",shader$1V=`#ifdef FRESNEL
  2476. float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)
  2477. {
  2478. float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);
  2479. return clamp(fresnelTerm,0.,1.);
  2480. }
  2481. #endif`;ShaderStore.IncludesShadersStore[name$1V]=shader$1V;var name$1U="reflectionFunction",shader$1U=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
  2482. {
  2483. float lon=atan(direction.z,direction.x);
  2484. float lat=acos(direction.y);
  2485. vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;
  2486. float s=sphereCoords.x*0.5+0.5;
  2487. float t=sphereCoords.y;
  2488. return vec3(s,t,0);
  2489. }
  2490. vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
  2491. {
  2492. float lon=atan(direction.z,direction.x);
  2493. float lat=acos(direction.y);
  2494. vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;
  2495. float s=sphereCoords.x*0.5+0.5;
  2496. float t=sphereCoords.y;
  2497. return vec3(1.0-s,t,0);
  2498. }
  2499. vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
  2500. {
  2501. vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);
  2502. vec3 r=normalize(reflect(cameraToVertex,worldNormal));
  2503. r=vec3(reflectionMatrix*vec4(r,0));
  2504. float lon=atan(r.z,r.x);
  2505. float lat=acos(r.y);
  2506. vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;
  2507. float s=sphereCoords.x*0.5+0.5;
  2508. float t=sphereCoords.y;
  2509. return vec3(s,t,0);
  2510. }
  2511. vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)
  2512. {
  2513. vec3 viewDir=normalize(vec3(view*worldPos));
  2514. vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));
  2515. vec3 r=reflect(viewDir,viewNormal);
  2516. r=vec3(reflectionMatrix*vec4(r,0));
  2517. r.z=r.z-1.0;
  2518. float m=2.0*length(r);
  2519. return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);
  2520. }
  2521. vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
  2522. {
  2523. vec3 viewDir=worldPos.xyz-eyePosition;
  2524. vec3 coords=normalize(reflect(viewDir,worldNormal));
  2525. return vec3(reflectionMatrix*vec4(coords,1));
  2526. }
  2527. vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
  2528. {
  2529. vec3 viewDir=normalize(worldPos.xyz-eyePosition);
  2530. vec3 coords=reflect(viewDir,worldNormal);
  2531. coords=vec3(reflectionMatrix*vec4(coords,0));
  2532. #ifdef INVERTCUBICMAP
  2533. coords.y*=-1.0;
  2534. #endif
  2535. return coords;
  2536. }
  2537. vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)
  2538. {
  2539. vec3 viewDir=normalize(worldPos.xyz-eyePosition);
  2540. vec3 coords=reflect(viewDir,worldNormal);
  2541. coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);
  2542. coords=vec3(reflectionMatrix*vec4(coords,0));
  2543. #ifdef INVERTCUBICMAP
  2544. coords.y*=-1.0;
  2545. #endif
  2546. return coords;
  2547. }
  2548. vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)
  2549. {
  2550. return vec3(reflectionMatrix*(view*worldPos));
  2551. }
  2552. vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)
  2553. {
  2554. return vec3(reflectionMatrix*vec4(positionW,1.));
  2555. }
  2556. #ifdef REFLECTION
  2557. vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)
  2558. {
  2559. #ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED
  2560. vec3 direction=normalize(vDirectionW);
  2561. return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);
  2562. #endif
  2563. #ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED
  2564. vec3 direction=normalize(vDirectionW);
  2565. return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);
  2566. #endif
  2567. #ifdef REFLECTIONMAP_EQUIRECTANGULAR
  2568. return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
  2569. #endif
  2570. #ifdef REFLECTIONMAP_SPHERICAL
  2571. return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);
  2572. #endif
  2573. #ifdef REFLECTIONMAP_PLANAR
  2574. return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
  2575. #endif
  2576. #ifdef REFLECTIONMAP_CUBIC
  2577. #ifdef USE_LOCAL_REFLECTIONMAP_CUBIC
  2578. return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);
  2579. #else
  2580. return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
  2581. #endif
  2582. #endif
  2583. #ifdef REFLECTIONMAP_PROJECTION
  2584. return computeProjectionCoords(worldPos,view,reflectionMatrix);
  2585. #endif
  2586. #ifdef REFLECTIONMAP_SKYBOX
  2587. return computeSkyBoxCoords(vPositionUVW,reflectionMatrix);
  2588. #endif
  2589. #ifdef REFLECTIONMAP_EXPLICIT
  2590. return vec3(0,0,0);
  2591. #endif
  2592. }
  2593. #endif`;ShaderStore.IncludesShadersStore[name$1U]=shader$1U;var name$1T="imageProcessingDeclaration",shader$1T=`#ifdef EXPOSURE
  2594. uniform float exposureLinear;
  2595. #endif
  2596. #ifdef CONTRAST
  2597. uniform float contrast;
  2598. #endif
  2599. #ifdef VIGNETTE
  2600. uniform vec2 vInverseScreenSize;
  2601. uniform vec4 vignetteSettings1;
  2602. uniform vec4 vignetteSettings2;
  2603. #endif
  2604. #ifdef COLORCURVES
  2605. uniform vec4 vCameraColorCurveNegative;
  2606. uniform vec4 vCameraColorCurveNeutral;
  2607. uniform vec4 vCameraColorCurvePositive;
  2608. #endif
  2609. #ifdef COLORGRADING
  2610. #ifdef COLORGRADING3D
  2611. uniform highp sampler3D txColorTransform;
  2612. #else
  2613. uniform sampler2D txColorTransform;
  2614. #endif
  2615. uniform vec4 colorTransformSettings;
  2616. #endif`;ShaderStore.IncludesShadersStore[name$1T]=shader$1T;var name$1S="imageProcessingFunctions",shader$1S=`#if defined(COLORGRADING) && !defined(COLORGRADING3D)
  2617. #define inline
  2618. vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)
  2619. {
  2620. float sliceSize=2.0*sampler3dSetting.x;
  2621. #ifdef SAMPLER3DGREENDEPTH
  2622. float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;
  2623. #else
  2624. float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;
  2625. #endif
  2626. float sliceInteger=floor(sliceContinuous);
  2627. float sliceFraction=sliceContinuous-sliceInteger;
  2628. #ifdef SAMPLER3DGREENDEPTH
  2629. vec2 sliceUV=color.rb;
  2630. #else
  2631. vec2 sliceUV=color.rg;
  2632. #endif
  2633. sliceUV.x*=sliceSize;
  2634. sliceUV.x+=sliceInteger*sliceSize;
  2635. sliceUV=saturate(sliceUV);
  2636. vec4 slice0Color=texture2D(colorTransform,sliceUV);
  2637. sliceUV.x+=sliceSize;
  2638. sliceUV=saturate(sliceUV);
  2639. vec4 slice1Color=texture2D(colorTransform,sliceUV);
  2640. vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);
  2641. #ifdef SAMPLER3DBGRMAP
  2642. color.rgb=result.rgb;
  2643. #else
  2644. color.rgb=result.bgr;
  2645. #endif
  2646. return color;
  2647. }
  2648. #endif
  2649. #ifdef TONEMAPPING_ACES
  2650. const mat3 ACESInputMat=mat3(
  2651. vec3(0.59719,0.07600,0.02840),
  2652. vec3(0.35458,0.90834,0.13383),
  2653. vec3(0.04823,0.01566,0.83777)
  2654. );
  2655. const mat3 ACESOutputMat=mat3(
  2656. vec3( 1.60475,-0.10208,-0.00327),
  2657. vec3(-0.53108,1.10813,-0.07276),
  2658. vec3(-0.07367,-0.00605,1.07602)
  2659. );
  2660. vec3 RRTAndODTFit(vec3 v)
  2661. {
  2662. vec3 a=v*(v+0.0245786)-0.000090537;
  2663. vec3 b=v*(0.983729*v+0.4329510)+0.238081;
  2664. return a/b;
  2665. }
  2666. vec3 ACESFitted(vec3 color)
  2667. {
  2668. color=ACESInputMat*color;
  2669. color=RRTAndODTFit(color);
  2670. color=ACESOutputMat*color;
  2671. color=saturate(color);
  2672. return color;
  2673. }
  2674. #endif
  2675. vec4 applyImageProcessing(vec4 result) {
  2676. #ifdef EXPOSURE
  2677. result.rgb*=exposureLinear;
  2678. #endif
  2679. #ifdef VIGNETTE
  2680. vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;
  2681. viewportXY=viewportXY*2.0-1.0;
  2682. vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);
  2683. float vignetteTerm=dot(vignetteXY1,vignetteXY1);
  2684. float vignette=pow(vignetteTerm,vignetteSettings2.w);
  2685. vec3 vignetteColor=vignetteSettings2.rgb;
  2686. #ifdef VIGNETTEBLENDMODEMULTIPLY
  2687. vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);
  2688. result.rgb*=vignetteColorMultiplier;
  2689. #endif
  2690. #ifdef VIGNETTEBLENDMODEOPAQUE
  2691. result.rgb=mix(vignetteColor,result.rgb,vignette);
  2692. #endif
  2693. #endif
  2694. #ifdef TONEMAPPING
  2695. #ifdef TONEMAPPING_ACES
  2696. result.rgb=ACESFitted(result.rgb);
  2697. #else
  2698. const float tonemappingCalibration=1.590579;
  2699. result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);
  2700. #endif
  2701. #endif
  2702. result.rgb=toGammaSpace(result.rgb);
  2703. result.rgb=saturate(result.rgb);
  2704. #ifdef CONTRAST
  2705. vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);
  2706. if (contrast<1.0) {
  2707. result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);
  2708. } else {
  2709. result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);
  2710. }
  2711. #endif
  2712. #ifdef COLORGRADING
  2713. vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;
  2714. #ifdef COLORGRADING3D
  2715. vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;
  2716. #else
  2717. vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;
  2718. #endif
  2719. result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);
  2720. #endif
  2721. #ifdef COLORCURVES
  2722. float luma=getLuminance(result.rgb);
  2723. vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));
  2724. vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;
  2725. result.rgb*=colorCurve.rgb;
  2726. result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);
  2727. #endif
  2728. return result;
  2729. }`;ShaderStore.IncludesShadersStore[name$1S]=shader$1S;var name$1R="bumpFragmentMainFunctions",shader$1R=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)
  2730. #if defined(TANGENT) && defined(NORMAL)
  2731. varying mat3 vTBN;
  2732. #endif
  2733. #ifdef OBJECTSPACE_NORMALMAP
  2734. uniform mat4 normalMatrix;
  2735. #endif
  2736. vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)
  2737. {
  2738. #ifdef NORMALXYSCALE
  2739. normal=normalize(normal*vec3(scale,scale,1.0));
  2740. #endif
  2741. return normalize(cotangentFrame*normal);
  2742. }
  2743. vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)
  2744. {
  2745. return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);
  2746. }
  2747. mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)
  2748. {
  2749. vec3 dp1=dFdx(p);
  2750. vec3 dp2=dFdy(p);
  2751. vec2 duv1=dFdx(uv);
  2752. vec2 duv2=dFdy(uv);
  2753. vec3 dp2perp=cross(dp2,normal);
  2754. vec3 dp1perp=cross(normal,dp1);
  2755. vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;
  2756. vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;
  2757. tangent*=tangentSpaceParams.x;
  2758. bitangent*=tangentSpaceParams.y;
  2759. float invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));
  2760. return mat3(tangent*invmax,bitangent*invmax,normal);
  2761. }
  2762. #endif
  2763. `;ShaderStore.IncludesShadersStore[name$1R]=shader$1R;var name$1Q="bumpFragmentFunctions",shader$1Q=`#if defined(BUMP)
  2764. #include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)
  2765. #endif
  2766. #if defined(DETAIL)
  2767. #include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
  2768. #endif
  2769. #if defined(BUMP) && defined(PARALLAX)
  2770. const float minSamples=4.;
  2771. const float maxSamples=15.;
  2772. const int iMaxSamples=15;
  2773. vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {
  2774. float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;
  2775. parallaxLimit*=parallaxScale;
  2776. vec2 vOffsetDir=normalize(vViewDirCoT.xy);
  2777. vec2 vMaxOffset=vOffsetDir*parallaxLimit;
  2778. float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));
  2779. float stepSize=1.0/numSamples;
  2780. float currRayHeight=1.0;
  2781. vec2 vCurrOffset=vec2(0,0);
  2782. vec2 vLastOffset=vec2(0,0);
  2783. float lastSampledHeight=1.0;
  2784. float currSampledHeight=1.0;
  2785. for (int i=0; i<iMaxSamples; i++)
  2786. {
  2787. currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;
  2788. if (currSampledHeight>currRayHeight)
  2789. {
  2790. float delta1=currSampledHeight-currRayHeight;
  2791. float delta2=(currRayHeight+stepSize)-lastSampledHeight;
  2792. float ratio=delta1/(delta1+delta2);
  2793. vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;
  2794. break;
  2795. }
  2796. else
  2797. {
  2798. currRayHeight-=stepSize;
  2799. vLastOffset=vCurrOffset;
  2800. vCurrOffset+=stepSize*vMaxOffset;
  2801. lastSampledHeight=currSampledHeight;
  2802. }
  2803. }
  2804. return vCurrOffset;
  2805. }
  2806. vec2 parallaxOffset(vec3 viewDir,float heightScale)
  2807. {
  2808. float height=texture2D(bumpSampler,vBumpUV).w;
  2809. vec2 texCoordOffset=heightScale*viewDir.xy*height;
  2810. return -texCoordOffset;
  2811. }
  2812. #endif
  2813. `;ShaderStore.IncludesShadersStore[name$1Q]=shader$1Q;var name$1P="logDepthDeclaration",shader$1P=`#ifdef LOGARITHMICDEPTH
  2814. uniform float logarithmicDepthConstant;
  2815. varying float vFragmentDepth;
  2816. #endif`;ShaderStore.IncludesShadersStore[name$1P]=shader$1P;var name$1O="fogFragmentDeclaration",shader$1O=`#ifdef FOG
  2817. #define FOGMODE_NONE 0.
  2818. #define FOGMODE_EXP 1.
  2819. #define FOGMODE_EXP2 2.
  2820. #define FOGMODE_LINEAR 3.
  2821. #define E 2.71828
  2822. uniform vec4 vFogInfos;
  2823. uniform vec3 vFogColor;
  2824. varying vec3 vFogDistance;
  2825. float CalcFogFactor()
  2826. {
  2827. float fogCoeff=1.0;
  2828. float fogStart=vFogInfos.y;
  2829. float fogEnd=vFogInfos.z;
  2830. float fogDensity=vFogInfos.w;
  2831. float fogDistance=length(vFogDistance);
  2832. if (FOGMODE_LINEAR == vFogInfos.x)
  2833. {
  2834. fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);
  2835. }
  2836. else if (FOGMODE_EXP == vFogInfos.x)
  2837. {
  2838. fogCoeff=1.0/pow(E,fogDistance*fogDensity);
  2839. }
  2840. else if (FOGMODE_EXP2 == vFogInfos.x)
  2841. {
  2842. fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);
  2843. }
  2844. return clamp(fogCoeff,0.0,1.0);
  2845. }
  2846. #endif`;ShaderStore.IncludesShadersStore[name$1O]=shader$1O;var name$1N="oitFragment",shader$1N=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
  2847. float fragDepth=gl_FragCoord.z;
  2848. #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS
  2849. uint halfFloat=packHalf2x16(vec2(fragDepth));
  2850. vec2 full=unpackHalf2x16(halfFloat);
  2851. fragDepth=full.x;
  2852. #endif
  2853. ivec2 fragCoord=ivec2(gl_FragCoord.xy);
  2854. vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;
  2855. vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);
  2856. depth.rg=vec2(-MAX_DEPTH);
  2857. frontColor=lastFrontColor;
  2858. backColor=vec4(0.0);
  2859. #ifdef USE_REVERSE_DEPTHBUFFER
  2860. float furthestDepth=-lastDepth.x;
  2861. float nearestDepth=lastDepth.y;
  2862. #else
  2863. float nearestDepth=-lastDepth.x;
  2864. float furthestDepth=lastDepth.y;
  2865. #endif
  2866. float alphaMultiplier=1.0-lastFrontColor.a;
  2867. #ifdef USE_REVERSE_DEPTHBUFFER
  2868. if (fragDepth>nearestDepth || fragDepth<furthestDepth) {
  2869. #else
  2870. if (fragDepth<nearestDepth || fragDepth>furthestDepth) {
  2871. #endif
  2872. return;
  2873. }
  2874. #ifdef USE_REVERSE_DEPTHBUFFER
  2875. if (fragDepth<nearestDepth && fragDepth>furthestDepth) {
  2876. #else
  2877. if (fragDepth>nearestDepth && fragDepth<furthestDepth) {
  2878. #endif
  2879. depth.rg=vec2(-fragDepth,fragDepth);
  2880. return;
  2881. }
  2882. #endif`;ShaderStore.IncludesShadersStore[name$1N]=shader$1N;var name$1M="bumpFragment",shader$1M=`vec2 uvOffset=vec2(0.0,0.0);
  2883. #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)
  2884. #ifdef NORMALXYSCALE
  2885. float normalScale=1.0;
  2886. #elif defined(BUMP)
  2887. float normalScale=vBumpInfos.y;
  2888. #else
  2889. float normalScale=1.0;
  2890. #endif
  2891. #if defined(TANGENT) && defined(NORMAL)
  2892. mat3 TBN=vTBN;
  2893. #elif defined(BUMP)
  2894. vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;
  2895. mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);
  2896. #else
  2897. vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;
  2898. mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));
  2899. #endif
  2900. #elif defined(ANISOTROPIC)
  2901. #if defined(TANGENT) && defined(NORMAL)
  2902. mat3 TBN=vTBN;
  2903. #else
  2904. vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;
  2905. mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));
  2906. #endif
  2907. #endif
  2908. #ifdef PARALLAX
  2909. mat3 invTBN=transposeMat3(TBN);
  2910. #ifdef PARALLAXOCCLUSION
  2911. uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);
  2912. #else
  2913. uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);
  2914. #endif
  2915. #endif
  2916. #ifdef DETAIL
  2917. vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);
  2918. vec2 detailNormalRG=detailColor.wy*2.0-1.0;
  2919. float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));
  2920. vec3 detailNormal=vec3(detailNormalRG,detailNormalB);
  2921. #endif
  2922. #ifdef BUMP
  2923. #ifdef OBJECTSPACE_NORMALMAP
  2924. normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);
  2925. normalW=normalize(mat3(normalMatrix)*normalW);
  2926. #elif !defined(DETAIL)
  2927. normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);
  2928. #else
  2929. vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;
  2930. #if DETAIL_NORMALBLENDMETHOD == 0
  2931. detailNormal.xy*=vDetailInfos.z;
  2932. vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));
  2933. #elif DETAIL_NORMALBLENDMETHOD == 1
  2934. detailNormal.xy*=vDetailInfos.z;
  2935. bumpNormal+=vec3(0.0,0.0,1.0);
  2936. detailNormal*=vec3(-1.0,-1.0,1.0);
  2937. vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;
  2938. #endif
  2939. normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);
  2940. #endif
  2941. #elif defined(DETAIL)
  2942. detailNormal.xy*=vDetailInfos.z;
  2943. normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);
  2944. #endif
  2945. `;ShaderStore.IncludesShadersStore[name$1M]=shader$1M;var name$1L="depthPrePass",shader$1L=`#ifdef DEPTHPREPASS
  2946. gl_FragColor=vec4(0.,0.,0.,1.0);
  2947. return;
  2948. #endif`;ShaderStore.IncludesShadersStore[name$1L]=shader$1L;var name$1K="lightFragment",shader$1K=`#ifdef LIGHT{X}
  2949. #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})
  2950. #else
  2951. #ifdef PBR
  2952. #ifdef SPOTLIGHT{X}
  2953. preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
  2954. #elif defined(POINTLIGHT{X})
  2955. preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
  2956. #elif defined(HEMILIGHT{X})
  2957. preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
  2958. #elif defined(DIRLIGHT{X})
  2959. preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
  2960. #endif
  2961. preInfo.NdotV=NdotV;
  2962. #ifdef SPOTLIGHT{X}
  2963. #ifdef LIGHT_FALLOFF_GLTF{X}
  2964. preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
  2965. preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
  2966. #elif defined(LIGHT_FALLOFF_PHYSICAL{X})
  2967. preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
  2968. preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);
  2969. #elif defined(LIGHT_FALLOFF_STANDARD{X})
  2970. preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
  2971. preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);
  2972. #else
  2973. preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
  2974. preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
  2975. #endif
  2976. #elif defined(POINTLIGHT{X})
  2977. #ifdef LIGHT_FALLOFF_GLTF{X}
  2978. preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
  2979. #elif defined(LIGHT_FALLOFF_PHYSICAL{X})
  2980. preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
  2981. #elif defined(LIGHT_FALLOFF_STANDARD{X})
  2982. preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
  2983. #else
  2984. preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
  2985. #endif
  2986. #else
  2987. preInfo.attenuation=1.0;
  2988. #endif
  2989. #ifdef HEMILIGHT{X}
  2990. preInfo.roughness=roughness;
  2991. #else
  2992. preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
  2993. #endif
  2994. #ifdef HEMILIGHT{X}
  2995. info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);
  2996. #elif defined(SS_TRANSLUCENCY)
  2997. info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);
  2998. #else
  2999. info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);
  3000. #endif
  3001. #ifdef SPECULARTERM
  3002. #ifdef ANISOTROPIC
  3003. info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
  3004. #else
  3005. info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
  3006. #endif
  3007. #endif
  3008. #ifdef SHEEN
  3009. #ifdef SHEEN_LINKWITHALBEDO
  3010. preInfo.roughness=sheenOut.sheenIntensity;
  3011. #else
  3012. #ifdef HEMILIGHT{X}
  3013. preInfo.roughness=sheenOut.sheenRoughness;
  3014. #else
  3015. preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
  3016. #endif
  3017. #endif
  3018. info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
  3019. #endif
  3020. #ifdef CLEARCOAT
  3021. #ifdef HEMILIGHT{X}
  3022. preInfo.roughness=clearcoatOut.clearCoatRoughness;
  3023. #else
  3024. preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
  3025. #endif
  3026. info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);
  3027. #ifdef CLEARCOAT_TINT
  3028. absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);
  3029. info.diffuse*=absorption;
  3030. #ifdef SPECULARTERM
  3031. info.specular*=absorption;
  3032. #endif
  3033. #endif
  3034. info.diffuse*=info.clearCoat.w;
  3035. #ifdef SPECULARTERM
  3036. info.specular*=info.clearCoat.w;
  3037. #endif
  3038. #ifdef SHEEN
  3039. info.sheen*=info.clearCoat.w;
  3040. #endif
  3041. #endif
  3042. #else
  3043. #ifdef SPOTLIGHT{X}
  3044. info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);
  3045. #elif defined(HEMILIGHT{X})
  3046. info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);
  3047. #elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})
  3048. info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);
  3049. #endif
  3050. #endif
  3051. #ifdef PROJECTEDLIGHTTEXTURE{X}
  3052. info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});
  3053. #endif
  3054. #endif
  3055. #ifdef SHADOW{X}
  3056. #ifdef SHADOWCSM{X}
  3057. for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++)
  3058. {
  3059. #ifdef SHADOWCSM_RIGHTHANDED{X}
  3060. diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;
  3061. #else
  3062. diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;
  3063. #endif
  3064. if (diff{X}>=0.) {
  3065. index{X}=i;
  3066. break;
  3067. }
  3068. }
  3069. #ifdef SHADOWCSMUSESHADOWMAXZ{X}
  3070. if (index{X}>=0)
  3071. #endif
  3072. {
  3073. #if defined(SHADOWPCF{X})
  3074. #if defined(SHADOWLOWQUALITY{X})
  3075. shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3076. #elif defined(SHADOWMEDIUMQUALITY{X})
  3077. shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3078. #else
  3079. shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3080. #endif
  3081. #elif defined(SHADOWPCSS{X})
  3082. #if defined(SHADOWLOWQUALITY{X})
  3083. shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
  3084. #elif defined(SHADOWMEDIUMQUALITY{X})
  3085. shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
  3086. #else
  3087. shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
  3088. #endif
  3089. #else
  3090. shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3091. #endif
  3092. #ifdef SHADOWCSMDEBUG{X}
  3093. shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];
  3094. #endif
  3095. #ifndef SHADOWCSMNOBLEND{X}
  3096. float frustumLength=frustumLengths{X}[index{X}];
  3097. float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};
  3098. if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)
  3099. {
  3100. index{X}+=1;
  3101. float nextShadow=0.;
  3102. #if defined(SHADOWPCF{X})
  3103. #if defined(SHADOWLOWQUALITY{X})
  3104. nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3105. #elif defined(SHADOWMEDIUMQUALITY{X})
  3106. nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3107. #else
  3108. nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3109. #endif
  3110. #elif defined(SHADOWPCSS{X})
  3111. #if defined(SHADOWLOWQUALITY{X})
  3112. nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
  3113. #elif defined(SHADOWMEDIUMQUALITY{X})
  3114. nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
  3115. #else
  3116. nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
  3117. #endif
  3118. #else
  3119. nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3120. #endif
  3121. shadow=mix(nextShadow,shadow,diffRatio);
  3122. #ifdef SHADOWCSMDEBUG{X}
  3123. shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);
  3124. #endif
  3125. }
  3126. #endif
  3127. }
  3128. #elif defined(SHADOWCLOSEESM{X})
  3129. #if defined(SHADOWCUBE{X})
  3130. shadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
  3131. #else
  3132. shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
  3133. #endif
  3134. #elif defined(SHADOWESM{X})
  3135. #if defined(SHADOWCUBE{X})
  3136. shadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
  3137. #else
  3138. shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
  3139. #endif
  3140. #elif defined(SHADOWPOISSON{X})
  3141. #if defined(SHADOWCUBE{X})
  3142. shadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);
  3143. #else
  3144. shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3145. #endif
  3146. #elif defined(SHADOWPCF{X})
  3147. #if defined(SHADOWLOWQUALITY{X})
  3148. shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3149. #elif defined(SHADOWMEDIUMQUALITY{X})
  3150. shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3151. #else
  3152. shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3153. #endif
  3154. #elif defined(SHADOWPCSS{X})
  3155. #if defined(SHADOWLOWQUALITY{X})
  3156. shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3157. #elif defined(SHADOWMEDIUMQUALITY{X})
  3158. shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3159. #else
  3160. shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3161. #endif
  3162. #else
  3163. #if defined(SHADOWCUBE{X})
  3164. shadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);
  3165. #else
  3166. shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
  3167. #endif
  3168. #endif
  3169. #ifdef SHADOWONLY
  3170. #ifndef SHADOWINUSE
  3171. #define SHADOWINUSE
  3172. #endif
  3173. globalShadow+=shadow;
  3174. shadowLightCount+=1.0;
  3175. #endif
  3176. #else
  3177. shadow=1.;
  3178. #endif
  3179. #ifndef SHADOWONLY
  3180. #ifdef CUSTOMUSERLIGHTING
  3181. diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);
  3182. #ifdef SPECULARTERM
  3183. specularBase+=computeCustomSpecularLighting(info,specularBase,shadow);
  3184. #endif
  3185. #elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})
  3186. diffuseBase+=lightmapColor.rgb*shadow;
  3187. #ifdef SPECULARTERM
  3188. #ifndef LIGHTMAPNOSPECULAR{X}
  3189. specularBase+=info.specular*shadow*lightmapColor.rgb;
  3190. #endif
  3191. #endif
  3192. #ifdef CLEARCOAT
  3193. #ifndef LIGHTMAPNOSPECULAR{X}
  3194. clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;
  3195. #endif
  3196. #endif
  3197. #ifdef SHEEN
  3198. #ifndef LIGHTMAPNOSPECULAR{X}
  3199. sheenBase+=info.sheen.rgb*shadow;
  3200. #endif
  3201. #endif
  3202. #else
  3203. #ifdef SHADOWCSMDEBUG{X}
  3204. diffuseBase+=info.diffuse*shadowDebug{X};
  3205. #else
  3206. diffuseBase+=info.diffuse*shadow;
  3207. #endif
  3208. #ifdef SPECULARTERM
  3209. specularBase+=info.specular*shadow;
  3210. #endif
  3211. #ifdef CLEARCOAT
  3212. clearCoatBase+=info.clearCoat.rgb*shadow;
  3213. #endif
  3214. #ifdef SHEEN
  3215. sheenBase+=info.sheen.rgb*shadow;
  3216. #endif
  3217. #endif
  3218. #endif
  3219. #endif`;ShaderStore.IncludesShadersStore[name$1K]=shader$1K;var name$1J="logDepthFragment",shader$1J=`#ifdef LOGARITHMICDEPTH
  3220. gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;
  3221. #endif`;ShaderStore.IncludesShadersStore[name$1J]=shader$1J;var name$1I="fogFragment",shader$1I=`#ifdef FOG
  3222. float fog=CalcFogFactor();
  3223. #ifdef PBR
  3224. fog=toLinearSpace(fog);
  3225. #endif
  3226. color.rgb=mix(vFogColor,color.rgb,fog);
  3227. #endif`;ShaderStore.IncludesShadersStore[name$1I]=shader$1I;var name$1H="defaultPixelShader",shader$1H=`#include<__decl__defaultFragment>
  3228. #if defined(BUMP) || !defined(NORMAL)
  3229. #extension GL_OES_standard_derivatives : enable
  3230. #endif
  3231. #include<prePassDeclaration>[SCENE_MRT_COUNT]
  3232. #include<oitDeclaration>
  3233. #define CUSTOM_FRAGMENT_BEGIN
  3234. #ifdef LOGARITHMICDEPTH
  3235. #extension GL_EXT_frag_depth : enable
  3236. #endif
  3237. #define RECIPROCAL_PI2 0.15915494
  3238. varying vec3 vPositionW;
  3239. #ifdef NORMAL
  3240. varying vec3 vNormalW;
  3241. #endif
  3242. #ifdef VERTEXCOLOR
  3243. varying vec4 vColor;
  3244. #endif
  3245. #include<mainUVVaryingDeclaration>[1..7]
  3246. #include<helperFunctions>
  3247. #include<__decl__lightFragment>[0..maxSimultaneousLights]
  3248. #include<lightsFragmentFunctions>
  3249. #include<shadowsFragmentFunctions>
  3250. #include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)
  3251. #include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
  3252. #include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
  3253. #include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
  3254. #include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
  3255. #ifdef REFRACTION
  3256. #ifdef REFRACTIONMAP_3D
  3257. uniform samplerCube refractionCubeSampler;
  3258. #else
  3259. uniform sampler2D refraction2DSampler;
  3260. #endif
  3261. #endif
  3262. #if defined(SPECULARTERM)
  3263. #include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)
  3264. #endif
  3265. #include<fresnelFunction>
  3266. #ifdef REFLECTION
  3267. #ifdef REFLECTIONMAP_3D
  3268. uniform samplerCube reflectionCubeSampler;
  3269. #else
  3270. uniform sampler2D reflection2DSampler;
  3271. #endif
  3272. #ifdef REFLECTIONMAP_SKYBOX
  3273. varying vec3 vPositionUVW;
  3274. #else
  3275. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  3276. varying vec3 vDirectionW;
  3277. #endif
  3278. #endif
  3279. #include<reflectionFunction>
  3280. #endif
  3281. #include<imageProcessingDeclaration>
  3282. #include<imageProcessingFunctions>
  3283. #include<bumpFragmentMainFunctions>
  3284. #include<bumpFragmentFunctions>
  3285. #include<clipPlaneFragmentDeclaration>
  3286. #include<logDepthDeclaration>
  3287. #include<fogFragmentDeclaration>
  3288. #define CUSTOM_FRAGMENT_DEFINITIONS
  3289. void main(void) {
  3290. #define CUSTOM_FRAGMENT_MAIN_BEGIN
  3291. #include<oitFragment>
  3292. #include<clipPlaneFragment>
  3293. vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
  3294. vec4 baseColor=vec4(1.,1.,1.,1.);
  3295. vec3 diffuseColor=vDiffuseColor.rgb;
  3296. float alpha=vDiffuseColor.a;
  3297. #ifdef NORMAL
  3298. vec3 normalW=normalize(vNormalW);
  3299. #else
  3300. vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));
  3301. #endif
  3302. #include<bumpFragment>
  3303. #ifdef TWOSIDEDLIGHTING
  3304. normalW=gl_FrontFacing ? normalW : -normalW;
  3305. #endif
  3306. #ifdef DIFFUSE
  3307. baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);
  3308. #if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)
  3309. if (baseColor.a<alphaCutOff)
  3310. discard;
  3311. #endif
  3312. #ifdef ALPHAFROMDIFFUSE
  3313. alpha*=baseColor.a;
  3314. #endif
  3315. #define CUSTOM_FRAGMENT_UPDATE_ALPHA
  3316. baseColor.rgb*=vDiffuseInfos.y;
  3317. #endif
  3318. #include<depthPrePass>
  3319. #ifdef VERTEXCOLOR
  3320. baseColor.rgb*=vColor.rgb;
  3321. #endif
  3322. #ifdef DETAIL
  3323. baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);
  3324. #endif
  3325. #define CUSTOM_FRAGMENT_UPDATE_DIFFUSE
  3326. vec3 baseAmbientColor=vec3(1.,1.,1.);
  3327. #ifdef AMBIENT
  3328. baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;
  3329. #endif
  3330. #define CUSTOM_FRAGMENT_BEFORE_LIGHTS
  3331. #ifdef SPECULARTERM
  3332. float glossiness=vSpecularColor.a;
  3333. vec3 specularColor=vSpecularColor.rgb;
  3334. #ifdef SPECULAR
  3335. vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);
  3336. specularColor=specularMapColor.rgb;
  3337. #ifdef GLOSSINESS
  3338. glossiness=glossiness*specularMapColor.a;
  3339. #endif
  3340. #endif
  3341. #else
  3342. float glossiness=0.;
  3343. #endif
  3344. vec3 diffuseBase=vec3(0.,0.,0.);
  3345. lightingInfo info;
  3346. #ifdef SPECULARTERM
  3347. vec3 specularBase=vec3(0.,0.,0.);
  3348. #endif
  3349. float shadow=1.;
  3350. #ifdef LIGHTMAP
  3351. vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
  3352. #ifdef RGBDLIGHTMAP
  3353. lightmapColor.rgb=fromRGBD(lightmapColor);
  3354. #endif
  3355. lightmapColor.rgb*=vLightmapInfos.y;
  3356. #endif
  3357. #include<lightFragment>[0..maxSimultaneousLights]
  3358. vec4 refractionColor=vec4(0.,0.,0.,1.);
  3359. #ifdef REFRACTION
  3360. vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));
  3361. #ifdef REFRACTIONMAP_3D
  3362. #ifdef USE_LOCAL_REFRACTIONMAP_CUBIC
  3363. refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);
  3364. #endif
  3365. refractionVector.y=refractionVector.y*vRefractionInfos.w;
  3366. if (dot(refractionVector,viewDirectionW)<1.0) {
  3367. refractionColor=textureCube(refractionCubeSampler,refractionVector);
  3368. }
  3369. #else
  3370. vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));
  3371. vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;
  3372. refractionCoords.y=1.0-refractionCoords.y;
  3373. refractionColor=texture2D(refraction2DSampler,refractionCoords);
  3374. #endif
  3375. #ifdef RGBDREFRACTION
  3376. refractionColor.rgb=fromRGBD(refractionColor);
  3377. #endif
  3378. #ifdef IS_REFRACTION_LINEAR
  3379. refractionColor.rgb=toGammaSpace(refractionColor.rgb);
  3380. #endif
  3381. refractionColor.rgb*=vRefractionInfos.x;
  3382. #endif
  3383. vec4 reflectionColor=vec4(0.,0.,0.,1.);
  3384. #ifdef REFLECTION
  3385. vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
  3386. #ifdef REFLECTIONMAP_OPPOSITEZ
  3387. vReflectionUVW.z*=-1.0;
  3388. #endif
  3389. #ifdef REFLECTIONMAP_3D
  3390. #ifdef ROUGHNESS
  3391. float bias=vReflectionInfos.y;
  3392. #ifdef SPECULARTERM
  3393. #ifdef SPECULAR
  3394. #ifdef GLOSSINESS
  3395. bias*=(1.0-specularMapColor.a);
  3396. #endif
  3397. #endif
  3398. #endif
  3399. reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);
  3400. #else
  3401. reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);
  3402. #endif
  3403. #else
  3404. vec2 coords=vReflectionUVW.xy;
  3405. #ifdef REFLECTIONMAP_PROJECTION
  3406. coords/=vReflectionUVW.z;
  3407. #endif
  3408. coords.y=1.0-coords.y;
  3409. reflectionColor=texture2D(reflection2DSampler,coords);
  3410. #endif
  3411. #ifdef RGBDREFLECTION
  3412. reflectionColor.rgb=fromRGBD(reflectionColor);
  3413. #endif
  3414. #ifdef IS_REFLECTION_LINEAR
  3415. reflectionColor.rgb=toGammaSpace(reflectionColor.rgb);
  3416. #endif
  3417. reflectionColor.rgb*=vReflectionInfos.x;
  3418. #ifdef REFLECTIONFRESNEL
  3419. float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);
  3420. #ifdef REFLECTIONFRESNELFROMSPECULAR
  3421. #ifdef SPECULARTERM
  3422. reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
  3423. #else
  3424. reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
  3425. #endif
  3426. #else
  3427. reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
  3428. #endif
  3429. #endif
  3430. #endif
  3431. #ifdef REFRACTIONFRESNEL
  3432. float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);
  3433. refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;
  3434. #endif
  3435. #ifdef OPACITY
  3436. vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
  3437. #ifdef OPACITYRGB
  3438. opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);
  3439. alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;
  3440. #else
  3441. alpha*=opacityMap.a*vOpacityInfos.y;
  3442. #endif
  3443. #endif
  3444. #ifdef VERTEXALPHA
  3445. alpha*=vColor.a;
  3446. #endif
  3447. #ifdef OPACITYFRESNEL
  3448. float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);
  3449. alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;
  3450. #endif
  3451. #ifdef ALPHATEST
  3452. #ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS
  3453. if (alpha<alphaCutOff)
  3454. discard;
  3455. #endif
  3456. #ifndef ALPHABLEND
  3457. alpha=1.0;
  3458. #endif
  3459. #endif
  3460. vec3 emissiveColor=vEmissiveColor;
  3461. #ifdef EMISSIVE
  3462. emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;
  3463. #endif
  3464. #ifdef EMISSIVEFRESNEL
  3465. float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);
  3466. emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;
  3467. #endif
  3468. #ifdef DIFFUSEFRESNEL
  3469. float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);
  3470. diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;
  3471. #endif
  3472. #ifdef EMISSIVEASILLUMINATION
  3473. vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
  3474. #else
  3475. #ifdef LINKEMISSIVEWITHDIFFUSE
  3476. vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
  3477. #else
  3478. vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
  3479. #endif
  3480. #endif
  3481. #ifdef SPECULARTERM
  3482. vec3 finalSpecular=specularBase*specularColor;
  3483. #ifdef SPECULAROVERALPHA
  3484. alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);
  3485. #endif
  3486. #else
  3487. vec3 finalSpecular=vec3(0.0);
  3488. #endif
  3489. #ifdef REFLECTIONOVERALPHA
  3490. alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.);
  3491. #endif
  3492. #ifdef EMISSIVEASILLUMINATION
  3493. vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);
  3494. #else
  3495. vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);
  3496. #endif
  3497. #ifdef LIGHTMAP
  3498. #ifndef LIGHTMAPEXCLUDED
  3499. #ifdef USELIGHTMAPASSHADOWMAP
  3500. color.rgb*=lightmapColor.rgb;
  3501. #else
  3502. color.rgb+=lightmapColor.rgb;
  3503. #endif
  3504. #endif
  3505. #endif
  3506. #define CUSTOM_FRAGMENT_BEFORE_FOG
  3507. color.rgb=max(color.rgb,0.);
  3508. #include<logDepthFragment>
  3509. #include<fogFragment>
  3510. #ifdef IMAGEPROCESSINGPOSTPROCESS
  3511. color.rgb=toLinearSpace(color.rgb);
  3512. #else
  3513. #ifdef IMAGEPROCESSING
  3514. color.rgb=toLinearSpace(color.rgb);
  3515. color=applyImageProcessing(color);
  3516. #endif
  3517. #endif
  3518. color.a*=visibility;
  3519. #ifdef PREMULTIPLYALPHA
  3520. color.rgb*=color.a;
  3521. #endif
  3522. #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
  3523. #ifdef PREPASS
  3524. float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;
  3525. gl_FragData[0]=color;
  3526. #ifdef PREPASS_POSITION
  3527. gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
  3528. #endif
  3529. #ifdef PREPASS_VELOCITY
  3530. vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;
  3531. vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;
  3532. vec2 velocity=abs(a-b);
  3533. velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;
  3534. gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
  3535. #endif
  3536. #ifdef PREPASS_IRRADIANCE
  3537. gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
  3538. #endif
  3539. #ifdef PREPASS_DEPTH
  3540. gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo);
  3541. #endif
  3542. #ifdef PREPASS_NORMAL
  3543. gl_FragData[PREPASS_NORMAL_INDEX]=vec4((view*vec4(normalW,0.0)).rgb,writeGeometryInfo);
  3544. #endif
  3545. #ifdef PREPASS_ALBEDO_SQRT
  3546. gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
  3547. #endif
  3548. #ifdef PREPASS_REFLECTIVITY
  3549. #if defined(SPECULAR)
  3550. gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularMapColor.rgb,specularMapColor.a*writeGeometryInfo);
  3551. #else
  3552. gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
  3553. #endif
  3554. #endif
  3555. #endif
  3556. #if !defined(PREPASS) || defined(WEBGL2)
  3557. gl_FragColor=color;
  3558. #endif
  3559. #if ORDER_INDEPENDENT_TRANSPARENCY
  3560. if (fragDepth == nearestDepth) {
  3561. frontColor.rgb+=color.rgb*color.a*alphaMultiplier;
  3562. frontColor.a=1.0-alphaMultiplier*(1.0-color.a);
  3563. } else {
  3564. backColor+=color;
  3565. }
  3566. #endif
  3567. }
  3568. `;ShaderStore.ShadersStore[name$1H]=shader$1H;var name$1G="defaultVertexDeclaration",shader$1G=`
  3569. uniform mat4 viewProjection;
  3570. uniform mat4 view;
  3571. #ifdef DIFFUSE
  3572. uniform mat4 diffuseMatrix;
  3573. uniform vec2 vDiffuseInfos;
  3574. #endif
  3575. #ifdef AMBIENT
  3576. uniform mat4 ambientMatrix;
  3577. uniform vec2 vAmbientInfos;
  3578. #endif
  3579. #ifdef OPACITY
  3580. uniform mat4 opacityMatrix;
  3581. uniform vec2 vOpacityInfos;
  3582. #endif
  3583. #ifdef EMISSIVE
  3584. uniform vec2 vEmissiveInfos;
  3585. uniform mat4 emissiveMatrix;
  3586. #endif
  3587. #ifdef LIGHTMAP
  3588. uniform vec2 vLightmapInfos;
  3589. uniform mat4 lightmapMatrix;
  3590. #endif
  3591. #if defined(SPECULAR) && defined(SPECULARTERM)
  3592. uniform vec2 vSpecularInfos;
  3593. uniform mat4 specularMatrix;
  3594. #endif
  3595. #ifdef BUMP
  3596. uniform vec3 vBumpInfos;
  3597. uniform mat4 bumpMatrix;
  3598. #endif
  3599. #ifdef REFLECTION
  3600. uniform mat4 reflectionMatrix;
  3601. #endif
  3602. #ifdef POINTSIZE
  3603. uniform float pointSize;
  3604. #endif
  3605. #ifdef DETAIL
  3606. uniform vec4 vDetailInfos;
  3607. uniform mat4 detailMatrix;
  3608. #endif`;ShaderStore.IncludesShadersStore[name$1G]=shader$1G;var name$1F="uvAttributeDeclaration",shader$1F=`#ifdef UV{X}
  3609. attribute vec2 uv{X};
  3610. #endif
  3611. `;ShaderStore.IncludesShadersStore[name$1F]=shader$1F;var name$1E="instancesDeclaration",shader$1E=`#ifdef INSTANCES
  3612. attribute vec4 world0;
  3613. attribute vec4 world1;
  3614. attribute vec4 world2;
  3615. attribute vec4 world3;
  3616. #if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
  3617. uniform mat4 world;
  3618. #endif
  3619. #if defined(VELOCITY) || defined(PREPASS_VELOCITY)
  3620. attribute vec4 previousWorld0;
  3621. attribute vec4 previousWorld1;
  3622. attribute vec4 previousWorld2;
  3623. attribute vec4 previousWorld3;
  3624. #ifdef THIN_INSTANCES
  3625. uniform mat4 previousWorld;
  3626. #endif
  3627. #endif
  3628. #else
  3629. #if !defined(WORLD_UBO)
  3630. uniform mat4 world;
  3631. #endif
  3632. #if defined(VELOCITY) || defined(PREPASS_VELOCITY)
  3633. uniform mat4 previousWorld;
  3634. #endif
  3635. #endif`;ShaderStore.IncludesShadersStore[name$1E]=shader$1E;var name$1D="prePassVertexDeclaration",shader$1D=`#ifdef PREPASS
  3636. #ifdef PREPASS_DEPTH
  3637. varying vec3 vViewPos;
  3638. #endif
  3639. #ifdef PREPASS_VELOCITY
  3640. uniform mat4 previousViewProjection;
  3641. varying vec4 vCurrentPosition;
  3642. varying vec4 vPreviousPosition;
  3643. #endif
  3644. #endif`;ShaderStore.IncludesShadersStore[name$1D]=shader$1D;var name$1C="samplerVertexDeclaration",shader$1C=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV == 0
  3645. varying vec2 v_VARYINGNAME_UV;
  3646. #endif
  3647. `;ShaderStore.IncludesShadersStore[name$1C]=shader$1C;var name$1B="bumpVertexDeclaration",shader$1B=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
  3648. #if defined(TANGENT) && defined(NORMAL)
  3649. varying mat3 vTBN;
  3650. #endif
  3651. #endif
  3652. `;ShaderStore.IncludesShadersStore[name$1B]=shader$1B;var name$1A="fogVertexDeclaration",shader$1A=`#ifdef FOG
  3653. varying vec3 vFogDistance;
  3654. #endif`;ShaderStore.IncludesShadersStore[name$1A]=shader$1A;var name$1z="lightVxFragmentDeclaration",shader$1z=`#ifdef LIGHT{X}
  3655. uniform vec4 vLightData{X};
  3656. uniform vec4 vLightDiffuse{X};
  3657. #ifdef SPECULARTERM
  3658. uniform vec4 vLightSpecular{X};
  3659. #else
  3660. vec4 vLightSpecular{X}=vec4(0.);
  3661. #endif
  3662. #ifdef SHADOW{X}
  3663. #ifdef SHADOWCSM{X}
  3664. uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
  3665. varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
  3666. varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
  3667. varying vec4 vPositionFromCamera{X};
  3668. #elif defined(SHADOWCUBE{X})
  3669. #else
  3670. varying vec4 vPositionFromLight{X};
  3671. varying float vDepthMetric{X};
  3672. uniform mat4 lightMatrix{X};
  3673. #endif
  3674. uniform vec4 shadowsInfo{X};
  3675. uniform vec2 depthValues{X};
  3676. #endif
  3677. #ifdef SPOTLIGHT{X}
  3678. uniform vec4 vLightDirection{X};
  3679. uniform vec4 vLightFalloff{X};
  3680. #elif defined(POINTLIGHT{X})
  3681. uniform vec4 vLightFalloff{X};
  3682. #elif defined(HEMILIGHT{X})
  3683. uniform vec3 vLightGround{X};
  3684. #endif
  3685. #endif`;ShaderStore.IncludesShadersStore[name$1z]=shader$1z;var name$1y="lightVxUboDeclaration",shader$1y=`#ifdef LIGHT{X}
  3686. uniform Light{X}
  3687. {
  3688. vec4 vLightData;
  3689. vec4 vLightDiffuse;
  3690. vec4 vLightSpecular;
  3691. #ifdef SPOTLIGHT{X}
  3692. vec4 vLightDirection;
  3693. vec4 vLightFalloff;
  3694. #elif defined(POINTLIGHT{X})
  3695. vec4 vLightFalloff;
  3696. #elif defined(HEMILIGHT{X})
  3697. vec3 vLightGround;
  3698. #endif
  3699. vec4 shadowsInfo;
  3700. vec2 depthValues;
  3701. } light{X};
  3702. #ifdef SHADOW{X}
  3703. #ifdef SHADOWCSM{X}
  3704. uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
  3705. varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
  3706. varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
  3707. varying vec4 vPositionFromCamera{X};
  3708. #elif defined(SHADOWCUBE{X})
  3709. #else
  3710. varying vec4 vPositionFromLight{X};
  3711. varying float vDepthMetric{X};
  3712. uniform mat4 lightMatrix{X};
  3713. #endif
  3714. #endif
  3715. #endif`;ShaderStore.IncludesShadersStore[name$1y]=shader$1y;var name$1x="prePassVertex",shader$1x=`#ifdef PREPASS_DEPTH
  3716. vViewPos=(view*worldPos).rgb;
  3717. #endif
  3718. #if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)
  3719. vCurrentPosition=viewProjection*worldPos;
  3720. #if NUM_BONE_INFLUENCERS>0
  3721. mat4 previousInfluence;
  3722. previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
  3723. #if NUM_BONE_INFLUENCERS>1
  3724. previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
  3725. #endif
  3726. #if NUM_BONE_INFLUENCERS>2
  3727. previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
  3728. #endif
  3729. #if NUM_BONE_INFLUENCERS>3
  3730. previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
  3731. #endif
  3732. #if NUM_BONE_INFLUENCERS>4
  3733. previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
  3734. #endif
  3735. #if NUM_BONE_INFLUENCERS>5
  3736. previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
  3737. #endif
  3738. #if NUM_BONE_INFLUENCERS>6
  3739. previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
  3740. #endif
  3741. #if NUM_BONE_INFLUENCERS>7
  3742. previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
  3743. #endif
  3744. vPreviousPosition=previousViewProjection*previousWorld*previousInfluence*vec4(positionUpdated,1.0);
  3745. #else
  3746. vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0);
  3747. #endif
  3748. #endif`;ShaderStore.IncludesShadersStore[name$1x]=shader$1x;var name$1w="uvVariableDeclaration",shader$1w=`#if !defined(UV{X}) && defined(MAINUV{X})
  3749. vec2 uv{X}=vec2(0.,0.);
  3750. #endif
  3751. #ifdef MAINUV{X}
  3752. vMainUV{X}=uv{X};
  3753. #endif
  3754. `;ShaderStore.IncludesShadersStore[name$1w]=shader$1w;var name$1v="samplerVertexImplementation",shader$1v=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV == 0
  3755. if (v_INFONAME_ == 0.)
  3756. {
  3757. v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));
  3758. }
  3759. #ifdef UV2
  3760. else if (v_INFONAME_ == 1.)
  3761. {
  3762. v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));
  3763. }
  3764. #endif
  3765. #ifdef UV3
  3766. else if (v_INFONAME_ == 2.)
  3767. {
  3768. v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));
  3769. }
  3770. #endif
  3771. #ifdef UV4
  3772. else if (v_INFONAME_ == 3.)
  3773. {
  3774. v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));
  3775. }
  3776. #endif
  3777. #ifdef UV5
  3778. else if (v_INFONAME_ == 4.)
  3779. {
  3780. v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));
  3781. }
  3782. #endif
  3783. #ifdef UV6
  3784. else if (v_INFONAME_ == 5.)
  3785. {
  3786. v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));
  3787. }
  3788. #endif
  3789. #endif
  3790. `;ShaderStore.IncludesShadersStore[name$1v]=shader$1v;var name$1u="bumpVertex",shader$1u=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
  3791. #if defined(TANGENT) && defined(NORMAL)
  3792. vec3 tbnNormal=normalize(normalUpdated);
  3793. vec3 tbnTangent=normalize(tangentUpdated.xyz);
  3794. vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;
  3795. vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);
  3796. #endif
  3797. #endif`;ShaderStore.IncludesShadersStore[name$1u]=shader$1u;var name$1t="fogVertex",shader$1t=`#ifdef FOG
  3798. vFogDistance=(view*worldPos).xyz;
  3799. #endif`;ShaderStore.IncludesShadersStore[name$1t]=shader$1t;var name$1s="shadowsVertex",shader$1s=`#ifdef SHADOWS
  3800. #if defined(SHADOWCSM{X})
  3801. vPositionFromCamera{X}=view*worldPos;
  3802. for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {
  3803. vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;
  3804. #ifdef USE_REVERSE_DEPTHBUFFER
  3805. vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
  3806. #else
  3807. vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
  3808. #endif
  3809. }
  3810. #elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})
  3811. vPositionFromLight{X}=lightMatrix{X}*worldPos;
  3812. #ifdef USE_REVERSE_DEPTHBUFFER
  3813. vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
  3814. #else
  3815. vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
  3816. #endif
  3817. #endif
  3818. #endif`;ShaderStore.IncludesShadersStore[name$1s]=shader$1s;var name$1r="pointCloudVertex",shader$1r=`#ifdef POINTSIZE
  3819. gl_PointSize=pointSize;
  3820. #endif`;ShaderStore.IncludesShadersStore[name$1r]=shader$1r;var name$1q="logDepthVertex",shader$1q=`#ifdef LOGARITHMICDEPTH
  3821. vFragmentDepth=1.0+gl_Position.w;
  3822. gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;
  3823. #endif`;ShaderStore.IncludesShadersStore[name$1q]=shader$1q;var name$1p="defaultVertexShader",shader$1p=`#include<__decl__defaultVertex>
  3824. #define CUSTOM_VERTEX_BEGIN
  3825. attribute vec3 position;
  3826. #ifdef NORMAL
  3827. attribute vec3 normal;
  3828. #endif
  3829. #ifdef TANGENT
  3830. attribute vec4 tangent;
  3831. #endif
  3832. #ifdef UV1
  3833. attribute vec2 uv;
  3834. #endif
  3835. #include<uvAttributeDeclaration>[2..7]
  3836. #ifdef VERTEXCOLOR
  3837. attribute vec4 color;
  3838. #endif
  3839. #include<helperFunctions>
  3840. #include<bonesDeclaration>
  3841. #include<bakedVertexAnimationDeclaration>
  3842. #include<instancesDeclaration>
  3843. #include<prePassVertexDeclaration>
  3844. #include<mainUVVaryingDeclaration>[1..7]
  3845. #include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
  3846. #include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
  3847. #include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
  3848. #include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
  3849. #include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
  3850. #include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
  3851. #if defined(SPECULARTERM)
  3852. #include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
  3853. #endif
  3854. #include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
  3855. varying vec3 vPositionW;
  3856. #ifdef NORMAL
  3857. varying vec3 vNormalW;
  3858. #endif
  3859. #ifdef VERTEXCOLOR
  3860. varying vec4 vColor;
  3861. #endif
  3862. #include<bumpVertexDeclaration>
  3863. #include<clipPlaneVertexDeclaration>
  3864. #include<fogVertexDeclaration>
  3865. #include<__decl__lightVxFragment>[0..maxSimultaneousLights]
  3866. #include<morphTargetsVertexGlobalDeclaration>
  3867. #include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
  3868. #ifdef REFLECTIONMAP_SKYBOX
  3869. varying vec3 vPositionUVW;
  3870. #endif
  3871. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  3872. varying vec3 vDirectionW;
  3873. #endif
  3874. #include<logDepthDeclaration>
  3875. #define CUSTOM_VERTEX_DEFINITIONS
  3876. void main(void) {
  3877. #define CUSTOM_VERTEX_MAIN_BEGIN
  3878. vec3 positionUpdated=position;
  3879. #ifdef NORMAL
  3880. vec3 normalUpdated=normal;
  3881. #endif
  3882. #ifdef TANGENT
  3883. vec4 tangentUpdated=tangent;
  3884. #endif
  3885. #ifdef UV1
  3886. vec2 uvUpdated=uv;
  3887. #endif
  3888. #include<morphTargetsVertexGlobal>
  3889. #include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
  3890. #ifdef REFLECTIONMAP_SKYBOX
  3891. vPositionUVW=positionUpdated;
  3892. #endif
  3893. #define CUSTOM_VERTEX_UPDATE_POSITION
  3894. #define CUSTOM_VERTEX_UPDATE_NORMAL
  3895. #include<instancesVertex>
  3896. #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)
  3897. vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
  3898. vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
  3899. #endif
  3900. #include<bonesVertex>
  3901. #include<bakedVertexAnimation>
  3902. vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
  3903. #ifdef NORMAL
  3904. mat3 normalWorld=mat3(finalWorld);
  3905. #if defined(INSTANCES) && defined(THIN_INSTANCES)
  3906. vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));
  3907. vNormalW=normalize(normalWorld*vNormalW);
  3908. #else
  3909. #ifdef NONUNIFORMSCALING
  3910. normalWorld=transposeMat3(inverseMat3(normalWorld));
  3911. #endif
  3912. vNormalW=normalize(normalWorld*normalUpdated);
  3913. #endif
  3914. #endif
  3915. #define CUSTOM_VERTEX_UPDATE_WORLDPOS
  3916. #ifdef MULTIVIEW
  3917. if (gl_ViewID_OVR == 0u) {
  3918. gl_Position=viewProjection*worldPos;
  3919. } else {
  3920. gl_Position=viewProjectionR*worldPos;
  3921. }
  3922. #else
  3923. gl_Position=viewProjection*worldPos;
  3924. #endif
  3925. vPositionW=vec3(worldPos);
  3926. #include<prePassVertex>
  3927. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  3928. vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
  3929. #endif
  3930. #ifndef UV1
  3931. vec2 uvUpdated=vec2(0.,0.);
  3932. #endif
  3933. #ifdef MAINUV1
  3934. vMainUV1=uvUpdated;
  3935. #endif
  3936. #include<uvVariableDeclaration>[2..7]
  3937. #include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
  3938. #include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
  3939. #include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
  3940. #include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
  3941. #include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
  3942. #include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
  3943. #if defined(SPECULARTERM)
  3944. #include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
  3945. #endif
  3946. #include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
  3947. #include<bumpVertex>
  3948. #include<clipPlaneVertex>
  3949. #include<fogVertex>
  3950. #include<shadowsVertex>[0..maxSimultaneousLights]
  3951. #ifdef VERTEXCOLOR
  3952. vColor=color;
  3953. #endif
  3954. #include<pointCloudVertex>
  3955. #include<logDepthVertex>
  3956. #define CUSTOM_VERTEX_MAIN_END
  3957. }
  3958. `;ShaderStore.ShadersStore[name$1p]=shader$1p;var DetailMapConfiguration=function(){function a(i){this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=i}return a.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},a.prototype.isReadyForSubMesh=function(i,e){if(!this._isEnabled)return!0;var o=e.getEngine();return!(i._areTexturesDirty&&e.texturesEnabled&&o.getCaps().standardDerivatives&&this._texture&&MaterialFlags.DetailTextureEnabled&&!this._texture.isReady())},a.prototype.prepareDefines=function(i,e){if(this._isEnabled){i.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;var o=e.getEngine();i._areTexturesDirty&&(o.getCaps().standardDerivatives&&this._texture&&MaterialFlags.DetailTextureEnabled&&this._isEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._texture,i,"DETAIL"),i.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):i.DETAIL=!1)}else i.DETAIL=!1},a.prototype.bindForSubMesh=function(i,e,o){!this._isEnabled||((!i.useUbo||!o||!i.isSync)&&this._texture&&MaterialFlags.DetailTextureEnabled&&(i.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),MaterialHelper.BindTextureMatrix(this._texture,i,"detail")),e.texturesEnabled&&this._texture&&MaterialFlags.DetailTextureEnabled&&i.setTexture("detailSampler",this._texture))},a.prototype.hasTexture=function(i){return this._texture===i},a.prototype.getActiveTextures=function(i){this._texture&&i.push(this._texture)},a.prototype.getAnimatables=function(i){this._texture&&this._texture.animations&&this._texture.animations.length>0&&i.push(this._texture)},a.prototype.dispose=function(i){var e;i&&((e=this._texture)===null||e===void 0||e.dispose())},a.prototype.getClassName=function(){return"DetailMapConfiguration"},a.AddUniforms=function(i){i.push("vDetailInfos"),i.push("detailMatrix")},a.AddSamplers=function(i){i.push("detailSampler")},a.PrepareUniformBuffer=function(i){i.addUniform("vDetailInfos",4),i.addUniform("detailMatrix",16)},a.prototype.copyTo=function(i){SerializationHelper.Clone(function(){return i},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.prototype.parse=function(i,e,o){var s=this;SerializationHelper.Parse(function(){return s},i,e,o)},__decorate([serializeAsTexture("detailTexture"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"texture",void 0),__decorate([serialize()],a.prototype,"diffuseBlendLevel",void 0),__decorate([serialize()],a.prototype,"roughnessBlendLevel",void 0),__decorate([serialize()],a.prototype,"bumpLevel",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"normalBlendMethod",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"isEnabled",void 0),a}(),onCreatedEffectParameters$2={effect:null,subMesh:null},StandardMaterialDefines=function(a){__extends(i,a);function i(){var e=a.call(this)||this;return e.MAINUV1=!1,e.MAINUV2=!1,e.MAINUV3=!1,e.MAINUV4=!1,e.MAINUV5=!1,e.MAINUV6=!1,e.DIFFUSE=!1,e.DIFFUSEDIRECTUV=0,e.DETAIL=!1,e.DETAILDIRECTUV=0,e.DETAIL_NORMALBLENDMETHOD=0,e.BAKED_VERTEX_ANIMATION_TEXTURE=!1,e.AMBIENT=!1,e.AMBIENTDIRECTUV=0,e.OPACITY=!1,e.OPACITYDIRECTUV=0,e.OPACITYRGB=!1,e.REFLECTION=!1,e.EMISSIVE=!1,e.EMISSIVEDIRECTUV=0,e.SPECULAR=!1,e.SPECULARDIRECTUV=0,e.BUMP=!1,e.BUMPDIRECTUV=0,e.PARALLAX=!1,e.PARALLAXOCCLUSION=!1,e.SPECULAROVERALPHA=!1,e.CLIPPLANE=!1,e.CLIPPLANE2=!1,e.CLIPPLANE3=!1,e.CLIPPLANE4=!1,e.CLIPPLANE5=!1,e.CLIPPLANE6=!1,e.ALPHATEST=!1,e.DEPTHPREPASS=!1,e.ALPHAFROMDIFFUSE=!1,e.POINTSIZE=!1,e.FOG=!1,e.SPECULARTERM=!1,e.DIFFUSEFRESNEL=!1,e.OPACITYFRESNEL=!1,e.REFLECTIONFRESNEL=!1,e.REFRACTIONFRESNEL=!1,e.EMISSIVEFRESNEL=!1,e.FRESNEL=!1,e.NORMAL=!1,e.TANGENT=!1,e.UV1=!1,e.UV2=!1,e.UV3=!1,e.UV4=!1,e.UV5=!1,e.UV6=!1,e.VERTEXCOLOR=!1,e.VERTEXALPHA=!1,e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE=!1,e.BONES_VELOCITY_ENABLED=!1,e.INSTANCES=!1,e.THIN_INSTANCES=!1,e.GLOSSINESS=!1,e.ROUGHNESS=!1,e.EMISSIVEASILLUMINATION=!1,e.LINKEMISSIVEWITHDIFFUSE=!1,e.REFLECTIONFRESNELFROMSPECULAR=!1,e.LIGHTMAP=!1,e.LIGHTMAPDIRECTUV=0,e.OBJECTSPACE_NORMALMAP=!1,e.USELIGHTMAPASSHADOWMAP=!1,e.REFLECTIONMAP_3D=!1,e.REFLECTIONMAP_SPHERICAL=!1,e.REFLECTIONMAP_PLANAR=!1,e.REFLECTIONMAP_CUBIC=!1,e.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,e.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.REFLECTIONMAP_PROJECTION=!1,e.REFLECTIONMAP_SKYBOX=!1,e.REFLECTIONMAP_EXPLICIT=!1,e.REFLECTIONMAP_EQUIRECTANGULAR=!1,e.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,e.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.REFLECTIONMAP_OPPOSITEZ=!1,e.INVERTCUBICMAP=!1,e.LOGARITHMICDEPTH=!1,e.REFRACTION=!1,e.REFRACTIONMAP_3D=!1,e.REFLECTIONOVERALPHA=!1,e.TWOSIDEDLIGHTING=!1,e.SHADOWFLOAT=!1,e.MORPHTARGETS=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_UV=!1,e.NUM_MORPH_INFLUENCERS=0,e.MORPHTARGETS_TEXTURE=!1,e.NONUNIFORMSCALING=!1,e.PREMULTIPLYALPHA=!1,e.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,e.ALPHABLEND=!0,e.PREPASS=!1,e.PREPASS_IRRADIANCE=!1,e.PREPASS_IRRADIANCE_INDEX=-1,e.PREPASS_ALBEDO_SQRT=!1,e.PREPASS_ALBEDO_SQRT_INDEX=-1,e.PREPASS_DEPTH=!1,e.PREPASS_DEPTH_INDEX=-1,e.PREPASS_NORMAL=!1,e.PREPASS_NORMAL_INDEX=-1,e.PREPASS_POSITION=!1,e.PREPASS_POSITION_INDEX=-1,e.PREPASS_VELOCITY=!1,e.PREPASS_VELOCITY_INDEX=-1,e.PREPASS_REFLECTIVITY=!1,e.PREPASS_REFLECTIVITY_INDEX=-1,e.SCENE_MRT_COUNT=0,e.RGBDLIGHTMAP=!1,e.RGBDREFLECTION=!1,e.RGBDREFRACTION=!1,e.IMAGEPROCESSING=!1,e.VIGNETTE=!1,e.VIGNETTEBLENDMODEMULTIPLY=!1,e.VIGNETTEBLENDMODEOPAQUE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=!1,e.SAMPLER3DBGRMAP=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.SKIPFINALCOLORCLAMP=!1,e.MULTIVIEW=!1,e.ORDER_INDEPENDENT_TRANSPARENCY=!1,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,e.IS_REFLECTION_LINEAR=!1,e.IS_REFRACTION_LINEAR=!1,e.EXPOSURE=!1,e.rebuild(),e}return i.prototype.setReflectionMode=function(e){for(var o=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"],s=0,c=o;s<c.length;s++){var d=c[s];this[d]=d===e}},i}(MaterialDefines),StandardMaterial=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s._diffuseTexture=null,s._ambientTexture=null,s._opacityTexture=null,s._reflectionTexture=null,s._emissiveTexture=null,s._specularTexture=null,s._bumpTexture=null,s._lightmapTexture=null,s._refractionTexture=null,s.ambientColor=new Color3(0,0,0),s.diffuseColor=new Color3(1,1,1),s.specularColor=new Color3(1,1,1),s.emissiveColor=new Color3(0,0,0),s.specularPower=64,s._useAlphaFromDiffuseTexture=!1,s._useEmissiveAsIllumination=!1,s._linkEmissiveWithDiffuse=!1,s._useSpecularOverAlpha=!1,s._useReflectionOverAlpha=!1,s._disableLighting=!1,s._useObjectSpaceNormalMap=!1,s._useParallax=!1,s._useParallaxOcclusion=!1,s.parallaxScaleBias=.05,s._roughness=0,s.indexOfRefraction=.98,s.invertRefractionY=!0,s.alphaCutOff=.4,s._useLightmapAsShadowmap=!1,s._useReflectionFresnelFromSpecular=!1,s._useGlossinessFromSpecularMapAlpha=!1,s._maxSimultaneousLights=4,s._invertNormalMapX=!1,s._invertNormalMapY=!1,s._twoSidedLighting=!1,s.detailMap=new DetailMapConfiguration(s._markAllSubMeshesAsTexturesDirty.bind(s)),s._renderTargets=new SmartArray(16),s._worldViewProjectionMatrix=Matrix.Zero(),s._globalAmbientColor=new Color3(0,0,0),s.buildUniformLayout(),s._attachImageProcessingConfiguration(null),s.prePassConfiguration=new PrePassConfiguration,s.getRenderTargetTextures=function(){return s._renderTargets.reset(),i.ReflectionTextureEnabled&&s._reflectionTexture&&s._reflectionTexture.isRenderTarget&&s._renderTargets.push(s._reflectionTexture),i.RefractionTextureEnabled&&s._refractionTexture&&s._refractionTexture.isRenderTarget&&s._renderTargets.push(s._refractionTexture),s._renderTargets},s}return Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),i.prototype._attachImageProcessingConfiguration=function(e){var o=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){o._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(i.prototype,"isPrePassCapable",{get:function(){return!this.disableDepthWrite},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"canRenderToMRT",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasRenderTargetTextures",{get:function(){return!!(i.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||i.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"StandardMaterial"},Object.defineProperty(i.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!1,configurable:!0}),i.prototype.needAlphaBlending=function(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled},i.prototype.needAlphaTesting=function(){return this._forceAlphaTest?!0:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Material.MATERIAL_ALPHATEST)},i.prototype._shouldUseAlphaFromDiffuseTexture=function(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Material.MATERIAL_OPAQUE},i.prototype._hasAlphaChannel=function(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null},i.prototype.getAlphaTestTexture=function(){return this._diffuseTexture},i.prototype.isReadyForSubMesh=function(e,o,s){if(s===void 0&&(s=!1),o.effect&&this.isFrozen&&o.effect._wasPreviouslyReady)return!0;o.materialDefines||(o.materialDefines=new StandardMaterialDefines);var c=this.getScene(),d=o.materialDefines;if(this._isReadyForSubMesh(o))return!0;var _=c.getEngine();d._needNormals=MaterialHelper.PrepareDefinesForLights(c,e,d,!0,this._maxSimultaneousLights,this._disableLighting),MaterialHelper.PrepareDefinesForMultiview(c,d);var b=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(MaterialHelper.PrepareDefinesForPrePass(c,d,this.canRenderToMRT&&!b),MaterialHelper.PrepareDefinesForOIT(c,d,b),d._areTexturesDirty){d._needUVs=!1;for(var k=1;k<=6;++k)d["MAINUV"+k]=!1;if(c.texturesEnabled){if(this._diffuseTexture&&i.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,d,"DIFFUSE");else return!1;else d.DIFFUSE=!1;if(this._ambientTexture&&i.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,d,"AMBIENT");else return!1;else d.AMBIENT=!1;if(this._opacityTexture&&i.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,d,"OPACITY"),d.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else d.OPACITY=!1;if(this._reflectionTexture&&i.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(d._needNormals=!0,d.REFLECTION=!0,d.ROUGHNESS=this._roughness>0,d.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,d.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Texture.INVCUBIC_MODE,d.REFLECTIONMAP_3D=this._reflectionTexture.isCube,d.RGBDREFLECTION=this._reflectionTexture.isRGBD,d.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,this._reflectionTexture.coordinatesMode){case Texture.EXPLICIT_MODE:d.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Texture.PLANAR_MODE:d.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Texture.PROJECTION_MODE:d.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Texture.SKYBOX_MODE:d.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Texture.SPHERICAL_MODE:d.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Texture.EQUIRECTANGULAR_MODE:d.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Texture.FIXED_EQUIRECTANGULAR_MODE:d.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:d.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Texture.CUBIC_MODE:case Texture.INVCUBIC_MODE:default:d.setReflectionMode("REFLECTIONMAP_CUBIC");break}d.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else d.REFLECTION=!1,d.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&i.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,d,"EMISSIVE");else return!1;else d.EMISSIVE=!1;if(this._lightmapTexture&&i.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,d,"LIGHTMAP"),d.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,d.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else d.LIGHTMAP=!1;if(this._specularTexture&&i.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture,d,"SPECULAR"),d.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else d.SPECULAR=!1;if(c.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&i.BumpTextureEnabled){if(this._bumpTexture.isReady())MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,d,"BUMP"),d.PARALLAX=this._useParallax,d.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;d.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else d.BUMP=!1;if(this._refractionTexture&&i.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())d._needUVs=!0,d.REFRACTION=!0,d.REFRACTIONMAP_3D=this._refractionTexture.isCube,d.RGBDREFRACTION=this._refractionTexture.isRGBD,d.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else d.REFRACTION=!1;d.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else d.DIFFUSE=!1,d.AMBIENT=!1,d.OPACITY=!1,d.REFLECTION=!1,d.EMISSIVE=!1,d.LIGHTMAP=!1,d.BUMP=!1,d.REFRACTION=!1;d.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),d.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,d.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,d.SPECULAROVERALPHA=this._useSpecularOverAlpha,d.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,d.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,d.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(!this.detailMap.isReadyForSubMesh(d,c))return!1;if(d._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(d),d.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,d.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(d._areFresnelDirty&&(i.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(d.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,d.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,d.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,d.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,d.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,d.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,d._needNormals=!0,d.FRESNEL=!0):d.FRESNEL=!1),MaterialHelper.PrepareDefinesForMisc(e,c,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,d),MaterialHelper.PrepareDefinesForAttributes(e,d,!0,!0,!0),MaterialHelper.PrepareDefinesForFrameBoundValues(c,_,d,s,null,o.getRenderingMesh().hasThinInstances),this.detailMap.prepareDefines(d,c),d.isDirty){var j=d._areLightsDisposed;d.markAsProcessed();var $=new EffectFallbacks;d.REFLECTION&&$.addFallback(0,"REFLECTION"),d.SPECULAR&&$.addFallback(0,"SPECULAR"),d.BUMP&&$.addFallback(0,"BUMP"),d.PARALLAX&&$.addFallback(1,"PARALLAX"),d.PARALLAXOCCLUSION&&$.addFallback(0,"PARALLAXOCCLUSION"),d.SPECULAROVERALPHA&&$.addFallback(0,"SPECULAROVERALPHA"),d.FOG&&$.addFallback(1,"FOG"),d.POINTSIZE&&$.addFallback(0,"POINTSIZE"),d.LOGARITHMICDEPTH&&$.addFallback(0,"LOGARITHMICDEPTH"),MaterialHelper.HandleFallbacksForShadows(d,$,this._maxSimultaneousLights),d.SPECULARTERM&&$.addFallback(0,"SPECULARTERM"),d.DIFFUSEFRESNEL&&$.addFallback(1,"DIFFUSEFRESNEL"),d.OPACITYFRESNEL&&$.addFallback(2,"OPACITYFRESNEL"),d.REFLECTIONFRESNEL&&$.addFallback(3,"REFLECTIONFRESNEL"),d.EMISSIVEFRESNEL&&$.addFallback(4,"EMISSIVEFRESNEL"),d.FRESNEL&&$.addFallback(4,"FRESNEL"),d.MULTIVIEW&&$.addFallback(0,"MULTIVIEW");var _e=[VertexBuffer.PositionKind];d.NORMAL&&_e.push(VertexBuffer.NormalKind),d.TANGENT&&_e.push(VertexBuffer.TangentKind);for(var k=1;k<=6;++k)d["UV"+k]&&_e.push("uv"+(k===1?"":k));d.VERTEXCOLOR&&_e.push(VertexBuffer.ColorKind),MaterialHelper.PrepareAttributesForBones(_e,e,d,$),MaterialHelper.PrepareAttributesForInstances(_e,d),MaterialHelper.PrepareAttributesForMorphTargets(_e,e,d),MaterialHelper.PrepareAttributesForBakedVertexAnimation(_e,e,d);var et="default",tt=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],rt=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],it=["Material","Scene","Mesh"];DetailMapConfiguration.AddUniforms(tt),DetailMapConfiguration.AddSamplers(rt),PrePassConfiguration.AddUniforms(tt),PrePassConfiguration.AddSamplers(rt),ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(tt,d),ImageProcessingConfiguration.PrepareSamplers(rt,d)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:tt,uniformBuffersNames:it,samplers:rt,defines:d,maxSimultaneousLights:this._maxSimultaneousLights});var nt={};this.customShaderNameResolve&&(et=this.customShaderNameResolve(et,tt,it,rt,d,_e,nt));var ot=d.toString(),at=o.effect,st=c.getEngine().createEffect(et,{attributes:_e,uniformsNames:tt,uniformBuffersNames:it,samplers:rt,defines:ot,fallbacks:$,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:d.NUM_MORPH_INFLUENCERS},processFinalCode:nt.processFinalCode,multiTarget:d.PREPASS},_);if(st)if(this._onEffectCreatedObservable&&(onCreatedEffectParameters$2.effect=st,onCreatedEffectParameters$2.subMesh=o,this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$2)),this.allowShaderHotSwapping&&at&&!st.isReady()){if(st=at,d.markAsUnprocessed(),j)return d._areLightsDisposed=!0,!1}else c.resetCachedMaterial(),o.setEffect(st,d,this._materialContext)}return!o.effect||!o.effect.isReady()?!1:(d._renderId=c.getRenderId(),o.effect._wasPreviouslyReady=!0,!0)},i.prototype.buildUniformLayout=function(){var e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),DetailMapConfiguration.PrepareUniformBuffer(e),e.create()},i.prototype.unbind=function(){if(this._activeEffect&&!this.getScene().getEngine()._features.needToAlwaysBindUniformBuffers){var e=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),e=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),e=!0),e&&this._markAllSubMeshesAsTexturesDirty()}a.prototype.unbind.call(this)},i.prototype.bindForSubMesh=function(e,o,s){var c,d=this.getScene(),_=s.materialDefines;if(!!_){var b=s.effect;if(!!b){this._activeEffect=b,o.getMeshUniformBuffer().bindToEffect(b,"Mesh"),o.transferToEffect(e),this.prePassConfiguration.bindForSubMesh(this._activeEffect,d,o,e,this.isFrozen),_.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var k=this._mustRebind(d,b,o.visibility);MaterialHelper.BindBonesParameters(o,b);var j=this._uniformBuffer;if(k){if(j.bindToEffect(b,"Material"),this.bindViewProjection(b),!j.useUbo||!this.isFrozen||!j.isSync){if(i.FresnelEnabled&&_.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(j.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),j.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&j.updateColor4("opacityParts",new Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(j.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),j.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(j.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),j.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(j.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),j.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),d.texturesEnabled){if(this._diffuseTexture&&i.DiffuseTextureEnabled&&(j.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),MaterialHelper.BindTextureMatrix(this._diffuseTexture,j,"diffuse")),this._ambientTexture&&i.AmbientTextureEnabled&&(j.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),MaterialHelper.BindTextureMatrix(this._ambientTexture,j,"ambient")),this._opacityTexture&&i.OpacityTextureEnabled&&(j.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),MaterialHelper.BindTextureMatrix(this._opacityTexture,j,"opacity")),this._hasAlphaChannel()&&j.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&i.ReflectionTextureEnabled&&(j.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),j.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var $=this._reflectionTexture;j.updateVector3("vReflectionPosition",$.boundingBoxPosition),j.updateVector3("vReflectionSize",$.boundingBoxSize)}if(this._emissiveTexture&&i.EmissiveTextureEnabled&&(j.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),MaterialHelper.BindTextureMatrix(this._emissiveTexture,j,"emissive")),this._lightmapTexture&&i.LightmapTextureEnabled&&(j.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),MaterialHelper.BindTextureMatrix(this._lightmapTexture,j,"lightmap")),this._specularTexture&&i.SpecularTextureEnabled&&(j.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),MaterialHelper.BindTextureMatrix(this._specularTexture,j,"specular")),this._bumpTexture&&d.getEngine().getCaps().standardDerivatives&&i.BumpTextureEnabled&&(j.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),MaterialHelper.BindTextureMatrix(this._bumpTexture,j,"bump"),d._mirroredCameraPosition?j.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):j.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&i.RefractionTextureEnabled){var _e=1;if(this._refractionTexture.isCube||(j.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(_e=this._refractionTexture.depth)),j.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,_e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){var $=this._refractionTexture;j.updateVector3("vRefractionPosition",$.boundingBoxPosition),j.updateVector3("vRefractionSize",$.boundingBoxSize)}}}this.pointsCloud&&j.updateFloat("pointSize",this.pointSize),_.SPECULARTERM&&j.updateColor4("vSpecularColor",this.specularColor,this.specularPower),j.updateColor3("vEmissiveColor",i.EmissiveTextureEnabled?this.emissiveColor:Color3.BlackReadOnly),j.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),d.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),j.updateColor3("vAmbientColor",this._globalAmbientColor)}if(d.texturesEnabled&&(this._diffuseTexture&&i.DiffuseTextureEnabled&&b.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&i.AmbientTextureEnabled&&b.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&i.OpacityTextureEnabled&&b.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&i.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?b.setTexture("reflectionCubeSampler",this._reflectionTexture):b.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&i.EmissiveTextureEnabled&&b.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&i.LightmapTextureEnabled&&b.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&i.SpecularTextureEnabled&&b.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&d.getEngine().getCaps().standardDerivatives&&i.BumpTextureEnabled&&b.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&i.RefractionTextureEnabled)){var _e=1;this._refractionTexture.isCube?b.setTexture("refractionCubeSampler",this._refractionTexture):b.setTexture("refraction2DSampler",this._refractionTexture)}this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(o)&&this.getScene().depthPeelingRenderer.bind(b),this.detailMap.bindForSubMesh(j,d,this.isFrozen),MaterialHelper.BindClipPlane(b,d),this.bindEyePosition(b)}else d.getEngine()._features.needToAlwaysBindUniformBuffers&&(j.bindToEffect(b,"Material"),this._needToBindSceneUbo=!0);(k||!this.isFrozen)&&(d.lightsEnabled&&!this._disableLighting&&MaterialHelper.BindLights(d,o,b,_,this._maxSimultaneousLights),(d.fogEnabled&&o.applyFog&&d.fogMode!==Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||o.receiveShadows)&&this.bindView(b),MaterialHelper.BindFogParameters(d,o,b),_.NUM_MORPH_INFLUENCERS&&MaterialHelper.BindMorphTargetParameters(o,b),_.BAKED_VERTEX_ANIMATION_TEXTURE&&((c=o.bakedVertexAnimationManager)===null||c===void 0||c.bind(b,_.INSTANCES)),this.useLogarithmicDepth&&MaterialHelper.BindLogDepth(_,b,d),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(o,this._activeEffect),j.update()}}},i.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this.detailMap.getAnimatables(e),e},i.prototype.getActiveTextures=function(){var e=a.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),this.detailMap.getActiveTextures(e),e},i.prototype.hasTexture=function(e){return!!(a.prototype.hasTexture.call(this,e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e||this.detailMap.hasTexture(e))},i.prototype.dispose=function(e,o){var s,c,d,_,b,k,j,$,_e;o&&((s=this._diffuseTexture)===null||s===void 0||s.dispose(),(c=this._ambientTexture)===null||c===void 0||c.dispose(),(d=this._opacityTexture)===null||d===void 0||d.dispose(),(_=this._reflectionTexture)===null||_===void 0||_.dispose(),(b=this._emissiveTexture)===null||b===void 0||b.dispose(),(k=this._specularTexture)===null||k===void 0||k.dispose(),(j=this._bumpTexture)===null||j===void 0||j.dispose(),($=this._lightmapTexture)===null||$===void 0||$.dispose(),(_e=this._refractionTexture)===null||_e===void 0||_e.dispose()),this.detailMap.dispose(o),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),a.prototype.dispose.call(this,e,o)},i.prototype.clone=function(e){var o=this,s=SerializationHelper.Clone(function(){return new i(e,o.getScene())},this);return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),s},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);return e.stencil=this.stencil.serialize(),e},i.Parse=function(e,o,s){var c=SerializationHelper.Parse(function(){return new i(e.name,o)},e,o,s);return e.stencil&&c.stencil.parse(e.stencil,o,s),c},Object.defineProperty(i,"DiffuseTextureEnabled",{get:function(){return MaterialFlags.DiffuseTextureEnabled},set:function(e){MaterialFlags.DiffuseTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"DetailTextureEnabled",{get:function(){return MaterialFlags.DetailTextureEnabled},set:function(e){MaterialFlags.DetailTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"AmbientTextureEnabled",{get:function(){return MaterialFlags.AmbientTextureEnabled},set:function(e){MaterialFlags.AmbientTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"OpacityTextureEnabled",{get:function(){return MaterialFlags.OpacityTextureEnabled},set:function(e){MaterialFlags.OpacityTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"ReflectionTextureEnabled",{get:function(){return MaterialFlags.ReflectionTextureEnabled},set:function(e){MaterialFlags.ReflectionTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"EmissiveTextureEnabled",{get:function(){return MaterialFlags.EmissiveTextureEnabled},set:function(e){MaterialFlags.EmissiveTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"SpecularTextureEnabled",{get:function(){return MaterialFlags.SpecularTextureEnabled},set:function(e){MaterialFlags.SpecularTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"BumpTextureEnabled",{get:function(){return MaterialFlags.BumpTextureEnabled},set:function(e){MaterialFlags.BumpTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"LightmapTextureEnabled",{get:function(){return MaterialFlags.LightmapTextureEnabled},set:function(e){MaterialFlags.LightmapTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"RefractionTextureEnabled",{get:function(){return MaterialFlags.RefractionTextureEnabled},set:function(e){MaterialFlags.RefractionTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"ColorGradingTextureEnabled",{get:function(){return MaterialFlags.ColorGradingTextureEnabled},set:function(e){MaterialFlags.ColorGradingTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i,"FresnelEnabled",{get:function(){return MaterialFlags.FresnelEnabled},set:function(e){MaterialFlags.FresnelEnabled=e},enumerable:!1,configurable:!0}),__decorate([serializeAsTexture("diffuseTexture")],i.prototype,"_diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"diffuseTexture",void 0),__decorate([serializeAsTexture("ambientTexture")],i.prototype,"_ambientTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTexture",void 0),__decorate([serializeAsTexture("opacityTexture")],i.prototype,"_opacityTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"opacityTexture",void 0),__decorate([serializeAsTexture("reflectionTexture")],i.prototype,"_reflectionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionTexture",void 0),__decorate([serializeAsTexture("emissiveTexture")],i.prototype,"_emissiveTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),__decorate([serializeAsTexture("specularTexture")],i.prototype,"_specularTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"specularTexture",void 0),__decorate([serializeAsTexture("bumpTexture")],i.prototype,"_bumpTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"bumpTexture",void 0),__decorate([serializeAsTexture("lightmapTexture")],i.prototype,"_lightmapTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"lightmapTexture",void 0),__decorate([serializeAsTexture("refractionTexture")],i.prototype,"_refractionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"refractionTexture",void 0),__decorate([serializeAsColor3("ambient")],i.prototype,"ambientColor",void 0),__decorate([serializeAsColor3("diffuse")],i.prototype,"diffuseColor",void 0),__decorate([serializeAsColor3("specular")],i.prototype,"specularColor",void 0),__decorate([serializeAsColor3("emissive")],i.prototype,"emissiveColor",void 0),__decorate([serialize()],i.prototype,"specularPower",void 0),__decorate([serialize("useAlphaFromDiffuseTexture")],i.prototype,"_useAlphaFromDiffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([serialize("useEmissiveAsIllumination")],i.prototype,"_useEmissiveAsIllumination",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useEmissiveAsIllumination",void 0),__decorate([serialize("linkEmissiveWithDiffuse")],i.prototype,"_linkEmissiveWithDiffuse",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([serialize("useSpecularOverAlpha")],i.prototype,"_useSpecularOverAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useSpecularOverAlpha",void 0),__decorate([serialize("useReflectionOverAlpha")],i.prototype,"_useReflectionOverAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useReflectionOverAlpha",void 0),__decorate([serialize("disableLighting")],i.prototype,"_disableLighting",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),__decorate([serialize("useObjectSpaceNormalMap")],i.prototype,"_useObjectSpaceNormalMap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useObjectSpaceNormalMap",void 0),__decorate([serialize("useParallax")],i.prototype,"_useParallax",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallax",void 0),__decorate([serialize("useParallaxOcclusion")],i.prototype,"_useParallaxOcclusion",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallaxOcclusion",void 0),__decorate([serialize()],i.prototype,"parallaxScaleBias",void 0),__decorate([serialize("roughness")],i.prototype,"_roughness",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),__decorate([serialize()],i.prototype,"indexOfRefraction",void 0),__decorate([serialize()],i.prototype,"invertRefractionY",void 0),__decorate([serialize()],i.prototype,"alphaCutOff",void 0),__decorate([serialize("useLightmapAsShadowmap")],i.prototype,"_useLightmapAsShadowmap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),__decorate([serializeAsFresnelParameters("diffuseFresnelParameters")],i.prototype,"_diffuseFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],i.prototype,"diffuseFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("opacityFresnelParameters")],i.prototype,"_opacityFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")],i.prototype,"opacityFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("reflectionFresnelParameters")],i.prototype,"_reflectionFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],i.prototype,"reflectionFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("refractionFresnelParameters")],i.prototype,"_refractionFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],i.prototype,"refractionFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("emissiveFresnelParameters")],i.prototype,"_emissiveFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],i.prototype,"emissiveFresnelParameters",void 0),__decorate([serialize("useReflectionFresnelFromSpecular")],i.prototype,"_useReflectionFresnelFromSpecular",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],i.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([serialize("useGlossinessFromSpecularMapAlpha")],i.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([serialize("maxSimultaneousLights")],i.prototype,"_maxSimultaneousLights",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),__decorate([serialize("invertNormalMapX")],i.prototype,"_invertNormalMapX",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),__decorate([serialize("invertNormalMapY")],i.prototype,"_invertNormalMapY",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),__decorate([serialize("twoSidedLighting")],i.prototype,"_twoSidedLighting",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"twoSidedLighting",void 0),__decorate([serialize()],i.prototype,"useLogarithmicDepth",null),i}(PushMaterial);RegisterClass("BABYLON.StandardMaterial",StandardMaterial);Scene.DefaultMaterialFactory=function(a){return new StandardMaterial("default material",a)};var CubeTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it){s===void 0&&(s=null),c===void 0&&(c=!1),d===void 0&&(d=null),_===void 0&&(_=null),b===void 0&&(b=null),k===void 0&&(k=5),j===void 0&&(j=!1),$===void 0&&($=null),_e===void 0&&(_e=!1),et===void 0&&(et=.8),tt===void 0&&(tt=0);var nt,ot=a.call(this,o)||this;return ot._lodScale=.8,ot._lodOffset=0,ot.onLoadObservable=new Observable,ot.boundingBoxPosition=Vector3.Zero(),ot._rotationY=0,ot._files=null,ot._forcedExtension=null,ot._extensions=null,ot.name=e,ot.url=e,ot._noMipmap=c,ot.hasAlpha=!1,ot._format=k,ot.isCube=!0,ot._textureMatrix=Matrix.Identity(),ot._createPolynomials=_e,ot.coordinatesMode=Texture.CUBIC_MODE,ot._extensions=s,ot._files=d,ot._forcedExtension=$,ot._loaderOptions=rt,ot._useSRGBBuffer=it,ot._lodScale=et,ot._lodOffset=tt,!e&&!d||ot.updateURL(e,$,_,j,b,s,(nt=ot.getScene())===null||nt===void 0?void 0:nt.useDelayedTextureLoading,d),ot}return Object.defineProperty(i.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!(this._boundingBoxSize&&this._boundingBoxSize.equals(e))){this._boundingBoxSize=e;var o=this.getScene();o&&o.markAllMaterialsAsDirty(1)}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rotationY",{get:function(){return this._rotationY},set:function(e){this._rotationY=e,this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"forcedExtension",{get:function(){return this._forcedExtension},enumerable:!1,configurable:!0}),i.CreateFromImages=function(e,o,s){var c="";return e.forEach(function(d){return c+=d}),new i(c,o,null,s,e)},i.CreateFromPrefilteredData=function(e,o,s,c){s===void 0&&(s=null),c===void 0&&(c=!0);var d=o.useDelayedTextureLoading;o.useDelayedTextureLoading=!1;var _=new i(e,o,null,!1,null,null,null,void 0,!0,s,c);return o.useDelayedTextureLoading=d,_},i.prototype.getClassName=function(){return"CubeTexture"},i.prototype.updateURL=function(e,o,s,c,d,_,b,k){s===void 0&&(s=null),c===void 0&&(c=!1),d===void 0&&(d=null),_===void 0&&(_=null),b===void 0&&(b=!1),k===void 0&&(k=null),(!this.name||StartsWith(this.name,"data:"))&&(this.name=e),this.url=e;var j=e.lastIndexOf("."),$=o||(j>-1?e.substring(j).toLowerCase():""),_e=$.indexOf(".dds")===0,et=$.indexOf(".env")===0;if(et?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=c,c&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),k)this._files=k;else if(!et&&!_e&&!_&&(_=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,_){for(var tt=0;tt<_.length;tt++)this._files.push(e+_[tt]);this._extensions=_}b?(this.delayLoadState=4,this._delayedOnLoad=s,this._delayedOnError=d):this._loadTexture(s,d)},i.prototype.delayLoad=function(e){this.delayLoadState===4&&(e&&(this._forcedExtension=e),this.delayLoadState=1,this._loadTexture(this._delayedOnLoad,this._delayedOnError))},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.prototype.setReflectionTextureMatrix=function(e){var o=this,s;e.updateFlag!==this._textureMatrix.updateFlag&&(e.isIdentity()!==this._textureMatrix.isIdentity()&&((s=this.getScene())===null||s===void 0||s.markAllMaterialsAsDirty(1,function(c){return c.getActiveTextures().indexOf(o)!==-1})),this._textureMatrix=e)},i.prototype._loadTexture=function(e,o){var s=this,c;e===void 0&&(e=null),o===void 0&&(o=null);var d=this.getScene(),_=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer);var b=function(){var j;s.onLoadObservable.notifyObservers(s),_&&(_.dispose(),(j=s.getScene())===null||j===void 0||j.markAllMaterialsAsDirty(1)),e&&e()},k=function(j,$){s._loadingError=!0,s._errorObject={message:j,exception:$},o&&o(j,$),Texture.OnTextureLoadErrorObservable.notifyObservers(s)};this._texture?this._texture.isReady?Tools.SetImmediate(function(){return b()}):this._texture.onLoadedObservable.add(function(){return b()}):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,d,this._lodScale,this._lodOffset,e,k,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,d,this._files,this._noMipmap,e,k,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),(c=this._texture)===null||c===void 0||c.onLoadedObservable.add(function(){return s.onLoadObservable.notifyObservers(s)}))},i.Parse=function(e,o,s){var c=SerializationHelper.Parse(function(){var k=!1;return e.prefiltered&&(k=e.prefiltered),new i(s+e.name,o,e.extensions,!1,e.files||null,null,null,void 0,k,e.forcedExtension)},e,o);if(e.boundingBoxPosition&&(c.boundingBoxPosition=Vector3.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(c.boundingBoxSize=Vector3.FromArray(e.boundingBoxSize)),e.animations)for(var d=0;d<e.animations.length;d++){var _=e.animations[d],b=GetClass("BABYLON.Animation");b&&c.animations.push(b.Parse(_))}return c},i.prototype.clone=function(){var e=this,o=0,s=SerializationHelper.Clone(function(){var c=new i(e.url,e.getScene()||e._getEngine(),e._extensions,e._noMipmap,e._files);return o=c.uniqueId,c},this);return s.uniqueId=o,s},__decorate([serialize()],i.prototype,"url",void 0),__decorate([serialize("rotationY")],i.prototype,"rotationY",null),__decorate([serialize("files")],i.prototype,"_files",void 0),__decorate([serialize("forcedExtension")],i.prototype,"_forcedExtension",void 0),__decorate([serialize("extensions")],i.prototype,"_extensions",void 0),__decorate([serializeAsMatrix("textureMatrix")],i.prototype,"_textureMatrix",void 0),i}(BaseTexture);Texture._CubeTextureParser=CubeTexture.Parse;RegisterClass("BABYLON.CubeTexture",CubeTexture);var DynamicTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b){s===void 0&&(s=null),c===void 0&&(c=!1),d===void 0&&(d=3),_===void 0&&(_=5);var k=a.call(this,null,s,!c,b,d,void 0,void 0,void 0,void 0,_)||this;k.name=e,k.wrapU=Texture.CLAMP_ADDRESSMODE,k.wrapV=Texture.CLAMP_ADDRESSMODE,k._generateMipMaps=c;var j=k._getEngine();if(!j)return k;o.getContext?(k._canvas=o,k._texture=j.createDynamicTexture(o.width,o.height,c,d)):(k._canvas=j.createCanvas(1,1),o.width||o.width===0?k._texture=j.createDynamicTexture(o.width,o.height,c,d):k._texture=j.createDynamicTexture(o,o,c,d));var $=k.getSize();return k._canvas.width!==$.width&&(k._canvas.width=$.width),k._canvas.height!==$.height&&(k._canvas.height=$.height),k._context=k._canvas.getContext("2d"),k}return i.prototype.getClassName=function(){return"DynamicTexture"},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!1,configurable:!0}),i.prototype._recreate=function(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)},i.prototype.scale=function(e){var o=this.getSize();o.width*=e,o.height*=e,this._recreate(o)},i.prototype.scaleTo=function(e,o){var s=this.getSize();s.width=e,s.height=o,this._recreate(s)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e,o,s){o===void 0&&(o=!1),s===void 0&&(s=!1),this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,o,this._format||void 0,void 0,s)},i.prototype.drawText=function(e,o,s,c,d,_,b,k){k===void 0&&(k=!0);var j=this.getSize();if(_&&(this._context.fillStyle=_,this._context.fillRect(0,0,j.width,j.height)),this._context.font=c,o==null){var $=this._context.measureText(e);o=(j.width-$.width)/2}if(s==null){var _e=parseInt(c.replace(/\D/g,""));s=j.height/2+_e/3.65}this._context.fillStyle=d||"",this._context.fillText(e,o,s),k&&this.update(b)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var o=this.getSize(),s=new i(this.name,o,e,this._generateMipMaps);return s.hasAlpha=this.hasAlpha,s.level=this.level,s.wrapU=this.wrapU,s.wrapV=this.wrapV,s},i.prototype.serialize=function(){var e=this.getScene();e&&!e.isReady()&&Logger$2.Warn("The scene must be ready before serializing the dynamic texture");var o=a.prototype.serialize.call(this);return this._IsCanvasElement(this._canvas)&&(o.base64String=this._canvas.toDataURL()),o.invertY=this._invertY,o.samplingMode=this.samplingMode,o},i.prototype._IsCanvasElement=function(e){return e.toDataURL!==void 0},i.prototype._rebuild=function(){this.update()},i}(Texture),VideoTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){c===void 0&&(c=!1),d===void 0&&(d=!1),_===void 0&&(_=Texture.TRILINEAR_SAMPLINGMODE);var j=a.call(this,null,s,!c,d)||this;j._onUserActionRequestedObservable=null,j._stillImageCaptured=!1,j._displayingPosterTexture=!1,j._frameId=-1,j._currentSrc=null,j._errorFound=!1,j._createInternalTexture=function(){if(j._texture!=null)if(j._displayingPosterTexture)j._texture.dispose(),j._displayingPosterTexture=!1;else return;if(!j._getEngine().needPOTTextures||Tools.IsExponentOfTwo(j.video.videoWidth)&&Tools.IsExponentOfTwo(j.video.videoHeight)?(j.wrapU=Texture.WRAP_ADDRESSMODE,j.wrapV=Texture.WRAP_ADDRESSMODE):(j.wrapU=Texture.CLAMP_ADDRESSMODE,j.wrapV=Texture.CLAMP_ADDRESSMODE,j._generateMipMaps=!1),j._texture=j._getEngine().createDynamicTexture(j.video.videoWidth,j.video.videoHeight,j._generateMipMaps,j.samplingMode),!j.video.autoplay&&!j._settings.poster){var _e=j.video.onplaying,et=j.video.muted;j.video.muted=!0,j.video.onplaying=function(){j.video.muted=et,j.video.onplaying=_e,j._updateInternalTexture(),j._errorFound||j.video.pause(),j.onLoadObservable.hasObservers()&&j.onLoadObservable.notifyObservers(j)},j._handlePlay()}else j._updateInternalTexture(),j.onLoadObservable.hasObservers()&&j.onLoadObservable.notifyObservers(j)},j.reset=function(){j._texture!=null&&(j._displayingPosterTexture||(j._texture.dispose(),j._texture=null))},j._updateInternalTexture=function(){if(j._texture!=null&&!(j.video.readyState<j.video.HAVE_CURRENT_DATA)&&!j._displayingPosterTexture){var _e=j.getScene().getFrameId();j._frameId!==_e&&(j._frameId=_e,j._getEngine().updateVideoTexture(j._texture,j.video,j._invertY))}},b||(b={autoPlay:!0,loop:!0,autoUpdateTexture:!0}),j._onError=k,j._generateMipMaps=c,j._initialSamplingMode=_,j.autoUpdateTexture=b.autoUpdateTexture,j._currentSrc=o,j.name=e||j._getName(o),j.video=j._getVideo(o),j._settings=b,b.poster&&(j.video.poster=b.poster),b.autoPlay!==void 0&&(j.video.autoplay=b.autoPlay),b.loop!==void 0&&(j.video.loop=b.loop),b.muted!==void 0&&(j.video.muted=b.muted),j.video.setAttribute("playsinline",""),j.video.addEventListener("paused",j._updateInternalTexture),j.video.addEventListener("seeked",j._updateInternalTexture),j.video.addEventListener("emptied",j.reset),j._createInternalTextureOnEvent=b.poster&&!b.autoPlay?"play":"canplay",j.video.addEventListener(j._createInternalTextureOnEvent,j._createInternalTexture),b.autoPlay&&j._handlePlay();var $=j.video.readyState>=j.video.HAVE_CURRENT_DATA;return b.poster&&(!b.autoPlay||!$)?(j._texture=j._getEngine().createTexture(b.poster,!1,!j.invertY,s),j._displayingPosterTexture=!0):$&&j._createInternalTexture(),j}return Object.defineProperty(i.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new Observable),this._onUserActionRequestedObservable},enumerable:!1,configurable:!0}),i.prototype._processError=function(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):Logger$2.Error(e==null?void 0:e.message)},i.prototype._handlePlay=function(){var e=this;this._errorFound=!1,this.video.play().catch(function(o){if((o==null?void 0:o.name)==="NotAllowedError"){if(e._onUserActionRequestedObservable&&e._onUserActionRequestedObservable.hasObservers()){e._onUserActionRequestedObservable.notifyObservers(e);return}else if(!e.video.muted){Logger$2.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),e.video.muted=!0,e._errorFound=!1,e.video.play().catch(function(s){e._processError(s)});return}}e._processError(o)})},i.prototype.getClassName=function(){return"VideoTexture"},i.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:typeof e=="object"?e.toString():e},i.prototype._getVideo=function(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Tools.SetCorsBehavior(e.currentSrc,e),e;var o=document.createElement("video");return typeof e=="string"?(Tools.SetCorsBehavior(e,o),o.src=e):(Tools.SetCorsBehavior(e[0],o),e.forEach(function(s){var c=document.createElement("source");c.src=s,o.appendChild(c)})),o},i.prototype._rebuild=function(){this.update()},i.prototype.update=function(){!this.autoUpdateTexture||this.updateTexture(!0)},i.prototype.updateTexture=function(e){!e||this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture())},i.prototype.updateURL=function(e){this.video.src=e,this._currentSrc=e},i.prototype.clone=function(){return new i(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this.reset),this.video.pause()},i.CreateFromStreamAsync=function(e,o,s,c){c===void 0&&(c=!0);var d=e.getEngine().createVideoElement(s);return e.getEngine()._badOS&&(document.body.appendChild(d),d.style.transform="scale(0.0001, 0.0001)",d.style.opacity="0",d.style.position="fixed",d.style.bottom="0px",d.style.right="0px"),d.setAttribute("autoplay",""),d.setAttribute("muted","true"),d.setAttribute("playsinline",""),d.muted=!0,d.mozSrcObject!==void 0?d.mozSrcObject=o:typeof d.srcObject=="object"?d.srcObject=o:(window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,d.src=window.URL&&window.URL.createObjectURL(o)),new Promise(function(_){var b=function(){_(new i("video",d,e,!0,c)),d.removeEventListener("playing",b)};d.addEventListener("playing",b),d.play()})},i.CreateFromWebCamAsync=function(e,o,s,c){var d=this;s===void 0&&(s=!1),c===void 0&&(c=!0);var _;if(o&&o.deviceId&&(_={exact:o.deviceId}),navigator.mediaDevices)return navigator.mediaDevices.getUserMedia({video:o,audio:s}).then(function(k){return d.CreateFromStreamAsync(e,k,o,c)});var b=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;return b&&b({video:{deviceId:_,width:{min:o&&o.minWidth||256,max:o&&o.maxWidth||640},height:{min:o&&o.minHeight||256,max:o&&o.maxHeight||480}},audio:s},function(k){return d.CreateFromStreamAsync(e,k,o,c)},function(k){Logger$2.Error(k.name)}),Promise.reject("No support for userMedia on this device")},i.CreateFromWebCam=function(e,o,s,c,d){c===void 0&&(c=!1),d===void 0&&(d=!0),this.CreateFromWebCamAsync(e,s,c,d).then(function(_){o&&o(_)}).catch(function(_){Logger$2.Error(_.name)})},i}(Texture),Action=function(){function a(i,e){this.triggerOptions=i,this.onBeforeExecuteObservable=new Observable,i.parameter?(this.trigger=i.trigger,this._triggerParameter=i.parameter):i.trigger?this.trigger=i.trigger:this.trigger=i,this._nextActiveAction=this,this._condition=e}return a.prototype._prepare=function(){},a.prototype.getTriggerParameter=function(){return this._triggerParameter},a.prototype.setTriggerParameter=function(i){this._triggerParameter=i},a.prototype._evaluateConditionForCurrentFrame=function(){var i=this._condition;if(!i)return!0;var e=this._actionManager.getScene().getRenderId();return i._evaluationId!==e&&(i._evaluationId=e,i._currentResult=i.isValid()),i._currentResult},a.prototype._executeCurrent=function(i){var e=this._evaluateConditionForCurrentFrame();!e||(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(i),this.skipToNextActiveAction())},a.prototype.execute=function(i){},a.prototype.skipToNextActiveAction=function(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this},a.prototype.then=function(i){return this._child=i,i._actionManager=this._actionManager,i._prepare(),i},a.prototype._getProperty=function(i){return this._actionManager._getProperty(i)},a.prototype._getEffectiveTarget=function(i,e){return this._actionManager._getEffectiveTarget(i,e)},a.prototype.serialize=function(i){},a.prototype._serialize=function(i,e){var o={type:1,children:[],name:i.name,properties:i.properties||[]};if(this._child&&this._child.serialize(o),this._condition){var s=this._condition.serialize();return s.children.push(o),e&&e.children.push(s),s}return e&&e.children.push(o),o},a._SerializeValueAsString=function(i){return typeof i=="number"?i.toString():typeof i=="boolean"?i?"true":"false":i instanceof Vector2?i.x+", "+i.y:i instanceof Vector3?i.x+", "+i.y+", "+i.z:i instanceof Color3?i.r+", "+i.g+", "+i.b:i instanceof Color4?i.r+", "+i.g+", "+i.b+", "+i.a:i},a._GetTargetProperty=function(i){return{name:"target",targetType:i._isMesh?"MeshProperties":i._isLight?"LightProperties":i._isCamera?"CameraProperties":"SceneProperties",value:i._isScene?"Scene":i.name}},a}();RegisterClass("BABYLON.Action",Action);var Condition=function(){function a(i){this._actionManager=i}return a.prototype.isValid=function(){return!0},a.prototype._getProperty=function(i){return this._actionManager._getProperty(i)},a.prototype._getEffectiveTarget=function(i,e){return this._actionManager._getEffectiveTarget(i,e)},a.prototype.serialize=function(){},a.prototype._serialize=function(i){return{type:2,children:[],name:i.name,properties:i.properties}},a}(),ValueCondition=function(a){__extends(i,a);function i(e,o,s,c,d){d===void 0&&(d=i.IsEqual);var _=a.call(this,e)||this;return _.propertyPath=s,_.value=c,_.operator=d,_._target=o,_._effectiveTarget=_._getEffectiveTarget(o,_.propertyPath),_._property=_._getProperty(_.propertyPath),_}return Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!1,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!1,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!1,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!1,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]<this.value;case i.IsEqual:case i.IsDifferent:var e;return this.value.equals?e=this.value.equals(this._effectiveTarget[this._property]):e=this.value===this._effectiveTarget[this._property],this.operator===i.IsEqual?e:!e}return!1},i.prototype.serialize=function(){return this._serialize({name:"ValueCondition",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)},{name:"operator",value:i.GetOperatorName(this.operator)}]})},i.GetOperatorName=function(e){switch(e){case i._IsEqual:return"IsEqual";case i._IsDifferent:return"IsDifferent";case i._IsGreater:return"IsGreater";case i._IsLesser:return"IsLesser";default:return""}},i._IsEqual=0,i._IsDifferent=1,i._IsGreater=2,i._IsLesser=3,i}(Condition),PredicateCondition=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e)||this;return s.predicate=o,s}return i.prototype.isValid=function(){return this.predicate()},i}(Condition),StateCondition=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e)||this;return c.value=s,c._target=o,c}return i.prototype.isValid=function(){return this._target.state===this.value},i.prototype.serialize=function(){return this._serialize({name:"StateCondition",properties:[Action._GetTargetProperty(this._target),{name:"value",value:this.value}]})},i}(Condition);RegisterClass("BABYLON.ValueCondition",ValueCondition);RegisterClass("BABYLON.PredicateCondition",PredicateCondition);RegisterClass("BABYLON.StateCondition",StateCondition);(function(a){__extends(i,a);function i(e,o,s,c){var d=a.call(this,e,c)||this;return d.propertyPath=s,d._target=d._effectiveTarget=o,d}return i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"SwitchBooleanAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)},i})(Action);var SetStateAction=function(a){__extends(i,a);function i(e,o,s,c){var d=a.call(this,e,c)||this;return d.value=s,d._target=o,d}return i.prototype.execute=function(){this._target.state=this.value},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"SetStateAction",properties:[Action._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)},i}(Action),SetValueAction=function(a){__extends(i,a);function i(e,o,s,c,d){var _=a.call(this,e,d)||this;return _.propertyPath=s,_.value=c,_._target=_._effectiveTarget=o,_}return i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"SetValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)},i}(Action),IncrementValueAction=function(a){__extends(i,a);function i(e,o,s,c,d){var _=a.call(this,e,d)||this;return _.propertyPath=s,_.value=c,_._target=_._effectiveTarget=o,_}return i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),typeof this._effectiveTarget[this._property]!="number"&&Logger$2.Warn("Warning: IncrementValueAction can only be used with number values")},i.prototype.execute=function(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"IncrementValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)},i}(Action),PlayAnimationAction=function(a){__extends(i,a);function i(e,o,s,c,d,_){var b=a.call(this,e,_)||this;return b.from=s,b.to=c,b.loop=d,b._target=o,b}return i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"PlayAnimationAction",properties:[Action._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Action._SerializeValueAsString(this.loop)||!1}]},e)},i}(Action),StopAnimationAction=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,s)||this;return c._target=o,c}return i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.stopAnimation(this._target)},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"StopAnimationAction",properties:[Action._GetTargetProperty(this._target)]},e)},i}(Action),DoNothingAction=function(a){__extends(i,a);function i(e,o){return e===void 0&&(e=0),a.call(this,e,o)||this}return i.prototype.execute=function(){},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"DoNothingAction",properties:[]},e)},i}(Action);(function(a){__extends(i,a);function i(e,o,s,c){c===void 0&&(c=!0);var d=a.call(this,e,s)||this;return d.children=o,d.enableChildrenConditions=c,d}return i.prototype._prepare=function(){for(var e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()},i.prototype.execute=function(e){for(var o=0,s=this.children;o<s.length;o++){var c=s[o];(!this.enableChildrenConditions||c._evaluateConditionForCurrentFrame())&&c.execute(e)}},i.prototype.serialize=function(e){for(var o=a.prototype._serialize.call(this,{name:"CombineAction",properties:[],combine:[]},e),s=0;s<this.children.length;s++)o.combine.push(this.children[s].serialize(null));return o},i})(Action);var ExecuteCodeAction=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,s)||this;return c.func=o,c}return i.prototype.execute=function(e){this.func(e)},i}(Action),SetParentAction=function(a){__extends(i,a);function i(e,o,s,c){var d=a.call(this,e,c)||this;return d._target=o,d._parent=s,d}return i.prototype._prepare=function(){},i.prototype.execute=function(){if(this._target.parent!==this._parent){var e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=Vector3.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}},i.prototype.serialize=function(e){return a.prototype._serialize.call(this,{name:"SetParentAction",properties:[Action._GetTargetProperty(this._target),Action._GetTargetProperty(this._parent)]},e)},i}(Action);RegisterClass("BABYLON.SetParentAction",SetParentAction);RegisterClass("BABYLON.ExecuteCodeAction",ExecuteCodeAction);RegisterClass("BABYLON.DoNothingAction",DoNothingAction);RegisterClass("BABYLON.StopAnimationAction",StopAnimationAction);RegisterClass("BABYLON.PlayAnimationAction",PlayAnimationAction);RegisterClass("BABYLON.IncrementValueAction",IncrementValueAction);RegisterClass("BABYLON.SetValueAction",SetValueAction);RegisterClass("BABYLON.SetStateAction",SetStateAction);RegisterClass("BABYLON.SetParentAction",SetParentAction);var ActionManager=function(a){__extends(i,a);function i(e){var o=a.call(this)||this;return o._scene=e||EngineStore.LastCreatedScene,e.actionManagers.push(o),o}return i.prototype.dispose=function(){for(var e=this._scene.actionManagers.indexOf(this),o=0;o<this.actions.length;o++){var s=this.actions[o];i.Triggers[s.trigger]--,i.Triggers[s.trigger]===0&&delete i.Triggers[s.trigger]}e>-1&&this._scene.actionManagers.splice(e,1)},i.prototype.getScene=function(){return this._scene},i.prototype.hasSpecificTriggers=function(e){for(var o=0;o<this.actions.length;o++){var s=this.actions[o];if(e.indexOf(s.trigger)>-1)return!0}return!1},i.prototype.hasSpecificTriggers2=function(e,o){for(var s=0;s<this.actions.length;s++){var c=this.actions[s];if(e==c.trigger||o==c.trigger)return!0}return!1},i.prototype.hasSpecificTrigger=function(e,o){for(var s=0;s<this.actions.length;s++){var c=this.actions[s];if(c.trigger===e)if(o){if(o(c.getTriggerParameter()))return!0}else return!0}return!1},Object.defineProperty(i.prototype,"hasPointerTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var o=this.actions[e];if(o.trigger>=i.OnPickTrigger&&o.trigger<=i.OnPointerOutTrigger)return!0}return!1},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasPickTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var o=this.actions[e];if(o.trigger>=i.OnPickTrigger&&o.trigger<=i.OnPickUpTrigger)return!0}return!1},enumerable:!1,configurable:!0}),i.prototype.registerAction=function(e){return e.trigger===i.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(Logger$2.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),i.Triggers[e.trigger]?i.Triggers[e.trigger]++:i.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)},i.prototype.unregisterAction=function(e){var o=this.actions.indexOf(e);return o!==-1?(this.actions.splice(o,1),i.Triggers[e.trigger]-=1,i.Triggers[e.trigger]===0&&delete i.Triggers[e.trigger],e._actionManager=null,!0):!1},i.prototype.processTrigger=function(e,o){for(var s=0;s<this.actions.length;s++){var c=this.actions[s];if(c.trigger===e){if(o&&(e===i.OnKeyUpTrigger||e===i.OnKeyDownTrigger)){var d=c.getTriggerParameter();if(d&&d!==o.sourceEvent.keyCode){if(!d.toLowerCase)continue;var _=d.toLowerCase();if(_!==o.sourceEvent.key){var b=o.sourceEvent.charCode?o.sourceEvent.charCode:o.sourceEvent.keyCode,k=String.fromCharCode(b).toLowerCase();if(k!==_)continue}}}c._executeCurrent(o)}}},i.prototype._getEffectiveTarget=function(e,o){for(var s=o.split("."),c=0;c<s.length-1;c++)e=e[s[c]];return e},i.prototype._getProperty=function(e){var o=e.split(".");return o[o.length-1]},i.prototype.serialize=function(e){for(var o={children:new Array,name:e,type:3,properties:new Array},s=0;s<this.actions.length;s++){var c={type:0,children:new Array,name:i.GetTriggerName(this.actions[s].trigger),properties:new Array},d=this.actions[s].triggerOptions;if(d&&typeof d!="number")if(d.parameter instanceof Node)c.properties.push(Action._GetTargetProperty(d.parameter));else{var _={};DeepCopier.DeepCopy(d.parameter,_,["mesh"]),d.parameter&&d.parameter.mesh&&(_._meshId=d.parameter.mesh.id),c.properties.push({name:"parameter",targetType:null,value:_})}this.actions[s].serialize(c),o.children.push(c)}return o},i.Parse=function(e,o,s){var c=new i(s);o===null?s.actionManager=c:o.actionManager=c;for(var d=function(rt,it){var nt=GetClass("BABYLON."+rt);if(nt){var ot=Object.create(nt.prototype);return ot.constructor.apply(ot,it),ot}},_=function(rt,it,nt,ot){if(ot===null){var at=parseFloat(it);return it==="true"||it==="false"?it==="true":isNaN(at)?it:at}for(var st=ot.split("."),ut=it.split(","),ft=0;ft<st.length;ft++)nt=nt[st[ft]];if(typeof nt=="boolean")return ut[0]==="true";if(typeof nt=="string")return ut[0];for(var lt=new Array,ft=0;ft<ut.length;ft++)lt.push(parseFloat(ut[ft]));return nt instanceof Vector3?Vector3.FromArray(lt):nt instanceof Vector4?Vector4.FromArray(lt):nt instanceof Color3?Color3.FromArray(lt):nt instanceof Color4?Color4.FromArray(lt):parseFloat(ut[0])},b=function(rt,it,nt,ot,at){if(at===void 0&&(at=null),!rt.detached){var st=new Array,ut=null,ft=null,lt=rt.combine&&rt.combine.length>0;if(rt.type===2?st.push(c):st.push(it),lt){for(var ht=new Array,pt=0;pt<rt.combine.length;pt++)b(rt.combine[pt],i.NothingTrigger,nt,ot,ht);st.push(ht)}else for(var mt=0;mt<rt.properties.length;mt++){var dt=rt.properties[mt].value,gt=rt.properties[mt].name,_t=rt.properties[mt].targetType;gt==="target"?_t!==null&&_t==="SceneProperties"?dt=ut=s:dt=ut=s.getNodeByName(dt):gt==="parent"?dt=s.getNodeByName(dt):gt==="sound"?s.getSoundByName&&(dt=s.getSoundByName(dt)):gt!=="propertyPath"?rt.type===2&&gt==="operator"?dt=ValueCondition[dt]:dt=_(gt,dt,ut,gt==="value"?ft:null):ft=dt,st.push(dt)}if(at===null?st.push(nt):st.push(null),rt.name==="InterpolateValueAction"){var yt=st[st.length-2];st[st.length-1]=yt,st[st.length-2]=nt}var Tt=d(rt.name,st);if(Tt instanceof Condition&&nt!==null){var St=new DoNothingAction(it,nt);ot?ot.then(St):c.registerAction(St),ot=St}at===null?Tt instanceof Condition?(nt=Tt,Tt=ot):(nt=null,ot?ot.then(Tt):c.registerAction(Tt)):at.push(Tt);for(var mt=0;mt<rt.children.length;mt++)b(rt.children[mt],it,nt,Tt,null)}},k=0;k<e.children.length;k++){var j,$=e.children[k];if($.properties.length>0){var _e=$.properties[0].value,et=$.properties[0].targetType===null?_e:s.getMeshByName(_e);et._meshId&&(et.mesh=s.getMeshById(et._meshId)),j={trigger:i[$.name],parameter:et}}else j=i[$.name];for(var tt=0;tt<$.children.length;tt++)$.detached||b($.children[tt],j,null,null)}},i.GetTriggerName=function(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnPickUpTrigger";case 7:return"OnLongPressTrigger";case 8:return"OnPointerOverTrigger";case 9:return"OnPointerOutTrigger";case 10:return"OnEveryFrameTrigger";case 11:return"OnIntersectionEnterTrigger";case 12:return"OnIntersectionExitTrigger";case 13:return"OnKeyDownTrigger";case 14:return"OnKeyUpTrigger";case 15:return"OnPickOutTrigger";default:return""}},i.NothingTrigger=0,i.OnPickTrigger=1,i.OnLeftPickTrigger=2,i.OnRightPickTrigger=3,i.OnCenterPickTrigger=4,i.OnPickDownTrigger=5,i.OnDoublePickTrigger=6,i.OnPickUpTrigger=7,i.OnPickOutTrigger=16,i.OnLongPressTrigger=8,i.OnPointerOverTrigger=9,i.OnPointerOutTrigger=10,i.OnEveryFrameTrigger=11,i.OnIntersectionEnterTrigger=12,i.OnIntersectionExitTrigger=13,i.OnKeyDownTrigger=14,i.OnKeyUpTrigger=15,i}(AbstractActionManager);Node$2.AddNodeConstructor("Light_Type_0",function(a,i){return function(){return new PointLight(a,Vector3.Zero(),i)}});var PointLight=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,s)||this;return c._shadowAngle=Math.PI/2,c.position=o,c}return Object.defineProperty(i.prototype,"shadowAngle",{get:function(){return this._shadowAngle},set:function(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"direction",{get:function(){return this._direction},set:function(e){var o=this.needCube();this._direction=e,this.needCube()!==o&&this._shadowGenerator&&this._shadowGenerator.recreateShadowMap()},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"PointLight"},i.prototype.getTypeID=function(){return Light.LIGHTTYPEID_POINTLIGHT},i.prototype.needCube=function(){return!this.direction},i.prototype.getShadowDirection=function(e){if(this.direction)return a.prototype.getShadowDirection.call(this,e);switch(e){case 0:return new Vector3(1,0,0);case 1:return new Vector3(-1,0,0);case 2:return new Vector3(0,-1,0);case 3:return new Vector3(0,1,0);case 4:return new Vector3(0,0,1);case 5:return new Vector3(0,0,-1)}return Vector3.Zero()},i.prototype._setDefaultShadowProjectionMatrix=function(e,o,s){var c=this.getScene().activeCamera;if(!!c){var d=this.shadowMinZ!==void 0?this.shadowMinZ:c.minZ,_=this.shadowMaxZ!==void 0?this.shadowMaxZ:c.maxZ,b=this.getScene().getEngine().useReverseDepthBuffer;Matrix.PerspectiveFovLHToRef(this.shadowAngle,1,b?_:d,b?d:_,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,b)}},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype.transferToEffect=function(e,o){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,o):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,o),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,o),this},i.prototype.transferToNodeMaterialEffect=function(e,o){return this.computeTransformedInformation()?e.setFloat3(o,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(o,this.position.x,this.position.y,this.position.z),this},i.prototype.prepareLightSpecificDefines=function(e,o){e["POINTLIGHT"+o]=!0},__decorate([serialize()],i.prototype,"shadowAngle",null),i}(ShadowLight);function CreateRibbonVertexData(a){var i=a.pathArray,e=a.closeArray||!1,o=a.closePath||!1,s=a.invertUV||!1,c=Math.floor(i[0].length/2),d=a.offset||c;d=d>c?c:Math.floor(d);var _=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,b=a.uvs,k=a.colors,j=[],$=[],_e=[],et=[],tt=[],rt=[],it=[],nt=[],ot,at=[],st=[],ut,ft,lt;if(i.length<2){var ht=[],pt=[];for(ft=0;ft<i[0].length-d;ft++)ht.push(i[0][ft]),pt.push(i[0][ft+d]);i=[ht,pt]}var mt=0,dt=o?1:0,gt,_t;ot=i[0].length;var yt,Tt;for(ut=0;ut<i.length;ut++){for(it[ut]=0,tt[ut]=[0],gt=i[ut],_t=gt.length,ot=ot<_t?ot:_t,lt=0;lt<_t;)j.push(gt[lt].x,gt[lt].y,gt[lt].z),lt>0&&(yt=gt[lt].subtract(gt[lt-1]).length(),Tt=yt+it[ut],tt[ut].push(Tt),it[ut]=Tt),lt++;o&&(lt--,j.push(gt[0].x,gt[0].y,gt[0].z),yt=gt[lt].subtract(gt[0]).length(),Tt=yt+it[ut],tt[ut].push(Tt),it[ut]=Tt),at[ut]=_t+dt,st[ut]=mt,mt+=_t+dt}var St,At,vt=null,Et=null;for(ft=0;ft<ot+dt;ft++){for(nt[ft]=0,rt[ft]=[0],ut=0;ut<i.length-1;ut++)St=i[ut],At=i[ut+1],ft===ot?(vt=St[0],Et=At[0]):(vt=St[ft],Et=At[ft]),yt=Et.subtract(vt).length(),Tt=yt+nt[ft],rt[ft].push(Tt),nt[ft]=Tt;e&&Et&&vt&&(St=i[ut],At=i[0],ft===ot&&(Et=At[0]),yt=Et.subtract(vt).length(),Tt=yt+nt[ft],nt[ft]=Tt)}var xt,bt;if(b)for(ut=0;ut<b.length;ut++)et.push(b[ut].x,b[ut].y);else for(ut=0;ut<i.length;ut++)for(ft=0;ft<ot+dt;ft++)xt=it[ut]!=0?tt[ut][ft]/it[ut]:0,bt=nt[ft]!=0?rt[ft][ut]/nt[ft]:0,s?et.push(bt,xt):et.push(xt,bt);ut=0;for(var Mt=0,Rt=at[ut]-1,Pt=at[ut+1]-1,It=Rt<Pt?Rt:Pt,Dt=st[1]-st[0],Ct=e?at.length:at.length-1;Mt<=It&&ut<Ct;)$.push(Mt,Mt+Dt,Mt+1),$.push(Mt+Dt+1,Mt+1,Mt+Dt),Mt+=1,Mt===It&&(ut++,ut===at.length-1?(Dt=st[0]-st[ut],Rt=at[ut]-1,Pt=at[0]-1):(Dt=st[ut+1]-st[ut],Rt=at[ut]-1,Pt=at[ut+1]-1),Mt=st[ut],It=Rt<Pt?Rt+Mt:Pt+Mt);if(VertexData.ComputeNormals(j,$,_e),o){var Ot=0,Ft=0;for(ut=0;ut<i.length;ut++)Ot=st[ut]*3,ut+1<i.length?Ft=(st[ut+1]-1)*3:Ft=_e.length-3,_e[Ot]=(_e[Ot]+_e[Ft])*.5,_e[Ot+1]=(_e[Ot+1]+_e[Ft+1])*.5,_e[Ot+2]=(_e[Ot+2]+_e[Ft+2])*.5,_e[Ft]=_e[Ot],_e[Ft+1]=_e[Ot+1],_e[Ft+2]=_e[Ot+2]}VertexData._ComputeSides(_,j,$,_e,et,a.frontUVs,a.backUVs);var wt=null;if(k){wt=new Float32Array(k.length*4);for(var Bt=0;Bt<k.length;Bt++)wt[Bt*4]=k[Bt].r,wt[Bt*4+1]=k[Bt].g,wt[Bt*4+2]=k[Bt].b,wt[Bt*4+3]=k[Bt].a}var Ut=new VertexData,Vt=new Float32Array(j),Gt=new Float32Array(_e),Lt=new Float32Array(et);return Ut.indices=$,Ut.positions=Vt,Ut.normals=Gt,Ut.uvs=Lt,wt&&Ut.set(wt,VertexBuffer.ColorKind),o&&(Ut._idx=st),Ut}function CreateRibbon(a,i,e){e===void 0&&(e=null);var o=i.pathArray,s=i.closeArray,c=i.closePath,d=Mesh._GetDefaultSideOrientation(i.sideOrientation),_=i.instance,b=i.updatable;if(_){var k=TmpVectors.Vector3[0].setAll(Number.MAX_VALUE),j=TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE),$=function(dt){for(var gt=o[0].length,_t=_,yt=0,Tt=_t._originalBuilderSideOrientation===Mesh.DOUBLESIDE?2:1,St=1;St<=Tt;++St)for(var At=0;At<o.length;++At){var vt=o[At],Et=vt.length;gt=gt<Et?gt:Et;for(var xt=0;xt<gt;++xt){var bt=vt[xt];dt[yt]=bt.x,dt[yt+1]=bt.y,dt[yt+2]=bt.z,k.minimizeInPlaceFromFloats(bt.x,bt.y,bt.z),j.maximizeInPlaceFromFloats(bt.x,bt.y,bt.z),yt+=3}if(_t._creationDataStorage&&_t._creationDataStorage.closePath){var bt=vt[0];dt[yt]=bt.x,dt[yt+1]=bt.y,dt[yt+2]=bt.z,yt+=3}}},_e=_.getVerticesData(VertexBuffer.PositionKind);if($(_e),_.hasBoundingInfo?_.getBoundingInfo().reConstruct(k,j,_._worldMatrix):_.buildBoundingInfo(k,j,_._worldMatrix),_.updateVerticesData(VertexBuffer.PositionKind,_e,!1,!1),i.colors){for(var et=_.getVerticesData(VertexBuffer.ColorKind),tt=0,rt=0;tt<i.colors.length;tt++,rt+=4){var it=i.colors[tt];et[rt]=it.r,et[rt+1]=it.g,et[rt+2]=it.b,et[rt+3]=it.a}_.updateVerticesData(VertexBuffer.ColorKind,et,!1,!1)}if(i.uvs){for(var nt=_.getVerticesData(VertexBuffer.UVKind),ot=0;ot<i.uvs.length;ot++)nt[ot*2]=i.uvs[ot].x,nt[ot*2+1]=i.uvs[ot].y;_.updateVerticesData(VertexBuffer.UVKind,nt,!1,!1)}if(!_.areNormalsFrozen||_.isFacetDataEnabled){var at=_.getIndices(),st=_.getVerticesData(VertexBuffer.NormalKind),ut=_.isFacetDataEnabled?_.getFacetDataParameters():null;if(VertexData.ComputeNormals(_e,at,st,ut),_._creationDataStorage&&_._creationDataStorage.closePath)for(var ft=0,lt=0,ht=0;ht<o.length;ht++)ft=_._creationDataStorage.idx[ht]*3,ht+1<o.length?lt=(_._creationDataStorage.idx[ht+1]-1)*3:lt=st.length-3,st[ft]=(st[ft]+st[lt])*.5,st[ft+1]=(st[ft+1]+st[lt+1])*.5,st[ft+2]=(st[ft+2]+st[lt+2])*.5,st[lt]=st[ft],st[lt+1]=st[ft+1],st[lt+2]=st[ft+2];_.areNormalsFrozen||_.updateVerticesData(VertexBuffer.NormalKind,st,!1,!1)}return _}else{var pt=new Mesh(a,e);pt._originalBuilderSideOrientation=d,pt._creationDataStorage=new _CreationDataStorage;var mt=CreateRibbonVertexData(i);return c&&(pt._creationDataStorage.idx=mt._idx),pt._creationDataStorage.closePath=c,pt._creationDataStorage.closeArray=s,mt.applyToMesh(pt,b),pt}}VertexData.CreateRibbon=CreateRibbonVertexData;Mesh.CreateRibbon=function(a,i,e,o,s,c,d,_,b){return e===void 0&&(e=!1),d===void 0&&(d=!1),CreateRibbon(a,{pathArray:i,closeArray:e,closePath:o,offset:s,updatable:d,sideOrientation:_,instance:b},c)};function CreateDiscVertexData(a){var i=new Array,e=new Array,o=new Array,s=new Array,c=a.radius||.5,d=a.tessellation||64,_=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,b=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE;i.push(0,0,0),s.push(.5,.5);for(var k=Math.PI*2*_,j=_===1?k/d:k/(d-1),$=0,_e=0;_e<d;_e++){var et=Math.cos($),tt=Math.sin($),rt=(et+1)/2,it=(1-tt)/2;i.push(c*et,c*tt,0),s.push(rt,it),$+=j}_===1&&(i.push(i[3],i[4],i[5]),s.push(s[2],s[3]));for(var nt=i.length/3,ot=1;ot<nt-1;ot++)e.push(ot+1,0,ot);VertexData.ComputeNormals(i,e,o),VertexData._ComputeSides(b,i,e,o,s,a.frontUVs,a.backUVs);var at=new VertexData;return at.indices=e,at.positions=i,at.normals=o,at.uvs=s,at}function CreateDisc(a,i,e){i===void 0&&(i={}),e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateDiscVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateDisc=CreateDiscVertexData;Mesh.CreateDisc=function(a,i,e,o,s,c){o===void 0&&(o=null);var d={radius:i,tessellation:e,sideOrientation:c,updatable:s};return CreateDisc(a,d,o)};function CreateBoxVertexData(a){var i=6,e=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23],o=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[],c=[],d=a.width||a.size||1,_=a.height||a.size||1,b=a.depth||a.size||1,k=a.wrap||!1,j=a.topBaseAt===void 0?1:a.topBaseAt,$=a.bottomBaseAt===void 0?0:a.bottomBaseAt;j=(j+4)%4,$=($+4)%4;var _e=[2,0,3,1],et=[2,0,1,3],tt=_e[j],rt=et[$],it=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(k){e=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],it=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];for(var nt=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],ot=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],at=[17,18,19,16],st=[22,23,20,21];tt>0;)nt.unshift(nt.pop()),at.unshift(at.pop()),tt--;for(;rt>0;)ot.unshift(ot.pop()),st.unshift(st.pop()),rt--;nt=nt.flat(),ot=ot.flat(),it=it.concat(nt).concat(ot),e.push(at[0],at[2],at[3],at[0],at[1],at[2]),e.push(st[0],st[2],st[3],st[0],st[1],st[2])}var ut=[d/2,_/2,b/2];c=it.reduce(function(Tt,St,At){return Tt.concat(St*ut[At%3])},[]);for(var ft=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,lt=a.faceUV||new Array(6),ht=a.faceColors,pt=[],mt=0;mt<6;mt++)lt[mt]===void 0&&(lt[mt]=new Vector4(0,0,1,1)),ht&&ht[mt]===void 0&&(ht[mt]=new Color4(1,1,1,1));for(var dt=0;dt<i;dt++)if(s.push(lt[dt].z,lt[dt].w),s.push(lt[dt].x,lt[dt].w),s.push(lt[dt].x,lt[dt].y),s.push(lt[dt].z,lt[dt].y),ht)for(var gt=0;gt<4;gt++)pt.push(ht[dt].r,ht[dt].g,ht[dt].b,ht[dt].a);VertexData._ComputeSides(ft,c,e,o,s,a.frontUVs,a.backUVs);var _t=new VertexData;if(_t.indices=e,_t.positions=c,_t.normals=o,_t.uvs=s,ht){var yt=ft===VertexData.DOUBLESIDE?pt.concat(pt):pt;_t.colors=yt}return _t}function CreateBox(a,i,e){i===void 0&&(i={}),e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateBoxVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateBox=CreateBoxVertexData;Mesh.CreateBox=function(a,i,e,o,s){e===void 0&&(e=null);var c={size:i,sideOrientation:s,updatable:o};return CreateBox(a,c,e)};function CreateTiledPlaneVertexData(a){var i=a.pattern||Mesh.NO_FLIP,e=a.tileWidth||a.tileSize||1,o=a.tileHeight||a.tileSize||1,s=a.alignHorizontal||0,c=a.alignVertical||0,d=a.width||a.size||1,_=Math.floor(d/e),b=d-_*e,k=a.height||a.size||1,j=Math.floor(k/o),$=k-j*o,_e=e*_/2,et=o*j/2,tt=0,rt=0,it=0,nt=0,ot=0,at=0;if(b>0||$>0){it=-_e,nt=-et;var ot=_e,at=et;switch(s){case Mesh.CENTER:b/=2,it-=b,ot+=b;break;case Mesh.LEFT:ot+=b,tt=-b/2;break;case Mesh.RIGHT:it-=b,tt=b/2;break}switch(c){case Mesh.CENTER:$/=2,nt-=$,at+=$;break;case Mesh.BOTTOM:at+=$,rt=-$/2;break;case Mesh.TOP:nt-=$,rt=$/2;break}}var st=[],ut=[],ft=[];ft[0]=[0,0,1,0,1,1,0,1],ft[1]=[0,0,1,0,1,1,0,1],(i===Mesh.ROTATE_TILE||i===Mesh.ROTATE_ROW)&&(ft[1]=[1,1,0,1,0,0,1,0]),(i===Mesh.FLIP_TILE||i===Mesh.FLIP_ROW)&&(ft[1]=[1,0,0,0,0,1,1,1]),(i===Mesh.FLIP_N_ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_ROW)&&(ft[1]=[0,1,1,1,1,0,0,0]);for(var lt=[],ht=[],pt=[],mt=0,dt=0;dt<j;dt++)for(var gt=0;gt<_;gt++)st.push(-_e+gt*e+tt,-et+dt*o+rt,0),st.push(-_e+(gt+1)*e+tt,-et+dt*o+rt,0),st.push(-_e+(gt+1)*e+tt,-et+(dt+1)*o+rt,0),st.push(-_e+gt*e+tt,-et+(dt+1)*o+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),i===Mesh.FLIP_TILE||i===Mesh.ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_TILE?lt=lt.concat(ft[(gt%2+dt%2)%2]):i===Mesh.FLIP_ROW||i===Mesh.ROTATE_ROW||i===Mesh.FLIP_N_ROTATE_ROW?lt=lt.concat(ft[dt%2]):lt=lt.concat(ft[0]),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),mt+=4;if(b>0||$>0){var _t=$>0&&(c===Mesh.CENTER||c===Mesh.TOP),yt=$>0&&(c===Mesh.CENTER||c===Mesh.BOTTOM),Tt=b>0&&(s===Mesh.CENTER||s===Mesh.RIGHT),St=b>0&&(s===Mesh.CENTER||s===Mesh.LEFT),At=[],vt,Et,xt,bt;if(_t&&Tt&&(st.push(it+tt,nt+rt,0),st.push(-_e+tt,nt+rt,0),st.push(-_e+tt,nt+$+rt,0),st.push(it+tt,nt+$+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,vt=1-b/e,Et=1-$/o,xt=1,bt=1,At=[vt,Et,xt,Et,xt,bt,vt,bt],i===Mesh.ROTATE_ROW&&(At=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),i===Mesh.FLIP_ROW&&(At=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),i===Mesh.FLIP_N_ROTATE_ROW&&(At=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]),lt=lt.concat(At),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),_t&&St&&(st.push(_e+tt,nt+rt,0),st.push(ot+tt,nt+rt,0),st.push(ot+tt,nt+$+rt,0),st.push(_e+tt,nt+$+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,vt=0,Et=1-$/o,xt=b/e,bt=1,At=[vt,Et,xt,Et,xt,bt,vt,bt],(i===Mesh.ROTATE_ROW||i===Mesh.ROTATE_TILE&&_%2===0)&&(At=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),(i===Mesh.FLIP_ROW||i===Mesh.FLIP_TILE&&_%2===0)&&(At=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),(i===Mesh.FLIP_N_ROTATE_ROW||i===Mesh.FLIP_N_ROTATE_TILE&&_%2===0)&&(At=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]),lt=lt.concat(At),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),yt&&Tt&&(st.push(it+tt,et+rt,0),st.push(-_e+tt,et+rt,0),st.push(-_e+tt,at+rt,0),st.push(it+tt,at+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,vt=1-b/e,Et=0,xt=1,bt=$/o,At=[vt,Et,xt,Et,xt,bt,vt,bt],(i===Mesh.ROTATE_ROW&&j%2===1||i===Mesh.ROTATE_TILE&&j%1===0)&&(At=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),(i===Mesh.FLIP_ROW&&j%2===1||i===Mesh.FLIP_TILE&&j%2===0)&&(At=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),(i===Mesh.FLIP_N_ROTATE_ROW&&j%2===1||i===Mesh.FLIP_N_ROTATE_TILE&&j%2===0)&&(At=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]),lt=lt.concat(At),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),yt&&St&&(st.push(_e+tt,et+rt,0),st.push(ot+tt,et+rt,0),st.push(ot+tt,at+rt,0),st.push(_e+tt,at+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,vt=0,Et=0,xt=b/e,bt=$/o,At=[vt,Et,xt,Et,xt,bt,vt,bt],(i===Mesh.ROTATE_ROW&&j%2===1||i===Mesh.ROTATE_TILE&&(j+_)%2===1)&&(At=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),(i===Mesh.FLIP_ROW&&j%2===1||i===Mesh.FLIP_TILE&&(j+_)%2===1)&&(At=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),(i===Mesh.FLIP_N_ROTATE_ROW&&j%2===1||i===Mesh.FLIP_N_ROTATE_TILE&&(j+_)%2===1)&&(At=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]),lt=lt.concat(At),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),_t){var Mt=[];vt=0,Et=1-$/o,xt=1,bt=1,Mt[0]=[vt,Et,xt,Et,xt,bt,vt,bt],Mt[1]=[vt,Et,xt,Et,xt,bt,vt,bt],(i===Mesh.ROTATE_TILE||i===Mesh.ROTATE_ROW)&&(Mt[1]=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),(i===Mesh.FLIP_TILE||i===Mesh.FLIP_ROW)&&(Mt[1]=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),(i===Mesh.FLIP_N_ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_ROW)&&(Mt[1]=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]);for(var gt=0;gt<_;gt++)st.push(-_e+gt*e+tt,nt+rt,0),st.push(-_e+(gt+1)*e+tt,nt+rt,0),st.push(-_e+(gt+1)*e+tt,nt+$+rt,0),st.push(-_e+gt*e+tt,nt+$+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,i===Mesh.FLIP_TILE||i===Mesh.ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_TILE?lt=lt.concat(Mt[(gt+1)%2]):i===Mesh.FLIP_ROW||i===Mesh.ROTATE_ROW||i===Mesh.FLIP_N_ROTATE_ROW?lt=lt.concat(Mt[1]):lt=lt.concat(Mt[0]),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(yt){var Rt=[];vt=0,Et=0,xt=1,bt=$/o,Rt[0]=[vt,Et,xt,Et,xt,bt,vt,bt],Rt[1]=[vt,Et,xt,Et,xt,bt,vt,bt],(i===Mesh.ROTATE_TILE||i===Mesh.ROTATE_ROW)&&(Rt[1]=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),(i===Mesh.FLIP_TILE||i===Mesh.FLIP_ROW)&&(Rt[1]=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),(i===Mesh.FLIP_N_ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_ROW)&&(Rt[1]=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]);for(var gt=0;gt<_;gt++)st.push(-_e+gt*e+tt,at-$+rt,0),st.push(-_e+(gt+1)*e+tt,at-$+rt,0),st.push(-_e+(gt+1)*e+tt,at+rt,0),st.push(-_e+gt*e+tt,at+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,i===Mesh.FLIP_TILE||i===Mesh.ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_TILE?lt=lt.concat(Rt[(gt+j)%2]):i===Mesh.FLIP_ROW||i===Mesh.ROTATE_ROW||i===Mesh.FLIP_N_ROTATE_ROW?lt=lt.concat(Rt[j%2]):lt=lt.concat(Rt[0]),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(Tt){var Pt=[];vt=1-b/e,Et=0,xt=1,bt=1,Pt[0]=[vt,Et,xt,Et,xt,bt,vt,bt],Pt[1]=[vt,Et,xt,Et,xt,bt,vt,bt],(i===Mesh.ROTATE_TILE||i===Mesh.ROTATE_ROW)&&(Pt[1]=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),(i===Mesh.FLIP_TILE||i===Mesh.FLIP_ROW)&&(Pt[1]=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),(i===Mesh.FLIP_N_ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_ROW)&&(Pt[1]=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]);for(var dt=0;dt<j;dt++)st.push(it+tt,-et+dt*o+rt,0),st.push(it+b+tt,-et+dt*o+rt,0),st.push(it+b+tt,-et+(dt+1)*o+rt,0),st.push(it+tt,-et+(dt+1)*o+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,i===Mesh.FLIP_TILE||i===Mesh.ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_TILE?lt=lt.concat(Pt[(dt+1)%2]):i===Mesh.FLIP_ROW||i===Mesh.ROTATE_ROW||i===Mesh.FLIP_N_ROTATE_ROW?lt=lt.concat(Pt[dt%2]):lt=lt.concat(Pt[0]),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(St){var It=[];vt=0,Et=0,xt=b/o,bt=1,It[0]=[vt,Et,xt,Et,xt,bt,vt,bt],It[1]=[vt,Et,xt,Et,xt,bt,vt,bt],(i===Mesh.ROTATE_TILE||i===Mesh.ROTATE_ROW)&&(It[1]=[1-vt,1-Et,1-xt,1-Et,1-xt,1-bt,1-vt,1-bt]),(i===Mesh.FLIP_TILE||i===Mesh.FLIP_ROW)&&(It[1]=[1-vt,Et,1-xt,Et,1-xt,bt,1-vt,bt]),(i===Mesh.FLIP_N_ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_ROW)&&(It[1]=[vt,1-Et,xt,1-Et,xt,1-bt,vt,1-bt]);for(var dt=0;dt<j;dt++)st.push(ot-b+tt,-et+dt*o+rt,0),st.push(ot+tt,-et+dt*o+rt,0),st.push(ot+tt,-et+(dt+1)*o+rt,0),st.push(ot-b+tt,-et+(dt+1)*o+rt,0),pt.push(mt,mt+1,mt+3,mt+1,mt+2,mt+3),mt+=4,i===Mesh.FLIP_TILE||i===Mesh.ROTATE_TILE||i===Mesh.FLIP_N_ROTATE_TILE?lt=lt.concat(It[(dt+_)%2]):i===Mesh.FLIP_ROW||i===Mesh.ROTATE_ROW||i===Mesh.FLIP_N_ROTATE_ROW?lt=lt.concat(It[dt%2]):lt=lt.concat(It[0]),ht.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),ut.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}var Dt=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE;VertexData._ComputeSides(Dt,st,pt,ut,lt,a.frontUVs,a.backUVs);var Ct=new VertexData;Ct.indices=pt,Ct.positions=st,Ct.normals=ut,Ct.uvs=lt;var Ot=Dt===VertexData.DOUBLESIDE?ht.concat(ht):ht;return Ct.colors=Ot,Ct}function CreateTiledPlane(a,i,e){e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateTiledPlaneVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateTiledPlane=CreateTiledPlaneVertexData;function CreateTiledBoxVertexData(a){for(var i=6,e=a.faceUV||new Array(6),o=a.faceColors,s=a.pattern||Mesh.NO_FLIP,c=a.width||a.size||1,d=a.height||a.size||1,_=a.depth||a.size||1,b=a.tileWidth||a.tileSize||1,k=a.tileHeight||a.tileSize||1,j=a.alignHorizontal||0,$=a.alignVertical||0,_e=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,et=0;et<i;et++)e[et]===void 0&&(e[et]=new Vector4(0,0,1,1)),o&&o[et]===void 0&&(o[et]=new Color4(1,1,1,1));for(var tt=c/2,rt=d/2,it=_/2,nt=[],et=0;et<2;et++)nt[et]=CreateTiledPlaneVertexData({pattern:s,tileWidth:b,tileHeight:k,width:c,height:d,alignVertical:$,alignHorizontal:j,sideOrientation:_e});for(var et=2;et<4;et++)nt[et]=CreateTiledPlaneVertexData({pattern:s,tileWidth:b,tileHeight:k,width:_,height:d,alignVertical:$,alignHorizontal:j,sideOrientation:_e});var ot=$;$===Mesh.BOTTOM?ot=Mesh.TOP:$===Mesh.TOP&&(ot=Mesh.BOTTOM);for(var et=4;et<6;et++)nt[et]=CreateTiledPlaneVertexData({pattern:s,tileWidth:b,tileHeight:k,width:c,height:_,alignVertical:ot,alignHorizontal:j,sideOrientation:_e});for(var at=[],st=[],ut=[],ft=[],lt=[],ht=[],pt=[],mt=[],dt=0,gt=0,_t=0,et=0;et<i;et++){var dt=nt[et].positions.length;ht[et]=[],pt[et]=[];for(var yt=0;yt<dt/3;yt++)ht[et].push(new Vector3(nt[et].positions[3*yt],nt[et].positions[3*yt+1],nt[et].positions[3*yt+2])),pt[et].push(new Vector3(nt[et].normals[3*yt],nt[et].normals[3*yt+1],nt[et].normals[3*yt+2]));gt=nt[et].uvs.length,mt[et]=[];for(var Tt=0;Tt<gt;Tt+=2)mt[et][Tt]=e[et].x+(e[et].z-e[et].x)*nt[et].uvs[Tt],mt[et][Tt+1]=e[et].y+(e[et].w-e[et].y)*nt[et].uvs[Tt+1];if(ut=ut.concat(mt[et]),ft=ft.concat(nt[et].indices.map(function(Ft){return Ft+_t})),_t+=ht[et].length,o)for(var St=0;St<4;St++)lt.push(o[et].r,o[et].g,o[et].b,o[et].a)}var At=new Vector3(0,0,it),vt=Matrix.RotationY(Math.PI);at=ht[0].map(function(Ct){return Vector3.TransformNormal(Ct,vt).add(At)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[]),st=pt[0].map(function(Ct){return Vector3.TransformNormal(Ct,vt)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[]),at=at.concat(ht[1].map(function(Ct){return Ct.subtract(At)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[])),st=st.concat(pt[1].map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[]));var Et=new Vector3(tt,0,0),xt=Matrix.RotationY(-Math.PI/2);at=at.concat(ht[2].map(function(Ct){return Vector3.TransformNormal(Ct,xt).add(Et)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[])),st=st.concat(pt[2].map(function(Ct){return Vector3.TransformNormal(Ct,xt)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[]));var bt=Matrix.RotationY(Math.PI/2);at=at.concat(ht[3].map(function(Ct){return Vector3.TransformNormal(Ct,bt).subtract(Et)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[])),st=st.concat(pt[3].map(function(Ct){return Vector3.TransformNormal(Ct,bt)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[]));var Mt=new Vector3(0,rt,0),Rt=Matrix.RotationX(Math.PI/2);at=at.concat(ht[4].map(function(Ct){return Vector3.TransformNormal(Ct,Rt).add(Mt)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[])),st=st.concat(pt[4].map(function(Ct){return Vector3.TransformNormal(Ct,Rt)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[]));var Pt=Matrix.RotationX(-Math.PI/2);at=at.concat(ht[5].map(function(Ct){return Vector3.TransformNormal(Ct,Pt).subtract(Mt)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[])),st=st.concat(pt[5].map(function(Ct){return Vector3.TransformNormal(Ct,Pt)}).map(function(Ct){return[Ct.x,Ct.y,Ct.z]}).reduce(function(Ct,Ot){return Ct.concat(Ot)},[])),VertexData._ComputeSides(_e,at,ft,st,ut);var It=new VertexData;if(It.indices=ft,It.positions=at,It.normals=st,It.uvs=ut,o){var Dt=_e===VertexData.DOUBLESIDE?lt.concat(lt):lt;It.colors=Dt}return It}function CreateTiledBox(a,i,e){e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateTiledBoxVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateTiledBox=CreateTiledBoxVertexData;function CreateSphereVertexData(a){for(var i=a.segments||32,e=a.diameterX||a.diameter||1,o=a.diameterY||a.diameter||1,s=a.diameterZ||a.diameter||1,c=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,d=a.slice&&a.slice<=0?1:a.slice||1,_=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,b=!!a.dedupTopBottomIndices,k=new Vector3(e/2,o/2,s/2),j=2+i,$=2*j,_e=[],et=[],tt=[],rt=[],it=0;it<=j;it++){for(var nt=it/j,ot=nt*Math.PI*d,at=0;at<=$;at++){var st=at/$,ut=st*Math.PI*2*c,ft=Matrix.RotationZ(-ot),lt=Matrix.RotationY(ut),ht=Vector3.TransformCoordinates(Vector3.Up(),ft),pt=Vector3.TransformCoordinates(ht,lt),mt=pt.multiply(k),dt=pt.divide(k).normalize();et.push(mt.x,mt.y,mt.z),tt.push(dt.x,dt.y,dt.z),rt.push(st,nt)}if(it>0)for(var gt=et.length/3,_t=gt-2*($+1);_t+$+2<gt;_t++)b?(it>1&&(_e.push(_t),_e.push(_t+1),_e.push(_t+$+1)),(it<j||d<1)&&(_e.push(_t+$+1),_e.push(_t+1),_e.push(_t+$+2))):(_e.push(_t),_e.push(_t+1),_e.push(_t+$+1),_e.push(_t+$+1),_e.push(_t+1),_e.push(_t+$+2))}VertexData._ComputeSides(_,et,_e,tt,rt,a.frontUVs,a.backUVs);var yt=new VertexData;return yt.indices=_e,yt.positions=et,yt.normals=tt,yt.uvs=rt,yt}function CreateSphere(a,i,e){i===void 0&&(i={}),e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateSphereVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateSphere=CreateSphereVertexData;Mesh.CreateSphere=function(a,i,e,o,s,c){var d={segments:i,diameterX:e,diameterY:e,diameterZ:e,sideOrientation:c,updatable:s};return CreateSphere(a,d,o)};function CreateCylinderVertexData(a){var i=a.height||2,e=a.diameterTop===0?0:a.diameterTop||a.diameter||1,o=a.diameterBottom===0?0:a.diameterBottom||a.diameter||1;e=e||1e-5,o=o||1e-5;var s=a.tessellation||24,c=a.subdivisions||1,d=!!a.hasRings,_=!!a.enclose,b=a.cap===0?0:a.cap||Mesh.CAP_ALL,k=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,j=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,$=a.faceUV||new Array(3),_e=a.faceColors,et=k!==1&&_?2:0,tt=d?c:1,rt=2+(1+et)*tt,it;for(it=0;it<rt;it++)_e&&_e[it]===void 0&&(_e[it]=new Color4(1,1,1,1));for(it=0;it<rt;it++)$&&$[it]===void 0&&($[it]=new Vector4(0,0,1,1));var nt=new Array,ot=new Array,at=new Array,st=new Array,ut=new Array,ft=Math.PI*2*k/s,lt,ht,pt,mt=(o-e)/2/i,dt=Vector3.Zero(),gt=Vector3.Zero(),_t=Vector3.Zero(),yt=Vector3.Zero(),Tt=Vector3.Zero(),St=Axis.Y,At,vt,Et,xt=1,Pt=1,bt=0,Mt=0;for(At=0;At<=c;At++)for(ht=At/c,pt=(ht*(e-o)+o)/2,xt=d&&At!==0&&At!==c?2:1,Et=0;Et<xt;Et++){for(d&&(Pt+=Et),_&&(Pt+=2*Et),vt=0;vt<=s;vt++)lt=vt*ft,dt.x=Math.cos(-lt)*pt,dt.y=-i/2+ht*i,dt.z=Math.sin(-lt)*pt,e===0&&At===c?(gt.x=at[at.length-(s+1)*3],gt.y=at[at.length-(s+1)*3+1],gt.z=at[at.length-(s+1)*3+2]):(gt.x=dt.x,gt.z=dt.z,gt.y=Math.sqrt(gt.x*gt.x+gt.z*gt.z)*mt,gt.normalize()),vt===0&&(_t.copyFrom(dt),yt.copyFrom(gt)),ot.push(dt.x,dt.y,dt.z),at.push(gt.x,gt.y,gt.z),d?Mt=bt!==Pt?$[Pt].y:$[Pt].w:Mt=$[Pt].y+($[Pt].w-$[Pt].y)*ht,st.push($[Pt].x+($[Pt].z-$[Pt].x)*vt/s,Mt),_e&&ut.push(_e[Pt].r,_e[Pt].g,_e[Pt].b,_e[Pt].a);k!==1&&_&&(ot.push(dt.x,dt.y,dt.z),ot.push(0,dt.y,0),ot.push(0,dt.y,0),ot.push(_t.x,_t.y,_t.z),Vector3.CrossToRef(St,gt,Tt),Tt.normalize(),at.push(Tt.x,Tt.y,Tt.z,Tt.x,Tt.y,Tt.z),Vector3.CrossToRef(yt,St,Tt),Tt.normalize(),at.push(Tt.x,Tt.y,Tt.z,Tt.x,Tt.y,Tt.z),d?Mt=bt!==Pt?$[Pt+1].y:$[Pt+1].w:Mt=$[Pt+1].y+($[Pt+1].w-$[Pt+1].y)*ht,st.push($[Pt+1].x,Mt),st.push($[Pt+1].z,Mt),d?Mt=bt!==Pt?$[Pt+2].y:$[Pt+2].w:Mt=$[Pt+2].y+($[Pt+2].w-$[Pt+2].y)*ht,st.push($[Pt+2].x,Mt),st.push($[Pt+2].z,Mt),_e&&(ut.push(_e[Pt+1].r,_e[Pt+1].g,_e[Pt+1].b,_e[Pt+1].a),ut.push(_e[Pt+1].r,_e[Pt+1].g,_e[Pt+1].b,_e[Pt+1].a),ut.push(_e[Pt+2].r,_e[Pt+2].g,_e[Pt+2].b,_e[Pt+2].a),ut.push(_e[Pt+2].r,_e[Pt+2].g,_e[Pt+2].b,_e[Pt+2].a))),bt!==Pt&&(bt=Pt)}var Rt=k!==1&&_?s+4:s,Pt;for(At=0,Pt=0;Pt<c;Pt++){var It=0,Dt=0,Ct=0,Ot=0;for(vt=0;vt<s;vt++)It=At*(Rt+1)+vt,Dt=(At+1)*(Rt+1)+vt,Ct=At*(Rt+1)+(vt+1),Ot=(At+1)*(Rt+1)+(vt+1),nt.push(It,Dt,Ct),nt.push(Ot,Ct,Dt);k!==1&&_&&(nt.push(It+2,Dt+2,Ct+2),nt.push(Ot+2,Ct+2,Dt+2),nt.push(It+4,Dt+4,Ct+4),nt.push(Ot+4,Ct+4,Dt+4)),At=d?At+2:At+1}var Ft=function(Bt){var Ut=Bt?e/2:o/2;if(Ut!==0){var Vt,Gt,Lt,Ht=Bt?$[rt-1]:$[0],Wt=null;_e&&(Wt=Bt?_e[rt-1]:_e[0]);var Yt=ot.length/3,jt=Bt?i/2:-i/2,$t=new Vector3(0,jt,0);ot.push($t.x,$t.y,$t.z),at.push(0,Bt?1:-1,0),st.push(Ht.x+(Ht.z-Ht.x)*.5,Ht.y+(Ht.w-Ht.y)*.5),Wt&&ut.push(Wt.r,Wt.g,Wt.b,Wt.a);var Qt=new Vector2(.5,.5);for(Lt=0;Lt<=s;Lt++){Vt=Math.PI*2*Lt*k/s;var ir=Math.cos(-Vt),nr=Math.sin(-Vt);Gt=new Vector3(ir*Ut,jt,nr*Ut);var rr=new Vector2(ir*Qt.x+.5,nr*Qt.y+.5);ot.push(Gt.x,Gt.y,Gt.z),at.push(0,Bt?1:-1,0),st.push(Ht.x+(Ht.z-Ht.x)*rr.x,Ht.y+(Ht.w-Ht.y)*rr.y),Wt&&ut.push(Wt.r,Wt.g,Wt.b,Wt.a)}for(Lt=0;Lt<s;Lt++)Bt?(nt.push(Yt),nt.push(Yt+(Lt+2)),nt.push(Yt+(Lt+1))):(nt.push(Yt),nt.push(Yt+(Lt+1)),nt.push(Yt+(Lt+2)))}};(b===Mesh.CAP_START||b===Mesh.CAP_ALL)&&Ft(!1),(b===Mesh.CAP_END||b===Mesh.CAP_ALL)&&Ft(!0),VertexData._ComputeSides(j,ot,nt,at,st,a.frontUVs,a.backUVs);var wt=new VertexData;return wt.indices=nt,wt.positions=ot,wt.normals=at,wt.uvs=st,_e&&(wt.colors=ut),wt}function CreateCylinder(a,i,e){i===void 0&&(i={});var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateCylinderVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateCylinder=CreateCylinderVertexData;Mesh.CreateCylinder=function(a,i,e,o,s,c,d,_,b){(d===void 0||!(d instanceof Scene))&&(d!==void 0&&(b=_||Mesh.DEFAULTSIDE,_=d),d=c,c=1);var k={height:i,diameterTop:e,diameterBottom:o,tessellation:s,subdivisions:c,sideOrientation:b,updatable:_};return CreateCylinder(a,k,d)};function CreateTorusVertexData(a){for(var i=[],e=[],o=[],s=[],c=a.diameter||1,d=a.thickness||.5,_=a.tessellation||16,b=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,k=_+1,j=0;j<=_;j++)for(var $=j/_,_e=j*Math.PI*2/_-Math.PI/2,et=Matrix.Translation(c/2,0,0).multiply(Matrix.RotationY(_e)),tt=0;tt<=_;tt++){var rt=1-tt/_,it=tt*Math.PI*2/_+Math.PI,nt=Math.cos(it),ot=Math.sin(it),at=new Vector3(nt,ot,0),st=at.scale(d/2),ut=new Vector2($,rt);st=Vector3.TransformCoordinates(st,et),at=Vector3.TransformNormal(at,et),e.push(st.x,st.y,st.z),o.push(at.x,at.y,at.z),s.push(ut.x,ut.y);var ft=(j+1)%k,lt=(tt+1)%k;i.push(j*k+tt),i.push(j*k+lt),i.push(ft*k+tt),i.push(j*k+lt),i.push(ft*k+lt),i.push(ft*k+tt)}VertexData._ComputeSides(b,e,i,o,s,a.frontUVs,a.backUVs);var ht=new VertexData;return ht.indices=i,ht.positions=e,ht.normals=o,ht.uvs=s,ht}function CreateTorus(a,i,e){i===void 0&&(i={});var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateTorusVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateTorus=CreateTorusVertexData;Mesh.CreateTorus=function(a,i,e,o,s,c,d){var _={diameter:i,thickness:e,tessellation:o,sideOrientation:d,updatable:c};return CreateTorus(a,_,s)};function CreateTorusKnotVertexData(a){var i=new Array,e=new Array,o=new Array,s=new Array,c=a.radius||2,d=a.tube||.5,_=a.radialSegments||32,b=a.tubularSegments||32,k=a.p||2,j=a.q||3,$=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,_e=function(St){var At=Math.cos(St),vt=Math.sin(St),Et=j/k*St,xt=Math.cos(Et),bt=c*(2+xt)*.5*At,Mt=c*(2+xt)*vt*.5,Rt=c*Math.sin(Et)*.5;return new Vector3(bt,Mt,Rt)},et,tt;for(et=0;et<=_;et++){var rt=et%_,it=rt/_*2*k*Math.PI,nt=_e(it),ot=_e(it+.01),at=ot.subtract(nt),st=ot.add(nt),ut=Vector3.Cross(at,st);for(st=Vector3.Cross(ut,at),ut.normalize(),st.normalize(),tt=0;tt<b;tt++){var ft=tt%b,lt=ft/b*2*Math.PI,ht=-d*Math.cos(lt),pt=d*Math.sin(lt);e.push(nt.x+ht*st.x+pt*ut.x),e.push(nt.y+ht*st.y+pt*ut.y),e.push(nt.z+ht*st.z+pt*ut.z),s.push(et/_),s.push(tt/b)}}for(et=0;et<_;et++)for(tt=0;tt<b;tt++){var mt=(tt+1)%b,dt=et*b+tt,gt=(et+1)*b+tt,_t=(et+1)*b+mt,yt=et*b+mt;i.push(yt),i.push(gt),i.push(dt),i.push(yt),i.push(_t),i.push(gt)}VertexData.ComputeNormals(e,i,o),VertexData._ComputeSides($,e,i,o,s,a.frontUVs,a.backUVs);var Tt=new VertexData;return Tt.indices=i,Tt.positions=e,Tt.normals=o,Tt.uvs=s,Tt}function CreateTorusKnot(a,i,e){i===void 0&&(i={});var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateTorusKnotVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateTorusKnot=CreateTorusKnotVertexData;Mesh.CreateTorusKnot=function(a,i,e,o,s,c,d,_,b,k){var j={radius:i,tube:e,radialSegments:o,tubularSegments:s,p:c,q:d,sideOrientation:k,updatable:b};return CreateTorusKnot(a,j,_)};Mesh._instancedMeshFactory=function(a,i){var e=new InstancedMesh(a,i);if(i.instancedBuffers){e.instancedBuffers={};for(var o in i.instancedBuffers)e.instancedBuffers[o]=i.instancedBuffers[o]}return e};var InstancedMesh=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o.getScene())||this;s._indexInSourceMeshInstanceArray=-1,s._distanceToCamera=0,o.addInstance(s),s._sourceMesh=o,s._unIndexed=o._unIndexed,s.position.copyFrom(o.position),s.rotation.copyFrom(o.rotation),s.scaling.copyFrom(o.scaling),o.rotationQuaternion&&(s.rotationQuaternion=o.rotationQuaternion.clone()),s.animations=Tools.Slice(o.animations);for(var c=0,d=o.getAnimationRanges();c<d.length;c++){var _=d[c];_!=null&&s.createAnimationRange(_.name,_.from,_.to)}return s.infiniteDistance=o.infiniteDistance,s.setPivotMatrix(o.getPivotMatrix()),s.refreshBoundingInfo(),s._syncSubMeshes(),s}return i.prototype.getClassName=function(){return"InstancedMesh"},Object.defineProperty(i.prototype,"lightSources",{get:function(){return this._sourceMesh._lightSources},enumerable:!1,configurable:!0}),i.prototype._resyncLightSources=function(){},i.prototype._resyncLightSource=function(e){},i.prototype._removeLightSource=function(e,o){},Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._sourceMesh.receiveShadows},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._sourceMesh.material},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._sourceMesh.visibility},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._sourceMesh.skeleton},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"renderingGroupId",{get:function(){return this._sourceMesh.renderingGroupId},set:function(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||Logger$2.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")},enumerable:!1,configurable:!0}),i.prototype.getTotalVertices=function(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0},i.prototype.getTotalIndices=function(){return this._sourceMesh.getTotalIndices()},Object.defineProperty(i.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!1,configurable:!0}),i.prototype.createInstance=function(e){return this._sourceMesh.createInstance(e)},i.prototype.isReady=function(e){return e===void 0&&(e=!1),this._sourceMesh.isReady(e,!0)},i.prototype.getVerticesData=function(e,o){return this._sourceMesh.getVerticesData(e,o)},i.prototype.setVerticesData=function(e,o,s,c){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,o,s,c),this.sourceMesh},i.prototype.updateVerticesData=function(e,o,s,c){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,o,s,c),this.sourceMesh},i.prototype.setIndices=function(e,o){return o===void 0&&(o=null),this.sourceMesh&&this.sourceMesh.setIndices(e,o),this.sourceMesh},i.prototype.isVerticesDataPresent=function(e){return this._sourceMesh.isVerticesDataPresent(e)},i.prototype.getIndices=function(){return this._sourceMesh.getIndices()},Object.defineProperty(i.prototype,"_positions",{get:function(){return this._sourceMesh._positions},enumerable:!1,configurable:!0}),i.prototype.refreshBoundingInfo=function(e,o){if(e===void 0&&(e=!1),o===void 0&&(o=!1),this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;var s=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,o),s),this},i.prototype._preActivate=function(){return this._currentLOD&&this._currentLOD._preActivate(),this},i.prototype._activate=function(e,o){if(this._sourceMesh.subMeshes||Logger$2.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){var s=this._currentLOD._getWorldMatrixDeterminant()>0!=this._getWorldMatrixDeterminant()>0;if(s)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),o){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1},i.prototype._postActivate=function(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)},i.prototype.getWorldMatrix=function(){if(this._currentLOD&&this._currentLOD.billboardMode!==TransformNode.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new Matrix);var e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,TmpVectors.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(TmpVectors.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return a.prototype.getWorldMatrix.call(this)},Object.defineProperty(i.prototype,"isAnInstance",{get:function(){return!0},enumerable:!1,configurable:!0}),i.prototype.getLOD=function(e){if(!e)return this;var o=this.getBoundingInfo();return this._currentLOD=this.sourceMesh.getLOD(e,o.boundingSphere),this._currentLOD===this.sourceMesh?this.sourceMesh:this._currentLOD},i.prototype._preActivateForIntermediateRendering=function(e){return this.sourceMesh._preActivateForIntermediateRendering(e)},i.prototype._syncSubMeshes=function(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(var e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this},i.prototype._generatePointsArray=function(){return this._sourceMesh._generatePointsArray()},i.prototype._updateBoundingInfo=function(){var e=this;return this.hasBoundingInfo?this.getBoundingInfo().update(e.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,e.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(e.worldMatrixFromCache),this},i.prototype.clone=function(e,o,s){o===void 0&&(o=null);var c=this._sourceMesh.createInstance(e);if(DeepCopier.DeepCopy(this,c,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances"],[]),this.refreshBoundingInfo(),o&&(c.parent=o),!s)for(var d=0;d<this.getScene().meshes.length;d++){var _=this.getScene().meshes[d];_.parent===this&&_.clone(_.name,c)}return c.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(c),c},i.prototype.dispose=function(e,o){o===void 0&&(o=!1),this._sourceMesh.removeInstance(this),a.prototype.dispose.call(this,e,o)},i}(AbstractMesh);Mesh.prototype.edgesShareWithInstances=!1;Mesh.prototype.registerInstancedBuffer=function(a,i){var e,o;if((o=(e=this._userInstancedBuffersStorage)===null||e===void 0?void 0:e.vertexBuffers[a])===null||o===void 0||o.dispose(),!this.instancedBuffers){this.instancedBuffers={};for(var s=0,c=this.instances;s<c.length;s++){var d=c[s];d.instancedBuffers={}}this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}}this.instancedBuffers[a]=null,this._userInstancedBuffersStorage.strides[a]=i,this._userInstancedBuffersStorage.sizes[a]=i*32,this._userInstancedBuffersStorage.data[a]=new Float32Array(this._userInstancedBuffersStorage.sizes[a]),this._userInstancedBuffersStorage.vertexBuffers[a]=new VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[a],a,!0,!1,i,!0);for(var _=0,b=this.instances;_<b.length;_++){var d=b[_];d.instancedBuffers[a]=null}this._invalidateInstanceVertexArrayObject()};Mesh.prototype._processInstancedBuffers=function(a,i){var e=a.length;for(var o in this.instancedBuffers){for(var s=this._userInstancedBuffersStorage.sizes[o],c=this._userInstancedBuffersStorage.strides[o],d=(e+1)*c;s<d;)s*=2;this._userInstancedBuffersStorage.data[o].length!=s&&(this._userInstancedBuffersStorage.data[o]=new Float32Array(s),this._userInstancedBuffersStorage.sizes[o]=s,this._userInstancedBuffersStorage.vertexBuffers[o]&&(this._userInstancedBuffersStorage.vertexBuffers[o].dispose(),this._userInstancedBuffersStorage.vertexBuffers[o]=null));var _=this._userInstancedBuffersStorage.data[o],b=0;if(i){var k=this.instancedBuffers[o];k.toArray?k.toArray(_,b):k.copyToArray?k.copyToArray(_,b):_[b]=k,b+=c}for(var j=0;j<e;j++){var $=a[j],k=$.instancedBuffers[o];k.toArray?k.toArray(_,b):k.copyToArray?k.copyToArray(_,b):_[b]=k,b+=c}this._userInstancedBuffersStorage.vertexBuffers[o]?this._userInstancedBuffersStorage.vertexBuffers[o].updateDirectly(_,0):(this._userInstancedBuffersStorage.vertexBuffers[o]=new VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[o],o,!0,!1,c,!0),this._invalidateInstanceVertexArrayObject())}};Mesh.prototype._invalidateInstanceVertexArrayObject=function(){if(!(!this._userInstancedBuffersStorage||this._userInstancedBuffersStorage.vertexArrayObjects===void 0)){for(var a in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[a]);this._userInstancedBuffersStorage.vertexArrayObjects={}}};Mesh.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(var a in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[a]&&this._userInstancedBuffersStorage.vertexBuffers[a].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}};var name$1o="colorPixelShader",shader$1o=`#ifdef VERTEXCOLOR
  3959. varying vec4 vColor;
  3960. #else
  3961. uniform vec4 color;
  3962. #endif
  3963. #include<clipPlaneFragmentDeclaration>
  3964. void main(void) {
  3965. #include<clipPlaneFragment>
  3966. #ifdef VERTEXCOLOR
  3967. gl_FragColor=vColor;
  3968. #else
  3969. gl_FragColor=color;
  3970. #endif
  3971. }`;ShaderStore.ShadersStore[name$1o]=shader$1o;var name$1n="colorVertexShader",shader$1n=`
  3972. attribute vec3 position;
  3973. #ifdef VERTEXCOLOR
  3974. attribute vec4 color;
  3975. #endif
  3976. #include<bonesDeclaration>
  3977. #include<bakedVertexAnimationDeclaration>
  3978. #include<clipPlaneVertexDeclaration>
  3979. #include<instancesDeclaration>
  3980. uniform mat4 viewProjection;
  3981. #ifdef MULTIVIEW
  3982. uniform mat4 viewProjectionR;
  3983. #endif
  3984. #ifdef VERTEXCOLOR
  3985. varying vec4 vColor;
  3986. #endif
  3987. void main(void) {
  3988. #include<instancesVertex>
  3989. #include<bonesVertex>
  3990. #include<bakedVertexAnimation>
  3991. vec4 worldPos=finalWorld*vec4(position,1.0);
  3992. #ifdef MULTIVIEW
  3993. if (gl_ViewID_OVR == 0u) {
  3994. gl_Position=viewProjection*worldPos;
  3995. } else {
  3996. gl_Position=viewProjectionR*worldPos;
  3997. }
  3998. #else
  3999. gl_Position=viewProjection*worldPos;
  4000. #endif
  4001. #include<clipPlaneVertex>
  4002. #ifdef VERTEXCOLOR
  4003. vColor=color;
  4004. #endif
  4005. }`;ShaderStore.ShadersStore[name$1n]=shader$1n;Mesh._LinesMeshParser=function(a,i){return LinesMesh.Parse(a,i)};var LinesMesh=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){o===void 0&&(o=null),s===void 0&&(s=null),c===void 0&&(c=null);var j=a.call(this,e,o,s,c,d)||this;j.useVertexColor=_,j.useVertexAlpha=b,j.color=new Color3(1,1,1),j.alpha=1,c&&(j.color=c.color.clone(),j.alpha=c.alpha,j.useVertexColor=c.useVertexColor,j.useVertexAlpha=c.useVertexAlpha),j.intersectionThreshold=.1;var $=[],_e={attributes:[VertexBuffer.PositionKind],uniforms:["vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","world","viewProjection"],needAlphaBlending:!0,defines:$,useClipPlane:null};return b===!1&&(_e.needAlphaBlending=!1),_?(_e.defines.push("#define VERTEXCOLOR"),_e.attributes.push(VertexBuffer.ColorKind)):(_e.uniforms.push("color"),j.color4=new Color4),k?j.material=k:j._lineMaterial=new ShaderMaterial("colorShader",j.getScene(),"color",_e,!1),j}return i.prototype._isShaderMaterial=function(e){return e.getClassName()==="ShaderMaterial"},i.prototype.isReady=function(){return this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage)?a.prototype.isReady.call(this):!1},i.prototype.getClassName=function(){return"LinesMesh"},Object.defineProperty(i.prototype,"material",{get:function(){return this._lineMaterial},set:function(e){this._lineMaterial=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return!1},set:function(e){},enumerable:!1,configurable:!0}),i.prototype._bind=function(e,o,s){if(!this._geometry)return this;var c=this._lineMaterial.getEffect(),d=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._userInstancedBuffersStorage?this._geometry._bind(c,d,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(c,d),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){var _=this.color,b=_.r,k=_.g,j=_.b;this.color4.set(b,k,j,this.alpha),this._lineMaterial.setColor4("color",this.color4)}return this},i.prototype._draw=function(e,o,s){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;var c=this.getScene().getEngine();return this._unIndexed?c.drawArraysType(Material.LineListDrawMode,e.verticesStart,e.verticesCount,s):c.drawElementsType(Material.LineListDrawMode,e.indexStart,e.indexCount,s),this},i.prototype.dispose=function(e){this._lineMaterial.dispose(!1,!1,!0),a.prototype.dispose.call(this,e)},i.prototype.clone=function(e,o,s){return o===void 0&&(o=null),new i(e,this.getScene(),o,this,s)},i.prototype.createInstance=function(e){var o=new InstancedLinesMesh(e,this);if(this.instancedBuffers){o.instancedBuffers={};for(var s in this.instancedBuffers)o.instancedBuffers[s]=this.instancedBuffers[s]}return o},i.prototype.serialize=function(e){a.prototype.serialize.call(this,e),e.color=this.color.asArray(),e.alpha=this.alpha},i.Parse=function(e,o){var s=new i(e.name,o);return s.color=Color3.FromArray(e.color),s.alpha=e.alpha,s},i}(Mesh),InstancedLinesMesh=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s.intersectionThreshold=o.intersectionThreshold,s}return i.prototype.getClassName=function(){return"InstancedLinesMesh"},i}(InstancedMesh);function CreateLineSystemVertexData(a){for(var i=[],e=[],o=a.lines,s=a.colors,c=[],d=0,_=0;_<o.length;_++)for(var b=o[_],k=0;k<b.length;k++){if(e.push(b[k].x,b[k].y,b[k].z),s){var j=s[_];c.push(j[k].r,j[k].g,j[k].b,j[k].a)}k>0&&(i.push(d-1),i.push(d)),d++}var $=new VertexData;return $.indices=i,$.positions=e,s&&($.colors=c),$}function CreateDashedLinesVertexData(a){var i=a.dashSize||3,e=a.gapSize||1,o=a.dashNb||200,s=a.points,c=new Array,d=new Array,_=Vector3.Zero(),b=0,k=0,j=0,$=0,_e=0,et=0,tt=0;for(tt=0;tt<s.length-1;tt++)s[tt+1].subtractToRef(s[tt],_),b+=_.length();for(j=b/o,$=i*j/(i+e),tt=0;tt<s.length-1;tt++){s[tt+1].subtractToRef(s[tt],_),k=Math.floor(_.length()/j),_.normalize();for(var rt=0;rt<k;rt++)_e=j*rt,c.push(s[tt].x+_e*_.x,s[tt].y+_e*_.y,s[tt].z+_e*_.z),c.push(s[tt].x+(_e+$)*_.x,s[tt].y+(_e+$)*_.y,s[tt].z+(_e+$)*_.z),d.push(et,et+1),et+=2}var it=new VertexData;return it.positions=c,it.indices=d,it}function CreateLineSystem(a,i,e){var o=i.instance,s=i.lines,c=i.colors;if(o){var d=o.getVerticesData(VertexBuffer.PositionKind),_,b;c&&(_=o.getVerticesData(VertexBuffer.ColorKind));for(var k=0,j=0,$=0;$<s.length;$++)for(var _e=s[$],et=0;et<_e.length;et++)d[k]=_e[et].x,d[k+1]=_e[et].y,d[k+2]=_e[et].z,c&&_&&(b=c[$],_[j]=b[et].r,_[j+1]=b[et].g,_[j+2]=b[et].b,_[j+3]=b[et].a,j+=4),k+=3;return o.updateVerticesData(VertexBuffer.PositionKind,d,!1,!1),c&&_&&o.updateVerticesData(VertexBuffer.ColorKind,_,!1,!1),o}var tt=!!c,rt=new LinesMesh(a,e,null,void 0,void 0,tt,i.useVertexAlpha,i.material),it=CreateLineSystemVertexData(i);return it.applyToMesh(rt,i.updatable),rt}function CreateLines(a,i,e){e===void 0&&(e=null);var o=i.colors?[i.colors]:null,s=CreateLineSystem(a,{lines:[i.points],updatable:i.updatable,instance:i.instance,colors:o,useVertexAlpha:i.useVertexAlpha,material:i.material},e);return s}function CreateDashedLines(a,i,e){e===void 0&&(e=null);var o=i.points,s=i.instance,c=i.gapSize||1,d=i.dashSize||3;if(s){var _=function(j){var $=Vector3.Zero(),_e=j.length/6,et=0,tt=0,rt=0,it=0,nt=0,ot=0,at=0,st=0;for(at=0;at<o.length-1;at++)o[at+1].subtractToRef(o[at],$),et+=$.length();rt=et/_e;var ut=s._creationDataStorage.dashSize,ft=s._creationDataStorage.gapSize;for(it=ut*rt/(ut+ft),at=0;at<o.length-1;at++)for(o[at+1].subtractToRef(o[at],$),tt=Math.floor($.length()/rt),$.normalize(),st=0;st<tt&&ot<j.length;)nt=rt*st,j[ot]=o[at].x+nt*$.x,j[ot+1]=o[at].y+nt*$.y,j[ot+2]=o[at].z+nt*$.z,j[ot+3]=o[at].x+(nt+it)*$.x,j[ot+4]=o[at].y+(nt+it)*$.y,j[ot+5]=o[at].z+(nt+it)*$.z,ot+=6,st++;for(;ot<j.length;)j[ot]=o[at].x,j[ot+1]=o[at].y,j[ot+2]=o[at].z,ot+=3};return s.updateMeshPositions(_,!1),s}var b=new LinesMesh(a,e,null,void 0,void 0,void 0,i.useVertexAlpha,i.material),k=CreateDashedLinesVertexData(i);return k.applyToMesh(b,i.updatable),b._creationDataStorage=new _CreationDataStorage,b._creationDataStorage.dashSize=d,b._creationDataStorage.gapSize=c,b}VertexData.CreateLineSystem=CreateLineSystemVertexData;VertexData.CreateDashedLines=CreateDashedLinesVertexData;Mesh.CreateLines=function(a,i,e,o,s){e===void 0&&(e=null),o===void 0&&(o=!1),s===void 0&&(s=null);var c={points:i,updatable:o,instance:s};return CreateLines(a,c,e)};Mesh.CreateDashedLines=function(a,i,e,o,s,c,d,_){c===void 0&&(c=null);var b={points:i,dashSize:e,gapSize:o,dashNb:s,updatable:d,instance:_};return CreateDashedLines(a,b,c)};var IndexedVector2=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e.x,e.y)||this;return s.index=o,s}return i}(Vector2),PolygonPoints=function(){function a(){this.elements=new Array}return a.prototype.add=function(i){var e=this,o=new Array;return i.forEach(function(s){var c=new IndexedVector2(s,e.elements.length);o.push(c),e.elements.push(c)}),o},a.prototype.computeBounds=function(){var i=new Vector2(this.elements[0].x,this.elements[0].y),e=new Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach(function(o){o.x<i.x?i.x=o.x:o.x>e.x&&(e.x=o.x),o.y<i.y?i.y=o.y:o.y>e.y&&(e.y=o.y)}),{min:i,max:e,width:e.x-i.x,height:e.y-i.y}},a}(),PolygonMeshBuilder=function(){function a(i,e,o,s){s===void 0&&(s=earcut),this._points=new PolygonPoints,this._outlinepoints=new PolygonPoints,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=i,this._scene=o||Engine.LastCreatedScene;var c;e instanceof Path2?c=e.getPoints():c=e,this._addToepoint(c),this._points.add(c),this._outlinepoints.add(c),typeof this.bjsEarcut=="undefined"&&Logger$2.Warn("Earcut was not found, the polygon will not be built.")}return a.prototype._addToepoint=function(i){for(var e=0,o=i;e<o.length;e++){var s=o[e];this._epoints.push(s.x,s.y)}},a.prototype.addHole=function(i){this._points.add(i);var e=new PolygonPoints;return e.add(i),this._holes.push(e),this._eholes.push(this._epoints.length/2),this._addToepoint(i),this},a.prototype.build=function(i,e,o){i===void 0&&(i=!1),e===void 0&&(e=0),o===void 0&&(o=2);var s=new Mesh(this._name,this._scene),c=this.buildVertexData(e,o);return s.setVerticesData(VertexBuffer.PositionKind,c.positions,i),s.setVerticesData(VertexBuffer.NormalKind,c.normals,i),s.setVerticesData(VertexBuffer.UVKind,c.uvs,i),s.setIndices(c.indices),s},a.prototype.buildVertexData=function(i,e){var o=this;i===void 0&&(i=0),e===void 0&&(e=2);var s=new VertexData,c=new Array,d=new Array,_=new Array,b=this._points.computeBounds();this._points.elements.forEach(function(nt){c.push(0,1,0),d.push(nt.x,0,nt.y),_.push((nt.x-b.min.x)/b.width,(nt.y-b.min.y)/b.height)});for(var k=new Array,j=this.bjsEarcut(this._epoints,this._eholes,2),$=0;$<j.length;$++)k.push(j[$]);if(i>0){var _e=d.length/3;this._points.elements.forEach(function(nt){c.push(0,-1,0),d.push(nt.x,-i,nt.y),_.push(1-(nt.x-b.min.x)/b.width,1-(nt.y-b.min.y)/b.height)});for(var et=k.length,$=0;$<et;$+=3){var tt=k[$+0],rt=k[$+1],it=k[$+2];k.push(it+_e),k.push(rt+_e),k.push(tt+_e)}this.addSide(d,c,_,k,b,this._outlinepoints,i,!1,e),this._holes.forEach(function(nt){o.addSide(d,c,_,k,b,nt,i,!0,e)})}return s.indices=k,s.positions=d,s.normals=c,s.uvs=_,s},a.prototype.addSide=function(i,e,o,s,c,d,_,b,k){for(var j=i.length/3,$=0,_e=0;_e<d.elements.length;_e++){var et=d.elements[_e],tt=d.elements[(_e+1)%d.elements.length];i.push(et.x,0,et.y),i.push(et.x,-_,et.y),i.push(tt.x,0,tt.y),i.push(tt.x,-_,tt.y);var rt=d.elements[(_e+d.elements.length-1)%d.elements.length],it=d.elements[(_e+2)%d.elements.length],nt=new Vector3(-(tt.y-et.y),0,tt.x-et.x),ot=new Vector3(-(et.y-rt.y),0,et.x-rt.x),at=new Vector3(-(it.y-tt.y),0,it.x-tt.x);b||(nt=nt.scale(-1),ot=ot.scale(-1),at=at.scale(-1));var st=nt.normalizeToNew(),ut=ot.normalizeToNew(),ft=at.normalizeToNew(),lt=Vector3.Dot(ut,st);lt>k?lt<Epsilon-1?ut=new Vector3(et.x,0,et.y).subtract(new Vector3(tt.x,0,tt.y)).normalize():ut=ot.add(nt).normalize():ut=st;var ht=Vector3.Dot(at,nt);ht>k?ht<Epsilon-1?ft=new Vector3(tt.x,0,tt.y).subtract(new Vector3(et.x,0,et.y)).normalize():ft=at.add(nt).normalize():ft=st,o.push($/c.width,0),o.push($/c.width,1),$+=nt.length(),o.push($/c.width,0),o.push($/c.width,1),e.push(ut.x,ut.y,ut.z),e.push(ut.x,ut.y,ut.z),e.push(ft.x,ft.y,ft.z),e.push(ft.x,ft.y,ft.z),b?(s.push(j),s.push(j+2),s.push(j+1),s.push(j+1),s.push(j+2),s.push(j+3)):(s.push(j),s.push(j+1),s.push(j+2),s.push(j+1),s.push(j+3),s.push(j+2)),j+=4}},a}();function CreatePolygonVertexData(a,i,e,o,s,c,d){for(var _=e||new Array(3),b=o,k=[],j=d||!1,$=0;$<3;$++)_[$]===void 0&&(_[$]=new Vector4(0,0,1,1)),b&&b[$]===void 0&&(b[$]=new Color4(1,1,1,1));var _e=a.getVerticesData(VertexBuffer.PositionKind),et=a.getVerticesData(VertexBuffer.NormalKind),tt=a.getVerticesData(VertexBuffer.UVKind),rt=a.getIndices(),it=_e.length/9,nt=0,ot=0,at=0,st=0,ut=0,ft=[0];if(j)for(var lt=it;lt<_e.length/3;lt+=4)ot=_e[3*(lt+2)]-_e[3*lt],at=_e[3*(lt+2)+2]-_e[3*lt+2],st=Math.sqrt(ot*ot+at*at),ut+=st,ft.push(ut);for(var lt=0,ht=0,pt=0;pt<et.length;pt+=3)Math.abs(et[pt+1])<.001&&(ht=1),Math.abs(et[pt+1]-1)<.001&&(ht=0),Math.abs(et[pt+1]+1)<.001&&(ht=2),lt=pt/3,ht===1?(nt=lt-it,nt%4<1.5?j?tt[2*lt]=_[ht].x+(_[ht].z-_[ht].x)*ft[Math.floor(nt/4)]/ut:tt[2*lt]=_[ht].x:j?tt[2*lt]=_[ht].x+(_[ht].z-_[ht].x)*ft[Math.floor(nt/4)+1]/ut:tt[2*lt]=_[ht].z,nt%2===0?tt[2*lt+1]=_[ht].w:tt[2*lt+1]=_[ht].y):(tt[2*lt]=(1-tt[2*lt])*_[ht].x+tt[2*lt]*_[ht].z,tt[2*lt+1]=(1-tt[2*lt+1])*_[ht].y+tt[2*lt+1]*_[ht].w),b&&k.push(b[ht].r,b[ht].g,b[ht].b,b[ht].a);VertexData._ComputeSides(i,_e,rt,et,tt,s,c);var mt=new VertexData;if(mt.indices=rt,mt.positions=_e,mt.normals=et,mt.uvs=tt,b){var dt=i===VertexData.DOUBLESIDE?k.concat(k):k;mt.colors=dt}return mt}function CreatePolygon(a,i,e,o){e===void 0&&(e=null),o===void 0&&(o=earcut),i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation);for(var s=i.shape,c=i.holes||[],d=i.depth||0,_=i.smoothingThreshold||2,b=[],k=[],j=0;j<s.length;j++)b[j]=new Vector2(s[j].x,s[j].z);var $=1e-8;b[0].equalsWithEpsilon(b[b.length-1],$)&&b.pop();for(var _e=new PolygonMeshBuilder(a,b,e||EngineStore.LastCreatedScene,o),et=0;et<c.length;et++){k=[];for(var tt=0;tt<c[et].length;tt++)k.push(new Vector2(c[et][tt].x,c[et][tt].z));_e.addHole(k)}var rt=_e.build(i.updatable,d,_);rt._originalBuilderSideOrientation=i.sideOrientation;var it=CreatePolygonVertexData(rt,i.sideOrientation,i.faceUV,i.faceColors,i.frontUVs,i.backUVs,i.wrap);return it.applyToMesh(rt,i.updatable),rt}function ExtrudePolygon(a,i,e,o){return e===void 0&&(e=null),o===void 0&&(o=earcut),CreatePolygon(a,i,e,o)}VertexData.CreatePolygon=CreatePolygonVertexData;Mesh.CreatePolygon=function(a,i,e,o,s,c,d){d===void 0&&(d=earcut);var _={shape:i,holes:o,updatable:s,sideOrientation:c};return CreatePolygon(a,_,e,d)};Mesh.ExtrudePolygon=function(a,i,e,o,s,c,d,_){_===void 0&&(_=earcut);var b={shape:i,holes:s,depth:e,updatable:c,sideOrientation:d};return ExtrudePolygon(a,b,o,_)};function ExtrudeShape(a,i,e){e===void 0&&(e=null);var o=i.path,s=i.shape,c=i.scale||1,d=i.rotation||0,_=i.cap===0?0:i.cap||Mesh.NO_CAP,b=i.updatable,k=Mesh._GetDefaultSideOrientation(i.sideOrientation),j=i.instance||null,$=i.invertUV||!1;return _ExtrudeShapeGeneric(a,s,o,c,d,null,null,!1,!1,_,!1,e,!!b,k,j,$,i.frontUVs||null,i.backUVs||null)}function ExtrudeShapeCustom(a,i,e){e===void 0&&(e=null);var o=i.path,s=i.shape,c=i.scaleFunction||function(){return 1},d=i.rotationFunction||function(){return 0},_=i.ribbonCloseArray||!1,b=i.ribbonClosePath||!1,k=i.cap===0?0:i.cap||Mesh.NO_CAP,j=i.updatable,$=Mesh._GetDefaultSideOrientation(i.sideOrientation),_e=i.instance,et=i.invertUV||!1;return _ExtrudeShapeGeneric(a,s,o,null,null,c,d,_,b,k,!0,e,!!j,$,_e||null,et,i.frontUVs||null,i.backUVs||null)}function _ExtrudeShapeGeneric(a,i,e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it,nt){var ot=function(ht,pt,mt,dt,gt,_t,yt,Tt,St,At){for(var vt=mt.getTangents(),Et=mt.getNormals(),xt=mt.getBinormals(),bt=mt.getDistances(),Mt=0,Rt=function(){return gt!==null?gt:1},Pt=function(){return _t!==null?_t:0},It=At&&Tt?Tt:Pt,Dt=At&&yt?yt:Rt,Ct=St===Mesh.NO_CAP||St===Mesh.CAP_END?0:2,Ot=TmpVectors.Matrix[0],Ft=0;Ft<pt.length;Ft++){for(var wt=new Array,Bt=It(Ft,bt[Ft]),Ut=Dt(Ft,bt[Ft]),Vt=0;Vt<ht.length;Vt++){Matrix.RotationAxisToRef(vt[Ft],Mt,Ot);var Gt=vt[Ft].scale(ht[Vt].z).add(Et[Ft].scale(ht[Vt].x)).add(xt[Ft].scale(ht[Vt].y)),Lt=wt[Vt]?wt[Vt]:Vector3.Zero();Vector3.TransformCoordinatesToRef(Gt,Ot,Lt),Lt.scaleInPlace(Ut).addInPlace(pt[Ft]),wt[Vt]=Lt}dt[Ct]=wt,Mt+=Bt,Ct++}var Ht=function(Wt){var Yt=Array(),jt=Vector3.Zero(),$t;for($t=0;$t<Wt.length;$t++)jt.addInPlace(Wt[$t]);for(jt.scaleInPlace(1/Wt.length),$t=0;$t<Wt.length;$t++)Yt.push(jt);return Yt};switch(St){case Mesh.NO_CAP:break;case Mesh.CAP_START:dt[0]=Ht(dt[2]),dt[1]=dt[2];break;case Mesh.CAP_END:dt[Ct]=dt[Ct-1],dt[Ct+1]=Ht(dt[Ct-1]);break;case Mesh.CAP_ALL:dt[0]=Ht(dt[2]),dt[1]=dt[2],dt[Ct]=dt[Ct-1],dt[Ct+1]=Ht(dt[Ct-1]);break}return dt},at,st;if(tt){var ut=tt._creationDataStorage;return at=ut.path3D.update(e),st=ot(i,e,ut.path3D,ut.pathArray,o,s,c,d,ut.cap,j),tt=CreateRibbon("",{pathArray:st,closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:tt},$||void 0),tt}at=new Path3D(e);var ft=new Array;k=k<0||k>3?0:k,st=ot(i,e,at,ft,o,s,c,d,k,j);var lt=CreateRibbon(a,{pathArray:st,closeArray:_,closePath:b,updatable:_e,sideOrientation:et,invertUV:rt,frontUVs:it||void 0,backUVs:nt||void 0},$);return lt._creationDataStorage.pathArray=st,lt._creationDataStorage.path3D=at,lt._creationDataStorage.cap=k,lt}Mesh.ExtrudeShape=function(a,i,e,o,s,c,d,_,b,k){d===void 0&&(d=null);var j={shape:i,path:e,scale:o,rotation:s,cap:c===0?0:c||Mesh.NO_CAP,sideOrientation:b,instance:k,updatable:_};return ExtrudeShape(a,j,d)};Mesh.ExtrudeShapeCustom=function(a,i,e,o,s,c,d,_,b,k,j,$){var _e={shape:i,path:e,scaleFunction:o,rotationFunction:s,ribbonCloseArray:c,ribbonClosePath:d,cap:_===0?0:_||Mesh.NO_CAP,sideOrientation:j,instance:$,updatable:k};return ExtrudeShapeCustom(a,_e,b)};function CreateLathe(a,i,e){e===void 0&&(e=null);var o=i.arc?i.arc<=0||i.arc>1?1:i.arc:1,s=i.closed===void 0?!0:i.closed,c=i.shape,d=i.radius||1,_=i.tessellation||64,b=i.clip||0,k=i.updatable,j=Mesh._GetDefaultSideOrientation(i.sideOrientation),$=i.cap||Mesh.NO_CAP,_e=Math.PI*2,et=new Array,tt=i.invertUV||!1,rt=0,it=0,nt=_e/_*o,ot,at=new Array;for(rt=0;rt<=_-b;rt++){var at=[];for(($==Mesh.CAP_START||$==Mesh.CAP_ALL)&&(at.push(new Vector3(0,c[0].y,0)),at.push(new Vector3(Math.cos(rt*nt)*c[0].x*d,c[0].y,Math.sin(rt*nt)*c[0].x*d))),it=0;it<c.length;it++)ot=new Vector3(Math.cos(rt*nt)*c[it].x*d,c[it].y,Math.sin(rt*nt)*c[it].x*d),at.push(ot);($==Mesh.CAP_END||$==Mesh.CAP_ALL)&&(at.push(new Vector3(Math.cos(rt*nt)*c[c.length-1].x*d,c[c.length-1].y,Math.sin(rt*nt)*c[c.length-1].x*d)),at.push(new Vector3(0,c[c.length-1].y,0))),et.push(at)}var st=CreateRibbon(a,{pathArray:et,closeArray:s,sideOrientation:j,updatable:k,invertUV:tt,frontUVs:i.frontUVs,backUVs:i.backUVs},e);return st}Mesh.CreateLathe=function(a,i,e,o,s,c,d){var _={shape:i,radius:e,tessellation:o,sideOrientation:d,updatable:c};return CreateLathe(a,_,s)};function CreatePlaneVertexData(a){var i=[],e=[],o=[],s=[],c=a.width||a.size||1,d=a.height||a.size||1,_=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,b=c/2,k=d/2;e.push(-b,-k,0),o.push(0,0,-1),s.push(0,0),e.push(b,-k,0),o.push(0,0,-1),s.push(1,0),e.push(b,k,0),o.push(0,0,-1),s.push(1,1),e.push(-b,k,0),o.push(0,0,-1),s.push(0,1),i.push(0),i.push(1),i.push(2),i.push(0),i.push(2),i.push(3),VertexData._ComputeSides(_,e,i,o,s,a.frontUVs,a.backUVs);var j=new VertexData;return j.indices=i,j.positions=e,j.normals=o,j.uvs=s,j}function CreatePlane(a,i,e){i===void 0&&(i={}),e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreatePlaneVertexData(i);return s.applyToMesh(o,i.updatable),i.sourcePlane&&(o.translate(i.sourcePlane.normal,-i.sourcePlane.d),o.setDirection(i.sourcePlane.normal.scale(-1))),o}VertexData.CreatePlane=CreatePlaneVertexData;Mesh.CreatePlane=function(a,i,e,o,s){var c={size:i,width:i,height:i,sideOrientation:s,updatable:o};return CreatePlane(a,c,e)};Mesh._GroundMeshParser=function(a,i){return GroundMesh.Parse(a,i)};var GroundMesh=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s.generateOctree=!1,s}return i.prototype.getClassName=function(){return"GroundMesh"},Object.defineProperty(i.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!1,configurable:!0}),i.prototype.optimize=function(e,o){o===void 0&&(o=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);var s=this;s.createOrUpdateSubmeshesOctree&&s.createOrUpdateSubmeshesOctree(o)},i.prototype.getHeightAtCoordinates=function(e,o){var s=this.getWorldMatrix(),c=TmpVectors.Matrix[5];s.invertToRef(c);var d=TmpVectors.Vector3[8];if(Vector3.TransformCoordinatesFromFloatsToRef(e,0,o,c,d),e=d.x,o=d.z,e<this._minX||e>this._maxX||o<this._minZ||o>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());var _=this._getFacetAt(e,o),b=-(_.x*e+_.z*o+_.w)/_.y;return Vector3.TransformCoordinatesFromFloatsToRef(0,b,0,s,d),d.y},i.prototype.getNormalAtCoordinates=function(e,o){var s=new Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(e,o,s),s},i.prototype.getNormalAtCoordinatesToRef=function(e,o,s){var c=this.getWorldMatrix(),d=TmpVectors.Matrix[5];c.invertToRef(d);var _=TmpVectors.Vector3[8];if(Vector3.TransformCoordinatesFromFloatsToRef(e,0,o,d,_),e=_.x,o=_.z,e<this._minX||e>this._maxX||o<this._minZ||o>this._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());var b=this._getFacetAt(e,o);return Vector3.TransformNormalFromFloatsToRef(b.x,b.y,b.z,c,s),this},i.prototype.updateCoordinateHeights=function(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this},i.prototype._getFacetAt=function(e,o){var s=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),c=Math.floor(-(o+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),d=this._heightQuads[c*this._subdivisionsX+s],_;return o<d.slope.x*e+d.slope.y?_=d.facet1:_=d.facet2,_},i.prototype._initHeightQuads=function(){var e=this._subdivisionsX,o=this._subdivisionsY;this._heightQuads=new Array;for(var s=0;s<o;s++)for(var c=0;c<e;c++){var d={slope:Vector2.Zero(),facet1:new Vector4(0,0,0,0),facet2:new Vector4(0,0,0,0)};this._heightQuads[s*e+c]=d}return this},i.prototype._computeHeightQuads=function(){var e=this.getVerticesData(VertexBuffer.PositionKind);if(!e)return this;for(var o=TmpVectors.Vector3[3],s=TmpVectors.Vector3[2],c=TmpVectors.Vector3[1],d=TmpVectors.Vector3[0],_=TmpVectors.Vector3[4],b=TmpVectors.Vector3[5],k=TmpVectors.Vector3[6],j=TmpVectors.Vector3[7],$=TmpVectors.Vector3[8],_e=0,et=0,tt=0,rt=0,it=0,nt=0,ot=0,at=this._subdivisionsX,st=this._subdivisionsY,ut=0;ut<st;ut++)for(var ft=0;ft<at;ft++){_e=ft*3,et=ut*(at+1)*3,tt=(ut+1)*(at+1)*3,o.x=e[et+_e],o.y=e[et+_e+1],o.z=e[et+_e+2],s.x=e[et+_e+3],s.y=e[et+_e+4],s.z=e[et+_e+5],c.x=e[tt+_e],c.y=e[tt+_e+1],c.z=e[tt+_e+2],d.x=e[tt+_e+3],d.y=e[tt+_e+4],d.z=e[tt+_e+5],rt=(d.z-o.z)/(d.x-o.x),it=o.z-rt*o.x,s.subtractToRef(o,_),c.subtractToRef(o,b),d.subtractToRef(o,k),Vector3.CrossToRef(k,b,j),Vector3.CrossToRef(_,k,$),j.normalize(),$.normalize(),nt=-(j.x*o.x+j.y*o.y+j.z*o.z),ot=-($.x*s.x+$.y*s.y+$.z*s.z);var lt=this._heightQuads[ut*at+ft];lt.slope.copyFromFloats(rt,it),lt.facet1.copyFromFloats(j.x,j.y,j.z,nt),lt.facet2.copyFromFloats($.x,$.y,$.z,ot)}return this},i.prototype.serialize=function(e){a.prototype.serialize.call(this,e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height},i.Parse=function(e,o){var s=new i(e.name,o);return s._subdivisionsX=e.subdivisionsX||1,s._subdivisionsY=e.subdivisionsY||1,s._minX=e.minX,s._maxX=e.maxX,s._minZ=e.minZ,s._maxZ=e.maxZ,s._width=e.width,s._height=e.height,s},i}(Mesh);function CreateGroundVertexData(a){var i=[],e=[],o=[],s=[],c,d,_=a.width||1,b=a.height||1,k=a.subdivisionsX||a.subdivisions||1,j=a.subdivisionsY||a.subdivisions||1;for(c=0;c<=j;c++)for(d=0;d<=k;d++){var $=new Vector3(d*_/k-_/2,0,(j-c)*b/j-b/2),_e=new Vector3(0,1,0);e.push($.x,$.y,$.z),o.push(_e.x,_e.y,_e.z),s.push(d/k,1-c/j)}for(c=0;c<j;c++)for(d=0;d<k;d++)i.push(d+1+(c+1)*(k+1)),i.push(d+1+c*(k+1)),i.push(d+c*(k+1)),i.push(d+(c+1)*(k+1)),i.push(d+1+(c+1)*(k+1)),i.push(d+c*(k+1));var et=new VertexData;return et.indices=i,et.positions=e,et.normals=o,et.uvs=s,et}function CreateTiledGroundVertexData(a){var i=a.xmin!==void 0&&a.xmin!==null?a.xmin:-1,e=a.zmin!==void 0&&a.zmin!==null?a.zmin:-1,o=a.xmax!==void 0&&a.xmax!==null?a.xmax:1,s=a.zmax!==void 0&&a.zmax!==null?a.zmax:1,c=a.subdivisions||{w:1,h:1},d=a.precision||{w:1,h:1},_=new Array,b=new Array,k=new Array,j=new Array,$,_e,et,tt;c.h=c.h<1?1:c.h,c.w=c.w<1?1:c.w,d.w=d.w<1?1:d.w,d.h=d.h<1?1:d.h;var rt={w:(o-i)/c.w,h:(s-e)/c.h};function it(ot,at,st,ut){var ft=b.length/3,lt=d.w+1;for($=0;$<d.h;$++)for(_e=0;_e<d.w;_e++){var ht=[ft+_e+$*lt,ft+(_e+1)+$*lt,ft+(_e+1)+($+1)*lt,ft+_e+($+1)*lt];_.push(ht[1]),_.push(ht[2]),_.push(ht[3]),_.push(ht[0]),_.push(ht[1]),_.push(ht[3])}var pt=Vector3.Zero(),mt=new Vector3(0,1,0);for($=0;$<=d.h;$++)for(pt.z=$*(ut-at)/d.h+at,_e=0;_e<=d.w;_e++)pt.x=_e*(st-ot)/d.w+ot,pt.y=0,b.push(pt.x,pt.y,pt.z),k.push(mt.x,mt.y,mt.z),j.push(_e/d.w,$/d.h)}for(et=0;et<c.h;et++)for(tt=0;tt<c.w;tt++)it(i+tt*rt.w,e+et*rt.h,i+(tt+1)*rt.w,e+(et+1)*rt.h);var nt=new VertexData;return nt.indices=_,nt.positions=b,nt.normals=k,nt.uvs=j,nt}function CreateGroundFromHeightMapVertexData(a){var i=[],e=[],o=[],s=[],c,d,_=a.colorFilter||new Color3(.3,.59,.11),b=a.alphaFilter||0,k=!1;if(a.minHeight>a.maxHeight){k=!0;var j=a.maxHeight;a.maxHeight=a.minHeight,a.minHeight=j}for(c=0;c<=a.subdivisions;c++)for(d=0;d<=a.subdivisions;d++){var $=new Vector3(d*a.width/a.subdivisions-a.width/2,0,(a.subdivisions-c)*a.height/a.subdivisions-a.height/2),_e=($.x+a.width/2)/a.width*(a.bufferWidth-1)|0,et=(1-($.z+a.height/2)/a.height)*(a.bufferHeight-1)|0,tt=(_e+et*a.bufferWidth)*4,rt=a.buffer[tt]/255,it=a.buffer[tt+1]/255,nt=a.buffer[tt+2]/255,ot=a.buffer[tt+3]/255;k&&(rt=1-rt,it=1-it,nt=1-nt);var at=rt*_.r+it*_.g+nt*_.b;ot>=b?$.y=a.minHeight+(a.maxHeight-a.minHeight)*at:$.y=a.minHeight-Epsilon,e.push($.x,$.y,$.z),o.push(0,0,0),s.push(d/a.subdivisions,1-c/a.subdivisions)}for(c=0;c<a.subdivisions;c++)for(d=0;d<a.subdivisions;d++){var st=d+1+(c+1)*(a.subdivisions+1),ut=d+1+c*(a.subdivisions+1),ft=d+c*(a.subdivisions+1),lt=d+(c+1)*(a.subdivisions+1),ht=e[st*3+1]>=a.minHeight,pt=e[ut*3+1]>=a.minHeight,mt=e[ft*3+1]>=a.minHeight;ht&&pt&&mt&&(i.push(st),i.push(ut),i.push(ft));var dt=e[lt*3+1]>=a.minHeight;dt&&ht&&mt&&(i.push(lt),i.push(st),i.push(ft))}VertexData.ComputeNormals(e,i,o);var gt=new VertexData;return gt.indices=i,gt.positions=e,gt.normals=o,gt.uvs=s,gt}function CreateGround(a,i,e){i===void 0&&(i={});var o=new GroundMesh(a,e);o._setReady(!1),o._subdivisionsX=i.subdivisionsX||i.subdivisions||1,o._subdivisionsY=i.subdivisionsY||i.subdivisions||1,o._width=i.width||1,o._height=i.height||1,o._maxX=o._width/2,o._maxZ=o._height/2,o._minX=-o._maxX,o._minZ=-o._maxZ;var s=CreateGroundVertexData(i);return s.applyToMesh(o,i.updatable),o._setReady(!0),o}function CreateTiledGround(a,i,e){e===void 0&&(e=null);var o=new Mesh(a,e),s=CreateTiledGroundVertexData(i);return s.applyToMesh(o,i.updatable),o}function CreateGroundFromHeightMap(a,i,e,o){e===void 0&&(e={}),o===void 0&&(o=null);var s=e.width||10,c=e.height||10,d=e.subdivisions||1,_=e.minHeight||0,b=e.maxHeight||1,k=e.colorFilter||new Color3(.3,.59,.11),j=e.alphaFilter||0,$=e.updatable,_e=e.onReady;o=o||EngineStore.LastCreatedScene;var et=new GroundMesh(a,o);et._subdivisionsX=d,et._subdivisionsY=d,et._width=s,et._height=c,et._maxX=et._width/2,et._maxZ=et._height/2,et._minX=-et._maxX,et._minZ=-et._maxZ,et._setReady(!1);var tt=function(rt){var it=rt.width,nt=rt.height;if(!o.isDisposed){var ot=o==null?void 0:o.getEngine().resizeImageBitmap(rt,it,nt),at=CreateGroundFromHeightMapVertexData({width:s,height:c,subdivisions:d,minHeight:_,maxHeight:b,colorFilter:k,buffer:ot,bufferWidth:it,bufferHeight:nt,alphaFilter:j});at.applyToMesh(et,$),_e&&_e(et),et._setReady(!0)}};return Tools.LoadImage(i,tt,function(){},o.offlineProvider),et}VertexData.CreateGround=CreateGroundVertexData;VertexData.CreateTiledGround=CreateTiledGroundVertexData;VertexData.CreateGroundFromHeightMap=CreateGroundFromHeightMapVertexData;Mesh.CreateGround=function(a,i,e,o,s,c){var d={width:i,height:e,subdivisions:o,updatable:c};return CreateGround(a,d,s)};Mesh.CreateTiledGround=function(a,i,e,o,s,c,d,_,b){var k={xmin:i,zmin:e,xmax:o,zmax:s,subdivisions:c,precision:d,updatable:b};return CreateTiledGround(a,k,_)};Mesh.CreateGroundFromHeightMap=function(a,i,e,o,s,c,d,_,b,k,j){var $={width:e,height:o,subdivisions:s,minHeight:c,maxHeight:d,updatable:b,onReady:k,alphaFilter:j};return CreateGroundFromHeightMap(a,i,$,_)};function CreateTube(a,i,e){e===void 0&&(e=null);var o=i.path,s=i.instance,c=1;i.radius!==void 0?c=i.radius:s&&(c=s._creationDataStorage.radius);var d=i.tessellation||64,_=i.radiusFunction||null,b=i.cap||Mesh.NO_CAP,k=i.invertUV||!1,j=i.updatable,$=Mesh._GetDefaultSideOrientation(i.sideOrientation);i.arc=i.arc&&(i.arc<=0||i.arc>1)?1:i.arc||1;var _e=function(at,st,ut,ft,lt,ht,pt,mt){for(var dt=st.getTangents(),gt=st.getNormals(),_t=st.getDistances(),yt=Math.PI*2,Tt=yt/lt*mt,St=function(){return ft},At=ht||St,vt,Et,xt,bt,Mt=TmpVectors.Matrix[0],Rt=pt===Mesh.NO_CAP||pt===Mesh.CAP_END?0:2,Pt=0;Pt<at.length;Pt++){Et=At(Pt,_t[Pt]),vt=Array(),xt=gt[Pt];for(var It=0;It<lt;It++)Matrix.RotationAxisToRef(dt[Pt],Tt*It,Mt),bt=vt[It]?vt[It]:Vector3.Zero(),Vector3.TransformCoordinatesToRef(xt,Mt,bt),bt.scaleInPlace(Et).addInPlace(at[Pt]),vt[It]=bt;ut[Rt]=vt,Rt++}var Dt=function(Ct,Ot){for(var Ft=Array(),wt=0;wt<Ct;wt++)Ft.push(at[Ot]);return Ft};switch(pt){case Mesh.NO_CAP:break;case Mesh.CAP_START:ut[0]=Dt(lt,0),ut[1]=ut[2].slice(0);break;case Mesh.CAP_END:ut[Rt]=ut[Rt-1].slice(0),ut[Rt+1]=Dt(lt,at.length-1);break;case Mesh.CAP_ALL:ut[0]=Dt(lt,0),ut[1]=ut[2].slice(0),ut[Rt]=ut[Rt-1].slice(0),ut[Rt+1]=Dt(lt,at.length-1);break}return ut},et,tt;if(s){var rt=s._creationDataStorage,it=i.arc||rt.arc;return et=rt.path3D.update(o),tt=_e(o,et,rt.pathArray,c,rt.tessellation,_,rt.cap,it),s=CreateRibbon("",{pathArray:tt,instance:s}),rt.path3D=et,rt.pathArray=tt,rt.arc=it,rt.radius=c,s}et=new Path3D(o);var nt=new Array;b=b<0||b>3?0:b,tt=_e(o,et,nt,c,d,_,b,i.arc);var ot=CreateRibbon(a,{pathArray:tt,closePath:!0,closeArray:!1,updatable:j,sideOrientation:$,invertUV:k,frontUVs:i.frontUVs,backUVs:i.backUVs},e);return ot._creationDataStorage.pathArray=tt,ot._creationDataStorage.path3D=et,ot._creationDataStorage.tessellation=d,ot._creationDataStorage.cap=b,ot._creationDataStorage.arc=i.arc,ot._creationDataStorage.radius=c,ot}Mesh.CreateTube=function(a,i,e,o,s,c,d,_,b,k){var j={path:i,radius:e,tessellation:o,radiusFunction:s,arc:1,cap:c,updatable:_,sideOrientation:b,instance:k};return CreateTube(a,j,d)};function CreatePolyhedronVertexData(a){var i=[];i[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},i[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},i[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},i[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},i[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},i[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},i[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},i[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},i[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},i[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},i[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},i[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},i[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},i[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},i[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};var e=a.type&&(a.type<0||a.type>=i.length)?0:a.type||0,o=a.size,s=a.sizeX||o||1,c=a.sizeY||o||1,d=a.sizeZ||o||1,_=a.custom||i[e],b=_.face.length,k=a.faceUV||new Array(b),j=a.faceColors,$=a.flat===void 0?!0:a.flat,_e=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,et=new Array,tt=new Array,rt=new Array,it=new Array,nt=new Array,ot=0,at=0,st=new Array,ut=0,ft=0,lt,ht,pt,mt,dt,gt;if($)for(ft=0;ft<b;ft++)j&&j[ft]===void 0&&(j[ft]=new Color4(1,1,1,1)),k&&k[ft]===void 0&&(k[ft]=new Vector4(0,0,1,1));if($)for(ft=0;ft<b;ft++){var _t=_.face[ft].length;for(pt=2*Math.PI/_t,mt=.5*Math.tan(pt/2),dt=.5,ut=0;ut<_t;ut++)et.push(_.vertex[_.face[ft][ut]][0]*s,_.vertex[_.face[ft][ut]][1]*c,_.vertex[_.face[ft][ut]][2]*d),st.push(ot),ot++,lt=k[ft].x+(k[ft].z-k[ft].x)*(.5+mt),ht=k[ft].y+(k[ft].w-k[ft].y)*(dt-.5),it.push(lt,ht),gt=mt*Math.cos(pt)-dt*Math.sin(pt),dt=mt*Math.sin(pt)+dt*Math.cos(pt),mt=gt,j&&nt.push(j[ft].r,j[ft].g,j[ft].b,j[ft].a);for(ut=0;ut<_t-2;ut++)tt.push(st[0+at],st[ut+2+at],st[ut+1+at]);at+=_t}else{for(ut=0;ut<_.vertex.length;ut++)et.push(_.vertex[ut][0]*s,_.vertex[ut][1]*c,_.vertex[ut][2]*d),it.push(0,0);for(ft=0;ft<b;ft++)for(ut=0;ut<_.face[ft].length-2;ut++)tt.push(_.face[ft][0],_.face[ft][ut+2],_.face[ft][ut+1])}VertexData.ComputeNormals(et,tt,rt),VertexData._ComputeSides(_e,et,tt,rt,it,a.frontUVs,a.backUVs);var yt=new VertexData;return yt.positions=et,yt.indices=tt,yt.normals=rt,yt.uvs=it,j&&$&&(yt.colors=nt),yt}function CreatePolyhedron(a,i,e){i===void 0&&(i={}),e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreatePolyhedronVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreatePolyhedron=CreatePolyhedronVertexData;Mesh.CreatePolyhedron=function(a,i,e){return CreatePolyhedron(a,i,e)};function CreateIcoSphereVertexData(a){var i=a.sideOrientation||VertexData.DEFAULTSIDE,e=a.radius||1,o=a.flat===void 0?!0:a.flat,s=a.subdivisions||4,c=a.radiusX||e,d=a.radiusY||e,_=a.radiusZ||e,b=(1+Math.sqrt(5))/2,k=[-1,b,-0,1,b,0,-1,-b,0,1,-b,0,0,-1,-b,0,1,-b,0,-1,b,0,1,b,b,0,1,b,0,-1,-b,0,1,-b,0,-1],j=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],$=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],_e=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],et=138/1024,tt=239/1024,rt=60/1024,it=26/1024,nt=-40/1024,ot=20/1024,at=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],st=new Array,ut=new Array,ft=new Array,lt=new Array,ht=0,pt=new Array(3),mt=new Array(3),dt;for(dt=0;dt<3;dt++)pt[dt]=Vector3.Zero(),mt[dt]=Vector2.Zero();for(var gt=0;gt<20;gt++){for(dt=0;dt<3;dt++){var _t=j[3*gt+dt];pt[dt].copyFromFloats(k[3*$[_t]],k[3*$[_t]+1],k[3*$[_t]+2]),pt[dt].normalize().scaleInPlace(e),mt[dt].copyFromFloats(_e[2*_t]*et+rt+at[gt]*nt,_e[2*_t+1]*tt+it+at[gt]*ot)}for(var yt=function(vt,Et,xt,bt){var Mt=Vector3.Lerp(pt[0],pt[2],Et/s),Rt=Vector3.Lerp(pt[1],pt[2],Et/s),Pt=s===Et?pt[2]:Vector3.Lerp(Mt,Rt,vt/(s-Et));Pt.normalize();var It;if(o){var Dt=Vector3.Lerp(pt[0],pt[2],bt/s),Ct=Vector3.Lerp(pt[1],pt[2],bt/s);It=Vector3.Lerp(Dt,Ct,xt/(s-bt))}else It=new Vector3(Pt.x,Pt.y,Pt.z);It.x/=c,It.y/=d,It.z/=_,It.normalize();var Ot=Vector2.Lerp(mt[0],mt[2],Et/s),Ft=Vector2.Lerp(mt[1],mt[2],Et/s),wt=s===Et?mt[2]:Vector2.Lerp(Ot,Ft,vt/(s-Et));ut.push(Pt.x*c,Pt.y*d,Pt.z*_),ft.push(It.x,It.y,It.z),lt.push(wt.x,wt.y),st.push(ht),ht++},Tt=0;Tt<s;Tt++)for(var St=0;St+Tt<s;St++)yt(St,Tt,St+1/3,Tt+1/3),yt(St+1,Tt,St+1/3,Tt+1/3),yt(St,Tt+1,St+1/3,Tt+1/3),St+Tt+1<s&&(yt(St+1,Tt,St+2/3,Tt+2/3),yt(St+1,Tt+1,St+2/3,Tt+2/3),yt(St,Tt+1,St+2/3,Tt+2/3))}VertexData._ComputeSides(i,ut,st,ft,lt,a.frontUVs,a.backUVs);var At=new VertexData;return At.indices=st,At.positions=ut,At.normals=ft,At.uvs=lt,At}function CreateIcoSphere(a,i,e){i===void 0&&(i={}),e===void 0&&(e=null);var o=new Mesh(a,e);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),o._originalBuilderSideOrientation=i.sideOrientation;var s=CreateIcoSphereVertexData(i);return s.applyToMesh(o,i.updatable),o}VertexData.CreateIcoSphere=CreateIcoSphereVertexData;Mesh.CreateIcoSphere=function(a,i,e){return CreateIcoSphere(a,i,e)};function CreateDecal(a,i,e){var o=i.getIndices(),s=i.getVerticesData(VertexBuffer.PositionKind),c=i.getVerticesData(VertexBuffer.NormalKind),d=i.getVerticesData(VertexBuffer.UVKind),_=e.position||Vector3.Zero(),b=e.normal||Vector3.Up(),k=e.size||Vector3.One(),j=e.angle||0;if(!b){var $=new Vector3(0,0,1),_e=i.getScene().activeCamera,et=Vector3.TransformCoordinates($,_e.getWorldMatrix());b=_e.globalPosition.subtract(et)}var tt=-Math.atan2(b.z,b.x)-Math.PI/2,rt=Math.sqrt(b.x*b.x+b.z*b.z),it=Math.atan2(b.y,rt),nt=Matrix.RotationYawPitchRoll(tt,it,j).multiply(Matrix.Translation(_.x,_.y,_.z)),ot=Matrix.Invert(nt),at=i.getWorldMatrix(),st=at.multiply(ot),ut=new VertexData;ut.indices=[],ut.positions=[],ut.normals=[],ut.uvs=[];for(var ft=0,lt=function(yt){var Tt=new PositionNormalTextureVertex;if(!o||!s||!c)return Tt;var St=o[yt];return Tt.position=new Vector3(s[St*3],s[St*3+1],s[St*3+2]),Tt.position=Vector3.TransformCoordinates(Tt.position,st),Tt.normal=new Vector3(c[St*3],c[St*3+1],c[St*3+2]),Tt.normal=Vector3.TransformNormal(Tt.normal,st),e.captureUVS&&d&&(Tt.uv=new Vector2(d[St*2],d[St*2+1])),Tt},ht=function(yt,Tt){if(yt.length===0)return yt;for(var St=.5*Math.abs(Vector3.Dot(k,Tt)),At=function(Bt,Ut){var Vt=Vector3.GetClipFactor(Bt.position,Ut.position,Tt,St);return new PositionNormalTextureVertex(Vector3.Lerp(Bt.position,Ut.position,Vt),Vector3.Lerp(Bt.normal,Ut.normal,Vt))},vt=new Array,Et=0;Et<yt.length;Et+=3){var xt,bt,Mt,Rt=0,Pt=null,It=null,Dt=null,Ct=null,Ot=Vector3.Dot(yt[Et].position,Tt)-St,Ft=Vector3.Dot(yt[Et+1].position,Tt)-St,wt=Vector3.Dot(yt[Et+2].position,Tt)-St;switch(xt=Ot>0,bt=Ft>0,Mt=wt>0,Rt=(xt?1:0)+(bt?1:0)+(Mt?1:0),Rt){case 0:vt.push(yt[Et]),vt.push(yt[Et+1]),vt.push(yt[Et+2]);break;case 1:if(xt&&(Pt=yt[Et+1],It=yt[Et+2],Dt=At(yt[Et],Pt),Ct=At(yt[Et],It)),bt){Pt=yt[Et],It=yt[Et+2],Dt=At(yt[Et+1],Pt),Ct=At(yt[Et+1],It),vt.push(Dt),vt.push(It.clone()),vt.push(Pt.clone()),vt.push(It.clone()),vt.push(Dt.clone()),vt.push(Ct);break}Mt&&(Pt=yt[Et],It=yt[Et+1],Dt=At(yt[Et+2],Pt),Ct=At(yt[Et+2],It)),Pt&&It&&Dt&&Ct&&(vt.push(Pt.clone()),vt.push(It.clone()),vt.push(Dt),vt.push(Ct),vt.push(Dt.clone()),vt.push(It.clone()));break;case 2:xt||(Pt=yt[Et].clone(),It=At(Pt,yt[Et+1]),Dt=At(Pt,yt[Et+2]),vt.push(Pt),vt.push(It),vt.push(Dt)),bt||(Pt=yt[Et+1].clone(),It=At(Pt,yt[Et+2]),Dt=At(Pt,yt[Et]),vt.push(Pt),vt.push(It),vt.push(Dt)),Mt||(Pt=yt[Et+2].clone(),It=At(Pt,yt[Et]),Dt=At(Pt,yt[Et+1]),vt.push(Pt),vt.push(It),vt.push(Dt));break}}return vt},pt=0;pt<o.length;pt+=3){var mt=new Array;if(mt.push(lt(pt)),mt.push(lt(pt+1)),mt.push(lt(pt+2)),mt=ht(mt,new Vector3(1,0,0)),mt=ht(mt,new Vector3(-1,0,0)),mt=ht(mt,new Vector3(0,1,0)),mt=ht(mt,new Vector3(0,-1,0)),mt=ht(mt,new Vector3(0,0,1)),mt=ht(mt,new Vector3(0,0,-1)),mt.length!==0)for(var dt=0;dt<mt.length;dt++){var gt=mt[dt];ut.indices.push(ft),gt.position.toArray(ut.positions,ft*3),gt.normal.toArray(ut.normals,ft*3),e.captureUVS?gt.uv.toArray(ut.uvs,ft*2):(ut.uvs.push(.5+gt.position.x/k.x),ut.uvs.push(.5+gt.position.y/k.y)),ft++}}var _t=new Mesh(a,i.getScene());return ut.applyToMesh(_t),_t.position=_.clone(),_t.rotation=new Vector3(it,tt,j),_t}Mesh.CreateDecal=function(a,i,e,o,s,c){var d={position:e,normal:o,size:s,angle:c};return CreateDecal(a,i,d)};function CreateCapsuleVertexData(a){a===void 0&&(a={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6});var i=Math.max(a.subdivisions?a.subdivisions:2,1),e=Math.max(a.tessellation?a.tessellation:16,3),o=Math.max(a.height?a.height:1,0),s=Math.max(a.radius?a.radius:.25,0),c=Math.max(a.capSubdivisions?a.capSubdivisions:6,1),d=e,_=i,b=Math.max(a.radiusTop?a.radiusTop:s,0),k=Math.max(a.radiusBottom?a.radiusBottom:s,0),j=o-(b+k),$=0,_e=2*Math.PI,et=Math.max(a.topCapSubdivisions?a.topCapSubdivisions:c,1),tt=Math.max(a.bottomCapSubdivisions?a.bottomCapSubdivisions:c,1),rt=Math.acos((k-b)/o),it=[],nt=[],ot=[],at=[],st=0,ut=[],ft=j*.5,lt=Math.PI*.5,ht,pt,mt=Vector3.Zero(),dt=Vector3.Zero(),gt=Math.cos(rt),_t=Math.sin(rt),yt=new Vector2(b*_t,ft+b*gt).subtract(new Vector2(k*_t,-ft+k*gt)).length(),Tt=b*rt+yt+k*(lt-rt),St=0;for(pt=0;pt<=et;pt++){var At=[],vt=lt-rt*(pt/et);St+=b*rt/et;var Et=Math.cos(vt),xt=Math.sin(vt),bt=Et*b;for(ht=0;ht<=d;ht++){var Mt=ht/d,Rt=Mt*_e+$,Pt=Math.sin(Rt),It=Math.cos(Rt);dt.x=bt*Pt,dt.y=ft+xt*b,dt.z=bt*It,nt.push(dt.x,dt.y,dt.z),mt.set(Et*Pt,xt,Et*It),ot.push(mt.x,mt.y,mt.z),at.push(Mt,1-St/Tt),At.push(st),st++}ut.push(At)}var Dt=o-b-k+gt*b-gt*k,Ct=_t*(k-b)/Dt;for(pt=1;pt<=_;pt++){var At=[];St+=yt/_;var bt=_t*(pt*(k-b)/_+b);for(ht=0;ht<=d;ht++){var Mt=ht/d,Rt=Mt*_e+$,Pt=Math.sin(Rt),It=Math.cos(Rt);dt.x=bt*Pt,dt.y=ft+gt*b-pt*Dt/_,dt.z=bt*It,nt.push(dt.x,dt.y,dt.z),mt.set(Pt,Ct,It).normalize(),ot.push(mt.x,mt.y,mt.z),at.push(Mt,1-St/Tt),At.push(st),st++}ut.push(At)}for(pt=1;pt<=tt;pt++){var At=[],vt=lt-rt-(Math.PI-rt)*(pt/tt);St+=k*rt/tt;var Et=Math.cos(vt),xt=Math.sin(vt),bt=Et*k;for(ht=0;ht<=d;ht++){var Mt=ht/d,Rt=Mt*_e+$,Pt=Math.sin(Rt),It=Math.cos(Rt);dt.x=bt*Pt,dt.y=-ft+xt*k,dt.z=bt*It,nt.push(dt.x,dt.y,dt.z),mt.set(Et*Pt,xt,Et*It),ot.push(mt.x,mt.y,mt.z),at.push(Mt,1-St/Tt),At.push(st),st++}ut.push(At)}for(ht=0;ht<d;ht++)for(pt=0;pt<et+_+tt;pt++){var Ot=ut[pt][ht],Ft=ut[pt+1][ht],wt=ut[pt+1][ht+1],Bt=ut[pt][ht+1];it.push(Ot),it.push(Ft),it.push(Bt),it.push(Ft),it.push(wt),it.push(Bt)}if(it=it.reverse(),a.orientation&&!a.orientation.equals(Vector3.Up())){var Ut=new Matrix;a.orientation.clone().scale(Math.PI*.5).cross(Vector3.Up()).toQuaternion().toRotationMatrix(Ut);for(var Vt=Vector3.Zero(),Gt=0;Gt<nt.length;Gt+=3)Vt.set(nt[Gt],nt[Gt+1],nt[Gt+2]),Vector3.TransformCoordinatesToRef(Vt.clone(),Ut,Vt),nt[Gt]=Vt.x,nt[Gt+1]=Vt.y,nt[Gt+2]=Vt.z}var Lt=new VertexData;return Lt.positions=nt,Lt.normals=ot,Lt.uvs=at,Lt.indices=it,Lt}function CreateCapsule(a,i,e){i===void 0&&(i={orientation:Vector3.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1}),e===void 0&&(e=null);var o=new Mesh(a,e),s=CreateCapsuleVertexData(i);return s.applyToMesh(o,i.updatable),o}Mesh.CreateCapsule=function(a,i,e){return CreateCapsule(a,i,e)};VertexData.CreateCapsule=CreateCapsuleVertexData;var _IsoVector=function(){function a(i,e){i===void 0&&(i=0),e===void 0&&(e=0),this.x=i,this.y=e,i!==Math.floor(i)&&Logger$2.Warn("x is not an integer, floor(x) used"),e!==Math.floor(e)&&Logger$2.Warn("y is not an integer, floor(y) used")}return a.prototype.clone=function(){return new a(this.x,this.y)},a.prototype.rotate60About=function(i){var e=this.x;return this.x=i.x+i.y-this.y,this.y=e+this.y-i.x,this},a.prototype.rotateNeg60About=function(i){var e=this.x;return this.x=e+this.y-i.y,this.y=i.x+i.y-e,this},a.prototype.rotate120=function(i,e){i!==Math.floor(i)&&Logger$2.Warn("m not an integer only floor(m) used"),e!==Math.floor(e)&&Logger$2.Warn("n not an integer only floor(n) used");var o=this.x;return this.x=i-o-this.y,this.y=e+o,this},a.prototype.rotateNeg120=function(i,e){i!==Math.floor(i)&&Logger$2.Warn("m is not an integer, floor(m) used"),e!==Math.floor(e)&&Logger$2.Warn("n is not an integer, floor(n) used");var o=this.x;return this.x=this.y-e,this.y=i+e-o-this.y,this},a.prototype.toCartesianOrigin=function(i,e){var o=Vector3.Zero();return o.x=i.x+2*this.x*e+this.y*e,o.y=i.y+Math.sqrt(3)*this.y*e,o},a.Zero=function(){return new a(0,0)},a}(),_PrimaryIsoTriangle=function(){function a(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new PolyhedronData("icosahedron","Regular",[[0,PHI,-1],[-PHI,1,0],[-1,0,-PHI],[1,0,-PHI],[PHI,1,0],[0,PHI,1],[-1,0,PHI],[-PHI,-1,0],[0,-PHI,-1],[PHI,-1,0],[1,0,PHI],[0,-PHI,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}return a.prototype.setIndices=function(){var i=12,e={},o=this.m,s=this.n,c=o,d=1,_=0;s!==0&&(c=Scalar.HCF(o,s)),d=o/c,_=s/c;var b,k,j,$,_e,et=_IsoVector.Zero(),tt=new _IsoVector(o,s),rt=new _IsoVector(-s,o+s),it=_IsoVector.Zero(),nt=_IsoVector.Zero(),ot=_IsoVector.Zero(),at=[],st,ut,ft,lt,ht=[],pt=this.vertByDist;this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(var mt=0;mt<20;mt++){if(at=this.IDATA.face[mt],j=at[2],$=at[1],_e=at[0],ft=et.x+"|"+et.y,st=mt+"|"+ft,st in e||(e[st]=j,ht[j]=[at[pt[ft][0]],pt[ft][1]]),ft=tt.x+"|"+tt.y,st=mt+"|"+ft,st in e||(e[st]=$,ht[$]=[at[pt[ft][0]],pt[ft][1]]),ft=rt.x+"|"+rt.y,st=mt+"|"+ft,st in e||(e[st]=_e,ht[_e]=[at[pt[ft][0]],pt[ft][1]]),b=this.IDATA.edgematch[mt][0],k=this.IDATA.edgematch[mt][1],k==="B")for(var dt=1;dt<c;dt++)nt.x=o-dt*(d+_),nt.y=s+dt*d,ot.x=-dt*_,ot.y=dt*(d+_),ft=nt.x+"|"+nt.y,lt=ot.x+"|"+ot.y,gt(mt,b,ft,lt);if(k==="O")for(var dt=1;dt<c;dt++)ot.x=-dt*_,ot.y=dt*(d+_),it.x=dt*d,it.y=dt*_,ft=ot.x+"|"+ot.y,lt=it.x+"|"+it.y,gt(mt,b,ft,lt);if(b=this.IDATA.edgematch[mt][2],k=this.IDATA.edgematch[mt][3],k&&k==="A")for(var dt=1;dt<c;dt++)it.x=dt*d,it.y=dt*_,nt.x=o-(c-dt)*(d+_),nt.y=s+(c-dt)*d,ft=it.x+"|"+it.y,lt=nt.x+"|"+nt.y,gt(mt,b,ft,lt);for(var dt=0;dt<this.vertices.length;dt++)ft=this.vertices[dt].x+"|"+this.vertices[dt].y,st=mt+"|"+ft,st in e||(e[st]=i++,pt[ft][0]>2?ht[e[st]]=[-pt[ft][0],pt[ft][1],e[st]]:ht[e[st]]=[at[pt[ft][0]],pt[ft][1],e[st]])}function gt(_t,yt,Tt,St){st=_t+"|"+Tt,ut=yt+"|"+St,st in e||ut in e?st in e&&!(ut in e)?e[ut]=e[st]:ut in e&&!(st in e)&&(e[st]=e[ut]):(e[st]=i,e[ut]=i,i++),pt[Tt][0]>2?ht[e[st]]=[-pt[Tt][0],pt[Tt][1],e[st]]:ht[e[st]]=[at[pt[Tt][0]],pt[Tt][1],e[st]]}this.closestTo=ht,this.vecToIdx=e},a.prototype.calcCoeffs=function(){var i=this.m,e=this.n,o=Math.sqrt(3)/3,s=i*i+e*e+i*e;this.coau=(i+e)/s,this.cobu=-e/s,this.coav=-o*(i-e)/s,this.cobv=o*(2*i+e)/s},a.prototype.createInnerFacets=function(){for(var i=this.m,e=this.n,o=0;o<e+i+1;o++)for(var s=this.min[o];s<this.max[o]+1;s++)s<this.max[o]&&s<this.max[o+1]+1&&this.innerFacets.push(["|"+s+"|"+o,"|"+s+"|"+(o+1),"|"+(s+1)+"|"+o]),o>0&&s<this.max[o-1]&&s+1<this.max[o]+1&&this.innerFacets.push(["|"+s+"|"+o,"|"+(s+1)+"|"+o,"|"+(s+1)+"|"+(o-1)])},a.prototype.edgeVecsABOB=function(){for(var i=this.m,e=this.n,o=new _IsoVector(-e,i+e),s=1;s<i+e;s++){var c=new _IsoVector(this.min[s],s),d=new _IsoVector(this.min[s-1],s-1),_=new _IsoVector(this.min[s+1],s+1),b=c.clone(),k=d.clone(),j=_.clone();b.rotate60About(o),k.rotate60About(o),j.rotate60About(o);var $=new _IsoVector(this.max[b.y],b.y),_e=new _IsoVector(this.max[b.y-1],b.y-1),et=new _IsoVector(this.max[b.y-1]-1,b.y-1);(b.x!==$.x||b.y!==$.y)&&(b.x!==_e.x?(this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([c,_e,et]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([c,et,$])):b.y===j.y?(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([c,d,_e]),this.vertexTypes.push([1,0,1]),this.isoVecsABOB.push([c,_e,_])):(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([c,d,_e]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([c,_e,$])))}},a.prototype.mapABOBtoOBOA=function(){for(var i=new _IsoVector(0,0),e=0;e<this.isoVecsABOB.length;e++){for(var o=[],s=0;s<3;s++)i.x=this.isoVecsABOB[e][s].x,i.y=this.isoVecsABOB[e][s].y,this.vertexTypes[e][s]===0&&i.rotateNeg120(this.m,this.n),o.push(i.clone());this.isoVecsOBOA.push(o)}},a.prototype.mapABOBtoBAOA=function(){for(var i=new _IsoVector(0,0),e=0;e<this.isoVecsABOB.length;e++){for(var o=[],s=0;s<3;s++)i.x=this.isoVecsABOB[e][s].x,i.y=this.isoVecsABOB[e][s].y,this.vertexTypes[e][s]===1&&i.rotate120(this.m,this.n),o.push(i.clone());this.isoVecsBAOA.push(o)}},a.prototype.MapToFace=function(i,e){for(var o=this.IDATA.face[i],s=o[2],c=o[1],d=o[0],_=Vector3.FromArray(this.IDATA.vertex[s]),b=Vector3.FromArray(this.IDATA.vertex[c]),k=Vector3.FromArray(this.IDATA.vertex[d]),j=b.subtract(_),$=k.subtract(_),_e=j.scale(this.coau).add($.scale(this.cobu)),et=j.scale(this.coav).add($.scale(this.cobv)),tt=[],rt,it=TmpVectors.Vector3[0],nt=0;nt<this.cartesian.length;nt++)it=_e.scale(this.cartesian[nt].x).add(et.scale(this.cartesian[nt].y)).add(_),tt[nt]=[it.x,it.y,it.z],rt=i+"|"+this.vertices[nt].x+"|"+this.vertices[nt].y,e.vertex[this.vecToIdx[rt]]=[it.x,it.y,it.z]},a.prototype.build=function(i,e){var o=new Array,s=_IsoVector.Zero(),c=new _IsoVector(i,e),d=new _IsoVector(-e,i+e);o.push(s,c,d);for(var _=e;_<i+1;_++)for(var b=0;b<i+1-_;b++)o.push(new _IsoVector(b,_));if(e>0){for(var k=Scalar.HCF(i,e),j=i/k,$=e/k,_e=1;_e<k;_e++)o.push(new _IsoVector(_e*j,_e*$)),o.push(new _IsoVector(-_e*$,_e*(j+$))),o.push(new _IsoVector(i-_e*(j+$),e+_e*j));for(var et=i/e,tt=1;tt<e;tt++)for(var rt=0;rt<tt*et;rt++)o.push(new _IsoVector(rt,tt)),o.push(new _IsoVector(rt,tt).rotate120(i,e)),o.push(new _IsoVector(rt,tt).rotateNeg120(i,e))}o.sort(function(Tt,St){return Tt.x-St.x}),o.sort(function(Tt,St){return Tt.y-St.y});for(var it=new Array(i+e+1),nt=new Array(i+e+1),_e=0;_e<it.length;_e++)it[_e]=1/0,nt[_e]=-1/0;for(var ot=0,at=0,st=o.length,_e=0;_e<st;_e++)at=o[_e].x,ot=o[_e].y,it[ot]=Math.min(at,it[ot]),nt[ot]=Math.max(at,nt[ot]);for(var ut=function(Tt,St){var At=Tt.clone();return St==="A"&&At.rotateNeg120(i,e),St==="B"&&At.rotate120(i,e),At.x<0?At.y:At.x+At.y},ft=[],lt=[],ht=[],pt=[],mt={},dt=[],gt=-1,_t=-1,_e=0;_e<st;_e++)ft[_e]=o[_e].toCartesianOrigin(new _IsoVector(0,0),.5),lt[_e]=ut(o[_e],"O"),ht[_e]=ut(o[_e],"A"),pt[_e]=ut(o[_e],"B"),lt[_e]===ht[_e]&&ht[_e]===pt[_e]?(gt=3,_t=lt[_e]):lt[_e]===ht[_e]?(gt=4,_t=lt[_e]):ht[_e]===pt[_e]?(gt=5,_t=ht[_e]):pt[_e]===lt[_e]&&(gt=6,_t=lt[_e]),lt[_e]<ht[_e]&&lt[_e]<pt[_e]&&(gt=2,_t=lt[_e]),ht[_e]<lt[_e]&&ht[_e]<pt[_e]&&(gt=1,_t=ht[_e]),pt[_e]<ht[_e]&&pt[_e]<lt[_e]&&(gt=0,_t=pt[_e]),dt.push([gt,_t,o[_e].x,o[_e].y]);dt.sort(function(Tt,St){return Tt[2]-St[2]}),dt.sort(function(Tt,St){return Tt[3]-St[3]}),dt.sort(function(Tt,St){return Tt[1]-St[1]}),dt.sort(function(Tt,St){return Tt[0]-St[0]});for(var yt=0;yt<dt.length;yt++)mt[dt[yt][2]+"|"+dt[yt][3]]=[dt[yt][0],dt[yt][1],yt];return this.m=i,this.n=e,this.vertices=o,this.vertByDist=mt,this.cartesian=ft,this.min=it,this.max=nt,this},a}(),PolyhedronData=function(){function a(i,e,o,s){this.name=i,this.category=e,this.vertex=o,this.face=s}return a}(),GeodesicData=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i.prototype.innerToData=function(e,o){for(var s=0;s<o.innerFacets.length;s++)this.face.push(o.innerFacets[s].map(function(c){return o.vecToIdx[e+c]}))},i.prototype.mapABOBtoDATA=function(e,o){for(var s=o.IDATA.edgematch[e][0],c=0;c<o.isoVecsABOB.length;c++){for(var d=[],_=0;_<3;_++)o.vertexTypes[c][_]===0?d.push(e+"|"+o.isoVecsABOB[c][_].x+"|"+o.isoVecsABOB[c][_].y):d.push(s+"|"+o.isoVecsABOB[c][_].x+"|"+o.isoVecsABOB[c][_].y);this.face.push([o.vecToIdx[d[0]],o.vecToIdx[d[1]],o.vecToIdx[d[2]]])}},i.prototype.mapOBOAtoDATA=function(e,o){for(var s=o.IDATA.edgematch[e][0],c=0;c<o.isoVecsOBOA.length;c++){for(var d=[],_=0;_<3;_++)o.vertexTypes[c][_]===1?d.push(e+"|"+o.isoVecsOBOA[c][_].x+"|"+o.isoVecsOBOA[c][_].y):d.push(s+"|"+o.isoVecsOBOA[c][_].x+"|"+o.isoVecsOBOA[c][_].y);this.face.push([o.vecToIdx[d[0]],o.vecToIdx[d[1]],o.vecToIdx[d[2]]])}},i.prototype.mapBAOAtoDATA=function(e,o){for(var s=o.IDATA.edgematch[e][2],c=0;c<o.isoVecsBAOA.length;c++){for(var d=[],_=0;_<3;_++)o.vertexTypes[c][_]===1?d.push(e+"|"+o.isoVecsBAOA[c][_].x+"|"+o.isoVecsBAOA[c][_].y):d.push(s+"|"+o.isoVecsBAOA[c][_].x+"|"+o.isoVecsBAOA[c][_].y);this.face.push([o.vecToIdx[d[0]],o.vecToIdx[d[1]],o.vecToIdx[d[2]]])}},i.prototype.orderData=function(e){for(var o=[],s=0;s<13;s++)o[s]=[];for(var c=e.closestTo,s=0;s<c.length;s++)c[s][0]>-1?c[s][1]>0&&o[c[s][0]].push([s,c[s][1]]):o[12].push([s,c[s][0]]);for(var d=[],s=0;s<12;s++)d[s]=s;for(var _=12,s=0;s<12;s++){o[s].sort(function(j,$){return j[1]-$[1]});for(var b=0;b<o[s].length;b++)d[o[s][b][0]]=_++}for(var b=0;b<o[12].length;b++)d[o[12][b][0]]=_++;for(var s=0;s<this.vertex.length;s++)this.vertex[s].push(d[s]);this.vertex.sort(function(k,j){return k[3]-j[3]});for(var s=0;s<this.vertex.length;s++)this.vertex[s].pop();for(var s=0;s<this.face.length;s++)for(var b=0;b<this.face[s].length;b++)this.face[s][b]=d[this.face[s][b]];this.sharedNodes=o[12].length,this.poleNodes=this.vertex.length-this.sharedNodes},i.prototype.setOrder=function(e,o){var s=[],c=[],d=o.pop();c.push(d);var _=this.face[d].indexOf(e);_=(_+2)%3;var b=this.face[d][_];s.push(b);for(var k=0;o.length>0;)d=o[k],this.face[d].indexOf(b)>-1?(_=(this.face[d].indexOf(b)+1)%3,b=this.face[d][_],s.push(b),c.push(d),o.splice(k,1),k=0):k++;return this.adjacentFaces.push(s),c},i.prototype.toGoldbergData=function(){var e=this,o=new PolyhedronData("GeoDual","Goldberg",[],[]);o.name="GD dual";for(var s=this.vertex.length,c=new Array(s),d=0;d<s;d++)c[d]=[];for(var _=0;_<this.face.length;_++)for(var b=0;b<3;b++)c[this.face[_][b]].push(_);var k=0,j=0,$=0,_e=[],et=[];this.adjacentFaces=[];for(var tt=0;tt<c.length;tt++)o.face[tt]=this.setOrder(tt,c[tt].concat([])),c[tt].forEach(function(rt){k=0,j=0,$=0,_e=e.face[rt];for(var it=0;it<3;it++)et=e.vertex[_e[it]],k+=et[0],j+=et[1],$+=et[2];o.vertex[rt]=[k/3,j/3,$/3]});return o},i.BuildGeodesicData=function(e){var o=new i("Geodesic-m-n","Geodesic",[[0,PHI,-1],[-PHI,1,0],[-1,0,-PHI],[1,0,-PHI],[PHI,1,0],[0,PHI,1],[-1,0,PHI],[-PHI,-1,0],[0,-PHI,-1],[PHI,-1,0],[1,0,PHI],[0,-PHI,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(var s=0;s<e.IDATA.face.length;s++)e.MapToFace(s,o),o.innerToData(s,e),e.IDATA.edgematch[s][1]==="B"&&o.mapABOBtoDATA(s,e),e.IDATA.edgematch[s][1]==="O"&&o.mapOBOAtoDATA(s,e),e.IDATA.edgematch[s][3]==="A"&&o.mapBAOAtoDATA(s,e);o.orderData(e);var c=1;return o.vertex=o.vertex.map(function(d){var _=d[0],b=d[1],k=d[2],j=Math.sqrt(_*_+b*b+k*k);return d[0]*=c/j,d[1]*=c/j,d[2]*=c/j,d}),o},i}(PolyhedronData);function CreateGeodesic(a,i,e){e===void 0&&(e=null);var o=i.m||1;o!==Math.floor(o)&&Logger$2.Warn("m not an integer only floor(m) used");var s=i.n||0;if(s!==Math.floor(s)&&Logger$2.Warn("n not an integer only floor(n) used"),s>o){var c=s;s=o,o=c,Logger$2.Warn("n > m therefore m and n swapped")}var d=new _PrimaryIsoTriangle;d.build(o,s);var _=GeodesicData.BuildGeodesicData(d),b={custom:_,size:i.size,sizeX:i.sizeX,sizeY:i.sizeY,sizeZ:i.sizeZ,faceUV:i.faceUV,faceColors:i.faceColors,flat:i.flat,updatable:i.updatable,sideOrientation:i.sideOrientation,frontUVs:i.frontUVs,backUVs:i.backUVs},k=CreatePolyhedron(a,b,e);return k}function CreateGoldbergVertexData(a,i){for(var e=a.size,o=a.sizeX||e||1,s=a.sizeY||e||1,c=a.sizeZ||e||1,d=a.sideOrientation===0?0:a.sideOrientation||VertexData.DEFAULTSIDE,_=new Array,b=new Array,k=new Array,j=new Array,$=1/0,_e=-1/0,et=1/0,tt=-1/0,rt=0;rt<i.vertex.length;rt++)$=Math.min($,i.vertex[rt][0]*o),_e=Math.max(_e,i.vertex[rt][0]*o),et=Math.min(et,i.vertex[rt][1]*s),tt=Math.max(tt,i.vertex[rt][1]*s);for(var it=0,nt=0;nt<i.face.length;nt++){for(var ot=i.face[nt],at=Vector3.FromArray(i.vertex[ot[0]]),st=Vector3.FromArray(i.vertex[ot[2]]),ut=Vector3.FromArray(i.vertex[ot[1]]),ft=st.subtract(at),lt=ut.subtract(at),ht=Vector3.Cross(lt,ft).normalize(),rt=0;rt<ot.length;rt++){k.push(ht.x,ht.y,ht.z);var pt=i.vertex[ot[rt]];_.push(pt[0]*o,pt[1]*s,pt[2]*c),j.push((pt[0]*o-$)/(_e-$),(pt[1]*s-et)/(tt-et))}for(var rt=0;rt<ot.length-2;rt++)b.push(it,it+rt+2,it+rt+1);it+=ot.length}VertexData._ComputeSides(d,_,b,k,j);var mt=new VertexData;return mt.positions=_,mt.indices=b,mt.normals=k,mt.uvs=j,mt}function CreateGoldberg(a,i,e){var o=i.m||1;o!==Math.floor(o)&&Logger$2.Warn("m not an integer only floor(m) used");var s=i.n||0;if(s!==Math.floor(s)&&Logger$2.Warn("n not an integer only floor(n) used"),s>o){var c=s;s=o,o=c,Logger$2.Warn("n > m therefore m and n swapped")}var d=new _PrimaryIsoTriangle;d.build(o,s);var _=GeodesicData.BuildGeodesicData(d),b=_.toGoldbergData(),k=new GoldbergMesh(a);i.sideOrientation=Mesh._GetDefaultSideOrientation(i.sideOrientation),k._originalBuilderSideOrientation=i.sideOrientation;var j=CreateGoldbergVertexData(i,b);j.applyToMesh(k,i.updatable),k.nbSharedFaces=_.sharedNodes,k.nbUnsharedFaces=_.poleNodes,k.adjacentFaces=_.adjacentFaces,k.nbFaces=k.nbSharedFaces+k.nbUnsharedFaces,k.nbFacesAtPole=(k.nbUnsharedFaces-12)/12;for(var $=0;$<_.vertex.length;$++)k.faceCenters.push(Vector3.FromArray(_.vertex[$])),k.faceColors.push(new Color4(1,1,1,1));for(var $=0;$<b.face.length;$++){var _e=b.face[$],et=Vector3.FromArray(b.vertex[_e[0]]),tt=Vector3.FromArray(b.vertex[_e[2]]),rt=Vector3.FromArray(b.vertex[_e[1]]),it=tt.subtract(et),nt=rt.subtract(et),ot=Vector3.Cross(nt,it).normalize(),at=Vector3.Cross(nt,ot).normalize();k.faceXaxis.push(nt.normalize()),k.faceYaxis.push(ot),k.faceZaxis.push(at)}return k.setMetadata(),k}function GoldbergCreate(a){return function(i){__extends(e,i);function e(){var o=i!==null&&i.apply(this,arguments)||this;return o.faceColors=[],o.faceCenters=[],o.faceZaxis=[],o.faceXaxis=[],o.faceYaxis=[],o}return e.prototype.setMetadata=function(){this.metadata={nbSharedFaces:this.nbSharedFaces,nbUnsharedFaces:this.nbUnsharedFaces,nbFacesAtPole:this.nbFacesAtPole,nbFaces:this.nbFaces,faceCenters:this.faceCenters,faceXaxis:this.faceXaxis,faceYaxis:this.faceYaxis,faceZaxis:this.faceZaxis,adjacentFaces:this.adjacentFaces}},e.prototype.relFace=function(o,s){return s===void 0?(o>this.nbUnsharedFaces-1&&(Logger$2.Warn("Maximum number of unshared faces used"),o=this.nbUnsharedFaces-1),this.nbUnsharedFaces+o):(o>11&&(Logger$2.Warn("Last pole used"),o=11),s>this.nbFacesAtPole-1&&(Logger$2.Warn("Maximum number of faces at a pole used"),s=this.nbFacesAtPole-1),12+o*this.nbFacesAtPole+s)},e.prototype.refreshFaceData=function(){this.nbSharedFaces=this.metadata.nbSharedFaces,this.nbUnsharedFaces=this.metadata.nbUnsharedFaces,this.nbFacesAtPole=this.metadata.nbFacesAtPole,this.adjacentFaces=this.metadata.adjacentFaces,this.nbFaces=this.metadata.nbFaces,this.faceCenters=this.metadata.faceCenters,this.faceXaxis=this.metadata.faceXaxis,this.faceYaxis=this.metadata.faceYaxis,this.faceZaxis=this.metadata.faceZaxis},e.prototype.changeFaceColors=function(o){for(var s=0;s<o.length;s++)for(var c=o[s][0],d=o[s][1],_=o[s][2],b=c;b<d+1;b++)this.faceColors[b]=_;for(var k=[],b=0;b<12;b++)for(var s=0;s<5;s++)k.push(this.faceColors[b].r,this.faceColors[b].g,this.faceColors[b].b,this.faceColors[b].a);for(var b=12;b<this.faceColors.length;b++)for(var s=0;s<6;s++)k.push(this.faceColors[b].r,this.faceColors[b].g,this.faceColors[b].b,this.faceColors[b].a);return k},e.prototype.setFaceColors=function(o){var s=this.changeFaceColors(o);this.setVerticesData(VertexBuffer.ColorKind,s)},e.prototype.updateFaceColors=function(o){var s=this.changeFaceColors(o);this.updateVerticesData(VertexBuffer.ColorKind,s)},e.prototype.changeFaceUVs=function(o){for(var s=this.getVerticesData(VertexBuffer.UVKind),c=0;c<o.length;c++){for(var d=o[c][0],_=o[c][1],b=o[c][2],k=o[c][3],j=o[c][4],$=[],_e=[],et=void 0,tt=void 0,rt=0;rt<5;rt++)et=b.x+k*Math.cos(j+rt*Math.PI/2.5),tt=b.y+k*Math.sin(j+rt*Math.PI/2.5),et<0&&(et=0),et>1&&(et=1),$.push(et,tt);for(var rt=0;rt<6;rt++)et=b.x+k*Math.cos(j+rt*Math.PI/3),tt=b.y+k*Math.sin(j+rt*Math.PI/3),et<0&&(et=0),et>1&&(et=1),_e.push(et,tt);for(var it=d;it<Math.min(12,_+1);it++)for(var rt=0;rt<5;rt++)s[10*it+2*rt]=$[2*rt],s[10*it+2*rt+1]=$[2*rt+1];for(var it=Math.max(12,d);it<_+1;it++)for(var rt=0;rt<6;rt++)s[12*it-24+2*rt]=_e[2*rt],s[12*it-23+2*rt]=_e[2*rt+1]}return s},e.prototype.setFaceUVs=function(o){var s=this.changeFaceUVs(o);this.setVerticesData(VertexBuffer.UVKind,s)},e.prototype.updateFaceUVs=function(o){var s=this.changeFaceUVs(o);this.updateVerticesData(VertexBuffer.UVKind,s)},e.prototype.placeOnFaceAt=function(o,s,c){var d=Vector3.RotationFromAxis(this.faceXaxis[s],this.faceYaxis[s],this.faceZaxis[s]);o.rotation=d,o.position=this.faceCenters[s].add(this.faceXaxis[s].scale(c.x)).add(this.faceYaxis[s].scale(c.y)).add(this.faceZaxis[s].scale(c.z))},e}(a)}var GoldbergMesh=GoldbergCreate(Mesh),MeshBuilder={CreateBox,CreateTiledBox,CreateSphere,CreateDisc,CreateIcoSphere,CreateRibbon,CreateCylinder,CreateTorus,CreateTorusKnot,CreateLineSystem,CreateLines,CreateDashedLines,ExtrudeShape,ExtrudeShapeCustom,CreateLathe,CreateTiledPlane,CreatePlane,CreateGround,CreateTiledGround,CreateGroundFromHeightMap,CreatePolygon,ExtrudePolygon,CreateTube,CreatePolyhedron,CreateGeodesic,CreateGoldberg,CreateDecal,CreateCapsule},Ray=function(){function a(i,e,o){o===void 0&&(o=Number.MAX_VALUE),this.origin=i,this.direction=e,this.length=o}return a.prototype.clone=function(){return new a(this.origin.clone(),this.direction.clone(),this.length)},a.prototype.intersectsBoxMinMax=function(i,e,o){o===void 0&&(o=0);var s=a._TmpVector3[0].copyFromFloats(i.x-o,i.y-o,i.z-o),c=a._TmpVector3[1].copyFromFloats(e.x+o,e.y+o,e.z+o),d=0,_=Number.MAX_VALUE,b,k,j,$;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<s.x||this.origin.x>c.x)return!1}else if(b=1/this.direction.x,k=(s.x-this.origin.x)*b,j=(c.x-this.origin.x)*b,j===-1/0&&(j=1/0),k>j&&($=k,k=j,j=$),d=Math.max(k,d),_=Math.min(j,_),d>_)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<s.y||this.origin.y>c.y)return!1}else if(b=1/this.direction.y,k=(s.y-this.origin.y)*b,j=(c.y-this.origin.y)*b,j===-1/0&&(j=1/0),k>j&&($=k,k=j,j=$),d=Math.max(k,d),_=Math.min(j,_),d>_)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<s.z||this.origin.z>c.z)return!1}else if(b=1/this.direction.z,k=(s.z-this.origin.z)*b,j=(c.z-this.origin.z)*b,j===-1/0&&(j=1/0),k>j&&($=k,k=j,j=$),d=Math.max(k,d),_=Math.min(j,_),d>_)return!1;return!0},a.prototype.intersectsBox=function(i,e){return e===void 0&&(e=0),this.intersectsBoxMinMax(i.minimum,i.maximum,e)},a.prototype.intersectsSphere=function(i,e){e===void 0&&(e=0);var o=i.center.x-this.origin.x,s=i.center.y-this.origin.y,c=i.center.z-this.origin.z,d=o*o+s*s+c*c,_=i.radius+e,b=_*_;if(d<=b)return!0;var k=o*this.direction.x+s*this.direction.y+c*this.direction.z;if(k<0)return!1;var j=d-k*k;return j<=b},a.prototype.intersectsTriangle=function(i,e,o){var s=a._TmpVector3[0],c=a._TmpVector3[1],d=a._TmpVector3[2],_=a._TmpVector3[3],b=a._TmpVector3[4];e.subtractToRef(i,s),o.subtractToRef(i,c),Vector3.CrossToRef(this.direction,c,d);var k=Vector3.Dot(s,d);if(k===0)return null;var j=1/k;this.origin.subtractToRef(i,_);var $=Vector3.Dot(_,d)*j;if($<0||$>1)return null;Vector3.CrossToRef(_,s,b);var _e=Vector3.Dot(this.direction,b)*j;if(_e<0||$+_e>1)return null;var et=Vector3.Dot(c,b)*j;return et>this.length?null:new IntersectionInfo(1-$-_e,$,et)},a.prototype.intersectsPlane=function(i){var e,o=Vector3.Dot(i.normal,this.direction);if(Math.abs(o)<999999997475243e-21)return null;var s=Vector3.Dot(i.normal,this.origin);return e=(-i.d-s)/o,e<0?e<-999999997475243e-21?null:0:e},a.prototype.intersectsAxis=function(i,e){switch(e===void 0&&(e=0),i){case"y":var o=(this.origin.y-e)/this.direction.y;return o>0?null:new Vector3(this.origin.x+this.direction.x*-o,e,this.origin.z+this.direction.z*-o);case"x":var o=(this.origin.x-e)/this.direction.x;return o>0?null:new Vector3(e,this.origin.y+this.direction.y*-o,this.origin.z+this.direction.z*-o);case"z":var o=(this.origin.z-e)/this.direction.z;return o>0?null:new Vector3(this.origin.x+this.direction.x*-o,this.origin.y+this.direction.y*-o,e);default:return null}},a.prototype.intersectsMesh=function(i,e){var o=TmpVectors.Matrix[0];return i.getWorldMatrix().invertToRef(o),this._tmpRay?a.TransformToRef(this,o,this._tmpRay):this._tmpRay=a.Transform(this,o),i.intersects(this._tmpRay,e)},a.prototype.intersectsMeshes=function(i,e,o){o?o.length=0:o=[];for(var s=0;s<i.length;s++){var c=this.intersectsMesh(i[s],e);c.hit&&o.push(c)}return o.sort(this._comparePickingInfo),o},a.prototype._comparePickingInfo=function(i,e){return i.distance<e.distance?-1:i.distance>e.distance?1:0},a.prototype.intersectionSegment=function(i,e,o){var s=this.origin,c=TmpVectors.Vector3[0],d=TmpVectors.Vector3[1],_=TmpVectors.Vector3[2],b=TmpVectors.Vector3[3];e.subtractToRef(i,c),this.direction.scaleToRef(a.rayl,_),s.addToRef(_,d),i.subtractToRef(s,b);var k=Vector3.Dot(c,c),j=Vector3.Dot(c,_),$=Vector3.Dot(_,_),_e=Vector3.Dot(c,b),et=Vector3.Dot(_,b),tt=k*$-j*j,rt,it,nt=tt,ot,at,st=tt;tt<a.smallnum?(it=0,nt=1,at=et,st=$):(it=j*et-$*_e,at=k*et-j*_e,it<0?(it=0,at=et,st=$):it>nt&&(it=nt,at=et+j,st=$)),at<0?(at=0,-_e<0?it=0:-_e>k?it=nt:(it=-_e,nt=k)):at>st&&(at=st,-_e+j<0?it=0:-_e+j>k?it=nt:(it=-_e+j,nt=k)),rt=Math.abs(it)<a.smallnum?0:it/nt,ot=Math.abs(at)<a.smallnum?0:at/st;var ut=TmpVectors.Vector3[4];_.scaleToRef(ot,ut);var ft=TmpVectors.Vector3[5];c.scaleToRef(rt,ft),ft.addInPlace(b);var lt=TmpVectors.Vector3[6];ft.subtractToRef(ut,lt);var ht=ot>0&&ot<=this.length&&lt.lengthSquared()<o*o;return ht?ft.length():-1},a.prototype.update=function(i,e,o,s,c,d,_){return this.unprojectRayToRef(i,e,o,s,c,d,_),this},a.Zero=function(){return new a(Vector3.Zero(),Vector3.Zero())},a.CreateNew=function(i,e,o,s,c,d,_){var b=a.Zero();return b.update(i,e,o,s,c,d,_)},a.CreateNewFromTo=function(i,e,o){o===void 0&&(o=Matrix.IdentityReadOnly);var s=e.subtract(i),c=Math.sqrt(s.x*s.x+s.y*s.y+s.z*s.z);return s.normalize(),a.Transform(new a(i,s,c),o)},a.Transform=function(i,e){var o=new a(new Vector3(0,0,0),new Vector3(0,0,0));return a.TransformToRef(i,e,o),o},a.TransformToRef=function(i,e,o){Vector3.TransformCoordinatesToRef(i.origin,e,o.origin),Vector3.TransformNormalToRef(i.direction,e,o.direction),o.length=i.length;var s=o.direction,c=s.length();if(!(c===0||c===1)){var d=1/c;s.x*=d,s.y*=d,s.z*=d,o.length*=c}},a.prototype.unprojectRayToRef=function(i,e,o,s,c,d,_){var b=TmpVectors.Matrix[0];c.multiplyToRef(d,b),b.multiplyToRef(_,b),b.invert();var k=TmpVectors.Vector3[0];k.x=i/o*2-1,k.y=-(e/s*2-1),k.z=-1;var j=TmpVectors.Vector3[1].copyFromFloats(k.x,k.y,1),$=TmpVectors.Vector3[2],_e=TmpVectors.Vector3[3];Vector3._UnprojectFromInvertedMatrixToRef(k,b,$),Vector3._UnprojectFromInvertedMatrixToRef(j,b,_e),this.origin.copyFrom($),_e.subtractToRef($,this.direction),this.direction.normalize()},a._TmpVector3=ArrayTools.BuildArray(6,Vector3.Zero),a.smallnum=1e-8,a.rayl=1e9,a}();Scene.prototype.createPickingRay=function(a,i,e,o,s){s===void 0&&(s=!1);var c=Ray.Zero();return this.createPickingRayToRef(a,i,e,c,o,s),c};Scene.prototype.createPickingRayToRef=function(a,i,e,o,s,c){c===void 0&&(c=!1);var d=this.getEngine();if(!s){if(!this.activeCamera)return this;s=this.activeCamera}var _=s.viewport,b=_.toGlobal(d.getRenderWidth(),d.getRenderHeight());return a=a/d.getHardwareScalingLevel()-b.x,i=i/d.getHardwareScalingLevel()-(d.getRenderHeight()-b.y-b.height),o.update(a,i,b.width,b.height,e||Matrix.IdentityReadOnly,c?Matrix.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix()),this};Scene.prototype.createPickingRayInCameraSpace=function(a,i,e){var o=Ray.Zero();return this.createPickingRayInCameraSpaceToRef(a,i,o,e),o};Scene.prototype.createPickingRayInCameraSpaceToRef=function(a,i,e,o){if(!PickingInfo)return this;var s=this.getEngine();if(!o){if(!this.activeCamera)throw new Error("Active camera not set");o=this.activeCamera}var c=o.viewport,d=c.toGlobal(s.getRenderWidth(),s.getRenderHeight()),_=Matrix.Identity();return a=a/s.getHardwareScalingLevel()-d.x,i=i/s.getHardwareScalingLevel()-(s.getRenderHeight()-d.y-d.height),e.update(a,i,d.width,d.height,_,_,o.getProjectionMatrix()),this};Scene.prototype._internalPickForMesh=function(a,i,e,o,s,c,d,_){var b=i(o),k=e.intersects(b,s,d,c,o,_);return!k||!k.hit||!s&&a!=null&&k.distance>=a.distance?null:k};Scene.prototype._internalPick=function(a,i,e,o,s){if(!PickingInfo)return null;for(var c=null,d=0;d<this.meshes.length;d++){var _=this.meshes[d];if(i){if(!i(_))continue}else if(!_.isEnabled()||!_.isVisible||!_.isPickable)continue;var b=_.skeleton&&_.skeleton.overrideMesh?_.skeleton.overrideMesh.getWorldMatrix():_.getWorldMatrix();if(_.hasThinInstances&&_.thinInstanceEnablePicking){var k=this._internalPickForMesh(c,a,_,b,!0,!0,s);if(k){if(o)return c;for(var j=TmpVectors.Matrix[1],$=_.thinInstanceGetWorldMatrices(),_e=0;_e<$.length;_e++){var et=$[_e];et.multiplyToRef(b,j);var tt=this._internalPickForMesh(c,a,_,j,e,o,s,!0);if(tt&&(c=tt,c.thinInstanceIndex=_e,e))return c}}}else{var k=this._internalPickForMesh(c,a,_,b,e,o,s);if(k&&(c=k,e))return c}}return c||new PickingInfo};Scene.prototype._internalMultiPick=function(a,i,e){if(!PickingInfo)return null;for(var o=new Array,s=0;s<this.meshes.length;s++){var c=this.meshes[s];if(i){if(!i(c))continue}else if(!c.isEnabled()||!c.isVisible||!c.isPickable)continue;var d=c.skeleton&&c.skeleton.overrideMesh?c.skeleton.overrideMesh.getWorldMatrix():c.getWorldMatrix();if(c.hasThinInstances&&c.thinInstanceEnablePicking){var _=this._internalPickForMesh(null,a,c,d,!0,!0,e);if(_)for(var b=TmpVectors.Matrix[1],k=c.thinInstanceGetWorldMatrices(),j=0;j<k.length;j++){var $=k[j];$.multiplyToRef(d,b);var _e=this._internalPickForMesh(null,a,c,b,!1,!1,e,!0);_e&&(_e.thinInstanceIndex=j,o.push(_e))}}else{var _=this._internalPickForMesh(null,a,c,d,!1,!1,e);_&&o.push(_)}}return o};Scene.prototype.pickWithBoundingInfo=function(a,i,e,o,s){var c=this;if(!PickingInfo)return null;var d=this._internalPick(function(_){return c._tempPickingRay||(c._tempPickingRay=Ray.Zero()),c.createPickingRayToRef(a,i,_,c._tempPickingRay,s||null),c._tempPickingRay},e,o,!0);return d&&(d.ray=this.createPickingRay(a,i,Matrix.Identity(),s||null)),d};Scene.prototype.pick=function(a,i,e,o,s,c){var d=this;if(!PickingInfo)return null;var _=this._internalPick(function(b){return d._tempPickingRay||(d._tempPickingRay=Ray.Zero()),d.createPickingRayToRef(a,i,b,d._tempPickingRay,s||null),d._tempPickingRay},e,o,!1,c);return _&&(_.ray=this.createPickingRay(a,i,Matrix.Identity(),s||null)),_};Scene.prototype.pickWithRay=function(a,i,e,o){var s=this,c=this._internalPick(function(d){return s._pickWithRayInverseMatrix||(s._pickWithRayInverseMatrix=Matrix.Identity()),d.invertToRef(s._pickWithRayInverseMatrix),s._cachedRayForTransform||(s._cachedRayForTransform=Ray.Zero()),Ray.TransformToRef(a,s._pickWithRayInverseMatrix,s._cachedRayForTransform),s._cachedRayForTransform},i,e,!1,o);return c&&(c.ray=a),c};Scene.prototype.multiPick=function(a,i,e,o,s){var c=this;return this._internalMultiPick(function(d){return c.createPickingRay(a,i,d,o||null)},e,s)};Scene.prototype.multiPickWithRay=function(a,i,e){var o=this;return this._internalMultiPick(function(s){return o._pickWithRayInverseMatrix||(o._pickWithRayInverseMatrix=Matrix.Identity()),s.invertToRef(o._pickWithRayInverseMatrix),o._cachedRayForTransform||(o._cachedRayForTransform=Ray.Zero()),Ray.TransformToRef(a,o._pickWithRayInverseMatrix,o._cachedRayForTransform),o._cachedRayForTransform},i,e)};Camera$1.prototype.getForwardRay=function(a,i,e){return a===void 0&&(a=100),this.getForwardRayToRef(new Ray(Vector3.Zero(),Vector3.Zero(),a),a,i,e)};Camera$1.prototype.getForwardRayToRef=function(a,i,e,o){return i===void 0&&(i=100),e||(e=this.getWorldMatrix()),a.length=i,o?a.origin.copyFrom(o):a.origin.copyFrom(this.position),TmpVectors.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),Vector3.TransformNormalToRef(TmpVectors.Vector3[2],e,TmpVectors.Vector3[3]),Vector3.NormalizeToRef(TmpVectors.Vector3[3],a.direction),a};var ColorGradient=function(){function a(i,e,o){this.gradient=i,this.color1=e,this.color2=o}return a.prototype.getColorToRef=function(i){if(!this.color2){i.copyFrom(this.color1);return}Color4.LerpToRef(this.color1,this.color2,Math.random(),i)},a}(),Color3Gradient=function(){function a(i,e){this.gradient=i,this.color=e}return a}(),FactorGradient=function(){function a(i,e,o){this.gradient=i,this.factor1=e,this.factor2=o}return a.prototype.getFactor=function(){return this.factor2===void 0||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()},a}(),GradientHelper=function(){function a(){}return a.GetCurrentGradient=function(i,e,o){if(e[0].gradient>i){o(e[0],e[0],1);return}for(var s=0;s<e.length-1;s++){var c=e[s],d=e[s+1];if(i>=c.gradient&&i<=d.gradient){var _=(i-c.gradient)/(d.gradient-c.gradient);o(c,d,_);return}}var b=e.length-1;o(e[b],e[b],1)},a}(),BoxParticleEmitter=function(){function a(){this.direction1=new Vector3(0,1,0),this.direction2=new Vector3(0,1,0),this.minEmitBox=new Vector3(-.5,-.5,-.5),this.maxEmitBox=new Vector3(.5,.5,.5)}return a.prototype.startDirectionFunction=function(i,e,o,s){var c=Scalar.RandomRange(this.direction1.x,this.direction2.x),d=Scalar.RandomRange(this.direction1.y,this.direction2.y),_=Scalar.RandomRange(this.direction1.z,this.direction2.z);if(s){e.x=c,e.y=d,e.z=_;return}Vector3.TransformNormalFromFloatsToRef(c,d,_,i,e)},a.prototype.startPositionFunction=function(i,e,o,s){var c=Scalar.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),d=Scalar.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),_=Scalar.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(s){e.x=c,e.y=d,e.z=_;return}Vector3.TransformCoordinatesFromFloatsToRef(c,d,_,i,e)},a.prototype.clone=function(){var i=new a;return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){i.setVector3("direction1",this.direction1),i.setVector3("direction2",this.direction2),i.setVector3("minEmitBox",this.minEmitBox),i.setVector3("maxEmitBox",this.maxEmitBox)},a.prototype.buildUniformLayout=function(i){i.addUniform("direction1",3),i.addUniform("direction2",3),i.addUniform("minEmitBox",3),i.addUniform("maxEmitBox",3)},a.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},a.prototype.getClassName=function(){return"BoxParticleEmitter"},a.prototype.serialize=function(){var i={};return i.type=this.getClassName(),i.direction1=this.direction1.asArray(),i.direction2=this.direction2.asArray(),i.minEmitBox=this.minEmitBox.asArray(),i.maxEmitBox=this.maxEmitBox.asArray(),i},a.prototype.parse=function(i){Vector3.FromArrayToRef(i.direction1,0,this.direction1),Vector3.FromArrayToRef(i.direction2,0,this.direction2),Vector3.FromArrayToRef(i.minEmitBox,0,this.minEmitBox),Vector3.FromArrayToRef(i.maxEmitBox,0,this.maxEmitBox)},a}(),ConeParticleEmitter=function(){function a(i,e,o){i===void 0&&(i=1),e===void 0&&(e=Math.PI),o===void 0&&(o=0),this.directionRandomizer=o,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=e,this.radius=i}return Object.defineProperty(a.prototype,"radius",{get:function(){return this._radius},set:function(i){this._radius=i,this._buildHeight()},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"angle",{get:function(){return this._angle},set:function(i){this._angle=i,this._buildHeight()},enumerable:!1,configurable:!0}),a.prototype._buildHeight=function(){this._angle!==0?this._height=this._radius/Math.tan(this._angle/2):this._height=1},a.prototype.startDirectionFunction=function(i,e,o,s){s?TmpVectors.Vector3[0].copyFrom(o._localPosition).normalize():o.position.subtractToRef(i.getTranslation(),TmpVectors.Vector3[0]).normalize();var c=Scalar.RandomRange(0,this.directionRandomizer),d=Scalar.RandomRange(0,this.directionRandomizer),_=Scalar.RandomRange(0,this.directionRandomizer);e.x=TmpVectors.Vector3[0].x+c,e.y=TmpVectors.Vector3[0].y+d,e.z=TmpVectors.Vector3[0].z+_,e.normalize()},a.prototype.startPositionFunction=function(i,e,o,s){var c=Scalar.RandomRange(0,Math.PI*2),d;this.emitFromSpawnPointOnly?d=1e-4:(d=Scalar.RandomRange(0,this.heightRange),d=1-d*d);var _=this._radius-Scalar.RandomRange(0,this._radius*this.radiusRange);_=_*d;var b=_*Math.sin(c),k=_*Math.cos(c),j=d*this._height;if(s){e.x=b,e.y=j,e.z=k;return}Vector3.TransformCoordinatesFromFloatsToRef(b,j,k,i,e)},a.prototype.clone=function(){var i=new a(this._radius,this._angle,this.directionRandomizer);return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){i.setFloat2("radius",this._radius,this.radiusRange),i.setFloat("coneAngle",this._angle),i.setFloat2("height",this._height,this.heightRange),i.setFloat("directionRandomizer",this.directionRandomizer)},a.prototype.buildUniformLayout=function(i){i.addUniform("radius",2),i.addUniform("coneAngle",1),i.addUniform("height",2),i.addUniform("directionRandomizer",1)},a.prototype.getEffectDefines=function(){var i="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(i+=`
  4006. #define CONEEMITTERSPAWNPOINT`),i},a.prototype.getClassName=function(){return"ConeParticleEmitter"},a.prototype.serialize=function(){var i={};return i.type=this.getClassName(),i.radius=this._radius,i.angle=this._angle,i.directionRandomizer=this.directionRandomizer,i.radiusRange=this.radiusRange,i.heightRange=this.heightRange,i.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,i},a.prototype.parse=function(i){this.radius=i.radius,this.angle=i.angle,this.directionRandomizer=i.directionRandomizer,this.radiusRange=i.radiusRange!==void 0?i.radiusRange:1,this.heightRange=i.radiusRange!==void 0?i.heightRange:1,this.emitFromSpawnPointOnly=i.emitFromSpawnPointOnly!==void 0?i.emitFromSpawnPointOnly:!1},a}(),CylinderParticleEmitter=function(){function a(i,e,o,s){i===void 0&&(i=1),e===void 0&&(e=1),o===void 0&&(o=1),s===void 0&&(s=0),this.radius=i,this.height=e,this.radiusRange=o,this.directionRandomizer=s,this._tempVector=Vector3.Zero()}return a.prototype.startDirectionFunction=function(i,e,o,s,c){o.position.subtractToRef(i.getTranslation(),this._tempVector),this._tempVector.normalize(),Vector3.TransformNormalToRef(this._tempVector,c,this._tempVector);var d=Scalar.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),_=Math.atan2(this._tempVector.x,this._tempVector.z);if(_+=Scalar.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=d,this._tempVector.x=Math.sin(_),this._tempVector.z=Math.cos(_),this._tempVector.normalize(),s){e.copyFrom(this._tempVector);return}Vector3.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,i,e)},a.prototype.startPositionFunction=function(i,e,o,s){var c=Scalar.RandomRange(-this.height/2,this.height/2),d=Scalar.RandomRange(0,2*Math.PI),_=Scalar.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),b=Math.sqrt(_)*this.radius,k=b*Math.cos(d),j=b*Math.sin(d);if(s){e.copyFromFloats(k,c,j);return}Vector3.TransformCoordinatesFromFloatsToRef(k,c,j,i,e)},a.prototype.clone=function(){var i=new a(this.radius,this.directionRandomizer);return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){i.setFloat("radius",this.radius),i.setFloat("height",this.height),i.setFloat("radiusRange",this.radiusRange),i.setFloat("directionRandomizer",this.directionRandomizer)},a.prototype.buildUniformLayout=function(i){i.addUniform("radius",1),i.addUniform("height",1),i.addUniform("radiusRange",1),i.addUniform("directionRandomizer",1)},a.prototype.getEffectDefines=function(){return"#define CYLINDEREMITTER"},a.prototype.getClassName=function(){return"CylinderParticleEmitter"},a.prototype.serialize=function(){var i={};return i.type=this.getClassName(),i.radius=this.radius,i.height=this.height,i.radiusRange=this.radiusRange,i.directionRandomizer=this.directionRandomizer,i},a.prototype.parse=function(i){this.radius=i.radius,this.height=i.height,this.radiusRange=i.radiusRange,this.directionRandomizer=i.directionRandomizer},a}(),CylinderDirectedParticleEmitter=function(a){__extends(i,a);function i(e,o,s,c,d){e===void 0&&(e=1),o===void 0&&(o=1),s===void 0&&(s=1),c===void 0&&(c=new Vector3(0,1,0)),d===void 0&&(d=new Vector3(0,1,0));var _=a.call(this,e,o,s)||this;return _.direction1=c,_.direction2=d,_}return i.prototype.startDirectionFunction=function(e,o,s){var c=Scalar.RandomRange(this.direction1.x,this.direction2.x),d=Scalar.RandomRange(this.direction1.y,this.direction2.y),_=Scalar.RandomRange(this.direction1.z,this.direction2.z);Vector3.TransformNormalFromFloatsToRef(c,d,_,e,o)},i.prototype.clone=function(){var e=new i(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return DeepCopier.DeepCopy(this,e),e},i.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},i.prototype.buildUniformLayout=function(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)},i.prototype.getEffectDefines=function(){return`#define CYLINDEREMITTER
  4007. #define DIRECTEDCYLINDEREMITTER`},i.prototype.getClassName=function(){return"CylinderDirectedParticleEmitter"},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},i.prototype.parse=function(e){a.prototype.parse.call(this,e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)},i}(CylinderParticleEmitter),HemisphericParticleEmitter=function(){function a(i,e,o){i===void 0&&(i=1),e===void 0&&(e=1),o===void 0&&(o=0),this.radius=i,this.radiusRange=e,this.directionRandomizer=o}return a.prototype.startDirectionFunction=function(i,e,o,s){var c=o.position.subtract(i.getTranslation()).normalize(),d=Scalar.RandomRange(0,this.directionRandomizer),_=Scalar.RandomRange(0,this.directionRandomizer),b=Scalar.RandomRange(0,this.directionRandomizer);if(c.x+=d,c.y+=_,c.z+=b,c.normalize(),s){e.copyFrom(c);return}Vector3.TransformNormalFromFloatsToRef(c.x,c.y,c.z,i,e)},a.prototype.startPositionFunction=function(i,e,o,s){var c=this.radius-Scalar.RandomRange(0,this.radius*this.radiusRange),d=Scalar.RandomRange(0,1),_=Scalar.RandomRange(0,2*Math.PI),b=Math.acos(2*d-1),k=c*Math.cos(_)*Math.sin(b),j=c*Math.cos(b),$=c*Math.sin(_)*Math.sin(b);if(s){e.copyFromFloats(k,Math.abs(j),$);return}Vector3.TransformCoordinatesFromFloatsToRef(k,Math.abs(j),$,i,e)},a.prototype.clone=function(){var i=new a(this.radius,this.directionRandomizer);return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){i.setFloat("radius",this.radius),i.setFloat("radiusRange",this.radiusRange),i.setFloat("directionRandomizer",this.directionRandomizer)},a.prototype.buildUniformLayout=function(i){i.addUniform("radius",1),i.addUniform("radiusRange",1),i.addUniform("directionRandomizer",1)},a.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},a.prototype.getClassName=function(){return"HemisphericParticleEmitter"},a.prototype.serialize=function(){var i={};return i.type=this.getClassName(),i.radius=this.radius,i.radiusRange=this.radiusRange,i.directionRandomizer=this.directionRandomizer,i},a.prototype.parse=function(i){this.radius=i.radius,this.radiusRange=i.radiusRange,this.directionRandomizer=i.directionRandomizer},a}(),PointParticleEmitter=function(){function a(){this.direction1=new Vector3(0,1,0),this.direction2=new Vector3(0,1,0)}return a.prototype.startDirectionFunction=function(i,e,o,s){var c=Scalar.RandomRange(this.direction1.x,this.direction2.x),d=Scalar.RandomRange(this.direction1.y,this.direction2.y),_=Scalar.RandomRange(this.direction1.z,this.direction2.z);if(s){e.copyFromFloats(c,d,_);return}Vector3.TransformNormalFromFloatsToRef(c,d,_,i,e)},a.prototype.startPositionFunction=function(i,e,o,s){if(s){e.copyFromFloats(0,0,0);return}Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,i,e)},a.prototype.clone=function(){var i=new a;return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){i.setVector3("direction1",this.direction1),i.setVector3("direction2",this.direction2)},a.prototype.buildUniformLayout=function(i){i.addUniform("direction1",3),i.addUniform("direction2",3)},a.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},a.prototype.getClassName=function(){return"PointParticleEmitter"},a.prototype.serialize=function(){var i={};return i.type=this.getClassName(),i.direction1=this.direction1.asArray(),i.direction2=this.direction2.asArray(),i},a.prototype.parse=function(i){Vector3.FromArrayToRef(i.direction1,0,this.direction1),Vector3.FromArrayToRef(i.direction2,0,this.direction2)},a}(),SphereParticleEmitter=function(){function a(i,e,o){i===void 0&&(i=1),e===void 0&&(e=1),o===void 0&&(o=0),this.radius=i,this.radiusRange=e,this.directionRandomizer=o}return a.prototype.startDirectionFunction=function(i,e,o,s){var c=o.position.subtract(i.getTranslation()).normalize(),d=Scalar.RandomRange(0,this.directionRandomizer),_=Scalar.RandomRange(0,this.directionRandomizer),b=Scalar.RandomRange(0,this.directionRandomizer);if(c.x+=d,c.y+=_,c.z+=b,c.normalize(),s){e.copyFrom(c);return}Vector3.TransformNormalFromFloatsToRef(c.x,c.y,c.z,i,e)},a.prototype.startPositionFunction=function(i,e,o,s){var c=this.radius-Scalar.RandomRange(0,this.radius*this.radiusRange),d=Scalar.RandomRange(0,1),_=Scalar.RandomRange(0,2*Math.PI),b=Math.acos(2*d-1),k=c*Math.cos(_)*Math.sin(b),j=c*Math.cos(b),$=c*Math.sin(_)*Math.sin(b);if(s){e.copyFromFloats(k,j,$);return}Vector3.TransformCoordinatesFromFloatsToRef(k,j,$,i,e)},a.prototype.clone=function(){var i=new a(this.radius,this.directionRandomizer);return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){i.setFloat("radius",this.radius),i.setFloat("radiusRange",this.radiusRange),i.setFloat("directionRandomizer",this.directionRandomizer)},a.prototype.buildUniformLayout=function(i){i.addUniform("radius",1),i.addUniform("radiusRange",1),i.addUniform("directionRandomizer",1)},a.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},a.prototype.getClassName=function(){return"SphereParticleEmitter"},a.prototype.serialize=function(){var i={};return i.type=this.getClassName(),i.radius=this.radius,i.radiusRange=this.radiusRange,i.directionRandomizer=this.directionRandomizer,i},a.prototype.parse=function(i){this.radius=i.radius,this.radiusRange=i.radiusRange,this.directionRandomizer=i.directionRandomizer},a}(),SphereDirectedParticleEmitter=function(a){__extends(i,a);function i(e,o,s){e===void 0&&(e=1),o===void 0&&(o=new Vector3(0,1,0)),s===void 0&&(s=new Vector3(0,1,0));var c=a.call(this,e)||this;return c.direction1=o,c.direction2=s,c}return i.prototype.startDirectionFunction=function(e,o,s){var c=Scalar.RandomRange(this.direction1.x,this.direction2.x),d=Scalar.RandomRange(this.direction1.y,this.direction2.y),_=Scalar.RandomRange(this.direction1.z,this.direction2.z);Vector3.TransformNormalFromFloatsToRef(c,d,_,e,o)},i.prototype.clone=function(){var e=new i(this.radius,this.direction1,this.direction2);return DeepCopier.DeepCopy(this,e),e},i.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},i.prototype.buildUniformLayout=function(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)},i.prototype.getEffectDefines=function(){return`#define SPHEREEMITTER
  4008. #define DIRECTEDSPHEREEMITTER`},i.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},i.prototype.parse=function(e){a.prototype.parse.call(this,e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)},i}(SphereParticleEmitter),CustomParticleEmitter=function(){function a(){this.particlePositionGenerator=function(){},this.particleDestinationGenerator=function(){}}return a.prototype.startDirectionFunction=function(i,e,o,s){var c=TmpVectors.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,o,c);var d=TmpVectors.Vector3[1];c.subtractToRef(o.position,d),d.scaleToRef(1/o.lifeTime,c)}else c.set(0,0,0);if(s){e.copyFrom(c);return}Vector3.TransformNormalToRef(c,i,e)},a.prototype.startPositionFunction=function(i,e,o,s){var c=TmpVectors.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,o,c):c.set(0,0,0),s){e.copyFrom(c);return}Vector3.TransformCoordinatesToRef(c,i,e)},a.prototype.clone=function(){var i=new a;return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){},a.prototype.buildUniformLayout=function(i){},a.prototype.getEffectDefines=function(){return"#define CUSTOMEMITTER"},a.prototype.getClassName=function(){return"CustomParticleEmitter"},a.prototype.serialize=function(){var i={};return i.type=this.getClassName(),i},a.prototype.parse=function(i){},a}(),MeshParticleEmitter=function(){function a(i){i===void 0&&(i=null),this._indices=null,this._positions=null,this._normals=null,this._storedNormal=Vector3.Zero(),this._mesh=null,this.direction1=new Vector3(0,1,0),this.direction2=new Vector3(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=i}return Object.defineProperty(a.prototype,"mesh",{get:function(){return this._mesh},set:function(i){this._mesh!==i&&(this._mesh=i,i?(this._indices=i.getIndices(),this._positions=i.getVerticesData(VertexBuffer.PositionKind),this._normals=i.getVerticesData(VertexBuffer.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))},enumerable:!1,configurable:!0}),a.prototype.startDirectionFunction=function(i,e,o,s){if(this.useMeshNormalsForDirection&&this._normals){Vector3.TransformNormalToRef(this._storedNormal,i,e);return}var c=Scalar.RandomRange(this.direction1.x,this.direction2.x),d=Scalar.RandomRange(this.direction1.y,this.direction2.y),_=Scalar.RandomRange(this.direction1.z,this.direction2.z);if(s){e.copyFromFloats(c,d,_);return}Vector3.TransformNormalFromFloatsToRef(c,d,_,i,e)},a.prototype.startPositionFunction=function(i,e,o,s){if(!(!this._indices||!this._positions)){var c=3*Math.random()*(this._indices.length/3)|0,d=Math.random(),_=Math.random()*(1-d),b=1-d-_,k=this._indices[c],j=this._indices[c+1],$=this._indices[c+2],_e=TmpVectors.Vector3[0],et=TmpVectors.Vector3[1],tt=TmpVectors.Vector3[2],rt=TmpVectors.Vector3[3];Vector3.FromArrayToRef(this._positions,k*3,_e),Vector3.FromArrayToRef(this._positions,j*3,et),Vector3.FromArrayToRef(this._positions,$*3,tt),rt.x=d*_e.x+_*et.x+b*tt.x,rt.y=d*_e.y+_*et.y+b*tt.y,rt.z=d*_e.z+_*et.z+b*tt.z,s?e.copyFromFloats(rt.x,rt.y,rt.z):Vector3.TransformCoordinatesFromFloatsToRef(rt.x,rt.y,rt.z,i,e),this.useMeshNormalsForDirection&&this._normals&&(Vector3.FromArrayToRef(this._normals,k*3,_e),Vector3.FromArrayToRef(this._normals,j*3,et),Vector3.FromArrayToRef(this._normals,$*3,tt),this._storedNormal.x=d*_e.x+_*et.x+b*tt.x,this._storedNormal.y=d*_e.y+_*et.y+b*tt.y,this._storedNormal.z=d*_e.z+_*et.z+b*tt.z)}},a.prototype.clone=function(){var i=new a(this.mesh);return DeepCopier.DeepCopy(this,i),i},a.prototype.applyToShader=function(i){i.setVector3("direction1",this.direction1),i.setVector3("direction2",this.direction2)},a.prototype.buildUniformLayout=function(i){i.addUniform("direction1",3),i.addUniform("direction2",3)},a.prototype.getEffectDefines=function(){return""},a.prototype.getClassName=function(){return"MeshParticleEmitter"},a.prototype.serialize=function(){var i,e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=(i=this.mesh)===null||i===void 0?void 0:i.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e},a.prototype.parse=function(i,e){Vector3.FromArrayToRef(i.direction1,0,this.direction1),Vector3.FromArrayToRef(i.direction2,0,this.direction2),i.meshId&&e&&(this.mesh=e.getLastMeshById(i.meshId)),this.useMeshNormalsForDirection=i.useMeshNormalsForDirection},a}(),BaseParticleSystem=function(){function a(i){this.animations=[],this.renderingGroupId=0,this.emitter=Vector3.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._rootUrl="",this.noiseStrength=new Vector3(10,10,10),this.onAnimationEnd=null,this.blendMode=a.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new Vector2(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new Vector3(0,0,0),this.gravity=Vector3.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new Color4(1,1,1,1),this.color2=new Color4(1,1,1,1),this.colorDead=new Color4(0,0,0,1),this.textureMask=new Color4(1,1,1,1),this._isSubEmitter=!1,this.billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ImageProcessingConfigurationDefines,this.id=i,this.name=i}return Object.defineProperty(a.prototype,"noiseTexture",{get:function(){return this._noiseTexture},set:function(i){this._noiseTexture!==i&&(this._noiseTexture=i,this._reset())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(i){this._isAnimationSheetEnabled!=i&&(this._isAnimationSheetEnabled=i,this._reset())},enumerable:!1,configurable:!0}),a.prototype.getScene=function(){return this._scene},a.prototype._hasTargetStopDurationDependantGradient=function(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0},a.prototype.getDragGradients=function(){return this._dragGradients},a.prototype.getLimitVelocityGradients=function(){return this._limitVelocityGradients},a.prototype.getColorGradients=function(){return this._colorGradients},a.prototype.getSizeGradients=function(){return this._sizeGradients},a.prototype.getColorRemapGradients=function(){return this._colorRemapGradients},a.prototype.getAlphaRemapGradients=function(){return this._alphaRemapGradients},a.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},a.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},a.prototype.getVelocityGradients=function(){return this._velocityGradients},a.prototype.getStartSizeGradients=function(){return this._startSizeGradients},a.prototype.getEmitRateGradients=function(){return this._emitRateGradients},Object.defineProperty(a.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:Vector3.Zero()},set:function(i){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:Vector3.Zero()},set:function(i){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:Vector3.Zero()},set:function(i){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:Vector3.Zero()},set:function(i){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(i){this._isBillboardBased!==i&&(this._isBillboardBased=i,this._reset())},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(i){this._attachImageProcessingConfiguration(i)},enumerable:!1,configurable:!0}),a.prototype._attachImageProcessingConfiguration=function(i){i!==this._imageProcessingConfiguration&&(!i&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=i)},a.prototype._reset=function(){},a.prototype._removeGradientAndTexture=function(i,e,o){if(!e)return this;for(var s=0,c=0,d=e;c<d.length;c++){var _=d[c];if(_.gradient===i){e.splice(s,1);break}s++}return o&&o.dispose(),this},a.prototype.createPointEmitter=function(i,e){var o=new PointParticleEmitter;return o.direction1=i,o.direction2=e,this.particleEmitterType=o,o},a.prototype.createHemisphericEmitter=function(i,e){i===void 0&&(i=1),e===void 0&&(e=1);var o=new HemisphericParticleEmitter(i,e);return this.particleEmitterType=o,o},a.prototype.createSphereEmitter=function(i,e){i===void 0&&(i=1),e===void 0&&(e=1);var o=new SphereParticleEmitter(i,e);return this.particleEmitterType=o,o},a.prototype.createDirectedSphereEmitter=function(i,e,o){i===void 0&&(i=1),e===void 0&&(e=new Vector3(0,1,0)),o===void 0&&(o=new Vector3(0,1,0));var s=new SphereDirectedParticleEmitter(i,e,o);return this.particleEmitterType=s,s},a.prototype.createCylinderEmitter=function(i,e,o,s){i===void 0&&(i=1),e===void 0&&(e=1),o===void 0&&(o=1),s===void 0&&(s=0);var c=new CylinderParticleEmitter(i,e,o,s);return this.particleEmitterType=c,c},a.prototype.createDirectedCylinderEmitter=function(i,e,o,s,c){i===void 0&&(i=1),e===void 0&&(e=1),o===void 0&&(o=1),s===void 0&&(s=new Vector3(0,1,0)),c===void 0&&(c=new Vector3(0,1,0));var d=new CylinderDirectedParticleEmitter(i,e,o,s,c);return this.particleEmitterType=d,d},a.prototype.createConeEmitter=function(i,e){i===void 0&&(i=1),e===void 0&&(e=Math.PI/4);var o=new ConeParticleEmitter(i,e);return this.particleEmitterType=o,o},a.prototype.createBoxEmitter=function(i,e,o,s){var c=new BoxParticleEmitter;return this.particleEmitterType=c,this.direction1=i,this.direction2=e,this.minEmitBox=o,this.maxEmitBox=s,c},a.BLENDMODE_ONEONE=0,a.BLENDMODE_STANDARD=1,a.BLENDMODE_ADD=2,a.BLENDMODE_MULTIPLY=3,a.BLENDMODE_MULTIPLYADD=4,a}(),Particle=function(){function a(i){this.particleSystem=i,this.position=Vector3.Zero(),this.direction=Vector3.Zero(),this.color=new Color4(0,0,0,0),this.colorStep=new Color4(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new Vector2(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Color4(0,0,0,0),this._currentColor2=new Color4(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=a._Count++,this.particleSystem.isAnimationSheetEnabled&&this.updateCellInfoFromSystem()}return a.prototype.updateCellInfoFromSystem=function(){this.cellIndex=this.particleSystem.startSpriteCellID},a.prototype.updateCellIndex=function(){var i=this.age,e=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(this._randomCellOffset===void 0&&(this._randomCellOffset=Math.random()*this.lifeTime),e===0?(e=1,i=this._randomCellOffset):i+=this._randomCellOffset);var o=this._initialEndSpriteCellID-this._initialStartSpriteCellID,s;this._initialSpriteCellLoop?s=Scalar.Clamp(i*e%this.lifeTime/this.lifeTime):s=Scalar.Clamp(i*e/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*o|0},a.prototype._inheritParticleInfoToSubEmitter=function(i){if(i.particleSystem.emitter.position){var e=i.particleSystem.emitter;if(e.position.copyFrom(this.position),i.inheritDirection){var o=TmpVectors.Vector3[0];this.direction.normalizeToRef(o),e.setDirection(o,0,Math.PI/2)}}else{var s=i.particleSystem.emitter;s.copyFrom(this.position)}this.direction.scaleToRef(i.inheritedVelocityAmount/2,TmpVectors.Vector3[0]),i.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0])},a.prototype._inheritParticleInfoToSubEmitters=function(){var i=this;this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(function(e){i._inheritParticleInfoToSubEmitter(e)})},a.prototype._reset=function(){this.age=0,this.id=a._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0},a.prototype.copyTo=function(i){i.position.copyFrom(this.position),this._initialDirection?i._initialDirection?i._initialDirection.copyFrom(this._initialDirection):i._initialDirection=this._initialDirection.clone():i._initialDirection=null,i.direction.copyFrom(this.direction),this._localPosition&&(i._localPosition?i._localPosition.copyFrom(this._localPosition):i._localPosition=this._localPosition.clone()),i.color.copyFrom(this.color),i.colorStep.copyFrom(this.colorStep),i.lifeTime=this.lifeTime,i.age=this.age,i._randomCellOffset=this._randomCellOffset,i.size=this.size,i.scale.copyFrom(this.scale),i.angle=this.angle,i.angularSpeed=this.angularSpeed,i.particleSystem=this.particleSystem,i.cellIndex=this.cellIndex,i.id=this.id,i._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(i._currentColorGradient=this._currentColorGradient,i._currentColor1.copyFrom(this._currentColor1),i._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(i._currentSizeGradient=this._currentSizeGradient,i._currentSize1=this._currentSize1,i._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(i._currentAngularSpeedGradient=this._currentAngularSpeedGradient,i._currentAngularSpeed1=this._currentAngularSpeed1,i._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(i._currentVelocityGradient=this._currentVelocityGradient,i._currentVelocity1=this._currentVelocity1,i._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(i._currentLimitVelocityGradient=this._currentLimitVelocityGradient,i._currentLimitVelocity1=this._currentLimitVelocity1,i._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(i._currentDragGradient=this._currentDragGradient,i._currentDrag1=this._currentDrag1,i._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(i._initialStartSpriteCellID=this._initialStartSpriteCellID,i._initialEndSpriteCellID=this._initialEndSpriteCellID,i._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(i.remapData&&this.remapData?i.remapData.copyFrom(this.remapData):i.remapData=new Vector4(0,0,0,0)),this._randomNoiseCoordinates1&&(i._randomNoiseCoordinates1?(i._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),i._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(i._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),i._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))},a._Count=0,a}(),SubEmitterType;(function(a){a[a.ATTACHED=0]="ATTACHED",a[a.END=1]="END"})(SubEmitterType||(SubEmitterType={}));var SubEmitter=function(){function a(i){if(this.particleSystem=i,this.type=SubEmitterType.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!i.emitter||!i.emitter.dispose){var e=GetClass("BABYLON.AbstractMesh");i.emitter=new e("SubemitterSystemEmitter",i.getScene()),i._disposeEmitterOnDispose=!0}}return a.prototype.clone=function(){var i=this.particleSystem.emitter;if(!i)i=new Vector3;else if(i instanceof Vector3)i=i.clone();else if(i.getClassName().indexOf("Mesh")!==-1){var e=GetClass("BABYLON.Mesh");i=new e("",i.getScene()),i.isVisible=!1}var o=new a(this.particleSystem.clone(this.particleSystem.name,i));return o.particleSystem.name+="Clone",o.type=this.type,o.inheritDirection=this.inheritDirection,o.inheritedVelocityAmount=this.inheritedVelocityAmount,o.particleSystem._disposeEmitterOnDispose=!0,o.particleSystem.disposeOnStop=!0,o},a.prototype.serialize=function(i){i===void 0&&(i=!1);var e={};return e.type=this.type,e.inheritDirection=this.inheritDirection,e.inheritedVelocityAmount=this.inheritedVelocityAmount,e.particleSystem=this.particleSystem.serialize(i),e},a._ParseParticleSystem=function(i,e,o,s){throw _WarnImport("ParseParticle")},a.Parse=function(i,e,o){var s=i.particleSystem,c=new a(a._ParseParticleSystem(s,e,o,!0));return c.type=i.type,c.inheritDirection=i.inheritDirection,c.inheritedVelocityAmount=i.inheritedVelocityAmount,c.particleSystem._isSubEmitter=!0,c},a.prototype.dispose=function(){this.particleSystem.dispose()},a}(),name$1m="particlesPixelShader",shader$1m=`
  4009. varying vec2 vUV;
  4010. varying vec4 vColor;
  4011. uniform vec4 textureMask;
  4012. uniform sampler2D diffuseSampler;
  4013. #include<clipPlaneFragmentDeclaration>
  4014. #include<imageProcessingDeclaration>
  4015. #include<helperFunctions>
  4016. #include<imageProcessingFunctions>
  4017. #ifdef RAMPGRADIENT
  4018. varying vec4 remapRanges;
  4019. uniform sampler2D rampSampler;
  4020. #endif
  4021. void main(void) {
  4022. #include<clipPlaneFragment>
  4023. vec4 textureColor=texture2D(diffuseSampler,vUV);
  4024. vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;
  4025. #ifdef RAMPGRADIENT
  4026. float alpha=baseColor.a;
  4027. float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);
  4028. vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));
  4029. baseColor.rgb*=rampColor.rgb;
  4030. float finalAlpha=baseColor.a;
  4031. baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);
  4032. #endif
  4033. #ifdef BLENDMULTIPLYMODE
  4034. float sourceAlpha=vColor.a*textureColor.a;
  4035. baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);
  4036. #endif
  4037. #ifdef IMAGEPROCESSINGPOSTPROCESS
  4038. baseColor.rgb=toLinearSpace(baseColor.rgb);
  4039. #else
  4040. #ifdef IMAGEPROCESSING
  4041. baseColor.rgb=toLinearSpace(baseColor.rgb);
  4042. baseColor=applyImageProcessing(baseColor);
  4043. #endif
  4044. #endif
  4045. gl_FragColor=baseColor;
  4046. }`;ShaderStore.ShadersStore[name$1m]=shader$1m;var name$1l="particlesVertexShader",shader$1l=`
  4047. attribute vec3 position;
  4048. attribute vec4 color;
  4049. attribute float angle;
  4050. attribute vec2 size;
  4051. #ifdef ANIMATESHEET
  4052. attribute float cellIndex;
  4053. #endif
  4054. #ifndef BILLBOARD
  4055. attribute vec3 direction;
  4056. #endif
  4057. #ifdef BILLBOARDSTRETCHED
  4058. attribute vec3 direction;
  4059. #endif
  4060. #ifdef RAMPGRADIENT
  4061. attribute vec4 remapData;
  4062. #endif
  4063. attribute vec2 offset;
  4064. uniform mat4 view;
  4065. uniform mat4 projection;
  4066. uniform vec2 translationPivot;
  4067. #ifdef ANIMATESHEET
  4068. uniform vec3 particlesInfos;
  4069. #endif
  4070. varying vec2 vUV;
  4071. varying vec4 vColor;
  4072. varying vec3 vPositionW;
  4073. #ifdef RAMPGRADIENT
  4074. varying vec4 remapRanges;
  4075. #endif
  4076. #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
  4077. uniform mat4 invView;
  4078. #endif
  4079. #include<clipPlaneVertexDeclaration>
  4080. #ifdef BILLBOARD
  4081. uniform vec3 eyePosition;
  4082. #endif
  4083. vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {
  4084. vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));
  4085. vec3 zaxis=normalize(cross(yaxis,xaxis));
  4086. vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);
  4087. vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);
  4088. vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);
  4089. mat3 rotMatrix=mat3(row0,row1,row2);
  4090. vec3 alignedCorner=rotMatrix*rotatedCorner;
  4091. return position+alignedCorner;
  4092. }
  4093. #ifdef BILLBOARDSTRETCHED
  4094. vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {
  4095. vec3 normalizedToCamera=normalize(toCamera);
  4096. vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));
  4097. vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));
  4098. vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);
  4099. vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);
  4100. vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);
  4101. mat3 rotMatrix=mat3(row0,row1,row2);
  4102. vec3 alignedCorner=rotMatrix*rotatedCorner;
  4103. return position+alignedCorner;
  4104. }
  4105. #endif
  4106. void main(void) {
  4107. vec2 cornerPos;
  4108. cornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;
  4109. #ifdef BILLBOARD
  4110. vec3 rotatedCorner;
  4111. #ifdef BILLBOARDY
  4112. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4113. rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4114. rotatedCorner.y=0.;
  4115. vec3 yaxis=position-eyePosition;
  4116. yaxis.y=0.;
  4117. vPositionW=rotate(normalize(yaxis),rotatedCorner);
  4118. vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
  4119. #elif defined(BILLBOARDSTRETCHED)
  4120. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4121. rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4122. rotatedCorner.z=0.;
  4123. vec3 toCamera=position-eyePosition;
  4124. vPositionW=rotateAlign(toCamera,rotatedCorner);
  4125. vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
  4126. #else
  4127. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4128. rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4129. rotatedCorner.z=0.;
  4130. vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;
  4131. vPositionW=(invView*vec4(viewPos,1)).xyz;
  4132. #endif
  4133. #ifdef RAMPGRADIENT
  4134. remapRanges=remapData;
  4135. #endif
  4136. gl_Position=projection*vec4(viewPos,1.0);
  4137. #else
  4138. vec3 rotatedCorner;
  4139. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4140. rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4141. rotatedCorner.y=0.;
  4142. vec3 yaxis=normalize(direction);
  4143. vPositionW=rotate(yaxis,rotatedCorner);
  4144. gl_Position=projection*view*vec4(vPositionW,1.0);
  4145. #endif
  4146. vColor=color;
  4147. #ifdef ANIMATESHEET
  4148. float rowOffset=floor(cellIndex*particlesInfos.z);
  4149. float columnOffset=cellIndex-rowOffset/particlesInfos.z;
  4150. vec2 uvScale=particlesInfos.xy;
  4151. vec2 uvOffset=vec2(offset.x ,1.0-offset.y);
  4152. vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
  4153. #else
  4154. vUV=offset;
  4155. #endif
  4156. #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
  4157. vec4 worldPos=vec4(vPositionW,1.0);
  4158. #endif
  4159. #include<clipPlaneVertex>
  4160. }`;ShaderStore.ShadersStore[name$1l]=shader$1l;var ParticleSystem=function(a){__extends(i,a);function i(e,o,s,c,d,_){c===void 0&&(c=null),d===void 0&&(d=!1),_===void 0&&(_=.01);var b=a.call(this,e)||this;b._emitterInverseWorldMatrix=Matrix.Identity(),b._inheritedVelocityOffset=new Vector3,b.onDisposeObservable=new Observable,b.onStoppedObservable=new Observable,b._particles=new Array,b._stockParticles=new Array,b._newPartsExcess=0,b._vertexBuffers={},b._scaledColorStep=new Color4(0,0,0,0),b._colorDiff=new Color4(0,0,0,0),b._scaledDirection=Vector3.Zero(),b._scaledGravity=Vector3.Zero(),b._currentRenderId=-1,b._useInstancing=!1,b._started=!1,b._stopped=!1,b._actualFrame=0,b._currentEmitRate1=0,b._currentEmitRate2=0,b._currentStartSize1=0,b._currentStartSize2=0,b._rawTextureWidth=256,b._useRampGradients=!1,b._disposeEmitterOnDispose=!1,b.isLocal=!1,b._onBeforeDrawParticlesObservable=null,b.recycleParticle=function(j){var $=b._particles.pop();$!==j&&$.copyTo(j),b._stockParticles.push($)},b._createParticle=function(){var j;if(b._stockParticles.length!==0?(j=b._stockParticles.pop(),j._reset()):j=new Particle(b),b._subEmitters&&b._subEmitters.length>0){var $=b._subEmitters[Math.floor(Math.random()*b._subEmitters.length)];j._attachedSubEmitters=[],$.forEach(function(_e){if(_e.type===SubEmitterType.ATTACHED){var et=_e.clone();j._attachedSubEmitters.push(et),et.particleSystem.start()}})}return j},b._emitFromParticle=function(j){if(!(!b._subEmitters||b._subEmitters.length===0)){var $=Math.floor(Math.random()*b._subEmitters.length);b._subEmitters[$].forEach(function(_e){if(_e.type===SubEmitterType.END){var et=_e.clone();j._inheritParticleInfoToSubEmitter(et),et.particleSystem._rootParticleSystem=b,b.activeSubSystems.push(et.particleSystem),et.particleSystem.start()}})}},b._capacity=o,b._epsilon=_,b._isAnimationSheetEnabled=d,!s||s.getClassName()==="Scene"?(b._scene=s||EngineStore.LastCreatedScene,b._engine=b._scene.getEngine(),b.uniqueId=b._scene.getUniqueId(),b._scene.particleSystems.push(b)):(b._engine=s,b.defaultProjectionMatrix=Matrix.PerspectiveFovLH(.8,1,.1,100,b._engine.isNDCHalfZRange)),b._engine.getCaps().vertexArrayObject&&(b._vertexArrayObject=null),b._attachImageProcessingConfiguration(null),b._customWrappers={0:new DrawWrapper(b._engine)},b._customWrappers[0].effect=c,b._drawWrappers=[],b._useInstancing=b._engine.getCaps().instancedArrays,b._createIndexBuffer(),b._createVertexBuffers(),b.particleEmitterType=new BoxParticleEmitter;var k=null;return b.updateFunction=function(j){var $,_e=null;b.noiseTexture&&(_e=b.noiseTexture.getSize(),($=b.noiseTexture.getContent())===null||$===void 0||$.then(function(it){k=it}));for(var et=function(){tt=j[rt];var it=b._scaledUpdateSpeed,nt=tt.age;if(tt.age+=it,tt.age>tt.lifeTime){var ot=tt.age-nt,at=tt.lifeTime-nt;it=at*it/ot,tt.age=tt.lifeTime}var st=tt.age/tt.lifeTime;b._colorGradients&&b._colorGradients.length>0?GradientHelper.GetCurrentGradient(st,b._colorGradients,function(dt,gt,_t){dt!==tt._currentColorGradient&&(tt._currentColor1.copyFrom(tt._currentColor2),gt.getColorToRef(tt._currentColor2),tt._currentColorGradient=dt),Color4.LerpToRef(tt._currentColor1,tt._currentColor2,_t,tt.color)}):(tt.colorStep.scaleToRef(it,b._scaledColorStep),tt.color.addInPlace(b._scaledColorStep),tt.color.a<0&&(tt.color.a=0)),b._angularSpeedGradients&&b._angularSpeedGradients.length>0&&GradientHelper.GetCurrentGradient(st,b._angularSpeedGradients,function(dt,gt,_t){dt!==tt._currentAngularSpeedGradient&&(tt._currentAngularSpeed1=tt._currentAngularSpeed2,tt._currentAngularSpeed2=gt.getFactor(),tt._currentAngularSpeedGradient=dt),tt.angularSpeed=Scalar.Lerp(tt._currentAngularSpeed1,tt._currentAngularSpeed2,_t)}),tt.angle+=tt.angularSpeed*it;var ut=it;if(b._velocityGradients&&b._velocityGradients.length>0&&GradientHelper.GetCurrentGradient(st,b._velocityGradients,function(dt,gt,_t){dt!==tt._currentVelocityGradient&&(tt._currentVelocity1=tt._currentVelocity2,tt._currentVelocity2=gt.getFactor(),tt._currentVelocityGradient=dt),ut*=Scalar.Lerp(tt._currentVelocity1,tt._currentVelocity2,_t)}),tt.direction.scaleToRef(ut,b._scaledDirection),b._limitVelocityGradients&&b._limitVelocityGradients.length>0&&GradientHelper.GetCurrentGradient(st,b._limitVelocityGradients,function(dt,gt,_t){dt!==tt._currentLimitVelocityGradient&&(tt._currentLimitVelocity1=tt._currentLimitVelocity2,tt._currentLimitVelocity2=gt.getFactor(),tt._currentLimitVelocityGradient=dt);var yt=Scalar.Lerp(tt._currentLimitVelocity1,tt._currentLimitVelocity2,_t),Tt=tt.direction.length();Tt>yt&&tt.direction.scaleInPlace(b.limitVelocityDamping)}),b._dragGradients&&b._dragGradients.length>0&&GradientHelper.GetCurrentGradient(st,b._dragGradients,function(dt,gt,_t){dt!==tt._currentDragGradient&&(tt._currentDrag1=tt._currentDrag2,tt._currentDrag2=gt.getFactor(),tt._currentDragGradient=dt);var yt=Scalar.Lerp(tt._currentDrag1,tt._currentDrag2,_t);b._scaledDirection.scaleInPlace(1-yt)}),b.isLocal&&tt._localPosition?(tt._localPosition.addInPlace(b._scaledDirection),Vector3.TransformCoordinatesToRef(tt._localPosition,b._emitterWorldMatrix,tt.position)):tt.position.addInPlace(b._scaledDirection),k&&_e&&tt._randomNoiseCoordinates1){var ft=b._fetchR(tt._randomNoiseCoordinates1.x,tt._randomNoiseCoordinates1.y,_e.width,_e.height,k),lt=b._fetchR(tt._randomNoiseCoordinates1.z,tt._randomNoiseCoordinates2.x,_e.width,_e.height,k),ht=b._fetchR(tt._randomNoiseCoordinates2.y,tt._randomNoiseCoordinates2.z,_e.width,_e.height,k),pt=TmpVectors.Vector3[0],mt=TmpVectors.Vector3[1];pt.copyFromFloats((2*ft-1)*b.noiseStrength.x,(2*lt-1)*b.noiseStrength.y,(2*ht-1)*b.noiseStrength.z),pt.scaleToRef(it,mt),tt.direction.addInPlace(mt)}if(b.gravity.scaleToRef(it,b._scaledGravity),tt.direction.addInPlace(b._scaledGravity),b._sizeGradients&&b._sizeGradients.length>0&&GradientHelper.GetCurrentGradient(st,b._sizeGradients,function(dt,gt,_t){dt!==tt._currentSizeGradient&&(tt._currentSize1=tt._currentSize2,tt._currentSize2=gt.getFactor(),tt._currentSizeGradient=dt),tt.size=Scalar.Lerp(tt._currentSize1,tt._currentSize2,_t)}),b._useRampGradients&&(b._colorRemapGradients&&b._colorRemapGradients.length>0&&GradientHelper.GetCurrentGradient(st,b._colorRemapGradients,function(dt,gt,_t){var yt=Scalar.Lerp(dt.factor1,gt.factor1,_t),Tt=Scalar.Lerp(dt.factor2,gt.factor2,_t);tt.remapData.x=yt,tt.remapData.y=Tt-yt}),b._alphaRemapGradients&&b._alphaRemapGradients.length>0&&GradientHelper.GetCurrentGradient(st,b._alphaRemapGradients,function(dt,gt,_t){var yt=Scalar.Lerp(dt.factor1,gt.factor1,_t),Tt=Scalar.Lerp(dt.factor2,gt.factor2,_t);tt.remapData.z=yt,tt.remapData.w=Tt-yt})),b._isAnimationSheetEnabled&&tt.updateCellIndex(),tt._inheritParticleInfoToSubEmitters(),tt.age>=tt.lifeTime)return b._emitFromParticle(tt),tt._attachedSubEmitters&&(tt._attachedSubEmitters.forEach(function(dt){dt.particleSystem.disposeOnStop=!0,dt.particleSystem.stop()}),tt._attachedSubEmitters=null),b.recycleParticle(tt),rt--,"continue"},tt,rt=0;rt<j.length;rt++)et()},b}return Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"useRampGradients",{get:function(){return this._useRampGradients},set:function(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"particles",{get:function(){return this._particles},enumerable:!1,configurable:!0}),i.prototype.getActiveCount=function(){return this._particles.length},i.prototype.getClassName=function(){return"ParticleSystem"},i.prototype.isStopping=function(){return this._stopped&&this.isAlive()},i.prototype.getCustomEffect=function(e){var o,s;return e===void 0&&(e=0),(s=(o=this._customWrappers[e])===null||o===void 0?void 0:o.effect)!==null&&s!==void 0?s:this._customWrappers[0].effect},i.prototype._getCustomDrawWrapper=function(e){var o;return e===void 0&&(e=0),(o=this._customWrappers[e])!==null&&o!==void 0?o:this._customWrappers[0]},i.prototype.setCustomEffect=function(e,o){o===void 0&&(o=0),this._customWrappers[o]=new DrawWrapper(this._engine),this._customWrappers[o].effect=e,this._customWrappers[o].drawContext&&(this._customWrappers[o].drawContext.useInstancing=this._useInstancing)},Object.defineProperty(i.prototype,"onBeforeDrawParticlesObservable",{get:function(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Observable),this._onBeforeDrawParticlesObservable},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vertexShaderName",{get:function(){return"particles"},enumerable:!1,configurable:!0}),i.prototype._addFactorGradient=function(e,o,s,c){var d=new FactorGradient(o,s,c);e.push(d),e.sort(function(_,b){return _.gradient<b.gradient?-1:_.gradient>b.gradient?1:0})},i.prototype._removeFactorGradient=function(e,o){if(!!e)for(var s=0,c=0,d=e;c<d.length;c++){var _=d[c];if(_.gradient===o){e.splice(s,1);break}s++}},i.prototype.addLifeTimeGradient=function(e,o,s){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,o,s),this},i.prototype.removeLifeTimeGradient=function(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this},i.prototype.addSizeGradient=function(e,o,s){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,o,s),this},i.prototype.removeSizeGradient=function(e){return this._removeFactorGradient(this._sizeGradients,e),this},i.prototype.addColorRemapGradient=function(e,o,s){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,o,s),this},i.prototype.removeColorRemapGradient=function(e){return this._removeFactorGradient(this._colorRemapGradients,e),this},i.prototype.addAlphaRemapGradient=function(e,o,s){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,o,s),this},i.prototype.removeAlphaRemapGradient=function(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this},i.prototype.addAngularSpeedGradient=function(e,o,s){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,o,s),this},i.prototype.removeAngularSpeedGradient=function(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this},i.prototype.addVelocityGradient=function(e,o,s){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,o,s),this},i.prototype.removeVelocityGradient=function(e){return this._removeFactorGradient(this._velocityGradients,e),this},i.prototype.addLimitVelocityGradient=function(e,o,s){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,o,s),this},i.prototype.removeLimitVelocityGradient=function(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this},i.prototype.addDragGradient=function(e,o,s){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,o,s),this},i.prototype.removeDragGradient=function(e){return this._removeFactorGradient(this._dragGradients,e),this},i.prototype.addEmitRateGradient=function(e,o,s){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,o,s),this},i.prototype.removeEmitRateGradient=function(e){return this._removeFactorGradient(this._emitRateGradients,e),this},i.prototype.addStartSizeGradient=function(e,o,s){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,o,s),this},i.prototype.removeStartSizeGradient=function(e){return this._removeFactorGradient(this._startSizeGradients,e),this},i.prototype._createRampGradientTexture=function(){if(!(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)){for(var e=new Uint8Array(this._rawTextureWidth*4),o=TmpColors.Color3[0],s=0;s<this._rawTextureWidth;s++){var c=s/this._rawTextureWidth;GradientHelper.GetCurrentGradient(c,this._rampGradients,function(d,_,b){Color3.LerpToRef(d.color,_.color,b,o),e[s*4]=o.r*255,e[s*4+1]=o.g*255,e[s*4+2]=o.b*255,e[s*4+3]=255})}this._rampGradientsTexture=RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}},i.prototype.getRampGradients=function(){return this._rampGradients},i.prototype.forceRefreshGradients=function(){this._syncRampGradientTexture()},i.prototype._syncRampGradientTexture=function(){!this._rampGradients||(this._rampGradients.sort(function(e,o){return e.gradient<o.gradient?-1:e.gradient>o.gradient?1:0}),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())},i.prototype.addRampGradient=function(e,o){this._rampGradients||(this._rampGradients=[]);var s=new Color3Gradient(e,o);return this._rampGradients.push(s),this._syncRampGradientTexture(),this},i.prototype.removeRampGradient=function(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this},i.prototype.addColorGradient=function(e,o,s){this._colorGradients||(this._colorGradients=[]);var c=new ColorGradient(e,o,s);return this._colorGradients.push(c),this._colorGradients.sort(function(d,_){return d.gradient<_.gradient?-1:d.gradient>_.gradient?1:0}),this},i.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var o=0,s=0,c=this._colorGradients;s<c.length;s++){var d=c[s];if(d.gradient===e){this._colorGradients.splice(o,1);break}o++}return this},i.prototype.resetDrawCache=function(){for(var e=0,o=this._drawWrappers;e<o.length;e++){var s=o[e];if(s)for(var c=0,d=s;c<d.length;c++){var _=d[c];_==null||_.dispose()}}this._drawWrappers=[]},i.prototype._fetchR=function(e,o,s,c,d){e=Math.abs(e)*.5+.5,o=Math.abs(o)*.5+.5;var _=e*s%s|0,b=o*c%c|0,k=(_+b*s)*4;return d[k]/255},i.prototype._reset=function(){this._resetEffect()},i.prototype._resetEffect=function(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()},i.prototype._createVertexBuffers=function(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),(!this._isBillboardBased||this.billboardMode===i.BILLBOARDMODE_STRETCHED)&&(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);var e=this._engine;this._vertexData=new Float32Array(this._capacity*this._vertexBufferSize*(this._useInstancing?1:4)),this._vertexBuffer=new Buffer(e,this._vertexData,!0,this._vertexBufferSize);var o=0,s=this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind,o,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[VertexBuffer.PositionKind]=s,o+=3;var c=this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind,o,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[VertexBuffer.ColorKind]=c,o+=4;var d=this._vertexBuffer.createVertexBuffer("angle",o,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=d,o+=1;var _=this._vertexBuffer.createVertexBuffer("size",o,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=_,o+=2,this._isAnimationSheetEnabled){var b=this._vertexBuffer.createVertexBuffer("cellIndex",o,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=b,o+=1}if(!this._isBillboardBased||this.billboardMode===i.BILLBOARDMODE_STRETCHED){var k=this._vertexBuffer.createVertexBuffer("direction",o,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=k,o+=3}if(this._useRampGradients){var j=this._vertexBuffer.createVertexBuffer("remapData",o,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=j,o+=4}var $;if(this._useInstancing){var _e=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Buffer(e,_e,!1,2),$=this._spriteBuffer.createVertexBuffer("offset",0,2)}else $=this._vertexBuffer.createVertexBuffer("offset",o,2,this._vertexBufferSize,this._useInstancing),o+=2;this._vertexBuffers.offset=$,this.resetDrawCache()},i.prototype._createIndexBuffer=function(){if(!this._useInstancing){for(var e=[],o=0,s=0;s<this._capacity;s++)e.push(o),e.push(o+1),e.push(o+2),e.push(o),e.push(o+2),e.push(o+3),o+=4;this._indexBuffer=this._engine.createIndexBuffer(e)}},i.prototype.getCapacity=function(){return this._capacity},i.prototype.isAlive=function(){return this._alive},i.prototype.isStarted=function(){return this._started},i.prototype._prepareSubEmitterInternalArray=function(){var e=this;this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach(function(o){o instanceof i?e._subEmitters.push([new SubEmitter(o)]):o instanceof SubEmitter?e._subEmitters.push([o]):o instanceof Array&&e._subEmitters.push(o)})},i.prototype.start=function(e){var o=this,s;if(e===void 0&&(e=this.startDelay),!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(function(){o.start(0)},e);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&this._subEmitters.length!=0&&(this.activeSubSystems=new Array),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){((s=this.emitter)===null||s===void 0?void 0:s.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);var c=this.noiseTexture;if(c&&c.onGeneratedObservable)c.onGeneratedObservable.addOnce(function(){setTimeout(function(){for(var _=0;_<o.preWarmCycles;_++)o.animate(!0),c.render()})});else for(var d=0;d<this.preWarmCycles;d++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)},i.prototype.stop=function(e){e===void 0&&(e=!0),!this._stopped&&(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())},i.prototype.reset=function(){this._stockParticles=[],this._particles=[]},i.prototype._appendParticleVertex=function(e,o,s,c){var d=e*this._vertexBufferSize;if(this._vertexData[d++]=o.position.x+this.worldOffset.x,this._vertexData[d++]=o.position.y+this.worldOffset.y,this._vertexData[d++]=o.position.z+this.worldOffset.z,this._vertexData[d++]=o.color.r,this._vertexData[d++]=o.color.g,this._vertexData[d++]=o.color.b,this._vertexData[d++]=o.color.a,this._vertexData[d++]=o.angle,this._vertexData[d++]=o.scale.x*o.size,this._vertexData[d++]=o.scale.y*o.size,this._isAnimationSheetEnabled&&(this._vertexData[d++]=o.cellIndex),this._isBillboardBased)this.billboardMode===i.BILLBOARDMODE_STRETCHED&&(this._vertexData[d++]=o.direction.x,this._vertexData[d++]=o.direction.y,this._vertexData[d++]=o.direction.z);else if(o._initialDirection){var _=o._initialDirection;this.isLocal&&(Vector3.TransformNormalToRef(_,this._emitterWorldMatrix,TmpVectors.Vector3[0]),_=TmpVectors.Vector3[0]),_.x===0&&_.z===0&&(_.x=.001),this._vertexData[d++]=_.x,this._vertexData[d++]=_.y,this._vertexData[d++]=_.z}else{var b=o.direction;this.isLocal&&(Vector3.TransformNormalToRef(b,this._emitterWorldMatrix,TmpVectors.Vector3[0]),b=TmpVectors.Vector3[0]),b.x===0&&b.z===0&&(b.x=.001),this._vertexData[d++]=b.x,this._vertexData[d++]=b.y,this._vertexData[d++]=b.z}this._useRampGradients&&o.remapData&&(this._vertexData[d++]=o.remapData.x,this._vertexData[d++]=o.remapData.y,this._vertexData[d++]=o.remapData.z,this._vertexData[d++]=o.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(s===0?s=this._epsilon:s===1&&(s=1-this._epsilon),c===0?c=this._epsilon:c===1&&(c=1-this._epsilon)),this._vertexData[d++]=s,this._vertexData[d++]=c)},i.prototype._stopSubEmitters=function(){!this.activeSubSystems||(this.activeSubSystems.forEach(function(e){e.stop(!0)}),this.activeSubSystems=new Array)},i.prototype._removeFromRoot=function(){if(!!this._rootParticleSystem){var e=this._rootParticleSystem.activeSubSystems.indexOf(this);e!==-1&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}},i.prototype._update=function(e){var o=this;if(this._alive=this._particles.length>0,this.emitter.position){var s=this.emitter;this._emitterWorldMatrix=s.getWorldMatrix()}else{var c=this.emitter;this._emitterWorldMatrix=Matrix.Translation(c.x,c.y,c.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(var d,_=function(){if(b._particles.length===b._capacity)return"break";if(d=b._createParticle(),b._particles.push(d),b.targetStopDuration&&b._lifeTimeGradients&&b._lifeTimeGradients.length>0){var _e=Scalar.Clamp(b._actualFrame/b.targetStopDuration);GradientHelper.GetCurrentGradient(_e,b._lifeTimeGradients,function(rt,it){var nt=rt,ot=it,at=nt.getFactor(),st=ot.getFactor(),ut=(_e-nt.gradient)/(ot.gradient-nt.gradient);d.lifeTime=Scalar.Lerp(at,st,ut)})}else d.lifeTime=Scalar.RandomRange(b.minLifeTime,b.maxLifeTime);var et=Scalar.RandomRange(b.minEmitPower,b.maxEmitPower);if(b.startPositionFunction?b.startPositionFunction(b._emitterWorldMatrix,d.position,d,b.isLocal):b.particleEmitterType.startPositionFunction(b._emitterWorldMatrix,d.position,d,b.isLocal),b.isLocal&&(d._localPosition?d._localPosition.copyFrom(d.position):d._localPosition=d.position.clone(),Vector3.TransformCoordinatesToRef(d._localPosition,b._emitterWorldMatrix,d.position)),b.startDirectionFunction?b.startDirectionFunction(b._emitterWorldMatrix,d.direction,d,b.isLocal):b.particleEmitterType.startDirectionFunction(b._emitterWorldMatrix,d.direction,d,b.isLocal,b._emitterInverseWorldMatrix),et===0?d._initialDirection?d._initialDirection.copyFrom(d.direction):d._initialDirection=d.direction.clone():d._initialDirection=null,d.direction.scaleInPlace(et),!b._sizeGradients||b._sizeGradients.length===0?d.size=Scalar.RandomRange(b.minSize,b.maxSize):(d._currentSizeGradient=b._sizeGradients[0],d._currentSize1=d._currentSizeGradient.getFactor(),d.size=d._currentSize1,b._sizeGradients.length>1?d._currentSize2=b._sizeGradients[1].getFactor():d._currentSize2=d._currentSize1),d.scale.copyFromFloats(Scalar.RandomRange(b.minScaleX,b.maxScaleX),Scalar.RandomRange(b.minScaleY,b.maxScaleY)),b._startSizeGradients&&b._startSizeGradients[0]&&b.targetStopDuration){var tt=b._actualFrame/b.targetStopDuration;GradientHelper.GetCurrentGradient(tt,b._startSizeGradients,function(rt,it,nt){rt!==o._currentStartSizeGradient&&(o._currentStartSize1=o._currentStartSize2,o._currentStartSize2=it.getFactor(),o._currentStartSizeGradient=rt);var ot=Scalar.Lerp(o._currentStartSize1,o._currentStartSize2,nt);d.scale.scaleInPlace(ot)})}!b._angularSpeedGradients||b._angularSpeedGradients.length===0?d.angularSpeed=Scalar.RandomRange(b.minAngularSpeed,b.maxAngularSpeed):(d._currentAngularSpeedGradient=b._angularSpeedGradients[0],d.angularSpeed=d._currentAngularSpeedGradient.getFactor(),d._currentAngularSpeed1=d.angularSpeed,b._angularSpeedGradients.length>1?d._currentAngularSpeed2=b._angularSpeedGradients[1].getFactor():d._currentAngularSpeed2=d._currentAngularSpeed1),d.angle=Scalar.RandomRange(b.minInitialRotation,b.maxInitialRotation),b._velocityGradients&&b._velocityGradients.length>0&&(d._currentVelocityGradient=b._velocityGradients[0],d._currentVelocity1=d._currentVelocityGradient.getFactor(),b._velocityGradients.length>1?d._currentVelocity2=b._velocityGradients[1].getFactor():d._currentVelocity2=d._currentVelocity1),b._limitVelocityGradients&&b._limitVelocityGradients.length>0&&(d._currentLimitVelocityGradient=b._limitVelocityGradients[0],d._currentLimitVelocity1=d._currentLimitVelocityGradient.getFactor(),b._limitVelocityGradients.length>1?d._currentLimitVelocity2=b._limitVelocityGradients[1].getFactor():d._currentLimitVelocity2=d._currentLimitVelocity1),b._dragGradients&&b._dragGradients.length>0&&(d._currentDragGradient=b._dragGradients[0],d._currentDrag1=d._currentDragGradient.getFactor(),b._dragGradients.length>1?d._currentDrag2=b._dragGradients[1].getFactor():d._currentDrag2=d._currentDrag1),!b._colorGradients||b._colorGradients.length===0?(k=Scalar.RandomRange(0,1),Color4.LerpToRef(b.color1,b.color2,k,d.color),b.colorDead.subtractToRef(d.color,b._colorDiff),b._colorDiff.scaleToRef(1/d.lifeTime,d.colorStep)):(d._currentColorGradient=b._colorGradients[0],d._currentColorGradient.getColorToRef(d.color),d._currentColor1.copyFrom(d.color),b._colorGradients.length>1?b._colorGradients[1].getColorToRef(d._currentColor2):d._currentColor2.copyFrom(d.color)),b._isAnimationSheetEnabled&&(d._initialStartSpriteCellID=b.startSpriteCellID,d._initialEndSpriteCellID=b.endSpriteCellID,d._initialSpriteCellLoop=b.spriteCellLoop),d.direction.addInPlace(b._inheritedVelocityOffset),b._useRampGradients&&(d.remapData=new Vector4(0,1,0,1)),b.noiseTexture&&(d._randomNoiseCoordinates1?(d._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),d._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(d._randomNoiseCoordinates1=new Vector3(Math.random(),Math.random(),Math.random()),d._randomNoiseCoordinates2=new Vector3(Math.random(),Math.random(),Math.random()))),d._inheritParticleInfoToSubEmitters()},b=this,k,j=0;j<e;j++){var $=_();if($==="break")break}},i._GetAttributeNamesOrOptions=function(e,o,s){e===void 0&&(e=!1),o===void 0&&(o=!1),s===void 0&&(s=!1);var c=[VertexBuffer.PositionKind,VertexBuffer.ColorKind,"angle","offset","size"];return e&&c.push("cellIndex"),o||c.push("direction"),s&&c.push("remapData"),c},i._GetEffectCreationOptions=function(e){e===void 0&&(e=!1);var o=["invView","view","projection","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","textureMask","translationPivot","eyePosition"];return e&&o.push("particlesInfos"),o},i.prototype.fillDefines=function(e,o){if(this._scene&&(this._scene.clipPlane&&e.push("#define CLIPPLANE"),this._scene.clipPlane2&&e.push("#define CLIPPLANE2"),this._scene.clipPlane3&&e.push("#define CLIPPLANE3"),this._scene.clipPlane4&&e.push("#define CLIPPLANE4"),this._scene.clipPlane5&&e.push("#define CLIPPLANE5"),this._scene.clipPlane6&&e.push("#define CLIPPLANE6")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),o===i.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case i.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case i.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case i.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))},i.prototype.fillUniformsAttributesAndSamplerNames=function(e,o,s){o.push.apply(o,i._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==i.BILLBOARDMODE_STRETCHED,this._useRampGradients)),e.push.apply(e,i._GetEffectCreationOptions(this._isAnimationSheetEnabled)),s.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ImageProcessingConfiguration.PrepareSamplers(s,this._imageProcessingConfigurationDefines))},i.prototype._getWrapper=function(e){var o=this._getCustomDrawWrapper(e);if(o!=null&&o.effect)return o;var s=[];this.fillDefines(s,e);var c=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,d=this._drawWrappers[c];d||(d=this._drawWrappers[c]=[]);var _=d[e];_||(_=new DrawWrapper(this._engine),_.drawContext&&(_.drawContext.useInstancing=this._useInstancing),d[e]=_);var b=s.join(`
  4161. `);if(_.defines!==b){var k=[],j=[],$=[];this.fillUniformsAttributesAndSamplerNames(j,k,$),_.setEffect(this._engine.createEffect("particles",k,j,$,b),b)}return _},i.prototype.animate=function(e){var o=this,s;if(e===void 0&&(e=!1),!!this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:((s=this._scene)===null||s===void 0?void 0:s.getAnimationRatio())||1);var c;if(this.manualEmitCount>-1)c=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{var d=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){var _=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(_,this._emitRateGradients,function($,_e,et){$!==o._currentEmitRateGradient&&(o._currentEmitRate1=o._currentEmitRate2,o._currentEmitRate2=_e.getFactor(),o._currentEmitRateGradient=$),d=Scalar.Lerp(o._currentEmitRate1,o._currentEmitRate2,et)})}c=d*this._scaledUpdateSpeed>>0,this._newPartsExcess+=d*this._scaledUpdateSpeed-c}if(this._newPartsExcess>1&&(c+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?c=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(c),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){for(var b=0,k=0;k<this._particles.length;k++){var j=this._particles[k];this._appendParticleVertices(b,j),b+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.updateDirectly(this._vertexData,0,this._particles.length)}this.manualEmitCount===0&&this.disposeOnStop&&this.stop()}},i.prototype._appendParticleVertices=function(e,o){this._appendParticleVertex(e++,o,0,0),this._useInstancing||(this._appendParticleVertex(e++,o,1,0),this._appendParticleVertex(e++,o,1,1),this._appendParticleVertex(e++,o,0,1))},i.prototype.rebuild=function(){var e,o;this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._createIndexBuffer(),(e=this._spriteBuffer)===null||e===void 0||e._rebuild(),(o=this._vertexBuffer)===null||o===void 0||o._rebuild();for(var s in this._vertexBuffers)this._vertexBuffers[s]._rebuild();this.resetDrawCache()},i.prototype.isReady=function(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==i.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(i.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(i.BLENDMODE_ADD).effect.isReady())return!1;return!0},i.prototype._render=function(e){var o,s,c=this._getWrapper(e),d=c.effect,_=this._engine;_.enableEffect(c);var b=(o=this.defaultViewMatrix)!==null&&o!==void 0?o:this._scene.getViewMatrix();if(d.setTexture("diffuseSampler",this.particleTexture),d.setMatrix("view",b),d.setMatrix("projection",(s=this.defaultProjectionMatrix)!==null&&s!==void 0?s:this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){var k=this.particleTexture.getBaseSize();d.setFloat3("particlesInfos",this.spriteCellWidth/k.width,this.spriteCellHeight/k.height,this.spriteCellWidth/k.width)}if(d.setVector2("translationPivot",this.translationPivot),d.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){var j=this._scene.activeCamera;d.setVector3("eyePosition",j.globalPosition)}this._rampGradientsTexture&&((!this._rampGradients||!this._rampGradients.length)&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),d.setTexture("rampSampler",this._rampGradientsTexture));var $=d.defines;switch(this._scene&&(this._scene.clipPlane||this._scene.clipPlane2||this._scene.clipPlane3||this._scene.clipPlane4||this._scene.clipPlane5||this._scene.clipPlane6)&&ThinMaterialHelper.BindClipPlane(d,this._scene),$.indexOf("#define BILLBOARDMODE_ALL")>=0&&(b.invertToRef(TmpVectors.Matrix[0]),d.setMatrix("invView",TmpVectors.Matrix[0])),this._vertexArrayObject!==void 0?(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,d)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):_.bindBuffers(this._vertexBuffers,this._indexBuffer,d),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(d),e){case i.BLENDMODE_ADD:_.setAlphaMode(1);break;case i.BLENDMODE_ONEONE:_.setAlphaMode(6);break;case i.BLENDMODE_STANDARD:_.setAlphaMode(2);break;case i.BLENDMODE_MULTIPLY:_.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(d),this._useInstancing?_.drawArraysType(7,0,4,this._particles.length):_.drawElementsType(0,0,this._particles.length*6),this._particles.length},i.prototype.render=function(){if(!this.isReady()||!this._particles.length)return 0;var e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));var o=0;return this.blendMode===i.BLENDMODE_MULTIPLYADD?o=this._render(i.BLENDMODE_MULTIPLY)+this._render(i.BLENDMODE_ADD):o=this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),o},i.prototype.dispose=function(e){if(e===void 0&&(e=!0),this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this._subEmitters&&this._subEmitters.length){for(var o=0;o<this._subEmitters.length;o++)for(var s=0,c=this._subEmitters[o];s<c.length;s++){var d=c[s];d.dispose()}this._subEmitters=[],this.subEmitters=[]}if(this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){var o=this._scene.particleSystems.indexOf(this);o>-1&&this._scene.particleSystems.splice(o,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()},i.prototype.clone=function(e,o){var s=__assign({},this._customWrappers),c=null,d=this._engine;if(d.createEffectForParticles&&this.customShader!=null){c=this.customShader;var _=c.shaderOptions.defines.length>0?c.shaderOptions.defines.join(`
  4162. `):"";s[0]=d.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,_)}var b=this.serialize(),k=i.Parse(b,this._scene||this._engine,this._rootUrl);return k.name=e,k.customShader=c,k._customWrappers=s,o===void 0&&(o=this.emitter),this.noiseTexture&&(k.noiseTexture=this.noiseTexture.clone()),k.emitter=o,this.preventAutoStart||k.start(),k},i.prototype.serialize=function(e){e===void 0&&(e=!1);var o={};if(i._Serialize(o,this,e),o.textureMask=this.textureMask.asArray(),o.customShader=this.customShader,o.preventAutoStart=this.preventAutoStart,this.subEmitters){o.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(var s=0,c=this._subEmitters;s<c.length;s++){for(var d=c[s],_=[],b=0,k=d;b<k.length;b++){var j=k[b];_.push(j.serialize(e))}o.subEmitters.push(_)}}return o},i._Serialize=function(e,o,s){if(e.name=o.name,e.id=o.id,e.capacity=o.getCapacity(),e.disposeOnStop=o.disposeOnStop,e.manualEmitCount=o.manualEmitCount,o.emitter.position){var c=o.emitter;e.emitterId=c.id}else{var d=o.emitter;e.emitter=d.asArray()}o.particleEmitterType&&(e.particleEmitterType=o.particleEmitterType.serialize()),o.particleTexture&&(s?e.texture=o.particleTexture.serialize():(e.textureName=o.particleTexture.name,e.invertY=!!o.particleTexture._invertY)),e.isLocal=o.isLocal,SerializationHelper.AppendSerializedAnimations(o,e),e.beginAnimationOnStart=o.beginAnimationOnStart,e.beginAnimationFrom=o.beginAnimationFrom,e.beginAnimationTo=o.beginAnimationTo,e.beginAnimationLoop=o.beginAnimationLoop,e.startDelay=o.startDelay,e.renderingGroupId=o.renderingGroupId,e.isBillboardBased=o.isBillboardBased,e.billboardMode=o.billboardMode,e.minAngularSpeed=o.minAngularSpeed,e.maxAngularSpeed=o.maxAngularSpeed,e.minSize=o.minSize,e.maxSize=o.maxSize,e.minScaleX=o.minScaleX,e.maxScaleX=o.maxScaleX,e.minScaleY=o.minScaleY,e.maxScaleY=o.maxScaleY,e.minEmitPower=o.minEmitPower,e.maxEmitPower=o.maxEmitPower,e.minLifeTime=o.minLifeTime,e.maxLifeTime=o.maxLifeTime,e.emitRate=o.emitRate,e.gravity=o.gravity.asArray(),e.noiseStrength=o.noiseStrength.asArray(),e.color1=o.color1.asArray(),e.color2=o.color2.asArray(),e.colorDead=o.colorDead.asArray(),e.updateSpeed=o.updateSpeed,e.targetStopDuration=o.targetStopDuration,e.blendMode=o.blendMode,e.preWarmCycles=o.preWarmCycles,e.preWarmStepOffset=o.preWarmStepOffset,e.minInitialRotation=o.minInitialRotation,e.maxInitialRotation=o.maxInitialRotation,e.startSpriteCellID=o.startSpriteCellID,e.spriteCellLoop=o.spriteCellLoop,e.endSpriteCellID=o.endSpriteCellID,e.spriteCellChangeSpeed=o.spriteCellChangeSpeed,e.spriteCellWidth=o.spriteCellWidth,e.spriteCellHeight=o.spriteCellHeight,e.spriteRandomStartCell=o.spriteRandomStartCell,e.isAnimationSheetEnabled=o.isAnimationSheetEnabled;var _=o.getColorGradients();if(_){e.colorGradients=[];for(var b=0,k=_;b<k.length;b++){var j=k[b],$={gradient:j.gradient,color1:j.color1.asArray()};j.color2?$.color2=j.color2.asArray():$.color2=j.color1.asArray(),e.colorGradients.push($)}}var _e=o.getRampGradients();if(_e){e.rampGradients=[];for(var et=0,tt=_e;et<tt.length;et++){var rt=tt[et],$={gradient:rt.gradient,color:rt.color.asArray()};e.rampGradients.push($)}e.useRampGradients=o.useRampGradients}var it=o.getColorRemapGradients();if(it){e.colorRemapGradients=[];for(var nt=0,ot=it;nt<ot.length;nt++){var at=ot[nt],$={gradient:at.gradient,factor1:at.factor1};at.factor2!==void 0?$.factor2=at.factor2:$.factor2=at.factor1,e.colorRemapGradients.push($)}}var st=o.getAlphaRemapGradients();if(st){e.alphaRemapGradients=[];for(var ut=0,ft=st;ut<ft.length;ut++){var lt=ft[ut],$={gradient:lt.gradient,factor1:lt.factor1};lt.factor2!==void 0?$.factor2=lt.factor2:$.factor2=lt.factor1,e.alphaRemapGradients.push($)}}var ht=o.getSizeGradients();if(ht){e.sizeGradients=[];for(var pt=0,mt=ht;pt<mt.length;pt++){var dt=mt[pt],$={gradient:dt.gradient,factor1:dt.factor1};dt.factor2!==void 0?$.factor2=dt.factor2:$.factor2=dt.factor1,e.sizeGradients.push($)}}var gt=o.getAngularSpeedGradients();if(gt){e.angularSpeedGradients=[];for(var _t=0,yt=gt;_t<yt.length;_t++){var Tt=yt[_t],$={gradient:Tt.gradient,factor1:Tt.factor1};Tt.factor2!==void 0?$.factor2=Tt.factor2:$.factor2=Tt.factor1,e.angularSpeedGradients.push($)}}var St=o.getVelocityGradients();if(St){e.velocityGradients=[];for(var At=0,vt=St;At<vt.length;At++){var Et=vt[At],$={gradient:Et.gradient,factor1:Et.factor1};Et.factor2!==void 0?$.factor2=Et.factor2:$.factor2=Et.factor1,e.velocityGradients.push($)}}var xt=o.getDragGradients();if(xt){e.dragGradients=[];for(var bt=0,Mt=xt;bt<Mt.length;bt++){var Rt=Mt[bt],$={gradient:Rt.gradient,factor1:Rt.factor1};Rt.factor2!==void 0?$.factor2=Rt.factor2:$.factor2=Rt.factor1,e.dragGradients.push($)}}var Pt=o.getEmitRateGradients();if(Pt){e.emitRateGradients=[];for(var It=0,Dt=Pt;It<Dt.length;It++){var Ct=Dt[It],$={gradient:Ct.gradient,factor1:Ct.factor1};Ct.factor2!==void 0?$.factor2=Ct.factor2:$.factor2=Ct.factor1,e.emitRateGradients.push($)}}var Ot=o.getStartSizeGradients();if(Ot){e.startSizeGradients=[];for(var Ft=0,wt=Ot;Ft<wt.length;Ft++){var Bt=wt[Ft],$={gradient:Bt.gradient,factor1:Bt.factor1};Bt.factor2!==void 0?$.factor2=Bt.factor2:$.factor2=Bt.factor1,e.startSizeGradients.push($)}}var Ut=o.getLifeTimeGradients();if(Ut){e.lifeTimeGradients=[];for(var Vt=0,Gt=Ut;Vt<Gt.length;Vt++){var Lt=Gt[Vt],$={gradient:Lt.gradient,factor1:Lt.factor1};Lt.factor2!==void 0?$.factor2=Lt.factor2:$.factor2=Lt.factor1,e.lifeTimeGradients.push($)}}var Ht=o.getLimitVelocityGradients();if(Ht){e.limitVelocityGradients=[];for(var Wt=0,Yt=Ht;Wt<Yt.length;Wt++){var jt=Yt[Wt],$={gradient:jt.gradient,factor1:jt.factor1};jt.factor2!==void 0?$.factor2=jt.factor2:$.factor2=jt.factor1,e.limitVelocityGradients.push($)}e.limitVelocityDamping=o.limitVelocityDamping}o.noiseTexture&&(e.noiseTexture=o.noiseTexture.serialize())},i._Parse=function(e,o,s,c){var d,_,b,k;s instanceof ThinEngine?k=null:k=s;var j=GetClass("BABYLON.Texture");if(j&&k&&(e.texture?o.particleTexture=j.Parse(e.texture,k,c):e.textureName&&(o.particleTexture=new j(c+e.textureName,k,!1,e.invertY!==void 0?e.invertY:!0),o.particleTexture.name=e.textureName)),!e.emitterId&&e.emitterId!==0&&e.emitter===void 0?o.emitter=Vector3.Zero():e.emitterId&&k?o.emitter=k.getLastMeshById(e.emitterId):o.emitter=Vector3.FromArray(e.emitter),o.isLocal=!!e.isLocal,e.renderingGroupId!==void 0&&(o.renderingGroupId=e.renderingGroupId),e.isBillboardBased!==void 0&&(o.isBillboardBased=e.isBillboardBased),e.billboardMode!==void 0&&(o.billboardMode=e.billboardMode),e.animations){for(var $=0;$<e.animations.length;$++){var _e=e.animations[$],et=GetClass("BABYLON.Animation");et&&o.animations.push(et.Parse(_e))}o.beginAnimationOnStart=e.beginAnimationOnStart,o.beginAnimationFrom=e.beginAnimationFrom,o.beginAnimationTo=e.beginAnimationTo,o.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&k&&k.beginAnimation(o,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),o.startDelay=e.startDelay|0,o.minAngularSpeed=e.minAngularSpeed,o.maxAngularSpeed=e.maxAngularSpeed,o.minSize=e.minSize,o.maxSize=e.maxSize,e.minScaleX&&(o.minScaleX=e.minScaleX,o.maxScaleX=e.maxScaleX,o.minScaleY=e.minScaleY,o.maxScaleY=e.maxScaleY),e.preWarmCycles!==void 0&&(o.preWarmCycles=e.preWarmCycles,o.preWarmStepOffset=e.preWarmStepOffset),e.minInitialRotation!==void 0&&(o.minInitialRotation=e.minInitialRotation,o.maxInitialRotation=e.maxInitialRotation),o.minLifeTime=e.minLifeTime,o.maxLifeTime=e.maxLifeTime,o.minEmitPower=e.minEmitPower,o.maxEmitPower=e.maxEmitPower,o.emitRate=e.emitRate,o.gravity=Vector3.FromArray(e.gravity),e.noiseStrength&&(o.noiseStrength=Vector3.FromArray(e.noiseStrength)),o.color1=Color4.FromArray(e.color1),o.color2=Color4.FromArray(e.color2),o.colorDead=Color4.FromArray(e.colorDead),o.updateSpeed=e.updateSpeed,o.targetStopDuration=e.targetStopDuration,o.blendMode=e.blendMode,e.colorGradients)for(var tt=0,rt=e.colorGradients;tt<rt.length;tt++){var it=rt[tt];o.addColorGradient(it.gradient,Color4.FromArray(it.color1),it.color2?Color4.FromArray(it.color2):void 0)}if(e.rampGradients){for(var nt=0,ot=e.rampGradients;nt<ot.length;nt++){var at=ot[nt];o.addRampGradient(at.gradient,Color3.FromArray(at.color))}o.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(var st=0,ut=e.colorRemapGradients;st<ut.length;st++){var ft=ut[st];o.addColorRemapGradient(ft.gradient,ft.factor1!==void 0?ft.factor1:ft.factor,ft.factor2)}if(e.alphaRemapGradients)for(var lt=0,ht=e.alphaRemapGradients;lt<ht.length;lt++){var pt=ht[lt];o.addAlphaRemapGradient(pt.gradient,pt.factor1!==void 0?pt.factor1:pt.factor,pt.factor2)}if(e.sizeGradients)for(var mt=0,dt=e.sizeGradients;mt<dt.length;mt++){var gt=dt[mt];o.addSizeGradient(gt.gradient,gt.factor1!==void 0?gt.factor1:gt.factor,gt.factor2)}if(e.angularSpeedGradients)for(var _t=0,yt=e.angularSpeedGradients;_t<yt.length;_t++){var Tt=yt[_t];o.addAngularSpeedGradient(Tt.gradient,Tt.factor1!==void 0?Tt.factor1:Tt.factor,Tt.factor2)}if(e.velocityGradients)for(var St=0,At=e.velocityGradients;St<At.length;St++){var vt=At[St];o.addVelocityGradient(vt.gradient,vt.factor1!==void 0?vt.factor1:vt.factor,vt.factor2)}if(e.dragGradients)for(var Et=0,xt=e.dragGradients;Et<xt.length;Et++){var bt=xt[Et];o.addDragGradient(bt.gradient,bt.factor1!==void 0?bt.factor1:bt.factor,bt.factor2)}if(e.emitRateGradients)for(var Mt=0,Rt=e.emitRateGradients;Mt<Rt.length;Mt++){var Pt=Rt[Mt];o.addEmitRateGradient(Pt.gradient,Pt.factor1!==void 0?Pt.factor1:Pt.factor,Pt.factor2)}if(e.startSizeGradients)for(var It=0,Dt=e.startSizeGradients;It<Dt.length;It++){var Ct=Dt[It];o.addStartSizeGradient(Ct.gradient,Ct.factor1!==void 0?Ct.factor1:Ct.factor,Ct.factor2)}if(e.lifeTimeGradients)for(var Ot=0,Ft=e.lifeTimeGradients;Ot<Ft.length;Ot++){var wt=Ft[Ot];o.addLifeTimeGradient(wt.gradient,wt.factor1!==void 0?wt.factor1:wt.factor,wt.factor2)}if(e.limitVelocityGradients){for(var Bt=0,Ut=e.limitVelocityGradients;Bt<Ut.length;Bt++){var Vt=Ut[Bt];o.addLimitVelocityGradient(Vt.gradient,Vt.factor1!==void 0?Vt.factor1:Vt.factor,Vt.factor2)}o.limitVelocityDamping=e.limitVelocityDamping}if(e.noiseTexture&&k){var Gt=GetClass("BABYLON.ProceduralTexture");o.noiseTexture=Gt.Parse(e.noiseTexture,k,c)}var Lt;if(e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":Lt=new SphereParticleEmitter;break;case"SphereDirectedParticleEmitter":Lt=new SphereDirectedParticleEmitter;break;case"ConeEmitter":case"ConeParticleEmitter":Lt=new ConeParticleEmitter;break;case"CylinderParticleEmitter":Lt=new CylinderParticleEmitter;break;case"CylinderDirectedParticleEmitter":Lt=new CylinderDirectedParticleEmitter;break;case"HemisphericParticleEmitter":Lt=new HemisphericParticleEmitter;break;case"PointParticleEmitter":Lt=new PointParticleEmitter;break;case"MeshParticleEmitter":Lt=new MeshParticleEmitter;break;case"BoxEmitter":case"BoxParticleEmitter":default:Lt=new BoxParticleEmitter;break}Lt.parse(e.particleEmitterType,k)}else Lt=new BoxParticleEmitter,Lt.parse(e,k);o.particleEmitterType=Lt,o.startSpriteCellID=e.startSpriteCellID,o.endSpriteCellID=e.endSpriteCellID,o.spriteCellLoop=(d=e.spriteCellLoop)!==null&&d!==void 0?d:!0,o.spriteCellWidth=e.spriteCellWidth,o.spriteCellHeight=e.spriteCellHeight,o.spriteCellChangeSpeed=e.spriteCellChangeSpeed,o.spriteRandomStartCell=e.spriteRandomStartCell,o.disposeOnStop=(_=e.disposeOnStop)!==null&&_!==void 0?_:!1,o.manualEmitCount=(b=e.manualEmitCount)!==null&&b!==void 0?b:-1},i.Parse=function(e,o,s,c,d){c===void 0&&(c=!1);var _=e.name,b=null,k=null,j,$;if(o instanceof ThinEngine?j=o:($=o,j=$.getEngine()),e.customShader&&j.createEffectForParticles){k=e.customShader;var _e=k.shaderOptions.defines.length>0?k.shaderOptions.defines.join(`
  4163. `):"";b=j.createEffectForParticles(k.shaderPath.fragmentElement,k.shaderOptions.uniforms,k.shaderOptions.samplers,_e)}var et=new i(_,d||e.capacity,o,b,e.isAnimationSheetEnabled);if(et.customShader=k,et._rootUrl=s,e.id&&(et.id=e.id),e.subEmitters){et.subEmitters=[];for(var tt=0,rt=e.subEmitters;tt<rt.length;tt++){for(var it=rt[tt],nt=[],ot=0,at=it;ot<at.length;ot++){var st=at[ot];nt.push(SubEmitter.Parse(st,o,s))}et.subEmitters.push(nt)}}return i._Parse(e,et,o,s),e.textureMask&&(et.textureMask=Color4.FromArray(e.textureMask)),e.preventAutoStart&&(et.preventAutoStart=e.preventAutoStart),!c&&!et.preventAutoStart&&et.start(),et},i.BILLBOARDMODE_Y=2,i.BILLBOARDMODE_ALL=7,i.BILLBOARDMODE_STRETCHED=8,i}(BaseParticleSystem);SubEmitter._ParseParticleSystem=ParticleSystem.Parse;var name$1k="clipPlaneFragmentDeclaration2",shader$1k=`#ifdef CLIPPLANE
  4164. in float fClipDistance;
  4165. #endif
  4166. #ifdef CLIPPLANE2
  4167. in float fClipDistance2;
  4168. #endif
  4169. #ifdef CLIPPLANE3
  4170. in float fClipDistance3;
  4171. #endif
  4172. #ifdef CLIPPLANE4
  4173. in float fClipDistance4;
  4174. #endif
  4175. #ifdef CLIPPLANE5
  4176. in float fClipDistance5;
  4177. #endif
  4178. #ifdef CLIPPLANE6
  4179. in float fClipDistance6;
  4180. #endif`;ShaderStore.IncludesShadersStore[name$1k]=shader$1k;var name$1j="gpuRenderParticlesPixelShader",shader$1j=`precision highp float;
  4181. uniform sampler2D diffuseSampler;
  4182. varying vec2 vUV;
  4183. varying vec4 vColor;
  4184. #include<clipPlaneFragmentDeclaration2>
  4185. #include<imageProcessingDeclaration>
  4186. #include<helperFunctions>
  4187. #include<imageProcessingFunctions>
  4188. void main() {
  4189. #include<clipPlaneFragment>
  4190. vec4 textureColor=texture2D(diffuseSampler,vUV);
  4191. gl_FragColor=textureColor*vColor;
  4192. #ifdef BLENDMULTIPLYMODE
  4193. float alpha=vColor.a*textureColor.a;
  4194. gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);
  4195. #endif
  4196. #ifdef IMAGEPROCESSINGPOSTPROCESS
  4197. gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);
  4198. #else
  4199. #ifdef IMAGEPROCESSING
  4200. gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);
  4201. gl_FragColor=applyImageProcessing(gl_FragColor);
  4202. #endif
  4203. #endif
  4204. }
  4205. `;ShaderStore.ShadersStore[name$1j]=shader$1j;var name$1i="clipPlaneVertexDeclaration2",shader$1i=`#ifdef CLIPPLANE
  4206. uniform vec4 vClipPlane;
  4207. out float fClipDistance;
  4208. #endif
  4209. #ifdef CLIPPLANE2
  4210. uniform vec4 vClipPlane2;
  4211. out float fClipDistance2;
  4212. #endif
  4213. #ifdef CLIPPLANE3
  4214. uniform vec4 vClipPlane3;
  4215. out float fClipDistance3;
  4216. #endif
  4217. #ifdef CLIPPLANE4
  4218. uniform vec4 vClipPlane4;
  4219. out float fClipDistance4;
  4220. #endif
  4221. #ifdef CLIPPLANE5
  4222. uniform vec4 vClipPlane5;
  4223. out float fClipDistance5;
  4224. #endif
  4225. #ifdef CLIPPLANE6
  4226. uniform vec4 vClipPlane6;
  4227. out float fClipDistance6;
  4228. #endif`;ShaderStore.IncludesShadersStore[name$1i]=shader$1i;var name$1h="gpuRenderParticlesVertexShader",shader$1h=`precision highp float;
  4229. uniform mat4 view;
  4230. uniform mat4 projection;
  4231. uniform vec2 translationPivot;
  4232. uniform vec3 worldOffset;
  4233. #ifdef LOCAL
  4234. uniform mat4 emitterWM;
  4235. #endif
  4236. attribute vec3 position;
  4237. attribute float age;
  4238. attribute float life;
  4239. attribute vec3 size;
  4240. #ifndef BILLBOARD
  4241. attribute vec3 initialDirection;
  4242. #endif
  4243. #ifdef BILLBOARDSTRETCHED
  4244. attribute vec3 direction;
  4245. #endif
  4246. attribute float angle;
  4247. #ifdef ANIMATESHEET
  4248. attribute float cellIndex;
  4249. #endif
  4250. attribute vec2 offset;
  4251. attribute vec2 uv;
  4252. varying vec2 vUV;
  4253. varying vec4 vColor;
  4254. varying vec3 vPositionW;
  4255. #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
  4256. uniform mat4 invView;
  4257. #endif
  4258. #include<clipPlaneVertexDeclaration2>
  4259. #ifdef COLORGRADIENTS
  4260. uniform sampler2D colorGradientSampler;
  4261. #else
  4262. uniform vec4 colorDead;
  4263. attribute vec4 color;
  4264. #endif
  4265. #ifdef ANIMATESHEET
  4266. uniform vec3 sheetInfos;
  4267. #endif
  4268. #ifdef BILLBOARD
  4269. uniform vec3 eyePosition;
  4270. #endif
  4271. vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {
  4272. vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));
  4273. vec3 zaxis=normalize(cross(yaxis,xaxis));
  4274. vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);
  4275. vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);
  4276. vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);
  4277. mat3 rotMatrix=mat3(row0,row1,row2);
  4278. vec3 alignedCorner=rotMatrix*rotatedCorner;
  4279. #ifdef LOCAL
  4280. return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
  4281. #else
  4282. return (position+worldOffset)+alignedCorner;
  4283. #endif
  4284. }
  4285. #ifdef BILLBOARDSTRETCHED
  4286. vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {
  4287. vec3 normalizedToCamera=normalize(toCamera);
  4288. vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));
  4289. vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));
  4290. vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);
  4291. vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);
  4292. vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);
  4293. mat3 rotMatrix=mat3(row0,row1,row2);
  4294. vec3 alignedCorner=rotMatrix*rotatedCorner;
  4295. #ifdef LOCAL
  4296. return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
  4297. #else
  4298. return (position+worldOffset)+alignedCorner;
  4299. #endif
  4300. }
  4301. #endif
  4302. void main() {
  4303. #ifdef ANIMATESHEET
  4304. float rowOffset=floor(cellIndex/sheetInfos.z);
  4305. float columnOffset=cellIndex-rowOffset*sheetInfos.z;
  4306. vec2 uvScale=sheetInfos.xy;
  4307. vec2 uvOffset=vec2(uv.x ,1.0-uv.y);
  4308. vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
  4309. #else
  4310. vUV=uv;
  4311. #endif
  4312. float ratio=age/life;
  4313. #ifdef COLORGRADIENTS
  4314. vColor=texture2D(colorGradientSampler,vec2(ratio,0));
  4315. #else
  4316. vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);
  4317. #endif
  4318. vec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;
  4319. #ifdef BILLBOARD
  4320. vec4 rotatedCorner;
  4321. rotatedCorner.w=0.;
  4322. #ifdef BILLBOARDY
  4323. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4324. rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4325. rotatedCorner.y=0.;
  4326. vec3 yaxis=(position+worldOffset)-eyePosition;
  4327. yaxis.y=0.;
  4328. vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);
  4329. vec4 viewPosition=(view*vec4(vPositionW,1.0));
  4330. #elif defined(BILLBOARDSTRETCHED)
  4331. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4332. rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4333. rotatedCorner.z=0.;
  4334. vec3 toCamera=(position+worldOffset)-eyePosition;
  4335. vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);
  4336. vec4 viewPosition=(view*vec4(vPositionW,1.0));
  4337. #else
  4338. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4339. rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4340. rotatedCorner.z=0.;
  4341. #ifdef LOCAL
  4342. vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;
  4343. #else
  4344. vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;
  4345. #endif
  4346. vPositionW=(invView*viewPosition).xyz;
  4347. #endif
  4348. #else
  4349. vec3 rotatedCorner;
  4350. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  4351. rotatedCorner.y=0.;
  4352. rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  4353. vec3 yaxis=normalize(initialDirection);
  4354. vPositionW=rotate(yaxis,rotatedCorner);
  4355. vec4 viewPosition=view*vec4(vPositionW,1.0);
  4356. #endif
  4357. gl_Position=projection*viewPosition;
  4358. #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
  4359. vec4 worldPos=vec4(vPositionW,1.0);
  4360. #endif
  4361. #include<clipPlaneVertex>
  4362. }`;ShaderStore.ShadersStore[name$1h]=shader$1h;var GPUParticleSystem=function(a){__extends(i,a);function i(e,o,s,c,d){c===void 0&&(c=null),d===void 0&&(d=!1);var _=a.call(this,e)||this;if(_.layerMask=268435455,_._accumulatedCount=0,_._targetIndex=0,_._currentRenderId=-1,_._currentRenderingCameraUniqueId=-1,_._started=!1,_._stopped=!1,_._timeDelta=0,_._actualFrame=0,_._rawTextureWidth=256,_.onDisposeObservable=new Observable,_.onStoppedObservable=new Observable,_.forceDepthWrite=!1,_._preWarmDone=!1,_.isLocal=!1,_._onBeforeDrawParticlesObservable=null,!s||s.getClassName()==="Scene"?(_._scene=s||EngineStore.LastCreatedScene,_._engine=_._scene.getEngine(),_.uniqueId=_._scene.getUniqueId(),_._scene.particleSystems.push(_)):(_._engine=s,_.defaultProjectionMatrix=Matrix.PerspectiveFovLH(.8,1,.1,100,_._engine.isNDCHalfZRange)),_._engine.getCaps().supportComputeShaders){if(!GetClass("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");_._platform=new(GetClass("BABYLON.ComputeShaderParticleSystem"))(_,_._engine)}else{if(!GetClass("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");_._platform=new(GetClass("BABYLON.WebGL2ParticleSystem"))(_,_._engine)}_._customWrappers={0:new DrawWrapper(_._engine)},_._customWrappers[0].effect=c,_._drawWrappers={0:new DrawWrapper(_._engine)},_._drawWrappers[0].drawContext&&(_._drawWrappers[0].drawContext.useInstancing=!0),_._attachImageProcessingConfiguration(null),o=o!=null?o:{},o.randomTextureSize||delete o.randomTextureSize;var b=__assign({capacity:5e4,randomTextureSize:_._engine.getCaps().maxTextureSize},o),k=o;isFinite(k)&&(b.capacity=k),_._capacity=b.capacity,_._activeCount=b.capacity,_._currentActiveCount=0,_._isAnimationSheetEnabled=d,_.particleEmitterType=new BoxParticleEmitter;for(var j=Math.min(_._engine.getCaps().maxTextureSize,b.randomTextureSize),$=[],_e=0;_e<j;++_e)$.push(Math.random()),$.push(Math.random()),$.push(Math.random()),$.push(Math.random());_._randomTexture=new RawTexture(new Float32Array($),j,1,5,s,!1,!1,1,1),_._randomTexture.name="GPUParticleSystem_random1",_._randomTexture.wrapU=1,_._randomTexture.wrapV=1,$=[];for(var _e=0;_e<j;++_e)$.push(Math.random()),$.push(Math.random()),$.push(Math.random()),$.push(Math.random());return _._randomTexture2=new RawTexture(new Float32Array($),j,1,5,s,!1,!1,1,1),_._randomTexture2.name="GPUParticleSystem_random2",_._randomTexture2.wrapU=1,_._randomTexture2.wrapV=1,_._randomTextureSize=j,_}return Object.defineProperty(i,"IsSupported",{get:function(){return EngineStore.LastCreatedEngine?EngineStore.LastCreatedEngine.name==="WebGL"&&EngineStore.LastCreatedEngine.version>1||EngineStore.LastCreatedEngine.getCaps().supportComputeShaders:!1},enumerable:!1,configurable:!0}),i.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(i.prototype,"activeParticleCount",{get:function(){return this._activeCount},set:function(e){this._activeCount=Math.min(e,this._capacity)},enumerable:!1,configurable:!0}),i.prototype.isReady=function(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)},i.prototype.isStarted=function(){return this._started},i.prototype.isStopped=function(){return this._stopped},i.prototype.isStopping=function(){return!1},i.prototype.getActiveCount=function(){return this._currentActiveCount},i.prototype.start=function(e){var o=this;if(e===void 0&&(e=this.startDelay),!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(function(){o.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)},i.prototype.stop=function(){this._stopped||(this._stopped=!0)},i.prototype.reset=function(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0},i.prototype.getClassName=function(){return"GPUParticleSystem"},i.prototype.getCustomEffect=function(e){var o,s;return e===void 0&&(e=0),(s=(o=this._customWrappers[e])===null||o===void 0?void 0:o.effect)!==null&&s!==void 0?s:this._customWrappers[0].effect},i.prototype._getCustomDrawWrapper=function(e){var o;return e===void 0&&(e=0),(o=this._customWrappers[e])!==null&&o!==void 0?o:this._customWrappers[0]},i.prototype.setCustomEffect=function(e,o){o===void 0&&(o=0),this._customWrappers[o]=new DrawWrapper(this._engine),this._customWrappers[o].effect=e},Object.defineProperty(i.prototype,"onBeforeDrawParticlesObservable",{get:function(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Observable),this._onBeforeDrawParticlesObservable},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vertexShaderName",{get:function(){return"gpuRenderParticles"},enumerable:!1,configurable:!0}),i.prototype._removeGradientAndTexture=function(e,o,s){return a.prototype._removeGradientAndTexture.call(this,e,o,s),this._releaseBuffers(),this},i.prototype.addColorGradient=function(e,o,s){this._colorGradients||(this._colorGradients=[]);var c=new ColorGradient(e,o);return this._colorGradients.push(c),this._refreshColorGradient(!0),this._releaseBuffers(),this},i.prototype._refreshColorGradient=function(e){e===void 0&&(e=!1),this._colorGradients&&(e&&this._colorGradients.sort(function(o,s){return o.gradient<s.gradient?-1:o.gradient>s.gradient?1:0}),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))},i.prototype.forceRefreshGradients=function(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()},i.prototype.removeColorGradient=function(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},i.prototype.resetDrawCache=function(){var e;for(var o in this._drawWrappers){var s=this._drawWrappers[o];(e=s.drawContext)===null||e===void 0||e.reset()}},i.prototype._addFactorGradient=function(e,o,s){var c=new FactorGradient(o,s);e.push(c),this._releaseBuffers()},i.prototype.addSizeGradient=function(e,o){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,o),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this},i.prototype.removeSizeGradient=function(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this},i.prototype._refreshFactorGradient=function(e,o,s){if(s===void 0&&(s=!1),!!e){s&&e.sort(function(d,_){return d.gradient<_.gradient?-1:d.gradient>_.gradient?1:0});var c=this;c[o]&&(c[o].dispose(),c[o]=null)}},i.prototype.addAngularSpeedGradient=function(e,o){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,o),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this},i.prototype.removeAngularSpeedGradient=function(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},i.prototype.addVelocityGradient=function(e,o){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,o),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this},i.prototype.removeVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},i.prototype.addLimitVelocityGradient=function(e,o){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,o),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this},i.prototype.removeLimitVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this},i.prototype.addDragGradient=function(e,o){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,o),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this},i.prototype.removeDragGradient=function(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this},i.prototype.addEmitRateGradient=function(e,o,s){return this},i.prototype.removeEmitRateGradient=function(e){return this},i.prototype.addStartSizeGradient=function(e,o,s){return this},i.prototype.removeStartSizeGradient=function(e){return this},i.prototype.addColorRemapGradient=function(e,o,s){return this},i.prototype.removeColorRemapGradient=function(){return this},i.prototype.addAlphaRemapGradient=function(e,o,s){return this},i.prototype.removeAlphaRemapGradient=function(){return this},i.prototype.addRampGradient=function(e,o){return this},i.prototype.removeRampGradient=function(){return this},i.prototype.getRampGradients=function(){return null},Object.defineProperty(i.prototype,"useRampGradients",{get:function(){return!1},set:function(e){},enumerable:!1,configurable:!0}),i.prototype.addLifeTimeGradient=function(e,o,s){return this},i.prototype.removeLifeTimeGradient=function(e){return this},i.prototype._reset=function(){this._releaseBuffers()},i.prototype._createVertexBuffers=function(e,o,s){var c={};c.position=o.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);var d=3;c.age=o.createVertexBuffer("age",d,1,this._attributesStrideSize,!0),d+=1,c.size=o.createVertexBuffer("size",d,3,this._attributesStrideSize,!0),d+=3,c.life=o.createVertexBuffer("life",d,1,this._attributesStrideSize,!0),d+=1,d+=4,this.billboardMode===ParticleSystem.BILLBOARDMODE_STRETCHED&&(c.direction=o.createVertexBuffer("direction",d,3,this._attributesStrideSize,!0)),d+=3,this._platform.alignDataInBuffer&&(d+=1),this.particleEmitterType instanceof CustomParticleEmitter&&(d+=3,this._platform.alignDataInBuffer&&(d+=1)),this._colorGradientsTexture||(c.color=o.createVertexBuffer("color",d,4,this._attributesStrideSize,!0),d+=4),this._isBillboardBased||(c.initialDirection=o.createVertexBuffer("initialDirection",d,3,this._attributesStrideSize,!0),d+=3,this._platform.alignDataInBuffer&&(d+=1)),this.noiseTexture&&(c.noiseCoordinates1=o.createVertexBuffer("noiseCoordinates1",d,3,this._attributesStrideSize,!0),d+=3,this._platform.alignDataInBuffer&&(d+=1),c.noiseCoordinates2=o.createVertexBuffer("noiseCoordinates2",d,3,this._attributesStrideSize,!0),d+=3,this._platform.alignDataInBuffer&&(d+=1)),c.angle=o.createVertexBuffer("angle",d,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?d++:d+=2,this._isAnimationSheetEnabled&&(c.cellIndex=o.createVertexBuffer("cellIndex",d,1,this._attributesStrideSize,!0),d+=1,this.spriteRandomStartCell&&(c.cellStartOffset=o.createVertexBuffer("cellStartOffset",d,1,this._attributesStrideSize,!0),d+=1)),c.offset=s.createVertexBuffer("offset",0,2),c.uv=s.createVertexBuffer("uv",2,2),this._platform.createVertexBuffers(e,c),this.resetDrawCache()},i.prototype._initialize=function(e){if(e===void 0&&(e=!1),!(this._buffer0&&!e)){var o=this._engine,s=new Array;this._attributesStrideSize=21,this._targetIndex=0,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1),this.particleEmitterType instanceof CustomParticleEmitter&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this.isBillboardBased||(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=2)),this._platform.alignDataInBuffer&&(this._attributesStrideSize+=3-(this._attributesStrideSize+3&3));for(var c=this.particleEmitterType instanceof CustomParticleEmitter,d=TmpVectors.Vector3[0],_=0,b=0;b<this._capacity;b++)if(s.push(0),s.push(0),s.push(0),s.push(0),s.push(0),s.push(0),s.push(0),s.push(0),s.push(Math.random()),s.push(Math.random()),s.push(Math.random()),s.push(Math.random()),c?(this.particleEmitterType.particleDestinationGenerator(b,null,d),s.push(d.x),s.push(d.y),s.push(d.z)):(s.push(0),s.push(0),s.push(0)),this._platform.alignDataInBuffer&&s.push(0),_+=16,c&&(this.particleEmitterType.particlePositionGenerator(b,null,d),s.push(d.x),s.push(d.y),s.push(d.z),this._platform.alignDataInBuffer&&s.push(0),_+=4),this._colorGradientsTexture||(s.push(0),s.push(0),s.push(0),s.push(0),_+=4),this.isBillboardBased||(s.push(0),s.push(0),s.push(0),this._platform.alignDataInBuffer&&s.push(0),_+=4),this.noiseTexture&&(s.push(Math.random()),s.push(Math.random()),s.push(Math.random()),this._platform.alignDataInBuffer&&s.push(0),s.push(Math.random()),s.push(Math.random()),s.push(Math.random()),this._platform.alignDataInBuffer&&s.push(0),_+=8),s.push(0),_+=1,this._angularSpeedGradientsTexture||(s.push(0),_+=1),this._isAnimationSheetEnabled&&(s.push(0),_+=1,this.spriteRandomStartCell&&(s.push(0),_+=1)),this._platform.alignDataInBuffer){var k=3-(_+3&3);for(_+=k;k-- >0;)s.push(0)}var j=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),$=this._platform.createParticleBuffer(s),_e=this._platform.createParticleBuffer(s);this._buffer0=new Buffer(o,$,!1,this._attributesStrideSize),this._buffer1=new Buffer(o,_e,!1,this._attributesStrideSize),this._spriteBuffer=new Buffer(o,j,!1,4),this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}},i.prototype._recreateUpdateEffect=function(){var e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";this._isBillboardBased&&(e+=`
  4363. #define BILLBOARD`),this._colorGradientsTexture&&(e+=`
  4364. #define COLORGRADIENTS`),this._sizeGradientsTexture&&(e+=`
  4365. #define SIZEGRADIENTS`),this._angularSpeedGradientsTexture&&(e+=`
  4366. #define ANGULARSPEEDGRADIENTS`),this._velocityGradientsTexture&&(e+=`
  4367. #define VELOCITYGRADIENTS`),this._limitVelocityGradientsTexture&&(e+=`
  4368. #define LIMITVELOCITYGRADIENTS`),this._dragGradientsTexture&&(e+=`
  4369. #define DRAGGRADIENTS`),this.isAnimationSheetEnabled&&(e+=`
  4370. #define ANIMATESHEET`,this.spriteRandomStartCell&&(e+=`
  4371. #define ANIMATESHEETRANDOMSTART`)),this.noiseTexture&&(e+=`
  4372. #define NOISE`),this.isLocal&&(e+=`
  4373. #define LOCAL`),!(this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e)&&(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e))},i.prototype._getWrapper=function(e){var o=this._getCustomDrawWrapper(e);if(o!=null&&o.effect)return o;var s=[];this.fillDefines(s,e);var c=this._drawWrappers[e];c||(c=new DrawWrapper(this._engine),c.drawContext&&(c.drawContext.useInstancing=!0),this._drawWrappers[e]=c);var d=s.join(`
  4374. `);if(c.defines!==d){var _=[],b=[],k=[];this.fillUniformsAttributesAndSamplerNames(b,_,k),c.setEffect(this._engine.createEffect("gpuRenderParticles",_,b,k,d),d)}return c},i._GetAttributeNamesOrOptions=function(e,o,s,c){e===void 0&&(e=!1),o===void 0&&(o=!1),s===void 0&&(s=!1),c===void 0&&(c=!1);var d=[VertexBuffer.PositionKind,"age","life","size","angle"];return e||d.push(VertexBuffer.ColorKind),o&&d.push("cellIndex"),s||d.push("initialDirection"),c||d.push("direction"),d.push("offset",VertexBuffer.UVKind),d},i._GetEffectCreationOptions=function(e){e===void 0&&(e=!1);var o=["emitterWM","worldOffset","view","projection","colorDead","invView","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","translationPivot","eyePosition"];return e&&o.push("sheetInfos"),o},i.prototype.fillDefines=function(e,o){if(o===void 0&&(o=0),this._scene&&(this._scene.clipPlane&&e.push("#define CLIPPLANE"),this._scene.clipPlane2&&e.push("#define CLIPPLANE2"),this._scene.clipPlane3&&e.push("#define CLIPPLANE3"),this._scene.clipPlane4&&e.push("#define CLIPPLANE4"),this._scene.clipPlane5&&e.push("#define CLIPPLANE5"),this._scene.clipPlane6&&e.push("#define CLIPPLANE6")),o===ParticleSystem.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case ParticleSystem.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case ParticleSystem.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))},i.prototype.fillUniformsAttributesAndSamplerNames=function(e,o,s){o.push.apply(o,i._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===ParticleSystem.BILLBOARDMODE_STRETCHED)),e.push.apply(e,i._GetEffectCreationOptions(this._isAnimationSheetEnabled)),s.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ImageProcessingConfiguration.PrepareSamplers(s,this._imageProcessingConfigurationDefines))},i.prototype.animate=function(e){var o;e===void 0&&(e=!1),this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:((o=this._scene)===null||o===void 0?void 0:o.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()},i.prototype._createFactorGradientTexture=function(e,o){var s=this[o];if(!(!e||!e.length||s)){for(var c=new Float32Array(this._rawTextureWidth),d=0;d<this._rawTextureWidth;d++){var _=d/this._rawTextureWidth;GradientHelper.GetCurrentGradient(_,e,function(b,k,j){c[d]=Scalar.Lerp(b.factor1,k.factor1,j)})}this[o]=RawTexture.CreateRTexture(c,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1)}},i.prototype._createSizeGradientTexture=function(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")},i.prototype._createAngularSpeedGradientTexture=function(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")},i.prototype._createVelocityGradientTexture=function(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")},i.prototype._createLimitVelocityGradientTexture=function(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")},i.prototype._createDragGradientTexture=function(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")},i.prototype._createColorGradientTexture=function(){if(!(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)){for(var e=new Uint8Array(this._rawTextureWidth*4),o=TmpColors.Color4[0],s=0;s<this._rawTextureWidth;s++){var c=s/this._rawTextureWidth;GradientHelper.GetCurrentGradient(c,this._colorGradients,function(d,_,b){Color4.LerpToRef(d.color1,_.color1,b,o),e[s*4]=o.r*255,e[s*4+1]=o.g*255,e[s*4+2]=o.b*255,e[s*4+3]=o.a*255})}this._colorGradientsTexture=RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}},i.prototype._render=function(e,o){var s,c,d=this._getWrapper(e),_=d.effect;this._engine.enableEffect(d);var b=((s=this._scene)===null||s===void 0?void 0:s.getViewMatrix())||Matrix.IdentityReadOnly;if(_.setMatrix("view",b),_.setMatrix("projection",(c=this.defaultProjectionMatrix)!==null&&c!==void 0?c:this._scene.getProjectionMatrix()),_.setTexture("diffuseSampler",this.particleTexture),_.setVector2("translationPivot",this.translationPivot),_.setVector3("worldOffset",this.worldOffset),this.isLocal&&_.setMatrix("emitterWM",o),this._colorGradientsTexture?_.setTexture("colorGradientSampler",this._colorGradientsTexture):_.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var k=this.particleTexture.getBaseSize();_.setFloat3("sheetInfos",this.spriteCellWidth/k.width,this.spriteCellHeight/k.height,k.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){var j=this._scene.activeCamera;_.setVector3("eyePosition",j.globalPosition)}var $=_.defines;if(this._scene&&(this._scene.clipPlane||this._scene.clipPlane2||this._scene.clipPlane3||this._scene.clipPlane4||this._scene.clipPlane5||this._scene.clipPlane6)&&MaterialHelper.BindClipPlane(_,this._scene),$.indexOf("#define BILLBOARDMODE_ALL")>=0){var _e=b.clone();_e.invert(),_.setMatrix("invView",_e)}switch(this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(_),e){case ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case ParticleSystem.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,_),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(_),this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._currentActiveCount},i.prototype.render=function(e,o){if(e===void 0&&(e=!1),o===void 0&&(o=!1),!this._started||(this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture(),this._recreateUpdateEffect(),!this.isReady()))return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(var s=0;s<this.preWarmCycles;s++)this.animate(!0),this.render(!0,!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getFrameId()&&(!this._scene.activeCamera||this._scene.activeCamera&&this._currentRenderingCameraUniqueId===this._scene.activeCamera.uniqueId))return 0;this._currentRenderId=this._scene.getFrameId(),this._scene.activeCamera&&(this._currentRenderingCameraUniqueId=this._scene.activeCamera.uniqueId)}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){var c=this._accumulatedCount|0;this._accumulatedCount-=c,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+c)}if(!this._currentActiveCount)return 0;var d;if(this.emitter.position){var _=this.emitter;d=_.getWorldMatrix()}else{var b=this.emitter;d=Matrix.Translation(b.x,b.y,b.z)}var k=this._engine;this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",d),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount);var j=0;!e&&!o&&(k.setState(!1),this.forceDepthWrite&&k.setDepthWrite(!0),this.blendMode===ParticleSystem.BLENDMODE_MULTIPLYADD?j=this._render(ParticleSystem.BLENDMODE_MULTIPLY,d)+this._render(ParticleSystem.BLENDMODE_ADD,d):j=this._render(this.blendMode,d),this._engine.setAlphaMode(0)),this._targetIndex++,this._targetIndex===2&&(this._targetIndex=0);var $=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=$,j},i.prototype.rebuild=function(){this._initialize(!0)},i.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()},i.prototype.dispose=function(e){e===void 0&&(e=!0);for(var o in this._drawWrappers){var s=this._drawWrappers[o];s.dispose()}if(this._drawWrappers={},this._scene){var c=this._scene.particleSystems.indexOf(this);c>-1&&this._scene.particleSystems.splice(c,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onStoppedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},i.prototype.clone=function(e,o){var s=__assign({},this._customWrappers),c=null,d=this._engine;if(d.createEffectForParticles&&this.customShader!=null){c=this.customShader;var _=c.shaderOptions.defines.length>0?c.shaderOptions.defines.join(`
  4375. `):"";s[0]=d.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,_,void 0,void 0,void 0,this)}var b=this.serialize(),k=i.Parse(b,this._scene||this._engine,this._rootUrl);return k.name=e,k.customShader=c,k._customWrappers=s,o===void 0&&(o=this.emitter),this.noiseTexture&&(k.noiseTexture=this.noiseTexture.clone()),k.emitter=o,k},i.prototype.serialize=function(e){e===void 0&&(e=!1);var o={};return ParticleSystem._Serialize(o,this,e),o.activeParticleCount=this.activeParticleCount,o.randomTextureSize=this._randomTextureSize,o.customShader=this.customShader,o},i.Parse=function(e,o,s,c,d){c===void 0&&(c=!1);var _=e.name,b,k;o instanceof ThinEngine?b=o:(k=o,b=k.getEngine());var j=new i(_,{capacity:d||e.capacity,randomTextureSize:e.randomTextureSize},o,null,e.isAnimationSheetEnabled);if(j._rootUrl=s,e.customShader&&b.createEffectForParticles){var $=e.customShader,_e=$.shaderOptions.defines.length>0?$.shaderOptions.defines.join(`
  4376. `):"",et=b.createEffectForParticles($.shaderPath.fragmentElement,$.shaderOptions.uniforms,$.shaderOptions.samplers,_e,void 0,void 0,void 0,j);j.setCustomEffect(et,0),j.customShader=$}return e.id&&(j.id=e.id),e.activeParticleCount&&(j.activeParticleCount=e.activeParticleCount),ParticleSystem._Parse(e,j,o,s),e.preventAutoStart&&(j.preventAutoStart=e.preventAutoStart),!c&&!j.preventAutoStart&&j.start(),j},i}(BaseParticleSystem),ParticleSystemSet=function(){function a(){this._emitterNodeIsOwned=!0,this.systems=new Array}return Object.defineProperty(a.prototype,"emitterNode",{get:function(){return this._emitterNode},set:function(i){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(var e=0,o=this.systems;e<o.length;e++){var s=o[e];s.emitter=i}this._emitterNode=i},enumerable:!1,configurable:!0}),a.prototype.setEmitterAsSphere=function(i,e,o){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:i,renderingGroupId:e};var s=CreateSphere("emitterSphere",{diameter:i.diameter,segments:i.segments},o);s.renderingGroupId=e;var c=new StandardMaterial("emitterSphereMaterial",o);c.emissiveColor=i.color,s.material=c;for(var d=0,_=this.systems;d<_.length;d++){var b=_[d];b.emitter=s}this._emitterNode=s},a.prototype.start=function(i){for(var e=0,o=this.systems;e<o.length;e++){var s=o[e];i&&(s.emitter=i),s.start()}},a.prototype.dispose=function(){for(var i=0,e=this.systems;i<e.length;i++){var o=e[i];o.dispose()}this.systems=[],this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)},a.prototype.serialize=function(i){i===void 0&&(i=!1);var e={};e.systems=[];for(var o=0,s=this.systems;o<s.length;o++){var c=s[o];e.systems.push(c.serialize(i))}return this._emitterNode&&(e.emitter=this._emitterCreationOptions),e},a.Parse=function(i,e,o,s){o===void 0&&(o=!1);var c=new a,d=this.BaseAssetsUrl+"/textures/";e=e||EngineStore.LastCreatedScene;for(var _=0,b=i.systems;_<b.length;_++){var k=b[_];c.systems.push(o?GPUParticleSystem.Parse(k,e,d,!0,s):ParticleSystem.Parse(k,e,d,!0,s))}if(i.emitter){var j=i.emitter.options;switch(i.emitter.kind){case"Sphere":c.setEmitterAsSphere({diameter:j.diameter,segments:j.segments,color:Color3.FromArray(j.color)},i.emitter.renderingGroupId,e);break}}return c},a.BaseAssetsUrl="https://assets.babylonjs.com/particles",a}(),ProceduralTextureSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_PROCEDURALTEXTURE,this.scene=i,this.scene.proceduralTextures=new Array}return a.prototype.register=function(){this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)},a.prototype.rebuild=function(){},a.prototype.dispose=function(){},a.prototype._beforeClear=function(){if(this.scene.proceduralTexturesEnabled){Tools.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(var i=0;i<this.scene.proceduralTextures.length;i++){var e=this.scene.proceduralTextures[i];e._shouldRender()&&e.render()}Tools.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}},a}(),name$1g="proceduralVertexShader",shader$1g=`
  4377. attribute vec2 position;
  4378. varying vec2 vPosition;
  4379. varying vec2 vUV;
  4380. const vec2 madd=vec2(0.5,0.5);
  4381. void main(void) {
  4382. vPosition=position;
  4383. vUV=position*madd+madd;
  4384. gl_Position=vec4(position,0.0,1.0);
  4385. }`;ShaderStore.ShadersStore[name$1g]=shader$1g;var ProceduralTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){d===void 0&&(d=null),_===void 0&&(_=!0),b===void 0&&(b=!1),k===void 0&&(k=0);var j=a.call(this,null,c,!_)||this;j.isEnabled=!0,j.autoClear=!0,j.onGeneratedObservable=new Observable,j.onBeforeGenerationObservable=new Observable,j.nodeMaterialSource=null,j._textures={},j._currentRefreshId=-1,j._frameId=-1,j._refreshRate=1,j._vertexBuffers={},j._uniforms=new Array,j._samplers=new Array,j._floats={},j._ints={},j._floatsArrays={},j._colors3={},j._colors4={},j._vectors2={},j._vectors3={},j._matrices={},j._fallbackTextureUsed=!1,j._cachedDefines=null,j._contentUpdateId=-1,j._rtWrapper=null,c=j.getScene()||EngineStore.LastCreatedScene;var $=c._getComponent(SceneComponentConstants.NAME_PROCEDURALTEXTURE);$||($=new ProceduralTextureSceneComponent(c),c._addComponent($)),c.proceduralTextures.push(j),j._fullEngine=c.getEngine(),j.name=e,j.isRenderTarget=!0,j._size=o,j._textureType=k,j._generateMipMaps=_,j._drawWrapper=new DrawWrapper(j._fullEngine),j.setFragment(s),j._fallbackTexture=d,b?(j._rtWrapper=j._fullEngine.createRenderTargetCubeTexture(o,{generateMipMaps:_,generateDepthBuffer:!1,generateStencilBuffer:!1,type:k}),j.setFloat("face",0)):j._rtWrapper=j._fullEngine.createRenderTargetTexture(o,{generateMipMaps:_,generateDepthBuffer:!1,generateStencilBuffer:!1,type:k}),j._texture=j._rtWrapper.texture;var _e=[];return _e.push(1,1),_e.push(-1,1),_e.push(-1,-1),_e.push(1,-1),j._vertexBuffers[VertexBuffer.PositionKind]=new VertexBuffer(j._fullEngine,_e,VertexBuffer.PositionKind,!1,!1,2),j._createIndexBuffer(),j}return i.prototype.getEffect=function(){return this._drawWrapper.effect},i.prototype._setEffect=function(e){this._drawWrapper.effect=e},i.prototype.getContent=function(){var e=this;return this._contentData&&this._frameId===this._contentUpdateId?this._contentData:(this._contentData?this._contentData.then(function(o){e._contentData=e.readPixels(0,0,o),e._contentUpdateId=e._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId),this._contentData)},i.prototype._createIndexBuffer=function(){var e=this._fullEngine,o=[];o.push(0),o.push(1),o.push(2),o.push(0),o.push(2),o.push(3),this._indexBuffer=e.createIndexBuffer(o)},i.prototype._rebuild=function(){var e=this._vertexBuffers[VertexBuffer.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=RenderTargetTexture.REFRESHRATE_RENDER_ONCE)},i.prototype.reset=function(){var e;(e=this._drawWrapper.effect)===null||e===void 0||e.dispose()},i.prototype._getDefines=function(){return""},i.prototype.isReady=function(){var e=this,o=this._fullEngine,s;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;var c=this._getDefines();return this._drawWrapper.effect&&c===this._cachedDefines&&this._drawWrapper.effect.isReady()?!0:(this._fragment.fragmentElement!==void 0?s={vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:s={vertex:"procedural",fragment:this._fragment},this._cachedDefines!==c&&(this._cachedDefines=c,this._drawWrapper.effect=o.createEffect(s,[VertexBuffer.PositionKind],this._uniforms,this._samplers,c,void 0,void 0,function(){var d;(d=e._rtWrapper)===null||d===void 0||d.dispose(),e._rtWrapper=e._texture=null,e._fallbackTexture&&(e._texture=e._fallbackTexture._texture,e._texture&&e._texture.incrementReferences()),e._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady())},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!1,configurable:!0}),i.prototype._shouldRender=function(){return!this.isEnabled||!this.isReady()||!this._texture?(this._texture&&(this._texture.isReady=!1),!1):this._fallbackTextureUsed?!1:this._currentRefreshId===-1?(this._currentRefreshId=1,this._frameId++,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,o){var s;this._fallbackTextureUsed||((s=this._rtWrapper)===null||s===void 0||s.dispose(),this._rtWrapper=this._fullEngine.createRenderTargetTexture(e,{generateMipMaps:o,generateDepthBuffer:!1,generateStencilBuffer:!1,type:this._textureType}),this._texture=this._rtWrapper.texture,this._size=e,this._generateMipMaps=o)},i.prototype._checkUniform=function(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)},i.prototype.setTexture=function(e,o){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=o,this},i.prototype.setFloat=function(e,o){return this._checkUniform(e),this._floats[e]=o,this},i.prototype.setInt=function(e,o){return this._checkUniform(e),this._ints[e]=o,this},i.prototype.setFloats=function(e,o){return this._checkUniform(e),this._floatsArrays[e]=o,this},i.prototype.setColor3=function(e,o){return this._checkUniform(e),this._colors3[e]=o,this},i.prototype.setColor4=function(e,o){return this._checkUniform(e),this._colors4[e]=o,this},i.prototype.setVector2=function(e,o){return this._checkUniform(e),this._vectors2[e]=o,this},i.prototype.setVector3=function(e,o){return this._checkUniform(e),this._vectors3[e]=o,this},i.prototype.setMatrix=function(e,o){return this._checkUniform(e),this._matrices[e]=o,this},i.prototype.render=function(e){var o,s,c=this.getScene();if(!!c){var d=this._fullEngine;if(d.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),d.setState(!1),!this.nodeMaterialSource){for(var _ in this._textures)this._drawWrapper.effect.setTexture(_,this._textures[_]);for(_ in this._ints)this._drawWrapper.effect.setInt(_,this._ints[_]);for(_ in this._floats)this._drawWrapper.effect.setFloat(_,this._floats[_]);for(_ in this._floatsArrays)this._drawWrapper.effect.setArray(_,this._floatsArrays[_]);for(_ in this._colors3)this._drawWrapper.effect.setColor3(_,this._colors3[_]);for(_ in this._colors4){var b=this._colors4[_];this._drawWrapper.effect.setFloat4(_,b.r,b.g,b.b,b.a)}for(_ in this._vectors2)this._drawWrapper.effect.setVector2(_,this._vectors2[_]);for(_ in this._vectors3)this._drawWrapper.effect.setVector3(_,this._vectors3[_]);for(_ in this._matrices)this._drawWrapper.effect.setMatrix(_,this._matrices[_])}if(!(!this._texture||!this._rtWrapper)){if((o=d._debugPushGroup)===null||o===void 0||o.call(d,"procedural texture generation for "+this.name,1),this.isCube)for(var k=0;k<6;k++)d.bindFramebuffer(this._rtWrapper,k,void 0,void 0,!0),d.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",k),this.autoClear&&d.clear(c.clearColor,!0,!1,!1),d.drawElementsType(Material.TriangleFillMode,0,6);else d.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),d.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&d.clear(c.clearColor,!0,!1,!1),d.drawElementsType(Material.TriangleFillMode,0,6);d.unBindFramebuffer(this._rtWrapper,this.isCube),this.isCube&&d.generateMipMapsForCubemap(this._texture),(s=d._debugPopGroup)===null||s===void 0||s.call(d,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}}},i.prototype.clone=function(){var e=this.getSize(),o=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return o.hasAlpha=this.hasAlpha,o.level=this.level,o.coordinatesMode=this.coordinatesMode,o},i.prototype.dispose=function(){var e=this.getScene();if(!!e){var o=e.proceduralTextures.indexOf(this);o>=0&&e.proceduralTextures.splice(o,1);var s=this._vertexBuffers[VertexBuffer.PositionKind];s&&(s.dispose(),this._vertexBuffers[VertexBuffer.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),a.prototype.dispose.call(this)}},__decorate([serialize()],i.prototype,"isEnabled",void 0),__decorate([serialize()],i.prototype,"autoClear",void 0),__decorate([serialize()],i.prototype,"_generateMipMaps",void 0),__decorate([serialize()],i.prototype,"_size",void 0),__decorate([serialize()],i.prototype,"refreshRate",null),i}(Texture);RegisterClass("BABYLON.ProceduralTexture",ProceduralTexture);var name$1f="noisePixelShader",shader$1f=`
  4386. uniform float brightness;
  4387. uniform float persistence;
  4388. uniform float timeScale;
  4389. varying vec2 vUV;
  4390. vec2 hash22(vec2 p)
  4391. {
  4392. p=p*mat2(127.1,311.7,269.5,183.3);
  4393. p=-1.0+2.0*fract(sin(p)*43758.5453123);
  4394. return sin(p*6.283+timeScale);
  4395. }
  4396. float interpolationNoise(vec2 p)
  4397. {
  4398. vec2 pi=floor(p);
  4399. vec2 pf=p-pi;
  4400. vec2 w=pf*pf*(3.-2.*pf);
  4401. float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));
  4402. float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));
  4403. float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));
  4404. float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));
  4405. float xm1=mix(f00,f10,w.x);
  4406. float xm2=mix(f01,f11,w.x);
  4407. float ym=mix(xm1,xm2,w.y);
  4408. return ym;
  4409. }
  4410. float perlinNoise2D(float x,float y)
  4411. {
  4412. float sum=0.0;
  4413. float frequency=0.0;
  4414. float amplitude=0.0;
  4415. for(int i=0; i<OCTAVES; i++)
  4416. {
  4417. frequency=pow(2.0,float(i));
  4418. amplitude=pow(persistence,float(i));
  4419. sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;
  4420. }
  4421. return sum;
  4422. }
  4423. void main(void)
  4424. {
  4425. float x=abs(vUV.x);
  4426. float y=abs(vUV.y);
  4427. float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);
  4428. gl_FragColor=vec4(noise,noise,noise,1.0);
  4429. }
  4430. `;ShaderStore.ShadersStore[name$1f]=shader$1f;var NoiseProceduralTexture=function(a){__extends(i,a);function i(e,o,s,c,d){o===void 0&&(o=256),s===void 0&&(s=EngineStore.LastCreatedScene);var _=a.call(this,e,o,"noise",s,c,d)||this;return _.time=0,_.brightness=.2,_.octaves=3,_.persistence=.8,_.animationSpeedFactor=1,_.autoClear=!1,_._updateShaderUniforms(),_}return i.prototype._updateShaderUniforms=function(){var e=this.getScene();!e||(this.time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this.time))},i.prototype._getDefines=function(){return"#define OCTAVES "+(this.octaves|0)},i.prototype.render=function(e){this._updateShaderUniforms(),a.prototype.render.call(this,e)},i.prototype.serialize=function(){var e={};return e.customType="BABYLON.NoiseProceduralTexture",e.brightness=this.brightness,e.octaves=this.octaves,e.persistence=this.persistence,e.animationSpeedFactor=this.animationSpeedFactor,e.size=this.getSize().width,e.generateMipMaps=this._generateMipMaps,e.time=this.time,e},i.prototype.clone=function(){var e=this.getSize(),o=new i(this.name,e.width,this.getScene(),this._fallbackTexture?this._fallbackTexture:void 0,this._generateMipMaps);return o.hasAlpha=this.hasAlpha,o.level=this.level,o.coordinatesMode=this.coordinatesMode,o.brightness=this.brightness,o.octaves=this.octaves,o.persistence=this.persistence,o.animationSpeedFactor=this.animationSpeedFactor,o.time=this.time,o},i.Parse=function(e,o){var s,c=new i(e.name,e.size,o,void 0,e.generateMipMaps);return c.brightness=e.brightness,c.octaves=e.octaves,c.persistence=e.persistence,c.animationSpeedFactor=e.animationSpeedFactor,c.time=(s=e.time)!==null&&s!==void 0?s:0,c},i}(ProceduralTexture);RegisterClass("BABYLON.NoiseProceduralTexture",NoiseProceduralTexture);var NodeMaterialBlockTargets;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Neutral=4]="Neutral",a[a.VertexAndFragment=3]="VertexAndFragment"})(NodeMaterialBlockTargets||(NodeMaterialBlockTargets={}));var NodeMaterialBlockConnectionPointTypes;(function(a){a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=4]="Vector2",a[a.Vector3=8]="Vector3",a[a.Vector4=16]="Vector4",a[a.Color3=32]="Color3",a[a.Color4=64]="Color4",a[a.Matrix=128]="Matrix",a[a.Object=256]="Object",a[a.AutoDetect=1024]="AutoDetect",a[a.BasedOnInput=2048]="BasedOnInput"})(NodeMaterialBlockConnectionPointTypes||(NodeMaterialBlockConnectionPointTypes={}));var NodeMaterialBlockConnectionPointMode;(function(a){a[a.Uniform=0]="Uniform",a[a.Attribute=1]="Attribute",a[a.Varying=2]="Varying",a[a.Undefined=3]="Undefined"})(NodeMaterialBlockConnectionPointMode||(NodeMaterialBlockConnectionPointMode={}));var NodeMaterialSystemValues;(function(a){a[a.World=1]="World",a[a.View=2]="View",a[a.Projection=3]="Projection",a[a.ViewProjection=4]="ViewProjection",a[a.WorldView=5]="WorldView",a[a.WorldViewProjection=6]="WorldViewProjection",a[a.CameraPosition=7]="CameraPosition",a[a.FogColor=8]="FogColor",a[a.DeltaTime=9]="DeltaTime",a[a.CameraParameters=10]="CameraParameters"})(NodeMaterialSystemValues||(NodeMaterialSystemValues={}));var NodeMaterialModes;(function(a){a[a.Material=0]="Material",a[a.PostProcess=1]="PostProcess",a[a.Particle=2]="Particle",a[a.ProceduralTexture=3]="ProceduralTexture"})(NodeMaterialModes||(NodeMaterialModes={}));var NodeMaterialConnectionPointCompatibilityStates;(function(a){a[a.Compatible=0]="Compatible",a[a.TypeIncompatible=1]="TypeIncompatible",a[a.TargetIncompatible=2]="TargetIncompatible",a[a.HierarchyIssue=3]="HierarchyIssue"})(NodeMaterialConnectionPointCompatibilityStates||(NodeMaterialConnectionPointCompatibilityStates={}));var NodeMaterialConnectionPointDirection;(function(a){a[a.Input=0]="Input",a[a.Output=1]="Output"})(NodeMaterialConnectionPointDirection||(NodeMaterialConnectionPointDirection={}));var NodeMaterialConnectionPoint=function(){function a(i,e,o){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=NodeMaterialBlockConnectionPointTypes.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=new Array,this.excludedConnectionPointTypes=new Array,this.onConnectionObservable=new Observable,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=NodeMaterialBlockTargets.VertexAndFragment,this._ownerBlock=e,this.name=i,this._direction=o}return a.AreEquivalentTypes=function(i,e){switch(i){case NodeMaterialBlockConnectionPointTypes.Vector3:{if(e===NodeMaterialBlockConnectionPointTypes.Color3)return!0;break}case NodeMaterialBlockConnectionPointTypes.Vector4:{if(e===NodeMaterialBlockConnectionPointTypes.Color4)return!0;break}case NodeMaterialBlockConnectionPointTypes.Color3:{if(e===NodeMaterialBlockConnectionPointTypes.Vector3)return!0;break}case NodeMaterialBlockConnectionPointTypes.Color4:{if(e===NodeMaterialBlockConnectionPointTypes.Vector4)return!0;break}}return!1},Object.defineProperty(a.prototype,"direction",{get:function(){return this._direction},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"associatedVariableName",{get:function(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:(!this._enforceAssociatedVariableName||!this._associatedVariableName)&&this._connectedPoint?this._connectedPoint.associatedVariableName:this._associatedVariableName},set:function(i){this._associatedVariableName=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"innerType",{get:function(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"type",{get:function(){if(this._type===NodeMaterialBlockConnectionPointTypes.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===NodeMaterialBlockConnectionPointTypes.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type},set:function(i){this._type=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"target",{get:function(){return!this._prioritizeVertex||!this._ownerBlock?this._target:this._target!==NodeMaterialBlockTargets.VertexAndFragment?this._target:this._ownerBlock.target===NodeMaterialBlockTargets.Fragment?NodeMaterialBlockTargets.Fragment:NodeMaterialBlockTargets.Vertex},set:function(i){this._target=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isConnected",{get:function(){return this.connectedPoint!==null||this.hasEndpoints},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isConnectedToInputBlock",{get:function(){return this.connectedPoint!==null&&this.connectedPoint.ownerBlock.isInput},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"connectInputBlock",{get:function(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"connectedPoint",{get:function(){return this._connectedPoint},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"ownerBlock",{get:function(){return this._ownerBlock},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"sourceBlock",{get:function(){return this._connectedPoint?this._connectedPoint.ownerBlock:null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"connectedBlocks",{get:function(){return this._endpoints.length===0?[]:this._endpoints.map(function(i){return i.ownerBlock})},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"endpoints",{get:function(){return this._endpoints},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasEndpoints",{get:function(){return this._endpoints&&this._endpoints.length>0},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isDirectlyConnectedToVertexOutput",{get:function(){if(!this.hasEndpoints)return!1;for(var i=0,e=this._endpoints;i<e.length;i++){var o=e[i];if(o.ownerBlock.target===NodeMaterialBlockTargets.Vertex||(o.ownerBlock.target===NodeMaterialBlockTargets.Neutral||o.ownerBlock.target===NodeMaterialBlockTargets.VertexAndFragment)&&o.ownerBlock.outputs.some(function(s){return s.isDirectlyConnectedToVertexOutput}))return!0}return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isConnectedInVertexShader",{get:function(){if(this.target===NodeMaterialBlockTargets.Vertex)return!0;if(!this.hasEndpoints)return!1;for(var i=0,e=this._endpoints;i<e.length;i++){var o=e[i];if(o.ownerBlock.target===NodeMaterialBlockTargets.Vertex||o.target===NodeMaterialBlockTargets.Vertex||(o.ownerBlock.target===NodeMaterialBlockTargets.Neutral||o.ownerBlock.target===NodeMaterialBlockTargets.VertexAndFragment)&&o.ownerBlock.outputs.some(function(s){return s.isConnectedInVertexShader}))return!0}return!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isConnectedInFragmentShader",{get:function(){if(this.target===NodeMaterialBlockTargets.Fragment)return!0;if(!this.hasEndpoints)return!1;for(var i=0,e=this._endpoints;i<e.length;i++){var o=e[i];if(o.ownerBlock.target===NodeMaterialBlockTargets.Fragment||(o.ownerBlock.target===NodeMaterialBlockTargets.Neutral||o.ownerBlock.target===NodeMaterialBlockTargets.VertexAndFragment)&&o.ownerBlock.outputs.some(function(s){return s.isConnectedInFragmentShader}))return!0}return!1},enumerable:!1,configurable:!0}),a.prototype.createCustomInputBlock=function(){return null},a.prototype.getClassName=function(){return"NodeMaterialConnectionPoint"},a.prototype.canConnectTo=function(i){return this.checkCompatibilityState(i)===NodeMaterialConnectionPointCompatibilityStates.Compatible},a.prototype.checkCompatibilityState=function(i){var e=this._ownerBlock,o=i.ownerBlock;if(e.target===NodeMaterialBlockTargets.Fragment){if(o.target===NodeMaterialBlockTargets.Vertex)return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;for(var s=0,c=o.outputs;s<c.length;s++){var d=c[s];if(d.ownerBlock.target!=NodeMaterialBlockTargets.Neutral&&d.isConnectedInVertexShader)return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible}}if(this.type!==i.type&&i.innerType!==NodeMaterialBlockConnectionPointTypes.AutoDetect)return a.AreEquivalentTypes(this.type,i.type)||i.acceptedConnectionPointTypes&&i.acceptedConnectionPointTypes.indexOf(this.type)!==-1||i._acceptedConnectionPointType&&a.AreEquivalentTypes(i._acceptedConnectionPointType.type,this.type)?NodeMaterialConnectionPointCompatibilityStates.Compatible:NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;if(i.excludedConnectionPointTypes&&i.excludedConnectionPointTypes.indexOf(this.type)!==-1)return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;var _=o,b=e;return this.direction===NodeMaterialConnectionPointDirection.Input&&(_=e,b=o),_.isAnAncestorOf(b)?NodeMaterialConnectionPointCompatibilityStates.HierarchyIssue:NodeMaterialConnectionPointCompatibilityStates.Compatible},a.prototype.connectTo=function(i,e){if(e===void 0&&(e=!1),!e&&!this.canConnectTo(i))throw"Cannot connect these two connectors.";return this._endpoints.push(i),i._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(i),i.onConnectionObservable.notifyObservers(this),this},a.prototype.disconnectFrom=function(i){var e=this._endpoints.indexOf(i);return e===-1?this:(this._endpoints.splice(e,1),i._connectedPoint=null,this._enforceAssociatedVariableName=!1,i._enforceAssociatedVariableName=!1,this)},a.prototype.serialize=function(i){i===void 0&&(i=!0);var e={};return e.name=this.name,e.displayName=this.displayName,i&&this.connectedPoint&&(e.inputName=this.name,e.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,e.targetConnectionName=this.connectedPoint.name,e.isExposedOnFrame=!0,e.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(e.isExposedOnFrame=!0,e.exposedPortPosition=this.exposedPortPosition),e},a.prototype.dispose=function(){this.onConnectionObservable.clear()},a}(),NodeMaterialBlock=function(){function a(i,e,o,s){e===void 0&&(e=NodeMaterialBlockTargets.Vertex),o===void 0&&(o=!1),s===void 0&&(s=!1),this._isFinalMerger=!1,this._isInput=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=e,this._originalTargetIsNeutral=e===NodeMaterialBlockTargets.Neutral,this._isFinalMerger=o,this._isInput=s,this._name=i,this.uniqueId=UniqueIdGenerator.UniqueId}return Object.defineProperty(a.prototype,"name",{get:function(){return this._name},set:function(i){!this.validateBlockName(i)||(this._name=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isUnique",{get:function(){return this._isUnique},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isFinalMerger",{get:function(){return this._isFinalMerger},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isInput",{get:function(){return this._isInput},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"buildId",{get:function(){return this._buildId},set:function(i){this._buildId=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"target",{get:function(){return this._target},set:function(i){(this._target&i)===0&&(this._target=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"inputs",{get:function(){return this._inputs},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"outputs",{get:function(){return this._outputs},enumerable:!1,configurable:!0}),a.prototype.getInputByName=function(i){var e=this._inputs.filter(function(o){return o.name===i});return e.length?e[0]:null},a.prototype.getOutputByName=function(i){var e=this._outputs.filter(function(o){return o.name===i});return e.length?e[0]:null},a.prototype.initialize=function(i){},a.prototype.bind=function(i,e,o,s){},a.prototype._declareOutput=function(i,e){return e._getGLType(i.type)+" "+i.associatedVariableName},a.prototype._writeVariable=function(i){var e=i.connectedPoint;return e?""+i.associatedVariableName:"0."},a.prototype._writeFloat=function(i){var e=i.toString();return e.indexOf(".")===-1&&(e+=".0"),""+e},a.prototype.getClassName=function(){return"NodeMaterialBlock"},a.prototype.registerInput=function(i,e,o,s,c){return o===void 0&&(o=!1),c=c!=null?c:new NodeMaterialConnectionPoint(i,this,NodeMaterialConnectionPointDirection.Input),c.type=e,c.isOptional=o,s&&(c.target=s),this._inputs.push(c),this},a.prototype.registerOutput=function(i,e,o,s){return s=s!=null?s:new NodeMaterialConnectionPoint(i,this,NodeMaterialConnectionPointDirection.Output),s.type=e,o&&(s.target=o),this._outputs.push(s),this},a.prototype.getFirstAvailableInput=function(i){i===void 0&&(i=null);for(var e=0,o=this._inputs;e<o.length;e++){var s=o[e];if(!s.connectedPoint&&(!i||i.type===s.type||s.type===NodeMaterialBlockConnectionPointTypes.AutoDetect))return s}return null},a.prototype.getFirstAvailableOutput=function(i){i===void 0&&(i=null);for(var e=0,o=this._outputs;e<o.length;e++){var s=o[e];if(!i||!i.target||i.target===NodeMaterialBlockTargets.Neutral||(i.target&s.target)!==0)return s}return null},a.prototype.getSiblingOutput=function(i){var e=this._outputs.indexOf(i);return e===-1||e>=this._outputs.length?null:this._outputs[e+1]},a.prototype.isAnAncestorOf=function(i){for(var e=0,o=this._outputs;e<o.length;e++){var s=o[e];if(!!s.hasEndpoints)for(var c=0,d=s.endpoints;c<d.length;c++){var _=d[c];if(_.ownerBlock===i||_.ownerBlock.isAnAncestorOf(i))return!0}}return!1},a.prototype.connectTo=function(i,e){if(this._outputs.length!==0){for(var o=e&&e.output?this.getOutputByName(e.output):this.getFirstAvailableOutput(i),s=!0;s;){var c=e&&e.input?i.getInputByName(e.input):i.getFirstAvailableInput(o);if(o&&c&&o.canConnectTo(c))o.connectTo(c),s=!1;else if(o)o=this.getSiblingOutput(o);else throw"Unable to find a compatible match"}return this}},a.prototype._buildBlock=function(i){},a.prototype.updateUniformsAndSamples=function(i,e,o,s){},a.prototype.provideFallbacks=function(i,e){},a.prototype.initializeDefines=function(i,e,o,s){},a.prototype.prepareDefines=function(i,e,o,s,c){},a.prototype.autoConfigure=function(i){},a.prototype.replaceRepeatableContent=function(i,e,o,s){},Object.defineProperty(a.prototype,"willBeGeneratedIntoVertexShaderFromFragmentShader",{get:function(){return this.isInput||this.isFinalMerger||this._outputs.some(function(i){return i.isDirectlyConnectedToVertexOutput})?!1:!!(this.target===NodeMaterialBlockTargets.Vertex||(this.target===NodeMaterialBlockTargets.VertexAndFragment||this.target===NodeMaterialBlockTargets.Neutral)&&this._outputs.some(function(i){return i.isConnectedInVertexShader}))},enumerable:!1,configurable:!0}),a.prototype.isReady=function(i,e,o,s){return!0},a.prototype._linkConnectionTypes=function(i,e,o){o===void 0&&(o=!1),o?this._inputs[e]._acceptedConnectionPointType=this._inputs[i]:this._inputs[i]._linkedConnectionSource=this._inputs[e],this._inputs[e]._linkedConnectionSource=this._inputs[i]},a.prototype._processBuild=function(i,e,o,s){i.build(e,s);var c=e._vertexState!=null,d=i._buildTarget===NodeMaterialBlockTargets.Vertex&&i.target!==NodeMaterialBlockTargets.VertexAndFragment;if(c&&((i.target&i._buildTarget)===0||(i.target&o.target)===0||this.target!==NodeMaterialBlockTargets.VertexAndFragment&&d)&&(!i.isInput&&e.target!==i._buildTarget||i.isInput&&i.isAttribute&&!i._noContextSwitch)){var _=o.connectedPoint;e._vertexState._emitVaryingFromString("v_"+_.associatedVariableName,e._getGLType(_.type))&&(e._vertexState.compilationString+="v_"+_.associatedVariableName+" = "+_.associatedVariableName+`;\r
  4431. `),o.associatedVariableName="v_"+_.associatedVariableName,o._enforceAssociatedVariableName=!0}},a.prototype.validateBlockName=function(i){for(var e=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"],o=0,s=e;o<s.length;o++){var c=s[o];if(i===c)return!1}return!0},a.prototype.build=function(i,e){if(this._buildId===i.sharedData.buildId)return!0;if(!this.isInput)for(var o=0,s=this._outputs;o<s.length;o++){var c=s[o];c.associatedVariableName||(c.associatedVariableName=i._getFreeVariableName(c.name))}for(var d=0,_=this._inputs;d<_.length;d++){var b=_[d];if(!b.connectedPoint){b.isOptional||i.sharedData.checks.notConnectedNonOptionalInputs.push(b);continue}if(!(this.target!==NodeMaterialBlockTargets.Neutral&&((b.target&this.target)===0||(b.target&i.target)===0))){var k=b.connectedPoint.ownerBlock;k&&k!==this&&this._processBuild(k,i,b,e)}}if(this._buildId===i.sharedData.buildId)return!0;if(i.sharedData.verbose&&console.log((i.target===NodeMaterialBlockTargets.Vertex?"Vertex shader":"Fragment shader")+": Building "+this.name+" ["+this.getClassName()+"]"),this.isFinalMerger)switch(i.target){case NodeMaterialBlockTargets.Vertex:i.sharedData.checks.emitVertex=!0;break;case NodeMaterialBlockTargets.Fragment:i.sharedData.checks.emitFragment=!0;break}!this.isInput&&i.sharedData.emitComments&&(i.compilationString+=`\r
  4432. //`+this.name+`\r
  4433. `),this._buildBlock(i),this._buildId=i.sharedData.buildId,this._buildTarget=i.target;for(var j=0,$=this._outputs;j<$.length;j++){var c=$[j];if((c.target&i.target)!==0)for(var _e=0,et=c.endpoints;_e<et.length;_e++){var tt=et[_e],k=tt.ownerBlock;k&&(k.target&i.target)!==0&&e.indexOf(k)!==-1&&this._processBuild(k,i,tt,e)}}return!1},a.prototype._inputRename=function(i){return i},a.prototype._outputRename=function(i){return i},a.prototype._dumpPropertiesCode=function(){var i=this._codeVariableName;return i+".visibleInInspector = "+this.visibleInInspector+`;\r
  4434. `+i+".visibleOnFrame = "+this.visibleOnFrame+`;\r
  4435. `+i+".target = "+this.target+`;\r
  4436. `},a.prototype._dumpCode=function(i,e){e.push(this);var o,s=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=s||this.getClassName()+"_"+this.uniqueId,i.indexOf(this._codeVariableName)!==-1){var c=0;do c++,this._codeVariableName=s+c;while(i.indexOf(this._codeVariableName)!==-1)}i.push(this._codeVariableName),o=`\r
  4437. // `+this.getClassName()+`\r
  4438. `,this.comments&&(o+="// "+this.comments+`\r
  4439. `),o+="var "+this._codeVariableName+" = new BABYLON."+this.getClassName()+'("'+this.name+`");\r
  4440. `,o+=this._dumpPropertiesCode();for(var d=0,_=this.inputs;d<_.length;d++){var b=_[d];if(!!b.isConnected){var k=b.connectedPoint,j=k.ownerBlock;e.indexOf(j)===-1&&(o+=j._dumpCode(i,e))}}for(var $=0,_e=this.outputs;$<_e.length;$++){var et=_e[$];if(!!et.hasEndpoints)for(var tt=0,rt=et.endpoints;tt<rt.length;tt++){var it=rt[tt],j=it.ownerBlock;j&&e.indexOf(j)===-1&&(o+=j._dumpCode(i,e))}}return o},a.prototype._dumpCodeForOutputConnections=function(i){var e="";if(i.indexOf(this)!==-1)return e;i.push(this);for(var o=0,s=this.inputs;o<s.length;o++){var c=s[o];if(!!c.isConnected){var d=c.connectedPoint,_=d.ownerBlock;e+=_._dumpCodeForOutputConnections(i),e+=_._codeVariableName+"."+_._outputRename(d.name)+".connectTo("+this._codeVariableName+"."+this._inputRename(c.name)+`);\r
  4441. `}}return e},a.prototype.clone=function(i,e){e===void 0&&(e="");var o=this.serialize(),s=GetClass(o.customType);if(s){var c=new s;return c._deserialize(o,i,e),c}return null},a.prototype.serialize=function(){var i={};i.customType="BABYLON."+this.getClassName(),i.id=this.uniqueId,i.name=this.name,i.comments=this.comments,i.visibleInInspector=this.visibleInInspector,i.visibleOnFrame=this.visibleOnFrame,i.target=this.target,i.inputs=[],i.outputs=[];for(var e=0,o=this.inputs;e<o.length;e++){var s=o[e];i.inputs.push(s.serialize())}for(var c=0,d=this.outputs;c<d.length;c++){var _=d[c];i.outputs.push(_.serialize(!1))}return i},a.prototype._deserialize=function(i,e,o){var s;this.name=i.name,this.comments=i.comments,this.visibleInInspector=!!i.visibleInInspector,this.visibleOnFrame=!!i.visibleOnFrame,this._target=(s=i.target)!==null&&s!==void 0?s:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(i)},a.prototype._deserializePortDisplayNamesAndExposedOnFrame=function(i){var e=this,o=i.inputs,s=i.outputs;o&&o.forEach(function(c,d){c.displayName&&(e.inputs[d].displayName=c.displayName),c.isExposedOnFrame&&(e.inputs[d].isExposedOnFrame=c.isExposedOnFrame,e.inputs[d].exposedPortPosition=c.exposedPortPosition)}),s&&s.forEach(function(c,d){c.displayName&&(e.outputs[d].displayName=c.displayName),c.isExposedOnFrame&&(e.outputs[d].isExposedOnFrame=c.isExposedOnFrame,e.outputs[d].exposedPortPosition=c.exposedPortPosition)})},a.prototype.dispose=function(){for(var i=0,e=this.inputs;i<e.length;i++){var o=e[i];o.dispose()}for(var s=0,c=this.outputs;s<c.length;s++){var d=c[s];d.dispose()}},a}(),NodeMaterialBuildState=function(){function a(){this.supportUniformBuffers=!1,this.attributes=new Array,this.uniforms=new Array,this.constants=new Array,this.samplers=new Array,this.functions={},this.extensions={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}return a.prototype.finalize=function(i){var e=i.sharedData.emitComments,o=this.target===NodeMaterialBlockTargets.Fragment;this.compilationString=`\r
  4442. `+(e?`//Entry point\r
  4443. `:"")+`void main(void) {\r
  4444. `+this.compilationString,this._constantDeclaration&&(this.compilationString=`\r
  4445. `+(e?`//Constants\r
  4446. `:"")+this._constantDeclaration+`\r
  4447. `+this.compilationString);var s="";for(var c in this.functions)s+=this.functions[c]+`\r
  4448. `;this.compilationString=`\r
  4449. `+s+`\r
  4450. `+this.compilationString,!o&&this._varyingTransfer&&(this.compilationString=this.compilationString+`\r
  4451. `+this._varyingTransfer),this._injectAtEnd&&(this.compilationString=this.compilationString+`\r
  4452. `+this._injectAtEnd),this.compilationString=this.compilationString+`\r
  4453. }`,this.sharedData.varyingDeclaration&&(this.compilationString=`\r
  4454. `+(e?`//Varyings\r
  4455. `:"")+this.sharedData.varyingDeclaration+`\r
  4456. `+this.compilationString),this._samplerDeclaration&&(this.compilationString=`\r
  4457. `+(e?`//Samplers\r
  4458. `:"")+this._samplerDeclaration+`\r
  4459. `+this.compilationString),this._uniformDeclaration&&(this.compilationString=`\r
  4460. `+(e?`//Uniforms\r
  4461. `:"")+this._uniformDeclaration+`\r
  4462. `+this.compilationString),this._attributeDeclaration&&!o&&(this.compilationString=`\r
  4463. `+(e?`//Attributes\r
  4464. `:"")+this._attributeDeclaration+`\r
  4465. `+this.compilationString),this.compilationString=`precision highp float;\r
  4466. `+this.compilationString;for(var d in this.extensions){var _=this.extensions[d];this.compilationString=`\r
  4467. `+_+`\r
  4468. `+this.compilationString}this._builtCompilationString=this.compilationString},Object.defineProperty(a.prototype,"_repeatableContentAnchor",{get:function(){return"###___ANCHOR"+this._repeatableContentAnchorIndex+++"___###"},enumerable:!1,configurable:!0}),a.prototype._getFreeVariableName=function(i){return i=i.replace(/[^a-zA-Z_]+/g,""),this.sharedData.variableNames[i]===void 0?(this.sharedData.variableNames[i]=0,i==="output"||i==="texture"?i+this.sharedData.variableNames[i]:i):(this.sharedData.variableNames[i]++,i+this.sharedData.variableNames[i])},a.prototype._getFreeDefineName=function(i){return this.sharedData.defineNames[i]===void 0?this.sharedData.defineNames[i]=0:this.sharedData.defineNames[i]++,i+this.sharedData.defineNames[i]},a.prototype._excludeVariableName=function(i){this.sharedData.variableNames[i]=0},a.prototype._emit2DSampler=function(i){this.samplers.indexOf(i)<0&&(this._samplerDeclaration+="uniform sampler2D "+i+`;\r
  4469. `,this.samplers.push(i))},a.prototype._getGLType=function(i){switch(i){case NodeMaterialBlockConnectionPointTypes.Float:return"float";case NodeMaterialBlockConnectionPointTypes.Int:return"int";case NodeMaterialBlockConnectionPointTypes.Vector2:return"vec2";case NodeMaterialBlockConnectionPointTypes.Color3:case NodeMaterialBlockConnectionPointTypes.Vector3:return"vec3";case NodeMaterialBlockConnectionPointTypes.Color4:case NodeMaterialBlockConnectionPointTypes.Vector4:return"vec4";case NodeMaterialBlockConnectionPointTypes.Matrix:return"mat4"}return""},a.prototype._emitExtension=function(i,e,o){o===void 0&&(o=""),!this.extensions[i]&&(o&&(e="#if "+o+`\r
  4470. `+e+`\r
  4471. #endif`),this.extensions[i]=e)},a.prototype._emitFunction=function(i,e,o){this.functions[i]||(this.sharedData.emitComments&&(e=o+`\r
  4472. `+e),this.functions[i]=e)},a.prototype._emitCodeFromInclude=function(i,e,o){if(o&&o.repeatKey)return"#include<"+i+">[0.."+o.repeatKey+`]\r
  4473. `;var s=Effect$1.IncludesShadersStore[i]+`\r
  4474. `;if(this.sharedData.emitComments&&(s=e+`\r
  4475. `+s),!o)return s;if(o.replaceStrings)for(var c=0;c<o.replaceStrings.length;c++){var d=o.replaceStrings[c];s=s.replace(d.search,d.replace)}return s},a.prototype._emitFunctionFromInclude=function(i,e,o,s){s===void 0&&(s="");var c=i+s;if(!this.functions[c]){if(!o||!o.removeAttributes&&!o.removeUniforms&&!o.removeVaryings&&!o.removeIfDef&&!o.replaceStrings){o&&o.repeatKey?this.functions[c]="#include<"+i+">[0.."+o.repeatKey+`]\r
  4476. `:this.functions[c]="#include<"+i+`>\r
  4477. `,this.sharedData.emitComments&&(this.functions[c]=e+`\r
  4478. `+this.functions[c]);return}if(this.functions[c]=Effect$1.IncludesShadersStore[i],this.sharedData.emitComments&&(this.functions[c]=e+`\r
  4479. `+this.functions[c]),o.removeIfDef&&(this.functions[c]=this.functions[c].replace(/^\s*?#ifdef.+$/gm,""),this.functions[c]=this.functions[c].replace(/^\s*?#endif.*$/gm,""),this.functions[c]=this.functions[c].replace(/^\s*?#else.*$/gm,""),this.functions[c]=this.functions[c].replace(/^\s*?#elif.*$/gm,"")),o.removeAttributes&&(this.functions[c]=this.functions[c].replace(/^\s*?attribute.+$/gm,"")),o.removeUniforms&&(this.functions[c]=this.functions[c].replace(/^\s*?uniform.+$/gm,"")),o.removeVaryings&&(this.functions[c]=this.functions[c].replace(/^\s*?varying.+$/gm,"")),o.replaceStrings)for(var d=0;d<o.replaceStrings.length;d++){var _=o.replaceStrings[d];this.functions[c]=this.functions[c].replace(_.search,_.replace)}}},a.prototype._registerTempVariable=function(i){return this.sharedData.temps.indexOf(i)!==-1?!1:(this.sharedData.temps.push(i),!0)},a.prototype._emitVaryingFromString=function(i,e,o,s){return o===void 0&&(o=""),s===void 0&&(s=!1),this.sharedData.varyings.indexOf(i)!==-1?!1:(this.sharedData.varyings.push(i),o&&(StartsWith(o,"defined(")?this.sharedData.varyingDeclaration+="#if "+o+`\r
  4480. `:this.sharedData.varyingDeclaration+=(s?"#ifndef":"#ifdef")+" "+o+`\r
  4481. `),this.sharedData.varyingDeclaration+="varying "+e+" "+i+`;\r
  4482. `,o&&(this.sharedData.varyingDeclaration+=`#endif\r
  4483. `),!0)},a.prototype._emitUniformFromString=function(i,e,o,s){o===void 0&&(o=""),s===void 0&&(s=!1),this.uniforms.indexOf(i)===-1&&(this.uniforms.push(i),o&&(StartsWith(o,"defined(")?this._uniformDeclaration+="#if "+o+`\r
  4484. `:this._uniformDeclaration+=(s?"#ifndef":"#ifdef")+" "+o+`\r
  4485. `),this._uniformDeclaration+="uniform "+e+" "+i+`;\r
  4486. `,o&&(this._uniformDeclaration+=`#endif\r
  4487. `))},a.prototype._emitFloat=function(i){return i.toString()===i.toFixed(0)?i+".0":i.toString()},a}(),NodeMaterialBuildStateSharedData=function(){function a(){this.temps=new Array,this.varyings=new Array,this.varyingDeclaration="",this.inputBlocks=new Array,this.textureBlocks=new Array,this.bindableBlocks=new Array,this.forcedBindableBlocks=new Array,this.blocksWithFallbacks=new Array,this.blocksWithDefines=new Array,this.repeatableContentBlocks=new Array,this.dynamicUniformBlocks=new Array,this.blockingBlocks=new Array,this.animatedInputs=new Array,this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}return a.prototype.emitErrors=function(){var i="";!this.checks.emitVertex&&!this.allowEmptyVertexProgram&&(i+=`NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\r
  4488. `),this.checks.emitFragment||(i+=`NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\r
  4489. `);for(var e=0,o=this.checks.notConnectedNonOptionalInputs;e<o.length;e++){var s=o[e];i+="input "+s.name+" from block "+s.ownerBlock.name+"["+s.ownerBlock.getClassName()+`] is not connected and is not optional.\r
  4490. `}if(i)throw`Build of NodeMaterial failed:\r
  4491. `+i},a}(),TransformBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.complementW=1,o.complementZ=0,o.target=NodeMaterialBlockTargets.Vertex,o.registerInput("vector",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("transform",NodeMaterialBlockConnectionPointTypes.Matrix),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerOutput("xyz",NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].onConnectionObservable.add(function(s){if(s.ownerBlock.isInput){var c=s.ownerBlock;(c.name==="normal"||c.name==="tangent")&&(o.complementW=0)}}),o}return i.prototype.getClassName=function(){return"TransformBlock"},Object.defineProperty(i.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyz",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"transform",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.vector,s=this.transform;if(o.connectedPoint){if(this.complementW===0){var c="//"+this.name;e._emitFunctionFromInclude("helperFunctions",c),e.sharedData.blocksWithDefines.push(this);var d=e._getFreeVariableName(s.associatedVariableName+"_NUS");switch(e.compilationString+="mat3 "+d+" = mat3("+s.associatedVariableName+`);\r
  4492. `,e.compilationString+=`#ifdef NONUNIFORMSCALING\r
  4493. `,e.compilationString+=d+" = transposeMat3(inverseMat3("+d+`));\r
  4494. `,e.compilationString+=`#endif\r
  4495. `,o.connectedPoint.type){case NodeMaterialBlockConnectionPointTypes.Vector2:e.compilationString+=this._declareOutput(this.output,e)+(" = vec4("+d+" * vec3("+o.associatedVariableName+", "+this._writeFloat(this.complementZ)+"), "+this._writeFloat(this.complementW)+`);\r
  4496. `);break;case NodeMaterialBlockConnectionPointTypes.Vector3:case NodeMaterialBlockConnectionPointTypes.Color3:e.compilationString+=this._declareOutput(this.output,e)+(" = vec4("+d+" * "+o.associatedVariableName+", "+this._writeFloat(this.complementW)+`);\r
  4497. `);break;default:e.compilationString+=this._declareOutput(this.output,e)+(" = vec4("+d+" * "+o.associatedVariableName+".xyz, "+this._writeFloat(this.complementW)+`);\r
  4498. `);break}}else{var d=s.associatedVariableName;switch(o.connectedPoint.type){case NodeMaterialBlockConnectionPointTypes.Vector2:e.compilationString+=this._declareOutput(this.output,e)+(" = "+d+" * vec4("+o.associatedVariableName+", "+this._writeFloat(this.complementZ)+", "+this._writeFloat(this.complementW)+`);\r
  4499. `);break;case NodeMaterialBlockConnectionPointTypes.Vector3:case NodeMaterialBlockConnectionPointTypes.Color3:e.compilationString+=this._declareOutput(this.output,e)+(" = "+d+" * vec4("+o.associatedVariableName+", "+this._writeFloat(this.complementW)+`);\r
  4500. `);break;default:e.compilationString+=this._declareOutput(this.output,e)+(" = "+d+" * "+o.associatedVariableName+`;\r
  4501. `);break}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+(" = "+this.output.associatedVariableName+`.xyz;\r
  4502. `))}return this},i.prototype.prepareDefines=function(e,o,s,c,d){e.nonUniformScaling&&s.setValue("NONUNIFORMSCALING",!0)},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.complementZ=this.complementZ,e.complementW=this.complementW,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.complementZ=e.complementZ!==void 0?e.complementZ:0,this.complementW=e.complementW!==void 0?e.complementW:1},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".complementZ = "+this.complementZ+`;\r
  4503. `);return e+=this._codeVariableName+".complementW = "+this.complementW+`;\r
  4504. `,e},i}(NodeMaterialBlock);RegisterClass("BABYLON.TransformBlock",TransformBlock);var VertexOutputBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Vertex,!0)||this;return o.registerInput("vector",NodeMaterialBlockConnectionPointTypes.Vector4),o}return i.prototype.getClassName=function(){return"VertexOutputBlock"},Object.defineProperty(i.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),i.prototype._isLogarithmicDepthEnabled=function(e){for(var o=0,s=e;o<s.length;o++){var c=s[o];if(c.useLogarithmicDepth)return!0}return!1},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.vector;return e.compilationString+="gl_Position = "+o.associatedVariableName+`;\r
  4505. `,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w;\r
  4506. `,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r
  4507. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.VertexOutputBlock",VertexOutputBlock);var PropertyTypeForEdition;(function(a){a[a.Boolean=0]="Boolean",a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=3]="Vector2",a[a.List=4]="List"})(PropertyTypeForEdition||(PropertyTypeForEdition={}));function editableInPropertyPage(a,i,e,o){return i===void 0&&(i=PropertyTypeForEdition.Boolean),e===void 0&&(e="PROPERTIES"),function(s,c){var d=s._propStore;d||(d=[],s._propStore=d),d.push({propertyName:c,displayName:a,type:i,groupName:e,options:o!=null?o:{}})}}var FragmentOutputBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment,!0)||this;return o.convertToGammaSpace=!1,o.convertToLinearSpace=!1,o.useLogarithmicDepth=!1,o.registerInput("rgba",NodeMaterialBlockConnectionPointTypes.Color4,!0),o.registerInput("rgb",NodeMaterialBlockConnectionPointTypes.Color3,!0),o.registerInput("a",NodeMaterialBlockConnectionPointTypes.Float,!0),o.rgb.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"FragmentOutputBlock"},i.prototype.initialize=function(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")},Object.defineProperty(i.prototype,"rgba",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgb",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"a",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),i.prototype.prepareDefines=function(e,o,s){s.setValue(this._linearDefineName,this.convertToLinearSpace,!0),s.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)},i.prototype.bind=function(e,o,s){this.useLogarithmicDepth&&s&&MaterialHelper.BindLogDepth(void 0,e,s.getScene())},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.rgba,s=this.rgb,c=this.a;e.sharedData.hints.needAlphaBlending=o.isConnected||c.isConnected,e.sharedData.blocksWithDefines.push(this),this.useLogarithmicDepth&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");var d="//"+this.name;if(e._emitFunctionFromInclude("helperFunctions",d),o.connectedPoint)c.isConnected?e.compilationString+="gl_FragColor = vec4("+o.associatedVariableName+".rgb, "+c.associatedVariableName+`);\r
  4508. `:e.compilationString+="gl_FragColor = "+o.associatedVariableName+`;\r
  4509. `;else if(s.connectedPoint){var _="1.0";c.connectedPoint&&(_=c.associatedVariableName),s.connectedPoint.type===NodeMaterialBlockConnectionPointTypes.Float?e.compilationString+="gl_FragColor = vec4("+s.associatedVariableName+", "+s.associatedVariableName+", "+s.associatedVariableName+", "+_+`);\r
  4510. `:e.compilationString+="gl_FragColor = vec4("+s.associatedVariableName+", "+_+`);\r
  4511. `}else e.sharedData.checks.notConnectedNonOptionalInputs.push(o);return e.compilationString+="#ifdef "+this._linearDefineName+`\r
  4512. `,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor);\r
  4513. `,e.compilationString+=`#endif\r
  4514. `,e.compilationString+="#ifdef "+this._gammaDefineName+`\r
  4515. `,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor);\r
  4516. `,e.compilationString+=`#endif\r
  4517. `,this.useLogarithmicDepth&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r
  4518. `),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".convertToGammaSpace = "+this.convertToGammaSpace+`;\r
  4519. `,e+=this._codeVariableName+".convertToLinearSpace = "+this.convertToLinearSpace+`;\r
  4520. `,e+=this._codeVariableName+".useLogarithmicDepth = "+this.useLogarithmicDepth+`;\r
  4521. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e},i.prototype._deserialize=function(e,o,s){var c;a.prototype._deserialize.call(this,e,o,s),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=(c=e.useLogarithmicDepth)!==null&&c!==void 0?c:!1},__decorate([editableInPropertyPage("Convert to gamma space",PropertyTypeForEdition.Boolean,"PROPERTIES",{notifiers:{update:!0}})],i.prototype,"convertToGammaSpace",void 0),__decorate([editableInPropertyPage("Convert to linear space",PropertyTypeForEdition.Boolean,"PROPERTIES",{notifiers:{update:!0}})],i.prototype,"convertToLinearSpace",void 0),__decorate([editableInPropertyPage("Use logarithmic depth",PropertyTypeForEdition.Boolean,"PROPERTIES")],i.prototype,"useLogarithmicDepth",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.FragmentOutputBlock",FragmentOutputBlock);var AnimatedInputBlockTypes;(function(a){a[a.None=0]="None",a[a.Time=1]="Time"})(AnimatedInputBlockTypes||(AnimatedInputBlockTypes={}));var remapAttributeName={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},attributeInFragmentOnly={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},attributeAsUniform={particle_texturemask:!0},InputBlock=function(a){__extends(i,a);function i(e,o,s){o===void 0&&(o=NodeMaterialBlockTargets.Vertex),s===void 0&&(s=NodeMaterialBlockConnectionPointTypes.AutoDetect);var c=a.call(this,e,o,!1,!0)||this;return c._mode=NodeMaterialBlockConnectionPointMode.Undefined,c._animationType=AnimatedInputBlockTypes.None,c.min=0,c.max=0,c.isBoolean=!1,c.matrixMode=0,c._systemValue=null,c.isConstant=!1,c.groupInInspector="",c.onValueChangedObservable=new Observable,c.convertToGammaSpace=!1,c.convertToLinearSpace=!1,c._type=s,c.setDefaultValue(),c.registerOutput("output",s),c}return Object.defineProperty(i.prototype,"type",{get:function(){if(this._type===NodeMaterialBlockConnectionPointTypes.AutoDetect){if(this.isUniform&&this.value!=null){if(!isNaN(this.value))return this._type=NodeMaterialBlockConnectionPointTypes.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=NodeMaterialBlockConnectionPointTypes.Vector2,this._type;case"Vector3":return this._type=NodeMaterialBlockConnectionPointTypes.Vector3,this._type;case"Vector4":return this._type=NodeMaterialBlockConnectionPointTypes.Vector4,this._type;case"Color3":return this._type=NodeMaterialBlockConnectionPointTypes.Color3,this._type;case"Color4":return this._type=NodeMaterialBlockConnectionPointTypes.Color4,this._type;case"Matrix":return this._type=NodeMaterialBlockConnectionPointTypes.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"tangent":case"particle_positionw":return this._type=NodeMaterialBlockConnectionPointTypes.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=NodeMaterialBlockConnectionPointTypes.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"world0":case"world1":case"world2":case"world3":return this._type=NodeMaterialBlockConnectionPointTypes.Vector4,this._type;case"color":case"particle_color":case"particle_texturemask":return this._type=NodeMaterialBlockConnectionPointTypes.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case NodeMaterialSystemValues.World:case NodeMaterialSystemValues.WorldView:case NodeMaterialSystemValues.WorldViewProjection:case NodeMaterialSystemValues.View:case NodeMaterialSystemValues.ViewProjection:case NodeMaterialSystemValues.Projection:return this._type=NodeMaterialBlockConnectionPointTypes.Matrix,this._type;case NodeMaterialSystemValues.CameraPosition:return this._type=NodeMaterialBlockConnectionPointTypes.Vector3,this._type;case NodeMaterialSystemValues.FogColor:return this._type=NodeMaterialBlockConnectionPointTypes.Color3,this._type;case NodeMaterialSystemValues.DeltaTime:return this._type=NodeMaterialBlockConnectionPointTypes.Float,this._type;case NodeMaterialSystemValues.CameraParameters:return this._type=NodeMaterialBlockConnectionPointTypes.Vector4,this._type}}return this._type},enumerable:!1,configurable:!0}),i.prototype.validateBlockName=function(e){return this.isAttribute?!0:a.prototype.validateBlockName.call(this,e)},Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.setAsAttribute=function(e){return this._mode=NodeMaterialBlockConnectionPointMode.Attribute,e&&(this.name=e),this},i.prototype.setAsSystemValue=function(e){return this.systemValue=e,this},Object.defineProperty(i.prototype,"value",{get:function(){return this._storedValue},set:function(e){this.type===NodeMaterialBlockConnectionPointTypes.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=NodeMaterialBlockConnectionPointMode.Uniform,this.onValueChangedObservable.notifyObservers(this)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"valueCallback",{get:function(){return this._valueCallback},set:function(e){this._valueCallback=e,this._mode=NodeMaterialBlockConnectionPointMode.Uniform},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"associatedVariableName",{get:function(){return this._associatedVariableName},set:function(e){this._associatedVariableName=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"animationType",{get:function(){return this._animationType},set:function(e){this._animationType=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isUndefined",{get:function(){return this._mode===NodeMaterialBlockConnectionPointMode.Undefined},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isUniform",{get:function(){return this._mode===NodeMaterialBlockConnectionPointMode.Uniform},set:function(e){this._mode=e?NodeMaterialBlockConnectionPointMode.Uniform:NodeMaterialBlockConnectionPointMode.Undefined,this.associatedVariableName=""},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isAttribute",{get:function(){return this._mode===NodeMaterialBlockConnectionPointMode.Attribute},set:function(e){this._mode=e?NodeMaterialBlockConnectionPointMode.Attribute:NodeMaterialBlockConnectionPointMode.Undefined,this.associatedVariableName=""},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isVarying",{get:function(){return this._mode===NodeMaterialBlockConnectionPointMode.Varying},set:function(e){this._mode=e?NodeMaterialBlockConnectionPointMode.Varying:NodeMaterialBlockConnectionPointMode.Undefined,this.associatedVariableName=""},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isSystemValue",{get:function(){return this._systemValue!=null},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"systemValue",{get:function(){return this._systemValue},set:function(e){this._mode=NodeMaterialBlockConnectionPointMode.Uniform,this.associatedVariableName="",this._systemValue=e},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"InputBlock"},i.prototype.animate=function(e){switch(this._animationType){case AnimatedInputBlockTypes.Time:{this.type===NodeMaterialBlockConnectionPointTypes.Float&&(this.value+=e.getAnimationRatio()*.01);break}}},i.prototype._emitDefine=function(e){return e[0]==="!"?"#ifndef "+e.substring(1)+`\r
  4522. `:"#ifdef "+e+`\r
  4523. `},i.prototype.initialize=function(e){this.associatedVariableName=""},i.prototype.setDefaultValue=function(){switch(this.type){case NodeMaterialBlockConnectionPointTypes.Float:this.value=0;break;case NodeMaterialBlockConnectionPointTypes.Vector2:this.value=Vector2.Zero();break;case NodeMaterialBlockConnectionPointTypes.Vector3:this.value=Vector3.Zero();break;case NodeMaterialBlockConnectionPointTypes.Vector4:this.value=Vector4.Zero();break;case NodeMaterialBlockConnectionPointTypes.Color3:this.value=Color3.White();break;case NodeMaterialBlockConnectionPointTypes.Color4:this.value=new Color4(1,1,1,1);break;case NodeMaterialBlockConnectionPointTypes.Matrix:this.value=Matrix.Identity();break}},i.prototype._emitConstant=function(e){switch(this.type){case NodeMaterialBlockConnectionPointTypes.Float:return""+e._emitFloat(this.value);case NodeMaterialBlockConnectionPointTypes.Vector2:return"vec2("+this.value.x+", "+this.value.y+")";case NodeMaterialBlockConnectionPointTypes.Vector3:return"vec3("+this.value.x+", "+this.value.y+", "+this.value.z+")";case NodeMaterialBlockConnectionPointTypes.Vector4:return"vec4("+this.value.x+", "+this.value.y+", "+this.value.z+", "+this.value.w+")";case NodeMaterialBlockConnectionPointTypes.Color3:return TmpColors.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0]),this.convertToLinearSpace&&TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0]),"vec3("+TmpColors.Color3[0].r+", "+TmpColors.Color3[0].g+", "+TmpColors.Color3[0].b+")";case NodeMaterialBlockConnectionPointTypes.Color4:return TmpColors.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0]),this.convertToLinearSpace&&TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0]),"vec4("+TmpColors.Color4[0].r+", "+TmpColors.Color4[0].g+", "+TmpColors.Color4[0].b+", "+TmpColors.Color4[0].a+")"}return""},Object.defineProperty(i.prototype,"_noContextSwitch",{get:function(){return attributeInFragmentOnly[this.name]},enumerable:!1,configurable:!0}),i.prototype._emit=function(e,o){var s;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(e.constants.indexOf(this.associatedVariableName)!==-1)return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+(" = "+this._emitConstant(e)+`;\r
  4524. `);return}if(e.uniforms.indexOf(this.associatedVariableName)!==-1)return;e.uniforms.push(this.associatedVariableName),o&&(e._uniformDeclaration+=this._emitDefine(o)),e._uniformDeclaration+="uniform "+e._getGLType(this.type)+" "+this.associatedVariableName+`;\r
  4525. `,o&&(e._uniformDeclaration+=`#endif\r
  4526. `);var c=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case NodeMaterialSystemValues.WorldView:c.needWorldViewMatrix=!0;break;case NodeMaterialSystemValues.WorldViewProjection:c.needWorldViewProjectionMatrix=!0;break}else this._animationType!==AnimatedInputBlockTypes.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=(s=remapAttributeName[this.name])!==null&&s!==void 0?s:this.name,this.target===NodeMaterialBlockTargets.Vertex&&e._vertexState){attributeInFragmentOnly[this.name]?attributeAsUniform[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),o):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),o):this._emit(e._vertexState,o);return}if(e.attributes.indexOf(this.associatedVariableName)!==-1)return;e.attributes.push(this.associatedVariableName),attributeInFragmentOnly[this.name]?attributeAsUniform[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),o):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),o):(o&&(e._attributeDeclaration+=this._emitDefine(o)),e._attributeDeclaration+="attribute "+e._getGLType(this.type)+" "+this.associatedVariableName+`;\r
  4527. `,o&&(e._attributeDeclaration+=`#endif\r
  4528. `))}},i.prototype._transmitWorld=function(e,o,s,c){if(!!this._systemValue){var d=this.associatedVariableName;switch(this._systemValue){case NodeMaterialSystemValues.World:e.setMatrix(d,o);break;case NodeMaterialSystemValues.WorldView:e.setMatrix(d,s);break;case NodeMaterialSystemValues.WorldViewProjection:e.setMatrix(d,c);break}}},i.prototype._transmit=function(e,o){if(!this.isAttribute){var s=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case NodeMaterialSystemValues.World:case NodeMaterialSystemValues.WorldView:case NodeMaterialSystemValues.WorldViewProjection:return;case NodeMaterialSystemValues.View:e.setMatrix(s,o.getViewMatrix());break;case NodeMaterialSystemValues.Projection:e.setMatrix(s,o.getProjectionMatrix());break;case NodeMaterialSystemValues.ViewProjection:e.setMatrix(s,o.getTransformMatrix());break;case NodeMaterialSystemValues.CameraPosition:o.bindEyePosition(e,s,!0);break;case NodeMaterialSystemValues.FogColor:e.setColor3(s,o.fogColor);break;case NodeMaterialSystemValues.DeltaTime:e.setFloat(s,o.deltaTime/1e3);case NodeMaterialSystemValues.CameraParameters:o.activeCamera&&e.setFloat4(s,o.getEngine().hasOriginBottomLeft?-1:1,o.activeCamera.minZ,o.activeCamera.maxZ,1/o.activeCamera.maxZ);break}return}var c=this._valueCallback?this._valueCallback():this._storedValue;if(c!==null)switch(this.type){case NodeMaterialBlockConnectionPointTypes.Float:e.setFloat(s,c);break;case NodeMaterialBlockConnectionPointTypes.Int:e.setInt(s,c);break;case NodeMaterialBlockConnectionPointTypes.Color3:TmpColors.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0]),this.convertToLinearSpace&&TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0]),e.setColor3(s,TmpColors.Color3[0]);break;case NodeMaterialBlockConnectionPointTypes.Color4:TmpColors.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0]),this.convertToLinearSpace&&TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0]),e.setDirectColor4(s,TmpColors.Color4[0]);break;case NodeMaterialBlockConnectionPointTypes.Vector2:e.setVector2(s,c);break;case NodeMaterialBlockConnectionPointTypes.Vector3:e.setVector3(s,c);break;case NodeMaterialBlockConnectionPointTypes.Vector4:e.setVector4(s,c);break;case NodeMaterialBlockConnectionPointTypes.Matrix:e.setMatrix(s,c);break}}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)},i.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName;if(this.isAttribute)return a.prototype._dumpPropertiesCode.call(this)+(e+'.setAsAttribute("'+this.name+`");\r
  4529. `);if(this.isSystemValue)return a.prototype._dumpPropertiesCode.call(this)+(e+".setAsSystemValue(BABYLON.NodeMaterialSystemValues."+NodeMaterialSystemValues[this._systemValue]+`);\r
  4530. `);if(this.isUniform){var o=[],s="";switch(this.type){case NodeMaterialBlockConnectionPointTypes.Float:s=""+this.value;break;case NodeMaterialBlockConnectionPointTypes.Vector2:s="new BABYLON.Vector2("+this.value.x+", "+this.value.y+")";break;case NodeMaterialBlockConnectionPointTypes.Vector3:s="new BABYLON.Vector3("+this.value.x+", "+this.value.y+", "+this.value.z+")";break;case NodeMaterialBlockConnectionPointTypes.Vector4:s="new BABYLON.Vector4("+this.value.x+", "+this.value.y+", "+this.value.z+", "+this.value.w+")";break;case NodeMaterialBlockConnectionPointTypes.Color3:s="new BABYLON.Color3("+this.value.r+", "+this.value.g+", "+this.value.b+")",this.convertToGammaSpace&&(s+=".toGammaSpace()"),this.convertToLinearSpace&&(s+=".toLinearSpace()");break;case NodeMaterialBlockConnectionPointTypes.Color4:s="new BABYLON.Color4("+this.value.r+", "+this.value.g+", "+this.value.b+", "+this.value.a+")",this.convertToGammaSpace&&(s+=".toGammaSpace()"),this.convertToLinearSpace&&(s+=".toLinearSpace()");break;case NodeMaterialBlockConnectionPointTypes.Matrix:s="BABYLON.Matrix.FromArray(["+this.value.m+"])";break}return o.push(e+".value = "+s),this.type===NodeMaterialBlockConnectionPointTypes.Float&&o.push(e+".min = "+this.min,e+".max = "+this.max,e+".isBoolean = "+this.isBoolean,e+".matrixMode = "+this.matrixMode,e+".animationType = BABYLON.AnimatedInputBlockTypes."+AnimatedInputBlockTypes[this.animationType]),o.push(e+".isConstant = "+this.isConstant),o.push(""),a.prototype._dumpPropertiesCode.call(this)+o.join(`;\r
  4531. `)}return a.prototype._dumpPropertiesCode.call(this)},i.prototype.dispose=function(){this.onValueChangedObservable.clear(),a.prototype.dispose.call(this)},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this._storedValue!=null&&this._mode===NodeMaterialBlockConnectionPointMode.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e},i.prototype._deserialize=function(e,o,s){if(this._mode=e.mode,a.prototype._deserialize.call(this,e,o,s),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{var c=GetClass(e.valueType);c&&(this._storedValue=c.FromArray(e.value))}},i}(NodeMaterialBlock);RegisterClass("BABYLON.InputBlock",InputBlock);var CurrentScreenBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.VertexAndFragment)||this;return o._samplerName="textureSampler",o.convertToGammaSpace=!1,o.convertToLinearSpace=!1,o._isUnique=!1,o.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2,!1,NodeMaterialBlockTargets.VertexAndFragment),o.registerOutput("rgba",NodeMaterialBlockConnectionPointTypes.Color4,NodeMaterialBlockTargets.Neutral),o.registerOutput("rgb",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Neutral),o.registerOutput("r",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o.registerOutput("g",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o.registerOutput("b",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o.registerOutput("a",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[0]._prioritizeVertex=!1,o}return i.prototype.getClassName=function(){return"CurrentScreenBlock"},Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),i.prototype.initialize=function(e){e._excludeVariableName("textureSampler")},Object.defineProperty(i.prototype,"target",{get:function(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?NodeMaterialBlockTargets.VertexAndFragment:NodeMaterialBlockTargets.Fragment},enumerable:!1,configurable:!0}),i.prototype.prepareDefines=function(e,o,s){s.setValue(this._linearDefineName,this.convertToGammaSpace,!0),s.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)},i.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},i.prototype._injectVertexCode=function(e){var o=this.uv;if(o.connectedPoint.ownerBlock.isInput){var s=o.connectedPoint.ownerBlock;s.isAttribute||e._emitUniformFromString(o.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+o.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=this._mainUVName+" = "+o.associatedVariableName+`.xy;\r
  4532. `,!!this._outputs.some(function(b){return b.isConnectedInVertexShader})){this._writeTextureRead(e,!0);for(var c=0,d=this._outputs;c<d.length;c++){var _=d[c];_.hasEndpoints&&this._writeOutput(e,_,_.name,!0)}}},i.prototype._writeTextureRead=function(e,o){o===void 0&&(o=!1);var s=this.uv;if(o){if(e.target===NodeMaterialBlockTargets.Fragment)return;e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+s.associatedVariableName+`);\r
  4533. `;return}if(this.uv.ownerBlock.target===NodeMaterialBlockTargets.Fragment){e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+s.associatedVariableName+`);\r
  4534. `;return}e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+this._mainUVName+`);\r
  4535. `},i.prototype._writeOutput=function(e,o,s,c){if(c===void 0&&(c=!1),c){if(e.target===NodeMaterialBlockTargets.Fragment)return;e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4536. `;return}if(this.uv.ownerBlock.target===NodeMaterialBlockTargets.Fragment){e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4537. `;return}e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4538. `,e.compilationString+="#ifdef "+this._linearDefineName+`\r
  4539. `,e.compilationString+=o.associatedVariableName+" = toGammaSpace("+o.associatedVariableName+`);\r
  4540. `,e.compilationString+=`#endif\r
  4541. `,e.compilationString+="#ifdef "+this._gammaDefineName+`\r
  4542. `,e.compilationString+=o.associatedVariableName+" = toLinearSpace("+o.associatedVariableName+`);\r
  4543. `,e.compilationString+=`#endif\r
  4544. `},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==NodeMaterialBlockTargets.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!!this._outputs.some(function(_){return _.isConnectedInFragmentShader})){e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");var o="//"+this.name;e._emitFunctionFromInclude("helperFunctions",o),this._writeTextureRead(e);for(var s=0,c=this._outputs;s<c.length;s++){var d=c[s];d.hasEndpoints&&this._writeOutput(e,d,d.name)}return this}},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(s=e.texture.url.indexOf("data:")===0?"":s,this.texture=Texture.Parse(e.texture,o,s))},i}(NodeMaterialBlock);RegisterClass("BABYLON.CurrentScreenBlock",CurrentScreenBlock);var ParticleTextureBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o._samplerName="diffuseSampler",o.convertToGammaSpace=!1,o.convertToLinearSpace=!1,o._isUnique=!1,o.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2,!1,NodeMaterialBlockTargets.VertexAndFragment),o.registerOutput("rgba",NodeMaterialBlockConnectionPointTypes.Color4,NodeMaterialBlockTargets.Neutral),o.registerOutput("rgb",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Neutral),o.registerOutput("r",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o.registerOutput("g",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o.registerOutput("b",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o.registerOutput("a",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o}return i.prototype.getClassName=function(){return"ParticleTextureBlock"},Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),i.prototype.initialize=function(e){e._excludeVariableName("diffuseSampler")},i.prototype.autoConfigure=function(e){if(!this.uv.isConnected){var o=e.getInputBlockByPredicate(function(s){return s.isAttribute&&s.name==="particle_uv"});o||(o=new InputBlock("uv"),o.setAsAttribute("particle_uv")),o.output.connectTo(this.uv)}},i.prototype.prepareDefines=function(e,o,s){s.setValue(this._linearDefineName,this.convertToGammaSpace,!0),s.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)},i.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},i.prototype._writeOutput=function(e,o,s){e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4545. `,e.compilationString+="#ifdef "+this._linearDefineName+`\r
  4546. `,e.compilationString+=o.associatedVariableName+" = toGammaSpace("+o.associatedVariableName+`);\r
  4547. `,e.compilationString+=`#endif\r
  4548. `,e.compilationString+="#ifdef "+this._gammaDefineName+`\r
  4549. `,e.compilationString+=o.associatedVariableName+" = toLinearSpace("+o.associatedVariableName+`);\r
  4550. `,e.compilationString+=`#endif\r
  4551. `},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.target!==NodeMaterialBlockTargets.Vertex){this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");var o="//"+this.name;e._emitFunctionFromInclude("helperFunctions",o),e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+this.uv.associatedVariableName+`);\r
  4552. `;for(var s=0,c=this._outputs;s<c.length;s++){var d=c[s];d.hasEndpoints&&this._writeOutput(e,d,d.name)}return this}},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(s=e.texture.url.indexOf("data:")===0?"":s,this.texture=Texture.Parse(e.texture,o,s))},i}(NodeMaterialBlock);RegisterClass("BABYLON.ParticleTextureBlock",ParticleTextureBlock);var ParticleRampGradientBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o._isUnique=!0,o.registerInput("color",NodeMaterialBlockConnectionPointTypes.Color4,!1,NodeMaterialBlockTargets.Fragment),o.registerOutput("rampColor",NodeMaterialBlockConnectionPointTypes.Color4,NodeMaterialBlockTargets.Fragment),o}return i.prototype.getClassName=function(){return"ParticleRampGradientBlock"},Object.defineProperty(i.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rampColor",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.initialize=function(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.target!==NodeMaterialBlockTargets.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`
  4553. #ifdef RAMPGRADIENT
  4554. vec4 baseColor = `+this.color.associatedVariableName+`;
  4555. float alpha = `+this.color.associatedVariableName+`.a;
  4556. float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);
  4557. vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));
  4558. baseColor.rgb *= rampColor.rgb;
  4559. // Remapped alpha
  4560. float finalAlpha = baseColor.a;
  4561. baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);
  4562. `+this._declareOutput(this.rampColor,e)+` = baseColor;
  4563. #else
  4564. `+this._declareOutput(this.rampColor,e)+" = "+this.color.associatedVariableName+`;
  4565. #endif
  4566. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ParticleRampGradientBlock",ParticleRampGradientBlock);var ParticleBlendMultiplyBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o._isUnique=!0,o.registerInput("color",NodeMaterialBlockConnectionPointTypes.Color4,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("alphaTexture",NodeMaterialBlockConnectionPointTypes.Float,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("alphaColor",NodeMaterialBlockConnectionPointTypes.Float,!1,NodeMaterialBlockTargets.Fragment),o.registerOutput("blendColor",NodeMaterialBlockConnectionPointTypes.Color4,NodeMaterialBlockTargets.Fragment),o}return i.prototype.getClassName=function(){return"ParticleBlendMultiplyBlock"},Object.defineProperty(i.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"alphaTexture",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"alphaColor",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"blendColor",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.initialize=function(e){e._excludeVariableName("sourceAlpha")},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.target!==NodeMaterialBlockTargets.Vertex)return e.compilationString+=`
  4567. #ifdef BLENDMULTIPLYMODE
  4568. `+this._declareOutput(this.blendColor,e)+`;
  4569. float sourceAlpha = `+this.alphaColor.associatedVariableName+" * "+this.alphaTexture.associatedVariableName+`;
  4570. `+this.blendColor.associatedVariableName+".rgb = "+this.color.associatedVariableName+`.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);
  4571. `+this.blendColor.associatedVariableName+".a = "+this.color.associatedVariableName+`.a;
  4572. #else
  4573. `+this._declareOutput(this.blendColor,e)+" = "+this.color.associatedVariableName+`;
  4574. #endif
  4575. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ParticleBlendMultiplyBlock",ParticleBlendMultiplyBlock);var VectorMergerBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.xSwizzle="x",o.ySwizzle="y",o.zSwizzle="z",o.wSwizzle="w",o.registerInput("xyzw ",NodeMaterialBlockConnectionPointTypes.Vector4,!0),o.registerInput("xyz ",NodeMaterialBlockConnectionPointTypes.Vector3,!0),o.registerInput("xy ",NodeMaterialBlockConnectionPointTypes.Vector2,!0),o.registerInput("zw ",NodeMaterialBlockConnectionPointTypes.Vector2,!0),o.registerInput("x",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("y",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("z",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("w",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerOutput("xyzw",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerOutput("xyz",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("xy",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("zw",NodeMaterialBlockConnectionPointTypes.Vector2),o}return i.prototype.getClassName=function(){return"VectorMergerBlock"},Object.defineProperty(i.prototype,"xyzwIn",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyzIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyIn",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"zwIn",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"x",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"z",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"w",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyzw",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyzOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyOut",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"zwOut",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xy",{get:function(){return this.xyOut},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyz",{get:function(){return this.xyzOut},enumerable:!1,configurable:!0}),i.prototype._inputRename=function(e){return e==="xyzw "?"xyzwIn":e==="xyz "?"xyzIn":e==="xy "?"xyIn":e==="zw "?"zwIn":e},i.prototype._buildSwizzle=function(e){var o=this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle;return"."+o.substr(0,e)},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.x,s=this.y,c=this.z,d=this.w,_=this.xyIn,b=this.zwIn,k=this.xyzIn,j=this.xyzwIn,$=this._outputs[0],_e=this._outputs[1],et=this._outputs[2],tt=this._outputs[3];return j.isConnected?($.hasEndpoints&&(e.compilationString+=this._declareOutput($,e)+(" = "+j.associatedVariableName+this._buildSwizzle(4)+`;\r
  4576. `)),_e.hasEndpoints&&(e.compilationString+=this._declareOutput(_e,e)+(" = "+j.associatedVariableName+this._buildSwizzle(3)+`;\r
  4577. `)),et.hasEndpoints&&(e.compilationString+=this._declareOutput(et,e)+(" = "+j.associatedVariableName+this._buildSwizzle(2)+`;\r
  4578. `))):k.isConnected?($.hasEndpoints&&(e.compilationString+=this._declareOutput($,e)+(" = vec4("+k.associatedVariableName+", "+(d.isConnected?this._writeVariable(d):"0.0")+")"+this._buildSwizzle(4)+`;\r
  4579. `)),_e.hasEndpoints&&(e.compilationString+=this._declareOutput(_e,e)+(" = "+k.associatedVariableName+this._buildSwizzle(3)+`;\r
  4580. `)),et.hasEndpoints&&(e.compilationString+=this._declareOutput(et,e)+(" = "+k.associatedVariableName+this._buildSwizzle(2)+`;\r
  4581. `))):_.isConnected?($.hasEndpoints&&(b.isConnected?e.compilationString+=this._declareOutput($,e)+(" = vec4("+_.associatedVariableName+", "+b.associatedVariableName+")"+this._buildSwizzle(4)+`;\r
  4582. `):e.compilationString+=this._declareOutput($,e)+(" = vec4("+_.associatedVariableName+", "+(c.isConnected?this._writeVariable(c):"0.0")+", "+(d.isConnected?this._writeVariable(d):"0.0")+")"+this._buildSwizzle(4)+`;\r
  4583. `)),_e.hasEndpoints&&(e.compilationString+=this._declareOutput(_e,e)+(" = vec3("+_.associatedVariableName+", "+(c.isConnected?this._writeVariable(c):"0.0")+")"+this._buildSwizzle(3)+`;\r
  4584. `)),et.hasEndpoints&&(e.compilationString+=this._declareOutput(et,e)+(" = "+_.associatedVariableName+this._buildSwizzle(2)+`;\r
  4585. `)),tt.hasEndpoints&&(b.isConnected?e.compilationString+=this._declareOutput(tt,e)+(" = "+b.associatedVariableName+this._buildSwizzle(2)+`;\r
  4586. `):e.compilationString+=this._declareOutput(tt,e)+(" = vec2("+(c.isConnected?this._writeVariable(c):"0.0")+", "+(d.isConnected?this._writeVariable(d):"0.0")+")"+this._buildSwizzle(2)+`;\r
  4587. `))):($.hasEndpoints&&(b.isConnected?e.compilationString+=this._declareOutput($,e)+(" = vec4("+(o.isConnected?this._writeVariable(o):"0.0")+", "+(s.isConnected?this._writeVariable(s):"0.0")+", "+b.associatedVariableName+")"+this._buildSwizzle(4)+`;\r
  4588. `):e.compilationString+=this._declareOutput($,e)+(" = vec4("+(o.isConnected?this._writeVariable(o):"0.0")+", "+(s.isConnected?this._writeVariable(s):"0.0")+", "+(c.isConnected?this._writeVariable(c):"0.0")+", "+(d.isConnected?this._writeVariable(d):"0.0")+")"+this._buildSwizzle(4)+`;\r
  4589. `)),_e.hasEndpoints&&(e.compilationString+=this._declareOutput(_e,e)+(" = vec3("+(o.isConnected?this._writeVariable(o):"0.0")+", "+(s.isConnected?this._writeVariable(s):"0.0")+", "+(c.isConnected?this._writeVariable(c):"0.0")+")"+this._buildSwizzle(3)+`;\r
  4590. `)),et.hasEndpoints&&(e.compilationString+=this._declareOutput(et,e)+(" = vec2("+(o.isConnected?this._writeVariable(o):"0.0")+", "+(s.isConnected?this._writeVariable(s):"0.0")+")"+this._buildSwizzle(2)+`;\r
  4591. `)),tt.hasEndpoints&&(b.isConnected?e.compilationString+=this._declareOutput(tt,e)+(" = "+b.associatedVariableName+this._buildSwizzle(2)+`;\r
  4592. `):e.compilationString+=this._declareOutput(tt,e)+(" = vec2("+(c.isConnected?this._writeVariable(c):"0.0")+", "+(d.isConnected?this._writeVariable(d):"0.0")+")"+this._buildSwizzle(2)+`;\r
  4593. `))),this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e},i.prototype._deserialize=function(e,o,s){var c,d,_,b;a.prototype._deserialize.call(this,e,o,s),this.xSwizzle=(c=e.xSwizzle)!==null&&c!==void 0?c:"x",this.ySwizzle=(d=e.ySwizzle)!==null&&d!==void 0?d:"y",this.zSwizzle=(_=e.zSwizzle)!==null&&_!==void 0?_:"z",this.wSwizzle=(b=e.wSwizzle)!==null&&b!==void 0?b:"w"},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+'.xSwizzle = "'+this.xSwizzle+`";\r
  4594. `,e+=this._codeVariableName+'.ySwizzle = "'+this.ySwizzle+`";\r
  4595. `,e+=this._codeVariableName+'.zSwizzle = "'+this.zSwizzle+`";\r
  4596. `,e+=this._codeVariableName+'.wSwizzle = "'+this.wSwizzle+`";\r
  4597. `,e},i}(NodeMaterialBlock);RegisterClass("BABYLON.VectorMergerBlock",VectorMergerBlock);var RemapBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.sourceRange=new Vector2(-1,1),o.targetRange=new Vector2(0,1),o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("sourceMin",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("sourceMax",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("targetMin",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("targetMax",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o}return i.prototype.getClassName=function(){return"RemapBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sourceMin",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sourceMax",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"targetMin",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"targetMax",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),c=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),d=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),_=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(o,e)+(" = "+d+" + ("+this._inputs[0].associatedVariableName+" - "+s+") * ("+_+" - "+d+") / ("+c+" - "+s+`);\r
  4598. `),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".sourceRange = new BABYLON.Vector2("+this.sourceRange.x+", "+this.sourceRange.y+`);\r
  4599. `);return e+=this._codeVariableName+".targetRange = new BABYLON.Vector2("+this.targetRange.x+", "+this.targetRange.y+`);\r
  4600. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.sourceRange=Vector2.FromArray(e.sourceRange),this.targetRange=Vector2.FromArray(e.targetRange)},__decorate([editableInPropertyPage("From",PropertyTypeForEdition.Vector2)],i.prototype,"sourceRange",void 0),__decorate([editableInPropertyPage("To",PropertyTypeForEdition.Vector2)],i.prototype,"targetRange",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.RemapBlock",RemapBlock);var MultiplyBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"MultiplyBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = "+this.left.associatedVariableName+" * "+this.right.associatedVariableName+`;\r
  4601. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.MultiplyBlock",MultiplyBlock);var ColorSplitterBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("rgba",NodeMaterialBlockConnectionPointTypes.Color4,!0),o.registerInput("rgb ",NodeMaterialBlockConnectionPointTypes.Color3,!0),o.registerOutput("rgb",NodeMaterialBlockConnectionPointTypes.Color3),o.registerOutput("r",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("g",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("b",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("a",NodeMaterialBlockConnectionPointTypes.Float),o.inputsAreExclusive=!0,o}return i.prototype.getClassName=function(){return"ColorSplitterBlock"},Object.defineProperty(i.prototype,"rgba",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgbIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgbOut",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"r",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"g",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"b",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"a",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),i.prototype._inputRename=function(e){return e==="rgb "?"rgbIn":e},i.prototype._outputRename=function(e){return e==="rgb"?"rgbOut":e},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.rgba.isConnected?this.rgba:this.rgbIn;if(!!o.isConnected){var s=this._outputs[0],c=this._outputs[1],d=this._outputs[2],_=this._outputs[3],b=this._outputs[4];return s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+(" = "+o.associatedVariableName+`.rgb;\r
  4602. `)),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+(" = "+o.associatedVariableName+`.r;\r
  4603. `)),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+(" = "+o.associatedVariableName+`.g;\r
  4604. `)),_.hasEndpoints&&(e.compilationString+=this._declareOutput(_,e)+(" = "+o.associatedVariableName+`.b;\r
  4605. `)),b.hasEndpoints&&(e.compilationString+=this._declareOutput(b,e)+(" = "+o.associatedVariableName+`.a;\r
  4606. `)),this}},i}(NodeMaterialBlock);RegisterClass("BABYLON.ColorSplitterBlock",ColorSplitterBlock);var TrigonometryBlockOperations;(function(a){a[a.Cos=0]="Cos",a[a.Sin=1]="Sin",a[a.Abs=2]="Abs",a[a.Exp=3]="Exp",a[a.Exp2=4]="Exp2",a[a.Round=5]="Round",a[a.Floor=6]="Floor",a[a.Ceiling=7]="Ceiling",a[a.Sqrt=8]="Sqrt",a[a.Log=9]="Log",a[a.Tan=10]="Tan",a[a.ArcTan=11]="ArcTan",a[a.ArcCos=12]="ArcCos",a[a.ArcSin=13]="ArcSin",a[a.Fract=14]="Fract",a[a.Sign=15]="Sign",a[a.Radians=16]="Radians",a[a.Degrees=17]="Degrees"})(TrigonometryBlockOperations||(TrigonometryBlockOperations={}));var TrigonometryBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.operation=TrigonometryBlockOperations.Cos,o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o}return i.prototype.getClassName=function(){return"TrigonometryBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s="";switch(this.operation){case TrigonometryBlockOperations.Cos:{s="cos";break}case TrigonometryBlockOperations.Sin:{s="sin";break}case TrigonometryBlockOperations.Abs:{s="abs";break}case TrigonometryBlockOperations.Exp:{s="exp";break}case TrigonometryBlockOperations.Exp2:{s="exp2";break}case TrigonometryBlockOperations.Round:{s="round";break}case TrigonometryBlockOperations.Floor:{s="floor";break}case TrigonometryBlockOperations.Ceiling:{s="ceil";break}case TrigonometryBlockOperations.Sqrt:{s="sqrt";break}case TrigonometryBlockOperations.Log:{s="log";break}case TrigonometryBlockOperations.Tan:{s="tan";break}case TrigonometryBlockOperations.ArcTan:{s="atan";break}case TrigonometryBlockOperations.ArcCos:{s="acos";break}case TrigonometryBlockOperations.ArcSin:{s="asin";break}case TrigonometryBlockOperations.Fract:{s="fract";break}case TrigonometryBlockOperations.Sign:{s="sign";break}case TrigonometryBlockOperations.Radians:{s="radians";break}case TrigonometryBlockOperations.Degrees:{s="degrees";break}}return e.compilationString+=this._declareOutput(o,e)+(" = "+s+"("+this.input.associatedVariableName+`);\r
  4607. `),this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.operation=this.operation,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.operation=e.operation},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".operation = BABYLON.TrigonometryBlockOperations."+TrigonometryBlockOperations[this.operation]+`;\r
  4608. `);return e},i}(NodeMaterialBlock);RegisterClass("BABYLON.TrigonometryBlock",TrigonometryBlock);var onCreatedEffectParameters$1={effect:null,subMesh:null},NodeMaterialDefines=function(a){__extends(i,a);function i(){var e=a.call(this)||this;return e.NORMAL=!1,e.TANGENT=!1,e.UV1=!1,e.UV2=!1,e.UV3=!1,e.UV4=!1,e.UV5=!1,e.UV6=!1,e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE=!1,e.MORPHTARGETS=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_UV=!1,e.NUM_MORPH_INFLUENCERS=0,e.MORPHTARGETS_TEXTURE=!1,e.IMAGEPROCESSING=!1,e.VIGNETTE=!1,e.VIGNETTEBLENDMODEMULTIPLY=!1,e.VIGNETTEBLENDMODEOPAQUE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=!1,e.SAMPLER3DBGRMAP=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.SKIPFINALCOLORCLAMP=!1,e.BUMPDIRECTUV=0,e.rebuild(),e}return i.prototype.setValue=function(e,o,s){s===void 0&&(s=!1),this[e]===void 0&&this._keys.push(e),s&&this[e]!==o&&this.markAsUnprocessed(),this[e]=o},i}(MaterialDefines),NodeMaterial=function(a){__extends(i,a);function i(e,o,s){s===void 0&&(s={});var c=a.call(this,e,o||Engine.LastCreatedScene)||this;return c._buildId=i._BuildIdGenerator++,c._buildWasSuccessful=!1,c._cachedWorldViewMatrix=new Matrix,c._cachedWorldViewProjectionMatrix=new Matrix,c._optimizers=new Array,c._animationFrame=-1,c.BJSNODEMATERIALEDITOR=c._getGlobalNodeMaterialEditor(),c.editorData=null,c.ignoreAlpha=!1,c.maxSimultaneousLights=4,c.onBuildObservable=new Observable,c._vertexOutputNodes=new Array,c._fragmentOutputNodes=new Array,c.attachedBlocks=new Array,c._mode=NodeMaterialModes.Material,c._options=__assign({emitComments:!1},s),c._attachImageProcessingConfiguration(null),c}return i.prototype._getGlobalNodeMaterialEditor=function(){if(typeof NODEEDITOR!="undefined")return NODEEDITOR;if(typeof BABYLON!="undefined"&&typeof BABYLON.NodeEditor!="undefined")return BABYLON},Object.defineProperty(i.prototype,"options",{get:function(){return this._options},set:function(e){this._options=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"mode",{get:function(){return this._mode},set:function(e){this._mode=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buildId",{get:function(){return this._buildId},set:function(e){this._buildId=e},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"NodeMaterial"},i.prototype._attachImageProcessingConfiguration=function(e){var o=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){o._markAllSubMeshesAsImageProcessingDirty()})))},i.prototype.getBlockByName=function(e){for(var o=null,s=0,c=this.attachedBlocks;s<c.length;s++){var d=c[s];if(d.name===e)if(!o)o=d;else return Tools.Warn("More than one block was found with the name `"+e+"`"),o}return o},i.prototype.getBlockByPredicate=function(e){for(var o=0,s=this.attachedBlocks;o<s.length;o++){var c=s[o];if(e(c))return c}return null},i.prototype.getInputBlockByPredicate=function(e){for(var o=0,s=this.attachedBlocks;o<s.length;o++){var c=s[o];if(c.isInput&&e(c))return c}return null},i.prototype.getInputBlocks=function(){for(var e=[],o=0,s=this.attachedBlocks;o<s.length;o++){var c=s[o];c.isInput&&e.push(c)}return e},i.prototype.registerOptimizer=function(e){var o=this._optimizers.indexOf(e);if(!(o>-1))return this._optimizers.push(e),this},i.prototype.unregisterOptimizer=function(e){var o=this._optimizers.indexOf(e);if(o!==-1)return this._optimizers.splice(o,1),this},i.prototype.addOutputNode=function(e){if(e.target===null)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&NodeMaterialBlockTargets.Vertex)!==0&&this._addVertexOutputNode(e),(e.target&NodeMaterialBlockTargets.Fragment)!==0&&this._addFragmentOutputNode(e),this},i.prototype.removeOutputNode=function(e){return e.target===null?this:((e.target&NodeMaterialBlockTargets.Vertex)!==0&&this._removeVertexOutputNode(e),(e.target&NodeMaterialBlockTargets.Fragment)!==0&&this._removeFragmentOutputNode(e),this)},i.prototype._addVertexOutputNode=function(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=NodeMaterialBlockTargets.Vertex,this._vertexOutputNodes.push(e),this},i.prototype._removeVertexOutputNode=function(e){var o=this._vertexOutputNodes.indexOf(e);if(o!==-1)return this._vertexOutputNodes.splice(o,1),this},i.prototype._addFragmentOutputNode=function(e){if(this._fragmentOutputNodes.indexOf(e)===-1)return e.target=NodeMaterialBlockTargets.Fragment,this._fragmentOutputNodes.push(e),this},i.prototype._removeFragmentOutputNode=function(e){var o=this._fragmentOutputNodes.indexOf(e);if(o!==-1)return this._fragmentOutputNodes.splice(o,1),this},i.prototype.needAlphaBlending=function(){return this.ignoreAlpha?!1:this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending},i.prototype.needAlphaTesting=function(){return this._sharedData&&this._sharedData.hints.needAlphaTesting},i.prototype._initializeBlock=function(e,o,s,c){if(c===void 0&&(c=!0),e.initialize(o),c&&e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique)for(var d=e.getClassName(),_=0,b=this.attachedBlocks;_<b.length;_++){var k=b[_];if(k.getClassName()===d)throw"Cannot have multiple blocks of type "+d+" in the same NodeMaterial"}this.attachedBlocks.push(e)}for(var j=0,$=e.inputs;j<$.length;j++){var _e=$[j];_e.associatedVariableName="";var et=_e.connectedPoint;if(et){var tt=et.ownerBlock;tt!==e&&((tt.target===NodeMaterialBlockTargets.VertexAndFragment||o.target===NodeMaterialBlockTargets.Fragment&&tt.target===NodeMaterialBlockTargets.Vertex&&tt._preparationId!==this._buildId)&&s.push(tt),this._initializeBlock(tt,o,s,c))}}for(var rt=0,it=e.outputs;rt<it.length;rt++){var nt=it[rt];nt.associatedVariableName=""}},i.prototype._resetDualBlocks=function(e,o){e.target===NodeMaterialBlockTargets.VertexAndFragment&&(e.buildId=o);for(var s=0,c=e.inputs;s<c.length;s++){var d=c[s],_=d.connectedPoint;if(_){var b=_.ownerBlock;b!==e&&this._resetDualBlocks(b,o)}}},i.prototype.removeBlock=function(e){var o=this.attachedBlocks.indexOf(e);o>-1&&this.attachedBlocks.splice(o,1),e.isFinalMerger&&this.removeOutputNode(e)},i.prototype.build=function(e,o,s){e===void 0&&(e=!1),o===void 0&&(o=!0),s===void 0&&(s=!0),this._buildWasSuccessful=!1;var c=this.getScene().getEngine(),d=this._mode===NodeMaterialModes.Particle;if(this._vertexOutputNodes.length===0&&!d)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new NodeMaterialBuildState,this._vertexCompilationState.supportUniformBuffers=c.supportsUniformBuffers,this._vertexCompilationState.target=NodeMaterialBlockTargets.Vertex,this._fragmentCompilationState=new NodeMaterialBuildState,this._fragmentCompilationState.supportUniformBuffers=c.supportsUniformBuffers,this._fragmentCompilationState.target=NodeMaterialBlockTargets.Fragment,this._sharedData=new NodeMaterialBuildStateSharedData,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=d;for(var _=[],b=[],k=0,j=this._vertexOutputNodes;k<j.length;k++){var $=j[k];_.push($),this._initializeBlock($,this._vertexCompilationState,b,s)}for(var _e=0,et=this._fragmentOutputNodes;_e<et.length;_e++){var tt=et[_e];b.push(tt),this._initializeBlock(tt,this._fragmentCompilationState,_,s)}this.optimize();for(var rt=0,it=_;rt<it.length;rt++){var $=it[rt];$.build(this._vertexCompilationState,_)}this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(var nt=0,ot=b;nt<ot.length;nt++){var tt=ot[nt];this._resetDualBlocks(tt,this._buildId-1)}for(var at=0,st=b;at<st.length;at++){var tt=st[at];tt.build(this._fragmentCompilationState,b)}this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),o&&(this._buildId=i._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);for(var ut=this.getScene().meshes,ft=0,lt=ut;ft<lt.length;ft++){var ht=lt[ft];if(!!ht.subMeshes)for(var pt=0,mt=ht.subMeshes;pt<mt.length;pt++){var dt=mt[pt];if(dt.getMaterial()===this&&!!dt.materialDefines){var gt=dt.materialDefines;gt.markAllAsDirty(),gt.reset()}}}},i.prototype.optimize=function(){for(var e=0,o=this._optimizers;e<o.length;e++){var s=o[e];s.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}},i.prototype._prepareDefinesForAttributes=function(e,o){var s=o.NORMAL,c=o.TANGENT;o.NORMAL=e.isVerticesDataPresent(VertexBuffer.NormalKind),o.TANGENT=e.isVerticesDataPresent(VertexBuffer.TangentKind);for(var d=!1,_=1;_<=6;++_){var b=o["UV"+_];o["UV"+_]=e.isVerticesDataPresent("uv"+(_===1?"":_)),d=d||o["UV"+_]!==b}(s!==o.NORMAL||c!==o.TANGENT||d)&&o.markAsAttributesDirty()},i.prototype.createPostProcess=function(e,o,s,c,d,_,b){return o===void 0&&(o=1),s===void 0&&(s=1),_===void 0&&(_=0),b===void 0&&(b=5),this.mode!==NodeMaterialModes.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,o,s,c,d,_,b)},i.prototype.createEffectForPostProcess=function(e){this._createEffectForPostProcess(e)},i.prototype._createEffectForPostProcess=function(e,o,s,c,d,_,b,k){var j=this;s===void 0&&(s=1),c===void 0&&(c=1),b===void 0&&(b=0),k===void 0&&(k=5);var $=this.name+this._buildId,_e=new NodeMaterialDefines,et=new AbstractMesh($+"PostProcess",this.getScene()),tt=this._buildId;return this._processDefines(et,_e),Effect$1.RegisterShader($,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(_e.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,$,$):e=new PostProcess(this.name+"PostProcess",$,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,s,o,c,d,_,_e.toString(),b,$,{maxSimultaneousLights:this.maxSimultaneousLights},!1,k),e.nodeMaterialSource=this,e.onApplyObservable.add(function(rt){tt!==j._buildId&&(delete Effect$1.ShadersStore[$+"VertexShader"],delete Effect$1.ShadersStore[$+"PixelShader"],$=j.name+j._buildId,_e.markAllAsDirty(),tt=j._buildId);var it=j._processDefines(et,_e);it&&(Effect$1.RegisterShader($,j._fragmentCompilationState._builtCompilationString,j._vertexCompilationState._builtCompilationString),TimingTools.SetImmediate(function(){return e.updateEffect(_e.toString(),j._fragmentCompilationState.uniforms,j._fragmentCompilationState.samplers,{maxSimultaneousLights:j.maxSimultaneousLights},void 0,void 0,$,$)})),j._checkInternals(rt)}),e},i.prototype.createProceduralTexture=function(e,o){var s=this;if(this.mode!==NodeMaterialModes.ProceduralTexture)return console.log("Incompatible material mode"),null;var c=this.name+this._buildId,d=new ProceduralTexture(c,e,null,o),_=new AbstractMesh(c+"Procedural",this.getScene());_.reservedDataStore={hidden:!0};var b=new NodeMaterialDefines,k=this._processDefines(_,b);Effect$1.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);var j=this.getScene().getEngine().createEffect({vertexElement:c,fragmentElement:c},[VertexBuffer.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,b.toString(),k==null?void 0:k.fallbacks,void 0);d.nodeMaterialSource=this,d._setEffect(j);var $=this._buildId;return d.onBeforeGenerationObservable.add(function(){$!==s._buildId&&(delete Effect$1.ShadersStore[c+"VertexShader"],delete Effect$1.ShadersStore[c+"PixelShader"],c=s.name+s._buildId,b.markAllAsDirty(),$=s._buildId);var _e=s._processDefines(_,b);_e&&(Effect$1.RegisterShader(c,s._fragmentCompilationState._builtCompilationString,s._vertexCompilationState._builtCompilationString),TimingTools.SetImmediate(function(){j=s.getScene().getEngine().createEffect({vertexElement:c,fragmentElement:c},[VertexBuffer.PositionKind],s._fragmentCompilationState.uniforms,s._fragmentCompilationState.samplers,b.toString(),_e==null?void 0:_e.fallbacks,void 0),d._setEffect(j)})),s._checkInternals(j)}),d},i.prototype._createEffectForParticles=function(e,o,s,c,d,_,b,k){var j=this;k===void 0&&(k="");var $=this.name+this._buildId+"_"+o;_||(_=new NodeMaterialDefines),b||(b=this.getScene().getMeshByName(this.name+"Particle"),b||(b=new AbstractMesh(this.name+"Particle",this.getScene()),b.reservedDataStore={hidden:!0}));var _e=this._buildId,et=[],tt=k;if(!d){var rt=this._processDefines(b,_);Effect$1.RegisterShader($,this._fragmentCompilationState._builtCompilationString),e.fillDefines(et,o),tt=et.join(`
  4609. `),d=this.getScene().getEngine().createEffectForParticles($,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,_.toString()+`
  4610. `+tt,rt==null?void 0:rt.fallbacks,s,c,e),e.setCustomEffect(d,o)}d.onBindObservable.add(function(it){_e!==j._buildId&&(delete Effect$1.ShadersStore[$+"PixelShader"],$=j.name+j._buildId+"_"+o,_.markAllAsDirty(),_e=j._buildId),et.length=0,e.fillDefines(et,o);var nt=et.join(`
  4611. `);nt!==tt&&(_.markAllAsDirty(),tt=nt);var ot=j._processDefines(b,_);if(ot){Effect$1.RegisterShader($,j._fragmentCompilationState._builtCompilationString),it=j.getScene().getEngine().createEffectForParticles($,j._fragmentCompilationState.uniforms,j._fragmentCompilationState.samplers,_.toString()+`
  4612. `+tt,ot==null?void 0:ot.fallbacks,s,c,e),e.setCustomEffect(it,o),j._createEffectForParticles(e,o,s,c,it,_,b,tt);return}j._checkInternals(it)})},i.prototype._checkInternals=function(e){if(this._sharedData.animatedInputs){var o=this.getScene(),s=o.getFrameId();if(this._animationFrame!==s){for(var c=0,d=this._sharedData.animatedInputs;c<d.length;c++){var _=d[c];_.animate(o)}this._animationFrame=s}}for(var b=0,k=this._sharedData.bindableBlocks;b<k.length;b++){var j=k[b];j.bind(e,this)}for(var $=0,_e=this._sharedData.inputBlocks;$<_e.length;$++){var et=_e[$];et._transmit(e,this.getScene())}},i.prototype.createEffectForParticles=function(e,o,s){if(this.mode!==NodeMaterialModes.Particle){console.log("Incompatible material mode");return}this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_ONEONE,o,s),this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_MULTIPLY,o,s)},i.prototype._processDefines=function(e,o,s,c){var d=this;s===void 0&&(s=!1);var _=null;if(this._sharedData.blocksWithDefines.forEach(function(et){et.initializeDefines(e,d,o,s)}),this._sharedData.blocksWithDefines.forEach(function(et){et.prepareDefines(e,d,o,s,c)}),o.isDirty){var b=o._areLightsDisposed;o.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(function(et){et.replaceRepeatableContent(d._vertexCompilationState,d._fragmentCompilationState,e,o)});var k=[];this._sharedData.dynamicUniformBlocks.forEach(function(et){et.updateUniformsAndSamples(d._vertexCompilationState,d,o,k)});var j=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(function(et){var tt=j.indexOf(et);tt===-1&&j.push(et)});var $=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(function(et){var tt=$.indexOf(et);tt===-1&&$.push(et)});var _e=new EffectFallbacks;this._sharedData.blocksWithFallbacks.forEach(function(et){et.provideFallbacks(e,_e)}),_={lightDisposed:b,uniformBuffers:k,mergedUniforms:j,mergedSamplers:$,fallbacks:_e}}return _},i.prototype.isReadyForSubMesh=function(e,o,s){var c=this;if(s===void 0&&(s=!1),!this._buildWasSuccessful)return!1;var d=this.getScene();if(this._sharedData.animatedInputs){var _=d.getFrameId();if(this._animationFrame!==_){for(var b=0,k=this._sharedData.animatedInputs;b<k.length;b++){var j=k[b];j.animate(d)}this._animationFrame=_}}if(o.effect&&this.isFrozen&&o.effect._wasPreviouslyReady)return!0;o.materialDefines||(o.materialDefines=new NodeMaterialDefines);var $=o.materialDefines;if(this._isReadyForSubMesh(o))return!0;var _e=d.getEngine();if(this._prepareDefinesForAttributes(e,$),this._sharedData.blockingBlocks.some(function(nt){return!nt.isReady(e,c,$,s)}))return!1;var et=this._processDefines(e,$,s,o);if(et){var tt=o.effect,rt=$.toString(),it=_e.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:et.mergedUniforms,uniformBuffersNames:et.uniformBuffers,samplers:et.mergedSamplers,defines:rt,fallbacks:et.fallbacks,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:$.NUM_MORPH_INFLUENCERS}},_e);if(it)if(this._onEffectCreatedObservable&&(onCreatedEffectParameters$1.effect=it,onCreatedEffectParameters$1.subMesh=o,this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$1)),this.allowShaderHotSwapping&&tt&&!it.isReady()){if(it=tt,$.markAsUnprocessed(),et.lightDisposed)return $._areLightsDisposed=!0,!1}else d.resetCachedMaterial(),o.setEffect(it,$,this._materialContext)}return!o.effect||!o.effect.isReady()?!1:($._renderId=d.getRenderId(),o.effect._wasPreviouslyReady=!0,!0)},Object.defineProperty(i.prototype,"compiledShaders",{get:function(){return`// Vertex shader\r
  4613. `+this._vertexCompilationState.compilationString+`\r
  4614. \r
  4615. // Fragment shader\r
  4616. `+this._fragmentCompilationState.compilationString},enumerable:!1,configurable:!0}),i.prototype.bindOnlyWorldMatrix=function(e){var o=this.getScene();if(!!this._activeEffect){var s=this._sharedData.hints;s.needWorldViewMatrix&&e.multiplyToRef(o.getViewMatrix(),this._cachedWorldViewMatrix),s.needWorldViewProjectionMatrix&&e.multiplyToRef(o.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(var c=0,d=this._sharedData.inputBlocks;c<d.length;c++){var _=d[c];_._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}}},i.prototype.bindForSubMesh=function(e,o,s){var c=this.getScene(),d=s.effect;if(!!d){this._activeEffect=d,this.bindOnlyWorldMatrix(e);var _=this._mustRebind(c,d,o.visibility),b=this._sharedData;if(_){if(d){for(var k=0,j=b.bindableBlocks;k<j.length;k++){var $=j[k];$.bind(d,this,o,s)}for(var _e=0,et=b.forcedBindableBlocks;_e<et.length;_e++){var $=et[_e];$.bind(d,this,o,s)}for(var tt=0,rt=b.inputBlocks;tt<rt.length;tt++){var it=rt[tt];it._transmit(d,c)}}}else if(!this.isFrozen)for(var nt=0,ot=b.forcedBindableBlocks;nt<ot.length;nt++){var $=ot[nt];$.bind(d,this,o,s)}this._afterBind(o,this._activeEffect)}},i.prototype.getActiveTextures=function(){var e=a.prototype.getActiveTextures.call(this);return this._sharedData&&e.push.apply(e,this._sharedData.textureBlocks.filter(function(o){return o.texture}).map(function(o){return o.texture})),e},i.prototype.getTextureBlocks=function(){return this._sharedData?this._sharedData.textureBlocks:[]},i.prototype.hasTexture=function(e){if(a.prototype.hasTexture.call(this,e))return!0;if(!this._sharedData)return!1;for(var o=0,s=this._sharedData.textureBlocks;o<s.length;o++){var c=s[o];if(c.texture===e)return!0}return!1},i.prototype.dispose=function(e,o,s){if(o&&this._sharedData)for(var c=0,d=this._sharedData.textureBlocks.filter(function($){return $.texture}).map(function($){return $.texture});c<d.length;c++){var _=d[c];_.dispose()}for(var b=0,k=this.attachedBlocks;b<k.length;b++){var j=k[b];j.dispose()}this.attachedBlocks=[],this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.attachedBlocks=[],this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),a.prototype.dispose.call(this,e,o,s)},i.prototype._createNodeEditor=function(){this.BJSNODEMATERIALEDITOR.NodeEditor.Show({nodeMaterial:this})},i.prototype.edit=function(e){var o=this;return new Promise(function(s,c){if(o.BJSNODEMATERIALEDITOR=o.BJSNODEMATERIALEDITOR||o._getGlobalNodeMaterialEditor(),typeof o.BJSNODEMATERIALEDITOR=="undefined"){var d=e&&e.editorURL?e.editorURL:i.EditorURL;Tools.LoadScript(d,function(){o.BJSNODEMATERIALEDITOR=o.BJSNODEMATERIALEDITOR||o._getGlobalNodeMaterialEditor(),o._createNodeEditor(),s()})}else o._createNodeEditor(),s()})},i.prototype.clear=function(){this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[]},i.prototype.setToDefault=function(){this.clear(),this.editorData=null;var e=new InputBlock("Position");e.setAsAttribute("position");var o=new InputBlock("World");o.setAsSystemValue(NodeMaterialSystemValues.World);var s=new TransformBlock("WorldPos");e.connectTo(s),o.connectTo(s);var c=new InputBlock("ViewProjection");c.setAsSystemValue(NodeMaterialSystemValues.ViewProjection);var d=new TransformBlock("WorldPos * ViewProjectionTransform");s.connectTo(d),c.connectTo(d);var _=new VertexOutputBlock("VertexOutput");d.connectTo(_);var b=new InputBlock("color");b.value=new Color4(.8,.8,.8,1);var k=new FragmentOutputBlock("FragmentOutput");b.connectTo(k),this.addOutputNode(_),this.addOutputNode(k),this._mode=NodeMaterialModes.Material},i.prototype.setToDefaultPostProcess=function(){this.clear(),this.editorData=null;var e=new InputBlock("Position");e.setAsAttribute("position2d");var o=new InputBlock("Constant1");o.isConstant=!0,o.value=1;var s=new VectorMergerBlock("Position3D");e.connectTo(s),o.connectTo(s,{input:"w"});var c=new VertexOutputBlock("VertexOutput");s.connectTo(c);var d=new InputBlock("Scale");d.visibleInInspector=!0,d.value=new Vector2(1,1);var _=new RemapBlock("uv0");e.connectTo(_);var b=new MultiplyBlock("UV scale");_.connectTo(b),d.connectTo(b);var k=new CurrentScreenBlock("CurrentScreen");b.connectTo(k),k.texture=new Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());var j=new FragmentOutputBlock("FragmentOutput");k.connectTo(j,{output:"rgba"}),this.addOutputNode(c),this.addOutputNode(j),this._mode=NodeMaterialModes.PostProcess},i.prototype.setToDefaultProceduralTexture=function(){this.clear(),this.editorData=null;var e=new InputBlock("Position");e.setAsAttribute("position2d");var o=new InputBlock("Constant1");o.isConstant=!0,o.value=1;var s=new VectorMergerBlock("Position3D");e.connectTo(s),o.connectTo(s,{input:"w"});var c=new VertexOutputBlock("VertexOutput");s.connectTo(c);var d=new InputBlock("Time");d.value=0,d.min=0,d.max=0,d.isBoolean=!1,d.matrixMode=0,d.animationType=AnimatedInputBlockTypes.Time,d.isConstant=!1;var _=new InputBlock("Color3");_.value=new Color3(1,1,1),_.isConstant=!1;var b=new FragmentOutputBlock("FragmentOutput"),k=new VectorMergerBlock("VectorMerger");k.visibleInInspector=!1;var j=new TrigonometryBlock("Cos");j.operation=TrigonometryBlockOperations.Cos,e.connectTo(k),d.output.connectTo(j.input),j.output.connectTo(k.z),k.xyzOut.connectTo(b.rgb),this.addOutputNode(c),this.addOutputNode(b),this._mode=NodeMaterialModes.ProceduralTexture},i.prototype.setToDefaultParticle=function(){this.clear(),this.editorData=null;var e=new InputBlock("uv");e.setAsAttribute("particle_uv");var o=new ParticleTextureBlock("ParticleTexture");e.connectTo(o);var s=new InputBlock("Color");s.setAsAttribute("particle_color");var c=new MultiplyBlock("Texture * Color");o.connectTo(c),s.connectTo(c);var d=new ParticleRampGradientBlock("ParticleRampGradient");c.connectTo(d);var _=new ColorSplitterBlock("ColorSplitter");s.connectTo(_);var b=new ParticleBlendMultiplyBlock("ParticleBlendMultiply");d.connectTo(b),o.connectTo(b,{output:"a"}),_.connectTo(b,{output:"a"});var k=new FragmentOutputBlock("FragmentOutput");b.connectTo(k),this.addOutputNode(k),this._mode=NodeMaterialModes.Particle},i.prototype.loadAsync=function(e){var o=this;return this.getScene()._loadFileAsync(e).then(function(s){var c=JSON.parse(s);o.loadFromSerialization(c,"")})},i.prototype._gatherBlocks=function(e,o){if(o.indexOf(e)===-1){o.push(e);for(var s=0,c=e.inputs;s<c.length;s++){var d=c[s],_=d.connectedPoint;if(_){var b=_.ownerBlock;b!==e&&this._gatherBlocks(b,o)}}}},i.prototype.generateCode=function(){for(var e=[],o=[],s=["const","var","let"],c=0,d=this._vertexOutputNodes;c<d.length;c++){var _=d[c];this._gatherBlocks(_,o)}for(var b=[],k=0,j=this._fragmentOutputNodes;k<j.length;k++){var _=j[k];this._gatherBlocks(_,b)}for(var $='var nodeMaterial = new BABYLON.NodeMaterial("'+(this.name||"node material")+`");\r
  4617. `,_e=0,et=o;_e<et.length;_e++){var tt=et[_e];tt.isInput&&e.indexOf(tt)===-1&&($+=tt._dumpCode(s,e))}for(var rt=0,it=b;rt<it.length;rt++){var tt=it[rt];tt.isInput&&e.indexOf(tt)===-1&&($+=tt._dumpCode(s,e))}e=[],$+=`\r
  4618. // Connections\r
  4619. `;for(var nt=0,ot=this._vertexOutputNodes;nt<ot.length;nt++){var tt=ot[nt];$+=tt._dumpCodeForOutputConnections(e)}for(var at=0,st=this._fragmentOutputNodes;at<st.length;at++){var tt=st[at];$+=tt._dumpCodeForOutputConnections(e)}$+=`\r
  4620. // Output nodes\r
  4621. `;for(var ut=0,ft=this._vertexOutputNodes;ut<ft.length;ut++){var tt=ft[ut];$+="nodeMaterial.addOutputNode("+tt._codeVariableName+`);\r
  4622. `}for(var lt=0,ht=this._fragmentOutputNodes;lt<ht.length;lt++){var tt=ht[lt];$+="nodeMaterial.addOutputNode("+tt._codeVariableName+`);\r
  4623. `}return $+=`nodeMaterial.build();\r
  4624. `,$},i.prototype.serialize=function(e){var o=e?{}:SerializationHelper.Serialize(this);o.editorData=JSON.parse(JSON.stringify(this.editorData));var s=[];if(e)s=e;else{o.customType="BABYLON.NodeMaterial",o.outputNodes=[];for(var c=0,d=this._vertexOutputNodes;c<d.length;c++){var _=d[c];this._gatherBlocks(_,s),o.outputNodes.push(_.uniqueId)}for(var b=0,k=this._fragmentOutputNodes;b<k.length;b++){var _=k[b];this._gatherBlocks(_,s),o.outputNodes.indexOf(_.uniqueId)===-1&&o.outputNodes.push(_.uniqueId)}}o.blocks=[];for(var j=0,$=s;j<$.length;j++){var _e=$[j];o.blocks.push(_e.serialize())}if(!e)for(var et=0,tt=this.attachedBlocks;et<tt.length;et++){var _e=tt[et];s.indexOf(_e)===-1&&o.blocks.push(_e.serialize())}return o},i.prototype._restoreConnections=function(e,o,s){for(var c=0,d=e.outputs;c<d.length;c++)for(var _=d[c],b=0,k=o.blocks;b<k.length;b++){var j=k[b],$=s[j.id];if(!!$)for(var _e=0,et=j.inputs;_e<et.length;_e++){var tt=et[_e];if(s[tt.targetBlockId]===e&&tt.targetConnectionName===_.name){var rt=$.getInputByName(tt.inputName);if(!rt||rt.isConnected)continue;_.connectTo(rt,!0),this._restoreConnections($,o,s);continue}}}},i.prototype.loadFromSerialization=function(e,o,s){var c;o===void 0&&(o=""),s===void 0&&(s=!1),s||this.clear();for(var d={},_=0,b=e.blocks;_<b.length;_++){var k=b[_],j=GetClass(k.customType);if(j){var $=new j;$._deserialize(k,this.getScene(),o),d[k.id]=$,this.attachedBlocks.push($)}}for(var _e=0;_e<e.blocks.length;_e++){var et=e.blocks[_e],$=d[et.id];!$||$.inputs.length&&!s||this._restoreConnections($,e,d)}if(e.outputNodes)for(var tt=0,rt=e.outputNodes;tt<rt.length;tt++){var it=rt[tt];this.addOutputNode(d[it])}if(e.locations||e.editorData&&e.editorData.locations){for(var nt=e.locations||e.editorData.locations,ot=0,at=nt;ot<at.length;ot++){var st=at[ot];d[st.blockId]&&(st.blockId=d[st.blockId].uniqueId)}s&&this.editorData&&this.editorData.locations&&nt.concat(this.editorData.locations),e.locations?this.editorData={locations:nt}:(this.editorData=e.editorData,this.editorData.locations=nt);var ut=[];for(var ft in d)ut[ft]=d[ft].uniqueId;this.editorData.map=ut}this.comment=e.comment,s||(this._mode=(c=e.mode)!==null&&c!==void 0?c:NodeMaterialModes.Material)},i.prototype.clone=function(e,o){var s=this;o===void 0&&(o=!1);var c=this.serialize(),d=SerializationHelper.Clone(function(){return new i(e,s.getScene(),s.options)},this);return d.id=e,d.name=e,d.loadFromSerialization(c),d._buildId=this._buildId,d.build(!1,!o),d},i.Parse=function(e,o,s){s===void 0&&(s="");var c=SerializationHelper.Parse(function(){return new i(e.name,o)},e,o,s);return c.loadFromSerialization(e,s),c.build(),c},i.ParseFromFileAsync=function(e,o,s){var c=new i(e,s);return new Promise(function(d,_){return c.loadAsync(o).then(function(){c.build(),d(c)}).catch(_)})},i.ParseFromSnippetAsync=function(e,o,s,c){var d=this;return s===void 0&&(s=""),e==="_BLANK"?Promise.resolve(this.CreateDefault("blank",o)):new Promise(function(_,b){var k=new WebRequest;k.addEventListener("readystatechange",function(){if(k.readyState==4)if(k.status==200){var j=JSON.parse(JSON.parse(k.responseText).jsonPayload),$=JSON.parse(j.nodeMaterial);c||(c=SerializationHelper.Parse(function(){return new i(e,o)},$,o,s),c.uniqueId=o.getUniqueId()),c.loadFromSerialization($),c.snippetId=e;try{c.build(),_(c)}catch(_e){b(_e)}}else b("Unable to load the snippet "+e)}),k.open("GET",d.SnippetUrl+"/"+e.replace(/#/g,"/")),k.send()})},i.CreateDefault=function(e,o){var s=new i(e,o);return s.setToDefault(),s.build(),s},i._BuildIdGenerator=0,i.EditorURL="https://unpkg.com/babylonjs-node-editor@"+Engine.Version+"/babylon.nodeEditor.js",i.SnippetUrl="https://snippet.babylonjs.com",i.IgnoreTexturesAtLoadTime=!1,__decorate([serialize()],i.prototype,"ignoreAlpha",void 0),__decorate([serialize()],i.prototype,"maxSimultaneousLights",void 0),__decorate([serialize("mode")],i.prototype,"_mode",void 0),__decorate([serialize("comment")],i.prototype,"comment",void 0),i}(PushMaterial);RegisterClass("BABYLON.NodeMaterial",NodeMaterial);var BonesBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Vertex)||this;return o.registerInput("matricesIndices",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("matricesWeights",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("matricesIndicesExtra",NodeMaterialBlockConnectionPointTypes.Vector4,!0),o.registerInput("matricesWeightsExtra",NodeMaterialBlockConnectionPointTypes.Vector4,!0),o.registerInput("world",NodeMaterialBlockConnectionPointTypes.Matrix),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.initialize=function(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")},i.prototype.getClassName=function(){return"BonesBlock"},Object.defineProperty(i.prototype,"matricesIndices",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"matricesWeights",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"matricesIndicesExtra",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"matricesWeightsExtra",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"world",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.matricesIndices.isConnected){var o=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="matricesIndices"});o||(o=new InputBlock("matricesIndices"),o.setAsAttribute("matricesIndices")),o.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){var s=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="matricesWeights"});s||(s=new InputBlock("matricesWeights"),s.setAsAttribute("matricesWeights")),s.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){var c=e.getInputBlockByPredicate(function(d){return d.systemValue===NodeMaterialSystemValues.World});c||(c=new InputBlock("world"),c.setAsSystemValue(NodeMaterialSystemValues.World)),c.output.connectTo(this.world)}},i.prototype.provideFallbacks=function(e,o){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&o.addCPUSkinningFallback(0,e)},i.prototype.bind=function(e,o,s){MaterialHelper.BindBonesParameters(s,e)},i.prototype.prepareDefines=function(e,o,s){!s._areAttributesDirty||MaterialHelper.PrepareDefinesForBones(e,s)},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");var o="//"+this.name;e._emitFunctionFromInclude("bonesDeclaration",o,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});var s=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",o,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:s}]});var c=this._outputs[0],d=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0\r
  4625. `,e.compilationString+=this._declareOutput(c,e)+(" = "+d.associatedVariableName+" * "+s+`;\r
  4626. `),e.compilationString+=`#else\r
  4627. `,e.compilationString+=this._declareOutput(c,e)+(" = "+d.associatedVariableName+`;\r
  4628. `),e.compilationString+=`#endif\r
  4629. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.BonesBlock",BonesBlock);var InstancesBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Vertex)||this;return o.registerInput("world0",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("world1",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("world2",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("world3",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("world",NodeMaterialBlockConnectionPointTypes.Matrix,!0),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Matrix),o.registerOutput("instanceID",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"InstancesBlock"},Object.defineProperty(i.prototype,"world0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"world1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"world2",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"world3",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"world",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"instanceID",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.world0.connectedPoint){var o=e.getInputBlockByPredicate(function(b){return b.isAttribute&&b.name==="world0"});o||(o=new InputBlock("world0"),o.setAsAttribute("world0")),o.output.connectTo(this.world0)}if(!this.world1.connectedPoint){var s=e.getInputBlockByPredicate(function(b){return b.isAttribute&&b.name==="world1"});s||(s=new InputBlock("world1"),s.setAsAttribute("world1")),s.output.connectTo(this.world1)}if(!this.world2.connectedPoint){var c=e.getInputBlockByPredicate(function(b){return b.isAttribute&&b.name==="world2"});c||(c=new InputBlock("world2"),c.setAsAttribute("world2")),c.output.connectTo(this.world2)}if(!this.world3.connectedPoint){var d=e.getInputBlockByPredicate(function(b){return b.isAttribute&&b.name==="world3"});d||(d=new InputBlock("world3"),d.setAsAttribute("world3")),d.output.connectTo(this.world3)}if(!this.world.connectedPoint){var _=e.getInputBlockByPredicate(function(b){return b.isAttribute&&b.name==="world"});_||(_=new InputBlock("world"),_.setAsSystemValue(NodeMaterialSystemValues.World)),_.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"},i.prototype.prepareDefines=function(e,o,s,c,d){c===void 0&&(c=!1);var _=!1;s.INSTANCES!==c&&(s.setValue("INSTANCES",c),_=!0),d&&s.THIN_INSTANCES!==!!(d!=null&&d.getRenderingMesh().hasThinInstances)&&(s.setValue("THIN_INSTANCES",!!(d!=null&&d.getRenderingMesh().hasThinInstances)),_=!0),_&&s.markAsUnprocessed()},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);var s=this._outputs[0],c=this._outputs[1],d=this.world0,_=this.world1,b=this.world2,k=this.world3;return e.compilationString+=`#ifdef INSTANCES\r
  4630. `,e.compilationString+=this._declareOutput(s,e)+(" = mat4("+d.associatedVariableName+", "+_.associatedVariableName+", "+b.associatedVariableName+", "+k.associatedVariableName+`);\r
  4631. `),e.compilationString+=`#ifdef THIN_INSTANCES\r
  4632. `,e.compilationString+=s.associatedVariableName+" = "+this.world.associatedVariableName+" * "+s.associatedVariableName+`;\r
  4633. `,e.compilationString+=`#endif\r
  4634. `,o._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(c,e)+` = float(gl_InstanceID);\r
  4635. `:e.compilationString+=this._declareOutput(c,e)+` = 0.0;\r
  4636. `,e.compilationString+=`#else\r
  4637. `,e.compilationString+=this._declareOutput(s,e)+(" = "+this.world.associatedVariableName+`;\r
  4638. `),e.compilationString+=this._declareOutput(c,e)+` = 0.0;\r
  4639. `,e.compilationString+=`#endif\r
  4640. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.InstancesBlock",InstancesBlock);var MorphTargetsBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Vertex)||this;return o.registerInput("position",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("normal",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("tangent",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("positionOutput",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("normalOutput",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("tangentOutput",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("uvOutput",NodeMaterialBlockConnectionPointTypes.Vector2),o}return i.prototype.getClassName=function(){return"MorphTargetsBlock"},Object.defineProperty(i.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tangent",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"positionOutput",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"normalOutput",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tangentOutput",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uvOutput",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),i.prototype.initialize=function(e){e._excludeVariableName("morphTargetInfluences")},i.prototype.autoConfigure=function(e){if(!this.position.isConnected){var o=e.getInputBlockByPredicate(function(_){return _.isAttribute&&_.name==="position"});o||(o=new InputBlock("position"),o.setAsAttribute()),o.output.connectTo(this.position)}if(!this.normal.isConnected){var s=e.getInputBlockByPredicate(function(_){return _.isAttribute&&_.name==="normal"});s||(s=new InputBlock("normal"),s.setAsAttribute("normal")),s.output.connectTo(this.normal)}if(!this.tangent.isConnected){var c=e.getInputBlockByPredicate(function(_){return _.isAttribute&&_.name==="tangent"});c||(c=new InputBlock("tangent"),c.setAsAttribute("tangent")),c.output.connectTo(this.tangent)}if(!this.uv.isConnected){var d=e.getInputBlockByPredicate(function(_){return _.isAttribute&&_.name==="uv"});d||(d=new InputBlock("uv"),d.setAsAttribute("uv")),d.output.connectTo(this.uv)}},i.prototype.prepareDefines=function(e,o,s){if(e.morphTargetManager){var c=e.morphTargetManager;(c==null?void 0:c.isUsingTextureForTargets)&&c.numInfluencers!==s.NUM_MORPH_INFLUENCERS&&s.markAsAttributesDirty()}!s._areAttributesDirty||MaterialHelper.PrepareDefinesForMorphTargets(e,s)},i.prototype.bind=function(e,o,s){s&&s.morphTargetManager&&s.morphTargetManager.numInfluencers>0&&(MaterialHelper.BindMorphTargetParameters(s,e),s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(e))},i.prototype.replaceRepeatableContent=function(e,o,s,c){var d=this.position,_=this.normal,b=this.tangent,k=this.uv,j=this.positionOutput,$=this.normalOutput,_e=this.tangentOutput,et=this.uvOutput,tt=e,rt=c.NUM_MORPH_INFLUENCERS,it=s.morphTargetManager,nt=it&&it.supportsNormals&&c.NORMAL,ot=it&&it.supportsTangents&&c.TANGENT,at=it&&it.supportsUVs&&c.UV1,st="";(it==null?void 0:it.isUsingTextureForTargets)&&rt>0&&(st+=`float vertexID;\r
  4641. `);for(var ut=0;ut<rt;ut++)st+=`#ifdef MORPHTARGETS\r
  4642. `,it!=null&&it.isUsingTextureForTargets?(st+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\r
  4643. `,st+=j.associatedVariableName+" += (readVector3FromRawSampler("+ut+", vertexID) - "+d.associatedVariableName+") * morphTargetInfluences["+ut+`];\r
  4644. `,st+=`vertexID += 1.0;\r
  4645. `):st+=j.associatedVariableName+" += (position"+ut+" - "+d.associatedVariableName+") * morphTargetInfluences["+ut+`];\r
  4646. `,nt&&(st+=`#ifdef MORPHTARGETS_NORMAL\r
  4647. `,it!=null&&it.isUsingTextureForTargets?(st+=$.associatedVariableName+" += (readVector3FromRawSampler("+ut+", vertexID) - "+_.associatedVariableName+") * morphTargetInfluences["+ut+`];\r
  4648. `,st+=`vertexID += 1.0;\r
  4649. `):st+=$.associatedVariableName+" += (normal"+ut+" - "+_.associatedVariableName+") * morphTargetInfluences["+ut+`];\r
  4650. `,st+=`#endif\r
  4651. `),at&&(st+=`#ifdef MORPHTARGETS_UV\r
  4652. `,it!=null&&it.isUsingTextureForTargets?(st+=et.associatedVariableName+" += (readVector3FromRawSampler("+ut+", vertexID).xy - "+k.associatedVariableName+") * morphTargetInfluences["+ut+`];\r
  4653. `,st+=`vertexID += 1.0;\r
  4654. `):st+=et.associatedVariableName+".xy += (uv_"+ut+" - "+k.associatedVariableName+".xy) * morphTargetInfluences["+ut+`];\r
  4655. `,st+=`#endif\r
  4656. `),ot&&(st+=`#ifdef MORPHTARGETS_TANGENT\r
  4657. `,it!=null&&it.isUsingTextureForTargets?st+=_e.associatedVariableName+" += (readVector3FromRawSampler("+ut+", vertexID) - "+b.associatedVariableName+") * morphTargetInfluences["+ut+`];\r
  4658. `:st+=_e.associatedVariableName+".xyz += (tangent"+ut+" - "+b.associatedVariableName+".xyz) * morphTargetInfluences["+ut+`];\r
  4659. `,st+=`#endif\r
  4660. `),st+=`#endif\r
  4661. `;if(tt.compilationString=tt.compilationString.replace(this._repeatableContentAnchor,st),rt>0)for(var ut=0;ut<rt;ut++)tt.attributes.push(VertexBuffer.PositionKind+ut),nt&&tt.attributes.push(VertexBuffer.NormalKind+ut),ot&&tt.attributes.push(VertexBuffer.TangentKind+ut),at&&tt.attributes.push(VertexBuffer.UVKind+"_"+ut)},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);var o=this.position,s=this.normal,c=this.tangent,d=this.uv,_=this.positionOutput,b=this.normalOutput,k=this.tangentOutput,j=this.uvOutput,$="//"+this.name;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",$),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",$,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=this._declareOutput(_,e)+" = "+o.associatedVariableName+`;\r
  4662. `,e.compilationString+=`#ifdef NORMAL\r
  4663. `,e.compilationString+=this._declareOutput(b,e)+" = "+s.associatedVariableName+`;\r
  4664. `,e.compilationString+=`#else\r
  4665. `,e.compilationString+=this._declareOutput(b,e)+` = vec3(0., 0., 0.);\r
  4666. `,e.compilationString+=`#endif\r
  4667. `,e.compilationString+=`#ifdef TANGENT\r
  4668. `,e.compilationString+=this._declareOutput(k,e)+" = "+c.associatedVariableName+`;\r
  4669. `,e.compilationString+=`#else\r
  4670. `,e.compilationString+=this._declareOutput(k,e)+` = vec3(0., 0., 0.);\r
  4671. `,e.compilationString+=`#endif\r
  4672. `,e.compilationString+=`#ifdef UV1\r
  4673. `,e.compilationString+=this._declareOutput(j,e)+" = "+d.associatedVariableName+`;\r
  4674. `,e.compilationString+=`#else\r
  4675. `,e.compilationString+=this._declareOutput(j,e)+` = vec2(0., 0.);\r
  4676. `,e.compilationString+=`#endif\r
  4677. `,this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.MorphTargetsBlock",MorphTargetsBlock);var LightInformationBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Vertex)||this;return o.registerInput("worldPosition",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Vertex),o.registerOutput("direction",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("color",NodeMaterialBlockConnectionPointTypes.Color3),o.registerOutput("intensity",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"LightInformationBlock"},Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"direction",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"color",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"intensity",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),i.prototype.bind=function(e,o,s){if(!!s){this.light&&this.light.isDisposed&&(this.light=null);var c=this.light,d=o.getScene();if(!c&&d.lights.length&&(c=this.light=d.lights[0],this._forcePrepareDefines=!0),!c||!c.isEnabled){e.setFloat3(this._lightDataUniformName,0,0,0),e.setFloat4(this._lightColorUniformName,0,0,0,0);return}c.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,c.diffuse,c.intensity)}},i.prototype.prepareDefines=function(e,o,s){if(!(!s._areLightsDirty&&!this._forcePrepareDefines)){this._forcePrepareDefines=!1;var c=this.light;s.setValue(this._lightTypeDefineName,!!(c&&c instanceof PointLight),!0)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);var o=this.direction,s=this.color,c=this.intensity;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+="#ifdef "+this._lightTypeDefineName+`\r
  4678. `,e.compilationString+=this._declareOutput(o,e)+(" = normalize("+this.worldPosition.associatedVariableName+".xyz - "+this._lightDataUniformName+`);\r
  4679. `),e.compilationString+=`#else\r
  4680. `,e.compilationString+=this._declareOutput(o,e)+(" = "+this._lightDataUniformName+`;\r
  4681. `),e.compilationString+=`#endif\r
  4682. `,e.compilationString+=this._declareOutput(s,e)+(" = "+this._lightColorUniformName+`.rgb;\r
  4683. `),e.compilationString+=this._declareOutput(c,e)+(" = "+this._lightColorUniformName+`.a;\r
  4684. `),this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return this.light&&(e.lightId=this.light.id),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),e.lightId&&(this.light=o.getLightById(e.lightId))},i}(NodeMaterialBlock);RegisterClass("BABYLON.LightInformationBlock",LightInformationBlock);var ImageProcessingBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.convertInputToLinearSpace=!0,o.registerInput("color",NodeMaterialBlockConnectionPointTypes.Color4),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Color4),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o}return i.prototype.getClassName=function(){return"ImageProcessingBlock"},Object.defineProperty(i.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.initialize=function(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings")},i.prototype.isReady=function(e,o,s){return!(s._areImageProcessingDirty&&o.imageProcessingConfiguration&&!o.imageProcessingConfiguration.isReady())},i.prototype.prepareDefines=function(e,o,s){s._areImageProcessingDirty&&o.imageProcessingConfiguration&&o.imageProcessingConfiguration.prepareDefines(s)},i.prototype.bind=function(e,o,s){!s||!o.imageProcessingConfiguration||o.imageProcessingConfiguration.bind(e)},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings");var o=this.color,s=this._outputs[0],c="//"+this.name;return e._emitFunctionFromInclude("helperFunctions",c),e._emitFunctionFromInclude("imageProcessingDeclaration",c),e._emitFunctionFromInclude("imageProcessingFunctions",c),o.connectedPoint.type===NodeMaterialBlockConnectionPointTypes.Color4||o.connectedPoint.type===NodeMaterialBlockConnectionPointTypes.Vector4?e.compilationString+=this._declareOutput(s,e)+" = "+o.associatedVariableName+`;\r
  4685. `:e.compilationString+=this._declareOutput(s,e)+" = vec4("+o.associatedVariableName+`, 1.0);\r
  4686. `,e.compilationString+=`#ifdef IMAGEPROCESSINGPOSTPROCESS\r
  4687. `,this.convertInputToLinearSpace&&(e.compilationString+=s.associatedVariableName+".rgb = toLinearSpace("+o.associatedVariableName+`.rgb);\r
  4688. `),e.compilationString+=`#else\r
  4689. `,e.compilationString+=`#ifdef IMAGEPROCESSING\r
  4690. `,this.convertInputToLinearSpace&&(e.compilationString+=s.associatedVariableName+".rgb = toLinearSpace("+o.associatedVariableName+`.rgb);\r
  4691. `),e.compilationString+=s.associatedVariableName+" = applyImageProcessing("+s.associatedVariableName+`);\r
  4692. `,e.compilationString+=`#endif\r
  4693. `,e.compilationString+=`#endif\r
  4694. `,this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".convertInputToLinearSpace = "+this.convertInputToLinearSpace+`;\r
  4695. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e},i.prototype._deserialize=function(e,o,s){var c;a.prototype._deserialize.call(this,e,o,s),this.convertInputToLinearSpace=(c=e.convertInputToLinearSpace)!==null&&c!==void 0?c:!0},__decorate([editableInPropertyPage("Convert input to linear space",PropertyTypeForEdition.Boolean,"ADVANCED")],i.prototype,"convertInputToLinearSpace",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.ImageProcessingBlock",ImageProcessingBlock);var PerturbNormalBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o._tangentSpaceParameterName="",o.invertX=!1,o.invertY=!1,o.useParallaxOcclusion=!1,o._isUnique=!0,o.registerInput("worldPosition",NodeMaterialBlockConnectionPointTypes.Vector4,!1),o.registerInput("worldNormal",NodeMaterialBlockConnectionPointTypes.Vector4,!1),o.registerInput("worldTangent",NodeMaterialBlockConnectionPointTypes.Vector4,!0),o.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2,!1),o.registerInput("normalMapColor",NodeMaterialBlockConnectionPointTypes.Color3,!1),o.registerInput("strength",NodeMaterialBlockConnectionPointTypes.Float,!1),o.registerInput("viewDirection",NodeMaterialBlockConnectionPointTypes.Vector3,!0),o.registerInput("parallaxScale",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("parallaxHeight",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerOutput("uvOffset",NodeMaterialBlockConnectionPointTypes.Vector2),o}return i.prototype.getClassName=function(){return"PerturbNormalBlock"},Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldTangent",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"normalMapColor",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"strength",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"viewDirection",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"parallaxScale",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"parallaxHeight",{get:function(){return this._inputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uvOffset",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),i.prototype.prepareDefines=function(e,o,s){var c=this.normalMapColor.connectedPoint._ownerBlock.samplerName,d=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&c||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);s.setValue("BUMP",!0),s.setValue("PARALLAX",d,!0),s.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0)},i.prototype.bind=function(e,o,s){o.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1)},i.prototype.autoConfigure=function(e){if(!this.uv.isConnected){var o=e.getInputBlockByPredicate(function(c){return c.isAttribute&&c.name==="uv"});o||(o=new InputBlock("uv"),o.setAsAttribute()),o.output.connectTo(this.uv)}if(!this.strength.isConnected){var s=new InputBlock("strength");s.value=1,s.output.connectTo(this.strength)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o="//"+this.name,s=this.uv,c=this.worldPosition,d=this.worldNormal,_=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2");var b=this.normalMapColor.connectedPoint._ownerBlock.samplerName,k=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&b||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),j=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",$=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\r
  4696. #if !defined(NORMALXYSCALE)\r
  4697. 1.0/\r
  4698. #endif\r
  4699. `+e._emitFloat(this.strength.connectInputBlock.value):`\r
  4700. #if !defined(NORMALXYSCALE)\r
  4701. 1.0/\r
  4702. #endif\r
  4703. `+this.strength.associatedVariableName;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var _e={search:/defined\(TANGENT\)/g,replace:_.isConnected?"defined(TANGENT)":"defined(IGNORE)"};_.isConnected&&(e.compilationString+="vec3 tbnNormal = normalize("+d.associatedVariableName+`.xyz);\r
  4704. `,e.compilationString+="vec3 tbnTangent = normalize("+_.associatedVariableName+`.xyz);\r
  4705. `,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
  4706. `,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
  4707. `),e._emitFunctionFromInclude("bumpFragmentMainFunctions",o,{replaceStrings:[_e]}),e._emitFunctionFromInclude("bumpFragmentFunctions",o,{replaceStrings:[{search:/#include<samplerFragmentDeclaration>\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:`#define inline\r
  4708. vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)`},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});var et=!k||!b?this.normalMapColor.associatedVariableName:"texture2D("+b+", "+s.associatedVariableName+" + uvOffset).xyz";return e.compilationString+=this._declareOutput(this.output,e)+` = vec4(0.);\r
  4709. `,e.compilationString+=e._emitCodeFromInclude("bumpFragment",o,{replaceStrings:[{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:"perturbNormal(TBN, "+et+", vBumpInfos.y)"},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:"parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, "+(k&&this.useParallaxOcclusion?b:"bumpSampler")+")"},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:"parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, "+(k?this.parallaxHeight.associatedVariableName:"0.")+")"},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:$},{search:/vBumpInfos.z/g,replace:j},{search:/vBumpUV/g,replace:s.associatedVariableName},{search:/vPositionW/g,replace:c.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:d.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:k?this.viewDirection.associatedVariableName:"vec3(0.)"},_e]}),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".invertX = "+this.invertX+`;\r
  4710. `);return e+=this._codeVariableName+".invertY = "+this.invertY+`;\r
  4711. `,e+=this._codeVariableName+".useParallaxOcclusion = "+this.useParallaxOcclusion+`;\r
  4712. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion},__decorate([editableInPropertyPage("Invert X axis",PropertyTypeForEdition.Boolean,"PROPERTIES",{notifiers:{update:!1}})],i.prototype,"invertX",void 0),__decorate([editableInPropertyPage("Invert Y axis",PropertyTypeForEdition.Boolean,"PROPERTIES",{notifiers:{update:!1}})],i.prototype,"invertY",void 0),__decorate([editableInPropertyPage("Use parallax occlusion",PropertyTypeForEdition.Boolean)],i.prototype,"useParallaxOcclusion",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.PerturbNormalBlock",PerturbNormalBlock);var DiscardBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment,!0)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("cutoff",NodeMaterialBlockConnectionPointTypes.Float,!0),o}return i.prototype.getClassName=function(){return"DiscardBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cutoff",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.sharedData.hints.needAlphaTesting=!0,!(!this.cutoff.isConnected||!this.value.isConnected))return e.compilationString+="if ("+this.value.associatedVariableName+" < "+this.cutoff.associatedVariableName+`) discard;\r
  4713. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.DiscardBlock",DiscardBlock);var FrontFacingBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o}return i.prototype.getClassName=function(){return"FrontFacingBlock"},Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.target===NodeMaterialBlockTargets.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+` = gl_FrontFacing ? 1.0 : 0.0;\r
  4714. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.FrontFacingBlock",FrontFacingBlock);var DerivativeBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect,!1),o.registerOutput("dx",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o.registerOutput("dy",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._outputs[1]._typeConnectionSource=o._inputs[0],o}return i.prototype.getClassName=function(){return"DerivativeBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dx",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dy",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+(" = dFdx("+this.input.associatedVariableName+`);\r
  4715. `)),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+(" = dFdy("+this.input.associatedVariableName+`);\r
  4716. `)),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.DerivativeBlock",DerivativeBlock);var FragCoordBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.registerOutput("xy",NodeMaterialBlockConnectionPointTypes.Vector2,NodeMaterialBlockTargets.Fragment),o.registerOutput("xyz",NodeMaterialBlockConnectionPointTypes.Vector3,NodeMaterialBlockTargets.Fragment),o.registerOutput("xyzw",NodeMaterialBlockConnectionPointTypes.Vector4,NodeMaterialBlockTargets.Fragment),o.registerOutput("x",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("y",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("z",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("w",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o}return i.prototype.getClassName=function(){return"FragCoordBlock"},Object.defineProperty(i.prototype,"xy",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyz",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyzw",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"x",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"z",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),i.prototype.writeOutputs=function(e){for(var o="",s=0,c=this._outputs;s<c.length;s++){var d=c[s];d.hasEndpoints&&(o+=this._declareOutput(d,e)+" = gl_FragCoord."+d.name+`;\r
  4717. `)}return o},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.target===NodeMaterialBlockTargets.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.FragCoordBlock",FragCoordBlock);var ScreenSizeBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.registerOutput("xy",NodeMaterialBlockConnectionPointTypes.Vector2,NodeMaterialBlockTargets.Fragment),o.registerOutput("x",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("y",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o}return i.prototype.getClassName=function(){return"ScreenSizeBlock"},Object.defineProperty(i.prototype,"xy",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),i.prototype.bind=function(e,o,s){var c=this._scene.getEngine();e.setFloat2(this._varName,c.getRenderWidth(),c.getRenderHeight())},i.prototype.writeOutputs=function(e,o){for(var s="",c=0,d=this._outputs;c<d.length;c++){var _=d[c];_.hasEndpoints&&(s+=this._declareOutput(_,e)+" = "+o+"."+_.name+`;\r
  4718. `)}return s},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),this._scene=e.sharedData.scene,e.target===NodeMaterialBlockTargets.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ScreenSizeBlock",ScreenSizeBlock);var ScreenSpaceBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.registerInput("vector",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("worldViewProjection",NodeMaterialBlockConnectionPointTypes.Matrix),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("x",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("y",NodeMaterialBlockConnectionPointTypes.Float),o.inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o}return i.prototype.getClassName=function(){return"ScreenSpaceBlock"},Object.defineProperty(i.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldViewProjection",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.worldViewProjection.isConnected){var o=e.getInputBlockByPredicate(function(s){return s.systemValue===NodeMaterialSystemValues.WorldViewProjection});o||(o=new InputBlock("worldViewProjection"),o.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection)),o.output.connectTo(this.worldViewProjection)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.vector,s=this.worldViewProjection;if(!!o.connectedPoint){var c=s.associatedVariableName,d=e._getFreeVariableName("screenSpaceTemp");switch(o.connectedPoint.type){case NodeMaterialBlockConnectionPointTypes.Vector3:e.compilationString+="vec4 "+d+" = "+c+" * vec4("+o.associatedVariableName+`, 1.0);\r
  4719. `;break;case NodeMaterialBlockConnectionPointTypes.Vector4:e.compilationString+="vec4 "+d+" = "+c+" * "+o.associatedVariableName+`;\r
  4720. `;break}return e.compilationString+=d+".xy /= "+d+".w;",e.compilationString+=d+".xy = "+d+".xy * 0.5 + vec2(0.5, 0.5);",this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+(" = "+d+`.xy;\r
  4721. `)),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+(" = "+d+`.x;\r
  4722. `)),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+(" = "+d+`.y;\r
  4723. `)),this}},i}(NodeMaterialBlock);RegisterClass("BABYLON.ScreenSpaceBlock",ScreenSpaceBlock);var TwirlBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.registerInput("input",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerInput("strength",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("center",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerInput("offset",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("x",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("y",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"TwirlBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"strength",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"center",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"offset",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.center.isConnected){var o=new InputBlock("center");o.value=new Vector2(.5,.5),o.output.connectTo(this.center)}if(!this.strength.isConnected){var s=new InputBlock("strength");s.value=1,s.output.connectTo(this.strength)}if(!this.offset.isConnected){var c=new InputBlock("offset");c.value=new Vector2(0,0),c.output.connectTo(this.offset)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=e._getFreeVariableName("delta"),s=e._getFreeVariableName("angle"),c=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),_=e._getFreeVariableName("result");return e.compilationString+=`
  4724. vec2 `+o+" = "+this.input.associatedVariableName+" - "+this.center.associatedVariableName+`;
  4725. float `+s+" = "+this.strength.associatedVariableName+" * length("+o+`);
  4726. float `+c+" = cos("+s+") * "+o+".x - sin("+s+") * "+o+`.y;
  4727. float `+d+" = sin("+s+") * "+o+".x + cos("+s+") * "+o+`.y;
  4728. vec2 `+_+" = vec2("+c+" + "+this.center.associatedVariableName+".x + "+this.offset.associatedVariableName+".x, "+d+" + "+this.center.associatedVariableName+".y + "+this.offset.associatedVariableName+`.y);
  4729. `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+(" = "+_+`;\r
  4730. `)),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+(" = "+_+`.x;\r
  4731. `)),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+(" = "+_+`.y;\r
  4732. `)),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.TwirlBlock",TwirlBlock);var FogBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.VertexAndFragment,!1)||this;return o.registerInput("worldPosition",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("view",NodeMaterialBlockConnectionPointTypes.Matrix,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("input",NodeMaterialBlockConnectionPointTypes.Color3,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("fogColor",NodeMaterialBlockConnectionPointTypes.Color3,!1,NodeMaterialBlockTargets.Fragment),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.input.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o.fogColor.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o}return i.prototype.getClassName=function(){return"FogBlock"},Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"view",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"fogColor",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.view.isConnected){var o=e.getInputBlockByPredicate(function(c){return c.systemValue===NodeMaterialSystemValues.View});o||(o=new InputBlock("view"),o.setAsSystemValue(NodeMaterialSystemValues.View)),o.output.connectTo(this.view)}if(!this.fogColor.isConnected){var s=e.getInputBlockByPredicate(function(c){return c.systemValue===NodeMaterialSystemValues.FogColor});s||(s=new InputBlock("fogColor",void 0,NodeMaterialBlockConnectionPointTypes.Color3),s.setAsSystemValue(NodeMaterialSystemValues.FogColor)),s.output.connectTo(this.fogColor)}},i.prototype.prepareDefines=function(e,o,s){var c=e.getScene();s.setValue("FOG",o.fogEnabled&&MaterialHelper.GetFogState(e,c))},i.prototype.bind=function(e,o,s){if(!!s){var c=s.getScene();e.setFloat4(this._fogParameters,c.fogMode,c.fogStart,c.fogEnd,c.fogDensity)}},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.target===NodeMaterialBlockTargets.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration","//"+this.name,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});var o=e._getFreeVariableName("fog"),s=this.input,c=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");var d=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG\r
  4733. `,e.compilationString+="float "+o+" = CalcFogFactor("+this._fogDistanceName+", "+this._fogParameters+`);\r
  4734. `,e.compilationString+=this._declareOutput(d,e)+(" = "+o+" * "+s.associatedVariableName+".rgb + (1.0 - "+o+") * "+c.associatedVariableName+`.rgb;\r
  4735. `),e.compilationString+=`#else\r
  4736. `+this._declareOutput(d,e)+" = "+s.associatedVariableName+`.rgb;\r
  4737. `,e.compilationString+=`#endif\r
  4738. `}else{var _=this.worldPosition,b=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=this._fogDistanceName+" = ("+b.associatedVariableName+" * "+_.associatedVariableName+`).xyz;\r
  4739. `}return this},i}(NodeMaterialBlock);RegisterClass("BABYLON.FogBlock",FogBlock);var LightBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.VertexAndFragment)||this;return o._isUnique=!0,o.registerInput("worldPosition",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("worldNormal",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("cameraPosition",NodeMaterialBlockConnectionPointTypes.Vector3,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("glossiness",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("glossPower",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("diffuseColor",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("specularColor",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("view",NodeMaterialBlockConnectionPointTypes.Matrix,!0),o.registerOutput("diffuseOutput",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("specularOutput",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("shadow",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o}return i.prototype.getClassName=function(){return"LightBlock"},Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraPosition",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"glossiness",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"glossPower",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"diffuseColor",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"specularColor",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"view",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"diffuseOutput",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"specularOutput",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadow",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.cameraPosition.isConnected){var o=e.getInputBlockByPredicate(function(s){return s.systemValue===NodeMaterialSystemValues.CameraPosition});o||(o=new InputBlock("cameraPosition"),o.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),o.output.connectTo(this.cameraPosition)}},i.prototype.prepareDefines=function(e,o,s){if(!!s._areLightsDirty){var c=e.getScene();if(!this.light)MaterialHelper.PrepareDefinesForLights(c,e,s,!0,o.maxSimultaneousLights);else{var d={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};MaterialHelper.PrepareDefinesForLight(c,e,this.light,this._lightId,s,!0,d),d.needRebuild&&s.rebuild()}}},i.prototype.updateUniformsAndSamples=function(e,o,s,c){for(var d=0;d<o.maxSimultaneousLights&&s["LIGHT"+d];d++){var _=e.uniforms.indexOf("vLightData"+d)>=0;MaterialHelper.PrepareUniformsAndSamplersForLight(d,e.uniforms,e.samplers,s["PROJECTEDLIGHTTEXTURE"+d],c,_)}},i.prototype.bind=function(e,o,s){if(!!s){var c=s.getScene();this.light?MaterialHelper.BindLight(this.light,this._lightId,c,e,!0):MaterialHelper.BindLights(c,s,e,!0,o.maxSimultaneousLights)}},i.prototype._injectVertexCode=function(e){var o=this.worldPosition,s="//"+this.name;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));var c="v_"+o.associatedVariableName;e._emitVaryingFromString(c,"vec4")&&(e.compilationString+=c+" = "+o.associatedVariableName+`;\r
  4740. `),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:o.associatedVariableName}]}):(e.compilationString+="vec4 worldPos = "+o.associatedVariableName+`;\r
  4741. `,this.view.isConnected&&(e.compilationString+="mat4 view = "+this.view.associatedVariableName+`;\r
  4742. `),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),e.target!==NodeMaterialBlockTargets.Fragment){this._injectVertexCode(e);return}e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);var o="//"+this.name,s=this.worldPosition;e._emitFunctionFromInclude("helperFunctions",o),e._emitFunctionFromInclude("lightsFragmentFunctions",o,{replaceStrings:[{search:/vPositionW/g,replace:"v_"+s.associatedVariableName+".xyz"}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",o,{replaceStrings:[{search:/vPositionW/g,replace:"v_"+s.associatedVariableName+".xyz"}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",o,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",o,{repeatKey:"maxSimultaneousLights"}),this._lightId===0&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+="vec3 viewDirectionW = normalize("+this.cameraPosition.associatedVariableName+" - "+("v_"+s.associatedVariableName)+`.xyz);\r
  4743. `),e.compilationString+=`lightingInfo info;\r
  4744. `,e.compilationString+=`float shadow = 1.;\r
  4745. `,e.compilationString+="float glossiness = "+(this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0")+" * "+(this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0")+`;\r
  4746. `,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.);\r
  4747. `,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.);\r
  4748. `,e.compilationString+="vec3 normalW = "+this.worldNormal.associatedVariableName+`.xyz;\r
  4749. `),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",o,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",o,{repeatKey:"maxSimultaneousLights"});var c=this.diffuseOutput,d=this.specularOutput;return e.compilationString+=this._declareOutput(c,e)+(" = diffuseBase"+(this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:"")+`;\r
  4750. `),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+(" = specularBase"+(this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:"")+`;\r
  4751. `)),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = shadow;\r
  4752. `),this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return this.light&&(e.lightId=this.light.id),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),e.lightId&&(this.light=o.getLightById(e.lightId))},i}(NodeMaterialBlock);RegisterClass("BABYLON.LightBlock",LightBlock);var NodeMaterialConnectionPointCustomObject=function(a){__extends(i,a);function i(e,o,s,c,d,_){var b=a.call(this,e,o,s)||this;return b._blockType=c,b._blockName=d,b._nameForCheking=_,b._nameForCheking||(b._nameForCheking=e),b.needDualDirectionValidation=!0,b}return i.prototype.checkCompatibilityState=function(e){return e instanceof i&&e.name===this._nameForCheking?NodeMaterialConnectionPointCompatibilityStates.Compatible:NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible},i.prototype.createCustomInputBlock=function(){return[new this._blockType(this._blockName),this.name]},i}(NodeMaterialConnectionPoint),ImageSourceBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.VertexAndFragment)||this;return o.registerOutput("source",NodeMaterialBlockConnectionPointTypes.Object,NodeMaterialBlockTargets.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",o,NodeMaterialConnectionPointDirection.Output,i,"ImageSourceBlock")),o}return Object.defineProperty(i.prototype,"texture",{get:function(){return this._texture},set:function(e){var o=this,s;if(this._texture!==e){var c=(s=e==null?void 0:e.getScene())!==null&&s!==void 0?s:Engine.LastCreatedScene;!e&&c&&c.markAllMaterialsAsDirty(1,function(d){return d.hasTexture(o._texture)}),this._texture=e,e&&c&&c.markAllMaterialsAsDirty(1,function(d){return d.hasTexture(e)})}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"samplerName",{get:function(){return this._samplerName},enumerable:!1,configurable:!0}),i.prototype.bind=function(e,o,s){!this.texture||e.setTexture(this._samplerName,this.texture)},i.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},i.prototype.getClassName=function(){return"ImageSourceBlock"},Object.defineProperty(i.prototype,"source",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){return a.prototype._buildBlock.call(this,e),e.target===NodeMaterialBlockTargets.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return this.texture&&(e+=this._codeVariableName+'.texture = new BABYLON.Texture("'+this.texture.name+'", null, '+this.texture.noMipmap+", "+this.texture.invertY+", "+this.texture.samplingMode+`);\r
  4753. `,e+=this._codeVariableName+".texture.wrapU = "+this.texture.wrapU+`;\r
  4754. `,e+=this._codeVariableName+".texture.wrapV = "+this.texture.wrapV+`;\r
  4755. `,e+=this._codeVariableName+".texture.uAng = "+this.texture.uAng+`;\r
  4756. `,e+=this._codeVariableName+".texture.vAng = "+this.texture.vAng+`;\r
  4757. `,e+=this._codeVariableName+".texture.wAng = "+this.texture.wAng+`;\r
  4758. `,e+=this._codeVariableName+".texture.uOffset = "+this.texture.uOffset+`;\r
  4759. `,e+=this._codeVariableName+".texture.vOffset = "+this.texture.vOffset+`;\r
  4760. `,e+=this._codeVariableName+".texture.uScale = "+this.texture.uScale+`;\r
  4761. `,e+=this._codeVariableName+".texture.vScale = "+this.texture.vScale+`;\r
  4762. `,e+=this._codeVariableName+".texture.coordinatesMode = "+this.texture.coordinatesMode+`;\r
  4763. `),e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(s=e.texture.url.indexOf("data:")===0?"":s,this.texture=Texture.Parse(e.texture,o,s))},i}(NodeMaterialBlock);RegisterClass("BABYLON.ImageSourceBlock",ImageSourceBlock);var TextureBlock=function(a){__extends(i,a);function i(e,o){o===void 0&&(o=!1);var s=a.call(this,e,o?NodeMaterialBlockTargets.Fragment:NodeMaterialBlockTargets.VertexAndFragment)||this;return s.convertToGammaSpace=!1,s.convertToLinearSpace=!1,s.disableLevelMultiplication=!1,s._fragmentOnly=o,s.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2,!1,NodeMaterialBlockTargets.VertexAndFragment),s.registerInput("source",NodeMaterialBlockConnectionPointTypes.Object,!0,NodeMaterialBlockTargets.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",s,NodeMaterialConnectionPointDirection.Input,ImageSourceBlock,"ImageSourceBlock")),s.registerOutput("rgba",NodeMaterialBlockConnectionPointTypes.Color4,NodeMaterialBlockTargets.Neutral),s.registerOutput("rgb",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Neutral),s.registerOutput("r",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),s.registerOutput("g",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),s.registerOutput("b",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),s.registerOutput("a",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),s.registerOutput("level",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),s._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),s._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),s._inputs[0]._prioritizeVertex=!o,s}return Object.defineProperty(i.prototype,"texture",{get:function(){var e;return this.source.isConnected?((e=this.source.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:this._texture},set:function(e){var o=this,s;if(this._texture!==e){var c=(s=e==null?void 0:e.getScene())!==null&&s!==void 0?s:Engine.LastCreatedScene;!e&&c&&c.markAllMaterialsAsDirty(1,function(d){return d.hasTexture(o._texture)}),this._texture=e,e&&c&&c.markAllMaterialsAsDirty(1,function(d){return d.hasTexture(e)})}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"samplerName",{get:function(){return this._imageSource?this._imageSource.samplerName:this._samplerName},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasImageSource",{get:function(){return!!this._imageSource},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"TextureBlock"},Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"source",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"level",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"target",{get:function(){if(this._fragmentOnly)return NodeMaterialBlockTargets.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return NodeMaterialBlockTargets.VertexAndFragment;for(var e=this.uv.connectedPoint;e;){if(e.target===NodeMaterialBlockTargets.Fragment)return NodeMaterialBlockTargets.Fragment;if(e.target===NodeMaterialBlockTargets.Vertex)return NodeMaterialBlockTargets.VertexAndFragment;if(e.target===NodeMaterialBlockTargets.Neutral||e.target===NodeMaterialBlockTargets.VertexAndFragment){var o=e.ownerBlock;if(o.target===NodeMaterialBlockTargets.Fragment)return NodeMaterialBlockTargets.Fragment;e=null;for(var s=0,c=o.inputs;s<c.length;s++){var d=c[s];if(d.connectedPoint){e=d.connectedPoint;break}}}}return NodeMaterialBlockTargets.VertexAndFragment},set:function(e){},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.uv.isConnected)if(e.mode===NodeMaterialModes.PostProcess){var o=e.getBlockByPredicate(function(c){return c.name==="uv"});o&&o.connectTo(this)}else{var s=e.mode===NodeMaterialModes.Particle?"particle_uv":"uv",o=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name===s});o||(o=new InputBlock("uv"),o.setAsAttribute(s)),o.output.connectTo(this.uv)}},i.prototype.initializeDefines=function(e,o,s,c){!s._areTexturesDirty||this._mainUVDefineName!==void 0&&s.setValue(this._mainUVDefineName,!1,!0)},i.prototype.prepareDefines=function(e,o,s){if(!!s._areTexturesDirty){if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(s.setValue(this._defineName,!1,!0),s.setValue(this._mainUVDefineName,!0,!0));return}s.setValue(this._linearDefineName,this.convertToGammaSpace,!0),s.setValue(this._gammaDefineName,this.convertToLinearSpace,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(s.setValue(this._defineName,!1,!0),s.setValue(this._mainUVDefineName,!0,!0)):(s.setValue(this._defineName,!0),s[this._mainUVDefineName]==null&&s.setValue(this._mainUVDefineName,!1,!0)))}},i.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},i.prototype.bind=function(e,o,s){!this.texture||(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))},Object.defineProperty(i.prototype,"_isMixed",{get:function(){return this.target!==NodeMaterialBlockTargets.Fragment},enumerable:!1,configurable:!0}),i.prototype._injectVertexCode=function(e){var o=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+o.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+o.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+="#ifdef "+this._defineName+`\r
  4764. `,e.compilationString+=this._transformedUVName+" = vec2("+this._textureTransformName+" * vec4("+o.associatedVariableName+`.xy, 1.0, 0.0));\r
  4765. `,e.compilationString+="#elif defined("+this._mainUVDefineName+`)\r
  4766. `,e.compilationString+=this._mainUVName+" = "+o.associatedVariableName+`.xy;\r
  4767. `,e.compilationString+=`#endif\r
  4768. `,!!this._outputs.some(function(_){return _.isConnectedInVertexShader})){this._writeTextureRead(e,!0);for(var s=0,c=this._outputs;s<c.length;s++){var d=c[s];d.hasEndpoints&&d.name!=="level"&&this._writeOutput(e,d,d.name,!0)}}},i.prototype._generateTextureLookup=function(e){var o=this.samplerName;e.compilationString+="#ifdef "+this._defineName+`\r
  4769. `,e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+o+", "+this._transformedUVName+`);\r
  4770. `,e.compilationString+="#elif defined("+this._mainUVDefineName+`)\r
  4771. `,e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+o+", "+(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)+`);\r
  4772. `,e.compilationString+=`#endif\r
  4773. `},i.prototype._writeTextureRead=function(e,o){o===void 0&&(o=!1);var s=this.uv;if(o){if(e.target===NodeMaterialBlockTargets.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===NodeMaterialBlockTargets.Fragment){e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this.samplerName+", "+s.associatedVariableName+`);\r
  4774. `;return}this._generateTextureLookup(e)},i.prototype._generateConversionCode=function(e,o,s){s!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+="#ifdef "+this._linearDefineName+`
  4775. `+o.associatedVariableName+" = toGammaSpace("+o.associatedVariableName+`);
  4776. #endif
  4777. `),(!this.texture||this.texture.gammaSpace)&&(e.compilationString+="#ifdef "+this._gammaDefineName+`
  4778. `+o.associatedVariableName+" = toLinearSpace("+o.associatedVariableName+`);
  4779. #endif
  4780. `))},i.prototype._writeOutput=function(e,o,s,c){if(c===void 0&&(c=!1),c){if(e.target===NodeMaterialBlockTargets.Fragment)return;e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4781. `,this._generateConversionCode(e,o,s);return}if(this.uv.ownerBlock.target===NodeMaterialBlockTargets.Fragment){e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4782. `,this._generateConversionCode(e,o,s);return}var d="";this.disableLevelMultiplication||(d=" * "+this._textureInfoName),e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+d+`;\r
  4783. `,this._generateConversionCode(e,o,s)},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===NodeMaterialBlockTargets.Vertex||this._fragmentOnly||e.target===NodeMaterialBlockTargets.Fragment&&this._tempTextureRead===void 0)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===NodeMaterialBlockTargets.Fragment||this._isMixed&&e.target===NodeMaterialBlockTargets.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==NodeMaterialBlockTargets.Fragment){this._injectVertexCode(e);return}if(!!this._outputs.some(function(_){return _.isConnectedInFragmentShader})){this._isMixed&&!this._imageSource&&e._emit2DSampler(this._samplerName);var o="//"+this.name;e._emitFunctionFromInclude("helperFunctions",o),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(var s=0,c=this._outputs;s<c.length;s++){var d=c[s];d.hasEndpoints&&d.name!=="level"&&this._writeOutput(e,d,d.name)}return this}},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".convertToGammaSpace = "+this.convertToGammaSpace+`;\r
  4784. `,e+=this._codeVariableName+".convertToLinearSpace = "+this.convertToLinearSpace+`;\r
  4785. `,e+=this._codeVariableName+".disableLevelMultiplication = "+this.disableLevelMultiplication+`;\r
  4786. `,this.texture&&(e+=this._codeVariableName+'.texture = new BABYLON.Texture("'+this.texture.name+'", null, '+this.texture.noMipmap+", "+this.texture.invertY+", "+this.texture.samplingMode+`);\r
  4787. `,e+=this._codeVariableName+".texture.wrapU = "+this.texture.wrapU+`;\r
  4788. `,e+=this._codeVariableName+".texture.wrapV = "+this.texture.wrapV+`;\r
  4789. `,e+=this._codeVariableName+".texture.uAng = "+this.texture.uAng+`;\r
  4790. `,e+=this._codeVariableName+".texture.vAng = "+this.texture.vAng+`;\r
  4791. `,e+=this._codeVariableName+".texture.wAng = "+this.texture.wAng+`;\r
  4792. `,e+=this._codeVariableName+".texture.uOffset = "+this.texture.uOffset+`;\r
  4793. `,e+=this._codeVariableName+".texture.vOffset = "+this.texture.vOffset+`;\r
  4794. `,e+=this._codeVariableName+".texture.uScale = "+this.texture.uScale+`;\r
  4795. `,e+=this._codeVariableName+".texture.vScale = "+this.texture.vScale+`;\r
  4796. `,e+=this._codeVariableName+".texture.coordinatesMode = "+this.texture.coordinatesMode+`;\r
  4797. `),e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(s=e.texture.url.indexOf("data:")===0?"":s,this.texture=Texture.Parse(e.texture,o,s))},i}(NodeMaterialBlock);RegisterClass("BABYLON.TextureBlock",TextureBlock);var ReflectionTextureBaseBlock=function(a){__extends(i,a);function i(e){return a.call(this,e,NodeMaterialBlockTargets.VertexAndFragment)||this}return Object.defineProperty(i.prototype,"texture",{get:function(){return this._texture},set:function(e){var o=this,s;if(this._texture!==e){var c=(s=e==null?void 0:e.getScene())!==null&&s!==void 0?s:Engine.LastCreatedScene;!e&&c&&c.markAllMaterialsAsDirty(1,function(d){return d.hasTexture(o._texture)}),this._texture=e,e&&c&&c.markAllMaterialsAsDirty(1,function(d){return d.hasTexture(e)})}},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"ReflectionTextureBaseBlock"},i.prototype._getTexture=function(){return this.texture},i.prototype.autoConfigure=function(e){if(!this.position.isConnected){var o=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="position"});o||(o=new InputBlock("position"),o.setAsAttribute()),o.output.connectTo(this.position)}if(!this.world.isConnected){var s=e.getInputBlockByPredicate(function(d){return d.systemValue===NodeMaterialSystemValues.World});s||(s=new InputBlock("world"),s.setAsSystemValue(NodeMaterialSystemValues.World)),s.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){var c=e.getInputBlockByPredicate(function(d){return d.systemValue===NodeMaterialSystemValues.View});c||(c=new InputBlock("view"),c.setAsSystemValue(NodeMaterialSystemValues.View)),c.output.connectTo(this.view)}},i.prototype.prepareDefines=function(e,o,s){if(!!s._areTexturesDirty){var c=this._getTexture();!c||!c.getTextureMatrix||(s.setValue(this._define3DName,c.isCube,!0),s.setValue(this._defineLocalCubicName,!!c.boundingBoxSize,!0),s.setValue(this._defineExplicitName,c.coordinatesMode===0,!0),s.setValue(this._defineSkyboxName,c.coordinatesMode===5,!0),s.setValue(this._defineCubicName,c.coordinatesMode===3||c.coordinatesMode===6,!0),s.setValue("INVERTCUBICMAP",c.coordinatesMode===6,!0),s.setValue(this._defineSphericalName,c.coordinatesMode===1,!0),s.setValue(this._definePlanarName,c.coordinatesMode===2,!0),s.setValue(this._defineProjectionName,c.coordinatesMode===4,!0),s.setValue(this._defineEquirectangularName,c.coordinatesMode===7,!0),s.setValue(this._defineEquirectangularFixedName,c.coordinatesMode===8,!0),s.setValue(this._defineMirroredEquirectangularFixedName,c.coordinatesMode===9,!0))}},i.prototype.isReady=function(){var e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())},i.prototype.bind=function(e,o,s){var c=this._getTexture();if(!(!s||!c)&&(e.setMatrix(this._reflectionMatrixName,c.getReflectionTextureMatrix()),c.isCube?e.setTexture(this._cubeSamplerName,c):e.setTexture(this._2DSamplerName,c),c.boundingBoxSize)){var d=c;e.setVector3(this._reflectionPositionName,d.boundingBoxPosition),e.setVector3(this._reflectionSizeName,d.boundingBoxSize)}},i.prototype.handleVertexSide=function(e){this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");var o="",s="v_"+this.worldPosition.associatedVariableName;return e._emitVaryingFromString(s,"vec4")&&(o+=s+" = "+this.worldPosition.associatedVariableName+`;\r
  4798. `),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName)&&(o+="#ifdef "+this._defineSkyboxName+`\r
  4799. `,o+=this._positionUVWName+" = "+this.position.associatedVariableName+`.xyz;\r
  4800. `,o+=`#endif\r
  4801. `),e._emitVaryingFromString(this._directionWName,"vec3","defined("+this._defineEquirectangularFixedName+") || defined("+this._defineMirroredEquirectangularFixedName+")")&&(o+="#if defined("+this._defineEquirectangularFixedName+") || defined("+this._defineMirroredEquirectangularFixedName+`)\r
  4802. `,o+=this._directionWName+" = normalize(vec3("+this.world.associatedVariableName+" * vec4("+this.position.associatedVariableName+`.xyz, 0.0)));\r
  4803. `,o+=`#endif\r
  4804. `),o},i.prototype.handleFragmentSideInits=function(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+="#ifdef "+this._define3DName+`\r
  4805. `,e._samplerDeclaration+="uniform samplerCube "+this._cubeSamplerName+`;\r
  4806. `,e._samplerDeclaration+=`#else\r
  4807. `,e._samplerDeclaration+="uniform sampler2D "+this._2DSamplerName+`;\r
  4808. `,e._samplerDeclaration+=`#endif\r
  4809. `,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);var o="//"+this.name;e._emitFunction("ReciprocalPI","#define RECIPROCAL_PI2 0.15915494",""),e._emitFunctionFromInclude("helperFunctions",o),e._emitFunctionFromInclude("reflectionFunction",o,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")},i.prototype.handleFragmentSideCodeReflectionCoords=function(e,o,s){s===void 0&&(s=!1),o||(o="v_"+this.worldPosition.associatedVariableName);var c=this._reflectionMatrixName,d="normalize("+this._directionWName+")",_=""+this._positionUVWName,b=""+this.cameraPosition.associatedVariableName,k=""+this.view.associatedVariableName;e+=".xyz";var j=`
  4810. #ifdef `+this._defineMirroredEquirectangularFixedName+`
  4811. vec3 `+this._reflectionVectorName+" = computeMirroredFixedEquirectangularCoords("+o+", "+e+", "+d+`);
  4812. #endif
  4813. #ifdef `+this._defineEquirectangularFixedName+`
  4814. vec3 `+this._reflectionVectorName+" = computeFixedEquirectangularCoords("+o+", "+e+", "+d+`);
  4815. #endif
  4816. #ifdef `+this._defineEquirectangularName+`
  4817. vec3 `+this._reflectionVectorName+" = computeEquirectangularCoords("+o+", "+e+", "+b+".xyz, "+c+`);
  4818. #endif
  4819. #ifdef `+this._defineSphericalName+`
  4820. vec3 `+this._reflectionVectorName+" = computeSphericalCoords("+o+", "+e+", "+k+", "+c+`);
  4821. #endif
  4822. #ifdef `+this._definePlanarName+`
  4823. vec3 `+this._reflectionVectorName+" = computePlanarCoords("+o+", "+e+", "+b+".xyz, "+c+`);
  4824. #endif
  4825. #ifdef `+this._defineCubicName+`
  4826. #ifdef `+this._defineLocalCubicName+`
  4827. vec3 `+this._reflectionVectorName+" = computeCubicLocalCoords("+o+", "+e+", "+b+".xyz, "+c+", "+this._reflectionSizeName+", "+this._reflectionPositionName+`);
  4828. #else
  4829. vec3 `+this._reflectionVectorName+" = computeCubicCoords("+o+", "+e+", "+b+".xyz, "+c+`);
  4830. #endif
  4831. #endif
  4832. #ifdef `+this._defineProjectionName+`
  4833. vec3 `+this._reflectionVectorName+" = computeProjectionCoords("+o+", "+k+", "+c+`);
  4834. #endif
  4835. #ifdef `+this._defineSkyboxName+`
  4836. vec3 `+this._reflectionVectorName+" = computeSkyBoxCoords("+_+", "+c+`);
  4837. #endif
  4838. #ifdef `+this._defineExplicitName+`
  4839. vec3 `+this._reflectionVectorName+` = vec3(0, 0, 0);
  4840. #endif
  4841. #ifdef `+this._defineOppositeZ+`
  4842. `+this._reflectionVectorName+`.z *= -1.0;
  4843. #endif\r
  4844. `;return s||(j+=`
  4845. #ifdef `+this._define3DName+`
  4846. vec3 `+this._reflectionCoordsName+" = "+this._reflectionVectorName+`;
  4847. #else
  4848. vec2 `+this._reflectionCoordsName+" = "+this._reflectionVectorName+`.xy;
  4849. #ifdef `+this._defineProjectionName+`
  4850. `+this._reflectionCoordsName+" /= "+this._reflectionVectorName+`.z;
  4851. #endif
  4852. `+this._reflectionCoordsName+".y = 1.0 - "+this._reflectionCoordsName+`.y;
  4853. #endif\r
  4854. `),j},i.prototype.handleFragmentSideCodeReflectionColor=function(e,o){o===void 0&&(o=".rgb");var s="vec"+(o.length===0?"4":o.length-1),c=s+" "+this._reflectionColorName+`;
  4855. #ifdef `+this._define3DName+`\r
  4856. `;return e?c+=this._reflectionColorName+" = textureCubeLodEXT("+this._cubeSamplerName+", "+this._reflectionVectorName+", "+e+")"+o+`;\r
  4857. `:c+=this._reflectionColorName+" = textureCube("+this._cubeSamplerName+", "+this._reflectionVectorName+")"+o+`;\r
  4858. `,c+=`
  4859. #else\r
  4860. `,e?c+=this._reflectionColorName+" = texture2DLodEXT("+this._2DSamplerName+", "+this._reflectionCoordsName+", "+e+")"+o+`;\r
  4861. `:c+=this._reflectionColorName+" = texture2D("+this._2DSamplerName+", "+this._reflectionCoordsName+")"+o+`;\r
  4862. `,c+=`#endif\r
  4863. `,c},i.prototype.writeOutputs=function(e,o){var s="";if(e.target===NodeMaterialBlockTargets.Fragment)for(var c=0,d=this._outputs;c<d.length;c++){var _=d[c];_.hasEndpoints&&(s+=this._declareOutput(_,e)+" = "+o+"."+_.name+`;\r
  4864. `)}return s},i.prototype._buildBlock=function(e){return a.prototype._buildBlock.call(this,e),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);if(!this.texture)return e;if(this.texture.isCube){var o=this.texture.forcedExtension;e+=this._codeVariableName+'.texture = new BABYLON.CubeTexture("'+this.texture.name+'", undefined, undefined, '+this.texture.noMipmap+", null, undefined, undefined, undefined, "+this.texture._prefiltered+", "+(o?'"'+o+'"':"null")+`);\r
  4865. `}else e+=this._codeVariableName+'.texture = new BABYLON.Texture("'+this.texture.name+`", null);\r
  4866. `;return e+=this._codeVariableName+".texture.coordinatesMode = "+this.texture.coordinatesMode+`;\r
  4867. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),e.texture&&(s=e.texture.url.indexOf("data:")===0?"":s,e.texture.isCube?this.texture=CubeTexture.Parse(e.texture,o,s):this.texture=Texture.Parse(e.texture,o,s))},i}(NodeMaterialBlock);RegisterClass("BABYLON.ReflectionTextureBaseBlock",ReflectionTextureBaseBlock);var ReflectionTextureBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e)||this;return o.registerInput("position",NodeMaterialBlockConnectionPointTypes.Vector3,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("worldPosition",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("worldNormal",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("world",NodeMaterialBlockConnectionPointTypes.Matrix,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("cameraPosition",NodeMaterialBlockConnectionPointTypes.Vector3,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("view",NodeMaterialBlockConnectionPointTypes.Matrix,!1,NodeMaterialBlockTargets.Fragment),o.registerOutput("rgb",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("rgba",NodeMaterialBlockConnectionPointTypes.Color4,NodeMaterialBlockTargets.Fragment),o.registerOutput("r",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("g",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("b",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("a",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o}return i.prototype.getClassName=function(){return"ReflectionTextureBlock"},Object.defineProperty(i.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldNormal",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"world",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraPosition",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"view",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgb",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgba",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(a.prototype.autoConfigure.call(this,e),!this.cameraPosition.isConnected){var o=e.getInputBlockByPredicate(function(s){return s.systemValue===NodeMaterialSystemValues.CameraPosition});o||(o=new InputBlock("cameraPosition"),o.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),o.output.connectTo(this.cameraPosition)}},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec3(0.)"),this;if(e.target!==NodeMaterialBlockTargets.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.handleFragmentSideInits(e);var o=e._getFreeVariableName("normalWUnit");return e.compilationString+="vec4 "+o+" = normalize("+this.worldNormal.associatedVariableName+`);\r
  4868. `,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(o),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this},i}(ReflectionTextureBaseBlock);RegisterClass("BABYLON.ReflectionTextureBlock",ReflectionTextureBlock);var SceneDepthBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.VertexAndFragment)||this;return o._samplerName="textureSampler",o.useNonLinearDepth=!1,o.force32itsFloat=!1,o._isUnique=!0,o.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2,!1,NodeMaterialBlockTargets.VertexAndFragment),o.registerOutput("depth",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Neutral),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[0]._prioritizeVertex=!1,o}return i.prototype.getClassName=function(){return"SceneDepthBlock"},Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"depth",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.initialize=function(e){e._excludeVariableName("textureSampler")},Object.defineProperty(i.prototype,"target",{get:function(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?NodeMaterialBlockTargets.VertexAndFragment:NodeMaterialBlockTargets.Fragment},enumerable:!1,configurable:!0}),i.prototype._getTexture=function(e){var o=e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat);return o.getDepthMap()},i.prototype.bind=function(e,o,s){var c=this._getTexture(o.getScene());e.setTexture(this._samplerName,c)},i.prototype._injectVertexCode=function(e){var o=this.uv;if(o.connectedPoint.ownerBlock.isInput){var s=o.connectedPoint.ownerBlock;s.isAttribute||e._emitUniformFromString(o.associatedVariableName,"vec"+(o.type===NodeMaterialBlockConnectionPointTypes.Vector3?"3":o.type===NodeMaterialBlockConnectionPointTypes.Vector4?"4":"2"))}if(this._mainUVName="vMain"+o.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=this._mainUVName+" = "+o.associatedVariableName+`.xy;\r
  4869. `,!!this._outputs.some(function(b){return b.isConnectedInVertexShader})){this._writeTextureRead(e,!0);for(var c=0,d=this._outputs;c<d.length;c++){var _=d[c];_.hasEndpoints&&this._writeOutput(e,_,"r",!0)}}},i.prototype._writeTextureRead=function(e,o){o===void 0&&(o=!1);var s=this.uv;if(o){if(e.target===NodeMaterialBlockTargets.Fragment)return;e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+s.associatedVariableName+`.xy);\r
  4870. `;return}if(this.uv.ownerBlock.target===NodeMaterialBlockTargets.Fragment){e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+s.associatedVariableName+`.xy);\r
  4871. `;return}e.compilationString+="vec4 "+this._tempTextureRead+" = texture2D("+this._samplerName+", "+this._mainUVName+`);\r
  4872. `},i.prototype._writeOutput=function(e,o,s,c){if(c===void 0&&(c=!1),c){if(e.target===NodeMaterialBlockTargets.Fragment)return;e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4873. `;return}if(this.uv.ownerBlock.target===NodeMaterialBlockTargets.Fragment){e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4874. `;return}e.compilationString+=this._declareOutput(o,e)+" = "+this._tempTextureRead+"."+s+`;\r
  4875. `},i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==NodeMaterialBlockTargets.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!!this._outputs.some(function(d){return d.isConnectedInFragmentShader})){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(var o=0,s=this._outputs;o<s.length;o++){var c=s[o];c.hasEndpoints&&this._writeOutput(e,c,"r")}return this}},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.useNonLinearDepth=this.useNonLinearDepth,e.force32itsFloat=this.force32itsFloat,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.useNonLinearDepth=e.useNonLinearDepth,this.force32itsFloat=e.force32itsFloat},__decorate([editableInPropertyPage("Use non linear depth",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:function(e){return e.disableDepthRenderer()}}})],i.prototype,"useNonLinearDepth",void 0),__decorate([editableInPropertyPage("Force 32 bits float",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:function(e){return e.disableDepthRenderer()}}})],i.prototype,"force32itsFloat",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.SceneDepthBlock",SceneDepthBlock);var AddBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"AddBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = "+this.left.associatedVariableName+" + "+this.right.associatedVariableName+`;\r
  4876. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.AddBlock",AddBlock);var ScaleBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("factor",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o}return i.prototype.getClassName=function(){return"ScaleBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"factor",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = "+this.input.associatedVariableName+" * "+this.factor.associatedVariableName+`;\r
  4877. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ScaleBlock",ScaleBlock);var ClampBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.minimum=0,o.maximum=1,o.registerInput("value",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o}return i.prototype.getClassName=function(){return"ClampBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = clamp("+this.value.associatedVariableName+", "+this._writeFloat(this.minimum)+", "+this._writeFloat(this.maximum)+`);\r
  4878. `),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".minimum = "+this.minimum+`;\r
  4879. `);return e+=this._codeVariableName+".maximum = "+this.maximum+`;\r
  4880. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.minimum=this.minimum,e.maximum=this.maximum,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.minimum=e.minimum,this.maximum=e.maximum},__decorate([editableInPropertyPage("Minimum",PropertyTypeForEdition.Float)],i.prototype,"minimum",void 0),__decorate([editableInPropertyPage("Maximum",PropertyTypeForEdition.Float)],i.prototype,"maximum",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.ClampBlock",ClampBlock);var CrossBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector3),o._linkConnectionTypes(0,1),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),o}return i.prototype.getClassName=function(){return"CrossBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = cross("+this.left.associatedVariableName+".xyz, "+this.right.associatedVariableName+`.xyz);\r
  4881. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.CrossBlock",CrossBlock);var CustomBlock=function(a){__extends(i,a);function i(e){return a.call(this,e)||this}return Object.defineProperty(i.prototype,"options",{get:function(){return this._options},set:function(e){this._deserializeOptions(e)},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"CustomBlock"},i.prototype._buildBlock=function(e){var o=this;a.prototype._buildBlock.call(this,e);var s=this._code,c=this._options.functionName;this._inputs.forEach(function(_){var b=new RegExp("\\{TYPE_"+_.name+"\\}","gm"),k=e._getGLType(_.type);s=s.replace(b,k),c=c.replace(b,k)}),this._outputs.forEach(function(_){var b=new RegExp("\\{TYPE_"+_.name+"\\}","gm"),k=e._getGLType(_.type);s=s.replace(b,k),c=c.replace(b,k)}),e._emitFunction(c,s,""),this._outputs.forEach(function(_){e.compilationString+=o._declareOutput(_,e)+`;\r
  4882. `}),e.compilationString+=c+"(";var d=!1;return this._inputs.forEach(function(_,b){b>0&&(e.compilationString+=", "),e.compilationString+=_.associatedVariableName,d=!0}),this._outputs.forEach(function(_,b){(b>0||d)&&(e.compilationString+=", "),e.compilationString+=_.associatedVariableName}),e.compilationString+=`);\r
  4883. `,this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".options = "+JSON.stringify(this._options)+`;\r
  4884. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.options=this._options,e},i.prototype._deserialize=function(e,o,s){this._deserializeOptions(e.options),a.prototype._deserialize.call(this,e,o,s)},i.prototype._deserializeOptions=function(e){var o=this,s,c,d;this._options=e,this._code=e.code.join(`\r
  4885. `)+`\r
  4886. `,this.name=this.name||e.name,this.target=NodeMaterialBlockTargets[e.target],(s=e.inParameters)===null||s===void 0||s.forEach(function(_,b){var k=NodeMaterialBlockConnectionPointTypes[_.type];o.registerInput(_.name,k),Object.defineProperty(o,_.name,{get:function(){return this._inputs[b]},enumerable:!0,configurable:!0})}),(c=e.outParameters)===null||c===void 0||c.forEach(function(_,b){o.registerOutput(_.name,NodeMaterialBlockConnectionPointTypes[_.type]),Object.defineProperty(o,_.name,{get:function(){return this._outputs[b]},enumerable:!0,configurable:!0}),_.type==="BasedOnInput"&&(o._outputs[b]._typeConnectionSource=o._findInputByName(_.typeFromInput)[0])}),(d=e.inLinkedConnectionTypes)===null||d===void 0||d.forEach(function(_){o._linkConnectionTypes(o._findInputByName(_.input1)[1],o._findInputByName(_.input2)[1])})},i.prototype._findInputByName=function(e){if(!e)return null;for(var o=0;o<this._inputs.length;o++)if(this._inputs[o].name===e)return[this._inputs[o],o];return null},i}(NodeMaterialBlock);RegisterClass("BABYLON.CustomBlock",CustomBlock);var DotBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o._linkConnectionTypes(0,1),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"DotBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = dot("+this.left.associatedVariableName+", "+this.right.associatedVariableName+`);\r
  4887. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.DotBlock",DotBlock);var NormalizeBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"NormalizeBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this._inputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = normalize("+s.associatedVariableName+`);\r
  4888. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.NormalizeBlock",NormalizeBlock);var ColorMergerBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.rSwizzle="r",o.gSwizzle="g",o.bSwizzle="b",o.aSwizzle="a",o.registerInput("rgb ",NodeMaterialBlockConnectionPointTypes.Color3,!0),o.registerInput("r",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("g",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("b",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("a",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerOutput("rgba",NodeMaterialBlockConnectionPointTypes.Color4),o.registerOutput("rgb",NodeMaterialBlockConnectionPointTypes.Color3),o}return i.prototype.getClassName=function(){return"ColorMergerBlock"},Object.defineProperty(i.prototype,"rgbIn",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"r",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"g",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"b",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"a",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgbOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rgb",{get:function(){return this.rgbOut},enumerable:!1,configurable:!0}),i.prototype._inputRename=function(e){return e==="rgb "?"rgbIn":e},i.prototype._buildSwizzle=function(e){var o=this.rSwizzle+this.gSwizzle+this.bSwizzle+this.aSwizzle;return"."+o.substr(0,e)},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.r,s=this.g,c=this.b,d=this.a,_=this.rgbIn,b=this._outputs[0],k=this._outputs[1];return _.isConnected?(b.hasEndpoints&&(e.compilationString+=this._declareOutput(b,e)+(" = vec4("+_.associatedVariableName+", "+(d.isConnected?this._writeVariable(d):"0.0")+")"+this._buildSwizzle(4)+`;\r
  4889. `)),k.hasEndpoints&&(e.compilationString+=this._declareOutput(k,e)+(" = "+_.associatedVariableName+this._buildSwizzle(3)+`;\r
  4890. `))):(b.hasEndpoints&&(e.compilationString+=this._declareOutput(b,e)+(" = vec4("+(o.isConnected?this._writeVariable(o):"0.0")+", "+(s.isConnected?this._writeVariable(s):"0.0")+", "+(c.isConnected?this._writeVariable(c):"0.0")+", "+(d.isConnected?this._writeVariable(d):"0.0")+")"+this._buildSwizzle(4)+`;\r
  4891. `)),k.hasEndpoints&&(e.compilationString+=this._declareOutput(k,e)+(" = vec3("+(o.isConnected?this._writeVariable(o):"0.0")+", "+(s.isConnected?this._writeVariable(s):"0.0")+", "+(c.isConnected?this._writeVariable(c):"0.0")+")"+this._buildSwizzle(3)+`;\r
  4892. `))),this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.rSwizzle=this.rSwizzle,e.gSwizzle=this.gSwizzle,e.bSwizzle=this.bSwizzle,e.aSwizzle=this.aSwizzle,e},i.prototype._deserialize=function(e,o,s){var c,d,_,b;a.prototype._deserialize.call(this,e,o,s),this.rSwizzle=(c=e.rSwizzle)!==null&&c!==void 0?c:"r",this.gSwizzle=(d=e.gSwizzle)!==null&&d!==void 0?d:"g",this.bSwizzle=(_=e.bSwizzle)!==null&&_!==void 0?_:"b",this.aSwizzle=(b=e.aSwizzle)!==null&&b!==void 0?b:"a"},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".rSwizzle = "+this.rSwizzle+`};\r
  4893. `,e+=this._codeVariableName+".gSwizzle = "+this.gSwizzle+`};\r
  4894. `,e+=this._codeVariableName+".bSwizzle = "+this.bSwizzle+`};\r
  4895. `,e+=this._codeVariableName+".aSwizzle = "+this.aSwizzle+`};\r
  4896. `,e},i}(NodeMaterialBlock);RegisterClass("BABYLON.ColorMergerBlock",ColorMergerBlock);var VectorSplitterBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("xyzw",NodeMaterialBlockConnectionPointTypes.Vector4,!0),o.registerInput("xyz ",NodeMaterialBlockConnectionPointTypes.Vector3,!0),o.registerInput("xy ",NodeMaterialBlockConnectionPointTypes.Vector2,!0),o.registerOutput("xyz",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("xy",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("zw",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("x",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("y",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("z",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("w",NodeMaterialBlockConnectionPointTypes.Float),o.inputsAreExclusive=!0,o}return i.prototype.getClassName=function(){return"VectorSplitterBlock"},Object.defineProperty(i.prototype,"xyzw",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyzIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyIn",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyzOut",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"xyOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"zw",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"x",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"z",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"w",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),i.prototype._inputRename=function(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}},i.prototype._outputRename=function(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,s=this._outputs[0],c=this._outputs[1],d=this._outputs[2],_=this._outputs[3],b=this._outputs[4],k=this._outputs[5],j=this._outputs[6];return s.hasEndpoints&&(o===this.xyIn?e.compilationString+=this._declareOutput(s,e)+(" = vec3("+o.associatedVariableName+`, 0.0);\r
  4897. `):e.compilationString+=this._declareOutput(s,e)+(" = "+o.associatedVariableName+`.xyz;\r
  4898. `)),d.hasEndpoints&&this.xyzw.isConnected&&(e.compilationString+=this._declareOutput(d,e)+(" = "+this.xyzw.associatedVariableName+`.zw;\r
  4899. `)),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+(" = "+o.associatedVariableName+`.xy;\r
  4900. `)),_.hasEndpoints&&(e.compilationString+=this._declareOutput(_,e)+(" = "+o.associatedVariableName+`.x;\r
  4901. `)),b.hasEndpoints&&(e.compilationString+=this._declareOutput(b,e)+(" = "+o.associatedVariableName+`.y;\r
  4902. `)),k.hasEndpoints&&(e.compilationString+=this._declareOutput(k,e)+(" = "+o.associatedVariableName+`.z;\r
  4903. `)),j.hasEndpoints&&(e.compilationString+=this._declareOutput(j,e)+(" = "+o.associatedVariableName+`.w;\r
  4904. `)),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.VectorSplitterBlock",VectorSplitterBlock);var LerpBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("gradient",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o._linkConnectionTypes(1,2,!0),o._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"LerpBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = mix("+this.left.associatedVariableName+" , "+this.right.associatedVariableName+", "+this.gradient.associatedVariableName+`);\r
  4905. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.LerpBlock",LerpBlock);var DivideBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"DivideBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = "+this.left.associatedVariableName+" / "+this.right.associatedVariableName+`;\r
  4906. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.DivideBlock",DivideBlock);var SubtractBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"SubtractBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = "+this.left.associatedVariableName+" - "+this.right.associatedVariableName+`;\r
  4907. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.SubtractBlock",SubtractBlock);var StepBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("edge",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"StepBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"edge",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = step("+this.edge.associatedVariableName+", "+this.value.associatedVariableName+`);\r
  4908. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.StepBlock",StepBlock);var OneMinusBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"OneMinusBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = 1. - "+this.input.associatedVariableName+`;\r
  4909. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.OneMinusBlock",OneMinusBlock);RegisterClass("BABYLON.OppositeBlock",OneMinusBlock);var ViewDirectionBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("worldPosition",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("cameraPosition",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector3),o}return i.prototype.getClassName=function(){return"ViewDirectionBlock"},Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraPosition",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.cameraPosition.isConnected){var o=e.getInputBlockByPredicate(function(s){return s.systemValue===NodeMaterialSystemValues.CameraPosition});o||(o=new InputBlock("cameraPosition"),o.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),o.output.connectTo(this.cameraPosition)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = normalize("+this.cameraPosition.associatedVariableName+" - "+this.worldPosition.associatedVariableName+`.xyz);\r
  4910. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ViewDirectionBlock",ViewDirectionBlock);var FresnelBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("worldNormal",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("viewDirection",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("bias",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("power",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("fresnel",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"FresnelBlock"},Object.defineProperty(i.prototype,"worldNormal",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"viewDirection",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bias",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"power",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"fresnel",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.viewDirection.isConnected){var o=new ViewDirectionBlock("View direction");o.output.connectTo(this.viewDirection),o.autoConfigure(e)}if(!this.bias.isConnected){var s=new InputBlock("bias");s.value=0,s.output.connectTo(this.bias)}if(!this.power.isConnected){var c=new InputBlock("power");c.value=1,c.output.connectTo(this.power)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o="//"+this.name;return e._emitFunctionFromInclude("fresnelFunction",o,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+(" = computeFresnelTerm("+this.viewDirection.associatedVariableName+".xyz, "+this.worldNormal.associatedVariableName+".xyz, "+this.bias.associatedVariableName+", "+this.power.associatedVariableName+`);\r
  4911. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.FresnelBlock",FresnelBlock);var MaxBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"MaxBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = max("+this.left.associatedVariableName+", "+this.right.associatedVariableName+`);\r
  4912. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.MaxBlock",MaxBlock);var MinBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"MinBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = min("+this.left.associatedVariableName+", "+this.right.associatedVariableName+`);\r
  4913. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.MinBlock",MinBlock);var DistanceBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o._linkConnectionTypes(0,1),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"DistanceBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = length("+this.left.associatedVariableName+" - "+this.right.associatedVariableName+`);\r
  4914. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.DistanceBlock",DistanceBlock);var LengthBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"LengthBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = length("+this.value.associatedVariableName+`);\r
  4915. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.LengthBlock",LengthBlock);var NegateBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o}return i.prototype.getClassName=function(){return"NegateBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = -1.0 * "+this.value.associatedVariableName+`;\r
  4916. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.NegateBlock",NegateBlock);var PowBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("power",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"PowBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"power",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = pow("+this.value.associatedVariableName+", "+this.power.associatedVariableName+`);\r
  4917. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.PowBlock",PowBlock);var RandomNumberBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("seed",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o}return i.prototype.getClassName=function(){return"RandomNumberBlock"},Object.defineProperty(i.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s="//"+this.name;return e._emitFunctionFromInclude("helperFunctions",s),e.compilationString+=this._declareOutput(o,e)+(" = getRand("+this.seed.associatedVariableName+`.xy);\r
  4918. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.RandomNumberBlock",RandomNumberBlock);var ArcTan2Block=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("x",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("y",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"ArcTan2Block"},Object.defineProperty(i.prototype,"x",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = atan("+this.x.associatedVariableName+", "+this.y.associatedVariableName+`);\r
  4919. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ArcTan2Block",ArcTan2Block);var SmoothStepBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("edge0",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("edge1",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o}return i.prototype.getClassName=function(){return"SmoothStepBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"edge0",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"edge1",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = smoothstep("+this.edge0.associatedVariableName+", "+this.edge1.associatedVariableName+", "+this.value.associatedVariableName+`);\r
  4920. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.SmoothStepBlock",SmoothStepBlock);var ReciprocalBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"ReciprocalBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = 1. / "+this.input.associatedVariableName+`;\r
  4921. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ReciprocalBlock",ReciprocalBlock);var ReplaceColorBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("reference",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("distance",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("replacement",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o._linkConnectionTypes(0,3),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"ReplaceColorBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"reference",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"distance",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"replacement",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+`;\r
  4922. `,e.compilationString+="if (length("+this.value.associatedVariableName+" - "+this.reference.associatedVariableName+") < "+this.distance.associatedVariableName+`) {\r
  4923. `,e.compilationString+=o.associatedVariableName+" = "+this.replacement.associatedVariableName+`;\r
  4924. `,e.compilationString+=`} else {\r
  4925. `,e.compilationString+=o.associatedVariableName+" = "+this.value.associatedVariableName+`;\r
  4926. `,e.compilationString+=`}\r
  4927. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ReplaceColorBlock",ReplaceColorBlock);var PosterizeBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("value",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("steps",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"PosterizeBlock"},Object.defineProperty(i.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"steps",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = floor("+this.value.associatedVariableName+" / (1.0 / "+this.steps.associatedVariableName+")) * (1.0 / "+this.steps.associatedVariableName+`);\r
  4928. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.PosterizeBlock",PosterizeBlock);var WaveBlockKind;(function(a){a[a.SawTooth=0]="SawTooth",a[a.Square=1]="Square",a[a.Triangle=2]="Triangle"})(WaveBlockKind||(WaveBlockKind={}));var WaveBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.kind=WaveBlockKind.SawTooth,o.registerInput("input",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"WaveBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];switch(this.kind){case WaveBlockKind.SawTooth:{e.compilationString+=this._declareOutput(o,e)+(" = "+this.input.associatedVariableName+" - floor(0.5 + "+this.input.associatedVariableName+`);\r
  4929. `);break}case WaveBlockKind.Square:{e.compilationString+=this._declareOutput(o,e)+(" = 1.0 - 2.0 * round(fract("+this.input.associatedVariableName+`));\r
  4930. `);break}case WaveBlockKind.Triangle:{e.compilationString+=this._declareOutput(o,e)+(" = 2.0 * abs(2.0 * ("+this.input.associatedVariableName+" - floor(0.5 + "+this.input.associatedVariableName+`))) - 1.0;\r
  4931. `);break}}return this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.kind=this.kind,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.kind=e.kind},i}(NodeMaterialBlock);RegisterClass("BABYLON.WaveBlock",WaveBlock);var GradientBlockColorStep=function(){function a(i,e){this.step=i,this.color=e}return Object.defineProperty(a.prototype,"step",{get:function(){return this._step},set:function(i){this._step=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"color",{get:function(){return this._color},set:function(i){this._color=i},enumerable:!1,configurable:!0}),a}(),GradientBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.colorSteps=[new GradientBlockColorStep(0,Color3.Black()),new GradientBlockColorStep(1,Color3.White())],o.onValueChangedObservable=new Observable,o.registerInput("gradient",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o}return i.prototype.colorStepsUpdated=function(){this.onValueChangedObservable.notifyObservers(this)},i.prototype.getClassName=function(){return"GradientBlock"},Object.defineProperty(i.prototype,"gradient",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._writeColorConstant=function(e){var o=this.colorSteps[e];return"vec3("+o.color.r+", "+o.color.g+", "+o.color.b+")"},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(o,e)+` = vec3(0., 0., 0.);\r
  4932. `;return}var s=e._getFreeVariableName("gradientTempColor"),c=e._getFreeVariableName("gradientTempPosition");e.compilationString+="vec3 "+s+" = "+this._writeColorConstant(0)+`;\r
  4933. `,e.compilationString+="float "+c+`;\r
  4934. `;var d=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==NodeMaterialBlockConnectionPointTypes.Float&&(d+=".x");for(var _=1;_<this.colorSteps.length;_++){var b=this.colorSteps[_],k=this.colorSteps[_-1];e.compilationString+=c+" = clamp(("+d+" - "+e._emitFloat(k.step)+") / ("+e._emitFloat(b.step)+" - "+e._emitFloat(k.step)+"), 0.0, 1.0) * step("+e._emitFloat(_)+", "+e._emitFloat(this.colorSteps.length-1)+`);\r
  4935. `,e.compilationString+=s+" = mix("+s+", "+this._writeColorConstant(_)+", "+c+`);\r
  4936. `}return e.compilationString+=this._declareOutput(o,e)+(" = "+s+`;\r
  4937. `),this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);e.colorSteps=[];for(var o=0,s=this.colorSteps;o<s.length;o++){var c=s[o];e.colorSteps.push({step:c.step,color:{r:c.color.r,g:c.color.g,b:c.color.b}})}return e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.colorSteps=[];for(var c=0,d=e.colorSteps;c<d.length;c++){var _=d[c];this.colorSteps.push(new GradientBlockColorStep(_.step,new Color3(_.color.r,_.color.g,_.color.b)))}},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);e+=this._codeVariableName+`.colorSteps = [];\r
  4938. `;for(var o=0,s=this.colorSteps;o<s.length;o++){var c=s[o];e+=this._codeVariableName+".colorSteps.push(new BABYLON.GradientBlockColorStep("+c.step+", new BABYLON.Color3("+c.color.r+", "+c.color.g+", "+c.color.b+`)));\r
  4939. `}return e},i}(NodeMaterialBlock);RegisterClass("BABYLON.GradientBlock",GradientBlock);var NLerpBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("gradient",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o._linkConnectionTypes(1,2,!0),o._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"NLerpBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = normalize(mix("+this.left.associatedVariableName+" , "+this.right.associatedVariableName+", "+this.gradient.associatedVariableName+`));\r
  4940. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.NLerpBlock",NLerpBlock);var WorleyNoise3DBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.manhattanDistance=!1,o.registerInput("seed",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("jitter",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerOutput("x",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("y",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"WorleyNoise3DBlock"},Object.defineProperty(i.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"jitter",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),!!this.seed.isConnected&&!(!this.output.hasEndpoints&&!this.x.hasEndpoints&&!this.y.hasEndpoints)){var o=`vec3 permute(vec3 x){\r
  4941. `;o+=` return mod((34.0 * x + 1.0) * x, 289.0);\r
  4942. `,o+=`}\r
  4943. \r
  4944. `,o+=`vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\r
  4945. `,o+=` return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\r
  4946. `,o+=`}\r
  4947. \r
  4948. `,o+=`vec2 worley(vec3 P, float jitter, bool manhattanDistance){\r
  4949. `,o+=` float K = 0.142857142857; // 1/7\r
  4950. `,o+=` float Ko = 0.428571428571; // 1/2-K/2\r
  4951. `,o+=` float K2 = 0.020408163265306; // 1/(7*7)\r
  4952. `,o+=` float Kz = 0.166666666667; // 1/6\r
  4953. `,o+=` float Kzo = 0.416666666667; // 1/2-1/6*2\r
  4954. `,o+=`\r
  4955. `,o+=` vec3 Pi = mod(floor(P), 289.0);\r
  4956. `,o+=` vec3 Pf = fract(P) - 0.5;\r
  4957. `,o+=`\r
  4958. `,o+=` vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r
  4959. `,o+=` vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r
  4960. `,o+=` vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r
  4961. `,o+=`\r
  4962. `,o+=` vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r
  4963. `,o+=` vec3 p1 = permute(p + Pi.y - 1.0);\r
  4964. `,o+=` vec3 p2 = permute(p + Pi.y);\r
  4965. `,o+=` vec3 p3 = permute(p + Pi.y + 1.0);\r
  4966. `,o+=`\r
  4967. `,o+=` vec3 p11 = permute(p1 + Pi.z - 1.0);\r
  4968. `,o+=` vec3 p12 = permute(p1 + Pi.z);\r
  4969. `,o+=` vec3 p13 = permute(p1 + Pi.z + 1.0);\r
  4970. `,o+=`\r
  4971. `,o+=` vec3 p21 = permute(p2 + Pi.z - 1.0);\r
  4972. `,o+=` vec3 p22 = permute(p2 + Pi.z);\r
  4973. `,o+=` vec3 p23 = permute(p2 + Pi.z + 1.0);\r
  4974. `,o+=`\r
  4975. `,o+=` vec3 p31 = permute(p3 + Pi.z - 1.0);\r
  4976. `,o+=` vec3 p32 = permute(p3 + Pi.z);\r
  4977. `,o+=` vec3 p33 = permute(p3 + Pi.z + 1.0);\r
  4978. `,o+=`\r
  4979. `,o+=` vec3 ox11 = fract(p11*K) - Ko;\r
  4980. `,o+=` vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r
  4981. `,o+=` vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r
  4982. `,o+=`\r
  4983. `,o+=` vec3 ox12 = fract(p12*K) - Ko;\r
  4984. `,o+=` vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r
  4985. `,o+=` vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r
  4986. `,o+=`\r
  4987. `,o+=` vec3 ox13 = fract(p13*K) - Ko;\r
  4988. `,o+=` vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r
  4989. `,o+=` vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r
  4990. `,o+=`\r
  4991. `,o+=` vec3 ox21 = fract(p21*K) - Ko;\r
  4992. `,o+=` vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r
  4993. `,o+=` vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r
  4994. `,o+=`\r
  4995. `,o+=` vec3 ox22 = fract(p22*K) - Ko;\r
  4996. `,o+=` vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r
  4997. `,o+=` vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r
  4998. `,o+=`\r
  4999. `,o+=` vec3 ox23 = fract(p23*K) - Ko;\r
  5000. `,o+=` vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r
  5001. `,o+=` vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r
  5002. `,o+=`\r
  5003. `,o+=` vec3 ox31 = fract(p31*K) - Ko;\r
  5004. `,o+=` vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r
  5005. `,o+=` vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r
  5006. `,o+=`\r
  5007. `,o+=` vec3 ox32 = fract(p32*K) - Ko;\r
  5008. `,o+=` vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r
  5009. `,o+=` vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r
  5010. `,o+=`\r
  5011. `,o+=` vec3 ox33 = fract(p33*K) - Ko;\r
  5012. `,o+=` vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r
  5013. `,o+=` vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r
  5014. `,o+=`\r
  5015. `,o+=` vec3 dx11 = Pfx + jitter*ox11;\r
  5016. `,o+=` vec3 dy11 = Pfy.x + jitter*oy11;\r
  5017. `,o+=` vec3 dz11 = Pfz.x + jitter*oz11;\r
  5018. `,o+=`\r
  5019. `,o+=` vec3 dx12 = Pfx + jitter*ox12;\r
  5020. `,o+=` vec3 dy12 = Pfy.x + jitter*oy12;\r
  5021. `,o+=` vec3 dz12 = Pfz.y + jitter*oz12;\r
  5022. `,o+=`\r
  5023. `,o+=` vec3 dx13 = Pfx + jitter*ox13;\r
  5024. `,o+=` vec3 dy13 = Pfy.x + jitter*oy13;\r
  5025. `,o+=` vec3 dz13 = Pfz.z + jitter*oz13;\r
  5026. `,o+=`\r
  5027. `,o+=` vec3 dx21 = Pfx + jitter*ox21;\r
  5028. `,o+=` vec3 dy21 = Pfy.y + jitter*oy21;\r
  5029. `,o+=` vec3 dz21 = Pfz.x + jitter*oz21;\r
  5030. `,o+=`\r
  5031. `,o+=` vec3 dx22 = Pfx + jitter*ox22;\r
  5032. `,o+=` vec3 dy22 = Pfy.y + jitter*oy22;\r
  5033. `,o+=` vec3 dz22 = Pfz.y + jitter*oz22;\r
  5034. `,o+=`\r
  5035. `,o+=` vec3 dx23 = Pfx + jitter*ox23;\r
  5036. `,o+=` vec3 dy23 = Pfy.y + jitter*oy23;\r
  5037. `,o+=` vec3 dz23 = Pfz.z + jitter*oz23;\r
  5038. `,o+=`\r
  5039. `,o+=` vec3 dx31 = Pfx + jitter*ox31;\r
  5040. `,o+=` vec3 dy31 = Pfy.z + jitter*oy31;\r
  5041. `,o+=` vec3 dz31 = Pfz.x + jitter*oz31;\r
  5042. `,o+=`\r
  5043. `,o+=` vec3 dx32 = Pfx + jitter*ox32;\r
  5044. `,o+=` vec3 dy32 = Pfy.z + jitter*oy32;\r
  5045. `,o+=` vec3 dz32 = Pfz.y + jitter*oz32;\r
  5046. `,o+=`\r
  5047. `,o+=` vec3 dx33 = Pfx + jitter*ox33;\r
  5048. `,o+=` vec3 dy33 = Pfy.z + jitter*oy33;\r
  5049. `,o+=` vec3 dz33 = Pfz.z + jitter*oz33;\r
  5050. `,o+=`\r
  5051. `,o+=` vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r
  5052. `,o+=` vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r
  5053. `,o+=` vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r
  5054. `,o+=` vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r
  5055. `,o+=` vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r
  5056. `,o+=` vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r
  5057. `,o+=` vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r
  5058. `,o+=` vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r
  5059. `,o+=` vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r
  5060. `,o+=`\r
  5061. `,o+=` vec3 d1a = min(d11, d12);\r
  5062. `,o+=` d12 = max(d11, d12);\r
  5063. `,o+=` d11 = min(d1a, d13); // Smallest now not in d12 or d13\r
  5064. `,o+=` d13 = max(d1a, d13);\r
  5065. `,o+=` d12 = min(d12, d13); // 2nd smallest now not in d13\r
  5066. `,o+=` vec3 d2a = min(d21, d22);\r
  5067. `,o+=` d22 = max(d21, d22);\r
  5068. `,o+=` d21 = min(d2a, d23); // Smallest now not in d22 or d23\r
  5069. `,o+=` d23 = max(d2a, d23);\r
  5070. `,o+=` d22 = min(d22, d23); // 2nd smallest now not in d23\r
  5071. `,o+=` vec3 d3a = min(d31, d32);\r
  5072. `,o+=` d32 = max(d31, d32);\r
  5073. `,o+=` d31 = min(d3a, d33); // Smallest now not in d32 or d33\r
  5074. `,o+=` d33 = max(d3a, d33);\r
  5075. `,o+=` d32 = min(d32, d33); // 2nd smallest now not in d33\r
  5076. `,o+=` vec3 da = min(d11, d21);\r
  5077. `,o+=` d21 = max(d11, d21);\r
  5078. `,o+=` d11 = min(da, d31); // Smallest now in d11\r
  5079. `,o+=` d31 = max(da, d31); // 2nd smallest now not in d31\r
  5080. `,o+=` d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r
  5081. `,o+=` d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r
  5082. `,o+=` d12 = min(d12, d21); // 2nd smallest now not in d21\r
  5083. `,o+=` d12 = min(d12, d22); // nor in d22\r
  5084. `,o+=` d12 = min(d12, d31); // nor in d31\r
  5085. `,o+=` d12 = min(d12, d32); // nor in d32\r
  5086. `,o+=` d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r
  5087. `,o+=` d11.y = min(d11.y,d12.z); // Only two more to go\r
  5088. `,o+=` d11.y = min(d11.y,d11.z); // Done! (Phew!)\r
  5089. `,o+=` return sqrt(d11.xy); // F1, F2\r
  5090. `,o+=`}\r
  5091. \r
  5092. `,e._emitFunction("worley3D",o,"// Worley3D");var s=e._getFreeVariableName("worleyTemp");return e.compilationString+="vec2 "+s+" = worley("+this.seed.associatedVariableName+", "+this.jitter.associatedVariableName+", "+this.manhattanDistance+`);\r
  5093. `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+(" = "+s+`;\r
  5094. `)),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+(" = "+s+`.x;\r
  5095. `)),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+(" = "+s+`.y;\r
  5096. `)),this}},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".manhattanDistance = "+this.manhattanDistance+`;\r
  5097. `);return e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.manhattanDistance=this.manhattanDistance,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.manhattanDistance=e.manhattanDistance},__decorate([editableInPropertyPage("Use Manhattan Distance",PropertyTypeForEdition.Boolean,"PROPERTIES",{notifiers:{update:!1}})],i.prototype,"manhattanDistance",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.WorleyNoise3DBlock",WorleyNoise3DBlock);var SimplexPerlin3DBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("seed",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"SimplexPerlin3DBlock"},Object.defineProperty(i.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),!!this.seed.isConnected&&!!this._outputs[0].hasEndpoints){var o=`const float SKEWFACTOR = 1.0/3.0;\r
  5098. `;return o+=`const float UNSKEWFACTOR = 1.0/6.0;\r
  5099. `,o+=`const float SIMPLEX_CORNER_POS = 0.5;\r
  5100. `,o+=`const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r
  5101. `,o+=`float SimplexPerlin3D( vec3 P ){\r
  5102. `,o+=` P *= SIMPLEX_TETRAHADRON_HEIGHT;\r
  5103. `,o+=" vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );",o+=` vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r
  5104. `,o+=` vec3 g = step(x0.yzx, x0.xyz);\r
  5105. `,o+=` vec3 l = 1.0 - g;\r
  5106. `,o+=` vec3 Pi_1 = min( g.xyz, l.zxy );\r
  5107. `,o+=` vec3 Pi_2 = max( g.xyz, l.zxy );\r
  5108. `,o+=` vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r
  5109. `,o+=` vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r
  5110. `,o+=` vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r
  5111. `,o+=` vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r
  5112. `,o+=` vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r
  5113. `,o+=` vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r
  5114. `,o+=` Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r
  5115. `,o+=` vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r
  5116. `,o+=` vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r
  5117. `,o+=` Pt *= Pt;\r
  5118. `,o+=` vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r
  5119. `,o+=` Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r
  5120. `,o+=` const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r
  5121. `,o+=` const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r
  5122. `,o+=` vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r
  5123. `,o+=` vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r
  5124. `,o+=` Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r
  5125. `,o+=` Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r
  5126. `,o+=` vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r
  5127. `,o+=` vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r
  5128. `,o+=` vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r
  5129. `,o+=` vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\r
  5130. `,o+=` const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r
  5131. `,o+=` vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r
  5132. `,o+=` kernel_weights = max(0.5 - kernel_weights, 0.0);\r
  5133. `,o+=` kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r
  5134. `,o+=` return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r
  5135. `,o+=`}\r
  5136. `,e._emitFunction("SimplexPerlin3D",o,"// SimplexPerlin3D"),e.compilationString+=this._declareOutput(this._outputs[0],e)+(" = SimplexPerlin3D("+this.seed.associatedVariableName+`);\r
  5137. `),this}},i}(NodeMaterialBlock);RegisterClass("BABYLON.SimplexPerlin3DBlock",SimplexPerlin3DBlock);var NormalBlendBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("normalMap0",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("normalMap1",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o}return i.prototype.getClassName=function(){return"NormalBlendBlock"},Object.defineProperty(i.prototype,"normalMap0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"normalMap1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this._inputs[0],c=this._inputs[1],d=e._getFreeVariableName("stepR"),_=e._getFreeVariableName("stepG");return e.compilationString+="float "+d+" = step(0.5, "+s.associatedVariableName+`.r);\r
  5138. `,e.compilationString+="float "+_+" = step(0.5, "+s.associatedVariableName+`.g);\r
  5139. `,e.compilationString+=this._declareOutput(o,e)+`;\r
  5140. `,e.compilationString+=o.associatedVariableName+".r = (1.0 - "+d+") * "+s.associatedVariableName+".r * "+c.associatedVariableName+".r * 2.0 + "+d+" * (1.0 - (1.0 - "+s.associatedVariableName+".r) * (1.0 - "+c.associatedVariableName+`.r) * 2.0);\r
  5141. `,e.compilationString+=o.associatedVariableName+".g = (1.0 - "+_+") * "+s.associatedVariableName+".g * "+c.associatedVariableName+".g * 2.0 + "+_+" * (1.0 - (1.0 - "+s.associatedVariableName+".g) * (1.0 - "+c.associatedVariableName+`.g) * 2.0);\r
  5142. `,e.compilationString+=o.associatedVariableName+".b = "+s.associatedVariableName+".b * "+c.associatedVariableName+`.b;\r
  5143. `,this},i}(NodeMaterialBlock);RegisterClass("BABYLON.NormalBlendBlock",NormalBlendBlock);var Rotate2dBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("input",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerInput("angle",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector2),o}return i.prototype.getClassName=function(){return"Rotate2dBlock"},Object.defineProperty(i.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"angle",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.angle.isConnected){var o=new InputBlock("angle");o.value=0,o.output.connectTo(this.angle)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this.angle,c=this.input;return e.compilationString+=this._declareOutput(o,e)+(" = vec2(cos("+s.associatedVariableName+") * "+c.associatedVariableName+".x - sin("+s.associatedVariableName+") * "+c.associatedVariableName+".y, sin("+s.associatedVariableName+") * "+c.associatedVariableName+".x + cos("+s.associatedVariableName+") * "+c.associatedVariableName+`.y);\r
  5144. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.Rotate2dBlock",Rotate2dBlock);var ReflectBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("incident",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("normal",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o}return i.prototype.getClassName=function(){return"ReflectBlock"},Object.defineProperty(i.prototype,"incident",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = reflect("+this.incident.associatedVariableName+".xyz, "+this.normal.associatedVariableName+`.xyz);\r
  5145. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ReflectBlock",ReflectBlock);var RefractBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("incident",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("normal",NodeMaterialBlockConnectionPointTypes.Vector3),o.registerInput("ior",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Vector3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),o}return i.prototype.getClassName=function(){return"RefractBlock"},Object.defineProperty(i.prototype,"incident",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"ior",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = refract("+this.incident.associatedVariableName+".xyz, "+this.normal.associatedVariableName+".xyz, "+this.ior.associatedVariableName+`);\r
  5146. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.RefractBlock",RefractBlock);var DesaturateBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("color",NodeMaterialBlockConnectionPointTypes.Color3),o.registerInput("level",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Color3),o}return i.prototype.getClassName=function(){return"DesaturateBlock"},Object.defineProperty(i.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"level",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this.color,c=s.associatedVariableName,d=e._getFreeVariableName("colorMin"),_=e._getFreeVariableName("colorMax"),b=e._getFreeVariableName("colorMerge");return e.compilationString+="float "+d+" = min(min("+c+".x, "+c+".y), "+c+`.z);\r
  5147. `,e.compilationString+="float "+_+" = max(max("+c+".x, "+c+".y), "+c+`.z);\r
  5148. `,e.compilationString+="float "+b+" = 0.5 * ("+d+" + "+_+`);\r
  5149. `,e.compilationString+=this._declareOutput(o,e)+(" = mix("+c+", vec3("+b+", "+b+", "+b+"), "+this.level.associatedVariableName+`);\r
  5150. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.DesaturateBlock",DesaturateBlock);var _environmentBRDFBase64Texture="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==",_instanceNumber=0,GetEnvironmentBRDFTexture=function(a){if(!a.environmentBRDFTexture){var i=a.useDelayedTextureLoading;a.useDelayedTextureLoading=!1;var e=a._blockEntityCollection;a._blockEntityCollection=!1;var o=Texture.CreateFromBase64String(_environmentBRDFBase64Texture,"EnvironmentBRDFTexture"+_instanceNumber++,a,!0,!1,Texture.BILINEAR_SAMPLINGMODE);a._blockEntityCollection=e;var s=a.getEngine().getLoadedTexturesCache(),c=s.indexOf(o.getInternalTexture());c!==-1&&s.splice(c,1),o.isRGBD=!0,o.wrapU=Texture.CLAMP_ADDRESSMODE,o.wrapV=Texture.CLAMP_ADDRESSMODE,a.environmentBRDFTexture=o,a.useDelayedTextureLoading=i,RGBDTextureTools.ExpandRGBDTexture(o),a.getEngine().onContextRestoredObservable.add(function(){o.isRGBD=!0;var d=function(){o.isReady()?RGBDTextureTools.ExpandRGBDTexture(o):Tools.SetImmediate(d)};d()})}return a.environmentBRDFTexture},PBRClearCoatConfiguration=function(){function a(i){this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=a._DefaultIndexOfRefraction,this.indexOfRefraction=a._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=Color3.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=i}return a.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},a.prototype.isReadyForSubMesh=function(i,e,o,s){return this._isEnabled?!(i._areTexturesDirty&&e.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&MaterialFlags.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||o.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.ClearCoatBumpTextureEnabled&&!s&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())):!0},a.prototype.prepareDefines=function(i,e){var o;this._isEnabled?(i.CLEARCOAT=!0,i.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,i.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=this._texture!==null&&this._texture._texture===((o=this._textureRoughness)===null||o===void 0?void 0:o._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),i.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,i._areTexturesDirty&&e.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._texture,i,"CLEARCOAT_TEXTURE"):i.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&MaterialFlags.ClearCoatTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness,i,"CLEARCOAT_TEXTURE_ROUGHNESS"):i.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&MaterialFlags.ClearCoatBumpTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,i,"CLEARCOAT_BUMP"):i.CLEARCOAT_BUMP=!1,i.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===a._DefaultIndexOfRefraction,this._isTintEnabled?(i.CLEARCOAT_TINT=!0,this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._tintTexture,i,"CLEARCOAT_TINT_TEXTURE"),i.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):i.CLEARCOAT_TINT_TEXTURE=!1):(i.CLEARCOAT_TINT=!1,i.CLEARCOAT_TINT_TEXTURE=!1))):(i.CLEARCOAT=!1,i.CLEARCOAT_TEXTURE=!1,i.CLEARCOAT_TEXTURE_ROUGHNESS=!1,i.CLEARCOAT_BUMP=!1,i.CLEARCOAT_TINT=!1,i.CLEARCOAT_TINT_TEXTURE=!1,i.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,i.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1)},a.prototype.bindForSubMesh=function(i,e,o,s,c,d,_,b){var k,j,$,_e,et,tt,rt,it;if(!!this._isEnabled){var nt=b.materialDefines,ot=nt.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!i.useUbo||!c||!i.isSync){ot&&MaterialFlags.ClearCoatTextureEnabled?(i.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,i,"clearCoat")):(this._texture||this._textureRoughness)&&MaterialFlags.ClearCoatTextureEnabled&&(i.updateFloat4("vClearCoatInfos",(j=(k=this._texture)===null||k===void 0?void 0:k.coordinatesIndex)!==null&&j!==void 0?j:0,(_e=($=this._texture)===null||$===void 0?void 0:$.level)!==null&&_e!==void 0?_e:0,(tt=(et=this._textureRoughness)===null||et===void 0?void 0:et.coordinatesIndex)!==null&&tt!==void 0?tt:0,(it=(rt=this._textureRoughness)===null||rt===void 0?void 0:rt.level)!==null&&it!==void 0?it:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,i,"clearCoat"),this._textureRoughness&&!ot&&!nt.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialHelper.BindTextureMatrix(this._textureRoughness,i,"clearCoatRoughness")),this._bumpTexture&&o.getCaps().standardDerivatives&&MaterialFlags.ClearCoatTextureEnabled&&!s&&(i.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),MaterialHelper.BindTextureMatrix(this._bumpTexture,i,"clearCoatBump"),e._mirroredCameraPosition?i.updateFloat2("vClearCoatTangentSpaceParams",d?1:-1,_?1:-1):i.updateFloat2("vClearCoatTangentSpaceParams",d?-1:1,_?-1:1)),this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&(i.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),MaterialHelper.BindTextureMatrix(this._tintTexture,i,"clearCoatTint")),i.updateFloat2("vClearCoatParams",this.intensity,this.roughness);var at=1-this._indexOfRefraction,st=1+this._indexOfRefraction,ut=Math.pow(-at/st,2),ft=1/this._indexOfRefraction;i.updateFloat4("vClearCoatRefractionParams",ut,ft,at,st),this._isTintEnabled&&(i.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),i.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}e.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled&&i.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!ot&&!nt.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.ClearCoatTextureEnabled&&i.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&o.getCaps().standardDerivatives&&MaterialFlags.ClearCoatBumpTextureEnabled&&!s&&i.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&i.setTexture("clearCoatTintSampler",this._tintTexture))}},a.prototype.hasTexture=function(i){return this._texture===i||this._textureRoughness===i||this._bumpTexture===i||this._tintTexture===i},a.prototype.getActiveTextures=function(i){this._texture&&i.push(this._texture),this._textureRoughness&&i.push(this._textureRoughness),this._bumpTexture&&i.push(this._bumpTexture),this._tintTexture&&i.push(this._tintTexture)},a.prototype.getAnimatables=function(i){this._texture&&this._texture.animations&&this._texture.animations.length>0&&i.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&i.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&i.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&i.push(this._tintTexture)},a.prototype.dispose=function(i){var e,o,s,c;i&&((e=this._texture)===null||e===void 0||e.dispose(),(o=this._textureRoughness)===null||o===void 0||o.dispose(),(s=this._bumpTexture)===null||s===void 0||s.dispose(),(c=this._tintTexture)===null||c===void 0||c.dispose())},a.prototype.getClassName=function(){return"PBRClearCoatConfiguration"},a.AddFallbacks=function(i,e,o){return i.CLEARCOAT_BUMP&&e.addFallback(o++,"CLEARCOAT_BUMP"),i.CLEARCOAT_TINT&&e.addFallback(o++,"CLEARCOAT_TINT"),i.CLEARCOAT&&e.addFallback(o++,"CLEARCOAT"),o},a.AddUniforms=function(i){i.push("vClearCoatTangentSpaceParams","vClearCoatParams","vClearCoatRefractionParams","vClearCoatTintParams","clearCoatColorAtDistance","clearCoatMatrix","clearCoatRoughnessMatrix","clearCoatBumpMatrix","clearCoatTintMatrix","vClearCoatInfos","vClearCoatBumpInfos","vClearCoatTintInfos")},a.AddSamplers=function(i){i.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")},a.PrepareUniformBuffer=function(i){i.addUniform("vClearCoatParams",2),i.addUniform("vClearCoatRefractionParams",4),i.addUniform("vClearCoatInfos",4),i.addUniform("clearCoatMatrix",16),i.addUniform("clearCoatRoughnessMatrix",16),i.addUniform("vClearCoatBumpInfos",2),i.addUniform("vClearCoatTangentSpaceParams",2),i.addUniform("clearCoatBumpMatrix",16),i.addUniform("vClearCoatTintParams",4),i.addUniform("clearCoatColorAtDistance",1),i.addUniform("vClearCoatTintInfos",2),i.addUniform("clearCoatTintMatrix",16)},a.prototype.copyTo=function(i){SerializationHelper.Clone(function(){return i},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.prototype.parse=function(i,e,o){var s=this;SerializationHelper.Parse(function(){return s},i,e,o)},a._DefaultIndexOfRefraction=1.5,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"isEnabled",void 0),__decorate([serialize()],a.prototype,"intensity",void 0),__decorate([serialize()],a.prototype,"roughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"indexOfRefraction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"useRoughnessFromMainTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"textureRoughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"remapF0OnInterfaceChange",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"bumpTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"isTintEnabled",void 0),__decorate([serializeAsColor3()],a.prototype,"tintColor",void 0),__decorate([serialize()],a.prototype,"tintColorAtDistance",void 0),__decorate([serialize()],a.prototype,"tintThickness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"tintTexture",void 0),a}(),PBRAnisotropicConfiguration=function(){function a(i){this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Vector2(1,0),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=i}return a.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},a.prototype.isReadyForSubMesh=function(i,e){return this._isEnabled?!(i._areTexturesDirty&&e.texturesEnabled&&this._texture&&MaterialFlags.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0},a.prototype.prepareDefines=function(i,e,o){this._isEnabled?(i.ANISOTROPIC=this._isEnabled,this._isEnabled&&!e.isVerticesDataPresent(VertexBuffer.TangentKind)&&(i._needUVs=!0,i.MAINUV1=!0),i._areTexturesDirty&&o.texturesEnabled&&(this._texture&&MaterialFlags.AnisotropicTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._texture,i,"ANISOTROPIC_TEXTURE"):i.ANISOTROPIC_TEXTURE=!1)):(i.ANISOTROPIC=!1,i.ANISOTROPIC_TEXTURE=!1)},a.prototype.bindForSubMesh=function(i,e,o){!this._isEnabled||((!i.useUbo||!o||!i.isSync)&&(this._texture&&MaterialFlags.AnisotropicTextureEnabled&&(i.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),MaterialHelper.BindTextureMatrix(this._texture,i,"anisotropy")),i.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),e.texturesEnabled&&this._texture&&MaterialFlags.AnisotropicTextureEnabled&&i.setTexture("anisotropySampler",this._texture))},a.prototype.hasTexture=function(i){return this._texture===i},a.prototype.getActiveTextures=function(i){this._texture&&i.push(this._texture)},a.prototype.getAnimatables=function(i){this._texture&&this._texture.animations&&this._texture.animations.length>0&&i.push(this._texture)},a.prototype.dispose=function(i){i&&this._texture&&this._texture.dispose()},a.prototype.getClassName=function(){return"PBRAnisotropicConfiguration"},a.AddFallbacks=function(i,e,o){return i.ANISOTROPIC&&e.addFallback(o++,"ANISOTROPIC"),o},a.AddUniforms=function(i){i.push("vAnisotropy","vAnisotropyInfos","anisotropyMatrix")},a.PrepareUniformBuffer=function(i){i.addUniform("vAnisotropy",3),i.addUniform("vAnisotropyInfos",2),i.addUniform("anisotropyMatrix",16)},a.AddSamplers=function(i){i.push("anisotropySampler")},a.prototype.copyTo=function(i){SerializationHelper.Clone(function(){return i},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.prototype.parse=function(i,e,o){var s=this;SerializationHelper.Parse(function(){return s},i,e,o)},__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"isEnabled",void 0),__decorate([serialize()],a.prototype,"intensity",void 0),__decorate([serializeAsVector2()],a.prototype,"direction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"texture",void 0),a}(),PBRBRDFConfiguration=function(){function a(i){this._useEnergyConservation=a.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=a.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=a.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=a.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=a.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=a.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=a.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=a.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=i}return a.prototype._markAllSubMeshesAsMiscDirty=function(){this._internalMarkAllSubMeshesAsMiscDirty()},a.prototype.prepareDefines=function(i){i.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,i.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,i.SPHERICAL_HARMONICS=this._useSphericalHarmonics,i.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation},a.prototype.getClassName=function(){return"PBRBRDFConfiguration"},a.prototype.copyTo=function(i){SerializationHelper.Clone(function(){return i},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.prototype.parse=function(i,e,o){var s=this;SerializationHelper.Parse(function(){return s},i,e,o)},a.DEFAULT_USE_ENERGY_CONSERVATION=!0,a.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,a.DEFAULT_USE_SPHERICAL_HARMONICS=!0,a.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],a.prototype,"useEnergyConservation",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],a.prototype,"useSmithVisibilityHeightCorrelated",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],a.prototype,"useSphericalHarmonics",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],a.prototype,"useSpecularGlossinessInputEnergyConservation",void 0),a}(),PBRSheenConfiguration=function(){function a(i){this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Color3.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=i}return a.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},a.prototype.isReadyForSubMesh=function(i,e){return this._isEnabled?!(i._areTexturesDirty&&e.texturesEnabled&&(this._texture&&MaterialFlags.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&MaterialFlags.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())):!0},a.prototype.prepareDefines=function(i,e){var o;this._isEnabled?(i.SHEEN=this._isEnabled,i.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,i.SHEEN_ROUGHNESS=this._roughness!==null,i.SHEEN_ALBEDOSCALING=this._albedoScaling,i.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,i.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=this._texture!==null&&this._texture._texture===((o=this._textureRoughness)===null||o===void 0?void 0:o._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),i._areTexturesDirty&&e.texturesEnabled&&(this._texture&&MaterialFlags.SheenTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._texture,i,"SHEEN_TEXTURE"),i.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):i.SHEEN_TEXTURE=!1,this._textureRoughness&&MaterialFlags.SheenTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness,i,"SHEEN_TEXTURE_ROUGHNESS"):i.SHEEN_TEXTURE_ROUGHNESS=!1)):(i.SHEEN=!1,i.SHEEN_TEXTURE=!1,i.SHEEN_TEXTURE_ROUGHNESS=!1,i.SHEEN_LINKWITHALBEDO=!1,i.SHEEN_ROUGHNESS=!1,i.SHEEN_ALBEDOSCALING=!1,i.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,i.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1)},a.prototype.bindForSubMesh=function(i,e,o,s){var c,d,_,b,k,j,$,_e;if(!!this._isEnabled){var et=s.materialDefines,tt=et.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;(!i.useUbo||!o||!i.isSync)&&(tt&&MaterialFlags.SheenTextureEnabled?(i.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,i,"sheen")):(this._texture||this._textureRoughness)&&MaterialFlags.SheenTextureEnabled&&(i.updateFloat4("vSheenInfos",(d=(c=this._texture)===null||c===void 0?void 0:c.coordinatesIndex)!==null&&d!==void 0?d:0,(b=(_=this._texture)===null||_===void 0?void 0:_.level)!==null&&b!==void 0?b:0,(j=(k=this._textureRoughness)===null||k===void 0?void 0:k.coordinatesIndex)!==null&&j!==void 0?j:0,(_e=($=this._textureRoughness)===null||$===void 0?void 0:$.level)!==null&&_e!==void 0?_e:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,i,"sheen"),this._textureRoughness&&!tt&&!et.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialHelper.BindTextureMatrix(this._textureRoughness,i,"sheenRoughness")),i.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&i.updateFloat("vSheenRoughness",this._roughness)),e.texturesEnabled&&(this._texture&&MaterialFlags.SheenTextureEnabled&&i.setTexture("sheenSampler",this._texture),this._textureRoughness&&!tt&&!et.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.SheenTextureEnabled&&i.setTexture("sheenRoughnessSampler",this._textureRoughness))}},a.prototype.hasTexture=function(i){return this._texture===i||this._textureRoughness===i},a.prototype.getActiveTextures=function(i){this._texture&&i.push(this._texture),this._textureRoughness&&i.push(this._textureRoughness)},a.prototype.getAnimatables=function(i){this._texture&&this._texture.animations&&this._texture.animations.length>0&&i.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&i.push(this._textureRoughness)},a.prototype.dispose=function(i){var e,o;i&&((e=this._texture)===null||e===void 0||e.dispose(),(o=this._textureRoughness)===null||o===void 0||o.dispose())},a.prototype.getClassName=function(){return"PBRSheenConfiguration"},a.AddFallbacks=function(i,e,o){return i.SHEEN&&e.addFallback(o++,"SHEEN"),o},a.AddUniforms=function(i){i.push("vSheenColor","vSheenRoughness","vSheenInfos","sheenMatrix","sheenRoughnessMatrix")},a.PrepareUniformBuffer=function(i){i.addUniform("vSheenColor",4),i.addUniform("vSheenRoughness",1),i.addUniform("vSheenInfos",4),i.addUniform("sheenMatrix",16),i.addUniform("sheenRoughnessMatrix",16)},a.AddSamplers=function(i){i.push("sheenSampler"),i.push("sheenRoughnessSampler")},a.prototype.copyTo=function(i){SerializationHelper.Clone(function(){return i},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.prototype.parse=function(i,e,o){var s=this;SerializationHelper.Parse(function(){return s},i,e,o)},__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"isEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"linkSheenWithAlbedo",void 0),__decorate([serialize()],a.prototype,"intensity",void 0),__decorate([serializeAsColor3()],a.prototype,"color",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"useRoughnessFromMainTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"roughness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"textureRoughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"albedoScaling",void 0),a}(),PBRSubSurfaceConfiguration=function(){function a(i,e,o){this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Color3.White(),this.tintColorAtDistance=1,this.diffusionDistance=Color3.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._internalMarkAllSubMeshesAsTexturesDirty=i,this._internalMarkScenePrePassDirty=e,this._scene=o}return Object.defineProperty(a.prototype,"scatteringDiffusionProfile",{get:function(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null},set:function(i){!this._scene.enableSubSurfaceForPrePass()||i&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(i))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"volumeIndexOfRefraction",{get:function(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction},set:function(i){i>=1?this._volumeIndexOfRefraction=i:this._volumeIndexOfRefraction=-1},enumerable:!1,configurable:!0}),a.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},a.prototype._markScenePrePassDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()},a.prototype.isReadyForSubMesh=function(i,e){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(i._areTexturesDirty&&e.texturesEnabled){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;var o=this._getRefractionTexture(e);if(o&&MaterialFlags.RefractionTextureEnabled&&!o.isReadyOrNotBlocking())return!1}return!0},a.prototype.prepareDefines=function(i,e){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){i.SUBSURFACE=!1,i.SS_TRANSLUCENCY=!1,i.SS_SCATTERING=!1,i.SS_REFRACTION=!1;return}if(i._areTexturesDirty){if(i.SUBSURFACE=!1,i.SS_TRANSLUCENCY=this._isTranslucencyEnabled,i.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,i.SS_SCATTERING=this._isScatteringEnabled,i.SS_THICKNESSANDMASK_TEXTURE=!1,i.SS_REFRACTIONINTENSITY_TEXTURE=!1,i.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,i.SS_HAS_THICKNESS=!1,i.SS_MASK_FROM_THICKNESS_TEXTURE=!1,i.SS_USE_GLTF_TEXTURES=!1,i.SS_REFRACTION=!1,i.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,i.SS_REFRACTIONMAP_3D=!1,i.SS_GAMMAREFRACTION=!1,i.SS_RGBDREFRACTION=!1,i.SS_LINEARSPECULARREFRACTION=!1,i.SS_REFRACTIONMAP_OPPOSITEZ=!1,i.SS_LODINREFRACTIONALPHA=!1,i.SS_LINKREFRACTIONTOTRANSPARENCY=!1,i.SS_ALBEDOFORREFRACTIONTINT=!1,i.SS_ALBEDOFORTRANSLUCENCYTINT=!1,i.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,i.SS_USE_THICKNESS_AS_DEPTH=!1,this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled){i.SUBSURFACE=!0;var o=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,s=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,c=(o||!this._refractionIntensityTexture)&&(s||!this._translucencyIntensityTexture);i._areTexturesDirty&&e.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture,i,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&!c&&MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture,i,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&!c&&MaterialHelper.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,i,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),i.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,i.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&c,i.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,i.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&c,i.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&c}if(this._isRefractionEnabled&&e.texturesEnabled){var d=this._getRefractionTexture(e);d&&MaterialFlags.RefractionTextureEnabled&&(i.SS_REFRACTION=!0,i.SS_REFRACTIONMAP_3D=d.isCube,i.SS_GAMMAREFRACTION=d.gammaSpace,i.SS_RGBDREFRACTION=d.isRGBD,i.SS_LINEARSPECULARREFRACTION=d.linearSpecularLOD,i.SS_REFRACTIONMAP_OPPOSITEZ=d.invertZ,i.SS_LODINREFRACTIONALPHA=d.lodLevelInAlpha,i.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,i.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,i.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=d.isCube&&d.boundingBoxSize,i.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(i.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}},a.prototype.hardBindForSubMesh=function(i,e,o,s,c,d,_){if(!(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)){_.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]);var b=Math.max(Math.abs(TmpVectors.Vector3[0].x),Math.abs(TmpVectors.Vector3[0].y),Math.abs(TmpVectors.Vector3[0].z));i.updateFloat2("vThicknessParam",this.minimumThickness*b,(this.maximumThickness-this.minimumThickness)*b)}},a.prototype.bindForSubMesh=function(i,e,o,s,c,d,_){if(!(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)){var b=_.materialDefines,k=this._getRefractionTexture(e);if(!i.useUbo||!s||!i.isSync){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&(i.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),MaterialHelper.BindTextureMatrix(this._thicknessTexture,i,"thickness")),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&b.SS_REFRACTIONINTENSITY_TEXTURE&&(i.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture,i,"refractionIntensity")),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&b.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(i.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture,i,"translucencyIntensity")),k&&MaterialFlags.RefractionTextureEnabled){i.updateMatrix("refractionMatrix",k.getReflectionTextureMatrix());var j=1;k.isCube||k.depth&&(j=k.depth);var $=k.getSize().width,_e=this.volumeIndexOfRefraction;if(i.updateFloat4("vRefractionInfos",k.level,1/_e,j,this._invertRefractionY?-1:1),i.updateFloat4("vRefractionMicrosurfaceInfos",$,k.lodGenerationScale,k.lodGenerationOffset,1/this.indexOfRefraction),d&&i.updateFloat2("vRefractionFilteringInfo",$,Scalar.Log2($)),k.boundingBoxSize){var et=k;i.updateVector3("vRefractionPosition",et.boundingBoxPosition),i.updateVector3("vRefractionSize",et.boundingBoxSize)}}this.isScatteringEnabled&&i.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),i.updateColor3("vDiffusionDistance",this.diffusionDistance),i.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),i.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}e.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&i.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&b.SS_REFRACTIONINTENSITY_TEXTURE&&i.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&b.SS_TRANSLUCENCYINTENSITY_TEXTURE&&i.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),k&&MaterialFlags.RefractionTextureEnabled&&(c?i.setTexture("refractionSampler",k):(i.setTexture("refractionSampler",k._lodTextureMid||k),i.setTexture("refractionSamplerLow",k._lodTextureLow||k),i.setTexture("refractionSamplerHigh",k._lodTextureHigh||k))))}},a.prototype.unbind=function(i){return this._refractionTexture&&this._refractionTexture.isRenderTarget?(i.setTexture("refractionSampler",null),!0):!1},a.prototype._getRefractionTexture=function(i){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?i.environmentTexture:null},Object.defineProperty(a.prototype,"disableAlphaBlending",{get:function(){return this.isRefractionEnabled&&this._linkRefractionWithTransparency},enumerable:!1,configurable:!0}),a.prototype.fillRenderTargetTextures=function(i){MaterialFlags.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&i.push(this._refractionTexture)},a.prototype.hasTexture=function(i){return this._thicknessTexture===i||this._refractionTexture===i},a.prototype.hasRenderTargetTextures=function(){return!!(MaterialFlags.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)},a.prototype.getActiveTextures=function(i){this._thicknessTexture&&i.push(this._thicknessTexture),this._refractionTexture&&i.push(this._refractionTexture)},a.prototype.getAnimatables=function(i){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&i.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&i.push(this._refractionTexture)},a.prototype.dispose=function(i){i&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())},a.prototype.getClassName=function(){return"PBRSubSurfaceConfiguration"},a.AddFallbacks=function(i,e,o){return i.SS_SCATTERING&&e.addFallback(o++,"SS_SCATTERING"),i.SS_TRANSLUCENCY&&e.addFallback(o++,"SS_TRANSLUCENCY"),o},a.AddUniforms=function(i){i.push("vDiffusionDistance","vTintColor","vSubSurfaceIntensity","vRefractionMicrosurfaceInfos","vRefractionFilteringInfo","vRefractionInfos","vThicknessInfos","vRefractionIntensityInfos","vTranslucencyIntensityInfos","vThicknessParam","vRefractionPosition","vRefractionSize","refractionMatrix","thicknessMatrix","refractionIntensityMatrix","translucencyIntensityMatrix","scatteringDiffusionProfile")},a.AddSamplers=function(i){i.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")},a.PrepareUniformBuffer=function(i){i.addUniform("vRefractionMicrosurfaceInfos",4),i.addUniform("vRefractionFilteringInfo",2),i.addUniform("vTranslucencyIntensityInfos",2),i.addUniform("vRefractionInfos",4),i.addUniform("refractionMatrix",16),i.addUniform("vThicknessInfos",2),i.addUniform("vRefractionIntensityInfos",2),i.addUniform("thicknessMatrix",16),i.addUniform("refractionIntensityMatrix",16),i.addUniform("translucencyIntensityMatrix",16),i.addUniform("vThicknessParam",2),i.addUniform("vDiffusionDistance",3),i.addUniform("vTintColor",4),i.addUniform("vSubSurfaceIntensity",3),i.addUniform("vRefractionPosition",3),i.addUniform("vRefractionSize",3),i.addUniform("scatteringDiffusionProfile",1)},a.prototype.copyTo=function(i){SerializationHelper.Clone(function(){return i},this)},a.prototype.serialize=function(){return SerializationHelper.Serialize(this)},a.prototype.parse=function(i,e,o){var s=this;SerializationHelper.Parse(function(){return s},i,e,o)},__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"isRefractionEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"isTranslucencyEnabled",void 0),__decorate([serialize(),expandToProperty("_markScenePrePassDirty")],a.prototype,"isScatteringEnabled",void 0),__decorate([serialize()],a.prototype,"_scatteringDiffusionProfileIndex",void 0),__decorate([serialize()],a.prototype,"refractionIntensity",void 0),__decorate([serialize()],a.prototype,"translucencyIntensity",void 0),__decorate([serialize()],a.prototype,"useAlbedoToTintRefraction",void 0),__decorate([serialize()],a.prototype,"useAlbedoToTintTranslucency",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"thicknessTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"refractionTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"indexOfRefraction",void 0),__decorate([serialize()],a.prototype,"_volumeIndexOfRefraction",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"volumeIndexOfRefraction",null),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"invertRefractionY",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"linkRefractionWithTransparency",void 0),__decorate([serialize()],a.prototype,"minimumThickness",void 0),__decorate([serialize()],a.prototype,"maximumThickness",void 0),__decorate([serialize()],a.prototype,"useThicknessAsDepth",void 0),__decorate([serializeAsColor3()],a.prototype,"tintColor",void 0),__decorate([serialize()],a.prototype,"tintColorAtDistance",void 0),__decorate([serializeAsColor3()],a.prototype,"diffusionDistance",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"useMaskFromThicknessTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"refractionIntensityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"translucencyIntensityTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],a.prototype,"useGltfStyleTextures",void 0),a}(),name$1e="pbrFragmentDeclaration",shader$1e=`uniform vec4 vEyePosition;
  5151. uniform vec3 vReflectionColor;
  5152. uniform vec4 vAlbedoColor;
  5153. uniform vec4 vLightingIntensity;
  5154. uniform vec4 vReflectivityColor;
  5155. uniform vec4 vMetallicReflectanceFactors;
  5156. uniform vec3 vEmissiveColor;
  5157. uniform float visibility;
  5158. uniform vec3 vAmbientColor;
  5159. #ifdef ALBEDO
  5160. uniform vec2 vAlbedoInfos;
  5161. #endif
  5162. #ifdef AMBIENT
  5163. uniform vec4 vAmbientInfos;
  5164. #endif
  5165. #ifdef BUMP
  5166. uniform vec3 vBumpInfos;
  5167. uniform vec2 vTangentSpaceParams;
  5168. #endif
  5169. #ifdef OPACITY
  5170. uniform vec2 vOpacityInfos;
  5171. #endif
  5172. #ifdef EMISSIVE
  5173. uniform vec2 vEmissiveInfos;
  5174. #endif
  5175. #ifdef LIGHTMAP
  5176. uniform vec2 vLightmapInfos;
  5177. #endif
  5178. #ifdef REFLECTIVITY
  5179. uniform vec3 vReflectivityInfos;
  5180. #endif
  5181. #ifdef MICROSURFACEMAP
  5182. uniform vec2 vMicroSurfaceSamplerInfos;
  5183. #endif
  5184. #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)
  5185. uniform mat4 view;
  5186. #endif
  5187. #ifdef REFLECTION
  5188. uniform vec2 vReflectionInfos;
  5189. #ifdef REALTIME_FILTERING
  5190. uniform vec2 vReflectionFilteringInfo;
  5191. #endif
  5192. uniform mat4 reflectionMatrix;
  5193. uniform vec3 vReflectionMicrosurfaceInfos;
  5194. #if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
  5195. uniform vec3 vReflectionPosition;
  5196. uniform vec3 vReflectionSize;
  5197. #endif
  5198. #endif
  5199. #if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)
  5200. uniform vec3 vRefractionPosition;
  5201. uniform vec3 vRefractionSize;
  5202. #endif
  5203. #ifdef CLEARCOAT
  5204. uniform vec2 vClearCoatParams;
  5205. uniform vec4 vClearCoatRefractionParams;
  5206. #if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
  5207. uniform vec4 vClearCoatInfos;
  5208. #endif
  5209. #ifdef CLEARCOAT_TEXTURE
  5210. uniform mat4 clearCoatMatrix;
  5211. #endif
  5212. #ifdef CLEARCOAT_TEXTURE_ROUGHNESS
  5213. uniform mat4 clearCoatRoughnessMatrix;
  5214. #endif
  5215. #ifdef CLEARCOAT_BUMP
  5216. uniform vec2 vClearCoatBumpInfos;
  5217. uniform vec2 vClearCoatTangentSpaceParams;
  5218. uniform mat4 clearCoatBumpMatrix;
  5219. #endif
  5220. #ifdef CLEARCOAT_TINT
  5221. uniform vec4 vClearCoatTintParams;
  5222. uniform float clearCoatColorAtDistance;
  5223. #ifdef CLEARCOAT_TINT_TEXTURE
  5224. uniform vec2 vClearCoatTintInfos;
  5225. uniform mat4 clearCoatTintMatrix;
  5226. #endif
  5227. #endif
  5228. #endif
  5229. #ifdef ANISOTROPIC
  5230. uniform vec3 vAnisotropy;
  5231. #ifdef ANISOTROPIC_TEXTURE
  5232. uniform vec2 vAnisotropyInfos;
  5233. uniform mat4 anisotropyMatrix;
  5234. #endif
  5235. #endif
  5236. #ifdef SHEEN
  5237. uniform vec4 vSheenColor;
  5238. #ifdef SHEEN_ROUGHNESS
  5239. uniform float vSheenRoughness;
  5240. #endif
  5241. #if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
  5242. uniform vec4 vSheenInfos;
  5243. #endif
  5244. #ifdef SHEEN_TEXTURE
  5245. uniform mat4 sheenMatrix;
  5246. #endif
  5247. #ifdef SHEEN_TEXTURE_ROUGHNESS
  5248. uniform mat4 sheenRoughnessMatrix;
  5249. #endif
  5250. #endif
  5251. #ifdef SUBSURFACE
  5252. #ifdef SS_REFRACTION
  5253. uniform vec4 vRefractionMicrosurfaceInfos;
  5254. uniform vec4 vRefractionInfos;
  5255. uniform mat4 refractionMatrix;
  5256. #ifdef REALTIME_FILTERING
  5257. uniform vec2 vRefractionFilteringInfo;
  5258. #endif
  5259. #endif
  5260. #ifdef SS_THICKNESSANDMASK_TEXTURE
  5261. uniform vec2 vThicknessInfos;
  5262. uniform mat4 thicknessMatrix;
  5263. #endif
  5264. #ifdef SS_REFRACTIONINTENSITY_TEXTURE
  5265. uniform vec2 vRefractionIntensityInfos;
  5266. uniform mat4 refractionIntensityMatrix;
  5267. #endif
  5268. #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
  5269. uniform vec2 vTranslucencyIntensityInfos;
  5270. uniform mat4 translucencyIntensityMatrix;
  5271. #endif
  5272. uniform vec2 vThicknessParam;
  5273. uniform vec3 vDiffusionDistance;
  5274. uniform vec4 vTintColor;
  5275. uniform vec3 vSubSurfaceIntensity;
  5276. #endif
  5277. #ifdef PREPASS
  5278. #ifdef SS_SCATTERING
  5279. uniform float scatteringDiffusionProfile;
  5280. #endif
  5281. #endif
  5282. #if DEBUGMODE>0
  5283. uniform vec2 vDebugMode;
  5284. #endif
  5285. #ifdef DETAIL
  5286. uniform vec4 vDetailInfos;
  5287. #endif
  5288. #ifdef USESPHERICALFROMREFLECTIONMAP
  5289. #ifdef SPHERICAL_HARMONICS
  5290. uniform vec3 vSphericalL00;
  5291. uniform vec3 vSphericalL1_1;
  5292. uniform vec3 vSphericalL10;
  5293. uniform vec3 vSphericalL11;
  5294. uniform vec3 vSphericalL2_2;
  5295. uniform vec3 vSphericalL2_1;
  5296. uniform vec3 vSphericalL20;
  5297. uniform vec3 vSphericalL21;
  5298. uniform vec3 vSphericalL22;
  5299. #else
  5300. uniform vec3 vSphericalX;
  5301. uniform vec3 vSphericalY;
  5302. uniform vec3 vSphericalZ;
  5303. uniform vec3 vSphericalXX_ZZ;
  5304. uniform vec3 vSphericalYY_ZZ;
  5305. uniform vec3 vSphericalZZ;
  5306. uniform vec3 vSphericalXY;
  5307. uniform vec3 vSphericalYZ;
  5308. uniform vec3 vSphericalZX;
  5309. #endif
  5310. #endif
  5311. `;ShaderStore.IncludesShadersStore[name$1e]=shader$1e;var name$1d="pbrUboDeclaration",shader$1d=`layout(std140,column_major) uniform;
  5312. uniform Material {
  5313. vec2 vAlbedoInfos;
  5314. vec4 vAmbientInfos;
  5315. vec2 vOpacityInfos;
  5316. vec2 vEmissiveInfos;
  5317. vec2 vLightmapInfos;
  5318. vec3 vReflectivityInfos;
  5319. vec2 vMicroSurfaceSamplerInfos;
  5320. vec2 vReflectionInfos;
  5321. vec2 vReflectionFilteringInfo;
  5322. vec3 vReflectionPosition;
  5323. vec3 vReflectionSize;
  5324. vec3 vBumpInfos;
  5325. mat4 albedoMatrix;
  5326. mat4 ambientMatrix;
  5327. mat4 opacityMatrix;
  5328. mat4 emissiveMatrix;
  5329. mat4 lightmapMatrix;
  5330. mat4 reflectivityMatrix;
  5331. mat4 microSurfaceSamplerMatrix;
  5332. mat4 bumpMatrix;
  5333. vec2 vTangentSpaceParams;
  5334. mat4 reflectionMatrix;
  5335. vec3 vReflectionColor;
  5336. vec4 vAlbedoColor;
  5337. vec4 vLightingIntensity;
  5338. vec3 vReflectionMicrosurfaceInfos;
  5339. float pointSize;
  5340. vec4 vReflectivityColor;
  5341. vec3 vEmissiveColor;
  5342. vec3 vAmbientColor;
  5343. vec2 vDebugMode;
  5344. vec4 vMetallicReflectanceFactors;
  5345. vec2 vMetallicReflectanceInfos;
  5346. mat4 metallicReflectanceMatrix;
  5347. vec2 vReflectanceInfos;
  5348. mat4 reflectanceMatrix;
  5349. vec2 vClearCoatParams;
  5350. vec4 vClearCoatRefractionParams;
  5351. vec4 vClearCoatInfos;
  5352. mat4 clearCoatMatrix;
  5353. mat4 clearCoatRoughnessMatrix;
  5354. vec2 vClearCoatBumpInfos;
  5355. vec2 vClearCoatTangentSpaceParams;
  5356. mat4 clearCoatBumpMatrix;
  5357. vec4 vClearCoatTintParams;
  5358. float clearCoatColorAtDistance;
  5359. vec2 vClearCoatTintInfos;
  5360. mat4 clearCoatTintMatrix;
  5361. vec3 vAnisotropy;
  5362. vec2 vAnisotropyInfos;
  5363. mat4 anisotropyMatrix;
  5364. vec4 vSheenColor;
  5365. float vSheenRoughness;
  5366. vec4 vSheenInfos;
  5367. mat4 sheenMatrix;
  5368. mat4 sheenRoughnessMatrix;
  5369. vec4 vRefractionMicrosurfaceInfos;
  5370. vec2 vRefractionFilteringInfo;
  5371. vec2 vTranslucencyIntensityInfos;
  5372. vec4 vRefractionInfos;
  5373. mat4 refractionMatrix;
  5374. vec2 vThicknessInfos;
  5375. vec2 vRefractionIntensityInfos;
  5376. mat4 thicknessMatrix;
  5377. mat4 refractionIntensityMatrix;
  5378. mat4 translucencyIntensityMatrix;
  5379. vec2 vThicknessParam;
  5380. vec3 vDiffusionDistance;
  5381. vec4 vTintColor;
  5382. vec3 vSubSurfaceIntensity;
  5383. vec3 vRefractionPosition;
  5384. vec3 vRefractionSize;
  5385. float scatteringDiffusionProfile;
  5386. vec4 vDetailInfos;
  5387. mat4 detailMatrix;
  5388. vec3 vSphericalL00;
  5389. vec3 vSphericalL1_1;
  5390. vec3 vSphericalL10;
  5391. vec3 vSphericalL11;
  5392. vec3 vSphericalL2_2;
  5393. vec3 vSphericalL2_1;
  5394. vec3 vSphericalL20;
  5395. vec3 vSphericalL21;
  5396. vec3 vSphericalL22;
  5397. vec3 vSphericalX;
  5398. vec3 vSphericalY;
  5399. vec3 vSphericalZ;
  5400. vec3 vSphericalXX_ZZ;
  5401. vec3 vSphericalYY_ZZ;
  5402. vec3 vSphericalZZ;
  5403. vec3 vSphericalXY;
  5404. vec3 vSphericalYZ;
  5405. vec3 vSphericalZX;
  5406. };
  5407. #include<sceneUboDeclaration>
  5408. #include<meshUboDeclaration>
  5409. `;ShaderStore.IncludesShadersStore[name$1d]=shader$1d;var name$1c="pbrFragmentExtraDeclaration",shader$1c=`
  5410. varying vec3 vPositionW;
  5411. #if DEBUGMODE>0
  5412. varying vec4 vClipSpacePosition;
  5413. #endif
  5414. #include<mainUVVaryingDeclaration>[1..7]
  5415. #ifdef NORMAL
  5416. varying vec3 vNormalW;
  5417. #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
  5418. varying vec3 vEnvironmentIrradiance;
  5419. #endif
  5420. #endif
  5421. #ifdef VERTEXCOLOR
  5422. varying vec4 vColor;
  5423. #endif`;ShaderStore.IncludesShadersStore[name$1c]=shader$1c;var name$1b="samplerFragmentAlternateDeclaration",shader$1b=`#ifdef _DEFINENAME_
  5424. #if _DEFINENAME_DIRECTUV == 1
  5425. #define v_VARYINGNAME_UV vMainUV1
  5426. #elif _DEFINENAME_DIRECTUV == 2
  5427. #define v_VARYINGNAME_UV vMainUV2
  5428. #elif _DEFINENAME_DIRECTUV == 3
  5429. #define v_VARYINGNAME_UV vMainUV3
  5430. #elif _DEFINENAME_DIRECTUV == 4
  5431. #define v_VARYINGNAME_UV vMainUV4
  5432. #elif _DEFINENAME_DIRECTUV == 5
  5433. #define v_VARYINGNAME_UV vMainUV5
  5434. #elif _DEFINENAME_DIRECTUV == 6
  5435. #define v_VARYINGNAME_UV vMainUV6
  5436. #else
  5437. varying vec2 v_VARYINGNAME_UV;
  5438. #endif
  5439. #endif
  5440. `;ShaderStore.IncludesShadersStore[name$1b]=shader$1b;var name$1a="pbrFragmentSamplersDeclaration",shader$1a=`#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)
  5441. #include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
  5442. #include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
  5443. #include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
  5444. #include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
  5445. #include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)
  5446. #include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)
  5447. #include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)
  5448. #include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)
  5449. #ifdef CLEARCOAT
  5450. #include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)
  5451. #include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
  5452. #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)
  5453. uniform sampler2D clearCoatRoughnessSampler;
  5454. #endif
  5455. #include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)
  5456. #include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)
  5457. #endif
  5458. #ifdef SHEEN
  5459. #include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)
  5460. #include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
  5461. #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)
  5462. uniform sampler2D sheenRoughnessSampler;
  5463. #endif
  5464. #endif
  5465. #ifdef ANISOTROPIC
  5466. #include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)
  5467. #endif
  5468. #ifdef REFLECTION
  5469. #ifdef REFLECTIONMAP_3D
  5470. #define sampleReflection(s,c) textureCube(s,c)
  5471. uniform samplerCube reflectionSampler;
  5472. #ifdef LODBASEDMICROSFURACE
  5473. #define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
  5474. #else
  5475. uniform samplerCube reflectionSamplerLow;
  5476. uniform samplerCube reflectionSamplerHigh;
  5477. #endif
  5478. #ifdef USEIRRADIANCEMAP
  5479. uniform samplerCube irradianceSampler;
  5480. #endif
  5481. #else
  5482. #define sampleReflection(s,c) texture2D(s,c)
  5483. uniform sampler2D reflectionSampler;
  5484. #ifdef LODBASEDMICROSFURACE
  5485. #define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
  5486. #else
  5487. uniform sampler2D reflectionSamplerLow;
  5488. uniform sampler2D reflectionSamplerHigh;
  5489. #endif
  5490. #ifdef USEIRRADIANCEMAP
  5491. uniform sampler2D irradianceSampler;
  5492. #endif
  5493. #endif
  5494. #ifdef REFLECTIONMAP_SKYBOX
  5495. varying vec3 vPositionUVW;
  5496. #else
  5497. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  5498. varying vec3 vDirectionW;
  5499. #endif
  5500. #endif
  5501. #endif
  5502. #ifdef ENVIRONMENTBRDF
  5503. uniform sampler2D environmentBrdfSampler;
  5504. #endif
  5505. #ifdef SUBSURFACE
  5506. #ifdef SS_REFRACTION
  5507. #ifdef SS_REFRACTIONMAP_3D
  5508. #define sampleRefraction(s,c) textureCube(s,c)
  5509. uniform samplerCube refractionSampler;
  5510. #ifdef LODBASEDMICROSFURACE
  5511. #define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)
  5512. #else
  5513. uniform samplerCube refractionSamplerLow;
  5514. uniform samplerCube refractionSamplerHigh;
  5515. #endif
  5516. #else
  5517. #define sampleRefraction(s,c) texture2D(s,c)
  5518. uniform sampler2D refractionSampler;
  5519. #ifdef LODBASEDMICROSFURACE
  5520. #define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)
  5521. #else
  5522. uniform sampler2D refractionSamplerLow;
  5523. uniform sampler2D refractionSamplerHigh;
  5524. #endif
  5525. #endif
  5526. #endif
  5527. #include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)
  5528. #include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)
  5529. #include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)
  5530. #endif`;ShaderStore.IncludesShadersStore[name$1a]=shader$1a;var name$19="subSurfaceScatteringFunctions",shader$19=`bool testLightingForSSS(float diffusionProfile)
  5531. {
  5532. return diffusionProfile<1.;
  5533. }`;ShaderStore.IncludesShadersStore[name$19]=shader$19;var name$18="importanceSampling",shader$18=`
  5534. vec3 hemisphereCosSample(vec2 u) {
  5535. float phi=2.*PI*u.x;
  5536. float cosTheta2=1.-u.y;
  5537. float cosTheta=sqrt(cosTheta2);
  5538. float sinTheta=sqrt(1.-cosTheta2);
  5539. return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);
  5540. }
  5541. vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {
  5542. float phi=2.*PI*u.x;
  5543. float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));
  5544. float cosTheta=sqrt(cosTheta2);
  5545. float sinTheta=sqrt(1.-cosTheta2);
  5546. return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);
  5547. }
  5548. vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) {
  5549. float phi=2.*PI*u.x;
  5550. float sinTheta=pow(u.y,a/(2.*a+1.));
  5551. float cosTheta=sqrt(1.-sinTheta*sinTheta);
  5552. return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);
  5553. }`;ShaderStore.IncludesShadersStore[name$18]=shader$18;var name$17="pbrHelperFunctions",shader$17=`
  5554. #define RECIPROCAL_PI2 0.15915494
  5555. #define RECIPROCAL_PI 0.31830988618
  5556. #define MINIMUMVARIANCE 0.0005
  5557. float convertRoughnessToAverageSlope(float roughness)
  5558. {
  5559. return square(roughness)+MINIMUMVARIANCE;
  5560. }
  5561. float fresnelGrazingReflectance(float reflectance0) {
  5562. float reflectance90=saturate(reflectance0*25.0);
  5563. return reflectance90;
  5564. }
  5565. vec2 getAARoughnessFactors(vec3 normalVector) {
  5566. #ifdef SPECULARAA
  5567. vec3 nDfdx=dFdx(normalVector.xyz);
  5568. vec3 nDfdy=dFdy(normalVector.xyz);
  5569. float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));
  5570. float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);
  5571. float geometricAlphaGFactor=sqrt(slopeSquare);
  5572. geometricAlphaGFactor*=0.75;
  5573. return vec2(geometricRoughnessFactor,geometricAlphaGFactor);
  5574. #else
  5575. return vec2(0.);
  5576. #endif
  5577. }
  5578. #ifdef ANISOTROPIC
  5579. vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {
  5580. float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);
  5581. float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);
  5582. return vec2(alphaT,alphaB);
  5583. }
  5584. vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy) {
  5585. vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;
  5586. vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);
  5587. vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);
  5588. vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));
  5589. return anisotropicNormal;
  5590. }
  5591. #endif
  5592. #if defined(CLEARCOAT) || defined(SS_REFRACTION)
  5593. vec3 cocaLambert(vec3 alpha,float distance) {
  5594. return exp(-alpha*distance);
  5595. }
  5596. vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {
  5597. return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));
  5598. }
  5599. vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {
  5600. return -log(color)/distance;
  5601. }
  5602. vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {
  5603. vec3 clearCoatAbsorption=mix(vec3(1.0),
  5604. cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),
  5605. clearCoatIntensity);
  5606. return clearCoatAbsorption;
  5607. }
  5608. #endif
  5609. #ifdef MICROSURFACEAUTOMATIC
  5610. float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)
  5611. {
  5612. const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;
  5613. float reflectivityLuminance=getLuminance(reflectivityColor);
  5614. float reflectivityLuma=sqrt(reflectivityLuminance);
  5615. microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;
  5616. return microSurface;
  5617. }
  5618. #endif`;ShaderStore.IncludesShadersStore[name$17]=shader$17;var name$16="harmonicsFunctions",shader$16=`#ifdef USESPHERICALFROMREFLECTIONMAP
  5619. #ifdef SPHERICAL_HARMONICS
  5620. vec3 computeEnvironmentIrradiance(vec3 normal) {
  5621. return vSphericalL00
  5622. +vSphericalL1_1*(normal.y)
  5623. +vSphericalL10*(normal.z)
  5624. +vSphericalL11*(normal.x)
  5625. +vSphericalL2_2*(normal.y*normal.x)
  5626. +vSphericalL2_1*(normal.y*normal.z)
  5627. +vSphericalL20*((3.0*normal.z*normal.z)-1.0)
  5628. +vSphericalL21*(normal.z*normal.x)
  5629. +vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));
  5630. }
  5631. #else
  5632. vec3 computeEnvironmentIrradiance(vec3 normal) {
  5633. float Nx=normal.x;
  5634. float Ny=normal.y;
  5635. float Nz=normal.z;
  5636. vec3 C1=vSphericalZZ.rgb;
  5637. vec3 Cx=vSphericalX.rgb;
  5638. vec3 Cy=vSphericalY.rgb;
  5639. vec3 Cz=vSphericalZ.rgb;
  5640. vec3 Cxx_zz=vSphericalXX_ZZ.rgb;
  5641. vec3 Cyy_zz=vSphericalYY_ZZ.rgb;
  5642. vec3 Cxy=vSphericalXY.rgb;
  5643. vec3 Cyz=vSphericalYZ.rgb;
  5644. vec3 Czx=vSphericalZX.rgb;
  5645. vec3 a1=Cyy_zz*Ny+Cy;
  5646. vec3 a2=Cyz*Nz+a1;
  5647. vec3 b1=Czx*Nz+Cx;
  5648. vec3 b2=Cxy*Ny+b1;
  5649. vec3 b3=Cxx_zz*Nx+b2;
  5650. vec3 t1=Cz*Nz+C1;
  5651. vec3 t2=a2*Ny+t1;
  5652. vec3 t3=b3*Nx+t2;
  5653. return t3;
  5654. }
  5655. #endif
  5656. #endif`;ShaderStore.IncludesShadersStore[name$16]=shader$16;var name$15="pbrDirectLightingSetupFunctions",shader$15=`
  5657. struct preLightingInfo
  5658. {
  5659. vec3 lightOffset;
  5660. float lightDistanceSquared;
  5661. float lightDistance;
  5662. float attenuation;
  5663. vec3 L;
  5664. vec3 H;
  5665. float NdotV;
  5666. float NdotLUnclamped;
  5667. float NdotL;
  5668. float VdotH;
  5669. float roughness;
  5670. };
  5671. preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {
  5672. preLightingInfo result;
  5673. result.lightOffset=lightData.xyz-vPositionW;
  5674. result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);
  5675. result.lightDistance=sqrt(result.lightDistanceSquared);
  5676. result.L=normalize(result.lightOffset);
  5677. result.H=normalize(V+result.L);
  5678. result.VdotH=saturate(dot(V,result.H));
  5679. result.NdotLUnclamped=dot(N,result.L);
  5680. result.NdotL=saturateEps(result.NdotLUnclamped);
  5681. return result;
  5682. }
  5683. preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {
  5684. preLightingInfo result;
  5685. result.lightDistance=length(-lightData.xyz);
  5686. result.L=normalize(-lightData.xyz);
  5687. result.H=normalize(V+result.L);
  5688. result.VdotH=saturate(dot(V,result.H));
  5689. result.NdotLUnclamped=dot(N,result.L);
  5690. result.NdotL=saturateEps(result.NdotLUnclamped);
  5691. return result;
  5692. }
  5693. preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {
  5694. preLightingInfo result;
  5695. result.NdotL=dot(N,lightData.xyz)*0.5+0.5;
  5696. result.NdotL=saturateEps(result.NdotL);
  5697. result.NdotLUnclamped=result.NdotL;
  5698. #ifdef SPECULARTERM
  5699. result.L=normalize(lightData.xyz);
  5700. result.H=normalize(V+result.L);
  5701. result.VdotH=saturate(dot(V,result.H));
  5702. #endif
  5703. return result;
  5704. }`;ShaderStore.IncludesShadersStore[name$15]=shader$15;var name$14="pbrDirectLightingFalloffFunctions",shader$14=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)
  5705. {
  5706. return max(0.,1.0-length(lightOffset)/range);
  5707. }
  5708. float computeDistanceLightFalloff_Physical(float lightDistanceSquared)
  5709. {
  5710. return 1.0/maxEps(lightDistanceSquared);
  5711. }
  5712. float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)
  5713. {
  5714. float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);
  5715. float factor=lightDistanceSquared*inverseSquaredRange;
  5716. float attenuation=saturate(1.0-factor*factor);
  5717. attenuation*=attenuation;
  5718. lightDistanceFalloff*=attenuation;
  5719. return lightDistanceFalloff;
  5720. }
  5721. float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)
  5722. {
  5723. #ifdef USEPHYSICALLIGHTFALLOFF
  5724. return computeDistanceLightFalloff_Physical(lightDistanceSquared);
  5725. #elif defined(USEGLTFLIGHTFALLOFF)
  5726. return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);
  5727. #else
  5728. return computeDistanceLightFalloff_Standard(lightOffset,range);
  5729. #endif
  5730. }
  5731. float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)
  5732. {
  5733. float falloff=0.0;
  5734. float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));
  5735. if (cosAngle>=cosHalfAngle)
  5736. {
  5737. falloff=max(0.,pow(cosAngle,exponent));
  5738. }
  5739. return falloff;
  5740. }
  5741. float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)
  5742. {
  5743. const float kMinusLog2ConeAngleIntensityRatio=6.64385618977;
  5744. float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);
  5745. vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);
  5746. float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));
  5747. return falloff;
  5748. }
  5749. float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)
  5750. {
  5751. float cd=dot(-lightDirection,directionToLightCenterW);
  5752. float falloff=saturate(cd*lightAngleScale+lightAngleOffset);
  5753. falloff*=falloff;
  5754. return falloff;
  5755. }
  5756. float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)
  5757. {
  5758. #ifdef USEPHYSICALLIGHTFALLOFF
  5759. return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);
  5760. #elif defined(USEGLTFLIGHTFALLOFF)
  5761. return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);
  5762. #else
  5763. return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);
  5764. #endif
  5765. }`;ShaderStore.IncludesShadersStore[name$14]=shader$14;var name$13="pbrBRDFFunctions",shader$13=`
  5766. #define FRESNEL_MAXIMUM_ON_ROUGH 0.25
  5767. #ifdef MS_BRDF_ENERGY_CONSERVATION
  5768. vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {
  5769. return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);
  5770. }
  5771. #endif
  5772. #ifdef ENVIRONMENTBRDF
  5773. vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {
  5774. vec2 UV=vec2(NdotV,perceptualRoughness);
  5775. vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);
  5776. #ifdef ENVIRONMENTBRDF_RGBD
  5777. brdfLookup.rgb=fromRGBD(brdfLookup.rgba);
  5778. #endif
  5779. return brdfLookup.rgb;
  5780. }
  5781. vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {
  5782. #ifdef BRDF_V_HEIGHT_CORRELATED
  5783. vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;
  5784. #else
  5785. vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;
  5786. #endif
  5787. return reflectance;
  5788. }
  5789. vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {
  5790. #ifdef BRDF_V_HEIGHT_CORRELATED
  5791. vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);
  5792. #else
  5793. vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;
  5794. #endif
  5795. return reflectance;
  5796. }
  5797. #endif
  5798. #if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)
  5799. vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
  5800. {
  5801. float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);
  5802. return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));
  5803. }
  5804. #endif
  5805. #if defined(SHEEN) && defined(ENVIRONMENTBRDF)
  5806. vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {
  5807. vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;
  5808. return sheenEnvironmentReflectance;
  5809. }
  5810. #endif
  5811. vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)
  5812. {
  5813. return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);
  5814. }
  5815. float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)
  5816. {
  5817. return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);
  5818. }
  5819. #ifdef CLEARCOAT
  5820. vec3 getR0RemappedForClearCoat(vec3 f0) {
  5821. #ifdef CLEARCOAT_DEFAULTIOR
  5822. #ifdef MOBILE
  5823. return saturate(f0*(f0*0.526868+0.529324)-0.0482256);
  5824. #else
  5825. return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);
  5826. #endif
  5827. #else
  5828. vec3 s=sqrt(f0);
  5829. vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);
  5830. return t*t;
  5831. #endif
  5832. }
  5833. #endif
  5834. float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)
  5835. {
  5836. float a2=square(alphaG);
  5837. float d=NdotH*NdotH*(a2-1.0)+1.0;
  5838. return a2/(PI*d*d);
  5839. }
  5840. #ifdef SHEEN
  5841. float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)
  5842. {
  5843. float invR=1./alphaG;
  5844. float cos2h=NdotH*NdotH;
  5845. float sin2h=1.-cos2h;
  5846. return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);
  5847. }
  5848. #endif
  5849. #ifdef ANISOTROPIC
  5850. float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {
  5851. float a2=alphaTB.x*alphaTB.y;
  5852. vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x*BdotH,a2*NdotH);
  5853. float v2=dot(v,v);
  5854. float w2=a2/v2;
  5855. return a2*w2*w2*RECIPROCAL_PI;
  5856. }
  5857. #endif
  5858. #ifdef BRDF_V_HEIGHT_CORRELATED
  5859. float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {
  5860. #ifdef MOBILE
  5861. float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);
  5862. float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);
  5863. return 0.5/(GGXV+GGXL);
  5864. #else
  5865. float a2=alphaG*alphaG;
  5866. float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);
  5867. float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);
  5868. return 0.5/(GGXV+GGXL);
  5869. #endif
  5870. }
  5871. #else
  5872. float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)
  5873. {
  5874. #ifdef MOBILE
  5875. return 1.0/(dot+alphaG+(1.0-alphaG)*dot ));
  5876. #else
  5877. float alphaSquared=alphaG*alphaG;
  5878. return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));
  5879. #endif
  5880. }
  5881. float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)
  5882. {
  5883. float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);
  5884. return visibility;
  5885. }
  5886. #endif
  5887. #ifdef ANISOTROPIC
  5888. float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {
  5889. float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));
  5890. float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));
  5891. float v=0.5/(lambdaV+lambdaL);
  5892. return v;
  5893. }
  5894. #endif
  5895. #ifdef CLEARCOAT
  5896. float visibility_Kelemen(float VdotH) {
  5897. return 0.25/(VdotH*VdotH);
  5898. }
  5899. #endif
  5900. #ifdef SHEEN
  5901. float visibility_Ashikhmin(float NdotL,float NdotV)
  5902. {
  5903. return 1./(4.*(NdotL+NdotV-NdotL*NdotV));
  5904. }
  5905. #endif
  5906. float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {
  5907. float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));
  5908. float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));
  5909. float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;
  5910. float fresnel =
  5911. (1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *
  5912. (1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);
  5913. return fresnel/PI;
  5914. }
  5915. #ifdef SS_TRANSLUCENCY
  5916. vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {
  5917. vec3 S=1./maxEps(diffusionDistance);
  5918. vec3 temp=exp((-0.333333333*thickness)*S);
  5919. return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);
  5920. }
  5921. float computeWrappedDiffuseNdotL(float NdotL,float w) {
  5922. float t=1.0+w;
  5923. float invt2=1.0/square(t);
  5924. return saturate((NdotL+w)*invt2);
  5925. }
  5926. #endif
  5927. `;ShaderStore.IncludesShadersStore[name$13]=shader$13;var name$12="hdrFilteringFunctions",shader$12=`#ifdef NUM_SAMPLES
  5928. #if NUM_SAMPLES>0
  5929. #if defined(WEBGL2) || defined(WEBGPU)
  5930. float radicalInverse_VdC(uint bits)
  5931. {
  5932. bits=(bits << 16u) | (bits >> 16u);
  5933. bits=((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  5934. bits=((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  5935. bits=((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  5936. bits=((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  5937. return float(bits)*2.3283064365386963e-10;
  5938. }
  5939. vec2 hammersley(uint i,uint N)
  5940. {
  5941. return vec2(float(i)/float(N),radicalInverse_VdC(i));
  5942. }
  5943. #else
  5944. float vanDerCorpus(int n,int base)
  5945. {
  5946. float invBase=1.0/float(base);
  5947. float denom=1.0;
  5948. float result=0.0;
  5949. for(int i=0; i<32; ++i)
  5950. {
  5951. if(n>0)
  5952. {
  5953. denom=mod(float(n),2.0);
  5954. result+=denom*invBase;
  5955. invBase=invBase/2.0;
  5956. n=int(float(n)/2.0);
  5957. }
  5958. }
  5959. return result;
  5960. }
  5961. vec2 hammersley(int i,int N)
  5962. {
  5963. return vec2(float(i)/float(N),vanDerCorpus(i,2));
  5964. }
  5965. #endif
  5966. float log4(float x) {
  5967. return log2(x)/2.;
  5968. }
  5969. const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);
  5970. const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;
  5971. const float K=4.;
  5972. #define inline
  5973. vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
  5974. {
  5975. vec3 n=normalize(inputN);
  5976. vec3 result=vec3(0.0);
  5977. vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);
  5978. tangent=normalize(cross(tangent,n));
  5979. vec3 bitangent=cross(n,tangent);
  5980. mat3 tbn=mat3(tangent,bitangent,n);
  5981. float maxLevel=filteringInfo.y;
  5982. float dim0=filteringInfo.x;
  5983. float omegaP=(4.*PI)/(6.*dim0*dim0);
  5984. #if defined(WEBGL2) || defined(WEBGPU)
  5985. for(uint i=0u; i<NUM_SAMPLES; ++i)
  5986. #else
  5987. for(int i=0; i<NUM_SAMPLES; ++i)
  5988. #endif
  5989. {
  5990. vec2 Xi=hammersley(i,NUM_SAMPLES);
  5991. vec3 Ls=hemisphereCosSample(Xi);
  5992. Ls=normalize(Ls);
  5993. vec3 Ns=vec3(0.,0.,1.);
  5994. float NoL=dot(Ns,Ls);
  5995. if (NoL>0.) {
  5996. float pdf_inversed=PI/NoL;
  5997. float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;
  5998. float l=log4(omegaS)-log4(omegaP)+log4(K);
  5999. float mipLevel=clamp(l,0.0,maxLevel);
  6000. vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;
  6001. #ifdef GAMMA_INPUT
  6002. c=toLinearSpace(c);
  6003. #endif
  6004. result+=c;
  6005. }
  6006. }
  6007. result=result*NUM_SAMPLES_FLOAT_INVERSED;
  6008. return result;
  6009. }
  6010. #define inline
  6011. vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
  6012. {
  6013. vec3 n=normalize(inputN);
  6014. if (alphaG == 0.) {
  6015. vec3 c=textureCube(inputTexture,n).rgb;
  6016. #ifdef GAMMA_INPUT
  6017. c=toLinearSpace(c);
  6018. #endif
  6019. return c;
  6020. } else {
  6021. vec3 result=vec3(0.);
  6022. vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);
  6023. tangent=normalize(cross(tangent,n));
  6024. vec3 bitangent=cross(n,tangent);
  6025. mat3 tbn=mat3(tangent,bitangent,n);
  6026. float maxLevel=filteringInfo.y;
  6027. float dim0=filteringInfo.x;
  6028. float omegaP=(4.*PI)/(6.*dim0*dim0);
  6029. float weight=0.;
  6030. #if defined(WEBGL2) || defined(WEBGPU)
  6031. for(uint i=0u; i<NUM_SAMPLES; ++i)
  6032. #else
  6033. for(int i=0; i<NUM_SAMPLES; ++i)
  6034. #endif
  6035. {
  6036. vec2 Xi=hammersley(i,NUM_SAMPLES);
  6037. vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);
  6038. float NoV=1.;
  6039. float NoH=H.z;
  6040. float NoH2=H.z*H.z;
  6041. float NoL=2.*NoH2-1.;
  6042. vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);
  6043. L=normalize(L);
  6044. if (NoL>0.) {
  6045. float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);
  6046. float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;
  6047. float l=log4(omegaS)-log4(omegaP)+log4(K);
  6048. float mipLevel=clamp(float(l),0.0,maxLevel);
  6049. weight+=NoL;
  6050. vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;
  6051. #ifdef GAMMA_INPUT
  6052. c=toLinearSpace(c);
  6053. #endif
  6054. result+=c*NoL;
  6055. }
  6056. }
  6057. result=result/weight;
  6058. return result;
  6059. }
  6060. }
  6061. #endif
  6062. #endif`;ShaderStore.IncludesShadersStore[name$12]=shader$12;var name$11="pbrDirectLightingFunctions",shader$11=`#define CLEARCOATREFLECTANCE90 1.0
  6063. struct lightingInfo
  6064. {
  6065. vec3 diffuse;
  6066. #ifdef SPECULARTERM
  6067. vec3 specular;
  6068. #endif
  6069. #ifdef CLEARCOAT
  6070. vec4 clearCoat;
  6071. #endif
  6072. #ifdef SHEEN
  6073. vec3 sheen;
  6074. #endif
  6075. };
  6076. float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {
  6077. #if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)
  6078. float lightRoughness=lightRadius/lightDistance;
  6079. float totalRoughness=saturate(lightRoughness+roughness);
  6080. return totalRoughness;
  6081. #else
  6082. return roughness;
  6083. #endif
  6084. }
  6085. vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {
  6086. return mix(groundColor,lightColor,info.NdotL);
  6087. }
  6088. vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {
  6089. float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);
  6090. return diffuseTerm*info.attenuation*info.NdotL*lightColor;
  6091. }
  6092. #define inline
  6093. vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){
  6094. vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);
  6095. strq/=strq.w;
  6096. vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;
  6097. return toLinearSpace(textureColor);
  6098. }
  6099. #ifdef SS_TRANSLUCENCY
  6100. vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {
  6101. float NdotL=absEps(info.NdotLUnclamped);
  6102. float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);
  6103. float trAdapt=step(0.,info.NdotLUnclamped);
  6104. vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);
  6105. float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);
  6106. return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;
  6107. }
  6108. #endif
  6109. #ifdef SPECULARTERM
  6110. vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {
  6111. float NdotH=saturateEps(dot(N,info.H));
  6112. float roughness=max(info.roughness,geometricRoughnessFactor);
  6113. float alphaG=convertRoughnessToAverageSlope(roughness);
  6114. vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
  6115. float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);
  6116. #ifdef BRDF_V_HEIGHT_CORRELATED
  6117. float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);
  6118. #else
  6119. float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);
  6120. #endif
  6121. vec3 specTerm=fresnel*distribution*smithVisibility;
  6122. return specTerm*info.attenuation*info.NdotL*lightColor;
  6123. }
  6124. #endif
  6125. #ifdef ANISOTROPIC
  6126. vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {
  6127. float NdotH=saturateEps(dot(N,info.H));
  6128. float TdotH=dot(T,info.H);
  6129. float BdotH=dot(B,info.H);
  6130. float TdotV=dot(T,V);
  6131. float BdotV=dot(B,V);
  6132. float TdotL=dot(T,info.L);
  6133. float BdotL=dot(B,info.L);
  6134. float alphaG=convertRoughnessToAverageSlope(info.roughness);
  6135. vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);
  6136. alphaTB=max(alphaTB,square(geometricRoughnessFactor));
  6137. vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
  6138. float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);
  6139. float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);
  6140. vec3 specTerm=fresnel*distribution*smithVisibility;
  6141. return specTerm*info.attenuation*info.NdotL*lightColor;
  6142. }
  6143. #endif
  6144. #ifdef CLEARCOAT
  6145. vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {
  6146. float NccdotL=saturateEps(dot(Ncc,info.L));
  6147. float NccdotH=saturateEps(dot(Ncc,info.H));
  6148. float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);
  6149. float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);
  6150. float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);
  6151. fresnel*=clearCoatIntensity;
  6152. float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);
  6153. float kelemenVisibility=visibility_Kelemen(info.VdotH);
  6154. float clearCoatTerm=fresnel*distribution*kelemenVisibility;
  6155. return vec4(
  6156. clearCoatTerm*info.attenuation*NccdotL*lightColor,
  6157. 1.0-fresnel
  6158. );
  6159. }
  6160. vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {
  6161. vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);
  6162. float NdotLRefract=saturateEps(dot(Ncc,LRefract));
  6163. vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);
  6164. return absorption;
  6165. }
  6166. #endif
  6167. #ifdef SHEEN
  6168. vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {
  6169. float NdotH=saturateEps(dot(N,info.H));
  6170. float roughness=max(info.roughness,geometricRoughnessFactor);
  6171. float alphaG=convertRoughnessToAverageSlope(roughness);
  6172. float fresnel=1.;
  6173. float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);
  6174. float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);
  6175. float sheenTerm=fresnel*distribution*visibility;
  6176. return sheenTerm*info.attenuation*info.NdotL*lightColor;
  6177. }
  6178. #endif
  6179. `;ShaderStore.IncludesShadersStore[name$11]=shader$11;var name$10="pbrIBLFunctions",shader$10=`#if defined(REFLECTION) || defined(SS_REFRACTION)
  6180. float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {
  6181. float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;
  6182. float lod=log2(microsurfaceAverageSlopeTexels);
  6183. return lod;
  6184. }
  6185. float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {
  6186. float lod=log2(cubeMapDimensionPixels)*roughness;
  6187. return lod;
  6188. }
  6189. #endif
  6190. #if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)
  6191. float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {
  6192. float temp=NdotVUnclamped+ambientOcclusion;
  6193. return saturate(square(temp)-1.0+ambientOcclusion);
  6194. }
  6195. #endif
  6196. #if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)
  6197. float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {
  6198. vec3 reflection=reflect(view,normal);
  6199. float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));
  6200. return square(temp);
  6201. }
  6202. #endif
  6203. #if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)
  6204. #define UNPACK_LOD(x) (1.0-x)*255.0
  6205. float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {
  6206. float microsurfaceAverageSlope=alphaG;
  6207. microsurfaceAverageSlope*=sqrt(abs(NdotV));
  6208. return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);
  6209. }
  6210. #endif`;ShaderStore.IncludesShadersStore[name$10]=shader$10;var name$$="pbrBlockAlbedoOpacity",shader$$=`struct albedoOpacityOutParams
  6211. {
  6212. vec3 surfaceAlbedo;
  6213. float alpha;
  6214. };
  6215. #define pbr_inline
  6216. void albedoOpacityBlock(
  6217. in vec4 vAlbedoColor,
  6218. #ifdef ALBEDO
  6219. in vec4 albedoTexture,
  6220. in vec2 albedoInfos,
  6221. #endif
  6222. #ifdef OPACITY
  6223. in vec4 opacityMap,
  6224. in vec2 vOpacityInfos,
  6225. #endif
  6226. #ifdef DETAIL
  6227. in vec4 detailColor,
  6228. in vec4 vDetailInfos,
  6229. #endif
  6230. out albedoOpacityOutParams outParams
  6231. )
  6232. {
  6233. vec3 surfaceAlbedo=vAlbedoColor.rgb;
  6234. float alpha=vAlbedoColor.a;
  6235. #ifdef ALBEDO
  6236. #if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)
  6237. alpha*=albedoTexture.a;
  6238. #endif
  6239. #ifdef GAMMAALBEDO
  6240. surfaceAlbedo*=toLinearSpace(albedoTexture.rgb);
  6241. #else
  6242. surfaceAlbedo*=albedoTexture.rgb;
  6243. #endif
  6244. surfaceAlbedo*=albedoInfos.y;
  6245. #endif
  6246. #ifdef VERTEXCOLOR
  6247. surfaceAlbedo*=vColor.rgb;
  6248. #endif
  6249. #ifdef DETAIL
  6250. float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);
  6251. surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo;
  6252. #endif
  6253. #define CUSTOM_FRAGMENT_UPDATE_ALBEDO
  6254. #ifdef OPACITY
  6255. #ifdef OPACITYRGB
  6256. alpha=getLuminance(opacityMap.rgb);
  6257. #else
  6258. alpha*=opacityMap.a;
  6259. #endif
  6260. alpha*=vOpacityInfos.y;
  6261. #endif
  6262. #ifdef VERTEXALPHA
  6263. alpha*=vColor.a;
  6264. #endif
  6265. #if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)
  6266. #ifdef ALPHATEST
  6267. if (alpha<ALPHATESTVALUE)
  6268. discard;
  6269. #ifndef ALPHABLEND
  6270. alpha=1.0;
  6271. #endif
  6272. #endif
  6273. #endif
  6274. outParams.surfaceAlbedo=surfaceAlbedo;
  6275. outParams.alpha=alpha;
  6276. }
  6277. `;ShaderStore.IncludesShadersStore[name$$]=shader$$;var name$_="pbrBlockReflectivity",shader$_=`struct reflectivityOutParams
  6278. {
  6279. float microSurface;
  6280. float roughness;
  6281. vec3 surfaceReflectivityColor;
  6282. #ifdef METALLICWORKFLOW
  6283. vec3 surfaceAlbedo;
  6284. #endif
  6285. #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
  6286. vec3 ambientOcclusionColor;
  6287. #endif
  6288. #if DEBUGMODE>0
  6289. vec4 surfaceMetallicColorMap;
  6290. vec4 surfaceReflectivityColorMap;
  6291. vec2 metallicRoughness;
  6292. vec3 metallicF0;
  6293. #endif
  6294. };
  6295. #define pbr_inline
  6296. void reflectivityBlock(
  6297. in vec4 vReflectivityColor,
  6298. #ifdef METALLICWORKFLOW
  6299. in vec3 surfaceAlbedo,
  6300. in vec4 metallicReflectanceFactors,
  6301. #endif
  6302. #ifdef REFLECTIVITY
  6303. in vec3 reflectivityInfos,
  6304. in vec4 surfaceMetallicOrReflectivityColorMap,
  6305. #endif
  6306. #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
  6307. in vec3 ambientOcclusionColorIn,
  6308. #endif
  6309. #ifdef MICROSURFACEMAP
  6310. in vec4 microSurfaceTexel,
  6311. #endif
  6312. #ifdef DETAIL
  6313. in vec4 detailColor,
  6314. in vec4 vDetailInfos,
  6315. #endif
  6316. out reflectivityOutParams outParams
  6317. )
  6318. {
  6319. float microSurface=vReflectivityColor.a;
  6320. vec3 surfaceReflectivityColor=vReflectivityColor.rgb;
  6321. #ifdef METALLICWORKFLOW
  6322. vec2 metallicRoughness=surfaceReflectivityColor.rg;
  6323. #ifdef REFLECTIVITY
  6324. #if DEBUGMODE>0
  6325. outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;
  6326. #endif
  6327. #ifdef AOSTOREINMETALMAPRED
  6328. vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);
  6329. outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);
  6330. #endif
  6331. #ifdef METALLNESSSTOREINMETALMAPBLUE
  6332. metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;
  6333. #else
  6334. metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;
  6335. #endif
  6336. #ifdef ROUGHNESSSTOREINMETALMAPALPHA
  6337. metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;
  6338. #else
  6339. #ifdef ROUGHNESSSTOREINMETALMAPGREEN
  6340. metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;
  6341. #endif
  6342. #endif
  6343. #endif
  6344. #ifdef DETAIL
  6345. float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);
  6346. float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);
  6347. float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);
  6348. metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));
  6349. #endif
  6350. #ifdef MICROSURFACEMAP
  6351. metallicRoughness.g*=microSurfaceTexel.r;
  6352. #endif
  6353. #if DEBUGMODE>0
  6354. outParams.metallicRoughness=metallicRoughness;
  6355. #endif
  6356. #define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS
  6357. microSurface=1.0-metallicRoughness.g;
  6358. vec3 baseColor=surfaceAlbedo;
  6359. #ifdef FROSTBITE_REFLECTANCE
  6360. outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);
  6361. surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);
  6362. #else
  6363. vec3 metallicF0=metallicReflectanceFactors.rgb;
  6364. #if DEBUGMODE>0
  6365. outParams.metallicF0=metallicF0;
  6366. #endif
  6367. outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);
  6368. surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);
  6369. #endif
  6370. #else
  6371. #ifdef REFLECTIVITY
  6372. surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;
  6373. #if DEBUGMODE>0
  6374. outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;
  6375. #endif
  6376. #ifdef MICROSURFACEFROMREFLECTIVITYMAP
  6377. microSurface*=surfaceMetallicOrReflectivityColorMap.a;
  6378. microSurface*=reflectivityInfos.z;
  6379. #else
  6380. #ifdef MICROSURFACEAUTOMATIC
  6381. microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);
  6382. #endif
  6383. #ifdef MICROSURFACEMAP
  6384. microSurface*=microSurfaceTexel.r;
  6385. #endif
  6386. #define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE
  6387. #endif
  6388. #endif
  6389. #endif
  6390. microSurface=saturate(microSurface);
  6391. float roughness=1.-microSurface;
  6392. outParams.microSurface=microSurface;
  6393. outParams.roughness=roughness;
  6394. outParams.surfaceReflectivityColor=surfaceReflectivityColor;
  6395. }
  6396. `;ShaderStore.IncludesShadersStore[name$_]=shader$_;var name$Z="pbrBlockAmbientOcclusion",shader$Z=`struct ambientOcclusionOutParams
  6397. {
  6398. vec3 ambientOcclusionColor;
  6399. #if DEBUGMODE>0
  6400. vec3 ambientOcclusionColorMap;
  6401. #endif
  6402. };
  6403. #define pbr_inline
  6404. void ambientOcclusionBlock(
  6405. #ifdef AMBIENT
  6406. in vec3 ambientOcclusionColorMap_,
  6407. in vec4 vAmbientInfos,
  6408. #endif
  6409. out ambientOcclusionOutParams outParams
  6410. )
  6411. {
  6412. vec3 ambientOcclusionColor=vec3(1.,1.,1.);
  6413. #ifdef AMBIENT
  6414. vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;
  6415. #ifdef AMBIENTINGRAYSCALE
  6416. ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);
  6417. #endif
  6418. ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);
  6419. #if DEBUGMODE>0
  6420. outParams.ambientOcclusionColorMap=ambientOcclusionColorMap;
  6421. #endif
  6422. #endif
  6423. outParams.ambientOcclusionColor=ambientOcclusionColor;
  6424. }
  6425. `;ShaderStore.IncludesShadersStore[name$Z]=shader$Z;var name$Y="pbrBlockAlphaFresnel",shader$Y=`#ifdef ALPHAFRESNEL
  6426. #if defined(ALPHATEST) || defined(ALPHABLEND)
  6427. struct alphaFresnelOutParams
  6428. {
  6429. float alpha;
  6430. };
  6431. #define pbr_inline
  6432. void alphaFresnelBlock(
  6433. in vec3 normalW,
  6434. in vec3 viewDirectionW,
  6435. in float alpha,
  6436. in float microSurface,
  6437. out alphaFresnelOutParams outParams
  6438. )
  6439. {
  6440. float opacityPerceptual=alpha;
  6441. #ifdef LINEARALPHAFRESNEL
  6442. float opacity0=opacityPerceptual;
  6443. #else
  6444. float opacity0=opacityPerceptual*opacityPerceptual;
  6445. #endif
  6446. float opacity90=fresnelGrazingReflectance(opacity0);
  6447. vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);
  6448. outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;
  6449. #ifdef ALPHATEST
  6450. if (outParams.alpha<ALPHATESTVALUE)
  6451. discard;
  6452. #ifndef ALPHABLEND
  6453. outParams.alpha=1.0;
  6454. #endif
  6455. #endif
  6456. }
  6457. #endif
  6458. #endif
  6459. `;ShaderStore.IncludesShadersStore[name$Y]=shader$Y;var name$X="pbrBlockAnisotropic",shader$X=`#ifdef ANISOTROPIC
  6460. struct anisotropicOutParams
  6461. {
  6462. float anisotropy;
  6463. vec3 anisotropicTangent;
  6464. vec3 anisotropicBitangent;
  6465. vec3 anisotropicNormal;
  6466. #if DEBUGMODE>0
  6467. vec3 anisotropyMapData;
  6468. #endif
  6469. };
  6470. #define pbr_inline
  6471. void anisotropicBlock(
  6472. in vec3 vAnisotropy,
  6473. #ifdef ANISOTROPIC_TEXTURE
  6474. in vec3 anisotropyMapData,
  6475. #endif
  6476. in mat3 TBN,
  6477. in vec3 normalW,
  6478. in vec3 viewDirectionW,
  6479. out anisotropicOutParams outParams
  6480. )
  6481. {
  6482. float anisotropy=vAnisotropy.b;
  6483. vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);
  6484. #ifdef ANISOTROPIC_TEXTURE
  6485. anisotropy*=anisotropyMapData.b;
  6486. anisotropyDirection.rg*=anisotropyMapData.rg*2.0-1.0;
  6487. #if DEBUGMODE>0
  6488. outParams.anisotropyMapData=anisotropyMapData;
  6489. #endif
  6490. #endif
  6491. mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));
  6492. vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);
  6493. vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));
  6494. outParams.anisotropy=anisotropy;
  6495. outParams.anisotropicTangent=anisotropicTangent;
  6496. outParams.anisotropicBitangent=anisotropicBitangent;
  6497. outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy);
  6498. }
  6499. #endif
  6500. `;ShaderStore.IncludesShadersStore[name$X]=shader$X;var name$W="pbrBlockReflection",shader$W=`#ifdef REFLECTION
  6501. struct reflectionOutParams
  6502. {
  6503. vec4 environmentRadiance;
  6504. vec3 environmentIrradiance;
  6505. #ifdef REFLECTIONMAP_3D
  6506. vec3 reflectionCoords;
  6507. #else
  6508. vec2 reflectionCoords;
  6509. #endif
  6510. #ifdef SS_TRANSLUCENCY
  6511. #ifdef USESPHERICALFROMREFLECTIONMAP
  6512. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  6513. vec3 irradianceVector;
  6514. #endif
  6515. #endif
  6516. #endif
  6517. };
  6518. #define pbr_inline
  6519. void createReflectionCoords(
  6520. in vec3 vPositionW,
  6521. in vec3 normalW,
  6522. #ifdef ANISOTROPIC
  6523. in anisotropicOutParams anisotropicOut,
  6524. #endif
  6525. #ifdef REFLECTIONMAP_3D
  6526. out vec3 reflectionCoords
  6527. #else
  6528. out vec2 reflectionCoords
  6529. #endif
  6530. )
  6531. {
  6532. #ifdef ANISOTROPIC
  6533. vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);
  6534. #else
  6535. vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
  6536. #endif
  6537. #ifdef REFLECTIONMAP_OPPOSITEZ
  6538. reflectionVector.z*=-1.0;
  6539. #endif
  6540. #ifdef REFLECTIONMAP_3D
  6541. reflectionCoords=reflectionVector;
  6542. #else
  6543. reflectionCoords=reflectionVector.xy;
  6544. #ifdef REFLECTIONMAP_PROJECTION
  6545. reflectionCoords/=reflectionVector.z;
  6546. #endif
  6547. reflectionCoords.y=1.0-reflectionCoords.y;
  6548. #endif
  6549. }
  6550. #define pbr_inline
  6551. #define inline
  6552. void sampleReflectionTexture(
  6553. in float alphaG,
  6554. in vec3 vReflectionMicrosurfaceInfos,
  6555. in vec2 vReflectionInfos,
  6556. in vec3 vReflectionColor,
  6557. #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
  6558. in float NdotVUnclamped,
  6559. #endif
  6560. #ifdef LINEARSPECULARREFLECTION
  6561. in float roughness,
  6562. #endif
  6563. #ifdef REFLECTIONMAP_3D
  6564. in samplerCube reflectionSampler,
  6565. const vec3 reflectionCoords,
  6566. #else
  6567. in sampler2D reflectionSampler,
  6568. const vec2 reflectionCoords,
  6569. #endif
  6570. #ifndef LODBASEDMICROSFURACE
  6571. #ifdef REFLECTIONMAP_3D
  6572. in samplerCube reflectionSamplerLow,
  6573. in samplerCube reflectionSamplerHigh,
  6574. #else
  6575. in sampler2D reflectionSamplerLow,
  6576. in sampler2D reflectionSamplerHigh,
  6577. #endif
  6578. #endif
  6579. #ifdef REALTIME_FILTERING
  6580. in vec2 vReflectionFilteringInfo,
  6581. #endif
  6582. out vec4 environmentRadiance
  6583. )
  6584. {
  6585. #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
  6586. float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);
  6587. #elif defined(LINEARSPECULARREFLECTION)
  6588. float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
  6589. #else
  6590. float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
  6591. #endif
  6592. #ifdef LODBASEDMICROSFURACE
  6593. reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
  6594. #ifdef LODINREFLECTIONALPHA
  6595. float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);
  6596. float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);
  6597. #else
  6598. float requestedReflectionLOD=reflectionLOD;
  6599. #endif
  6600. #ifdef REALTIME_FILTERING
  6601. environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
  6602. #else
  6603. environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
  6604. #endif
  6605. #else
  6606. float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));
  6607. float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;
  6608. vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);
  6609. if (lodReflectionNormalizedDoubled<1.0){
  6610. environmentRadiance=mix(
  6611. sampleReflection(reflectionSamplerHigh,reflectionCoords),
  6612. environmentMid,
  6613. lodReflectionNormalizedDoubled
  6614. );
  6615. } else {
  6616. environmentRadiance=mix(
  6617. environmentMid,
  6618. sampleReflection(reflectionSamplerLow,reflectionCoords),
  6619. lodReflectionNormalizedDoubled-1.0
  6620. );
  6621. }
  6622. #endif
  6623. #ifdef RGBDREFLECTION
  6624. environmentRadiance.rgb=fromRGBD(environmentRadiance);
  6625. #endif
  6626. #ifdef GAMMAREFLECTION
  6627. environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);
  6628. #endif
  6629. environmentRadiance.rgb*=vReflectionInfos.x;
  6630. environmentRadiance.rgb*=vReflectionColor.rgb;
  6631. }
  6632. #define pbr_inline
  6633. #define inline
  6634. void reflectionBlock(
  6635. in vec3 vPositionW,
  6636. in vec3 normalW,
  6637. in float alphaG,
  6638. in vec3 vReflectionMicrosurfaceInfos,
  6639. in vec2 vReflectionInfos,
  6640. in vec3 vReflectionColor,
  6641. #ifdef ANISOTROPIC
  6642. in anisotropicOutParams anisotropicOut,
  6643. #endif
  6644. #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
  6645. in float NdotVUnclamped,
  6646. #endif
  6647. #ifdef LINEARSPECULARREFLECTION
  6648. in float roughness,
  6649. #endif
  6650. #ifdef REFLECTIONMAP_3D
  6651. in samplerCube reflectionSampler,
  6652. #else
  6653. in sampler2D reflectionSampler,
  6654. #endif
  6655. #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
  6656. in vec3 vEnvironmentIrradiance,
  6657. #endif
  6658. #ifdef USESPHERICALFROMREFLECTIONMAP
  6659. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  6660. in mat4 reflectionMatrix,
  6661. #endif
  6662. #endif
  6663. #ifdef USEIRRADIANCEMAP
  6664. #ifdef REFLECTIONMAP_3D
  6665. in samplerCube irradianceSampler,
  6666. #else
  6667. in sampler2D irradianceSampler,
  6668. #endif
  6669. #endif
  6670. #ifndef LODBASEDMICROSFURACE
  6671. #ifdef REFLECTIONMAP_3D
  6672. in samplerCube reflectionSamplerLow,
  6673. in samplerCube reflectionSamplerHigh,
  6674. #else
  6675. in sampler2D reflectionSamplerLow,
  6676. in sampler2D reflectionSamplerHigh,
  6677. #endif
  6678. #endif
  6679. #ifdef REALTIME_FILTERING
  6680. in vec2 vReflectionFilteringInfo,
  6681. #endif
  6682. out reflectionOutParams outParams
  6683. )
  6684. {
  6685. vec4 environmentRadiance=vec4(0.,0.,0.,0.);
  6686. #ifdef REFLECTIONMAP_3D
  6687. vec3 reflectionCoords=vec3(0.);
  6688. #else
  6689. vec2 reflectionCoords=vec2(0.);
  6690. #endif
  6691. createReflectionCoords(
  6692. vPositionW,
  6693. normalW,
  6694. #ifdef ANISOTROPIC
  6695. anisotropicOut,
  6696. #endif
  6697. reflectionCoords
  6698. );
  6699. sampleReflectionTexture(
  6700. alphaG,
  6701. vReflectionMicrosurfaceInfos,
  6702. vReflectionInfos,
  6703. vReflectionColor,
  6704. #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
  6705. NdotVUnclamped,
  6706. #endif
  6707. #ifdef LINEARSPECULARREFLECTION
  6708. roughness,
  6709. #endif
  6710. #ifdef REFLECTIONMAP_3D
  6711. reflectionSampler,
  6712. reflectionCoords,
  6713. #else
  6714. reflectionSampler,
  6715. reflectionCoords,
  6716. #endif
  6717. #ifndef LODBASEDMICROSFURACE
  6718. reflectionSamplerLow,
  6719. reflectionSamplerHigh,
  6720. #endif
  6721. #ifdef REALTIME_FILTERING
  6722. vReflectionFilteringInfo,
  6723. #endif
  6724. environmentRadiance
  6725. );
  6726. vec3 environmentIrradiance=vec3(0.,0.,0.);
  6727. #ifdef USESPHERICALFROMREFLECTIONMAP
  6728. #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
  6729. environmentIrradiance=vEnvironmentIrradiance;
  6730. #else
  6731. #ifdef ANISOTROPIC
  6732. vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;
  6733. #else
  6734. vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
  6735. #endif
  6736. #ifdef REFLECTIONMAP_OPPOSITEZ
  6737. irradianceVector.z*=-1.0;
  6738. #endif
  6739. #ifdef INVERTCUBICMAP
  6740. irradianceVector.y*=-1.0;
  6741. #endif
  6742. #if defined(REALTIME_FILTERING)
  6743. environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);
  6744. #else
  6745. environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
  6746. #endif
  6747. #ifdef SS_TRANSLUCENCY
  6748. outParams.irradianceVector=irradianceVector;
  6749. #endif
  6750. #endif
  6751. #elif defined(USEIRRADIANCEMAP)
  6752. vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);
  6753. environmentIrradiance=environmentIrradiance4.rgb;
  6754. #ifdef RGBDREFLECTION
  6755. environmentIrradiance.rgb=fromRGBD(environmentIrradiance4);
  6756. #endif
  6757. #ifdef GAMMAREFLECTION
  6758. environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);
  6759. #endif
  6760. #endif
  6761. environmentIrradiance*=vReflectionColor.rgb;
  6762. outParams.environmentRadiance=environmentRadiance;
  6763. outParams.environmentIrradiance=environmentIrradiance;
  6764. outParams.reflectionCoords=reflectionCoords;
  6765. }
  6766. #endif
  6767. `;ShaderStore.IncludesShadersStore[name$W]=shader$W;var name$V="pbrBlockSheen",shader$V=`#ifdef SHEEN
  6768. struct sheenOutParams
  6769. {
  6770. float sheenIntensity;
  6771. vec3 sheenColor;
  6772. float sheenRoughness;
  6773. #ifdef SHEEN_LINKWITHALBEDO
  6774. vec3 surfaceAlbedo;
  6775. #endif
  6776. #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
  6777. float sheenAlbedoScaling;
  6778. #endif
  6779. #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
  6780. vec3 finalSheenRadianceScaled;
  6781. #endif
  6782. #if DEBUGMODE>0
  6783. vec4 sheenMapData;
  6784. vec3 sheenEnvironmentReflectance;
  6785. #endif
  6786. };
  6787. #define pbr_inline
  6788. #define inline
  6789. void sheenBlock(
  6790. in vec4 vSheenColor,
  6791. #ifdef SHEEN_ROUGHNESS
  6792. in float vSheenRoughness,
  6793. #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
  6794. in vec4 sheenMapRoughnessData,
  6795. #endif
  6796. #endif
  6797. in float roughness,
  6798. #ifdef SHEEN_TEXTURE
  6799. in vec4 sheenMapData,
  6800. in float sheenMapLevel,
  6801. #endif
  6802. in float reflectance,
  6803. #ifdef SHEEN_LINKWITHALBEDO
  6804. in vec3 baseColor,
  6805. in vec3 surfaceAlbedo,
  6806. #endif
  6807. #ifdef ENVIRONMENTBRDF
  6808. in float NdotV,
  6809. in vec3 environmentBrdf,
  6810. #endif
  6811. #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
  6812. in vec2 AARoughnessFactors,
  6813. in vec3 vReflectionMicrosurfaceInfos,
  6814. in vec2 vReflectionInfos,
  6815. in vec3 vReflectionColor,
  6816. in vec4 vLightingIntensity,
  6817. #ifdef REFLECTIONMAP_3D
  6818. in samplerCube reflectionSampler,
  6819. in vec3 reflectionCoords,
  6820. #else
  6821. in sampler2D reflectionSampler,
  6822. in vec2 reflectionCoords,
  6823. #endif
  6824. in float NdotVUnclamped,
  6825. #ifndef LODBASEDMICROSFURACE
  6826. #ifdef REFLECTIONMAP_3D
  6827. in samplerCube reflectionSamplerLow,
  6828. in samplerCube reflectionSamplerHigh,
  6829. #else
  6830. in sampler2D reflectionSamplerLow,
  6831. in sampler2D reflectionSamplerHigh,
  6832. #endif
  6833. #endif
  6834. #ifdef REALTIME_FILTERING
  6835. in vec2 vReflectionFilteringInfo,
  6836. #endif
  6837. #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
  6838. in float seo,
  6839. #endif
  6840. #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
  6841. in float eho,
  6842. #endif
  6843. #endif
  6844. out sheenOutParams outParams
  6845. )
  6846. {
  6847. float sheenIntensity=vSheenColor.a;
  6848. #ifdef SHEEN_TEXTURE
  6849. #if DEBUGMODE>0
  6850. outParams.sheenMapData=sheenMapData;
  6851. #endif
  6852. #endif
  6853. #ifdef SHEEN_LINKWITHALBEDO
  6854. float sheenFactor=pow5(1.0-sheenIntensity);
  6855. vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);
  6856. float sheenRoughness=sheenIntensity;
  6857. outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;
  6858. #ifdef SHEEN_TEXTURE
  6859. sheenIntensity*=sheenMapData.a;
  6860. #endif
  6861. #else
  6862. vec3 sheenColor=vSheenColor.rgb;
  6863. #ifdef SHEEN_TEXTURE
  6864. #ifdef SHEEN_GAMMATEXTURE
  6865. sheenColor.rgb*=toLinearSpace(sheenMapData.rgb);
  6866. #else
  6867. sheenColor.rgb*=sheenMapData.rgb;
  6868. #endif
  6869. sheenColor.rgb*=sheenMapLevel;
  6870. #endif
  6871. #ifdef SHEEN_ROUGHNESS
  6872. float sheenRoughness=vSheenRoughness;
  6873. #ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE
  6874. #if defined(SHEEN_TEXTURE)
  6875. sheenRoughness*=sheenMapData.a;
  6876. #endif
  6877. #elif defined(SHEEN_TEXTURE_ROUGHNESS)
  6878. #ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL
  6879. sheenRoughness*=sheenMapData.a;
  6880. #else
  6881. sheenRoughness*=sheenMapRoughnessData.a;
  6882. #endif
  6883. #endif
  6884. #else
  6885. float sheenRoughness=roughness;
  6886. #ifdef SHEEN_TEXTURE
  6887. sheenIntensity*=sheenMapData.a;
  6888. #endif
  6889. #endif
  6890. #if !defined(SHEEN_ALBEDOSCALING)
  6891. sheenIntensity*=(1.-reflectance);
  6892. #endif
  6893. sheenColor*=sheenIntensity;
  6894. #endif
  6895. #ifdef ENVIRONMENTBRDF
  6896. #ifdef SHEEN_ROUGHNESS
  6897. vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);
  6898. #else
  6899. vec3 environmentSheenBrdf=environmentBrdf;
  6900. #endif
  6901. #endif
  6902. #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
  6903. float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);
  6904. #ifdef SPECULARAA
  6905. sheenAlphaG+=AARoughnessFactors.y;
  6906. #endif
  6907. vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);
  6908. sampleReflectionTexture(
  6909. sheenAlphaG,
  6910. vReflectionMicrosurfaceInfos,
  6911. vReflectionInfos,
  6912. vReflectionColor,
  6913. #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
  6914. NdotVUnclamped,
  6915. #endif
  6916. #ifdef LINEARSPECULARREFLECTION
  6917. sheenRoughness,
  6918. #endif
  6919. reflectionSampler,
  6920. reflectionCoords,
  6921. #ifndef LODBASEDMICROSFURACE
  6922. reflectionSamplerLow,
  6923. reflectionSamplerHigh,
  6924. #endif
  6925. #ifdef REALTIME_FILTERING
  6926. vReflectionFilteringInfo,
  6927. #endif
  6928. environmentSheenRadiance
  6929. );
  6930. vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);
  6931. #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
  6932. sheenEnvironmentReflectance*=seo;
  6933. #endif
  6934. #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
  6935. sheenEnvironmentReflectance*=eho;
  6936. #endif
  6937. #if DEBUGMODE>0
  6938. outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;
  6939. #endif
  6940. outParams.finalSheenRadianceScaled=
  6941. environmentSheenRadiance.rgb *
  6942. sheenEnvironmentReflectance *
  6943. vLightingIntensity.z;
  6944. #endif
  6945. #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
  6946. outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;
  6947. #endif
  6948. outParams.sheenIntensity=sheenIntensity;
  6949. outParams.sheenColor=sheenColor;
  6950. outParams.sheenRoughness=sheenRoughness;
  6951. }
  6952. #endif
  6953. `;ShaderStore.IncludesShadersStore[name$V]=shader$V;var name$U="pbrBlockClearcoat",shader$U=`struct clearcoatOutParams
  6954. {
  6955. vec3 specularEnvironmentR0;
  6956. float conservationFactor;
  6957. vec3 clearCoatNormalW;
  6958. vec2 clearCoatAARoughnessFactors;
  6959. float clearCoatIntensity;
  6960. float clearCoatRoughness;
  6961. #ifdef REFLECTION
  6962. vec3 finalClearCoatRadianceScaled;
  6963. #endif
  6964. #ifdef CLEARCOAT_TINT
  6965. vec3 absorption;
  6966. float clearCoatNdotVRefract;
  6967. vec3 clearCoatColor;
  6968. float clearCoatThickness;
  6969. #endif
  6970. #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
  6971. vec3 energyConservationFactorClearCoat;
  6972. #endif
  6973. #if DEBUGMODE>0
  6974. mat3 TBNClearCoat;
  6975. vec2 clearCoatMapData;
  6976. vec4 clearCoatTintMapData;
  6977. vec4 environmentClearCoatRadiance;
  6978. float clearCoatNdotV;
  6979. vec3 clearCoatEnvironmentReflectance;
  6980. #endif
  6981. };
  6982. #ifdef CLEARCOAT
  6983. #define pbr_inline
  6984. #define inline
  6985. void clearcoatBlock(
  6986. in vec3 vPositionW,
  6987. in vec3 geometricNormalW,
  6988. in vec3 viewDirectionW,
  6989. in vec2 vClearCoatParams,
  6990. #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
  6991. in vec4 clearCoatMapRoughnessData,
  6992. #endif
  6993. in vec3 specularEnvironmentR0,
  6994. #ifdef CLEARCOAT_TEXTURE
  6995. in vec2 clearCoatMapData,
  6996. #endif
  6997. #ifdef CLEARCOAT_TINT
  6998. in vec4 vClearCoatTintParams,
  6999. in float clearCoatColorAtDistance,
  7000. in vec4 vClearCoatRefractionParams,
  7001. #ifdef CLEARCOAT_TINT_TEXTURE
  7002. in vec4 clearCoatTintMapData,
  7003. #endif
  7004. #endif
  7005. #ifdef CLEARCOAT_BUMP
  7006. in vec2 vClearCoatBumpInfos,
  7007. in vec4 clearCoatBumpMapData,
  7008. in vec2 vClearCoatBumpUV,
  7009. #if defined(TANGENT) && defined(NORMAL)
  7010. in mat3 vTBN,
  7011. #else
  7012. in vec2 vClearCoatTangentSpaceParams,
  7013. #endif
  7014. #ifdef OBJECTSPACE_NORMALMAP
  7015. in mat4 normalMatrix,
  7016. #endif
  7017. #endif
  7018. #if defined(FORCENORMALFORWARD) && defined(NORMAL)
  7019. in vec3 faceNormal,
  7020. #endif
  7021. #ifdef REFLECTION
  7022. in vec3 vReflectionMicrosurfaceInfos,
  7023. in vec2 vReflectionInfos,
  7024. in vec3 vReflectionColor,
  7025. in vec4 vLightingIntensity,
  7026. #ifdef REFLECTIONMAP_3D
  7027. in samplerCube reflectionSampler,
  7028. #else
  7029. in sampler2D reflectionSampler,
  7030. #endif
  7031. #ifndef LODBASEDMICROSFURACE
  7032. #ifdef REFLECTIONMAP_3D
  7033. in samplerCube reflectionSamplerLow,
  7034. in samplerCube reflectionSamplerHigh,
  7035. #else
  7036. in sampler2D reflectionSamplerLow,
  7037. in sampler2D reflectionSamplerHigh,
  7038. #endif
  7039. #endif
  7040. #ifdef REALTIME_FILTERING
  7041. in vec2 vReflectionFilteringInfo,
  7042. #endif
  7043. #endif
  7044. #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
  7045. #ifdef RADIANCEOCCLUSION
  7046. in float ambientMonochrome,
  7047. #endif
  7048. #endif
  7049. #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
  7050. in float frontFacingMultiplier,
  7051. #endif
  7052. out clearcoatOutParams outParams
  7053. )
  7054. {
  7055. float clearCoatIntensity=vClearCoatParams.x;
  7056. float clearCoatRoughness=vClearCoatParams.y;
  7057. #ifdef CLEARCOAT_TEXTURE
  7058. clearCoatIntensity*=clearCoatMapData.x;
  7059. #ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE
  7060. clearCoatRoughness*=clearCoatMapData.y;
  7061. #endif
  7062. #if DEBUGMODE>0
  7063. outParams.clearCoatMapData=clearCoatMapData;
  7064. #endif
  7065. #endif
  7066. #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
  7067. #ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL
  7068. clearCoatRoughness*=clearCoatMapData.y;
  7069. #else
  7070. clearCoatRoughness*=clearCoatMapRoughnessData.y;
  7071. #endif
  7072. #endif
  7073. outParams.clearCoatIntensity=clearCoatIntensity;
  7074. outParams.clearCoatRoughness=clearCoatRoughness;
  7075. #ifdef CLEARCOAT_TINT
  7076. vec3 clearCoatColor=vClearCoatTintParams.rgb;
  7077. float clearCoatThickness=vClearCoatTintParams.a;
  7078. #ifdef CLEARCOAT_TINT_TEXTURE
  7079. #ifdef CLEARCOAT_TINT_GAMMATEXTURE
  7080. clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);
  7081. #else
  7082. clearCoatColor*=clearCoatTintMapData.rgb;
  7083. #endif
  7084. clearCoatThickness*=clearCoatTintMapData.a;
  7085. #if DEBUGMODE>0
  7086. outParams.clearCoatTintMapData=clearCoatTintMapData;
  7087. #endif
  7088. #endif
  7089. outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);
  7090. outParams.clearCoatThickness=clearCoatThickness;
  7091. #endif
  7092. #ifdef CLEARCOAT_REMAP_F0
  7093. vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);
  7094. #else
  7095. vec3 specularEnvironmentR0Updated=specularEnvironmentR0;
  7096. #endif
  7097. outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);
  7098. vec3 clearCoatNormalW=geometricNormalW;
  7099. #ifdef CLEARCOAT_BUMP
  7100. #ifdef NORMALXYSCALE
  7101. float clearCoatNormalScale=1.0;
  7102. #else
  7103. float clearCoatNormalScale=vClearCoatBumpInfos.y;
  7104. #endif
  7105. #if defined(TANGENT) && defined(NORMAL)
  7106. mat3 TBNClearCoat=vTBN;
  7107. #else
  7108. vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;
  7109. mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);
  7110. #endif
  7111. #if DEBUGMODE>0
  7112. outParams.TBNClearCoat=TBNClearCoat;
  7113. #endif
  7114. #ifdef OBJECTSPACE_NORMALMAP
  7115. clearCoatNormalW=normalize(clearCoatBumpMapData.xyz*2.0-1.0);
  7116. clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);
  7117. #else
  7118. clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);
  7119. #endif
  7120. #endif
  7121. #if defined(FORCENORMALFORWARD) && defined(NORMAL)
  7122. clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));
  7123. #endif
  7124. #if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
  7125. clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;
  7126. #endif
  7127. outParams.clearCoatNormalW=clearCoatNormalW;
  7128. outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);
  7129. float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);
  7130. float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);
  7131. #if DEBUGMODE>0
  7132. outParams.clearCoatNdotV=clearCoatNdotV;
  7133. #endif
  7134. #ifdef CLEARCOAT_TINT
  7135. vec3 clearCoatVRefract=-refract(vPositionW,clearCoatNormalW,vClearCoatRefractionParams.y);
  7136. outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));
  7137. #endif
  7138. #if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))
  7139. vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);
  7140. #endif
  7141. #if defined(REFLECTION)
  7142. float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);
  7143. #ifdef SPECULARAA
  7144. clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;
  7145. #endif
  7146. vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);
  7147. vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);
  7148. #ifdef REFLECTIONMAP_OPPOSITEZ
  7149. clearCoatReflectionVector.z*=-1.0;
  7150. #endif
  7151. #ifdef REFLECTIONMAP_3D
  7152. vec3 clearCoatReflectionCoords=clearCoatReflectionVector;
  7153. #else
  7154. vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;
  7155. #ifdef REFLECTIONMAP_PROJECTION
  7156. clearCoatReflectionCoords/=clearCoatReflectionVector.z;
  7157. #endif
  7158. clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;
  7159. #endif
  7160. sampleReflectionTexture(
  7161. clearCoatAlphaG,
  7162. vReflectionMicrosurfaceInfos,
  7163. vReflectionInfos,
  7164. vReflectionColor,
  7165. #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
  7166. clearCoatNdotVUnclamped,
  7167. #endif
  7168. #ifdef LINEARSPECULARREFLECTION
  7169. clearCoatRoughness,
  7170. #endif
  7171. reflectionSampler,
  7172. clearCoatReflectionCoords,
  7173. #ifndef LODBASEDMICROSFURACE
  7174. reflectionSamplerLow,
  7175. reflectionSamplerHigh,
  7176. #endif
  7177. #ifdef REALTIME_FILTERING
  7178. vReflectionFilteringInfo,
  7179. #endif
  7180. environmentClearCoatRadiance
  7181. );
  7182. #if DEBUGMODE>0
  7183. outParams.environmentClearCoatRadiance=environmentClearCoatRadiance;
  7184. #endif
  7185. #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
  7186. vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);
  7187. #ifdef RADIANCEOCCLUSION
  7188. float clearCoatSeo=environmentRadianceOcclusion(ambientMonochrome,clearCoatNdotVUnclamped);
  7189. clearCoatEnvironmentReflectance*=clearCoatSeo;
  7190. #endif
  7191. #ifdef HORIZONOCCLUSION
  7192. #ifdef BUMP
  7193. #ifdef REFLECTIONMAP_3D
  7194. float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);
  7195. clearCoatEnvironmentReflectance*=clearCoatEho;
  7196. #endif
  7197. #endif
  7198. #endif
  7199. #else
  7200. vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));
  7201. #endif
  7202. clearCoatEnvironmentReflectance*=clearCoatIntensity;
  7203. #if DEBUGMODE>0
  7204. outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;
  7205. #endif
  7206. outParams.finalClearCoatRadianceScaled=
  7207. environmentClearCoatRadiance.rgb *
  7208. clearCoatEnvironmentReflectance *
  7209. vLightingIntensity.z;
  7210. #endif
  7211. #if defined(CLEARCOAT_TINT)
  7212. outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);
  7213. #endif
  7214. float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);
  7215. fresnelIBLClearCoat*=clearCoatIntensity;
  7216. outParams.conservationFactor=(1.-fresnelIBLClearCoat);
  7217. #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
  7218. outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);
  7219. #endif
  7220. }
  7221. #endif
  7222. `;ShaderStore.IncludesShadersStore[name$U]=shader$U;var name$T="pbrBlockSubSurface",shader$T=`struct subSurfaceOutParams
  7223. {
  7224. vec3 specularEnvironmentReflectance;
  7225. #ifdef SS_REFRACTION
  7226. vec3 finalRefraction;
  7227. vec3 surfaceAlbedo;
  7228. #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
  7229. float alpha;
  7230. #endif
  7231. #ifdef REFLECTION
  7232. float refractionFactorForIrradiance;
  7233. #endif
  7234. #endif
  7235. #ifdef SS_TRANSLUCENCY
  7236. vec3 transmittance;
  7237. float translucencyIntensity;
  7238. #ifdef REFLECTION
  7239. vec3 refractionIrradiance;
  7240. #endif
  7241. #endif
  7242. #if DEBUGMODE>0
  7243. vec4 thicknessMap;
  7244. vec4 environmentRefraction;
  7245. vec3 refractionTransmittance;
  7246. #endif
  7247. };
  7248. #ifdef SUBSURFACE
  7249. #define pbr_inline
  7250. #define inline
  7251. void subSurfaceBlock(
  7252. in vec3 vSubSurfaceIntensity,
  7253. in vec2 vThicknessParam,
  7254. in vec4 vTintColor,
  7255. in vec3 normalW,
  7256. in vec3 specularEnvironmentReflectance,
  7257. #ifdef SS_THICKNESSANDMASK_TEXTURE
  7258. in vec4 thicknessMap,
  7259. #endif
  7260. #ifdef SS_REFRACTIONINTENSITY_TEXTURE
  7261. in vec4 refractionIntensityMap,
  7262. #endif
  7263. #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
  7264. in vec4 translucencyIntensityMap,
  7265. #endif
  7266. #ifdef REFLECTION
  7267. #ifdef SS_TRANSLUCENCY
  7268. in mat4 reflectionMatrix,
  7269. #ifdef USESPHERICALFROMREFLECTIONMAP
  7270. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  7271. in vec3 irradianceVector_,
  7272. #endif
  7273. #if defined(REALTIME_FILTERING)
  7274. in samplerCube reflectionSampler,
  7275. in vec2 vReflectionFilteringInfo,
  7276. #endif
  7277. #endif
  7278. #ifdef USEIRRADIANCEMAP
  7279. #ifdef REFLECTIONMAP_3D
  7280. in samplerCube irradianceSampler,
  7281. #else
  7282. in sampler2D irradianceSampler,
  7283. #endif
  7284. #endif
  7285. #endif
  7286. #endif
  7287. #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
  7288. in vec3 surfaceAlbedo,
  7289. #endif
  7290. #ifdef SS_REFRACTION
  7291. in vec3 vPositionW,
  7292. in vec3 viewDirectionW,
  7293. in mat4 view,
  7294. in vec4 vRefractionInfos,
  7295. in mat4 refractionMatrix,
  7296. in vec4 vRefractionMicrosurfaceInfos,
  7297. in vec4 vLightingIntensity,
  7298. #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
  7299. in float alpha,
  7300. #endif
  7301. #ifdef SS_LODINREFRACTIONALPHA
  7302. in float NdotVUnclamped,
  7303. #endif
  7304. #ifdef SS_LINEARSPECULARREFRACTION
  7305. in float roughness,
  7306. #endif
  7307. in float alphaG,
  7308. #ifdef SS_REFRACTIONMAP_3D
  7309. in samplerCube refractionSampler,
  7310. #ifndef LODBASEDMICROSFURACE
  7311. in samplerCube refractionSamplerLow,
  7312. in samplerCube refractionSamplerHigh,
  7313. #endif
  7314. #else
  7315. in sampler2D refractionSampler,
  7316. #ifndef LODBASEDMICROSFURACE
  7317. in sampler2D refractionSamplerLow,
  7318. in sampler2D refractionSamplerHigh,
  7319. #endif
  7320. #endif
  7321. #ifdef ANISOTROPIC
  7322. in anisotropicOutParams anisotropicOut,
  7323. #endif
  7324. #ifdef REALTIME_FILTERING
  7325. in vec2 vRefractionFilteringInfo,
  7326. #endif
  7327. #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
  7328. in vec3 refractionPosition,
  7329. in vec3 refractionSize,
  7330. #endif
  7331. #endif
  7332. #ifdef SS_TRANSLUCENCY
  7333. in vec3 vDiffusionDistance,
  7334. #endif
  7335. out subSurfaceOutParams outParams
  7336. )
  7337. {
  7338. outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;
  7339. #ifdef SS_REFRACTION
  7340. float refractionIntensity=vSubSurfaceIntensity.x;
  7341. #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
  7342. refractionIntensity*=(1.0-alpha);
  7343. outParams.alpha=1.0;
  7344. #endif
  7345. #endif
  7346. #ifdef SS_TRANSLUCENCY
  7347. float translucencyIntensity=vSubSurfaceIntensity.y;
  7348. #endif
  7349. #ifdef SS_THICKNESSANDMASK_TEXTURE
  7350. #if defined(SS_USE_GLTF_TEXTURES)
  7351. float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;
  7352. #else
  7353. float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;
  7354. #endif
  7355. #if DEBUGMODE>0
  7356. outParams.thicknessMap=thicknessMap;
  7357. #endif
  7358. #ifdef SS_MASK_FROM_THICKNESS_TEXTURE
  7359. #if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE)
  7360. #if defined(SS_USE_GLTF_TEXTURES)
  7361. refractionIntensity*=thicknessMap.r;
  7362. #else
  7363. refractionIntensity*=thicknessMap.g;
  7364. #endif
  7365. #endif
  7366. #if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE)
  7367. translucencyIntensity*=thicknessMap.b;
  7368. #endif
  7369. #endif
  7370. #else
  7371. float thickness=vThicknessParam.y;
  7372. #endif
  7373. #ifdef SS_REFRACTIONINTENSITY_TEXTURE
  7374. #ifdef SS_USE_GLTF_TEXTURES
  7375. refractionIntensity*=refractionIntensityMap.r;
  7376. #else
  7377. refractionIntensity*=refractionIntensityMap.g;
  7378. #endif
  7379. #endif
  7380. #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
  7381. translucencyIntensity*=translucencyIntensityMap.b;
  7382. #endif
  7383. #ifdef SS_TRANSLUCENCY
  7384. thickness=maxEps(thickness);
  7385. vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);
  7386. transmittance*=translucencyIntensity;
  7387. outParams.transmittance=transmittance;
  7388. outParams.translucencyIntensity=translucencyIntensity;
  7389. #endif
  7390. #ifdef SS_REFRACTION
  7391. vec4 environmentRefraction=vec4(0.,0.,0.,0.);
  7392. #ifdef ANISOTROPIC
  7393. vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y);
  7394. #else
  7395. vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);
  7396. #endif
  7397. #ifdef SS_REFRACTIONMAP_OPPOSITEZ
  7398. refractionVector.z*=-1.0;
  7399. #endif
  7400. #ifdef SS_REFRACTIONMAP_3D
  7401. #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
  7402. refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);
  7403. #endif
  7404. refractionVector.y=refractionVector.y*vRefractionInfos.w;
  7405. vec3 refractionCoords=refractionVector;
  7406. refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));
  7407. #else
  7408. #ifdef SS_USE_THICKNESS_AS_DEPTH
  7409. vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));
  7410. #else
  7411. vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));
  7412. #endif
  7413. vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;
  7414. refractionCoords.y=1.0-refractionCoords.y;
  7415. #endif
  7416. #ifdef SS_HAS_THICKNESS
  7417. float ior=vRefractionInfos.y;
  7418. #else
  7419. float ior=vRefractionMicrosurfaceInfos.w;
  7420. #endif
  7421. #ifdef SS_LODINREFRACTIONALPHA
  7422. float refractionAlphaG=alphaG;
  7423. refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));
  7424. float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);
  7425. #elif defined(SS_LINEARSPECULARREFRACTION)
  7426. float refractionRoughness=alphaG;
  7427. refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));
  7428. float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);
  7429. #else
  7430. float refractionAlphaG=alphaG;
  7431. refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));
  7432. float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);
  7433. #endif
  7434. #ifdef LODBASEDMICROSFURACE
  7435. refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;
  7436. #ifdef SS_LODINREFRACTIONALPHA
  7437. float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);
  7438. float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);
  7439. #else
  7440. float requestedRefractionLOD=refractionLOD;
  7441. #endif
  7442. #ifdef REALTIME_FILTERING
  7443. environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);
  7444. #else
  7445. environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);
  7446. #endif
  7447. #else
  7448. float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));
  7449. float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;
  7450. vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);
  7451. if (lodRefractionNormalizedDoubled<1.0){
  7452. environmentRefraction=mix(
  7453. sampleRefraction(refractionSamplerHigh,refractionCoords),
  7454. environmentRefractionMid,
  7455. lodRefractionNormalizedDoubled
  7456. );
  7457. } else {
  7458. environmentRefraction=mix(
  7459. environmentRefractionMid,
  7460. sampleRefraction(refractionSamplerLow,refractionCoords),
  7461. lodRefractionNormalizedDoubled-1.0
  7462. );
  7463. }
  7464. #endif
  7465. #ifdef SS_RGBDREFRACTION
  7466. environmentRefraction.rgb=fromRGBD(environmentRefraction);
  7467. #endif
  7468. #ifdef SS_GAMMAREFRACTION
  7469. environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);
  7470. #endif
  7471. environmentRefraction.rgb*=vRefractionInfos.x;
  7472. #endif
  7473. #ifdef SS_REFRACTION
  7474. vec3 refractionTransmittance=vec3(refractionIntensity);
  7475. #ifdef SS_THICKNESSANDMASK_TEXTURE
  7476. vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);
  7477. refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);
  7478. #elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)
  7479. float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);
  7480. vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);
  7481. environmentRefraction.rgb*=volumeAlbedo;
  7482. #else
  7483. vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);
  7484. refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);
  7485. #endif
  7486. #ifdef SS_ALBEDOFORREFRACTIONTINT
  7487. environmentRefraction.rgb*=surfaceAlbedo.rgb;
  7488. #endif
  7489. outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);
  7490. #ifdef REFLECTION
  7491. outParams.refractionFactorForIrradiance=(1.-refractionIntensity);
  7492. #endif
  7493. #ifdef UNUSED_MULTIPLEBOUNCES
  7494. vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);
  7495. outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);
  7496. #endif
  7497. refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;
  7498. #if DEBUGMODE>0
  7499. outParams.refractionTransmittance=refractionTransmittance;
  7500. #endif
  7501. outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;
  7502. #if DEBUGMODE>0
  7503. outParams.environmentRefraction=environmentRefraction;
  7504. #endif
  7505. #endif
  7506. #if defined(REFLECTION) && defined(SS_TRANSLUCENCY)
  7507. #if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)
  7508. vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
  7509. #ifdef REFLECTIONMAP_OPPOSITEZ
  7510. irradianceVector.z*=-1.0;
  7511. #endif
  7512. #ifdef INVERTCUBICMAP
  7513. irradianceVector.y*=-1.0;
  7514. #endif
  7515. #else
  7516. vec3 irradianceVector=irradianceVector_;
  7517. #endif
  7518. #if defined(USESPHERICALFROMREFLECTIONMAP)
  7519. #if defined(REALTIME_FILTERING)
  7520. vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);
  7521. #else
  7522. vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);
  7523. #endif
  7524. #elif defined(USEIRRADIANCEMAP)
  7525. #ifdef REFLECTIONMAP_3D
  7526. vec3 irradianceCoords=irradianceVector;
  7527. #else
  7528. vec2 irradianceCoords=irradianceVector.xy;
  7529. #ifdef REFLECTIONMAP_PROJECTION
  7530. irradianceCoords/=irradianceVector.z;
  7531. #endif
  7532. irradianceCoords.y=1.0-irradianceCoords.y;
  7533. #endif
  7534. vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);
  7535. #ifdef RGBDREFLECTION
  7536. refractionIrradiance.rgb=fromRGBD(refractionIrradiance);
  7537. #endif
  7538. #ifdef GAMMAREFLECTION
  7539. refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);
  7540. #endif
  7541. #else
  7542. vec4 refractionIrradiance=vec4(0.);
  7543. #endif
  7544. refractionIrradiance.rgb*=transmittance;
  7545. #ifdef SS_ALBEDOFORTRANSLUCENCYTINT
  7546. refractionIrradiance.rgb*=surfaceAlbedo.rgb;
  7547. #endif
  7548. outParams.refractionIrradiance=refractionIrradiance.rgb;
  7549. #endif
  7550. }
  7551. #endif
  7552. `;ShaderStore.IncludesShadersStore[name$T]=shader$T;var name$S="pbrBlockNormalGeometric",shader$S=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
  7553. #ifdef NORMAL
  7554. vec3 normalW=normalize(vNormalW);
  7555. #else
  7556. vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
  7557. #endif
  7558. vec3 geometricNormalW=normalW;
  7559. #if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
  7560. geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;
  7561. #endif
  7562. `;ShaderStore.IncludesShadersStore[name$S]=shader$S;var name$R="pbrBlockNormalFinal",shader$R=`#if defined(FORCENORMALFORWARD) && defined(NORMAL)
  7563. vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
  7564. #if defined(TWOSIDEDLIGHTING)
  7565. faceNormal=gl_FrontFacing ? faceNormal : -faceNormal;
  7566. #endif
  7567. normalW*=sign(dot(normalW,faceNormal));
  7568. #endif
  7569. #if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
  7570. normalW=gl_FrontFacing ? normalW : -normalW;
  7571. #endif
  7572. `;ShaderStore.IncludesShadersStore[name$R]=shader$R;var name$Q="pbrBlockLightmapInit",shader$Q=`#ifdef LIGHTMAP
  7573. vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
  7574. #ifdef RGBDLIGHTMAP
  7575. lightmapColor.rgb=fromRGBD(lightmapColor);
  7576. #endif
  7577. #ifdef GAMMALIGHTMAP
  7578. lightmapColor.rgb=toLinearSpace(lightmapColor.rgb);
  7579. #endif
  7580. lightmapColor.rgb*=vLightmapInfos.y;
  7581. #endif
  7582. `;ShaderStore.IncludesShadersStore[name$Q]=shader$Q;var name$P="pbrBlockGeometryInfo",shader$P=`float NdotVUnclamped=dot(normalW,viewDirectionW);
  7583. float NdotV=absEps(NdotVUnclamped);
  7584. float alphaG=convertRoughnessToAverageSlope(roughness);
  7585. vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);
  7586. #ifdef SPECULARAA
  7587. alphaG+=AARoughnessFactors.y;
  7588. #endif
  7589. #if defined(ENVIRONMENTBRDF)
  7590. vec3 environmentBrdf=getBRDFLookup(NdotV,roughness);
  7591. #endif
  7592. #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
  7593. #ifdef RADIANCEOCCLUSION
  7594. #ifdef AMBIENTINGRAYSCALE
  7595. float ambientMonochrome=aoOut.ambientOcclusionColor.r;
  7596. #else
  7597. float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);
  7598. #endif
  7599. float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);
  7600. #endif
  7601. #ifdef HORIZONOCCLUSION
  7602. #ifdef BUMP
  7603. #ifdef REFLECTIONMAP_3D
  7604. float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
  7605. #endif
  7606. #endif
  7607. #endif
  7608. #endif
  7609. `;ShaderStore.IncludesShadersStore[name$P]=shader$P;var name$O="pbrBlockReflectance0",shader$O=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);
  7610. vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;
  7611. #ifdef METALLICWORKFLOW
  7612. vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);
  7613. #else
  7614. vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);
  7615. #endif
  7616. #ifdef ALPHAFRESNEL
  7617. float reflectance90=fresnelGrazingReflectance(reflectance);
  7618. specularEnvironmentR90=specularEnvironmentR90*reflectance90;
  7619. #endif
  7620. `;ShaderStore.IncludesShadersStore[name$O]=shader$O;var name$N="pbrBlockReflectance",shader$N=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
  7621. vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);
  7622. #ifdef RADIANCEOCCLUSION
  7623. specularEnvironmentReflectance*=seo;
  7624. #endif
  7625. #ifdef HORIZONOCCLUSION
  7626. #ifdef BUMP
  7627. #ifdef REFLECTIONMAP_3D
  7628. specularEnvironmentReflectance*=eho;
  7629. #endif
  7630. #endif
  7631. #endif
  7632. #else
  7633. vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));
  7634. #endif
  7635. #ifdef CLEARCOAT
  7636. specularEnvironmentReflectance*=clearcoatOut.conservationFactor;
  7637. #if defined(CLEARCOAT_TINT)
  7638. specularEnvironmentReflectance*=clearcoatOut.absorption;
  7639. #endif
  7640. #endif
  7641. `;ShaderStore.IncludesShadersStore[name$N]=shader$N;var name$M="pbrBlockDirectLighting",shader$M=`vec3 diffuseBase=vec3(0.,0.,0.);
  7642. #ifdef SPECULARTERM
  7643. vec3 specularBase=vec3(0.,0.,0.);
  7644. #endif
  7645. #ifdef CLEARCOAT
  7646. vec3 clearCoatBase=vec3(0.,0.,0.);
  7647. #endif
  7648. #ifdef SHEEN
  7649. vec3 sheenBase=vec3(0.,0.,0.);
  7650. #endif
  7651. preLightingInfo preInfo;
  7652. lightingInfo info;
  7653. float shadow=1.;
  7654. #if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
  7655. vec3 absorption=vec3(0.);
  7656. #endif
  7657. `;ShaderStore.IncludesShadersStore[name$M]=shader$M;var name$L="pbrBlockFinalLitComponents",shader$L=`
  7658. #if defined(ENVIRONMENTBRDF)
  7659. #ifdef MS_BRDF_ENERGY_CONSERVATION
  7660. vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);
  7661. #endif
  7662. #endif
  7663. #ifndef METALLICWORKFLOW
  7664. #ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION
  7665. surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;
  7666. #endif
  7667. #endif
  7668. #if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)
  7669. surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;
  7670. #endif
  7671. #ifdef REFLECTION
  7672. vec3 finalIrradiance=reflectionOut.environmentIrradiance;
  7673. #if defined(CLEARCOAT)
  7674. finalIrradiance*=clearcoatOut.conservationFactor;
  7675. #if defined(CLEARCOAT_TINT)
  7676. finalIrradiance*=clearcoatOut.absorption;
  7677. #endif
  7678. #endif
  7679. #if defined(SS_REFRACTION)
  7680. finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;
  7681. #endif
  7682. #if defined(SS_TRANSLUCENCY)
  7683. finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);
  7684. finalIrradiance+=subSurfaceOut.refractionIrradiance;
  7685. #endif
  7686. finalIrradiance*=surfaceAlbedo.rgb;
  7687. finalIrradiance*=vLightingIntensity.z;
  7688. finalIrradiance*=aoOut.ambientOcclusionColor;
  7689. #endif
  7690. #ifdef SPECULARTERM
  7691. vec3 finalSpecular=specularBase;
  7692. finalSpecular=max(finalSpecular,0.0);
  7693. vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;
  7694. #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
  7695. finalSpecularScaled*=energyConservationFactor;
  7696. #endif
  7697. #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
  7698. finalSpecularScaled*=sheenOut.sheenAlbedoScaling;
  7699. #endif
  7700. #endif
  7701. #ifdef REFLECTION
  7702. vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;
  7703. finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;
  7704. vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;
  7705. #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
  7706. finalRadianceScaled*=energyConservationFactor;
  7707. #endif
  7708. #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
  7709. finalRadianceScaled*=sheenOut.sheenAlbedoScaling;
  7710. #endif
  7711. #endif
  7712. #ifdef SHEEN
  7713. vec3 finalSheen=sheenBase*sheenOut.sheenColor;
  7714. finalSheen=max(finalSheen,0.0);
  7715. vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;
  7716. #if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)
  7717. sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;
  7718. #if defined(CLEARCOAT_TINT)
  7719. sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;
  7720. #endif
  7721. #endif
  7722. #endif
  7723. #ifdef CLEARCOAT
  7724. vec3 finalClearCoat=clearCoatBase;
  7725. finalClearCoat=max(finalClearCoat,0.0);
  7726. vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;
  7727. #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
  7728. finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;
  7729. #endif
  7730. #ifdef SS_REFRACTION
  7731. subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;
  7732. #ifdef CLEARCOAT_TINT
  7733. subSurfaceOut.finalRefraction*=clearcoatOut.absorption;
  7734. #endif
  7735. #endif
  7736. #endif
  7737. #ifdef ALPHABLEND
  7738. float luminanceOverAlpha=0.0;
  7739. #if defined(REFLECTION) && defined(RADIANCEOVERALPHA)
  7740. luminanceOverAlpha+=getLuminance(finalRadianceScaled);
  7741. #if defined(CLEARCOAT)
  7742. luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);
  7743. #endif
  7744. #endif
  7745. #if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)
  7746. luminanceOverAlpha+=getLuminance(finalSpecularScaled);
  7747. #endif
  7748. #if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)
  7749. luminanceOverAlpha+=getLuminance(finalClearCoatScaled);
  7750. #endif
  7751. #if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)
  7752. alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);
  7753. #endif
  7754. #endif
  7755. `;ShaderStore.IncludesShadersStore[name$L]=shader$L;var name$K="pbrBlockFinalUnlitComponents",shader$K=`
  7756. vec3 finalDiffuse=diffuseBase;
  7757. finalDiffuse*=surfaceAlbedo.rgb;
  7758. finalDiffuse=max(finalDiffuse,0.0);
  7759. finalDiffuse*=vLightingIntensity.x;
  7760. vec3 finalAmbient=vAmbientColor;
  7761. finalAmbient*=surfaceAlbedo.rgb;
  7762. vec3 finalEmissive=vEmissiveColor;
  7763. #ifdef EMISSIVE
  7764. vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;
  7765. #ifdef GAMMAEMISSIVE
  7766. finalEmissive*=toLinearSpace(emissiveColorTex.rgb);
  7767. #else
  7768. finalEmissive*=emissiveColorTex.rgb;
  7769. #endif
  7770. finalEmissive*=vEmissiveInfos.y;
  7771. #endif
  7772. finalEmissive*=vLightingIntensity.y;
  7773. #ifdef AMBIENT
  7774. vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);
  7775. #else
  7776. vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;
  7777. #endif
  7778. finalAmbient*=aoOut.ambientOcclusionColor;
  7779. finalDiffuse*=ambientOcclusionForDirectDiffuse;
  7780. `;ShaderStore.IncludesShadersStore[name$K]=shader$K;var name$J="pbrBlockFinalColorComposition",shader$J=`vec4 finalColor=vec4(
  7781. finalAmbient +
  7782. finalDiffuse +
  7783. #ifndef UNLIT
  7784. #ifdef REFLECTION
  7785. finalIrradiance +
  7786. #endif
  7787. #ifdef SPECULARTERM
  7788. finalSpecularScaled +
  7789. #endif
  7790. #ifdef SHEEN
  7791. finalSheenScaled +
  7792. #endif
  7793. #ifdef CLEARCOAT
  7794. finalClearCoatScaled +
  7795. #endif
  7796. #ifdef REFLECTION
  7797. finalRadianceScaled +
  7798. #if defined(SHEEN) && defined(ENVIRONMENTBRDF)
  7799. sheenOut.finalSheenRadianceScaled +
  7800. #endif
  7801. #ifdef CLEARCOAT
  7802. clearcoatOut.finalClearCoatRadianceScaled +
  7803. #endif
  7804. #endif
  7805. #ifdef SS_REFRACTION
  7806. subSurfaceOut.finalRefraction +
  7807. #endif
  7808. #endif
  7809. finalEmissive,
  7810. alpha);
  7811. #ifdef LIGHTMAP
  7812. #ifndef LIGHTMAPEXCLUDED
  7813. #ifdef USELIGHTMAPASSHADOWMAP
  7814. finalColor.rgb*=lightmapColor.rgb;
  7815. #else
  7816. finalColor.rgb+=lightmapColor.rgb;
  7817. #endif
  7818. #endif
  7819. #endif
  7820. #define CUSTOM_FRAGMENT_BEFORE_FOG
  7821. finalColor=max(finalColor,0.0);
  7822. `;ShaderStore.IncludesShadersStore[name$J]=shader$J;var name$I="pbrBlockImageProcessing",shader$I=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)
  7823. #if !defined(SKIPFINALCOLORCLAMP)
  7824. finalColor.rgb=clamp(finalColor.rgb,0.,30.0);
  7825. #endif
  7826. #else
  7827. finalColor=applyImageProcessing(finalColor);
  7828. #endif
  7829. finalColor.a*=visibility;
  7830. #ifdef PREMULTIPLYALPHA
  7831. finalColor.rgb*=finalColor.a;
  7832. #endif
  7833. `;ShaderStore.IncludesShadersStore[name$I]=shader$I;var name$H="pbrDebug",shader$H=`#if DEBUGMODE>0
  7834. if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {
  7835. #if DEBUGMODE == 1
  7836. gl_FragColor.rgb=vPositionW.rgb;
  7837. #define DEBUGMODE_NORMALIZE
  7838. #elif DEBUGMODE == 2 && defined(NORMAL)
  7839. gl_FragColor.rgb=vNormalW.rgb;
  7840. #define DEBUGMODE_NORMALIZE
  7841. #elif DEBUGMODE == 3 && defined(BUMP) || DEBUGMODE == 3 && defined(PARALLAX) || DEBUGMODE == 3 && defined(ANISOTROPIC)
  7842. gl_FragColor.rgb=TBN[0];
  7843. #define DEBUGMODE_NORMALIZE
  7844. #elif DEBUGMODE == 4 && defined(BUMP) || DEBUGMODE == 4 && defined(PARALLAX) || DEBUGMODE == 4 && defined(ANISOTROPIC)
  7845. gl_FragColor.rgb=TBN[1];
  7846. #define DEBUGMODE_NORMALIZE
  7847. #elif DEBUGMODE == 5
  7848. gl_FragColor.rgb=normalW;
  7849. #define DEBUGMODE_NORMALIZE
  7850. #elif DEBUGMODE == 6 && defined(MAINUV1)
  7851. gl_FragColor.rgb=vec3(vMainUV1,0.0);
  7852. #elif DEBUGMODE == 7 && defined(MAINUV2)
  7853. gl_FragColor.rgb=vec3(vMainUV2,0.0);
  7854. #elif DEBUGMODE == 8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
  7855. gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];
  7856. #define DEBUGMODE_NORMALIZE
  7857. #elif DEBUGMODE == 9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
  7858. gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];
  7859. #define DEBUGMODE_NORMALIZE
  7860. #elif DEBUGMODE == 10 && defined(CLEARCOAT)
  7861. gl_FragColor.rgb=clearcoatOut.clearCoatNormalW;
  7862. #define DEBUGMODE_NORMALIZE
  7863. #elif DEBUGMODE == 11 && defined(ANISOTROPIC)
  7864. gl_FragColor.rgb=anisotropicOut.anisotropicNormal;
  7865. #define DEBUGMODE_NORMALIZE
  7866. #elif DEBUGMODE == 12 && defined(ANISOTROPIC)
  7867. gl_FragColor.rgb=anisotropicOut.anisotropicTangent;
  7868. #define DEBUGMODE_NORMALIZE
  7869. #elif DEBUGMODE == 13 && defined(ANISOTROPIC)
  7870. gl_FragColor.rgb=anisotropicOut.anisotropicBitangent;
  7871. #define DEBUGMODE_NORMALIZE
  7872. #elif DEBUGMODE == 20 && defined(ALBEDO)
  7873. gl_FragColor.rgb=albedoTexture.rgb;
  7874. #elif DEBUGMODE == 21 && defined(AMBIENT)
  7875. gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;
  7876. #elif DEBUGMODE == 22 && defined(OPACITY)
  7877. gl_FragColor.rgb=opacityMap.rgb;
  7878. #elif DEBUGMODE == 23 && defined(EMISSIVE)
  7879. gl_FragColor.rgb=emissiveColorTex.rgb;
  7880. #define DEBUGMODE_GAMMA
  7881. #elif DEBUGMODE == 24 && defined(LIGHTMAP)
  7882. gl_FragColor.rgb=lightmapColor.rgb;
  7883. #define DEBUGMODE_GAMMA
  7884. #elif DEBUGMODE == 25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)
  7885. gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;
  7886. #elif DEBUGMODE == 26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)
  7887. gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;
  7888. #define DEBUGMODE_GAMMA
  7889. #elif DEBUGMODE == 27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)
  7890. gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);
  7891. #elif DEBUGMODE == 28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
  7892. gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;
  7893. #elif DEBUGMODE == 29 && defined(SHEEN) && defined(SHEEN_TEXTURE)
  7894. gl_FragColor.rgb=sheenOut.sheenMapData.rgb;
  7895. #elif DEBUGMODE == 30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)
  7896. gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;
  7897. #elif DEBUGMODE == 31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)
  7898. gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;
  7899. #elif DEBUGMODE == 40 && defined(SS_REFRACTION)
  7900. gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;
  7901. #define DEBUGMODE_GAMMA
  7902. #elif DEBUGMODE == 41 && defined(REFLECTION)
  7903. gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;
  7904. #define DEBUGMODE_GAMMA
  7905. #elif DEBUGMODE == 42 && defined(CLEARCOAT) && defined(REFLECTION)
  7906. gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;
  7907. #define DEBUGMODE_GAMMA
  7908. #elif DEBUGMODE == 50
  7909. gl_FragColor.rgb=diffuseBase.rgb;
  7910. #define DEBUGMODE_GAMMA
  7911. #elif DEBUGMODE == 51 && defined(SPECULARTERM)
  7912. gl_FragColor.rgb=specularBase.rgb;
  7913. #define DEBUGMODE_GAMMA
  7914. #elif DEBUGMODE == 52 && defined(CLEARCOAT)
  7915. gl_FragColor.rgb=clearCoatBase.rgb;
  7916. #define DEBUGMODE_GAMMA
  7917. #elif DEBUGMODE == 53 && defined(SHEEN)
  7918. gl_FragColor.rgb=sheenBase.rgb;
  7919. #define DEBUGMODE_GAMMA
  7920. #elif DEBUGMODE == 54 && defined(REFLECTION)
  7921. gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;
  7922. #define DEBUGMODE_GAMMA
  7923. #elif DEBUGMODE == 60
  7924. gl_FragColor.rgb=surfaceAlbedo.rgb;
  7925. #define DEBUGMODE_GAMMA
  7926. #elif DEBUGMODE == 61
  7927. gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;
  7928. #define DEBUGMODE_GAMMA
  7929. #elif DEBUGMODE == 62 && defined(METALLICWORKFLOW)
  7930. gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);
  7931. #elif DEBUGMODE == 71 && defined(METALLICWORKFLOW)
  7932. gl_FragColor.rgb=reflectivityOut.metallicF0;
  7933. #elif DEBUGMODE == 63
  7934. gl_FragColor.rgb=vec3(roughness);
  7935. #elif DEBUGMODE == 64
  7936. gl_FragColor.rgb=vec3(alphaG);
  7937. #elif DEBUGMODE == 65
  7938. gl_FragColor.rgb=vec3(NdotV);
  7939. #elif DEBUGMODE == 66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
  7940. gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;
  7941. #define DEBUGMODE_GAMMA
  7942. #elif DEBUGMODE == 67 && defined(CLEARCOAT)
  7943. gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);
  7944. #elif DEBUGMODE == 68 && defined(CLEARCOAT)
  7945. gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);
  7946. #elif DEBUGMODE == 69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)
  7947. gl_FragColor.rgb=subSurfaceOut.transmittance;
  7948. #elif DEBUGMODE == 70 && defined(SUBSURFACE) && defined(SS_REFRACTION)
  7949. gl_FragColor.rgb=subSurfaceOut.refractionTransmittance;
  7950. #elif DEBUGMODE == 80 && defined(RADIANCEOCCLUSION)
  7951. gl_FragColor.rgb=vec3(seo);
  7952. #elif DEBUGMODE == 81 && defined(HORIZONOCCLUSION)
  7953. gl_FragColor.rgb=vec3(eho);
  7954. #elif DEBUGMODE == 82 && defined(MS_BRDF_ENERGY_CONSERVATION)
  7955. gl_FragColor.rgb=vec3(energyConservationFactor);
  7956. #elif DEBUGMODE == 83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
  7957. gl_FragColor.rgb=specularEnvironmentReflectance;
  7958. #define DEBUGMODE_GAMMA
  7959. #elif DEBUGMODE == 84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
  7960. gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;
  7961. #define DEBUGMODE_GAMMA
  7962. #elif DEBUGMODE == 85 && defined(SHEEN) && defined(REFLECTION)
  7963. gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;
  7964. #define DEBUGMODE_GAMMA
  7965. #elif DEBUGMODE == 86 && defined(ALPHABLEND)
  7966. gl_FragColor.rgb=vec3(luminanceOverAlpha);
  7967. #elif DEBUGMODE == 87
  7968. gl_FragColor.rgb=vec3(alpha);
  7969. #endif
  7970. gl_FragColor.rgb*=vDebugMode.y;
  7971. #ifdef DEBUGMODE_NORMALIZE
  7972. gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;
  7973. #endif
  7974. #ifdef DEBUGMODE_GAMMA
  7975. gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);
  7976. #endif
  7977. gl_FragColor.a=1.0;
  7978. #ifdef PREPASS
  7979. gl_FragData[0]=toLinearSpace(gl_FragColor);
  7980. gl_FragData[1]=vec4(0.,0.,0.,0.);
  7981. #endif
  7982. return;
  7983. }
  7984. #endif`;ShaderStore.IncludesShadersStore[name$H]=shader$H;var name$G="pbrPixelShader",shader$G=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
  7985. #extension GL_OES_standard_derivatives : enable
  7986. #endif
  7987. #ifdef LODBASEDMICROSFURACE
  7988. #extension GL_EXT_shader_texture_lod : enable
  7989. #endif
  7990. #define CUSTOM_FRAGMENT_BEGIN
  7991. #ifdef LOGARITHMICDEPTH
  7992. #extension GL_EXT_frag_depth : enable
  7993. #endif
  7994. #include<prePassDeclaration>[SCENE_MRT_COUNT]
  7995. precision highp float;
  7996. #include<oitDeclaration>
  7997. #ifndef FROMLINEARSPACE
  7998. #define FROMLINEARSPACE
  7999. #endif
  8000. #include<__decl__pbrFragment>
  8001. #include<pbrFragmentExtraDeclaration>
  8002. #include<__decl__lightFragment>[0..maxSimultaneousLights]
  8003. #include<pbrFragmentSamplersDeclaration>
  8004. #include<imageProcessingDeclaration>
  8005. #include<clipPlaneFragmentDeclaration>
  8006. #include<logDepthDeclaration>
  8007. #include<fogFragmentDeclaration>
  8008. #include<helperFunctions>
  8009. #include<subSurfaceScatteringFunctions>
  8010. #include<importanceSampling>
  8011. #include<pbrHelperFunctions>
  8012. #include<imageProcessingFunctions>
  8013. #include<shadowsFragmentFunctions>
  8014. #include<harmonicsFunctions>
  8015. #include<pbrDirectLightingSetupFunctions>
  8016. #include<pbrDirectLightingFalloffFunctions>
  8017. #include<pbrBRDFFunctions>
  8018. #include<hdrFilteringFunctions>
  8019. #include<pbrDirectLightingFunctions>
  8020. #include<pbrIBLFunctions>
  8021. #include<bumpFragmentMainFunctions>
  8022. #include<bumpFragmentFunctions>
  8023. #ifdef REFLECTION
  8024. #include<reflectionFunction>
  8025. #endif
  8026. #define CUSTOM_FRAGMENT_DEFINITIONS
  8027. #include<pbrBlockAlbedoOpacity>
  8028. #include<pbrBlockReflectivity>
  8029. #include<pbrBlockAmbientOcclusion>
  8030. #include<pbrBlockAlphaFresnel>
  8031. #include<pbrBlockAnisotropic>
  8032. #include<pbrBlockReflection>
  8033. #include<pbrBlockSheen>
  8034. #include<pbrBlockClearcoat>
  8035. #include<pbrBlockSubSurface>
  8036. void main(void) {
  8037. #define CUSTOM_FRAGMENT_MAIN_BEGIN
  8038. #include<oitFragment>
  8039. #include<clipPlaneFragment>
  8040. #include<pbrBlockNormalGeometric>
  8041. #include<bumpFragment>
  8042. #include<pbrBlockNormalFinal>
  8043. albedoOpacityOutParams albedoOpacityOut;
  8044. #ifdef ALBEDO
  8045. vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);
  8046. #endif
  8047. #ifdef OPACITY
  8048. vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
  8049. #endif
  8050. albedoOpacityBlock(
  8051. vAlbedoColor,
  8052. #ifdef ALBEDO
  8053. albedoTexture,
  8054. vAlbedoInfos,
  8055. #endif
  8056. #ifdef OPACITY
  8057. opacityMap,
  8058. vOpacityInfos,
  8059. #endif
  8060. #ifdef DETAIL
  8061. detailColor,
  8062. vDetailInfos,
  8063. #endif
  8064. albedoOpacityOut
  8065. );
  8066. vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;
  8067. float alpha=albedoOpacityOut.alpha;
  8068. #define CUSTOM_FRAGMENT_UPDATE_ALPHA
  8069. #include<depthPrePass>
  8070. #define CUSTOM_FRAGMENT_BEFORE_LIGHTS
  8071. ambientOcclusionOutParams aoOut;
  8072. #ifdef AMBIENT
  8073. vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;
  8074. #endif
  8075. ambientOcclusionBlock(
  8076. #ifdef AMBIENT
  8077. ambientOcclusionColorMap,
  8078. vAmbientInfos,
  8079. #endif
  8080. aoOut
  8081. );
  8082. #include<pbrBlockLightmapInit>
  8083. #ifdef UNLIT
  8084. vec3 diffuseBase=vec3(1.,1.,1.);
  8085. #else
  8086. vec3 baseColor=surfaceAlbedo;
  8087. reflectivityOutParams reflectivityOut;
  8088. #if defined(REFLECTIVITY)
  8089. vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);
  8090. vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;
  8091. #ifndef METALLICWORKFLOW
  8092. #ifdef REFLECTIVITY_GAMMA
  8093. surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);
  8094. #endif
  8095. surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;
  8096. #endif
  8097. #endif
  8098. #if defined(MICROSURFACEMAP)
  8099. vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;
  8100. #endif
  8101. #ifdef METALLICWORKFLOW
  8102. vec4 metallicReflectanceFactors=vMetallicReflectanceFactors;
  8103. #ifdef REFLECTANCE
  8104. vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);
  8105. #ifdef REFLECTANCE_GAMMA
  8106. reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);
  8107. #endif
  8108. metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;
  8109. #endif
  8110. #ifdef METALLIC_REFLECTANCE
  8111. vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);
  8112. #ifdef METALLIC_REFLECTANCE_GAMMA
  8113. metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);
  8114. #endif
  8115. #ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY
  8116. metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;
  8117. #endif
  8118. metallicReflectanceFactors*=metallicReflectanceFactorsMap.a;
  8119. #endif
  8120. #endif
  8121. reflectivityBlock(
  8122. vReflectivityColor,
  8123. #ifdef METALLICWORKFLOW
  8124. surfaceAlbedo,
  8125. metallicReflectanceFactors,
  8126. #endif
  8127. #ifdef REFLECTIVITY
  8128. vReflectivityInfos,
  8129. surfaceMetallicOrReflectivityColorMap,
  8130. #endif
  8131. #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
  8132. aoOut.ambientOcclusionColor,
  8133. #endif
  8134. #ifdef MICROSURFACEMAP
  8135. microSurfaceTexel,
  8136. #endif
  8137. #ifdef DETAIL
  8138. detailColor,
  8139. vDetailInfos,
  8140. #endif
  8141. reflectivityOut
  8142. );
  8143. float microSurface=reflectivityOut.microSurface;
  8144. float roughness=reflectivityOut.roughness;
  8145. #ifdef METALLICWORKFLOW
  8146. surfaceAlbedo=reflectivityOut.surfaceAlbedo;
  8147. #endif
  8148. #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
  8149. aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;
  8150. #endif
  8151. #ifdef ALPHAFRESNEL
  8152. #if defined(ALPHATEST) || defined(ALPHABLEND)
  8153. alphaFresnelOutParams alphaFresnelOut;
  8154. alphaFresnelBlock(
  8155. normalW,
  8156. viewDirectionW,
  8157. alpha,
  8158. microSurface,
  8159. alphaFresnelOut
  8160. );
  8161. alpha=alphaFresnelOut.alpha;
  8162. #endif
  8163. #endif
  8164. #include<pbrBlockGeometryInfo>
  8165. #ifdef ANISOTROPIC
  8166. anisotropicOutParams anisotropicOut;
  8167. #ifdef ANISOTROPIC_TEXTURE
  8168. vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;
  8169. #endif
  8170. anisotropicBlock(
  8171. vAnisotropy,
  8172. #ifdef ANISOTROPIC_TEXTURE
  8173. anisotropyMapData,
  8174. #endif
  8175. TBN,
  8176. normalW,
  8177. viewDirectionW,
  8178. anisotropicOut
  8179. );
  8180. #endif
  8181. #ifdef REFLECTION
  8182. reflectionOutParams reflectionOut;
  8183. reflectionBlock(
  8184. vPositionW,
  8185. normalW,
  8186. alphaG,
  8187. vReflectionMicrosurfaceInfos,
  8188. vReflectionInfos,
  8189. vReflectionColor,
  8190. #ifdef ANISOTROPIC
  8191. anisotropicOut,
  8192. #endif
  8193. #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
  8194. NdotVUnclamped,
  8195. #endif
  8196. #ifdef LINEARSPECULARREFLECTION
  8197. roughness,
  8198. #endif
  8199. reflectionSampler,
  8200. #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
  8201. vEnvironmentIrradiance,
  8202. #endif
  8203. #ifdef USESPHERICALFROMREFLECTIONMAP
  8204. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  8205. reflectionMatrix,
  8206. #endif
  8207. #endif
  8208. #ifdef USEIRRADIANCEMAP
  8209. irradianceSampler,
  8210. #endif
  8211. #ifndef LODBASEDMICROSFURACE
  8212. reflectionSamplerLow,
  8213. reflectionSamplerHigh,
  8214. #endif
  8215. #ifdef REALTIME_FILTERING
  8216. vReflectionFilteringInfo,
  8217. #endif
  8218. reflectionOut
  8219. );
  8220. #endif
  8221. #include<pbrBlockReflectance0>
  8222. #ifdef SHEEN
  8223. sheenOutParams sheenOut;
  8224. #ifdef SHEEN_TEXTURE
  8225. vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);
  8226. #endif
  8227. #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
  8228. vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;
  8229. #endif
  8230. sheenBlock(
  8231. vSheenColor,
  8232. #ifdef SHEEN_ROUGHNESS
  8233. vSheenRoughness,
  8234. #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
  8235. sheenMapRoughnessData,
  8236. #endif
  8237. #endif
  8238. roughness,
  8239. #ifdef SHEEN_TEXTURE
  8240. sheenMapData,
  8241. vSheenInfos.y,
  8242. #endif
  8243. reflectance,
  8244. #ifdef SHEEN_LINKWITHALBEDO
  8245. baseColor,
  8246. surfaceAlbedo,
  8247. #endif
  8248. #ifdef ENVIRONMENTBRDF
  8249. NdotV,
  8250. environmentBrdf,
  8251. #endif
  8252. #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
  8253. AARoughnessFactors,
  8254. vReflectionMicrosurfaceInfos,
  8255. vReflectionInfos,
  8256. vReflectionColor,
  8257. vLightingIntensity,
  8258. reflectionSampler,
  8259. reflectionOut.reflectionCoords,
  8260. NdotVUnclamped,
  8261. #ifndef LODBASEDMICROSFURACE
  8262. reflectionSamplerLow,
  8263. reflectionSamplerHigh,
  8264. #endif
  8265. #ifdef REALTIME_FILTERING
  8266. vReflectionFilteringInfo,
  8267. #endif
  8268. #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
  8269. seo,
  8270. #endif
  8271. #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
  8272. eho,
  8273. #endif
  8274. #endif
  8275. sheenOut
  8276. );
  8277. #ifdef SHEEN_LINKWITHALBEDO
  8278. surfaceAlbedo=sheenOut.surfaceAlbedo;
  8279. #endif
  8280. #endif
  8281. clearcoatOutParams clearcoatOut;
  8282. #ifdef CLEARCOAT
  8283. #ifdef CLEARCOAT_TEXTURE
  8284. vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;
  8285. #endif
  8286. #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
  8287. vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;
  8288. #endif
  8289. #if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
  8290. vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);
  8291. #endif
  8292. #ifdef CLEARCOAT_BUMP
  8293. vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);
  8294. #endif
  8295. clearcoatBlock(
  8296. vPositionW,
  8297. geometricNormalW,
  8298. viewDirectionW,
  8299. vClearCoatParams,
  8300. #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
  8301. clearCoatMapRoughnessData,
  8302. #endif
  8303. specularEnvironmentR0,
  8304. #ifdef CLEARCOAT_TEXTURE
  8305. clearCoatMapData,
  8306. #endif
  8307. #ifdef CLEARCOAT_TINT
  8308. vClearCoatTintParams,
  8309. clearCoatColorAtDistance,
  8310. vClearCoatRefractionParams,
  8311. #ifdef CLEARCOAT_TINT_TEXTURE
  8312. clearCoatTintMapData,
  8313. #endif
  8314. #endif
  8315. #ifdef CLEARCOAT_BUMP
  8316. vClearCoatBumpInfos,
  8317. clearCoatBumpMapData,
  8318. vClearCoatBumpUV,
  8319. #if defined(TANGENT) && defined(NORMAL)
  8320. vTBN,
  8321. #else
  8322. vClearCoatTangentSpaceParams,
  8323. #endif
  8324. #ifdef OBJECTSPACE_NORMALMAP
  8325. normalMatrix,
  8326. #endif
  8327. #endif
  8328. #if defined(FORCENORMALFORWARD) && defined(NORMAL)
  8329. faceNormal,
  8330. #endif
  8331. #ifdef REFLECTION
  8332. vReflectionMicrosurfaceInfos,
  8333. vReflectionInfos,
  8334. vReflectionColor,
  8335. vLightingIntensity,
  8336. reflectionSampler,
  8337. #ifndef LODBASEDMICROSFURACE
  8338. reflectionSamplerLow,
  8339. reflectionSamplerHigh,
  8340. #endif
  8341. #ifdef REALTIME_FILTERING
  8342. vReflectionFilteringInfo,
  8343. #endif
  8344. #endif
  8345. #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
  8346. #ifdef RADIANCEOCCLUSION
  8347. ambientMonochrome,
  8348. #endif
  8349. #endif
  8350. #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
  8351. (gl_FrontFacing ? 1. : -1.),
  8352. #endif
  8353. clearcoatOut
  8354. );
  8355. #else
  8356. clearcoatOut.specularEnvironmentR0=specularEnvironmentR0;
  8357. #endif
  8358. #include<pbrBlockReflectance>
  8359. subSurfaceOutParams subSurfaceOut;
  8360. #ifdef SUBSURFACE
  8361. #ifdef SS_THICKNESSANDMASK_TEXTURE
  8362. vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);
  8363. #endif
  8364. #ifdef SS_REFRACTIONINTENSITY_TEXTURE
  8365. vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);
  8366. #endif
  8367. #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
  8368. vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);
  8369. #endif
  8370. subSurfaceBlock(
  8371. vSubSurfaceIntensity,
  8372. vThicknessParam,
  8373. vTintColor,
  8374. normalW,
  8375. specularEnvironmentReflectance,
  8376. #ifdef SS_THICKNESSANDMASK_TEXTURE
  8377. thicknessMap,
  8378. #endif
  8379. #ifdef SS_REFRACTIONINTENSITY_TEXTURE
  8380. refractionIntensityMap,
  8381. #endif
  8382. #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
  8383. translucencyIntensityMap,
  8384. #endif
  8385. #ifdef REFLECTION
  8386. #ifdef SS_TRANSLUCENCY
  8387. reflectionMatrix,
  8388. #ifdef USESPHERICALFROMREFLECTIONMAP
  8389. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  8390. reflectionOut.irradianceVector,
  8391. #endif
  8392. #if defined(REALTIME_FILTERING)
  8393. reflectionSampler,
  8394. vReflectionFilteringInfo,
  8395. #endif
  8396. #endif
  8397. #ifdef USEIRRADIANCEMAP
  8398. irradianceSampler,
  8399. #endif
  8400. #endif
  8401. #endif
  8402. #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
  8403. surfaceAlbedo,
  8404. #endif
  8405. #ifdef SS_REFRACTION
  8406. vPositionW,
  8407. viewDirectionW,
  8408. view,
  8409. vRefractionInfos,
  8410. refractionMatrix,
  8411. vRefractionMicrosurfaceInfos,
  8412. vLightingIntensity,
  8413. #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
  8414. alpha,
  8415. #endif
  8416. #ifdef SS_LODINREFRACTIONALPHA
  8417. NdotVUnclamped,
  8418. #endif
  8419. #ifdef SS_LINEARSPECULARREFRACTION
  8420. roughness,
  8421. #endif
  8422. alphaG,
  8423. refractionSampler,
  8424. #ifndef LODBASEDMICROSFURACE
  8425. refractionSamplerLow,
  8426. refractionSamplerHigh,
  8427. #endif
  8428. #ifdef ANISOTROPIC
  8429. anisotropicOut,
  8430. #endif
  8431. #ifdef REALTIME_FILTERING
  8432. vRefractionFilteringInfo,
  8433. #endif
  8434. #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
  8435. vRefractionPosition,
  8436. vRefractionSize,
  8437. #endif
  8438. #endif
  8439. #ifdef SS_TRANSLUCENCY
  8440. vDiffusionDistance,
  8441. #endif
  8442. subSurfaceOut
  8443. );
  8444. #ifdef SS_REFRACTION
  8445. surfaceAlbedo=subSurfaceOut.surfaceAlbedo;
  8446. #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
  8447. alpha=subSurfaceOut.alpha;
  8448. #endif
  8449. #endif
  8450. #else
  8451. subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;
  8452. #endif
  8453. #include<pbrBlockDirectLighting>
  8454. #include<lightFragment>[0..maxSimultaneousLights]
  8455. #include<pbrBlockFinalLitComponents>
  8456. #endif
  8457. #include<pbrBlockFinalUnlitComponents>
  8458. #define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
  8459. #include<pbrBlockFinalColorComposition>
  8460. #include<logDepthFragment>
  8461. #include<fogFragment>(color,finalColor)
  8462. #include<pbrBlockImageProcessing>
  8463. #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
  8464. #ifdef PREPASS
  8465. float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;
  8466. #ifdef PREPASS_POSITION
  8467. gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
  8468. #endif
  8469. #ifdef PREPASS_VELOCITY
  8470. vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;
  8471. vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;
  8472. vec2 velocity=abs(a-b);
  8473. velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;
  8474. gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
  8475. #endif
  8476. #ifdef PREPASS_ALBEDO_SQRT
  8477. vec3 sqAlbedo=sqrt(surfaceAlbedo);
  8478. #endif
  8479. #ifdef PREPASS_IRRADIANCE
  8480. vec3 irradiance=finalDiffuse;
  8481. #ifndef UNLIT
  8482. #ifdef REFLECTION
  8483. irradiance+=finalIrradiance;
  8484. #endif
  8485. #endif
  8486. #ifdef SS_SCATTERING
  8487. gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a);
  8488. irradiance/=sqAlbedo;
  8489. #else
  8490. gl_FragData[0]=finalColor;
  8491. float scatteringDiffusionProfile=255.;
  8492. #endif
  8493. gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.);
  8494. #else
  8495. gl_FragData[0]=vec4(finalColor.rgb,finalColor.a);
  8496. #endif
  8497. #ifdef PREPASS_DEPTH
  8498. gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo);
  8499. #endif
  8500. #ifdef PREPASS_NORMAL
  8501. gl_FragData[PREPASS_NORMAL_INDEX]=vec4((view*vec4(normalW,0.0)).rgb,writeGeometryInfo);
  8502. #endif
  8503. #ifdef PREPASS_ALBEDO_SQRT
  8504. gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo);
  8505. #endif
  8506. #ifdef PREPASS_REFLECTIVITY
  8507. #if defined(REFLECTIVITY)
  8508. gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(baseReflectivity.rgb,baseReflectivity.a*writeGeometryInfo);
  8509. #else
  8510. gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
  8511. #endif
  8512. #endif
  8513. #endif
  8514. #if !defined(PREPASS) || defined(WEBGL2)
  8515. gl_FragColor=finalColor;
  8516. #endif
  8517. #if ORDER_INDEPENDENT_TRANSPARENCY
  8518. if (fragDepth == nearestDepth) {
  8519. frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;
  8520. frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);
  8521. } else {
  8522. backColor+=finalColor;
  8523. }
  8524. #endif
  8525. #include<pbrDebug>
  8526. }
  8527. `;ShaderStore.ShadersStore[name$G]=shader$G;var name$F="pbrVertexDeclaration",shader$F=`uniform mat4 view;
  8528. uniform mat4 viewProjection;
  8529. #ifdef ALBEDO
  8530. uniform mat4 albedoMatrix;
  8531. uniform vec2 vAlbedoInfos;
  8532. #endif
  8533. #ifdef AMBIENT
  8534. uniform mat4 ambientMatrix;
  8535. uniform vec4 vAmbientInfos;
  8536. #endif
  8537. #ifdef OPACITY
  8538. uniform mat4 opacityMatrix;
  8539. uniform vec2 vOpacityInfos;
  8540. #endif
  8541. #ifdef EMISSIVE
  8542. uniform vec2 vEmissiveInfos;
  8543. uniform mat4 emissiveMatrix;
  8544. #endif
  8545. #ifdef LIGHTMAP
  8546. uniform vec2 vLightmapInfos;
  8547. uniform mat4 lightmapMatrix;
  8548. #endif
  8549. #ifdef REFLECTIVITY
  8550. uniform vec3 vReflectivityInfos;
  8551. uniform mat4 reflectivityMatrix;
  8552. #endif
  8553. #ifdef METALLIC_REFLECTANCE
  8554. uniform vec2 vMetallicReflectanceInfos;
  8555. uniform mat4 metallicReflectanceMatrix;
  8556. #endif
  8557. #ifdef REFLECTANCE
  8558. uniform vec2 vReflectanceInfos;
  8559. uniform mat4 reflectanceMatrix;
  8560. #endif
  8561. #ifdef MICROSURFACEMAP
  8562. uniform vec2 vMicroSurfaceSamplerInfos;
  8563. uniform mat4 microSurfaceSamplerMatrix;
  8564. #endif
  8565. #ifdef BUMP
  8566. uniform vec3 vBumpInfos;
  8567. uniform mat4 bumpMatrix;
  8568. #endif
  8569. #ifdef POINTSIZE
  8570. uniform float pointSize;
  8571. #endif
  8572. #ifdef REFLECTION
  8573. uniform vec2 vReflectionInfos;
  8574. uniform mat4 reflectionMatrix;
  8575. #endif
  8576. #ifdef CLEARCOAT
  8577. #if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
  8578. uniform vec4 vClearCoatInfos;
  8579. #endif
  8580. #ifdef CLEARCOAT_TEXTURE
  8581. uniform mat4 clearCoatMatrix;
  8582. #endif
  8583. #ifdef CLEARCOAT_TEXTURE_ROUGHNESS
  8584. uniform mat4 clearCoatRoughnessMatrix;
  8585. #endif
  8586. #ifdef CLEARCOAT_BUMP
  8587. uniform vec2 vClearCoatBumpInfos;
  8588. uniform mat4 clearCoatBumpMatrix;
  8589. #endif
  8590. #ifdef CLEARCOAT_TINT_TEXTURE
  8591. uniform vec2 vClearCoatTintInfos;
  8592. uniform mat4 clearCoatTintMatrix;
  8593. #endif
  8594. #endif
  8595. #ifdef ANISOTROPIC
  8596. #ifdef ANISOTROPIC_TEXTURE
  8597. uniform vec2 vAnisotropyInfos;
  8598. uniform mat4 anisotropyMatrix;
  8599. #endif
  8600. #endif
  8601. #ifdef SHEEN
  8602. #if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
  8603. uniform vec4 vSheenInfos;
  8604. #endif
  8605. #ifdef SHEEN_TEXTURE
  8606. uniform mat4 sheenMatrix;
  8607. #endif
  8608. #ifdef SHEEN_TEXTURE_ROUGHNESS
  8609. uniform mat4 sheenRoughnessMatrix;
  8610. #endif
  8611. #endif
  8612. #ifdef SUBSURFACE
  8613. #ifdef SS_REFRACTION
  8614. uniform vec4 vRefractionInfos;
  8615. uniform mat4 refractionMatrix;
  8616. #endif
  8617. #ifdef SS_THICKNESSANDMASK_TEXTURE
  8618. uniform vec2 vThicknessInfos;
  8619. uniform mat4 thicknessMatrix;
  8620. #endif
  8621. #ifdef SS_REFRACTIONINTENSITY_TEXTURE
  8622. uniform vec2 vRefractionIntensityInfos;
  8623. uniform mat4 refractionIntensityMatrix;
  8624. #endif
  8625. #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
  8626. uniform vec2 vTranslucencyIntensityInfos;
  8627. uniform mat4 translucencyIntensityMatrix;
  8628. #endif
  8629. #endif
  8630. #ifdef NORMAL
  8631. #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
  8632. #ifdef USESPHERICALFROMREFLECTIONMAP
  8633. #ifdef SPHERICAL_HARMONICS
  8634. uniform vec3 vSphericalL00;
  8635. uniform vec3 vSphericalL1_1;
  8636. uniform vec3 vSphericalL10;
  8637. uniform vec3 vSphericalL11;
  8638. uniform vec3 vSphericalL2_2;
  8639. uniform vec3 vSphericalL2_1;
  8640. uniform vec3 vSphericalL20;
  8641. uniform vec3 vSphericalL21;
  8642. uniform vec3 vSphericalL22;
  8643. #else
  8644. uniform vec3 vSphericalX;
  8645. uniform vec3 vSphericalY;
  8646. uniform vec3 vSphericalZ;
  8647. uniform vec3 vSphericalXX_ZZ;
  8648. uniform vec3 vSphericalYY_ZZ;
  8649. uniform vec3 vSphericalZZ;
  8650. uniform vec3 vSphericalXY;
  8651. uniform vec3 vSphericalYZ;
  8652. uniform vec3 vSphericalZX;
  8653. #endif
  8654. #endif
  8655. #endif
  8656. #endif
  8657. #ifdef DETAIL
  8658. uniform vec4 vDetailInfos;
  8659. uniform mat4 detailMatrix;
  8660. #endif`;ShaderStore.IncludesShadersStore[name$F]=shader$F;var name$E="pbrVertexShader",shader$E=`precision highp float;
  8661. #include<__decl__pbrVertex>
  8662. #define CUSTOM_VERTEX_BEGIN
  8663. attribute vec3 position;
  8664. #ifdef NORMAL
  8665. attribute vec3 normal;
  8666. #endif
  8667. #ifdef TANGENT
  8668. attribute vec4 tangent;
  8669. #endif
  8670. #ifdef UV1
  8671. attribute vec2 uv;
  8672. #endif
  8673. #include<uvAttributeDeclaration>[2..7]
  8674. #include<mainUVVaryingDeclaration>[1..7]
  8675. #ifdef VERTEXCOLOR
  8676. attribute vec4 color;
  8677. #endif
  8678. #include<helperFunctions>
  8679. #include<bonesDeclaration>
  8680. #include<bakedVertexAnimationDeclaration>
  8681. #include<instancesDeclaration>
  8682. #include<prePassVertexDeclaration>
  8683. #include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)
  8684. #include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
  8685. #include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
  8686. #include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
  8687. #include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
  8688. #include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
  8689. #include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)
  8690. #include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)
  8691. #include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)
  8692. #include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)
  8693. #include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
  8694. #ifdef CLEARCOAT
  8695. #include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)
  8696. #include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
  8697. #include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)
  8698. #include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)
  8699. #endif
  8700. #ifdef SHEEN
  8701. #include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)
  8702. #include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
  8703. #endif
  8704. #ifdef ANISOTROPIC
  8705. #include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)
  8706. #endif
  8707. #ifdef SUBSURFACE
  8708. #include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)
  8709. #include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)
  8710. #include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)
  8711. #endif
  8712. varying vec3 vPositionW;
  8713. #if DEBUGMODE>0
  8714. varying vec4 vClipSpacePosition;
  8715. #endif
  8716. #ifdef NORMAL
  8717. varying vec3 vNormalW;
  8718. #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
  8719. varying vec3 vEnvironmentIrradiance;
  8720. #include<harmonicsFunctions>
  8721. #endif
  8722. #endif
  8723. #ifdef VERTEXCOLOR
  8724. varying vec4 vColor;
  8725. #endif
  8726. #include<bumpVertexDeclaration>
  8727. #include<clipPlaneVertexDeclaration>
  8728. #include<fogVertexDeclaration>
  8729. #include<__decl__lightVxFragment>[0..maxSimultaneousLights]
  8730. #include<morphTargetsVertexGlobalDeclaration>
  8731. #include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
  8732. #ifdef REFLECTIONMAP_SKYBOX
  8733. varying vec3 vPositionUVW;
  8734. #endif
  8735. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  8736. varying vec3 vDirectionW;
  8737. #endif
  8738. #include<logDepthDeclaration>
  8739. #define CUSTOM_VERTEX_DEFINITIONS
  8740. void main(void) {
  8741. #define CUSTOM_VERTEX_MAIN_BEGIN
  8742. vec3 positionUpdated=position;
  8743. #ifdef NORMAL
  8744. vec3 normalUpdated=normal;
  8745. #endif
  8746. #ifdef TANGENT
  8747. vec4 tangentUpdated=tangent;
  8748. #endif
  8749. #ifdef UV1
  8750. vec2 uvUpdated=uv;
  8751. #endif
  8752. #include<morphTargetsVertexGlobal>
  8753. #include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
  8754. #ifdef REFLECTIONMAP_SKYBOX
  8755. vPositionUVW=positionUpdated;
  8756. #endif
  8757. #define CUSTOM_VERTEX_UPDATE_POSITION
  8758. #define CUSTOM_VERTEX_UPDATE_NORMAL
  8759. #include<instancesVertex>
  8760. #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)
  8761. vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
  8762. vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0);
  8763. #endif
  8764. #include<bonesVertex>
  8765. #include<bakedVertexAnimation>
  8766. vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
  8767. vPositionW=vec3(worldPos);
  8768. #include<prePassVertex>
  8769. #ifdef NORMAL
  8770. mat3 normalWorld=mat3(finalWorld);
  8771. #if defined(INSTANCES) && defined(THIN_INSTANCES)
  8772. vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));
  8773. vNormalW=normalize(normalWorld*vNormalW);
  8774. #else
  8775. #ifdef NONUNIFORMSCALING
  8776. normalWorld=transposeMat3(inverseMat3(normalWorld));
  8777. #endif
  8778. vNormalW=normalize(normalWorld*normalUpdated);
  8779. #endif
  8780. #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
  8781. vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;
  8782. #ifdef REFLECTIONMAP_OPPOSITEZ
  8783. reflectionVector.z*=-1.0;
  8784. #endif
  8785. vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
  8786. #endif
  8787. #endif
  8788. #define CUSTOM_VERTEX_UPDATE_WORLDPOS
  8789. #ifdef MULTIVIEW
  8790. if (gl_ViewID_OVR == 0u) {
  8791. gl_Position=viewProjection*worldPos;
  8792. } else {
  8793. gl_Position=viewProjectionR*worldPos;
  8794. }
  8795. #else
  8796. gl_Position=viewProjection*worldPos;
  8797. #endif
  8798. #if DEBUGMODE>0
  8799. vClipSpacePosition=gl_Position;
  8800. #endif
  8801. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  8802. vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
  8803. #endif
  8804. #ifndef UV1
  8805. vec2 uvUpdated=vec2(0.,0.);
  8806. #endif
  8807. #ifdef MAINUV1
  8808. vMainUV1=uvUpdated;
  8809. #endif
  8810. #include<uvVariableDeclaration>[2..7]
  8811. #include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)
  8812. #include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
  8813. #include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
  8814. #include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
  8815. #include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
  8816. #include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
  8817. #include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)
  8818. #include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)
  8819. #include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)
  8820. #include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)
  8821. #include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
  8822. #ifdef CLEARCOAT
  8823. #include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)
  8824. #include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)
  8825. #include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)
  8826. #include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)
  8827. #endif
  8828. #ifdef SHEEN
  8829. #include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)
  8830. #include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z)
  8831. #endif
  8832. #ifdef ANISOTROPIC
  8833. #include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)
  8834. #endif
  8835. #ifdef SUBSURFACE
  8836. #include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)
  8837. #include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)
  8838. #include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)
  8839. #endif
  8840. #include<bumpVertex>
  8841. #include<clipPlaneVertex>
  8842. #include<fogVertex>
  8843. #include<shadowsVertex>[0..maxSimultaneousLights]
  8844. #ifdef VERTEXCOLOR
  8845. vColor=color;
  8846. #endif
  8847. #ifdef POINTSIZE
  8848. gl_PointSize=pointSize;
  8849. #endif
  8850. #include<logDepthVertex>
  8851. #define CUSTOM_VERTEX_MAIN_END
  8852. }`;ShaderStore.ShadersStore[name$E]=shader$E;var onCreatedEffectParameters={effect:null,subMesh:null},PBRMaterialDefines=function(a){__extends(i,a);function i(){var e=a.call(this)||this;return e.PBR=!0,e.NUM_SAMPLES="0",e.REALTIME_FILTERING=!1,e.MAINUV1=!1,e.MAINUV2=!1,e.MAINUV3=!1,e.MAINUV4=!1,e.MAINUV5=!1,e.MAINUV6=!1,e.UV1=!1,e.UV2=!1,e.UV3=!1,e.UV4=!1,e.UV5=!1,e.UV6=!1,e.ALBEDO=!1,e.GAMMAALBEDO=!1,e.ALBEDODIRECTUV=0,e.VERTEXCOLOR=!1,e.DETAIL=!1,e.DETAILDIRECTUV=0,e.DETAIL_NORMALBLENDMETHOD=0,e.BAKED_VERTEX_ANIMATION_TEXTURE=!1,e.AMBIENT=!1,e.AMBIENTDIRECTUV=0,e.AMBIENTINGRAYSCALE=!1,e.OPACITY=!1,e.VERTEXALPHA=!1,e.OPACITYDIRECTUV=0,e.OPACITYRGB=!1,e.ALPHATEST=!1,e.DEPTHPREPASS=!1,e.ALPHABLEND=!1,e.ALPHAFROMALBEDO=!1,e.ALPHATESTVALUE="0.5",e.SPECULAROVERALPHA=!1,e.RADIANCEOVERALPHA=!1,e.ALPHAFRESNEL=!1,e.LINEARALPHAFRESNEL=!1,e.PREMULTIPLYALPHA=!1,e.EMISSIVE=!1,e.EMISSIVEDIRECTUV=0,e.GAMMAEMISSIVE=!1,e.REFLECTIVITY=!1,e.REFLECTIVITY_GAMMA=!1,e.REFLECTIVITYDIRECTUV=0,e.SPECULARTERM=!1,e.MICROSURFACEFROMREFLECTIVITYMAP=!1,e.MICROSURFACEAUTOMATIC=!1,e.LODBASEDMICROSFURACE=!1,e.MICROSURFACEMAP=!1,e.MICROSURFACEMAPDIRECTUV=0,e.METALLICWORKFLOW=!1,e.ROUGHNESSSTOREINMETALMAPALPHA=!1,e.ROUGHNESSSTOREINMETALMAPGREEN=!1,e.METALLNESSSTOREINMETALMAPBLUE=!1,e.AOSTOREINMETALMAPRED=!1,e.METALLIC_REFLECTANCE=!1,e.METALLIC_REFLECTANCE_GAMMA=!1,e.METALLIC_REFLECTANCEDIRECTUV=0,e.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,e.REFLECTANCE=!1,e.REFLECTANCE_GAMMA=!1,e.REFLECTANCEDIRECTUV=0,e.ENVIRONMENTBRDF=!1,e.ENVIRONMENTBRDF_RGBD=!1,e.NORMAL=!1,e.TANGENT=!1,e.BUMP=!1,e.BUMPDIRECTUV=0,e.OBJECTSPACE_NORMALMAP=!1,e.PARALLAX=!1,e.PARALLAXOCCLUSION=!1,e.NORMALXYSCALE=!0,e.LIGHTMAP=!1,e.LIGHTMAPDIRECTUV=0,e.USELIGHTMAPASSHADOWMAP=!1,e.GAMMALIGHTMAP=!1,e.RGBDLIGHTMAP=!1,e.REFLECTION=!1,e.REFLECTIONMAP_3D=!1,e.REFLECTIONMAP_SPHERICAL=!1,e.REFLECTIONMAP_PLANAR=!1,e.REFLECTIONMAP_CUBIC=!1,e.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,e.REFLECTIONMAP_PROJECTION=!1,e.REFLECTIONMAP_SKYBOX=!1,e.REFLECTIONMAP_EXPLICIT=!1,e.REFLECTIONMAP_EQUIRECTANGULAR=!1,e.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,e.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.INVERTCUBICMAP=!1,e.USESPHERICALFROMREFLECTIONMAP=!1,e.USEIRRADIANCEMAP=!1,e.SPHERICAL_HARMONICS=!1,e.USESPHERICALINVERTEX=!1,e.REFLECTIONMAP_OPPOSITEZ=!1,e.LODINREFLECTIONALPHA=!1,e.GAMMAREFLECTION=!1,e.RGBDREFLECTION=!1,e.LINEARSPECULARREFLECTION=!1,e.RADIANCEOCCLUSION=!1,e.HORIZONOCCLUSION=!1,e.INSTANCES=!1,e.THIN_INSTANCES=!1,e.PREPASS=!1,e.PREPASS_IRRADIANCE=!1,e.PREPASS_IRRADIANCE_INDEX=-1,e.PREPASS_ALBEDO_SQRT=!1,e.PREPASS_ALBEDO_SQRT_INDEX=-1,e.PREPASS_DEPTH=!1,e.PREPASS_DEPTH_INDEX=-1,e.PREPASS_NORMAL=!1,e.PREPASS_NORMAL_INDEX=-1,e.PREPASS_POSITION=!1,e.PREPASS_POSITION_INDEX=-1,e.PREPASS_VELOCITY=!1,e.PREPASS_VELOCITY_INDEX=-1,e.PREPASS_REFLECTIVITY=!1,e.PREPASS_REFLECTIVITY_INDEX=-1,e.SCENE_MRT_COUNT=0,e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE=!1,e.BONES_VELOCITY_ENABLED=!1,e.NONUNIFORMSCALING=!1,e.MORPHTARGETS=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_UV=!1,e.NUM_MORPH_INFLUENCERS=0,e.MORPHTARGETS_TEXTURE=!1,e.IMAGEPROCESSING=!1,e.VIGNETTE=!1,e.VIGNETTEBLENDMODEMULTIPLY=!1,e.VIGNETTEBLENDMODEOPAQUE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=!1,e.SAMPLER3DBGRMAP=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.SKIPFINALCOLORCLAMP=!1,e.EXPOSURE=!1,e.MULTIVIEW=!1,e.ORDER_INDEPENDENT_TRANSPARENCY=!1,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,e.USEPHYSICALLIGHTFALLOFF=!1,e.USEGLTFLIGHTFALLOFF=!1,e.TWOSIDEDLIGHTING=!1,e.SHADOWFLOAT=!1,e.CLIPPLANE=!1,e.CLIPPLANE2=!1,e.CLIPPLANE3=!1,e.CLIPPLANE4=!1,e.CLIPPLANE5=!1,e.CLIPPLANE6=!1,e.POINTSIZE=!1,e.FOG=!1,e.LOGARITHMICDEPTH=!1,e.FORCENORMALFORWARD=!1,e.SPECULARAA=!1,e.CLEARCOAT=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!0,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_TINT_GAMMATEXTURE=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.BRDF_V_HEIGHT_CORRELATED=!1,e.MS_BRDF_ENERGY_CONSERVATION=!1,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1,e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SUBSURFACE=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_SCATTERING=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.UNLIT=!1,e.DEBUGMODE=0,e.rebuild(),e}return i.prototype.reset=function(){a.prototype.reset.call(this),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0},i}(MaterialDefines),PBRBaseMaterial=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s._directIntensity=1,s._emissiveIntensity=1,s._environmentIntensity=1,s._specularIntensity=1,s._lightingInfos=new Vector4(s._directIntensity,s._emissiveIntensity,s._environmentIntensity,s._specularIntensity),s._disableBumpMap=!1,s._albedoTexture=null,s._ambientTexture=null,s._ambientTextureStrength=1,s._ambientTextureImpactOnAnalyticalLights=i.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,s._opacityTexture=null,s._reflectionTexture=null,s._emissiveTexture=null,s._reflectivityTexture=null,s._metallicTexture=null,s._metallic=null,s._roughness=null,s._metallicF0Factor=1,s._metallicReflectanceColor=Color3.White(),s._useOnlyMetallicFromMetallicReflectanceTexture=!1,s._metallicReflectanceTexture=null,s._reflectanceTexture=null,s._microSurfaceTexture=null,s._bumpTexture=null,s._lightmapTexture=null,s._ambientColor=new Color3(0,0,0),s._albedoColor=new Color3(1,1,1),s._reflectivityColor=new Color3(1,1,1),s._reflectionColor=new Color3(1,1,1),s._emissiveColor=new Color3(0,0,0),s._microSurface=.9,s._useLightmapAsShadowmap=!1,s._useHorizonOcclusion=!0,s._useRadianceOcclusion=!0,s._useAlphaFromAlbedoTexture=!1,s._useSpecularOverAlpha=!0,s._useMicroSurfaceFromReflectivityMapAlpha=!1,s._useRoughnessFromMetallicTextureAlpha=!0,s._useRoughnessFromMetallicTextureGreen=!1,s._useMetallnessFromMetallicTextureBlue=!1,s._useAmbientOcclusionFromMetallicTextureRed=!1,s._useAmbientInGrayScale=!1,s._useAutoMicroSurfaceFromReflectivityMap=!1,s._lightFalloff=i.LIGHTFALLOFF_PHYSICAL,s._useRadianceOverAlpha=!0,s._useObjectSpaceNormalMap=!1,s._useParallax=!1,s._useParallaxOcclusion=!1,s._parallaxScaleBias=.05,s._disableLighting=!1,s._maxSimultaneousLights=4,s._invertNormalMapX=!1,s._invertNormalMapY=!1,s._twoSidedLighting=!1,s._alphaCutOff=.4,s._forceAlphaTest=!1,s._useAlphaFresnel=!1,s._useLinearAlphaFresnel=!1,s._environmentBRDFTexture=null,s._forceIrradianceInFragment=!1,s._realTimeFiltering=!1,s._realTimeFilteringQuality=8,s._forceNormalForward=!1,s._enableSpecularAntiAliasing=!1,s._imageProcessingObserver=null,s._renderTargets=new SmartArray(16),s._globalAmbientColor=new Color3(0,0,0),s._useLogarithmicDepth=!1,s._unlit=!1,s._debugMode=0,s.debugMode=0,s.debugLimit=-1,s.debugFactor=1,s.clearCoat=new PBRClearCoatConfiguration(s._markAllSubMeshesAsTexturesDirty.bind(s)),s.anisotropy=new PBRAnisotropicConfiguration(s._markAllSubMeshesAsTexturesDirty.bind(s)),s.brdf=new PBRBRDFConfiguration(s._markAllSubMeshesAsMiscDirty.bind(s)),s.sheen=new PBRSheenConfiguration(s._markAllSubMeshesAsTexturesDirty.bind(s)),s.detailMap=new DetailMapConfiguration(s._markAllSubMeshesAsTexturesDirty.bind(s)),s.buildUniformLayout(),s._attachImageProcessingConfiguration(null),s.getRenderTargetTextures=function(){return s._renderTargets.reset(),MaterialFlags.ReflectionTextureEnabled&&s._reflectionTexture&&s._reflectionTexture.isRenderTarget&&s._renderTargets.push(s._reflectionTexture),s.subSurface.fillRenderTargetTextures(s._renderTargets),s._renderTargets},s._environmentBRDFTexture=GetEnvironmentBRDFTexture(o),s.subSurface=new PBRSubSurfaceConfiguration(s._markAllSubMeshesAsTexturesDirty.bind(s),s._markScenePrePassDirty.bind(s),o),s.prePassConfiguration=new PrePassConfiguration,s}return Object.defineProperty(i.prototype,"realTimeFiltering",{get:function(){return this._realTimeFiltering},set:function(e){this._realTimeFiltering=e,this.markAsDirty(1)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"realTimeFilteringQuality",{get:function(){return this._realTimeFilteringQuality},set:function(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"canRenderToMRT",{get:function(){return!0},enumerable:!1,configurable:!0}),i.prototype._attachImageProcessingConfiguration=function(e){var o=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){o._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(i.prototype,"hasRenderTargetTextures",{get:function(){return MaterialFlags.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this.subSurface.hasRenderTargetTextures()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isPrePassCapable",{get:function(){return!this.disableDepthWrite},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"PBRBaseMaterial"},Object.defineProperty(i.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_disableAlphaBlending",{get:function(){return this.subSurface.disableAlphaBlending||this._transparencyMode===i.PBRMATERIAL_OPAQUE||this._transparencyMode===i.PBRMATERIAL_ALPHATEST},enumerable:!1,configurable:!0}),i.prototype.needAlphaBlending=function(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture()},i.prototype.needAlphaTesting=function(){return this._forceAlphaTest?!0:this.subSurface.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===i.PBRMATERIAL_ALPHATEST)},i.prototype._shouldUseAlphaFromAlbedoTexture=function(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==i.PBRMATERIAL_OPAQUE},i.prototype._hasAlphaChannel=function(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null},i.prototype.getAlphaTestTexture=function(){return this._albedoTexture},i.prototype.isReadyForSubMesh=function(e,o,s){if(o.effect&&this.isFrozen&&o.effect._wasPreviouslyReady)return!0;o.materialDefines||(o.materialDefines=new PBRMaterialDefines);var c=o.materialDefines;if(this._isReadyForSubMesh(o))return!0;var d=this.getScene(),_=d.getEngine();if(c._areTexturesDirty&&d.texturesEnabled){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;var b=this._getReflectionTexture();if(b&&MaterialFlags.ReflectionTextureEnabled&&(!b.isReadyOrNotBlocking()||b.irradianceTexture&&!b.irradianceTexture.isReadyOrNotBlocking())||this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(_.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(!this.subSurface.isReadyForSubMesh(c,d)||!this.clearCoat.isReadyForSubMesh(c,d,_,this._disableBumpMap)||!this.sheen.isReadyForSubMesh(c,d)||!this.anisotropy.isReadyForSubMesh(c,d)||!this.detailMap.isReadyForSubMesh(c,d)||c._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;!_.getCaps().standardDerivatives&&!e.isVerticesDataPresent(VertexBuffer.NormalKind)&&(e.createNormals(!0),Logger$2.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));var k=o.effect,j=c._areLightsDisposed,$=this._prepareEffect(e,c,this.onCompiled,this.onError,s,null,o.getRenderingMesh().hasThinInstances);if($)if(this._onEffectCreatedObservable&&(onCreatedEffectParameters.effect=$,onCreatedEffectParameters.subMesh=o,this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters)),this.allowShaderHotSwapping&&k&&!$.isReady()){if($=k,c.markAsUnprocessed(),j)return c._areLightsDisposed=!0,!1}else d.resetCachedMaterial(),o.setEffect($,c,this._materialContext);return!o.effect||!o.effect.isReady()?!1:(c._renderId=d.getRenderId(),o.effect._wasPreviouslyReady=!0,!0)},i.prototype.isMetallicWorkflow=function(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)},i.prototype._prepareEffect=function(e,o,s,c,d,_,b){if(s===void 0&&(s=null),c===void 0&&(c=null),d===void 0&&(d=null),_===void 0&&(_=null),this._prepareDefines(e,o,d,_,b),!o.isDirty)return null;o.markAsProcessed();var k=this.getScene(),j=k.getEngine(),$=new EffectFallbacks,_e=0;o.USESPHERICALINVERTEX&&$.addFallback(_e++,"USESPHERICALINVERTEX"),o.FOG&&$.addFallback(_e,"FOG"),o.SPECULARAA&&$.addFallback(_e,"SPECULARAA"),o.POINTSIZE&&$.addFallback(_e,"POINTSIZE"),o.LOGARITHMICDEPTH&&$.addFallback(_e,"LOGARITHMICDEPTH"),o.PARALLAX&&$.addFallback(_e,"PARALLAX"),o.PARALLAXOCCLUSION&&$.addFallback(_e++,"PARALLAXOCCLUSION"),_e=PBRClearCoatConfiguration.AddFallbacks(o,$,_e),_e=PBRAnisotropicConfiguration.AddFallbacks(o,$,_e),_e=PBRSubSurfaceConfiguration.AddFallbacks(o,$,_e),_e=PBRSheenConfiguration.AddFallbacks(o,$,_e),o.ENVIRONMENTBRDF&&$.addFallback(_e++,"ENVIRONMENTBRDF"),o.TANGENT&&$.addFallback(_e++,"TANGENT"),o.BUMP&&$.addFallback(_e++,"BUMP"),_e=MaterialHelper.HandleFallbacksForShadows(o,$,this._maxSimultaneousLights,_e++),o.SPECULARTERM&&$.addFallback(_e++,"SPECULARTERM"),o.USESPHERICALFROMREFLECTIONMAP&&$.addFallback(_e++,"USESPHERICALFROMREFLECTIONMAP"),o.USEIRRADIANCEMAP&&$.addFallback(_e++,"USEIRRADIANCEMAP"),o.LIGHTMAP&&$.addFallback(_e++,"LIGHTMAP"),o.NORMAL&&$.addFallback(_e++,"NORMAL"),o.AMBIENT&&$.addFallback(_e++,"AMBIENT"),o.EMISSIVE&&$.addFallback(_e++,"EMISSIVE"),o.VERTEXCOLOR&&$.addFallback(_e++,"VERTEXCOLOR"),o.MORPHTARGETS&&$.addFallback(_e++,"MORPHTARGETS"),o.MULTIVIEW&&$.addFallback(0,"MULTIVIEW");var et=[VertexBuffer.PositionKind];o.NORMAL&&et.push(VertexBuffer.NormalKind),o.TANGENT&&et.push(VertexBuffer.TangentKind);for(var tt=1;tt<=6;++tt)o["UV"+tt]&&et.push("uv"+(tt===1?"":tt));o.VERTEXCOLOR&&et.push(VertexBuffer.ColorKind),MaterialHelper.PrepareAttributesForBones(et,e,o,$),MaterialHelper.PrepareAttributesForInstances(et,o),MaterialHelper.PrepareAttributesForMorphTargets(et,e,o),MaterialHelper.PrepareAttributesForBakedVertexAnimation(et,e,o);var rt="pbr",it=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],nt=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],ot=["Material","Scene","Mesh"];DetailMapConfiguration.AddUniforms(it),DetailMapConfiguration.AddSamplers(nt),PBRSubSurfaceConfiguration.AddUniforms(it),PBRSubSurfaceConfiguration.AddSamplers(nt),PBRClearCoatConfiguration.AddUniforms(it),PBRClearCoatConfiguration.AddSamplers(nt),PBRAnisotropicConfiguration.AddUniforms(it),PBRAnisotropicConfiguration.AddSamplers(nt),PBRSheenConfiguration.AddUniforms(it),PBRSheenConfiguration.AddSamplers(nt),PrePassConfiguration.AddUniforms(it),PrePassConfiguration.AddSamplers(nt),ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(it,o),ImageProcessingConfiguration.PrepareSamplers(nt,o)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:it,uniformBuffersNames:ot,samplers:nt,defines:o,maxSimultaneousLights:this._maxSimultaneousLights});var at={};this.customShaderNameResolve&&(rt=this.customShaderNameResolve(rt,it,ot,nt,o,et,at));var st=o.toString();return j.createEffect(rt,{attributes:et,uniformsNames:it,uniformBuffersNames:ot,samplers:nt,defines:st,fallbacks:$,onCompiled:s,onError:c,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:o.NUM_MORPH_INFLUENCERS},processFinalCode:at.processFinalCode,multiTarget:o.PREPASS},j)},i.prototype._prepareDefines=function(e,o,s,c,d){var _;s===void 0&&(s=null),c===void 0&&(c=null),d===void 0&&(d=!1);var b=this.getScene(),k=b.getEngine();MaterialHelper.PrepareDefinesForLights(b,e,o,!0,this._maxSimultaneousLights,this._disableLighting),o._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(b,o);var j=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(MaterialHelper.PrepareDefinesForPrePass(b,o,this.canRenderToMRT&&!j),MaterialHelper.PrepareDefinesForOIT(b,o,j),o.METALLICWORKFLOW=this.isMetallicWorkflow(),o._areTexturesDirty){if(o._needUVs=!1,b.texturesEnabled){b.getEngine().getCaps().textureLOD&&(o.LODBASEDMICROSFURACE=!0),this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture,o,"ALBEDO"),o.GAMMAALBEDO=this._albedoTexture.gammaSpace):o.ALBEDO=!1,this._ambientTexture&&MaterialFlags.AmbientTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,o,"AMBIENT"),o.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):o.AMBIENT=!1,this._opacityTexture&&MaterialFlags.OpacityTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,o,"OPACITY"),o.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):o.OPACITY=!1;var $=this._getReflectionTexture();if($&&MaterialFlags.ReflectionTextureEnabled){switch(o.REFLECTION=!0,o.GAMMAREFLECTION=$.gammaSpace,o.RGBDREFLECTION=$.isRGBD,o.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!$.invertZ:$.invertZ,o.LODINREFLECTIONALPHA=$.lodLevelInAlpha,o.LINEARSPECULARREFLECTION=$.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(o.NUM_SAMPLES=""+this.realTimeFilteringQuality,k._features.needTypeSuffixInShaderConstants&&(o.NUM_SAMPLES=o.NUM_SAMPLES+"u"),o.REALTIME_FILTERING=!0):o.REALTIME_FILTERING=!1,$.coordinatesMode===Texture.INVCUBIC_MODE&&(o.INVERTCUBICMAP=!0),o.REFLECTIONMAP_3D=$.isCube,o.REFLECTIONMAP_CUBIC=!1,o.REFLECTIONMAP_EXPLICIT=!1,o.REFLECTIONMAP_PLANAR=!1,o.REFLECTIONMAP_PROJECTION=!1,o.REFLECTIONMAP_SKYBOX=!1,o.REFLECTIONMAP_SPHERICAL=!1,o.REFLECTIONMAP_EQUIRECTANGULAR=!1,o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,$.coordinatesMode){case Texture.EXPLICIT_MODE:o.REFLECTIONMAP_EXPLICIT=!0;break;case Texture.PLANAR_MODE:o.REFLECTIONMAP_PLANAR=!0;break;case Texture.PROJECTION_MODE:o.REFLECTIONMAP_PROJECTION=!0;break;case Texture.SKYBOX_MODE:o.REFLECTIONMAP_SKYBOX=!0;break;case Texture.SPHERICAL_MODE:o.REFLECTIONMAP_SPHERICAL=!0;break;case Texture.EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Texture.FIXED_EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Texture.CUBIC_MODE:case Texture.INVCUBIC_MODE:default:o.REFLECTIONMAP_CUBIC=!0,o.USE_LOCAL_REFLECTIONMAP_CUBIC=!!$.boundingBoxSize;break}$.coordinatesMode!==Texture.SKYBOX_MODE&&($.irradianceTexture?(o.USEIRRADIANCEMAP=!0,o.USESPHERICALFROMREFLECTIONMAP=!1):$.isCube&&(o.USESPHERICALFROMREFLECTIONMAP=!0,o.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||b.getEngine().getCaps().maxVaryingVectors<=8?o.USESPHERICALINVERTEX=!1:o.USESPHERICALINVERTEX=!0))}else o.REFLECTION=!1,o.REFLECTIONMAP_3D=!1,o.REFLECTIONMAP_SPHERICAL=!1,o.REFLECTIONMAP_PLANAR=!1,o.REFLECTIONMAP_CUBIC=!1,o.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,o.REFLECTIONMAP_PROJECTION=!1,o.REFLECTIONMAP_SKYBOX=!1,o.REFLECTIONMAP_EXPLICIT=!1,o.REFLECTIONMAP_EQUIRECTANGULAR=!1,o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,o.INVERTCUBICMAP=!1,o.USESPHERICALFROMREFLECTIONMAP=!1,o.USEIRRADIANCEMAP=!1,o.USESPHERICALINVERTEX=!1,o.REFLECTIONMAP_OPPOSITEZ=!1,o.LODINREFLECTIONALPHA=!1,o.GAMMAREFLECTION=!1,o.RGBDREFLECTION=!1,o.LINEARSPECULARREFLECTION=!1;if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,o,"LIGHTMAP"),o.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,o.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,o.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):o.LIGHTMAP=!1,this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,o,"EMISSIVE"),o.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):o.EMISSIVE=!1,MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture?(MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture,o,"REFLECTIVITY"),o.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,o.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,o.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,o.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,o.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture,o,"REFLECTIVITY"),o.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,o.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,o.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):o.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture){var _e=this._metallicReflectanceTexture!==null&&this._metallicReflectanceTexture._texture===((_=this._reflectanceTexture)===null||_===void 0?void 0:_._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);o.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!_e,this._metallicReflectanceTexture?(MaterialHelper.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,o,"METALLIC_REFLECTANCE"),o.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):o.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!_e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(MaterialHelper.PrepareDefinesForMergedUV(this._reflectanceTexture,o,"REFLECTANCE"),o.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):o.REFLECTANCE=!1}else o.METALLIC_REFLECTANCE=!1,o.REFLECTANCE=!1;this._microSurfaceTexture?MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture,o,"MICROSURFACEMAP"):o.MICROSURFACEMAP=!1}else o.REFLECTIVITY=!1,o.MICROSURFACEMAP=!1;b.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap?(MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,o,"BUMP"),this._useParallax&&this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(o.PARALLAX=!0,o.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):o.PARALLAX=!1,o.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):o.BUMP=!1,this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled?(o.ENVIRONMENTBRDF=!0,o.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(o.ENVIRONMENTBRDF=!1,o.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?o.ALPHAFROMALBEDO=!0:o.ALPHAFROMALBEDO=!1}o.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===i.LIGHTFALLOFF_STANDARD?(o.USEPHYSICALLIGHTFALLOFF=!1,o.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===i.LIGHTFALLOFF_GLTF?(o.USEPHYSICALLIGHTFALLOFF=!1,o.USEGLTFLIGHTFALLOFF=!0):(o.USEPHYSICALLIGHTFALLOFF=!0,o.USEGLTFLIGHTFALLOFF=!1),o.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?o.TWOSIDEDLIGHTING=!0:o.TWOSIDEDLIGHTING=!1,o.SPECULARAA=b.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(o._areTexturesDirty||o._areMiscDirty)&&(o.ALPHATESTVALUE=""+this._alphaCutOff+(this._alphaCutOff%1===0?".":""),o.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,o.ALPHABLEND=this.needAlphaBlendingForMesh(e),o.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,o.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),o._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(o),o.FORCENORMALFORWARD=this._forceNormalForward,o.RADIANCEOCCLUSION=this._useRadianceOcclusion,o.HORIZONOCCLUSION=this._useHorizonOcclusion,o._areMiscDirty&&(MaterialHelper.PrepareDefinesForMisc(e,b,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,o),o.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(VertexBuffer.NormalKind),o.DEBUGMODE=this._debugMode),this.detailMap.prepareDefines(o,b),this.subSurface.prepareDefines(o,b),this.clearCoat.prepareDefines(o,b),this.anisotropy.prepareDefines(o,e,b),this.brdf.prepareDefines(o),this.sheen.prepareDefines(o,b),MaterialHelper.PrepareDefinesForFrameBoundValues(b,k,o,!!s,c,d),MaterialHelper.PrepareDefinesForAttributes(e,o,!0,!0,!0,this._transparencyMode!==i.PBRMATERIAL_OPAQUE)},i.prototype.forceCompilation=function(e,o,s){var c=this,d=__assign({clipPlane:!1,useInstances:!1},s),_=new PBRMaterialDefines,b=this._prepareEffect(e,_,void 0,void 0,d.useInstances,d.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(onCreatedEffectParameters.effect=b,onCreatedEffectParameters.subMesh=null,this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters)),b.isReady()?o&&o(this):b.onCompileObservable.add(function(){o&&o(c)})},i.prototype.buildUniformLayout=function(){var e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),PBRClearCoatConfiguration.PrepareUniformBuffer(e),PBRAnisotropicConfiguration.PrepareUniformBuffer(e),PBRSheenConfiguration.PrepareUniformBuffer(e),PBRSubSurfaceConfiguration.PrepareUniformBuffer(e),DetailMapConfiguration.PrepareUniformBuffer(e),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),e.create()},i.prototype.unbind=function(){if(this._activeEffect&&!this.getScene().getEngine()._features.needToAlwaysBindUniformBuffers){var e=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),e=!0),this.subSurface.unbind(this._activeEffect)&&(e=!0),e&&this._markAllSubMeshesAsTexturesDirty()}a.prototype.unbind.call(this)},i.prototype.bindForSubMesh=function(e,o,s){var c,d=this.getScene(),_=s.materialDefines;if(!!_){var b=s.effect;if(!!b){this._activeEffect=b,o.getMeshUniformBuffer().bindToEffect(b,"Mesh"),o.transferToEffect(e);var k=d.getEngine();this._uniformBuffer.bindToEffect(b,"Material"),this.subSurface.hardBindForSubMesh(this._uniformBuffer,d,k,this.isFrozen,_.LODBASEDMICROSFURACE,this.realTimeFiltering,s),this.prePassConfiguration.bindForSubMesh(this._activeEffect,d,o,e,this.isFrozen),_.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var j=this._mustRebind(d,b,o.visibility);MaterialHelper.BindBonesParameters(o,this._activeEffect,this.prePassConfiguration);var $=null,_e=this._uniformBuffer;if(j){if(this.bindViewProjection(b),$=this._getReflectionTexture(),!_e.useUbo||!this.isFrozen||!_e.isSync){if(d.texturesEnabled){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&(_e.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),MaterialHelper.BindTextureMatrix(this._albedoTexture,_e,"albedo")),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&(_e.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),MaterialHelper.BindTextureMatrix(this._ambientTexture,_e,"ambient")),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&(_e.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),MaterialHelper.BindTextureMatrix(this._opacityTexture,_e,"opacity")),$&&MaterialFlags.ReflectionTextureEnabled){if(_e.updateMatrix("reflectionMatrix",$.getReflectionTextureMatrix()),_e.updateFloat2("vReflectionInfos",$.level,0),$.boundingBoxSize){var et=$;_e.updateVector3("vReflectionPosition",et.boundingBoxPosition),_e.updateVector3("vReflectionSize",et.boundingBoxSize)}if(this.realTimeFiltering){var tt=$.getSize().width;_e.updateFloat2("vReflectionFilteringInfo",tt,Scalar.Log2(tt))}if(!_.USEIRRADIANCEMAP){var rt=$.sphericalPolynomial;if(_.USESPHERICALFROMREFLECTIONMAP&&rt)if(_.SPHERICAL_HARMONICS){var it=rt.preScaledHarmonics;_e.updateVector3("vSphericalL00",it.l00),_e.updateVector3("vSphericalL1_1",it.l1_1),_e.updateVector3("vSphericalL10",it.l10),_e.updateVector3("vSphericalL11",it.l11),_e.updateVector3("vSphericalL2_2",it.l2_2),_e.updateVector3("vSphericalL2_1",it.l2_1),_e.updateVector3("vSphericalL20",it.l20),_e.updateVector3("vSphericalL21",it.l21),_e.updateVector3("vSphericalL22",it.l22)}else _e.updateFloat3("vSphericalX",rt.x.x,rt.x.y,rt.x.z),_e.updateFloat3("vSphericalY",rt.y.x,rt.y.y,rt.y.z),_e.updateFloat3("vSphericalZ",rt.z.x,rt.z.y,rt.z.z),_e.updateFloat3("vSphericalXX_ZZ",rt.xx.x-rt.zz.x,rt.xx.y-rt.zz.y,rt.xx.z-rt.zz.z),_e.updateFloat3("vSphericalYY_ZZ",rt.yy.x-rt.zz.x,rt.yy.y-rt.zz.y,rt.yy.z-rt.zz.z),_e.updateFloat3("vSphericalZZ",rt.zz.x,rt.zz.y,rt.zz.z),_e.updateFloat3("vSphericalXY",rt.xy.x,rt.xy.y,rt.xy.z),_e.updateFloat3("vSphericalYZ",rt.yz.x,rt.yz.y,rt.yz.z),_e.updateFloat3("vSphericalZX",rt.zx.x,rt.zx.y,rt.zx.z)}_e.updateFloat3("vReflectionMicrosurfaceInfos",$.getSize().width,$.lodGenerationScale,$.lodGenerationOffset)}this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&(_e.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),MaterialHelper.BindTextureMatrix(this._emissiveTexture,_e,"emissive")),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&(_e.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),MaterialHelper.BindTextureMatrix(this._lightmapTexture,_e,"lightmap")),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?(_e.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),MaterialHelper.BindTextureMatrix(this._metallicTexture,_e,"reflectivity")):this._reflectivityTexture&&(_e.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),MaterialHelper.BindTextureMatrix(this._reflectivityTexture,_e,"reflectivity")),this._metallicReflectanceTexture&&(_e.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture,_e,"metallicReflectance")),this._reflectanceTexture&&_.REFLECTANCE&&(_e.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),MaterialHelper.BindTextureMatrix(this._reflectanceTexture,_e,"reflectance")),this._microSurfaceTexture&&(_e.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),MaterialHelper.BindTextureMatrix(this._microSurfaceTexture,_e,"microSurfaceSampler"))),this._bumpTexture&&k.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&(_e.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),MaterialHelper.BindTextureMatrix(this._bumpTexture,_e,"bump"),d._mirroredCameraPosition?_e.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):_e.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&_e.updateFloat("pointSize",this.pointSize),_.METALLICWORKFLOW){TmpColors.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,TmpColors.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,_e.updateColor4("vReflectivityColor",TmpColors.Color3[0],1);var nt=this.subSurface.indexOfRefraction,ot=1,at=Math.pow((nt-ot)/(nt+ot),2);this._metallicReflectanceColor.scaleToRef(at*this._metallicF0Factor,TmpColors.Color3[0]);var st=this._metallicF0Factor;_e.updateColor4("vMetallicReflectanceFactors",TmpColors.Color3[0],st)}else _e.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);_e.updateColor3("vEmissiveColor",MaterialFlags.EmissiveTextureEnabled?this._emissiveColor:Color3.BlackReadOnly),_e.updateColor3("vReflectionColor",this._reflectionColor),!_.SS_REFRACTION&&this.subSurface.linkRefractionWithTransparency?_e.updateColor4("vAlbedoColor",this._albedoColor,1):_e.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*d.environmentIntensity,this._lightingInfos.w=this._specularIntensity,_e.updateVector4("vLightingIntensity",this._lightingInfos),d.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),_e.updateColor3("vAmbientColor",this._globalAmbientColor),_e.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}d.texturesEnabled&&(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&_e.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&_e.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&_e.setTexture("opacitySampler",this._opacityTexture),$&&MaterialFlags.ReflectionTextureEnabled&&(_.LODBASEDMICROSFURACE?_e.setTexture("reflectionSampler",$):(_e.setTexture("reflectionSampler",$._lodTextureMid||$),_e.setTexture("reflectionSamplerLow",$._lodTextureLow||$),_e.setTexture("reflectionSamplerHigh",$._lodTextureHigh||$)),_.USEIRRADIANCEMAP&&_e.setTexture("irradianceSampler",$.irradianceTexture)),_.ENVIRONMENTBRDF&&_e.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&_e.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&_e.setTexture("lightmapSampler",this._lightmapTexture),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?_e.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&_e.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&_e.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&_.REFLECTANCE&&_e.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&_e.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&k.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&_e.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(o)&&this.getScene().depthPeelingRenderer.bind(b),this.detailMap.bindForSubMesh(_e,d,this.isFrozen),this.subSurface.bindForSubMesh(_e,d,k,this.isFrozen,_.LODBASEDMICROSFURACE,this.realTimeFiltering,s),this.clearCoat.bindForSubMesh(_e,d,k,this._disableBumpMap,this.isFrozen,this._invertNormalMapX,this._invertNormalMapY,s),this.anisotropy.bindForSubMesh(_e,d,this.isFrozen),this.sheen.bindForSubMesh(_e,d,this.isFrozen,s),MaterialHelper.BindClipPlane(this._activeEffect,d),this.bindEyePosition(b)}else d.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(j||!this.isFrozen)&&(d.lightsEnabled&&!this._disableLighting&&MaterialHelper.BindLights(d,o,this._activeEffect,_,this._maxSimultaneousLights),(d.fogEnabled&&o.applyFog&&d.fogMode!==Scene.FOGMODE_NONE||$||o.receiveShadows)&&this.bindView(b),MaterialHelper.BindFogParameters(d,o,this._activeEffect,!0),_.NUM_MORPH_INFLUENCERS&&MaterialHelper.BindMorphTargetParameters(o,this._activeEffect),_.BAKED_VERTEX_ANIMATION_TEXTURE&&((c=o.bakedVertexAnimationManager)===null||c===void 0||c.bind(b,_.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),MaterialHelper.BindLogDepth(_,this._activeEffect,d)),this._afterBind(o,this._activeEffect),_e.update()}}},i.prototype.getAnimatables=function(){var e=[];return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this.detailMap.getAnimatables(e),this.subSurface.getAnimatables(e),this.clearCoat.getAnimatables(e),this.sheen.getAnimatables(e),this.anisotropy.getAnimatables(e),e},i.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},i.prototype.getActiveTextures=function(){var e=a.prototype.getActiveTextures.call(this);return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this.detailMap.getActiveTextures(e),this.subSurface.getActiveTextures(e),this.clearCoat.getActiveTextures(e),this.sheen.getActiveTextures(e),this.anisotropy.getActiveTextures(e),e},i.prototype.hasTexture=function(e){return a.prototype.hasTexture.call(this,e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e?!0:this.detailMap.hasTexture(e)||this.subSurface.hasTexture(e)||this.clearCoat.hasTexture(e)||this.sheen.hasTexture(e)||this.anisotropy.hasTexture(e)},i.prototype.setPrePassRenderer=function(e){if(this.subSurface.isScatteringEnabled){var o=this.getScene().enableSubSurfaceForPrePass();return o&&(o.enabled=!0),!0}return!1},i.prototype.dispose=function(e,o){var s,c,d,_,b,k,j,$,_e,et,tt,rt;o&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(s=this._albedoTexture)===null||s===void 0||s.dispose(),(c=this._ambientTexture)===null||c===void 0||c.dispose(),(d=this._opacityTexture)===null||d===void 0||d.dispose(),(_=this._reflectionTexture)===null||_===void 0||_.dispose(),(b=this._emissiveTexture)===null||b===void 0||b.dispose(),(k=this._metallicTexture)===null||k===void 0||k.dispose(),(j=this._reflectivityTexture)===null||j===void 0||j.dispose(),($=this._bumpTexture)===null||$===void 0||$.dispose(),(_e=this._lightmapTexture)===null||_e===void 0||_e.dispose(),(et=this._metallicReflectanceTexture)===null||et===void 0||et.dispose(),(tt=this._reflectanceTexture)===null||tt===void 0||tt.dispose(),(rt=this._microSurfaceTexture)===null||rt===void 0||rt.dispose()),this.detailMap.dispose(o),this.subSurface.dispose(o),this.clearCoat.dispose(o),this.sheen.dispose(o),this.anisotropy.dispose(o),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),a.prototype.dispose.call(this,e,o)},i.PBRMATERIAL_OPAQUE=Material.MATERIAL_OPAQUE,i.PBRMATERIAL_ALPHATEST=Material.MATERIAL_ALPHATEST,i.PBRMATERIAL_ALPHABLEND=Material.MATERIAL_ALPHABLEND,i.PBRMATERIAL_ALPHATESTANDBLEND=Material.MATERIAL_ALPHATESTANDBLEND,i.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,i.LIGHTFALLOFF_PHYSICAL=0,i.LIGHTFALLOFF_GLTF=1,i.LIGHTFALLOFF_STANDARD=2,__decorate([serializeAsImageProcessingConfiguration()],i.prototype,"_imageProcessingConfiguration",void 0),__decorate([expandToProperty("_markAllSubMeshesAsMiscDirty")],i.prototype,"debugMode",void 0),__decorate([serialize()],i.prototype,"useLogarithmicDepth",null),i}(PushMaterial),SheenBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.albedoScaling=!1,o.linkSheenWithAlbedo=!1,o._isUnique=!0,o.registerInput("intensity",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("color",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("roughness",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerOutput("sheen",NodeMaterialBlockConnectionPointTypes.Object,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",o,NodeMaterialConnectionPointDirection.Output,i,"SheenBlock")),o}return i.prototype.initialize=function(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")},i.prototype.getClassName=function(){return"SheenBlock"},Object.defineProperty(i.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"color",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"roughness",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sheen",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.prepareDefines=function(e,o,s){a.prototype.prepareDefines.call(this,e,o,s),s.setValue("SHEEN",!0),s.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),s.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),s.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),s.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)},i.prototype.getCode=function(e){var o="",s=this.color.isConnected?this.color.associatedVariableName:"vec3(1.)",c=this.intensity.isConnected?this.intensity.associatedVariableName:"1.",d=this.roughness.isConnected?this.roughness.associatedVariableName:"0.",_="vec4(0.)";return o=`#ifdef SHEEN
  8853. sheenOutParams sheenOut;
  8854. vec4 vSheenColor = vec4(`+s+", "+c+`);
  8855. sheenBlock(
  8856. vSheenColor,
  8857. #ifdef SHEEN_ROUGHNESS
  8858. `+d+`,
  8859. #endif
  8860. roughness,
  8861. #ifdef SHEEN_TEXTURE
  8862. `+_+`,
  8863. 1.0,
  8864. #endif
  8865. reflectance,
  8866. #ifdef SHEEN_LINKWITHALBEDO
  8867. baseColor,
  8868. surfaceAlbedo,
  8869. #endif
  8870. #ifdef ENVIRONMENTBRDF
  8871. NdotV,
  8872. environmentBrdf,
  8873. #endif
  8874. #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
  8875. AARoughnessFactors,
  8876. `+(e==null?void 0:e._vReflectionMicrosurfaceInfosName)+`,
  8877. `+(e==null?void 0:e._vReflectionInfosName)+`,
  8878. `+(e==null?void 0:e.reflectionColor)+`,
  8879. vLightingIntensity,
  8880. #ifdef `+(e==null?void 0:e._define3DName)+`
  8881. `+(e==null?void 0:e._cubeSamplerName)+`,
  8882. #else
  8883. `+(e==null?void 0:e._2DSamplerName)+`,
  8884. #endif
  8885. reflectionOut.reflectionCoords,
  8886. NdotVUnclamped,
  8887. #ifndef LODBASEDMICROSFURACE
  8888. #ifdef `+(e==null?void 0:e._define3DName)+`
  8889. `+(e==null?void 0:e._cubeSamplerName)+`,
  8890. `+(e==null?void 0:e._cubeSamplerName)+`,
  8891. #else
  8892. `+(e==null?void 0:e._2DSamplerName)+`,
  8893. `+(e==null?void 0:e._2DSamplerName)+`,
  8894. #endif
  8895. #endif
  8896. #if !defined(`+(e==null?void 0:e._defineSkyboxName)+`) && defined(RADIANCEOCCLUSION)
  8897. seo,
  8898. #endif
  8899. #if !defined(`+(e==null?void 0:e._defineSkyboxName)+") && defined(HORIZONOCCLUSION) && defined(BUMP) && defined("+(e==null?void 0:e._define3DName)+`)
  8900. eho,
  8901. #endif
  8902. #endif
  8903. sheenOut
  8904. );
  8905. #ifdef SHEEN_LINKWITHALBEDO
  8906. surfaceAlbedo = sheenOut.surfaceAlbedo;
  8907. #endif
  8908. #endif\r
  8909. `,o},i.prototype._buildBlock=function(e){return e.target===NodeMaterialBlockTargets.Fragment&&e.sharedData.blocksWithDefines.push(this),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".albedoScaling = "+this.albedoScaling+`;\r
  8910. `,e+=this._codeVariableName+".linkSheenWithAlbedo = "+this.linkSheenWithAlbedo+`;\r
  8911. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.albedoScaling=this.albedoScaling,e.linkSheenWithAlbedo=this.linkSheenWithAlbedo,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.albedoScaling=e.albedoScaling,this.linkSheenWithAlbedo=e.linkSheenWithAlbedo},__decorate([editableInPropertyPage("Albedo scaling",PropertyTypeForEdition.Boolean,"PROPERTIES",{notifiers:{update:!0}})],i.prototype,"albedoScaling",void 0),__decorate([editableInPropertyPage("Link sheen with albedo",PropertyTypeForEdition.Boolean,"PROPERTIES",{notifiers:{update:!0}})],i.prototype,"linkSheenWithAlbedo",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.SheenBlock",SheenBlock);var AnisotropyBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o._isUnique=!0,o.registerInput("intensity",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("direction",NodeMaterialBlockConnectionPointTypes.Vector2,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2,!0),o.registerInput("worldTangent",NodeMaterialBlockConnectionPointTypes.Vector4,!0),o.registerOutput("anisotropy",NodeMaterialBlockConnectionPointTypes.Object,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",o,NodeMaterialConnectionPointDirection.Output,i,"AnisotropyBlock")),o}return i.prototype.initialize=function(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")},i.prototype.getClassName=function(){return"AnisotropyBlock"},Object.defineProperty(i.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"direction",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldTangent",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"anisotropy",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._generateTBNSpace=function(e){var o="",s="//"+this.name,c=this.uv,d=this.worldPositionConnectionPoint,_=this.worldNormalConnectionPoint,b=this.worldTangent;c.isConnected||console.error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var k={search:/defined\(TANGENT\)/g,replace:b.isConnected?"defined(TANGENT)":"defined(IGNORE)"};return b.isConnected&&(o+="vec3 tbnNormal = normalize("+_.associatedVariableName+`.xyz);\r
  8912. `,o+="vec3 tbnTangent = normalize("+b.associatedVariableName+`.xyz);\r
  8913. `,o+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
  8914. `,o+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
  8915. `),o+=`
  8916. #if defined(`+(b.isConnected?"TANGENT":"IGNORE")+`) && defined(NORMAL)
  8917. mat3 TBN = vTBN;
  8918. #else
  8919. mat3 TBN = cotangent_frame(`+(_.associatedVariableName+".xyz")+", "+("v_"+d.associatedVariableName+".xyz")+", "+(c.isConnected?c.associatedVariableName:"vec2(0.)")+`, vec2(1., 1.));
  8920. #endif\r
  8921. `,e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[k]}),o},i.prototype.getCode=function(e,o){o===void 0&&(o=!1);var s="";o&&(s+=this._generateTBNSpace(e));var c=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0",d=this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)";return s+=`anisotropicOutParams anisotropicOut;
  8922. anisotropicBlock(
  8923. vec3(`+d+", "+c+`),
  8924. #ifdef ANISOTROPIC_TEXTURE
  8925. vec3(0.),
  8926. #endif
  8927. TBN,
  8928. normalW,
  8929. viewDirectionW,
  8930. anisotropicOut
  8931. );\r
  8932. `,s},i.prototype.prepareDefines=function(e,o,s){a.prototype.prepareDefines.call(this,e,o,s),s.setValue("ANISOTROPIC",!0),s.setValue("ANISOTROPIC_TEXTURE",!1,!0)},i.prototype._buildBlock=function(e){return e.target===NodeMaterialBlockTargets.Fragment&&e.sharedData.blocksWithDefines.push(this),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.AnisotropyBlock",AnisotropyBlock);var ReflectionBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e)||this;return o.useSphericalHarmonics=!0,o.forceIrradianceInFragment=!1,o._isUnique=!0,o.registerInput("position",NodeMaterialBlockConnectionPointTypes.Vector3,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("world",NodeMaterialBlockConnectionPointTypes.Matrix,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("color",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerOutput("reflection",NodeMaterialBlockConnectionPointTypes.Object,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",o,NodeMaterialConnectionPointDirection.Output,i,"ReflectionBlock")),o}return i.prototype.getClassName=function(){return"ReflectionBlock"},Object.defineProperty(i.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this.worldPositionConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldNormal",{get:function(){return this.worldNormalConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"world",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraPosition",{get:function(){return this.cameraPositionConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"view",{get:function(){return this.viewConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"color",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"reflection",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasTexture",{get:function(){return!!this._getTexture()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"reflectionColor",{get:function(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"},enumerable:!1,configurable:!0}),i.prototype._getTexture=function(){return this.texture?this.texture:this._scene.environmentTexture},i.prototype.prepareDefines=function(e,o,s){a.prototype.prepareDefines.call(this,e,o,s);var c=this._getTexture(),d=c&&c.getTextureMatrix;s.setValue("REFLECTION",d,!0),d&&(s.setValue(this._defineLODReflectionAlpha,c.lodLevelInAlpha,!0),s.setValue(this._defineLinearSpecularReflection,c.linearSpecularLOD,!0),s.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!c.invertZ:c.invertZ,!0),s.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),s.setValue("GAMMAREFLECTION",c.gammaSpace,!0),s.setValue("RGBDREFLECTION",c.isRGBD,!0),c&&c.coordinatesMode!==Texture.SKYBOX_MODE&&c.isCube&&(s.setValue("USESPHERICALFROMREFLECTIONMAP",!0),s.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?s.setValue("USESPHERICALINVERTEX",!1):s.setValue("USESPHERICALINVERTEX",!0)))},i.prototype.bind=function(e,o,s,c){a.prototype.bind.call(this,e,o,s);var d=this._getTexture();if(!(!d||!c)){d.isCube?e.setTexture(this._cubeSamplerName,d):e.setTexture(this._2DSamplerName,d);var _=d.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,_,d.lodGenerationScale,d.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,_,Scalar.Log2(_));var b=c.materialDefines,k=d.sphericalPolynomial;if(b.USESPHERICALFROMREFLECTIONMAP&&k)if(b.SPHERICAL_HARMONICS){var j=k.preScaledHarmonics;e.setVector3("vSphericalL00",j.l00),e.setVector3("vSphericalL1_1",j.l1_1),e.setVector3("vSphericalL10",j.l10),e.setVector3("vSphericalL11",j.l11),e.setVector3("vSphericalL2_2",j.l2_2),e.setVector3("vSphericalL2_1",j.l2_1),e.setVector3("vSphericalL20",j.l20),e.setVector3("vSphericalL21",j.l21),e.setVector3("vSphericalL22",j.l22)}else e.setFloat3("vSphericalX",k.x.x,k.x.y,k.x.z),e.setFloat3("vSphericalY",k.y.x,k.y.y,k.y.z),e.setFloat3("vSphericalZ",k.z.x,k.z.y,k.z.z),e.setFloat3("vSphericalXX_ZZ",k.xx.x-k.zz.x,k.xx.y-k.zz.y,k.xx.z-k.zz.z),e.setFloat3("vSphericalYY_ZZ",k.yy.x-k.zz.x,k.yy.y-k.zz.y,k.yy.z-k.zz.z),e.setFloat3("vSphericalZZ",k.zz.x,k.zz.y,k.zz.z),e.setFloat3("vSphericalXY",k.xy.x,k.xy.y,k.xy.z),e.setFloat3("vSphericalYZ",k.yz.x,k.yz.y,k.yz.z),e.setFloat3("vSphericalZX",k.zx.x,k.zx.y,k.zx.z)}},i.prototype.handleVertexSide=function(e){var o=a.prototype.handleVertexSide.call(this,e);e._emitFunctionFromInclude("harmonicsFunctions","//"+this.name,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});var s=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),o+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
  8933. vec3 `+s+" = vec3("+this._reflectionMatrixName+" * vec4(normalize("+this.worldNormal.associatedVariableName+`).xyz, 0)).xyz;
  8934. #ifdef `+this._defineOppositeZ+`
  8935. `+s+`.z *= -1.0;
  8936. #endif
  8937. `+this._vEnvironmentIrradianceName+" = computeEnvironmentIrradiance("+s+`);
  8938. #endif\r
  8939. `,o},i.prototype.getCode=function(e,o){var s="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions","//"+this.name,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",`
  8940. #ifdef `+this._define3DName+`
  8941. #define sampleReflection(s, c) textureCube(s, c)
  8942. #else
  8943. #define sampleReflection(s, c) texture2D(s, c)
  8944. #endif\r
  8945. `,"//"+this.name),e._emitFunction("sampleReflectionLod",`
  8946. #ifdef `+this._define3DName+`
  8947. #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)
  8948. #else
  8949. #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)
  8950. #endif\r
  8951. `,"//"+this.name);var c=`
  8952. vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {
  8953. `+this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0)+`
  8954. return `+this._reflectionVectorName+`;
  8955. }\r
  8956. `;return e._emitFunction("computeReflectionCoordsPBR",c,"//"+this.name),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),s+=`#ifdef REFLECTION
  8957. vec2 `+this._vReflectionInfosName+` = vec2(1., 0.);
  8958. reflectionOutParams reflectionOut;
  8959. reflectionBlock(
  8960. `+("v_"+this.worldPosition.associatedVariableName+".xyz")+`,
  8961. `+o+`,
  8962. alphaG,
  8963. `+this._vReflectionMicrosurfaceInfosName+`,
  8964. `+this._vReflectionInfosName+`,
  8965. `+this.reflectionColor+`,
  8966. #ifdef ANISOTROPIC
  8967. anisotropicOut,
  8968. #endif
  8969. #if defined(`+this._defineLODReflectionAlpha+") && !defined("+this._defineSkyboxName+`)
  8970. NdotVUnclamped,
  8971. #endif
  8972. #ifdef `+this._defineLinearSpecularReflection+`
  8973. roughness,
  8974. #endif
  8975. #ifdef `+this._define3DName+`
  8976. `+this._cubeSamplerName+`,
  8977. #else
  8978. `+this._2DSamplerName+`,
  8979. #endif
  8980. #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
  8981. `+this._vEnvironmentIrradianceName+`,
  8982. #endif
  8983. #ifdef USESPHERICALFROMREFLECTIONMAP
  8984. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  8985. `+this._reflectionMatrixName+`,
  8986. #endif
  8987. #endif
  8988. #ifdef USEIRRADIANCEMAP
  8989. irradianceSampler, // ** not handled **
  8990. #endif
  8991. #ifndef LODBASEDMICROSFURACE
  8992. #ifdef `+this._define3DName+`
  8993. `+this._cubeSamplerName+`,
  8994. `+this._cubeSamplerName+`,
  8995. #else
  8996. `+this._2DSamplerName+`,
  8997. `+this._2DSamplerName+`,
  8998. #endif
  8999. #endif
  9000. #ifdef REALTIME_FILTERING
  9001. `+this._vReflectionFilteringInfoName+`,
  9002. #endif
  9003. reflectionOut
  9004. );
  9005. #endif\r
  9006. `,s},i.prototype._buildBlock=function(e){return this._scene=e.sharedData.scene,e.target!==NodeMaterialBlockTargets.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return this.texture&&(e+=this._codeVariableName+".texture.gammaSpace = "+this.texture.gammaSpace+`;\r
  9007. `),e+=this._codeVariableName+".useSphericalHarmonics = "+this.useSphericalHarmonics+`;\r
  9008. `,e+=this._codeVariableName+".forceIrradianceInFragment = "+this.forceIrradianceInFragment+`;\r
  9009. `,e},i.prototype.serialize=function(){var e,o,s=a.prototype.serialize.call(this);return s.useSphericalHarmonics=this.useSphericalHarmonics,s.forceIrradianceInFragment=this.forceIrradianceInFragment,s.gammaSpace=(o=(e=this.texture)===null||e===void 0?void 0:e.gammaSpace)!==null&&o!==void 0?o:!0,s},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)},__decorate([editableInPropertyPage("Spherical Harmonics",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"useSphericalHarmonics",void 0),__decorate([editableInPropertyPage("Force irradiance in fragment",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"forceIrradianceInFragment",void 0),i}(ReflectionTextureBaseBlock);RegisterClass("BABYLON.ReflectionBlock",ReflectionBlock);var ClearCoatBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.remapF0OnInterfaceChange=!0,o._isUnique=!0,o.registerInput("intensity",NodeMaterialBlockConnectionPointTypes.Float,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("roughness",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("indexOfRefraction",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("normalMapColor",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("uv",NodeMaterialBlockConnectionPointTypes.Vector2,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("tintColor",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("tintAtDistance",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("tintThickness",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("worldTangent",NodeMaterialBlockConnectionPointTypes.Vector4,!0),o.registerOutput("clearcoat",NodeMaterialBlockConnectionPointTypes.Object,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",o,NodeMaterialConnectionPointDirection.Output,i,"ClearCoatBlock")),o}return i.prototype.initialize=function(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams")},i.prototype.getClassName=function(){return"ClearCoatBlock"},Object.defineProperty(i.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"roughness",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"indexOfRefraction",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"normalMapColor",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"uv",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tintColor",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tintAtDistance",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tintThickness",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldTangent",{get:function(){return this._inputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"clearcoat",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.intensity.isConnected){var o=new InputBlock("ClearCoat intensity",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);o.value=1,o.output.connectTo(this.intensity)}},i.prototype.prepareDefines=function(e,o,s){a.prototype.prepareDefines.call(this,e,o,s),s.setValue("CLEARCOAT",!0),s.setValue("CLEARCOAT_TEXTURE",!1,!0),s.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),s.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),s.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),s.setValue("CLEARCOAT_DEFAULTIOR",this.indexOfRefraction.isConnected?this.indexOfRefraction.connectInputBlock.value===PBRClearCoatConfiguration._DefaultIndexOfRefraction:!0,!0),s.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)},i.prototype.bind=function(e,o,s,c){var d,_;a.prototype.bind.call(this,e,o,s);var b=(_=(d=this.indexOfRefraction.connectInputBlock)===null||d===void 0?void 0:d.value)!==null&&_!==void 0?_:PBRClearCoatConfiguration._DefaultIndexOfRefraction,k=1-b,j=1+b,$=Math.pow(-k/j,2),_e=1/b;e.setFloat4("vClearCoatRefractionParams",$,_e,k,j);var et=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,tt=et!=null&&et.perturbedNormal.isConnected?et.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",tt!=null&&tt.invertX?1:-1,tt!=null&&tt.invertY?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",tt!=null&&tt.invertX?-1:1,tt!=null&&tt.invertY?-1:1)},i.prototype._generateTBNSpace=function(e,o,s){var c="",d="//"+this.name,_=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var b={search:/defined\(TANGENT\)/g,replace:_.isConnected?"defined(TANGENT)":"defined(IGNORE)"};return _.isConnected&&(c+="vec3 tbnNormal = normalize("+s+`.xyz);\r
  9010. `,c+="vec3 tbnTangent = normalize("+_.associatedVariableName+`.xyz);\r
  9011. `,c+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
  9012. `,c+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
  9013. `),e._emitFunctionFromInclude("bumpFragmentMainFunctions",d,{replaceStrings:[b]}),c},i.GetCode=function(e,o,s,c,d,_,b){var k="",j=o!=null&&o.intensity.isConnected?o.intensity.associatedVariableName:"1.",$=o!=null&&o.roughness.isConnected?o.roughness.associatedVariableName:"0.",_e=o!=null&&o.normalMapColor.isConnected?o.normalMapColor.associatedVariableName:"vec3(0.)",et=o!=null&&o.uv.isConnected?o.uv.associatedVariableName:"vec2(0.)",tt=o!=null&&o.tintColor.isConnected?o.tintColor.associatedVariableName:"vec3(1.)",rt=o!=null&&o.tintThickness.isConnected?o.tintThickness.associatedVariableName:"1.",it=o!=null&&o.tintAtDistance.isConnected?o.tintAtDistance.associatedVariableName:"1.",nt="vec4(0.)";return o&&(e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2")),d&&o&&(k+=o._generateTBNSpace(e,c,b),_=o.worldTangent.isConnected),k+=`clearcoatOutParams clearcoatOut;
  9014. #ifdef CLEARCOAT
  9015. vec2 vClearCoatParams = vec2(`+j+", "+$+`);
  9016. vec4 vClearCoatTintParams = vec4(`+tt+", "+rt+`);
  9017. clearcoatBlock(
  9018. `+c+`.xyz,
  9019. geometricNormalW,
  9020. viewDirectionW,
  9021. vClearCoatParams,
  9022. specularEnvironmentR0,
  9023. #ifdef CLEARCOAT_TEXTURE
  9024. vec2(0.),
  9025. #endif
  9026. #ifdef CLEARCOAT_TINT
  9027. vClearCoatTintParams,
  9028. `+it+`,
  9029. vClearCoatRefractionParams,
  9030. #ifdef CLEARCOAT_TINT_TEXTURE
  9031. `+nt+`,
  9032. #endif
  9033. #endif
  9034. #ifdef CLEARCOAT_BUMP
  9035. vec2(0., 1.),
  9036. vec4(`+_e+`, 0.),
  9037. `+et+`,
  9038. #if defined(`+(_?"TANGENT":"IGNORE")+`) && defined(NORMAL)
  9039. vTBN,
  9040. #else
  9041. vClearCoatTangentSpaceParams,
  9042. #endif
  9043. #ifdef OBJECTSPACE_NORMALMAP
  9044. normalMatrix,
  9045. #endif
  9046. #endif
  9047. #if defined(FORCENORMALFORWARD) && defined(NORMAL)
  9048. faceNormal,
  9049. #endif
  9050. #ifdef REFLECTION
  9051. `+(s==null?void 0:s._vReflectionMicrosurfaceInfosName)+`,
  9052. `+(s==null?void 0:s._vReflectionInfosName)+`,
  9053. `+(s==null?void 0:s.reflectionColor)+`,
  9054. vLightingIntensity,
  9055. #ifdef `+(s==null?void 0:s._define3DName)+`
  9056. `+(s==null?void 0:s._cubeSamplerName)+`,
  9057. #else
  9058. `+(s==null?void 0:s._2DSamplerName)+`,
  9059. #endif
  9060. #ifndef LODBASEDMICROSFURACE
  9061. #ifdef `+(s==null?void 0:s._define3DName)+`
  9062. `+(s==null?void 0:s._cubeSamplerName)+`,
  9063. `+(s==null?void 0:s._cubeSamplerName)+`,
  9064. #else
  9065. `+(s==null?void 0:s._2DSamplerName)+`,
  9066. `+(s==null?void 0:s._2DSamplerName)+`,
  9067. #endif
  9068. #endif
  9069. #endif
  9070. #if defined(ENVIRONMENTBRDF) && !defined(`+(s==null?void 0:s._defineSkyboxName)+`)
  9071. #ifdef RADIANCEOCCLUSION
  9072. ambientMonochrome,
  9073. #endif
  9074. #endif
  9075. #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
  9076. (gl_FrontFacing ? 1. : -1.),
  9077. #endif
  9078. clearcoatOut
  9079. );
  9080. #else
  9081. clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;
  9082. #endif\r
  9083. `,k},i.prototype._buildBlock=function(e){return this._scene=e.sharedData.scene,e.target===NodeMaterialBlockTargets.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".remapF0OnInterfaceChange = "+this.remapF0OnInterfaceChange+`;\r
  9084. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e},i.prototype._deserialize=function(e,o,s){var c;a.prototype._deserialize.call(this,e,o,s),this.remapF0OnInterfaceChange=(c=e.remapF0OnInterfaceChange)!==null&&c!==void 0?c:!0},__decorate([editableInPropertyPage("Remap F0 on interface change",PropertyTypeForEdition.Boolean,"ADVANCED")],i.prototype,"remapF0OnInterfaceChange",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.ClearCoatBlock",ClearCoatBlock);var RefractionBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o.linkRefractionWithTransparency=!1,o.invertRefractionY=!1,o.useThicknessAsDepth=!1,o._isUnique=!0,o.registerInput("intensity",NodeMaterialBlockConnectionPointTypes.Float,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("tintAtDistance",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("volumeIndexOfRefraction",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerOutput("refraction",NodeMaterialBlockConnectionPointTypes.Object,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",o,NodeMaterialConnectionPointDirection.Output,i,"RefractionBlock")),o}return i.prototype.initialize=function(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")},i.prototype.getClassName=function(){return"RefractionBlock"},Object.defineProperty(i.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tintAtDistance",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"volumeIndexOfRefraction",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"view",{get:function(){return this.viewConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"refraction",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasTexture",{get:function(){return!!this._getTexture()},enumerable:!1,configurable:!0}),i.prototype._getTexture=function(){return this.texture?this.texture:this._scene.environmentTexture},i.prototype.autoConfigure=function(e){if(!this.intensity.isConnected){var o=new InputBlock("Refraction intensity",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);o.value=1,o.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){var s=e.getInputBlockByPredicate(function(c){return c.systemValue===NodeMaterialSystemValues.View});s||(s=new InputBlock("view"),s.setAsSystemValue(NodeMaterialSystemValues.View)),s.output.connectTo(this.view)}},i.prototype.prepareDefines=function(e,o,s){a.prototype.prepareDefines.call(this,e,o,s);var c=this._getTexture(),d=c&&c.getTextureMatrix;s.setValue("SS_REFRACTION",d,!0),d&&(s.setValue(this._define3DName,c.isCube,!0),s.setValue(this._defineLODRefractionAlpha,c.lodLevelInAlpha,!0),s.setValue(this._defineLinearSpecularRefraction,c.linearSpecularLOD,!0),s.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!c.invertZ:c.invertZ,!0),s.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),s.setValue("SS_GAMMAREFRACTION",c.gammaSpace,!0),s.setValue("SS_RGBDREFRACTION",c.isRGBD,!0),s.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!c.boundingBoxSize,!0),s.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))},i.prototype.isReady=function(){var e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())},i.prototype.bind=function(e,o,s,c){var d,_,b,k;a.prototype.bind.call(this,e,o,s);var j=this._getTexture();if(!!j){j.isCube?e.setTexture(this._cubeSamplerName,j):e.setTexture(this._2DSamplerName,j),e.setMatrix(this._refractionMatrixName,j.getReflectionTextureMatrix());var $=1;j.isCube||j.depth&&($=j.depth);var _e=(k=(_=(d=this.volumeIndexOfRefraction.connectInputBlock)===null||d===void 0?void 0:d.value)!==null&&_!==void 0?_:(b=this.indexOfRefractionConnectionPoint.connectInputBlock)===null||b===void 0?void 0:b.value)!==null&&k!==void 0?k:1.5;e.setFloat4(this._vRefractionInfosName,j.level,1/_e,$,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,j.getSize().width,j.lodGenerationScale,j.lodGenerationOffset,1/_e);var et=j.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,et,Scalar.Log2(et)),j.boundingBoxSize){var tt=j;e.setVector3("vRefractionPosition",tt.boundingBoxPosition),e.setVector3("vRefractionSize",tt.boundingBoxSize)}}},i.prototype.getCode=function(e){var o="";return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+="#ifdef "+this._define3DName+`\r
  9085. `,e._samplerDeclaration+="uniform samplerCube "+this._cubeSamplerName+`;\r
  9086. `,e._samplerDeclaration+=`#else\r
  9087. `,e._samplerDeclaration+="uniform sampler2D "+this._2DSamplerName+`;\r
  9088. `,e._samplerDeclaration+=`#endif\r
  9089. `,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",`
  9090. #ifdef `+this._define3DName+`
  9091. #define sampleRefraction(s, c) textureCube(s, c)
  9092. #else
  9093. #define sampleRefraction(s, c) texture2D(s, c)
  9094. #endif\r
  9095. `,"//"+this.name),e._emitFunction("sampleRefractionLod",`
  9096. #ifdef `+this._define3DName+`
  9097. #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)
  9098. #else
  9099. #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)
  9100. #endif\r
  9101. `,"//"+this.name),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),o},i.prototype._buildBlock=function(e){return this._scene=e.sharedData.scene,this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return this.texture&&(this.texture.isCube?e=this._codeVariableName+'.texture = new BABYLON.CubeTexture("'+this.texture.name+`");\r
  9102. `:e=this._codeVariableName+'.texture = new BABYLON.Texture("'+this.texture.name+`");\r
  9103. `,e+=this._codeVariableName+".texture.coordinatesMode = "+this.texture.coordinatesMode+`;\r
  9104. `),e+=this._codeVariableName+".linkRefractionWithTransparency = "+this.linkRefractionWithTransparency+`;\r
  9105. `,e+=this._codeVariableName+".invertRefractionY = "+this.invertRefractionY+`;\r
  9106. `,e+=this._codeVariableName+".useThicknessAsDepth = "+this.useThicknessAsDepth+`;\r
  9107. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),e.texture&&(s=e.texture.url.indexOf("data:")===0?"":s,e.texture.isCube?this.texture=CubeTexture.Parse(e.texture,o,s):this.texture=Texture.Parse(e.texture,o,s)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth},__decorate([editableInPropertyPage("Link refraction to transparency",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"linkRefractionWithTransparency",void 0),__decorate([editableInPropertyPage("Invert refraction Y",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"invertRefractionY",void 0),__decorate([editableInPropertyPage("Use thickness as depth",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"useThicknessAsDepth",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.RefractionBlock",RefractionBlock);var SubSurfaceBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Fragment)||this;return o._isUnique=!0,o.registerInput("thickness",NodeMaterialBlockConnectionPointTypes.Float,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("tintColor",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("translucencyIntensity",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("translucencyDiffusionDist",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("refraction",NodeMaterialBlockConnectionPointTypes.Object,!0,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",o,NodeMaterialConnectionPointDirection.Input,RefractionBlock,"RefractionBlock")),o.registerOutput("subsurface",NodeMaterialBlockConnectionPointTypes.Object,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",o,NodeMaterialConnectionPointDirection.Output,i,"SubSurfaceBlock")),o}return i.prototype.initialize=function(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity")},i.prototype.getClassName=function(){return"SubSurfaceBlock"},Object.defineProperty(i.prototype,"thickness",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tintColor",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"translucencyIntensity",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"translucencyDiffusionDist",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"refraction",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"subsurface",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.thickness.isConnected){var o=new InputBlock("SubSurface thickness",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);o.value=0,o.output.connectTo(this.thickness)}},i.prototype.prepareDefines=function(e,o,s){a.prototype.prepareDefines.call(this,e,o,s);var c=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;s.setValue("SUBSURFACE",c||this.refraction.isConnected,!0),s.setValue("SS_TRANSLUCENCY",c,!0),s.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),s.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),s.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),s.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),s.setValue("SS_USE_GLTF_TEXTURES",!1,!0)},i.GetCode=function(e,o,s,c){var d,_,b,k,j,$,_e,et,tt,rt,it,nt,ot,at,st,ut,ft="",lt=o!=null&&o.thickness.isConnected?o.thickness.associatedVariableName:"0.",ht=o!=null&&o.tintColor.isConnected?o.tintColor.associatedVariableName:"vec3(1.)",pt=o!=null&&o.translucencyIntensity.isConnected?o==null?void 0:o.translucencyIntensity.associatedVariableName:"1.",mt=o!=null&&o.translucencyDiffusionDist.isConnected?o==null?void 0:o.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",dt=o!=null&&o.refraction.isConnected?(d=o==null?void 0:o.refraction.connectedPoint)===null||d===void 0?void 0:d.ownerBlock:null,gt=dt!=null&&dt.tintAtDistance.isConnected?dt.tintAtDistance.associatedVariableName:"1.",_t=dt!=null&&dt.intensity.isConnected?dt.intensity.associatedVariableName:"1.",yt=dt!=null&&dt.view.isConnected?dt.view.associatedVariableName:"";return ft+=(_=dt==null?void 0:dt.getCode(e))!==null&&_!==void 0?_:"",ft+=`subSurfaceOutParams subSurfaceOut;
  9108. #ifdef SUBSURFACE
  9109. vec2 vThicknessParam = vec2(0., `+lt+`);
  9110. vec4 vTintColor = vec4(`+ht+", "+gt+`);
  9111. vec3 vSubSurfaceIntensity = vec3(`+_t+", "+pt+`, 0.);
  9112. subSurfaceBlock(
  9113. vSubSurfaceIntensity,
  9114. vThicknessParam,
  9115. vTintColor,
  9116. normalW,
  9117. specularEnvironmentReflectance,
  9118. #ifdef SS_THICKNESSANDMASK_TEXTURE
  9119. vec4(0.),
  9120. #endif
  9121. #ifdef REFLECTION
  9122. #ifdef SS_TRANSLUCENCY
  9123. `+(s==null?void 0:s._reflectionMatrixName)+`,
  9124. #ifdef USESPHERICALFROMREFLECTIONMAP
  9125. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  9126. reflectionOut.irradianceVector,
  9127. #endif
  9128. #if defined(REALTIME_FILTERING)
  9129. `+(s==null?void 0:s._cubeSamplerName)+`,
  9130. `+(s==null?void 0:s._vReflectionFilteringInfoName)+`,
  9131. #endif
  9132. #endif
  9133. #ifdef USEIRRADIANCEMAP
  9134. irradianceSampler,
  9135. #endif
  9136. #endif
  9137. #endif
  9138. #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
  9139. surfaceAlbedo,
  9140. #endif
  9141. #ifdef SS_REFRACTION
  9142. `+c+`.xyz,
  9143. viewDirectionW,
  9144. `+yt+`,
  9145. `+((b=dt==null?void 0:dt._vRefractionInfosName)!==null&&b!==void 0?b:"")+`,
  9146. `+((k=dt==null?void 0:dt._refractionMatrixName)!==null&&k!==void 0?k:"")+`,
  9147. `+((j=dt==null?void 0:dt._vRefractionMicrosurfaceInfosName)!==null&&j!==void 0?j:"")+`,
  9148. vLightingIntensity,
  9149. #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
  9150. alpha,
  9151. #endif
  9152. #ifdef `+(($=dt==null?void 0:dt._defineLODRefractionAlpha)!==null&&$!==void 0?$:"IGNORE")+`
  9153. NdotVUnclamped,
  9154. #endif
  9155. #ifdef `+((_e=dt==null?void 0:dt._defineLinearSpecularRefraction)!==null&&_e!==void 0?_e:"IGNORE")+`
  9156. roughness,
  9157. #endif
  9158. alphaG,
  9159. #ifdef `+((et=dt==null?void 0:dt._define3DName)!==null&&et!==void 0?et:"IGNORE")+`
  9160. `+((tt=dt==null?void 0:dt._cubeSamplerName)!==null&&tt!==void 0?tt:"")+`,
  9161. #else
  9162. `+((rt=dt==null?void 0:dt._2DSamplerName)!==null&&rt!==void 0?rt:"")+`,
  9163. #endif
  9164. #ifndef LODBASEDMICROSFURACE
  9165. #ifdef `+((it=dt==null?void 0:dt._define3DName)!==null&&it!==void 0?it:"IGNORE")+`
  9166. `+((nt=dt==null?void 0:dt._cubeSamplerName)!==null&&nt!==void 0?nt:"")+`,
  9167. `+((ot=dt==null?void 0:dt._cubeSamplerName)!==null&&ot!==void 0?ot:"")+`,
  9168. #else
  9169. `+((at=dt==null?void 0:dt._2DSamplerName)!==null&&at!==void 0?at:"")+`,
  9170. `+((st=dt==null?void 0:dt._2DSamplerName)!==null&&st!==void 0?st:"")+`,
  9171. #endif
  9172. #endif
  9173. #ifdef ANISOTROPIC
  9174. anisotropicOut,
  9175. #endif
  9176. #ifdef REALTIME_FILTERING
  9177. `+((ut=dt==null?void 0:dt._vRefractionFilteringInfoName)!==null&&ut!==void 0?ut:"")+`,
  9178. #endif
  9179. #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
  9180. vRefractionPosition,
  9181. vRefractionSize,
  9182. #endif
  9183. #endif
  9184. #ifdef SS_TRANSLUCENCY
  9185. `+mt+`,
  9186. #endif
  9187. subSurfaceOut
  9188. );
  9189. #ifdef SS_REFRACTION
  9190. surfaceAlbedo = subSurfaceOut.surfaceAlbedo;
  9191. #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
  9192. alpha = subSurfaceOut.alpha;
  9193. #endif
  9194. #endif
  9195. #else
  9196. subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;
  9197. #endif\r
  9198. `,ft},i.prototype._buildBlock=function(e){return e.target===NodeMaterialBlockTargets.Fragment&&e.sharedData.blocksWithDefines.push(this),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.SubSurfaceBlock",SubSurfaceBlock);var mapOutputToVariable={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["shadow",""],alpha:["alpha",""]},PBRMetallicRoughnessBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.VertexAndFragment)||this;return o._environmentBRDFTexture=null,o._metallicReflectanceColor=Color3.White(),o._metallicF0Factor=1,o.directIntensity=1,o.environmentIntensity=1,o.specularIntensity=1,o.lightFalloff=0,o.useAlphaTest=!1,o.alphaTestCutoff=.5,o.useAlphaBlending=!1,o.useRadianceOverAlpha=!0,o.useSpecularOverAlpha=!0,o.enableSpecularAntiAliasing=!1,o.realTimeFiltering=!1,o.realTimeFilteringQuality=8,o.useEnergyConservation=!0,o.useRadianceOcclusion=!0,o.useHorizonOcclusion=!0,o.unlit=!1,o.forceNormalForward=!1,o.debugMode=0,o.debugLimit=0,o.debugFactor=1,o._isUnique=!0,o.registerInput("worldPosition",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Vertex),o.registerInput("worldNormal",NodeMaterialBlockConnectionPointTypes.Vector4,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("view",NodeMaterialBlockConnectionPointTypes.Matrix,!1),o.registerInput("cameraPosition",NodeMaterialBlockConnectionPointTypes.Vector3,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("perturbedNormal",NodeMaterialBlockConnectionPointTypes.Vector4,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("baseColor",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("metallic",NodeMaterialBlockConnectionPointTypes.Float,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("roughness",NodeMaterialBlockConnectionPointTypes.Float,!1,NodeMaterialBlockTargets.Fragment),o.registerInput("ambientOcc",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("opacity",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("indexOfRefraction",NodeMaterialBlockConnectionPointTypes.Float,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("ambientColor",NodeMaterialBlockConnectionPointTypes.Color3,!0,NodeMaterialBlockTargets.Fragment),o.registerInput("reflection",NodeMaterialBlockConnectionPointTypes.Object,!0,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",o,NodeMaterialConnectionPointDirection.Input,ReflectionBlock,"ReflectionBlock")),o.registerInput("clearcoat",NodeMaterialBlockConnectionPointTypes.Object,!0,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",o,NodeMaterialConnectionPointDirection.Input,ClearCoatBlock,"ClearCoatBlock")),o.registerInput("sheen",NodeMaterialBlockConnectionPointTypes.Object,!0,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",o,NodeMaterialConnectionPointDirection.Input,SheenBlock,"SheenBlock")),o.registerInput("subsurface",NodeMaterialBlockConnectionPointTypes.Object,!0,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",o,NodeMaterialConnectionPointDirection.Input,SubSurfaceBlock,"SubSurfaceBlock")),o.registerInput("anisotropy",NodeMaterialBlockConnectionPointTypes.Object,!0,NodeMaterialBlockTargets.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",o,NodeMaterialConnectionPointDirection.Input,AnisotropyBlock,"AnisotropyBlock")),o.registerOutput("ambientClr",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("diffuseDir",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("specularDir",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("clearcoatDir",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("sheenDir",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("diffuseInd",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("specularInd",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("clearcoatInd",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("sheenInd",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("refraction",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("lighting",NodeMaterialBlockConnectionPointTypes.Color3,NodeMaterialBlockTargets.Fragment),o.registerOutput("shadow",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o.registerOutput("alpha",NodeMaterialBlockConnectionPointTypes.Float,NodeMaterialBlockTargets.Fragment),o}return i.prototype.initialize=function(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")},i.prototype.getClassName=function(){return"PBRMetallicRoughnessBlock"},Object.defineProperty(i.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"view",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraPosition",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"perturbedNormal",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"baseColor",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"metallic",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"roughness",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"ambientOcc",{get:function(){return this._inputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"opacity",{get:function(){return this._inputs[9]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"indexOfRefraction",{get:function(){return this._inputs[10]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"ambientColor",{get:function(){return this._inputs[11]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"reflection",{get:function(){return this._inputs[12]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"clearcoat",{get:function(){return this._inputs[13]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sheen",{get:function(){return this._inputs[14]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"subsurface",{get:function(){return this._inputs[15]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"anisotropy",{get:function(){return this._inputs[16]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"ambientClr",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"diffuseDir",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"specularDir",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"clearcoatDir",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sheenDir",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"diffuseInd",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"specularInd",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"clearcoatInd",{get:function(){return this._outputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sheenInd",{get:function(){return this._outputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"refraction",{get:function(){return this._outputs[9]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lighting",{get:function(){return this._outputs[10]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadow",{get:function(){return this._outputs[11]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"alpha",{get:function(){return this._outputs[12]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.cameraPosition.isConnected){var o=e.getInputBlockByPredicate(function(c){return c.systemValue===NodeMaterialSystemValues.CameraPosition});o||(o=new InputBlock("cameraPosition"),o.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),o.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){var s=e.getInputBlockByPredicate(function(c){return c.systemValue===NodeMaterialSystemValues.View});s||(s=new InputBlock("view"),s.setAsSystemValue(NodeMaterialSystemValues.View)),s.output.connectTo(this.view)}},i.prototype.prepareDefines=function(e,o,s){s.setValue("PBR",!0),s.setValue("METALLICWORKFLOW",!0),s.setValue("DEBUGMODE",this.debugMode,!0),s.setValue("NORMALXYSCALE",!0),s.setValue("BUMP",this.perturbedNormal.isConnected,!0),s.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),s.setValue("ALBEDO",!1,!0),s.setValue("OPACITY",this.opacity.isConnected,!0),s.setValue("AMBIENT",!0,!0),s.setValue("AMBIENTINGRAYSCALE",!1,!0),s.setValue("REFLECTIVITY",!1,!0),s.setValue("AOSTOREINMETALMAPRED",!1,!0),s.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),s.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),s.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(s.setValue("USEPHYSICALLIGHTFALLOFF",!1),s.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===PBRBaseMaterial.LIGHTFALLOFF_GLTF?(s.setValue("USEPHYSICALLIGHTFALLOFF",!1),s.setValue("USEGLTFLIGHTFALLOFF",!0)):(s.setValue("USEPHYSICALLIGHTFALLOFF",!0),s.setValue("USEGLTFLIGHTFALLOFF",!1));var c=this.alphaTestCutoff.toString();s.setValue("ALPHABLEND",this.useAlphaBlending,!0),s.setValue("ALPHAFROMALBEDO",!1,!0),s.setValue("ALPHATEST",this.useAlphaTest,!0),s.setValue("ALPHATESTVALUE",c.indexOf(".")<0?c+".":c,!0),s.setValue("OPACITYRGB",!1,!0),s.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),s.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),s.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),s.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);var d=e.getScene();if(d.getEngine()._features.needTypeSuffixInShaderConstants?s.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):s.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),s.setValue("BRDF_V_HEIGHT_CORRELATED",!0),s.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),s.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),s.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),s.setValue("UNLIT",this.unlit,!0),s.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled?(s.setValue("ENVIRONMENTBRDF",!0),s.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(s.setValue("ENVIRONMENTBRDF",!1),s.setValue("ENVIRONMENTBRDF_RGBD",!1)),s._areImageProcessingDirty&&o.imageProcessingConfiguration&&o.imageProcessingConfiguration.prepareDefines(s),!!s._areLightsDirty)if(!this.light)MaterialHelper.PrepareDefinesForLights(d,e,s,!0,o.maxSimultaneousLights),s._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(d,s);else{var _={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};MaterialHelper.PrepareDefinesForLight(d,e,this.light,this._lightId,s,!0,_),_.needRebuild&&s.rebuild()}},i.prototype.updateUniformsAndSamples=function(e,o,s,c){for(var d=0;d<o.maxSimultaneousLights&&s["LIGHT"+d];d++){var _=e.uniforms.indexOf("vLightData"+d)>=0;MaterialHelper.PrepareUniformsAndSamplersForLight(d,e.uniforms,e.samplers,s["PROJECTEDLIGHTTEXTURE"+d],c,_)}},i.prototype.isReady=function(e,o,s){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||s._areImageProcessingDirty&&o.imageProcessingConfiguration&&!o.imageProcessingConfiguration.isReady())},i.prototype.bind=function(e,o,s){var c,d;if(!!s){var _=s.getScene();this.light?MaterialHelper.BindLight(this.light,this._lightId,_,e,!0):MaterialHelper.BindLights(_,s,e,!0,o.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);var b=this._scene.ambientColor;b&&e.setColor3("ambientFromScene",b);var k=_.useRightHandedSystem===(_._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,k?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);var j=1,$=(d=(c=this.indexOfRefraction.connectInputBlock)===null||c===void 0?void 0:c.value)!==null&&d!==void 0?d:1.5,_e=Math.pow(($-j)/($+j),2);this._metallicReflectanceColor.scaleToRef(_e*this._metallicF0Factor,TmpColors.Color3[0]);var et=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,TmpColors.Color3[0],et),o.imageProcessingConfiguration&&o.imageProcessingConfiguration.bind(e)}},i.prototype._injectVertexCode=function(e){var o,s,c=this.worldPosition,d="//"+this.name;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",d,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",d,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));var _="v_"+c.associatedVariableName;e._emitVaryingFromString(_,"vec4")&&(e.compilationString+=_+" = "+c.associatedVariableName+`;\r
  9199. `);var b=this.reflection.isConnected?(o=this.reflection.connectedPoint)===null||o===void 0?void 0:o.ownerBlock:null;b&&(b.viewConnectionPoint=this.view),e.compilationString+=(s=b==null?void 0:b.handleVertexSide(e))!==null&&s!==void 0?s:"",e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0\r
  9200. `,e._injectAtEnd+=`vClipSpacePosition = gl_Position;\r
  9201. `,e._injectAtEnd+=`#endif\r
  9202. `),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",d,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:c.associatedVariableName}]}):(e.compilationString+="vec4 worldPos = "+c.associatedVariableName+`;\r
  9203. `,this.view.isConnected&&(e.compilationString+="mat4 view = "+this.view.associatedVariableName+`;\r
  9204. `),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",d,{repeatKey:"maxSimultaneousLights"}))},i.prototype._getAlbedoOpacityCode=function(){var e=`albedoOpacityOutParams albedoOpacityOut;\r
  9205. `,o=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",s=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+=`albedoOpacityBlock(
  9206. vec4(`+o+`, 1.),
  9207. #ifdef ALBEDO
  9208. vec4(1.),
  9209. vec2(1., 1.),
  9210. #endif
  9211. #ifdef OPACITY
  9212. vec4(`+s+`),
  9213. vec2(1., 1.),
  9214. #endif
  9215. albedoOpacityOut
  9216. );
  9217. vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;
  9218. float alpha = albedoOpacityOut.alpha;\r
  9219. `,e},i.prototype._getAmbientOcclusionCode=function(){var e=`ambientOcclusionOutParams aoOut;\r
  9220. `,o=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+=`ambientOcclusionBlock(
  9221. #ifdef AMBIENT
  9222. vec3(`+o+`),
  9223. vec4(0., 1.0, 1.0, 0.),
  9224. #endif
  9225. aoOut
  9226. );\r
  9227. `,e},i.prototype._getReflectivityCode=function(e){var o=`reflectivityOutParams reflectivityOut;\r
  9228. `,s="1.";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),o+=`vec3 baseColor = surfaceAlbedo;
  9229. reflectivityBlock(
  9230. vec4(`+this.metallic.associatedVariableName+", "+this.roughness.associatedVariableName+`, 0., 0.),
  9231. #ifdef METALLICWORKFLOW
  9232. surfaceAlbedo,
  9233. `+this._vMetallicReflectanceFactorsName+`,
  9234. #endif
  9235. #ifdef REFLECTIVITY
  9236. vec3(0., 0., `+s+`),
  9237. vec4(1.),
  9238. #endif
  9239. #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
  9240. aoOut.ambientOcclusionColor,
  9241. #endif
  9242. #ifdef MICROSURFACEMAP
  9243. microSurfaceTexel, <== not handled!
  9244. #endif
  9245. reflectivityOut
  9246. );
  9247. float microSurface = reflectivityOut.microSurface;
  9248. float roughness = reflectivityOut.roughness;
  9249. #ifdef METALLICWORKFLOW
  9250. surfaceAlbedo = reflectivityOut.surfaceAlbedo;
  9251. #endif
  9252. #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
  9253. aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;
  9254. #endif\r
  9255. `,o},i.prototype._buildBlock=function(e){var o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it,nt,ot,at,st,ut,ft,lt,ht,pt,mt,dt,gt,_t,yt,Tt,St,At,vt,Et,xt,bt,Mt,Rt,Pt,It,Dt;a.prototype._buildBlock.call(this,e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this._scene));var Ct=this.reflection.isConnected?(o=this.reflection.connectedPoint)===null||o===void 0?void 0:o.ownerBlock:null;if(Ct&&(Ct.worldPositionConnectionPoint=this.worldPosition,Ct.cameraPositionConnectionPoint=this.cameraPosition,Ct.worldNormalConnectionPoint=this.worldNormal),e.target!==NodeMaterialBlockTargets.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this);var Ot="//"+this.name,Ft="v_"+this.worldPosition.associatedVariableName,wt=this.perturbedNormal;this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",Ot,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",Ot,{repeatKey:"maxSimultaneousLights"}),e._emitFunctionFromInclude("helperFunctions",Ot),e._emitFunctionFromInclude("importanceSampling",Ot),e._emitFunctionFromInclude("pbrHelperFunctions",Ot),e._emitFunctionFromInclude("imageProcessingDeclaration",Ot),e._emitFunctionFromInclude("imageProcessingFunctions",Ot),e._emitFunctionFromInclude("shadowsFragmentFunctions",Ot,{replaceStrings:[{search:/vPositionW/g,replace:Ft+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",Ot,{replaceStrings:[{search:/vPositionW/g,replace:Ft+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",Ot),e._emitFunctionFromInclude("pbrBRDFFunctions",Ot,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(s=Ct==null?void 0:Ct._defineSkyboxName)!==null&&s!==void 0?s:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",Ot),e._emitFunctionFromInclude("pbrDirectLightingFunctions",Ot,{replaceStrings:[{search:/vPositionW/g,replace:Ft+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",Ot),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",Ot),e._emitFunctionFromInclude("pbrBlockReflectivity",Ot),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",Ot),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",Ot),e._emitFunctionFromInclude("pbrBlockAnisotropic",Ot),e._emitUniformFromString("vLightingIntensity","vec4"),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+="vec4 "+this._vNormalWName+" = normalize("+this.worldNormal.associatedVariableName+`);\r
  9256. `,e._registerTempVariable("viewDirectionW")&&(e.compilationString+="vec3 viewDirectionW = normalize("+this.cameraPosition.associatedVariableName+" - "+Ft+`.xyz);\r
  9257. `),e.compilationString+="vec3 geometricNormalW = "+this._vNormalWName+`.xyz;\r
  9258. `,e.compilationString+="vec3 normalW = "+(wt.isConnected?"normalize("+wt.associatedVariableName+".xyz)":"geometricNormalW")+`;\r
  9259. `,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",Ot,{replaceStrings:[{search:/vPositionW/g,replace:Ft+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",Ot),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",Ot),e.compilationString+=`#ifdef UNLIT
  9260. vec3 diffuseBase = vec3(1., 1., 1.);
  9261. #else\r
  9262. `,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",Ot,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(c=Ct==null?void 0:Ct._defineSkyboxName)!==null&&c!==void 0?c:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(d=Ct==null?void 0:Ct._define3DName)!==null&&d!==void 0?d:"REFLECTIONMAP_3D"}]});var Bt=this.anisotropy.isConnected?(_=this.anisotropy.connectedPoint)===null||_===void 0?void 0:_.ownerBlock:null;Bt&&(Bt.worldPositionConnectionPoint=this.worldPosition,Bt.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=Bt.getCode(e,!this.perturbedNormal.isConnected)),Ct&&Ct.hasTexture&&(e.compilationString+=Ct.getCode(e,Bt?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",Ot,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(b=Ct==null?void 0:Ct._define3DName)!==null&&b!==void 0?b:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(k=Ct==null?void 0:Ct._defineOppositeZ)!==null&&k!==void 0?k:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(j=Ct==null?void 0:Ct._defineProjectionName)!==null&&j!==void 0?j:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:($=Ct==null?void 0:Ct._defineSkyboxName)!==null&&$!==void 0?$:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(_e=Ct==null?void 0:Ct._defineLODReflectionAlpha)!==null&&_e!==void 0?_e:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(et=Ct==null?void 0:Ct._defineLinearSpecularReflection)!==null&&et!==void 0?et:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(tt=Ct==null?void 0:Ct._vReflectionFilteringInfoName)!==null&&tt!==void 0?tt:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",Ot,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});var Ut=this.sheen.isConnected?(rt=this.sheen.connectedPoint)===null||rt===void 0?void 0:rt.ownerBlock:null;Ut&&(e.compilationString+=Ut.getCode(Ct)),e._emitFunctionFromInclude("pbrBlockSheen",Ot,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(it=Ct==null?void 0:Ct._define3DName)!==null&&it!==void 0?it:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(nt=Ct==null?void 0:Ct._defineSkyboxName)!==null&&nt!==void 0?nt:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(ot=Ct==null?void 0:Ct._defineLODReflectionAlpha)!==null&&ot!==void 0?ot:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(at=Ct==null?void 0:Ct._defineLinearSpecularReflection)!==null&&at!==void 0?at:"LINEARSPECULARREFLECTION"}]});var Vt=this.clearcoat.isConnected?(st=this.clearcoat.connectedPoint)===null||st===void 0?void 0:st.ownerBlock:null,Gt=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Lt=this.perturbedNormal.isConnected&&((ft=((ut=this.perturbedNormal.connectedPoint)===null||ut===void 0?void 0:ut.ownerBlock).worldTangent)===null||ft===void 0?void 0:ft.isConnected),Ht=this.anisotropy.isConnected&&((lt=this.anisotropy.connectedPoint)===null||lt===void 0?void 0:lt.ownerBlock).worldTangent.isConnected,Wt=Lt||!this.perturbedNormal.isConnected&&Ht;e.compilationString+=ClearCoatBlock.GetCode(e,Vt,Ct,Ft,Gt,Wt,this.worldNormal.associatedVariableName),Gt&&(Wt=(ht=Vt==null?void 0:Vt.worldTangent.isConnected)!==null&&ht!==void 0?ht:!1),e._emitFunctionFromInclude("pbrBlockClearcoat",Ot,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(pt=Ct==null?void 0:Ct._define3DName)!==null&&pt!==void 0?pt:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(mt=Ct==null?void 0:Ct._defineOppositeZ)!==null&&mt!==void 0?mt:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(dt=Ct==null?void 0:Ct._defineProjectionName)!==null&&dt!==void 0?dt:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(gt=Ct==null?void 0:Ct._defineSkyboxName)!==null&&gt!==void 0?gt:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(_t=Ct==null?void 0:Ct._defineLODReflectionAlpha)!==null&&_t!==void 0?_t:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(yt=Ct==null?void 0:Ct._defineLinearSpecularReflection)!==null&&yt!==void 0?yt:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:Wt?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",Ot,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(Tt=Ct==null?void 0:Ct._defineSkyboxName)!==null&&Tt!==void 0?Tt:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(St=Ct==null?void 0:Ct._define3DName)!==null&&St!==void 0?St:"REFLECTIONMAP_3D"}]});var Yt=this.subsurface.isConnected?(At=this.subsurface.connectedPoint)===null||At===void 0?void 0:At.ownerBlock:null,jt=this.subsurface.isConnected?(Et=((vt=this.subsurface.connectedPoint)===null||vt===void 0?void 0:vt.ownerBlock).refraction.connectedPoint)===null||Et===void 0?void 0:Et.ownerBlock:null;jt&&(jt.viewConnectionPoint=this.view,jt.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=SubSurfaceBlock.GetCode(e,Yt,Ct,Ft),e._emitFunctionFromInclude("pbrBlockSubSurface",Ot,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(xt=Ct==null?void 0:Ct._define3DName)!==null&&xt!==void 0?xt:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(bt=Ct==null?void 0:Ct._defineOppositeZ)!==null&&bt!==void 0?bt:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(Mt=Ct==null?void 0:Ct._defineProjectionName)!==null&&Mt!==void 0?Mt:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(Rt=jt==null?void 0:jt._define3DName)!==null&&Rt!==void 0?Rt:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(Pt=jt==null?void 0:jt._defineLODRefractionAlpha)!==null&&Pt!==void 0?Pt:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(It=jt==null?void 0:jt._defineLinearSpecularRefraction)!==null&&It!==void 0?It:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(Dt=jt==null?void 0:jt._defineOppositeZ)!==null&&Dt!==void 0?Dt:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",Ot),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",Ot,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",Ot,{repeatKey:"maxSimultaneousLights"}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",Ot),e.compilationString+=`#endif\r
  9263. `;var $t=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",Qt=PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();Qt.indexOf(".")===-1&&(Qt+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",Ot,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:$t+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:Qt}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",Ot,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",Ot,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",Ot,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:Ft},{search:/albedoTexture\.rgb;/g,replace:`vec3(1.);\r
  9264. gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r
  9265. `}]});for(var ir=0,nr=this._outputs;ir<nr.length;ir++){var rr=nr[ir];if(rr.hasEndpoints){var or=mapOutputToVariable[rr.name];if(or){var tr=or[0],Jt=or[1];Jt&&(e.compilationString+="#if "+Jt+`\r
  9266. `),e.compilationString+=this._declareOutput(rr,e)+" = "+tr+`;\r
  9267. `,Jt&&(e.compilationString+=`#else\r
  9268. `,e.compilationString+=this._declareOutput(rr,e)+` = vec3(0.);\r
  9269. `,e.compilationString+=`#endif\r
  9270. `)}else console.error("There's no remapping for the "+rr.name+" end point! No code generated")}}return this},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this);return e+=this._codeVariableName+".lightFalloff = "+this.lightFalloff+`;\r
  9271. `,e+=this._codeVariableName+".useAlphaTest = "+this.useAlphaTest+`;\r
  9272. `,e+=this._codeVariableName+".alphaTestCutoff = "+this.alphaTestCutoff+`;\r
  9273. `,e+=this._codeVariableName+".useAlphaBlending = "+this.useAlphaBlending+`;\r
  9274. `,e+=this._codeVariableName+".useRadianceOverAlpha = "+this.useRadianceOverAlpha+`;\r
  9275. `,e+=this._codeVariableName+".useSpecularOverAlpha = "+this.useSpecularOverAlpha+`;\r
  9276. `,e+=this._codeVariableName+".enableSpecularAntiAliasing = "+this.enableSpecularAntiAliasing+`;\r
  9277. `,e+=this._codeVariableName+".realTimeFiltering = "+this.realTimeFiltering+`;\r
  9278. `,e+=this._codeVariableName+".realTimeFilteringQuality = "+this.realTimeFilteringQuality+`;\r
  9279. `,e+=this._codeVariableName+".useEnergyConservation = "+this.useEnergyConservation+`;\r
  9280. `,e+=this._codeVariableName+".useRadianceOcclusion = "+this.useRadianceOcclusion+`;\r
  9281. `,e+=this._codeVariableName+".useHorizonOcclusion = "+this.useHorizonOcclusion+`;\r
  9282. `,e+=this._codeVariableName+".unlit = "+this.unlit+`;\r
  9283. `,e+=this._codeVariableName+".forceNormalForward = "+this.forceNormalForward+`;\r
  9284. `,e+=this._codeVariableName+".debugMode = "+this.debugMode+`;\r
  9285. `,e+=this._codeVariableName+".debugLimit = "+this.debugLimit+`;\r
  9286. `,e+=this._codeVariableName+".debugFactor = "+this.debugFactor+`;\r
  9287. `,e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e},i.prototype._deserialize=function(e,o,s){var c,d;a.prototype._deserialize.call(this,e,o,s),e.lightId&&(this.light=o.getLightById(e.lightId)),this.lightFalloff=(c=e.lightFalloff)!==null&&c!==void 0?c:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=(d=e.realTimeFilteringQuality)!==null&&d!==void 0?d:8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor},__decorate([editableInPropertyPage("Direct lights",PropertyTypeForEdition.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],i.prototype,"directIntensity",void 0),__decorate([editableInPropertyPage("Environment lights",PropertyTypeForEdition.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],i.prototype,"environmentIntensity",void 0),__decorate([editableInPropertyPage("Specular highlights",PropertyTypeForEdition.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],i.prototype,"specularIntensity",void 0),__decorate([editableInPropertyPage("Light falloff",PropertyTypeForEdition.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:PBRBaseMaterial.LIGHTFALLOFF_GLTF},{label:"Standard",value:PBRBaseMaterial.LIGHTFALLOFF_STANDARD}]})],i.prototype,"lightFalloff",void 0),__decorate([editableInPropertyPage("Alpha Testing",PropertyTypeForEdition.Boolean,"OPACITY")],i.prototype,"useAlphaTest",void 0),__decorate([editableInPropertyPage("Alpha CutOff",PropertyTypeForEdition.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],i.prototype,"alphaTestCutoff",void 0),__decorate([editableInPropertyPage("Alpha blending",PropertyTypeForEdition.Boolean,"OPACITY")],i.prototype,"useAlphaBlending",void 0),__decorate([editableInPropertyPage("Radiance over alpha",PropertyTypeForEdition.Boolean,"RENDERING",{notifiers:{update:!0}})],i.prototype,"useRadianceOverAlpha",void 0),__decorate([editableInPropertyPage("Specular over alpha",PropertyTypeForEdition.Boolean,"RENDERING",{notifiers:{update:!0}})],i.prototype,"useSpecularOverAlpha",void 0),__decorate([editableInPropertyPage("Specular anti-aliasing",PropertyTypeForEdition.Boolean,"RENDERING",{notifiers:{update:!0}})],i.prototype,"enableSpecularAntiAliasing",void 0),__decorate([editableInPropertyPage("Realtime filtering",PropertyTypeForEdition.Boolean,"RENDERING",{notifiers:{update:!0}})],i.prototype,"realTimeFiltering",void 0),__decorate([editableInPropertyPage("Realtime filtering quality",PropertyTypeForEdition.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],i.prototype,"realTimeFilteringQuality",void 0),__decorate([editableInPropertyPage("Energy Conservation",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"useEnergyConservation",void 0),__decorate([editableInPropertyPage("Radiance occlusion",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"useRadianceOcclusion",void 0),__decorate([editableInPropertyPage("Horizon occlusion",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"useHorizonOcclusion",void 0),__decorate([editableInPropertyPage("Unlit",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"unlit",void 0),__decorate([editableInPropertyPage("Force normal forward",PropertyTypeForEdition.Boolean,"ADVANCED",{notifiers:{update:!0}})],i.prototype,"forceNormalForward",void 0),__decorate([editableInPropertyPage("Debug mode",PropertyTypeForEdition.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],i.prototype,"debugMode",void 0),__decorate([editableInPropertyPage("Split position",PropertyTypeForEdition.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],i.prototype,"debugLimit",void 0),__decorate([editableInPropertyPage("Output factor",PropertyTypeForEdition.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],i.prototype,"debugFactor",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.PBRMetallicRoughnessBlock",PBRMetallicRoughnessBlock);var ModBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("left",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("right",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._outputs[0]._typeConnectionSource=o._inputs[0],o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"ModBlock"},Object.defineProperty(i.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0];return e.compilationString+=this._declareOutput(o,e)+(" = mod("+this.left.associatedVariableName+", "+this.right.associatedVariableName+`);\r
  9288. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.ModBlock",ModBlock);var MatrixBuilderBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("row0",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("row1",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("row2",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerInput("row3",NodeMaterialBlockConnectionPointTypes.Vector4),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Matrix),o}return i.prototype.getClassName=function(){return"MatrixBuilder"},Object.defineProperty(i.prototype,"row0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"row1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"row2",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"row3",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype.autoConfigure=function(e){if(!this.row0.isConnected){var o=new InputBlock("row0");o.value=new Vector4(1,0,0,0),o.output.connectTo(this.row0)}if(!this.row1.isConnected){var s=new InputBlock("row1");s.value=new Vector4(0,1,0,0),s.output.connectTo(this.row1)}if(!this.row2.isConnected){var c=new InputBlock("row2");c.value=new Vector4(0,0,1,0),c.output.connectTo(this.row2)}if(!this.row3.isConnected){var d=new InputBlock("row3");d.value=new Vector4(0,0,0,1),d.output.connectTo(this.row3)}},i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this.row0,c=this.row1,d=this.row2,_=this.row3;return e.compilationString+=this._declareOutput(o,e)+(" = mat4("+s.associatedVariableName+", "+c.associatedVariableName+", "+d.associatedVariableName+", "+_.associatedVariableName+`);\r
  9289. `),this},i}(NodeMaterialBlock);RegisterClass("BABYLON.MatrixBuilder",MatrixBuilderBlock);var ConditionalBlockConditions;(function(a){a[a.Equal=0]="Equal",a[a.NotEqual=1]="NotEqual",a[a.LessThan=2]="LessThan",a[a.GreaterThan=3]="GreaterThan",a[a.LessOrEqual=4]="LessOrEqual",a[a.GreaterOrEqual=5]="GreaterOrEqual",a[a.Xor=6]="Xor",a[a.Or=7]="Or",a[a.And=8]="And"})(ConditionalBlockConditions||(ConditionalBlockConditions={}));var ConditionalBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.condition=ConditionalBlockConditions.LessThan,o.registerInput("a",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("b",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("true",NodeMaterialBlockConnectionPointTypes.AutoDetect,!0),o.registerInput("false",NodeMaterialBlockConnectionPointTypes.AutoDetect,!0),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.BasedOnInput),o._linkConnectionTypes(2,3),o._outputs[0]._typeConnectionSource=o._inputs[2],o._outputs[0]._defaultConnectionPointType=NodeMaterialBlockConnectionPointTypes.Float,o}return i.prototype.getClassName=function(){return"ConditionalBlock"},Object.defineProperty(i.prototype,"a",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"b",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"true",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"false",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){a.prototype._buildBlock.call(this,e);var o=this._outputs[0],s=this.true.isConnected?this.true.associatedVariableName:"1.0",c=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case ConditionalBlockConditions.Equal:{e.compilationString+=this._declareOutput(o,e)+(" = "+this.a.associatedVariableName+" == "+this.b.associatedVariableName+" ? "+s+" : "+c+`;\r
  9290. `);break}case ConditionalBlockConditions.NotEqual:{e.compilationString+=this._declareOutput(o,e)+(" = "+this.a.associatedVariableName+" != "+this.b.associatedVariableName+" ? "+s+" : "+c+`;\r
  9291. `);break}case ConditionalBlockConditions.LessThan:{e.compilationString+=this._declareOutput(o,e)+(" = "+this.a.associatedVariableName+" < "+this.b.associatedVariableName+" ? "+s+" : "+c+`;\r
  9292. `);break}case ConditionalBlockConditions.LessOrEqual:{e.compilationString+=this._declareOutput(o,e)+(" = "+this.a.associatedVariableName+" <= "+this.b.associatedVariableName+" ? "+s+" : "+c+`;\r
  9293. `);break}case ConditionalBlockConditions.GreaterThan:{e.compilationString+=this._declareOutput(o,e)+(" = "+this.a.associatedVariableName+" > "+this.b.associatedVariableName+" ? "+s+" : "+c+`;\r
  9294. `);break}case ConditionalBlockConditions.GreaterOrEqual:{e.compilationString+=this._declareOutput(o,e)+(" = "+this.a.associatedVariableName+" >= "+this.b.associatedVariableName+" ? "+s+" : "+c+`;\r
  9295. `);break}case ConditionalBlockConditions.Xor:{e.compilationString+=this._declareOutput(o,e)+(" = (mod("+this.a.associatedVariableName+" + "+this.b.associatedVariableName+", 2.0) > 0.0) ? "+s+" : "+c+`;\r
  9296. `);break}case ConditionalBlockConditions.Or:{e.compilationString+=this._declareOutput(o,e)+(" = (min("+this.a.associatedVariableName+" + "+this.b.associatedVariableName+", 1.0) > 0.0) ? "+s+" : "+c+`;\r
  9297. `);break}case ConditionalBlockConditions.And:{e.compilationString+=this._declareOutput(o,e)+(" = ("+this.a.associatedVariableName+" * "+this.b.associatedVariableName+" > 0.0) ? "+s+" : "+c+`;\r
  9298. `);break}}return this},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.condition=this.condition,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.condition=e.condition},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".condition = BABYLON.ConditionalBlockConditions."+ConditionalBlockConditions[this.condition]+`;\r
  9299. `);return e},i}(NodeMaterialBlock);RegisterClass("BABYLON.ConditionalBlock",ConditionalBlock);var CloudBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.octaves=6,o.registerInput("seed",NodeMaterialBlockConnectionPointTypes.AutoDetect),o.registerInput("chaos",NodeMaterialBlockConnectionPointTypes.AutoDetect,!0),o.registerInput("offsetX",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("offsetY",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerInput("offsetZ",NodeMaterialBlockConnectionPointTypes.Float,!0),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),o._linkConnectionTypes(0,1),o}return i.prototype.getClassName=function(){return"CloudBlock"},Object.defineProperty(i.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"chaos",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"offsetX",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"offsetY",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"offsetZ",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){var o,s;if(a.prototype._buildBlock.call(this,e),!!this.seed.isConnected&&!!this._outputs[0].hasEndpoints){var c=`
  9300. float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }
  9301. // Based on Morgan McGuire @morgan3d
  9302. // https://www.shadertoy.com/view/4dS3Wd
  9303. float cloudNoise(in vec2 x, in vec2 chaos) {
  9304. vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);
  9305. vec2 i = floor(x);
  9306. vec2 f = fract(x);
  9307. float n = dot(i, step);
  9308. vec2 u = f * f * (3.0 - 2.0 * f);
  9309. return mix(
  9310. mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),
  9311. mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),
  9312. u.y
  9313. );
  9314. }
  9315. float cloudNoise(in vec3 x, in vec3 chaos) {
  9316. vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);
  9317. vec3 i = floor(x);
  9318. vec3 f = fract(x);
  9319. float n = dot(i, step);
  9320. vec3 u = f * f * (3.0 - 2.0 * f);
  9321. return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),
  9322. mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),
  9323. mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),
  9324. mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);
  9325. }`,d=`
  9326. float fbm(in vec2 st, in vec2 chaos) {
  9327. // Initial values
  9328. float value = 0.0;
  9329. float amplitude = .5;
  9330. float frequency = 0.;
  9331. // Loop of octaves
  9332. for (int i = 0; i < OCTAVES; i++) {
  9333. value += amplitude * cloudNoise(st, chaos);
  9334. st *= 2.0;
  9335. amplitude *= 0.5;
  9336. }
  9337. return value;
  9338. }
  9339. float fbm(in vec3 x, in vec3 chaos) {
  9340. // Initial values
  9341. float value = 0.0;
  9342. float amplitude = 0.5;
  9343. for (int i = 0; i < OCTAVES; ++i) {
  9344. value += amplitude * cloudNoise(x, chaos);
  9345. x = x * 2.0;
  9346. amplitude *= 0.5;
  9347. }
  9348. return value;
  9349. }`,_="fbm"+this.octaves;e._emitFunction("CloudBlockCode",c,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,d.replace(/fbm/gi,_).replace(/OCTAVES/gi,(this.octaves|0).toString()),"// CloudBlockCode FBM");var b=e._getFreeVariableName("st"),k=((o=this.seed.connectedPoint)===null||o===void 0?void 0:o.type)===NodeMaterialBlockConnectionPointTypes.Vector2?"vec2":"vec3";e.compilationString+=k+" "+b+" = "+this.seed.associatedVariableName+`;\r
  9350. `,this.offsetX.isConnected&&(e.compilationString+=b+".x += 0.1 * "+this.offsetX.associatedVariableName+`;\r
  9351. `),this.offsetY.isConnected&&(e.compilationString+=b+".y += 0.1 * "+this.offsetY.associatedVariableName+`;\r
  9352. `),this.offsetZ.isConnected&&k==="vec3"&&(e.compilationString+=b+".z += 0.1 * "+this.offsetZ.associatedVariableName+`;\r
  9353. `);var j="";return this.chaos.isConnected?j=this.chaos.associatedVariableName:j=((s=this.seed.connectedPoint)===null||s===void 0?void 0:s.type)===NodeMaterialBlockConnectionPointTypes.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+(" = "+_+"("+b+", "+j+`);\r
  9354. `),this}},i.prototype._dumpPropertiesCode=function(){var e=a.prototype._dumpPropertiesCode.call(this)+(this._codeVariableName+".octaves = "+this.octaves+`;\r
  9355. `);return e},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this);return e.octaves=this.octaves,e},i.prototype._deserialize=function(e,o,s){a.prototype._deserialize.call(this,e,o,s),this.octaves=e.octaves},__decorate([editableInPropertyPage("Octaves",PropertyTypeForEdition.Int)],i.prototype,"octaves",void 0),i}(NodeMaterialBlock);RegisterClass("BABYLON.CloudBlock",CloudBlock);var VoronoiNoiseBlock=function(a){__extends(i,a);function i(e){var o=a.call(this,e,NodeMaterialBlockTargets.Neutral)||this;return o.registerInput("seed",NodeMaterialBlockConnectionPointTypes.Vector2),o.registerInput("offset",NodeMaterialBlockConnectionPointTypes.Float),o.registerInput("density",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("output",NodeMaterialBlockConnectionPointTypes.Float),o.registerOutput("cells",NodeMaterialBlockConnectionPointTypes.Float),o}return i.prototype.getClassName=function(){return"VoronoiNoiseBlock"},Object.defineProperty(i.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"offset",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"density",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cells",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),i.prototype._buildBlock=function(e){if(a.prototype._buildBlock.call(this,e),!!this.seed.isConnected){var o=`vec2 voronoiRandom(vec2 seed, float offset){
  9356. mat2 m = mat2(15.27, 47.63, 99.41, 89.98);
  9357. vec2 uv = fract(sin(m * seed) * 46839.32);
  9358. return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);
  9359. }
  9360. `;e._emitFunction("voronoiRandom",o,"// Voronoi random generator"),o=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){
  9361. vec2 g = floor(seed * density);
  9362. vec2 f = fract(seed * density);
  9363. float t = 8.0;
  9364. vec3 res = vec3(8.0, 0.0, 0.0);
  9365. for(int y=-1; y<=1; y++)
  9366. {
  9367. for(int x=-1; x<=1; x++)
  9368. {
  9369. vec2 lattice = vec2(x,y);
  9370. vec2 randomOffset = voronoiRandom(lattice + g, offset);
  9371. float d = distance(lattice + randomOffset, f);
  9372. if(d < res.x)
  9373. {
  9374. res = vec3(d, randomOffset.x, randomOffset.y);
  9375. outValue = res.x;
  9376. cells = res.y;
  9377. }
  9378. }
  9379. }
  9380. }
  9381. `,e._emitFunction("voronoi",o,"// Voronoi");var s=e._getFreeVariableName("tempOutput"),c=e._getFreeVariableName("tempCells");return e.compilationString+="float "+s+` = 0.0;\r
  9382. `,e.compilationString+="float "+c+` = 0.0;\r
  9383. `,e.compilationString+="voronoi("+this.seed.associatedVariableName+", "+this.offset.associatedVariableName+", "+this.density.associatedVariableName+", "+s+", "+c+`);\r
  9384. `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+(" = "+s+`;\r
  9385. `)),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+(" = "+c+`;\r
  9386. `)),this}},i}(NodeMaterialBlock);RegisterClass("BABYLON.VoronoiNoiseBlock",VoronoiNoiseBlock);Node$2.AddNodeConstructor("Light_Type_2",function(a,i){return function(){return new SpotLight(a,Vector3.Zero(),Vector3.Zero(),0,0,i)}});var SpotLight=function(a){__extends(i,a);function i(e,o,s,c,d,_){var b=a.call(this,e,_)||this;return b._innerAngle=0,b._projectionTextureMatrix=Matrix.Zero(),b._projectionTextureLightNear=1e-6,b._projectionTextureLightFar=1e3,b._projectionTextureUpDirection=Vector3.Up(),b._projectionTextureViewLightDirty=!0,b._projectionTextureProjectionLightDirty=!0,b._projectionTextureDirty=!0,b._projectionTextureViewTargetVector=Vector3.Zero(),b._projectionTextureViewLightMatrix=Matrix.Zero(),b._projectionTextureProjectionLightMatrix=Matrix.Zero(),b._projectionTextureScalingMatrix=Matrix.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),b.position=o,b.direction=s,b.angle=c,b.exponent=d,b}return Object.defineProperty(i.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._cosHalfAngle=Math.cos(e*.5),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"innerAngle",{get:function(){return this._innerAngle},set:function(e){this._innerAngle=e,this._computeAngleValues()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){var o=this;this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(i._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(function(){o._markMeshesAsLightDirty()}):i._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(function(){o._markMeshesAsLightDirty()})))},enumerable:!1,configurable:!0}),i._IsProceduralTexture=function(e){return e.onGeneratedObservable!==void 0},i._IsTexture=function(e){return e.onLoadObservable!==void 0},Object.defineProperty(i.prototype,"projectionTextureProjectionLightMatrix",{get:function(){return this._projectionTextureProjectionLightMatrix},set:function(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"SpotLight"},i.prototype.getTypeID=function(){return Light.LIGHTTYPEID_SPOTLIGHT},i.prototype._setDirection=function(e){a.prototype._setDirection.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setPosition=function(e){a.prototype._setPosition.call(this,e),this._projectionTextureViewLightDirty=!0},i.prototype._setDefaultShadowProjectionMatrix=function(e,o,s){var c=this.getScene().activeCamera;if(!!c){this._shadowAngleScale=this._shadowAngleScale||1;var d=this._shadowAngleScale*this._angle,_=this.shadowMinZ!==void 0?this.shadowMinZ:c.minZ,b=this.shadowMaxZ!==void 0?this.shadowMaxZ:c.maxZ,k=this.getScene().getEngine().useReverseDepthBuffer;Matrix.PerspectiveFovLHToRef(d,1,k?b:_,k?_:b,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,k)}},i.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),Matrix.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},i.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var e=this.projectionTextureLightFar,o=this.projectionTextureLightNear,s=e/(e-o),c=-s*o,d=1/Math.tan(this._angle/2),_=1;Matrix.FromValuesToRef(d/_,0,0,0,0,d,0,0,0,0,s,1,0,0,c,0,this._projectionTextureProjectionLightMatrix)},i.prototype._computeProjectionTextureMatrix=function(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Texture){var e=this._projectionTexture.uScale/2,o=this._projectionTexture.vScale/2;Matrix.FromValuesToRef(e,0,0,0,0,o,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},i.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},i.prototype._computeAngleValues=function(){this._lightAngleScale=1/Math.max(.001,Math.cos(this._innerAngle*.5)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale},i.prototype.transferTexturesToEffect=function(e,o){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+o,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+o,this.projectionTexture)),this},i.prototype.transferToEffect=function(e,o){var s;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,o),s=Vector3.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,o),s=Vector3.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",s.x,s.y,s.z,this._cosHalfAngle,o),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,o),this},i.prototype.transferToNodeMaterialEffect=function(e,o){var s;return this.computeTransformedInformation()?s=Vector3.Normalize(this.transformedDirection):s=Vector3.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(o,-s.x,-s.y,-s.z):e.setFloat3(o,s.x,s.y,s.z),this},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},i.prototype.getDepthMinZ=function(e){var o=this._scene.getEngine(),s=this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ;return o.useReverseDepthBuffer&&o.isNDCHalfZRange?s:this._scene.getEngine().isNDCHalfZRange?0:s},i.prototype.getDepthMaxZ=function(e){var o=this._scene.getEngine(),s=this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ;return o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:s},i.prototype.prepareLightSpecificDefines=function(e,o){e["SPOTLIGHT"+o]=!0,e["PROJECTEDLIGHTTEXTURE"+o]=!!(this.projectionTexture&&this.projectionTexture.isReady())},__decorate([serialize()],i.prototype,"angle",null),__decorate([serialize()],i.prototype,"innerAngle",null),__decorate([serialize()],i.prototype,"shadowAngleScale",null),__decorate([serialize()],i.prototype,"exponent",void 0),__decorate([serialize()],i.prototype,"projectionTextureLightNear",null),__decorate([serialize()],i.prototype,"projectionTextureLightFar",null),__decorate([serialize()],i.prototype,"projectionTextureUpDirection",null),__decorate([serializeAsTexture("projectedLightTexture")],i.prototype,"_projectionTexture",void 0),i}(ShadowLight),name$D="glowMapGenerationPixelShader",shader$D=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)
  9387. #include<helperFunctions>
  9388. #endif
  9389. #ifdef DIFFUSE
  9390. varying vec2 vUVDiffuse;
  9391. uniform sampler2D diffuseSampler;
  9392. #endif
  9393. #ifdef OPACITY
  9394. varying vec2 vUVOpacity;
  9395. uniform sampler2D opacitySampler;
  9396. uniform float opacityIntensity;
  9397. #endif
  9398. #ifdef EMISSIVE
  9399. varying vec2 vUVEmissive;
  9400. uniform sampler2D emissiveSampler;
  9401. #endif
  9402. #ifdef VERTEXALPHA
  9403. varying vec4 vColor;
  9404. #endif
  9405. uniform vec4 glowColor;
  9406. void main(void)
  9407. {
  9408. vec4 finalColor=glowColor;
  9409. #ifdef DIFFUSE
  9410. vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);
  9411. #ifdef DIFFUSE_ISLINEAR
  9412. albedoTexture=toGammaSpace(albedoTexture);
  9413. #endif
  9414. #ifdef GLOW
  9415. finalColor.a*=albedoTexture.a;
  9416. #endif
  9417. #ifdef HIGHLIGHT
  9418. finalColor.a=albedoTexture.a;
  9419. #endif
  9420. #endif
  9421. #ifdef OPACITY
  9422. vec4 opacityMap=texture2D(opacitySampler,vUVOpacity);
  9423. #ifdef OPACITYRGB
  9424. finalColor.a*=getLuminance(opacityMap.rgb);
  9425. #else
  9426. finalColor.a*=opacityMap.a;
  9427. #endif
  9428. finalColor.a*=opacityIntensity;
  9429. #endif
  9430. #ifdef VERTEXALPHA
  9431. finalColor.a*=vColor.a;
  9432. #endif
  9433. #ifdef ALPHATEST
  9434. if (finalColor.a<ALPHATESTVALUE)
  9435. discard;
  9436. #endif
  9437. #ifdef EMISSIVE
  9438. vec4 emissive=texture2D(emissiveSampler,vUVEmissive);
  9439. #ifdef EMISSIVE_ISLINEAR
  9440. emissive=toGammaSpace(emissive);
  9441. #endif
  9442. gl_FragColor=emissive*finalColor;
  9443. #else
  9444. gl_FragColor=finalColor;
  9445. #endif
  9446. #ifdef HIGHLIGHT
  9447. gl_FragColor.a=glowColor.a;
  9448. #endif
  9449. }`;ShaderStore.ShadersStore[name$D]=shader$D;var name$C="glowMapGenerationVertexShader",shader$C=`
  9450. attribute vec3 position;
  9451. #include<bonesDeclaration>
  9452. #include<bakedVertexAnimationDeclaration>
  9453. #include<morphTargetsVertexGlobalDeclaration>
  9454. #include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
  9455. #include<instancesDeclaration>
  9456. uniform mat4 viewProjection;
  9457. varying vec4 vPosition;
  9458. #ifdef UV1
  9459. attribute vec2 uv;
  9460. #endif
  9461. #ifdef UV2
  9462. attribute vec2 uv2;
  9463. #endif
  9464. #ifdef DIFFUSE
  9465. varying vec2 vUVDiffuse;
  9466. uniform mat4 diffuseMatrix;
  9467. #endif
  9468. #ifdef OPACITY
  9469. varying vec2 vUVOpacity;
  9470. uniform mat4 opacityMatrix;
  9471. #endif
  9472. #ifdef EMISSIVE
  9473. varying vec2 vUVEmissive;
  9474. uniform mat4 emissiveMatrix;
  9475. #endif
  9476. #ifdef VERTEXALPHA
  9477. attribute vec4 color;
  9478. varying vec4 vColor;
  9479. #endif
  9480. void main(void)
  9481. {
  9482. vec3 positionUpdated=position;
  9483. #ifdef UV1
  9484. vec2 uvUpdated=uv;
  9485. #endif
  9486. #include<morphTargetsVertexGlobal>
  9487. #include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
  9488. #include<instancesVertex>
  9489. #include<bonesVertex>
  9490. #include<bakedVertexAnimation>
  9491. #ifdef CUBEMAP
  9492. vPosition=finalWorld*vec4(positionUpdated,1.0);
  9493. gl_Position=viewProjection*finalWorld*vec4(position,1.0);
  9494. #else
  9495. vPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
  9496. gl_Position=vPosition;
  9497. #endif
  9498. #ifdef DIFFUSE
  9499. #ifdef DIFFUSEUV1
  9500. vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
  9501. #endif
  9502. #ifdef DIFFUSEUV2
  9503. vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
  9504. #endif
  9505. #endif
  9506. #ifdef OPACITY
  9507. #ifdef OPACITYUV1
  9508. vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));
  9509. #endif
  9510. #ifdef OPACITYUV2
  9511. vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));
  9512. #endif
  9513. #endif
  9514. #ifdef EMISSIVE
  9515. #ifdef EMISSIVEUV1
  9516. vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));
  9517. #endif
  9518. #ifdef EMISSIVEUV2
  9519. vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));
  9520. #endif
  9521. #endif
  9522. #ifdef VERTEXALPHA
  9523. vColor=color;
  9524. #endif
  9525. }`;ShaderStore.ShadersStore[name$C]=shader$C;var EffectLayer=function(){function a(i,e){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new Color4},this.neutralColor=new Color4,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new Observable,this.onBeforeRenderMainTextureObservable=new Observable,this.onBeforeComposeObservable=new Observable,this.onBeforeRenderMeshToEffect=new Observable,this.onAfterRenderMeshToEffect=new Observable,this.onAfterComposeObservable=new Observable,this.onSizeChangedObservable=new Observable,this.name=i,this._scene=e||EngineStore.LastCreatedScene,a._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}return Object.defineProperty(a.prototype,"camera",{get:function(){return this._effectLayerOptions.camera},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"renderingGroupId",{get:function(){return this._effectLayerOptions.renderingGroupId},set:function(i){this._effectLayerOptions.renderingGroupId=i},enumerable:!1,configurable:!0}),a.prototype.setMaterialForRendering=function(i,e){this._mainTexture.setMaterialForRendering(i,e)},a.prototype._numInternalDraws=function(){return 1},a.prototype._init=function(i){this._effectLayerOptions=__assign({mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1},i),this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses()},a.prototype._generateIndexBuffer=function(){var i=[];i.push(0),i.push(1),i.push(2),i.push(0),i.push(2),i.push(3),this._indexBuffer=this._engine.createIndexBuffer(i)},a.prototype._generateVertexBuffer=function(){var i=[];i.push(1,1),i.push(-1,1),i.push(-1,-1),i.push(1,-1);var e=new VertexBuffer(this._engine,i,VertexBuffer.PositionKind,!1,!1,2);this._vertexBuffers[VertexBuffer.PositionKind]=e},a.prototype._setMainTextureSize=function(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?Engine.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)},a.prototype._createMainTexture=function(){var i=this;if(this._mainTexture=new RenderTargetTexture("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,0),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=Texture.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=Texture.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._mainTexture.customRenderFunction=function(o,s,c,d){i.onBeforeRenderMainTextureObservable.notifyObservers(i);var _,b=i._scene.getEngine();if(d.length){for(b.setColorWrite(!1),_=0;_<d.length;_++)i._renderSubMesh(d.data[_]);b.setColorWrite(!0)}for(_=0;_<o.length;_++)i._renderSubMesh(o.data[_]);for(_=0;_<s.length;_++)i._renderSubMesh(s.data[_]);var k=b.getAlphaMode();for(_=0;_<c.length;_++)i._renderSubMesh(c.data[_],!0);b.setAlphaMode(k)},this._mainTexture.onClearObservable.add(function(o){o.clear(i.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){var e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(function(){i._scene.getBoundingBoxRenderer().enabled=!i.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(function(){i._scene.getBoundingBoxRenderer().enabled=e})}},a.prototype._addCustomEffectDefines=function(i){},a.prototype._isReady=function(i,e,o){var s,c=this._scene.getEngine(),d=i.getMesh(),_=(s=d._internalAbstractMeshDataInfo._materialForRenderPass)===null||s===void 0?void 0:s[c.currentRenderPassId];if(_)return _.isReadyForSubMesh(d,i,e);var b=i.getMaterial();if(!b)return!1;if(this._useMeshMaterial(i.getRenderingMesh()))return b.isReadyForSubMesh(i.getMesh(),i,e);var k=[],j=[VertexBuffer.PositionKind],$=!1,_e=!1;if(b){var et=b.needAlphaTesting(),tt=b.getAlphaTestTexture(),rt=tt&&tt.hasAlpha&&(b.useAlphaFromDiffuseTexture||b._useAlphaFromAlbedoTexture);tt&&(et||rt)&&(k.push("#define DIFFUSE"),d.isVerticesDataPresent(VertexBuffer.UV2Kind)&&tt.coordinatesIndex===1?(k.push("#define DIFFUSEUV2"),_e=!0):d.isVerticesDataPresent(VertexBuffer.UVKind)&&(k.push("#define DIFFUSEUV1"),$=!0),et&&(k.push("#define ALPHATEST"),k.push("#define ALPHATESTVALUE 0.4")),tt.gammaSpace||k.push("#define DIFFUSE_ISLINEAR"));var it=b.opacityTexture;it&&(k.push("#define OPACITY"),d.isVerticesDataPresent(VertexBuffer.UV2Kind)&&it.coordinatesIndex===1?(k.push("#define OPACITYUV2"),_e=!0):d.isVerticesDataPresent(VertexBuffer.UVKind)&&(k.push("#define OPACITYUV1"),$=!0))}o&&(k.push("#define EMISSIVE"),d.isVerticesDataPresent(VertexBuffer.UV2Kind)&&o.coordinatesIndex===1?(k.push("#define EMISSIVEUV2"),_e=!0):d.isVerticesDataPresent(VertexBuffer.UVKind)&&(k.push("#define EMISSIVEUV1"),$=!0),o.gammaSpace||k.push("#define EMISSIVE_ISLINEAR")),d.isVerticesDataPresent(VertexBuffer.ColorKind)&&d.hasVertexAlpha&&(j.push(VertexBuffer.ColorKind),k.push("#define VERTEXALPHA")),$&&(j.push(VertexBuffer.UVKind),k.push("#define UV1")),_e&&(j.push(VertexBuffer.UV2Kind),k.push("#define UV2"));var nt=new EffectFallbacks;if(d.useBones&&d.computeBonesUsingShaders){j.push(VertexBuffer.MatricesIndicesKind),j.push(VertexBuffer.MatricesWeightsKind),d.numBoneInfluencers>4&&(j.push(VertexBuffer.MatricesIndicesExtraKind),j.push(VertexBuffer.MatricesWeightsExtraKind)),k.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers);var ot=d.skeleton;ot&&ot.isUsingTextureForMatrices?k.push("#define BONETEXTURE"):k.push("#define BonesPerMesh "+(ot?ot.bones.length+1:0)),d.numBoneInfluencers>0&&nt.addCPUSkinningFallback(0,d)}else k.push("#define NUM_BONE_INFLUENCERS 0");var at=d.morphTargetManager,st=0;at&&at.numInfluencers>0&&(k.push("#define MORPHTARGETS"),st=at.numInfluencers,k.push("#define NUM_MORPH_INFLUENCERS "+st),at.isUsingTextureForTargets&&k.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(j,d,st)),e&&(k.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(j),i.getRenderingMesh().hasThinInstances&&k.push("#define THIN_INSTANCES")),this._addCustomEffectDefines(k);var ut=i._getDrawWrapper(void 0,!0),ft=ut.defines,lt=k.join(`
  9526. `);return ft!==lt&&ut.setEffect(this._engine.createEffect("glowMapGeneration",j,["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices"],["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],lt,nt,void 0,void 0,{maxSimultaneousMorphTargets:st}),lt),ut.effect.isReady()},a.prototype.render=function(){for(var i=0;i<this._postProcesses.length;i++)if(!this._postProcesses[i].isReady())return;for(var e=this._scene.getEngine(),o=this._numInternalDraws(),s=!0,c=0;c<o;++c){var d=this._mergeDrawWrapper[c];d||(d=this._mergeDrawWrapper[c]=new DrawWrapper(this._engine),d.setEffect(this._createMergeEffect())),s=s&&d.effect.isReady()}if(!!s){this.onBeforeComposeObservable.notifyObservers(this);for(var _=e.getAlphaMode(),b=0;b<o;++b){var d=this._mergeDrawWrapper[b];e.enableEffect(d),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,d.effect),e.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(d.effect,b)}e.setAlphaMode(_),this.onAfterComposeObservable.notifyObservers(this);var k=this._mainTexture.getSize();this._setMainTextureSize(),(k.width!==this._mainTextureDesiredSize.width||k.height!==this._mainTextureDesiredSize.height)&&this._mainTextureDesiredSize.width!==0&&this._mainTextureDesiredSize.height!==0&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}},a.prototype.hasMesh=function(i){return this.renderingGroupId===-1||i.renderingGroupId===this.renderingGroupId},a.prototype.shouldRender=function(){return this.isEnabled&&this._shouldRender},a.prototype._shouldRenderMesh=function(i){return!0},a.prototype._canRenderMesh=function(i,e){return!e.needAlphaBlendingForMesh(i)},a.prototype._shouldRenderEmissiveTextureForMesh=function(){return!0},a.prototype._renderSubMesh=function(i,e){var o,s;if(e===void 0&&(e=!1),!!this.shouldRender()){var c=i.getMaterial(),d=i.getMesh(),_=i.getReplacementMesh(),b=i.getRenderingMesh(),k=i.getEffectiveMesh(),j=this._scene,$=j.getEngine();if(k._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!!c&&!!this._canRenderMesh(b,c)){var _e=(o=b.overrideMaterialSideOrientation)!==null&&o!==void 0?o:c.sideOrientation,et=b._getWorldMatrixDeterminant();et<0&&(_e=_e===Material.ClockWiseSideOrientation?Material.CounterClockWiseSideOrientation:Material.ClockWiseSideOrientation);var tt=_e===Material.ClockWiseSideOrientation;$.setState(c.backFaceCulling,c.zOffset,void 0,tt,c.cullBackFaces,void 0,c.zOffsetUnits);var rt=b._getInstancesRenderList(i._id,!!_);if(!rt.mustReturn&&!!this._shouldRenderMesh(b)){var it=rt.hardwareInstancedRendering[i._id]||b.hasThinInstances;if(this._setEmissiveTextureAndColor(b,i,c),this.onBeforeRenderMeshToEffect.notifyObservers(d),this._useMeshMaterial(b))b.render(i,it,_||void 0);else if(this._isReady(i,it,this._emissiveTextureAndColor.texture)){var nt=(s=k._internalAbstractMeshDataInfo._materialForRenderPass)===null||s===void 0?void 0:s[$.currentRenderPassId],ot=i._getDrawWrapper();if(!ot&&nt&&(ot=nt._getDrawWrapper()),!ot)return;var at=ot.effect;if($.enableEffect(ot),!it){var st=j.forcePointsCloud?Material.PointFillMode:j.forceWireframe?Material.WireFrameFillMode:c.fillMode;b._bind(i,at,st)}if(nt?nt.bindForSubMesh(k.getWorldMatrix(),k,i):(at.setMatrix("viewProjection",j.getTransformMatrix()),at.setMatrix("world",k.getWorldMatrix()),at.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!nt){var ut=c.needAlphaTesting(),ft=c.getAlphaTestTexture(),lt=ft&&ft.hasAlpha&&(c.useAlphaFromDiffuseTexture||c._useAlphaFromAlbedoTexture);if(ft&&(ut||lt)){at.setTexture("diffuseSampler",ft);var ht=ft.getTextureMatrix();ht&&at.setMatrix("diffuseMatrix",ht)}var pt=c.opacityTexture;if(pt){at.setTexture("opacitySampler",pt),at.setFloat("opacityIntensity",pt.level);var ht=pt.getTextureMatrix();ht&&at.setMatrix("opacityMatrix",ht)}if(this._emissiveTextureAndColor.texture&&(at.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),at.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),b.useBones&&b.computeBonesUsingShaders&&b.skeleton){var mt=b.skeleton;if(mt.isUsingTextureForMatrices){var dt=mt.getTransformMatrixTexture(b);if(!dt)return;at.setTexture("boneSampler",dt),at.setFloat("boneTextureWidth",4*(mt.bones.length+1))}else at.setMatrices("mBones",mt.getTransformMatrices(b))}MaterialHelper.BindMorphTargetParameters(b,at),b.morphTargetManager&&b.morphTargetManager.isUsingTextureForTargets&&b.morphTargetManager._bind(at),e&&$.setAlphaMode(c.alphaMode)}b._processRendering(k,i,at,c.fillMode,rt,it,function(gt,_t){return at.setMatrix("world",_t)})}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(d)}}}},a.prototype._useMeshMaterial=function(i){return!1},a.prototype._rebuild=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&i._rebuild(),this._generateIndexBuffer()},a.prototype._disposeTextureAndPostProcesses=function(){this._mainTexture.dispose();for(var i=0;i<this._postProcesses.length;i++)this._postProcesses[i]&&this._postProcesses[i].dispose();this._postProcesses=[];for(var i=0;i<this._textures.length;i++)this._textures[i]&&this._textures[i].dispose();this._textures=[]},a.prototype.dispose=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&(i.dispose(),this._vertexBuffers[VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(var e=0,o=this._mergeDrawWrapper;e<o.length;e++){var s=o[e];s.dispose()}this._mergeDrawWrapper=[],this._disposeTextureAndPostProcesses();var c=this._scene.effectLayers.indexOf(this,0);c>-1&&this._scene.effectLayers.splice(c,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},a.prototype.getClassName=function(){return"EffectLayer"},a.Parse=function(i,e,o){var s=Tools.Instantiate(i.customType);return s.Parse(i,e,o)},a._SceneComponentInitialization=function(i){throw _WarnImport("EffectLayerSceneComponent")},__decorate([serialize()],a.prototype,"name",void 0),__decorate([serializeAsColor4()],a.prototype,"neutralColor",void 0),__decorate([serialize()],a.prototype,"isEnabled",void 0),__decorate([serializeAsCameraReference()],a.prototype,"camera",null),__decorate([serialize()],a.prototype,"renderingGroupId",null),__decorate([serialize()],a.prototype,"disableBoundingBoxesFromEffectLayer",void 0),a}(),name$B="glowMapMergePixelShader",shader$B=`
  9527. varying vec2 vUV;
  9528. uniform sampler2D textureSampler;
  9529. #ifdef EMISSIVE
  9530. uniform sampler2D textureSampler2;
  9531. #endif
  9532. uniform float offset;
  9533. void main(void) {
  9534. vec4 baseColor=texture2D(textureSampler,vUV);
  9535. #ifdef EMISSIVE
  9536. baseColor+=texture2D(textureSampler2,vUV);
  9537. baseColor*=offset;
  9538. #else
  9539. baseColor.a=abs(offset-baseColor.a);
  9540. #ifdef STROKE
  9541. float alpha=smoothstep(.0,.1,baseColor.a);
  9542. baseColor.a=alpha;
  9543. baseColor.rgb=baseColor.rgb*alpha;
  9544. #endif
  9545. #endif
  9546. #if LDR
  9547. baseColor=clamp(baseColor,0.,1.0);
  9548. #endif
  9549. gl_FragColor=baseColor;
  9550. }`;ShaderStore.ShadersStore[name$B]=shader$B;var name$A="glowMapMergeVertexShader",shader$A=`
  9551. attribute vec2 position;
  9552. varying vec2 vUV;
  9553. const vec2 madd=vec2(0.5,0.5);
  9554. void main(void) {
  9555. vUV=position*madd+madd;
  9556. gl_Position=vec4(position,0.0,1.0);
  9557. }`;ShaderStore.ShadersStore[name$A]=shader$A;AbstractScene.AddParser(SceneComponentConstants.NAME_EFFECTLAYER,function(a,i,e,o){if(a.effectLayers){e.effectLayers||(e.effectLayers=new Array);for(var s=0;s<a.effectLayers.length;s++){var c=EffectLayer.Parse(a.effectLayers[s],i,o);e.effectLayers.push(c)}}});AbstractScene.prototype.removeEffectLayer=function(a){var i=this.effectLayers.indexOf(a);return i!==-1&&this.effectLayers.splice(i,1),i};AbstractScene.prototype.addEffectLayer=function(a){this.effectLayers.push(a)};var EffectLayerSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=i,this._engine=i.getEngine(),i.effectLayers=new Array}return a.prototype.register=function(){this.scene._isReadyForMeshStage.registerStep(SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)},a.prototype.rebuild=function(){for(var i=this.scene.effectLayers,e=0,o=i;e<o.length;e++){var s=o[e];s._rebuild()}},a.prototype.serialize=function(i){i.effectLayers=[];for(var e=this.scene.effectLayers,o=0,s=e;o<s.length;o++){var c=s[o];c.serialize&&i.effectLayers.push(c.serialize())}},a.prototype.addFromContainer=function(i){var e=this;!i.effectLayers||i.effectLayers.forEach(function(o){e.scene.addEffectLayer(o)})},a.prototype.removeFromContainer=function(i,e){var o=this;!i.effectLayers||i.effectLayers.forEach(function(s){o.scene.removeEffectLayer(s),e&&s.dispose()})},a.prototype.dispose=function(){for(var i=this.scene.effectLayers;i.length;)i[0].dispose()},a.prototype._isReadyForMesh=function(i,e){for(var o=this._engine.currentRenderPassId,s=this.scene.effectLayers,c=0,d=s;c<d.length;c++){var _=d[c];if(!!_.hasMesh(i)){var b=_._mainTexture;this._engine.currentRenderPassId=b.renderPassId;for(var k=0,j=i.subMeshes;k<j.length;k++){var $=j[k];if(!_.isReady($,e))return this._engine.currentRenderPassId=o,!1}}}return this._engine.currentRenderPassId=o,!0},a.prototype._renderMainTexture=function(i){this._renderEffects=!1,this._needStencil=!1;var e=!1,o=this.scene.effectLayers;if(o&&o.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(var s=0,c=o;s<c.length;s++){var d=c[s];if(d.shouldRender()&&(!d.camera||d.camera.cameraRigMode===Camera$1.RIG_MODE_NONE&&i===d.camera||d.camera.cameraRigMode!==Camera$1.RIG_MODE_NONE&&d.camera._rigCameras.indexOf(i)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||d.needStencil();var _=d._mainTexture;_._shouldRender()&&(this.scene.incrementRenderId(),_.render(!1,!1),e=!0)}}this.scene.incrementRenderId()}return e},a.prototype._setStencil=function(){this._needStencil&&this._engine.setStencilBuffer(!0)},a.prototype._setStencilBack=function(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},a.prototype._draw=function(i){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var e=this.scene.effectLayers,o=0;o<e.length;o++){var s=e[o];s.renderingGroupId===i&&s.shouldRender()&&s.render()}this._engine.setDepthBuffer(!0)}},a.prototype._drawCamera=function(){this._renderEffects&&this._draw(-1)},a.prototype._drawRenderingGroup=function(i){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(i)},a}();EffectLayer._SceneComponentInitialization=function(a){var i=a._getComponent(SceneComponentConstants.NAME_EFFECTLAYER);i||(i=new EffectLayerSceneComponent(a),a._addComponent(i))};AbstractScene.prototype.getGlowLayerByName=function(a){for(var i=0;i<this.effectLayers.length;i++)if(this.effectLayers[i].name===a&&this.effectLayers[i].getEffectName()===GlowLayer.EffectName)return this.effectLayers[i];return null};var GlowLayer=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o)||this;return c._intensity=1,c._includedOnlyMeshes=[],c._excludedMeshes=[],c._meshesUsingTheirOwnMaterials=[],c.neutralColor=new Color4(0,0,0,1),c._options=__assign({mainTextureRatio:i.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1},s),c._init({alphaBlendingMode:c._options.alphaBlendingMode,camera:c._options.camera,mainTextureFixedSize:c._options.mainTextureFixedSize,mainTextureRatio:c._options.mainTextureRatio,renderingGroupId:c._options.renderingGroupId}),c}return Object.defineProperty(i.prototype,"blurKernelSize",{get:function(){return this._horizontalBlurPostprocess1.kernel},set:function(e){this._horizontalBlurPostprocess1.kernel=e,this._verticalBlurPostprocess1.kernel=e,this._horizontalBlurPostprocess2.kernel=e,this._verticalBlurPostprocess2.kernel=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"intensity",{get:function(){return this._intensity},set:function(e){this._intensity=e},enumerable:!1,configurable:!0}),i.prototype.getEffectName=function(){return i.EffectName},i.prototype._createMergeEffect=function(){var e=`#define EMISSIVE
  9558. `;return this._options.ldrMerge&&(e+=`#define LDR
  9559. `),this._engine.createEffect("glowMapMerge",[VertexBuffer.PositionKind],["offset"],["textureSampler","textureSampler2"],e)},i.prototype._createTextureAndPostProcesses=function(){var e=this,o=this._mainTextureDesiredSize.width,s=this._mainTextureDesiredSize.height;o=this._engine.needPOTTextures?Engine.GetExponentOfTwo(o,this._maxSize):o,s=this._engine.needPOTTextures?Engine.GetExponentOfTwo(s,this._maxSize):s;var c=0;this._engine.getCaps().textureHalfFloatRender?c=2:c=0,this._blurTexture1=new RenderTargetTexture("GlowLayerBlurRTT",{width:o,height:s},this._scene,!1,!0,c),this._blurTexture1.wrapU=Texture.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=Texture.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;var d=Math.floor(o/2),_=Math.floor(s/2);this._blurTexture2=new RenderTargetTexture("GlowLayerBlurRTT2",{width:d,height:_},this._scene,!1,!0,c),this._blurTexture2.wrapU=Texture.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=Texture.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2],this._horizontalBlurPostprocess1=new BlurPostProcess("GlowLayerHBP1",new Vector2(1,0),this._options.blurKernelSize/2,{width:o,height:s},null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),this._horizontalBlurPostprocess1.width=o,this._horizontalBlurPostprocess1.height=s,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(function(b){b.setTexture("textureSampler",e._mainTexture)}),this._verticalBlurPostprocess1=new BlurPostProcess("GlowLayerVBP1",new Vector2(0,1),this._options.blurKernelSize/2,{width:o,height:s},null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),this._horizontalBlurPostprocess2=new BlurPostProcess("GlowLayerHBP2",new Vector2(1,0),this._options.blurKernelSize/2,{width:d,height:_},null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),this._horizontalBlurPostprocess2.width=d,this._horizontalBlurPostprocess2.height=_,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(function(b){b.setTexture("textureSampler",e._blurTexture1)}),this._verticalBlurPostprocess2=new BlurPostProcess("GlowLayerVBP2",new Vector2(0,1),this._options.blurKernelSize/2,{width:d,height:_},null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(function(){var b=e._blurTexture1.renderTarget;if(b){e._scene.postProcessManager.directRender(e._postProcesses1,b,!0);var k=e._blurTexture2.renderTarget;k&&e._scene.postProcessManager.directRender(e._postProcesses2,k,!0),e._engine.unBindFramebuffer(k!=null?k:b,!0)}}),this._postProcesses.map(function(b){b.autoClear=!1})},i.prototype.isReady=function(e,o){var s=e.getMaterial(),c=e.getRenderingMesh();if(!s||!c)return!1;var d=s.emissiveTexture;return a.prototype._isReady.call(this,e,o,d)},i.prototype.needStencil=function(){return!1},i.prototype._canRenderMesh=function(e,o){return!0},i.prototype._internalRender=function(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);var o=this._engine,s=o.getStencilBuffer();o.setStencilBuffer(!1),o.drawElementsType(Material.TriangleFillMode,0,6),o.setStencilBuffer(s)},i.prototype._setEmissiveTextureAndColor=function(e,o,s){var c,d=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,o,s):s?(this._emissiveTextureAndColor.texture=s.emissiveTexture,this._emissiveTextureAndColor.texture&&(d=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,o,s,this._emissiveTextureAndColor.color);else if(s.emissiveColor){var _=(c=s.emissiveIntensity)!==null&&c!==void 0?c:1;d*=_,this._emissiveTextureAndColor.color.set(s.emissiveColor.r*d,s.emissiveColor.g*d,s.emissiveColor.b*d,s.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)},i.prototype._shouldRenderMesh=function(e){return this.hasMesh(e)},i.prototype._addCustomEffectDefines=function(e){e.push("#define GLOW")},i.prototype.addExcludedMesh=function(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)},i.prototype.removeExcludedMesh=function(e){var o=this._excludedMeshes.indexOf(e.uniqueId);o!==-1&&this._excludedMeshes.splice(o,1)},i.prototype.addIncludedOnlyMesh=function(e){this._includedOnlyMeshes.indexOf(e.uniqueId)===-1&&this._includedOnlyMeshes.push(e.uniqueId)},i.prototype.removeIncludedOnlyMesh=function(e){var o=this._includedOnlyMeshes.indexOf(e.uniqueId);o!==-1&&this._includedOnlyMeshes.splice(o,1)},i.prototype.hasMesh=function(e){return a.prototype.hasMesh.call(this,e)?this._includedOnlyMeshes.length?this._includedOnlyMeshes.indexOf(e.uniqueId)!==-1:this._excludedMeshes.length?this._excludedMeshes.indexOf(e.uniqueId)===-1:!0:!1},i.prototype._useMeshMaterial=function(e){return this._meshesUsingTheirOwnMaterials.length==0?!1:this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1},i.prototype.referenceMeshToUseItsOwnMaterial=function(e){var o=this;this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(function(){o._disposeMesh(e)})},i.prototype.unReferenceMeshFromUsingItsOwnMaterial=function(e){for(var o=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);o>=0;)this._meshesUsingTheirOwnMaterials.splice(o,1),o=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)},i.prototype._disposeMesh=function(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)},i.prototype.getClassName=function(){return"GlowLayer"},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);e.customType="BABYLON.GlowLayer";var o;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(o=0;o<this._includedOnlyMeshes.length;o++){var s=this._scene.getMeshByUniqueId(this._includedOnlyMeshes[o]);s&&e.includedMeshes.push(s.id)}if(e.excludedMeshes=[],this._excludedMeshes.length)for(o=0;o<this._excludedMeshes.length;o++){var s=this._scene.getMeshByUniqueId(this._excludedMeshes[o]);s&&e.excludedMeshes.push(s.id)}return e},i.Parse=function(e,o,s){var c=SerializationHelper.Parse(function(){return new i(e.name,o,e.options)},e,o,s),d;for(d=0;d<e.excludedMeshes.length;d++){var _=o.getMeshById(e.excludedMeshes[d]);_&&c.addExcludedMesh(_)}for(d=0;d<e.includedMeshes.length;d++){var _=o.getMeshById(e.includedMeshes[d]);_&&c.addIncludedOnlyMesh(_)}return c},i.EffectName="GlowLayer",i.DefaultBlurKernelSize=32,i.DefaultTextureRatio=.5,__decorate([serialize()],i.prototype,"blurKernelSize",null),__decorate([serialize()],i.prototype,"intensity",null),__decorate([serialize("options")],i.prototype,"_options",void 0),i}(EffectLayer);RegisterClass("BABYLON.GlowLayer",GlowLayer);var name$z="glowBlurPostProcessPixelShader",shader$z=`
  9560. varying vec2 vUV;
  9561. uniform sampler2D textureSampler;
  9562. uniform vec2 screenSize;
  9563. uniform vec2 direction;
  9564. uniform float blurWidth;
  9565. float getLuminance(vec3 color)
  9566. {
  9567. return dot(color,vec3(0.2126,0.7152,0.0722));
  9568. }
  9569. void main(void)
  9570. {
  9571. float weights[7];
  9572. weights[0]=0.05;
  9573. weights[1]=0.1;
  9574. weights[2]=0.2;
  9575. weights[3]=0.3;
  9576. weights[4]=0.2;
  9577. weights[5]=0.1;
  9578. weights[6]=0.05;
  9579. vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);
  9580. vec2 texelStep=texelSize*direction*blurWidth;
  9581. vec2 start=vUV-3.0*texelStep;
  9582. vec4 baseColor=vec4(0.,0.,0.,0.);
  9583. vec2 texelOffset=vec2(0.,0.);
  9584. for (int i=0; i<7; i++)
  9585. {
  9586. vec4 texel=texture2D(textureSampler,start+texelOffset);
  9587. baseColor.a+=texel.a*weights[i];
  9588. float luminance=getLuminance(baseColor.rgb);
  9589. float luminanceTexel=getLuminance(texel.rgb);
  9590. float choice=step(luminanceTexel,luminance);
  9591. baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;
  9592. texelOffset+=texelStep;
  9593. }
  9594. gl_FragColor=baseColor;
  9595. }`;ShaderStore.ShadersStore[name$z]=shader$z;AbstractScene.prototype.getHighlightLayerByName=function(a){for(var i=0;i<this.effectLayers.length;i++)if(this.effectLayers[i].name===a&&this.effectLayers[i].getEffectName()===HighlightLayer.EffectName)return this.effectLayers[i];return null};var GlowBlurPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){_===void 0&&(_=Texture.BILINEAR_SAMPLINGMODE);var j=a.call(this,e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,c,d,_,b,k)||this;return j.direction=o,j.kernel=s,j.onApplyObservable.add(function($){$.setFloat2("screenSize",j.width,j.height),$.setVector2("direction",j.direction),$.setFloat("blurWidth",j.kernel)}),j}return i}(PostProcess),HighlightLayer=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o)||this;return c.name=e,c.innerGlow=!0,c.outerGlow=!0,c.onBeforeBlurObservable=new Observable,c.onAfterBlurObservable=new Observable,c._instanceGlowingMeshStencilReference=i.GlowingMeshStencilReference++,c._meshes={},c._excludedMeshes={},c.neutralColor=i.NeutralColor,c._engine.isStencilEnable||Logger$2.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),c._options=__assign({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1},s),c._init({alphaBlendingMode:c._options.alphaBlendingMode,camera:c._options.camera,mainTextureFixedSize:c._options.mainTextureFixedSize,mainTextureRatio:c._options.mainTextureRatio,renderingGroupId:c._options.renderingGroupId}),c._shouldRender=!1,c}return Object.defineProperty(i.prototype,"blurHorizontalSize",{get:function(){return this._horizontalBlurPostprocess.kernel},set:function(e){this._horizontalBlurPostprocess.kernel=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"blurVerticalSize",{get:function(){return this._verticalBlurPostprocess.kernel},set:function(e){this._verticalBlurPostprocess.kernel=e},enumerable:!1,configurable:!0}),i.prototype.getEffectName=function(){return i.EffectName},i.prototype._numInternalDraws=function(){return 2},i.prototype._createMergeEffect=function(){return this._engine.createEffect("glowMapMerge",[VertexBuffer.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE
  9596. `:void 0)},i.prototype._createTextureAndPostProcesses=function(){var e=this,o=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,s=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;o=this._engine.needPOTTextures?Engine.GetExponentOfTwo(o,this._maxSize):o,s=this._engine.needPOTTextures?Engine.GetExponentOfTwo(s,this._maxSize):s;var c=0;this._engine.getCaps().textureHalfFloatRender?c=2:c=0,this._blurTexture=new RenderTargetTexture("HighlightLayerBlurRTT",{width:o,height:s},this._scene,!1,!0,c),this._blurTexture.wrapU=Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(function(d){d.setTexture("textureSampler",e._mainTexture)}),this._horizontalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerHBP",new Vector2(1,0),this._options.blurHorizontalSize,1,null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(function(d){d.setFloat2("screenSize",o,s)}),this._verticalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerVBP",new Vector2(0,1),this._options.blurVerticalSize,1,null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(function(d){d.setFloat2("screenSize",o,s)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new BlurPostProcess("HighlightLayerHBP",new Vector2(1,0),this._options.blurHorizontalSize/2,{width:o,height:s},null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),this._horizontalBlurPostprocess.width=o,this._horizontalBlurPostprocess.height=s,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(function(d){d.setTexture("textureSampler",e._mainTexture)}),this._verticalBlurPostprocess=new BlurPostProcess("HighlightLayerVBP",new Vector2(0,1),this._options.blurVerticalSize/2,{width:o,height:s},null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(function(){e.onBeforeBlurObservable.notifyObservers(e);var d=e._blurTexture.renderTarget;d&&(e._scene.postProcessManager.directRender(e._postProcesses,d,!0),e._engine.unBindFramebuffer(d,!0)),e.onAfterBlurObservable.notifyObservers(e)}),this._postProcesses.map(function(d){d.autoClear=!1})},i.prototype.needStencil=function(){return!0},i.prototype.isReady=function(e,o){var s=e.getMaterial(),c=e.getRenderingMesh();if(!s||!c||!this._meshes)return!1;var d=null,_=this._meshes[c.uniqueId];return _&&_.glowEmissiveOnly&&s&&(d=s.emissiveTexture),a.prototype._isReady.call(this,e,o,d)},i.prototype._internalRender=function(e,o){e.setTexture("textureSampler",this._blurTexture);var s=this._engine;s.cacheStencilState(),s.setStencilOperationPass(7681),s.setStencilOperationFail(7680),s.setStencilOperationDepthFail(7680),s.setStencilMask(0),s.setStencilBuffer(!0),s.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&o===0&&(e.setFloat("offset",0),s.setStencilFunction(517),s.drawElementsType(Material.TriangleFillMode,0,6)),this.innerGlow&&o===1&&(e.setFloat("offset",1),s.setStencilFunction(514),s.drawElementsType(Material.TriangleFillMode,0,6)),s.restoreStencilState()},i.prototype.shouldRender=function(){return a.prototype.shouldRender.call(this)?!!this._meshes:!1},i.prototype._shouldRenderMesh=function(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!a.prototype.hasMesh.call(this,e))},i.prototype._canRenderMesh=function(e,o){return!0},i.prototype._addCustomEffectDefines=function(e){e.push("#define HIGHLIGHT")},i.prototype._setEmissiveTextureAndColor=function(e,o,s){var c=this._meshes[e.uniqueId];c?this._emissiveTextureAndColor.color.set(c.color.r,c.color.g,c.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),c&&c.glowEmissiveOnly&&s?(this._emissiveTextureAndColor.texture=s.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null},i.prototype.addExcludedMesh=function(e){if(!!this._excludedMeshes){var o=this._excludedMeshes[e.uniqueId];o||(this._excludedMeshes[e.uniqueId]={mesh:e,beforeBind:e.onBeforeBindObservable.add(function(s){s.getEngine().setStencilBuffer(!1)}),afterRender:e.onAfterRenderObservable.add(function(s){s.getEngine().setStencilBuffer(!0)})})}},i.prototype.removeExcludedMesh=function(e){if(!!this._excludedMeshes){var o=this._excludedMeshes[e.uniqueId];o&&(o.beforeBind&&e.onBeforeBindObservable.remove(o.beforeBind),o.afterRender&&e.onAfterRenderObservable.remove(o.afterRender)),this._excludedMeshes[e.uniqueId]=null}},i.prototype.hasMesh=function(e){return!this._meshes||!a.prototype.hasMesh.call(this,e)?!1:this._meshes[e.uniqueId]!==void 0&&this._meshes[e.uniqueId]!==null},i.prototype.addMesh=function(e,o,s){var c=this;if(s===void 0&&(s=!1),!!this._meshes){var d=this._meshes[e.uniqueId];d?d.color=o:(this._meshes[e.uniqueId]={mesh:e,color:o,observerHighlight:e.onBeforeBindObservable.add(function(_){c.isEnabled&&(c._excludedMeshes&&c._excludedMeshes[_.uniqueId]?c._defaultStencilReference(_):_.getScene().getEngine().setStencilFunctionReference(c._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(function(_){c.isEnabled&&c._defaultStencilReference(_)}),glowEmissiveOnly:s},e.onDisposeObservable.add(function(){c._disposeMesh(e)})),this._shouldRender=!0}},i.prototype.removeMesh=function(e){if(!!this._meshes){var o=this._meshes[e.uniqueId];o&&(o.observerHighlight&&e.onBeforeBindObservable.remove(o.observerHighlight),o.observerDefault&&e.onAfterRenderObservable.remove(o.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(var s in this._meshes)if(this._meshes[s]){this._shouldRender=!0;break}}},i.prototype.removeAllMeshes=function(){if(!!this._meshes){for(var e in this._meshes)if(this._meshes.hasOwnProperty(e)){var o=this._meshes[e];o&&this.removeMesh(o.mesh)}}},i.prototype._defaultStencilReference=function(e){e.getScene().getEngine().setStencilFunctionReference(i.NormalMeshStencilReference)},i.prototype._disposeMesh=function(e){this.removeMesh(e),this.removeExcludedMesh(e)},i.prototype.dispose=function(){if(this._meshes){for(var e in this._meshes){var o=this._meshes[e];o&&o.mesh&&(o.observerHighlight&&o.mesh.onBeforeBindObservable.remove(o.observerHighlight),o.observerDefault&&o.mesh.onAfterRenderObservable.remove(o.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(var e in this._excludedMeshes){var o=this._excludedMeshes[e];o&&(o.beforeBind&&o.mesh.onBeforeBindObservable.remove(o.beforeBind),o.afterRender&&o.mesh.onAfterRenderObservable.remove(o.afterRender))}this._excludedMeshes=null}a.prototype.dispose.call(this)},i.prototype.getClassName=function(){return"HighlightLayer"},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(var o in this._meshes){var s=this._meshes[o];s&&e.meshes.push({glowEmissiveOnly:s.glowEmissiveOnly,color:s.color.asArray(),meshId:s.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(var c in this._excludedMeshes){var d=this._excludedMeshes[c];d&&e.excludedMeshes.push(d.mesh.id)}return e},i.Parse=function(e,o,s){var c=SerializationHelper.Parse(function(){return new i(e.name,o,e.options)},e,o,s),d;for(d=0;d<e.excludedMeshes.length;d++){var _=o.getMeshById(e.excludedMeshes[d]);_&&c.addExcludedMesh(_)}for(d=0;d<e.meshes.length;d++){var b=e.meshes[d],_=o.getMeshById(b.meshId);_&&c.addMesh(_,Color3.FromArray(b.color),b.glowEmissiveOnly)}return c},i.EffectName="HighlightLayer",i.NeutralColor=new Color4(0,0,0,0),i.GlowingMeshStencilReference=2,i.NormalMeshStencilReference=1,__decorate([serialize()],i.prototype,"innerGlow",void 0),__decorate([serialize()],i.prototype,"outerGlow",void 0),__decorate([serialize()],i.prototype,"blurHorizontalSize",null),__decorate([serialize()],i.prototype,"blurVerticalSize",null),__decorate([serialize("options")],i.prototype,"_options",void 0),i}(EffectLayer);RegisterClass("BABYLON.HighlightLayer",HighlightLayer);var name$y="sharpenPixelShader",shader$y=`
  9597. varying vec2 vUV;
  9598. uniform sampler2D textureSampler;
  9599. uniform vec2 screenSize;
  9600. uniform vec2 sharpnessAmounts;
  9601. void main(void)
  9602. {
  9603. vec2 onePixel=vec2(1.0,1.0)/screenSize;
  9604. vec4 color=texture2D(textureSampler,vUV);
  9605. vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +
  9606. texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +
  9607. texture2D(textureSampler,vUV+onePixel*vec2(1,0)) +
  9608. texture2D(textureSampler,vUV+onePixel*vec2(0,1)) -
  9609. color*4.0;
  9610. gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);
  9611. }`;ShaderStore.ShadersStore[name$y]=shader$y;var SharpenPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){b===void 0&&(b=0),k===void 0&&(k=!1);var j=a.call(this,e,"sharpen",["sharpnessAmounts","screenSize"],null,o,s,c,d,_,null,b,void 0,null,k)||this;return j.colorAmount=1,j.edgeAmount=.3,j.onApply=function($){$.setFloat2("screenSize",j.width,j.height),$.setFloat2("sharpnessAmounts",j.edgeAmount,j.colorAmount)},j}return i.prototype.getClassName=function(){return"SharpenPostProcess"},i._Parse=function(e,o,s,c){return SerializationHelper.Parse(function(){return new i(e.name,e.options,o,e.renderTargetSamplingMode,s.getEngine(),e.textureType,e.reusable)},e,s,c)},__decorate([serialize()],i.prototype,"colorAmount",void 0),__decorate([serialize()],i.prototype,"edgeAmount",void 0),i}(PostProcess);RegisterClass("BABYLON.SharpenPostProcess",SharpenPostProcess);var name$x="imageProcessingPixelShader",shader$x=`
  9612. varying vec2 vUV;
  9613. uniform sampler2D textureSampler;
  9614. #include<imageProcessingDeclaration>
  9615. #include<helperFunctions>
  9616. #include<imageProcessingFunctions>
  9617. void main(void)
  9618. {
  9619. vec4 result=texture2D(textureSampler,vUV);
  9620. #ifdef IMAGEPROCESSING
  9621. #ifndef FROMLINEARSPACE
  9622. result.rgb=toLinearSpace(result.rgb);
  9623. #endif
  9624. result=applyImageProcessing(result);
  9625. #else
  9626. #ifdef FROMLINEARSPACE
  9627. result=applyImageProcessing(result);
  9628. #endif
  9629. #endif
  9630. gl_FragColor=result;
  9631. }`;ShaderStore.ShadersStore[name$x]=shader$x;var ImageProcessingPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){s===void 0&&(s=null),b===void 0&&(b=0);var j=a.call(this,e,"imageProcessing",[],[],o,s,c,d,_,null,b,"postprocess",null,!0)||this;return j._fromLinearSpace=!0,j._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},k?(k.applyByPostProcess=!0,j._attachImageProcessingConfiguration(k,!0),j.fromLinearSpace=!1):(j._attachImageProcessingConfiguration(null,!0),j.imageProcessingConfiguration.applyByPostProcess=!0),j.onApply=function($){j.imageProcessingConfiguration.bind($,j.aspectRatio)},j}return Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)},enumerable:!1,configurable:!0}),i.prototype._attachImageProcessingConfiguration=function(e,o){var s=this;if(o===void 0&&(o=!1),e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{var c=null,d=this.getEngine(),_=this.getCamera();if(_)c=_.getScene();else if(d&&d.scenes){var b=d.scenes;c=b[b.length-1]}else c=EngineStore.LastCreatedScene;c?this._imageProcessingConfiguration=c.imageProcessingConfiguration:this._imageProcessingConfiguration=new ImageProcessingConfiguration}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){s._updateParameters()})),o||this._updateParameters()}},Object.defineProperty(i.prototype,"isSupported",{get:function(){var e=this.getEffect();return!e||e.isSupported},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"colorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"colorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"colorGradingTexture",{get:function(){return this.imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"colorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"exposure",{get:function(){return this.imageProcessingConfiguration.exposure},set:function(e){this.imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"toneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"toneMappingType",{get:function(){return this._imageProcessingConfiguration.toneMappingType},set:function(e){this._imageProcessingConfiguration.toneMappingType=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"contrast",{get:function(){return this.imageProcessingConfiguration.contrast},set:function(e){this.imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteStretch",{get:function(){return this.imageProcessingConfiguration.vignetteStretch},set:function(e){this.imageProcessingConfiguration.vignetteStretch=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteCentreX",{get:function(){return this.imageProcessingConfiguration.vignetteCentreX},set:function(e){this.imageProcessingConfiguration.vignetteCentreX=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteCentreY",{get:function(){return this.imageProcessingConfiguration.vignetteCentreY},set:function(e){this.imageProcessingConfiguration.vignetteCentreY=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteWeight",{get:function(){return this.imageProcessingConfiguration.vignetteWeight},set:function(e){this.imageProcessingConfiguration.vignetteWeight=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteColor",{get:function(){return this.imageProcessingConfiguration.vignetteColor},set:function(e){this.imageProcessingConfiguration.vignetteColor=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteCameraFov",{get:function(){return this.imageProcessingConfiguration.vignetteCameraFov},set:function(e){this.imageProcessingConfiguration.vignetteCameraFov=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteBlendMode",{get:function(){return this.imageProcessingConfiguration.vignetteBlendMode},set:function(e){this.imageProcessingConfiguration.vignetteBlendMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"vignetteEnabled",{get:function(){return this.imageProcessingConfiguration.vignetteEnabled},set:function(e){this.imageProcessingConfiguration.vignetteEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"fromLinearSpace",{get:function(){return this._fromLinearSpace},set:function(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"ImageProcessingPostProcess"},i.prototype._updateParameters=function(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);var e="";for(var o in this._defines)this._defines[o]&&(e+="#define "+o+`;\r
  9632. `);var s=["textureSampler"],c=["scale"];ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareSamplers(s,this._defines),ImageProcessingConfiguration.PrepareUniforms(c,this._defines)),this.updateEffect(e,c,s)},i.prototype.dispose=function(e){a.prototype.dispose.call(this,e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)},__decorate([serialize()],i.prototype,"_fromLinearSpace",void 0),i}(PostProcess),name$w="chromaticAberrationPixelShader",shader$w=`
  9633. uniform sampler2D textureSampler;
  9634. uniform float chromatic_aberration;
  9635. uniform float radialIntensity;
  9636. uniform vec2 direction;
  9637. uniform vec2 centerPosition;
  9638. uniform float screen_width;
  9639. uniform float screen_height;
  9640. varying vec2 vUV;
  9641. void main(void)
  9642. {
  9643. vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);
  9644. vec2 directionOfEffect=direction;
  9645. if(directionOfEffect.x == 0. && directionOfEffect.y == 0.){
  9646. directionOfEffect=normalize(centered_screen_pos);
  9647. }
  9648. float radius2=centered_screen_pos.x*centered_screen_pos.x
  9649. +centered_screen_pos.y*centered_screen_pos.y;
  9650. float radius=sqrt(radius2);
  9651. vec4 original=texture2D(textureSampler,vUV);
  9652. vec3 ref_indices=vec3(-0.3,0.0,0.3);
  9653. float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;
  9654. float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;
  9655. vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);
  9656. vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);
  9657. vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);
  9658. original.r=texture2D(textureSampler,ref_coords_r).r;
  9659. original.g=texture2D(textureSampler,ref_coords_g).g;
  9660. original.b=texture2D(textureSampler,ref_coords_b).b;
  9661. original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);
  9662. gl_FragColor=original;
  9663. }`;ShaderStore.ShadersStore[name$w]=shader$w;var ChromaticAberrationPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$){j===void 0&&(j=0),$===void 0&&($=!1);var _e=a.call(this,e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],c,d,_,b,k,null,j,void 0,null,$)||this;return _e.aberrationAmount=30,_e.radialIntensity=0,_e.direction=new Vector2(.707,.707),_e.centerPosition=new Vector2(.5,.5),_e.screenWidth=o,_e.screenHeight=s,_e.onApplyObservable.add(function(et){et.setFloat("chromatic_aberration",_e.aberrationAmount),et.setFloat("screen_width",o),et.setFloat("screen_height",s),et.setFloat("radialIntensity",_e.radialIntensity),et.setFloat2("direction",_e.direction.x,_e.direction.y),et.setFloat2("centerPosition",_e.centerPosition.x,_e.centerPosition.y)}),_e}return i.prototype.getClassName=function(){return"ChromaticAberrationPostProcess"},i._Parse=function(e,o,s,c){return SerializationHelper.Parse(function(){return new i(e.name,e.screenWidth,e.screenHeight,e.options,o,e.renderTargetSamplingMode,s.getEngine(),e.reusable,e.textureType,!1)},e,s,c)},__decorate([serialize()],i.prototype,"aberrationAmount",void 0),__decorate([serialize()],i.prototype,"radialIntensity",void 0),__decorate([serialize()],i.prototype,"direction",void 0),__decorate([serialize()],i.prototype,"centerPosition",void 0),__decorate([serialize()],i.prototype,"screenWidth",void 0),__decorate([serialize()],i.prototype,"screenHeight",void 0),i}(PostProcess);RegisterClass("BABYLON.ChromaticAberrationPostProcess",ChromaticAberrationPostProcess);var name$v="grainPixelShader",shader$v=`#include<helperFunctions>
  9664. uniform sampler2D textureSampler;
  9665. uniform float intensity;
  9666. uniform float animatedSeed;
  9667. varying vec2 vUV;
  9668. void main(void)
  9669. {
  9670. gl_FragColor=texture2D(textureSampler,vUV);
  9671. vec2 seed=vUV*(animatedSeed);
  9672. float grain=dither(seed,intensity);
  9673. float lum=getLuminance(gl_FragColor.rgb);
  9674. float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;
  9675. gl_FragColor.rgb+=grain*grainAmount;
  9676. gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);
  9677. }`;ShaderStore.ShadersStore[name$v]=shader$v;var GrainPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){b===void 0&&(b=0),k===void 0&&(k=!1);var j=a.call(this,e,"grain",["intensity","animatedSeed"],[],o,s,c,d,_,null,b,void 0,null,k)||this;return j.intensity=30,j.animated=!1,j.onApplyObservable.add(function($){$.setFloat("intensity",j.intensity),$.setFloat("animatedSeed",j.animated?Math.random()+1:1)}),j}return i.prototype.getClassName=function(){return"GrainPostProcess"},i._Parse=function(e,o,s,c){return SerializationHelper.Parse(function(){return new i(e.name,e.options,o,e.renderTargetSamplingMode,s.getEngine(),e.reusable)},e,s,c)},__decorate([serialize()],i.prototype,"intensity",void 0),__decorate([serialize()],i.prototype,"animated",void 0),i}(PostProcess);RegisterClass("BABYLON.GrainPostProcess",GrainPostProcess);var name$u="fxaaPixelShader",shader$u=`uniform sampler2D textureSampler;
  9678. uniform vec2 texelSize;
  9679. varying vec2 vUV;
  9680. varying vec2 sampleCoordS;
  9681. varying vec2 sampleCoordE;
  9682. varying vec2 sampleCoordN;
  9683. varying vec2 sampleCoordW;
  9684. varying vec2 sampleCoordNW;
  9685. varying vec2 sampleCoordSE;
  9686. varying vec2 sampleCoordNE;
  9687. varying vec2 sampleCoordSW;
  9688. const float fxaaQualitySubpix=1.0;
  9689. const float fxaaQualityEdgeThreshold=0.166;
  9690. const float fxaaQualityEdgeThresholdMin=0.0833;
  9691. const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);
  9692. #define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)
  9693. void main(){
  9694. vec2 posM;
  9695. posM.x=vUV.x;
  9696. posM.y=vUV.y;
  9697. vec4 rgbyM=texture2D(textureSampler,vUV,0.0);
  9698. float lumaM=FxaaLuma(rgbyM);
  9699. float lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));
  9700. float lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));
  9701. float lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));
  9702. float lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));
  9703. float maxSM=max(lumaS,lumaM);
  9704. float minSM=min(lumaS,lumaM);
  9705. float maxESM=max(lumaE,maxSM);
  9706. float minESM=min(lumaE,minSM);
  9707. float maxWN=max(lumaN,lumaW);
  9708. float minWN=min(lumaN,lumaW);
  9709. float rangeMax=max(maxWN,maxESM);
  9710. float rangeMin=min(minWN,minESM);
  9711. float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;
  9712. float range=rangeMax-rangeMin;
  9713. float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);
  9714. #ifndef MALI
  9715. if(range<rangeMaxClamped)
  9716. {
  9717. gl_FragColor=rgbyM;
  9718. return;
  9719. }
  9720. #endif
  9721. float lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));
  9722. float lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));
  9723. float lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));
  9724. float lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));
  9725. float lumaNS=lumaN+lumaS;
  9726. float lumaWE=lumaW+lumaE;
  9727. float subpixRcpRange=1.0/range;
  9728. float subpixNSWE=lumaNS+lumaWE;
  9729. float edgeHorz1=(-2.0*lumaM)+lumaNS;
  9730. float edgeVert1=(-2.0*lumaM)+lumaWE;
  9731. float lumaNESE=lumaNE+lumaSE;
  9732. float lumaNWNE=lumaNW+lumaNE;
  9733. float edgeHorz2=(-2.0*lumaE)+lumaNESE;
  9734. float edgeVert2=(-2.0*lumaN)+lumaNWNE;
  9735. float lumaNWSW=lumaNW+lumaSW;
  9736. float lumaSWSE=lumaSW+lumaSE;
  9737. float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);
  9738. float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);
  9739. float edgeHorz3=(-2.0*lumaW)+lumaNWSW;
  9740. float edgeVert3=(-2.0*lumaS)+lumaSWSE;
  9741. float edgeHorz=abs(edgeHorz3)+edgeHorz4;
  9742. float edgeVert=abs(edgeVert3)+edgeVert4;
  9743. float subpixNWSWNESE=lumaNWSW+lumaNESE;
  9744. float lengthSign=texelSize.x;
  9745. bool horzSpan=edgeHorz>=edgeVert;
  9746. float subpixA=subpixNSWE*2.0+subpixNWSWNESE;
  9747. if (!horzSpan)
  9748. {
  9749. lumaN=lumaW;
  9750. }
  9751. if (!horzSpan)
  9752. {
  9753. lumaS=lumaE;
  9754. }
  9755. if (horzSpan)
  9756. {
  9757. lengthSign=texelSize.y;
  9758. }
  9759. float subpixB=(subpixA*(1.0/12.0))-lumaM;
  9760. float gradientN=lumaN-lumaM;
  9761. float gradientS=lumaS-lumaM;
  9762. float lumaNN=lumaN+lumaM;
  9763. float lumaSS=lumaS+lumaM;
  9764. bool pairN=abs(gradientN)>=abs(gradientS);
  9765. float gradient=max(abs(gradientN),abs(gradientS));
  9766. if (pairN)
  9767. {
  9768. lengthSign=-lengthSign;
  9769. }
  9770. float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);
  9771. vec2 posB;
  9772. posB.x=posM.x;
  9773. posB.y=posM.y;
  9774. vec2 offNP;
  9775. offNP.x=(!horzSpan) ? 0.0 : texelSize.x;
  9776. offNP.y=(horzSpan) ? 0.0 : texelSize.y;
  9777. if (!horzSpan)
  9778. {
  9779. posB.x+=lengthSign*0.5;
  9780. }
  9781. if (horzSpan)
  9782. {
  9783. posB.y+=lengthSign*0.5;
  9784. }
  9785. vec2 posN;
  9786. posN.x=posB.x-offNP.x*1.5;
  9787. posN.y=posB.y-offNP.y*1.5;
  9788. vec2 posP;
  9789. posP.x=posB.x+offNP.x*1.5;
  9790. posP.y=posB.y+offNP.y*1.5;
  9791. float subpixD=((-2.0)*subpixC)+3.0;
  9792. float lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));
  9793. float subpixE=subpixC*subpixC;
  9794. float lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));
  9795. if (!pairN)
  9796. {
  9797. lumaNN=lumaSS;
  9798. }
  9799. float gradientScaled=gradient*1.0/4.0;
  9800. float lumaMM=lumaM-lumaNN*0.5;
  9801. float subpixF=subpixD*subpixE;
  9802. bool lumaMLTZero=lumaMM<0.0;
  9803. lumaEndN-=lumaNN*0.5;
  9804. lumaEndP-=lumaNN*0.5;
  9805. bool doneN=abs(lumaEndN)>=gradientScaled;
  9806. bool doneP=abs(lumaEndP)>=gradientScaled;
  9807. if (!doneN)
  9808. {
  9809. posN.x-=offNP.x*3.0;
  9810. }
  9811. if (!doneN)
  9812. {
  9813. posN.y-=offNP.y*3.0;
  9814. }
  9815. bool doneNP=(!doneN) || (!doneP);
  9816. if (!doneP)
  9817. {
  9818. posP.x+=offNP.x*3.0;
  9819. }
  9820. if (!doneP)
  9821. {
  9822. posP.y+=offNP.y*3.0;
  9823. }
  9824. if (doneNP)
  9825. {
  9826. if (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));
  9827. if (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));
  9828. if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;
  9829. if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;
  9830. doneN=abs(lumaEndN)>=gradientScaled;
  9831. doneP=abs(lumaEndP)>=gradientScaled;
  9832. if (!doneN) posN.x-=offNP.x*12.0;
  9833. if (!doneN) posN.y-=offNP.y*12.0;
  9834. doneNP=(!doneN) || (!doneP);
  9835. if (!doneP) posP.x+=offNP.x*12.0;
  9836. if (!doneP) posP.y+=offNP.y*12.0;
  9837. }
  9838. float dstN=posM.x-posN.x;
  9839. float dstP=posP.x-posM.x;
  9840. if (!horzSpan)
  9841. {
  9842. dstN=posM.y-posN.y;
  9843. }
  9844. if (!horzSpan)
  9845. {
  9846. dstP=posP.y-posM.y;
  9847. }
  9848. bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;
  9849. float spanLength=(dstP+dstN);
  9850. bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;
  9851. float spanLengthRcp=1.0/spanLength;
  9852. bool directionN=dstN<dstP;
  9853. float dst=min(dstN,dstP);
  9854. bool goodSpan=directionN ? goodSpanN : goodSpanP;
  9855. float subpixG=subpixF*subpixF;
  9856. float pixelOffset=(dst*(-spanLengthRcp))+0.5;
  9857. float subpixH=subpixG*fxaaQualitySubpix;
  9858. float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;
  9859. float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);
  9860. if (!horzSpan)
  9861. {
  9862. posM.x+=pixelOffsetSubpix*lengthSign;
  9863. }
  9864. if (horzSpan)
  9865. {
  9866. posM.y+=pixelOffsetSubpix*lengthSign;
  9867. }
  9868. #ifdef MALI
  9869. if(range<rangeMaxClamped)
  9870. {
  9871. gl_FragColor=rgbyM;
  9872. }
  9873. else
  9874. {
  9875. gl_FragColor=texture2D(textureSampler,posM,0.0);
  9876. }
  9877. #else
  9878. gl_FragColor=texture2D(textureSampler,posM,0.0);
  9879. #endif
  9880. }`;ShaderStore.ShadersStore[name$u]=shader$u;var name$t="fxaaVertexShader",shader$t=`
  9881. attribute vec2 position;
  9882. uniform vec2 texelSize;
  9883. varying vec2 vUV;
  9884. varying vec2 sampleCoordS;
  9885. varying vec2 sampleCoordE;
  9886. varying vec2 sampleCoordN;
  9887. varying vec2 sampleCoordW;
  9888. varying vec2 sampleCoordNW;
  9889. varying vec2 sampleCoordSE;
  9890. varying vec2 sampleCoordNE;
  9891. varying vec2 sampleCoordSW;
  9892. const vec2 madd=vec2(0.5,0.5);
  9893. void main(void) {
  9894. vUV=(position*madd+madd);
  9895. sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;
  9896. sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;
  9897. sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;
  9898. sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;
  9899. sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;
  9900. sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;
  9901. sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;
  9902. sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;
  9903. gl_Position=vec4(position,0.0,1.0);
  9904. }`;ShaderStore.ShadersStore[name$t]=shader$t;var FxaaPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b){s===void 0&&(s=null),b===void 0&&(b=0);var k=a.call(this,e,"fxaa",["texelSize"],null,o,s,c||Texture.BILINEAR_SAMPLINGMODE,d,_,null,b,"fxaa",void 0,!0)||this,j=k._getDefines();return k.updateEffect(j),k.onApplyObservable.add(function($){var _e=k.texelSize;$.setFloat2("texelSize",_e.x,_e.y)}),k}return i.prototype.getClassName=function(){return"FxaaPostProcess"},i.prototype._getDefines=function(){var e=this.getEngine();if(!e)return null;var o=e.getGlInfo();return o&&o.renderer&&o.renderer.toLowerCase().indexOf("mali")>-1?`#define MALI 1
  9905. `:null},i._Parse=function(e,o,s,c){return SerializationHelper.Parse(function(){return new i(e.name,e.options,o,e.renderTargetSamplingMode,s.getEngine(),e.reusable)},e,s,c)},i}(PostProcess);RegisterClass("BABYLON.FxaaPostProcess",FxaaPostProcess);var PostProcessRenderPipeline=function(){function a(i,e){this.engine=i,this._name=e,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}return Object.defineProperty(a.prototype,"name",{get:function(){return this._name},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"cameras",{get:function(){return this._cameras},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"PostProcessRenderPipeline"},Object.defineProperty(a.prototype,"isSupported",{get:function(){for(var i in this._renderEffects)if(this._renderEffects.hasOwnProperty(i)&&!this._renderEffects[i].isSupported)return!1;return!0},enumerable:!1,configurable:!0}),a.prototype.addEffect=function(i){this._renderEffects[i._name]=i},a.prototype._rebuild=function(){},a.prototype._enableEffect=function(i,e){var o=this._renderEffects[i];!o||o._enable(Tools.MakeArray(e||this._cameras))},a.prototype._disableEffect=function(i,e){var o=this._renderEffects[i];!o||o._disable(Tools.MakeArray(e||this._cameras))},a.prototype._attachCameras=function(i,e){var o=Tools.MakeArray(i||this._cameras);if(!!o){var s=[],c;for(c=0;c<o.length;c++){var d=o[c];if(!!d){var _=d.name;this._cameras.indexOf(d)===-1?this._cameras[_]=d:e&&s.push(c)}}for(c=0;c<s.length;c++)o.splice(s[c],1);for(var b in this._renderEffects)this._renderEffects.hasOwnProperty(b)&&this._renderEffects[b]._attachCameras(o)}},a.prototype._detachCameras=function(i){var e=Tools.MakeArray(i||this._cameras);if(!!e){for(var o in this._renderEffects)this._renderEffects.hasOwnProperty(o)&&this._renderEffects[o]._detachCameras(e);for(var s=0;s<e.length;s++)this._cameras.splice(this._cameras.indexOf(e[s]),1)}},a.prototype._update=function(){for(var i in this._renderEffects)this._renderEffects.hasOwnProperty(i)&&this._renderEffects[i]._update();for(var e=0;e<this._cameras.length;e++)if(!!this._cameras[e]){var o=this._cameras[e].name;this._renderEffectsForIsolatedPass[o]&&this._renderEffectsForIsolatedPass[o]._update()}},a.prototype._reset=function(){this._renderEffects={},this._renderEffectsForIsolatedPass=new Array},a.prototype._enableMSAAOnFirstPostProcess=function(i){if(!this.engine._features.supportMSAA)return!1;var e=Object.keys(this._renderEffects);if(e.length>0){var o=this._renderEffects[e[0]].getPostProcesses();o&&(o[0].samples=i)}return!0},a.prototype.setPrePassRenderer=function(i){return!1},a.prototype.dispose=function(){},__decorate([serialize()],a.prototype,"_name",void 0),a}(),PostProcessRenderEffect=function(){function a(i,e,o,s){this._name=e,this._singleInstance=s||!0,this._getPostProcesses=o,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(a.prototype,"isSupported",{get:function(){for(var i in this._postProcesses)if(this._postProcesses.hasOwnProperty(i)){for(var e=this._postProcesses[i],o=0;o<e.length;o++)if(!e[o].isSupported)return!1}return!0},enumerable:!1,configurable:!0}),a.prototype._update=function(){},a.prototype._attachCameras=function(i){var e=this,o,s=Tools.MakeArray(i||this._cameras);if(!!s)for(var c=0;c<s.length;c++){var d=s[c];if(!!d){var _=d.name;if(this._singleInstance?o=0:o=_,!this._postProcesses[o]){var b=this._getPostProcesses();b&&(this._postProcesses[o]=Array.isArray(b)?b:[b])}this._indicesForCamera[_]||(this._indicesForCamera[_]=[]),this._postProcesses[o].forEach(function(k){var j=d.attachPostProcess(k);e._indicesForCamera[_].push(j)}),this._cameras[_]||(this._cameras[_]=d)}}},a.prototype._detachCameras=function(i){var e=Tools.MakeArray(i||this._cameras);if(!!e)for(var o=0;o<e.length;o++){var s=e[o],c=s.name,d=this._postProcesses[this._singleInstance?0:c];d&&d.forEach(function(_){s.detachPostProcess(_)}),this._cameras[c]&&(this._cameras[c]=null)}},a.prototype._enable=function(i){var e=this,o=Tools.MakeArray(i||this._cameras);if(!!o)for(var s=0;s<o.length;s++)for(var c=o[s],d=c.name,_=0;_<this._indicesForCamera[d].length;_++)(c._postProcesses[this._indicesForCamera[d][_]]===void 0||c._postProcesses[this._indicesForCamera[d][_]]===null)&&this._postProcesses[this._singleInstance?0:d].forEach(function(b){o[s].attachPostProcess(b,e._indicesForCamera[d][_])})},a.prototype._disable=function(i){var e=Tools.MakeArray(i||this._cameras);if(!!e)for(var o=0;o<e.length;o++){var s=e[o],c=s.name;this._postProcesses[this._singleInstance?0:c].forEach(function(d){s.detachPostProcess(d)})}},a.prototype.getPostProcesses=function(i){return this._singleInstance?this._postProcesses[0]:i?this._postProcesses[i.name]:null},a}(),name$s="circleOfConfusionPixelShader",shader$s=`
  9906. uniform sampler2D depthSampler;
  9907. varying vec2 vUV;
  9908. uniform vec2 cameraMinMaxZ;
  9909. uniform float focusDistance;
  9910. uniform float cocPrecalculation;
  9911. void main(void)
  9912. {
  9913. float depth=texture2D(depthSampler,vUV).r;
  9914. float pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0;
  9915. float coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));
  9916. coc=clamp(coc,0.0,1.0);
  9917. gl_FragColor=vec4(coc,depth,coc,1.0);
  9918. }
  9919. `;ShaderStore.ShadersStore[name$s]=shader$s;var CircleOfConfusionPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j){k===void 0&&(k=0),j===void 0&&(j=!1);var $=a.call(this,e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],s,c,d,_,b,null,k,void 0,null,j)||this;return $.lensSize=50,$.fStop=1.4,$.focusDistance=2e3,$.focalLength=50,$._depthTexture=null,$._depthTexture=o,$.onApplyObservable.add(function(_e){if(!$._depthTexture){Logger$2.Warn("No depth texture set on CircleOfConfusionPostProcess");return}_e.setTexture("depthSampler",$._depthTexture);var et=$.lensSize/$.fStop,tt=et*$.focalLength/($.focusDistance-$.focalLength);_e.setFloat("focusDistance",$.focusDistance),_e.setFloat("cocPrecalculation",tt),_e.setFloat2("cameraMinMaxZ",$._depthTexture.activeCamera.minZ,$._depthTexture.activeCamera.maxZ)}),$}return i.prototype.getClassName=function(){return"CircleOfConfusionPostProcess"},Object.defineProperty(i.prototype,"depthTexture",{set:function(e){this._depthTexture=e},enumerable:!1,configurable:!0}),__decorate([serialize()],i.prototype,"lensSize",void 0),__decorate([serialize()],i.prototype,"fStop",void 0),__decorate([serialize()],i.prototype,"focusDistance",void 0),__decorate([serialize()],i.prototype,"focalLength",void 0),i}(PostProcess);RegisterClass("BABYLON.CircleOfConfusionPostProcess",CircleOfConfusionPostProcess);var DepthOfFieldBlurPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$,_e,et,tt){k===void 0&&(k=null),tt===void 0&&(tt=!1);var rt=a.call(this,e,s,c,d,_,2,$,_e,0,`#define DOF 1\r
  9920. `,tt)||this;return rt.direction=s,rt.externalTextureSamplerBinding=!!k,rt.onApplyObservable.add(function(it){k!=null&&it.setTextureFromPostProcess("textureSampler",k),it.setTextureFromPostProcessOutput("circleOfConfusionSampler",b),o.activeCamera&&it.setFloat2("cameraMinMaxZ",o.activeCamera.minZ,o.activeCamera.maxZ)}),rt}return i.prototype.getClassName=function(){return"DepthOfFieldBlurPostProcess"},__decorate([serialize()],i.prototype,"direction",void 0),i}(BlurPostProcess);RegisterClass("BABYLON.DepthOfFieldBlurPostProcess",DepthOfFieldBlurPostProcess);var name$r="depthOfFieldMergePixelShader",shader$r=`uniform sampler2D textureSampler;
  9921. varying vec2 vUV;
  9922. uniform sampler2D circleOfConfusionSampler;
  9923. uniform sampler2D blurStep0;
  9924. #if BLUR_LEVEL>0
  9925. uniform sampler2D blurStep1;
  9926. #endif
  9927. #if BLUR_LEVEL>1
  9928. uniform sampler2D blurStep2;
  9929. #endif
  9930. void main(void)
  9931. {
  9932. float coc=texture2D(circleOfConfusionSampler,vUV).r;
  9933. #if BLUR_LEVEL == 0
  9934. vec4 original=texture2D(textureSampler,vUV);
  9935. vec4 blurred0=texture2D(blurStep0,vUV);
  9936. gl_FragColor=mix(original,blurred0,coc);
  9937. #endif
  9938. #if BLUR_LEVEL == 1
  9939. if(coc<0.5){
  9940. vec4 original=texture2D(textureSampler,vUV);
  9941. vec4 blurred1=texture2D(blurStep1,vUV);
  9942. gl_FragColor=mix(original,blurred1,coc/0.5);
  9943. }else{
  9944. vec4 blurred0=texture2D(blurStep0,vUV);
  9945. vec4 blurred1=texture2D(blurStep1,vUV);
  9946. gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);
  9947. }
  9948. #endif
  9949. #if BLUR_LEVEL == 2
  9950. if(coc<0.33){
  9951. vec4 original=texture2D(textureSampler,vUV);
  9952. vec4 blurred2=texture2D(blurStep2,vUV);
  9953. gl_FragColor=mix(original,blurred2,coc/0.33);
  9954. }else if(coc<0.66){
  9955. vec4 blurred1=texture2D(blurStep1,vUV);
  9956. vec4 blurred2=texture2D(blurStep2,vUV);
  9957. gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);
  9958. }else{
  9959. vec4 blurred0=texture2D(blurStep0,vUV);
  9960. vec4 blurred1=texture2D(blurStep1,vUV);
  9961. gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);
  9962. }
  9963. #endif
  9964. }
  9965. `;ShaderStore.ShadersStore[name$r]=shader$r;var DepthOfFieldMergePostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$,_e){$===void 0&&($=0),_e===void 0&&(_e=!1);var et=a.call(this,e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],d,_,b,k,j,null,$,void 0,null,!0)||this;return et.blurSteps=c,et.externalTextureSamplerBinding=!0,et.onApplyObservable.add(function(tt){tt.setTextureFromPostProcess("textureSampler",o),tt.setTextureFromPostProcessOutput("circleOfConfusionSampler",s),c.forEach(function(rt,it){tt.setTextureFromPostProcessOutput("blurStep"+(c.length-it-1),rt)})}),_e||et.updateEffect(),et}return i.prototype.getClassName=function(){return"DepthOfFieldMergePostProcess"},i.prototype.updateEffect=function(e,o,s,c,d,_){e===void 0&&(e=null),o===void 0&&(o=null),s===void 0&&(s=null),e||(e="",e+="#define BLUR_LEVEL "+(this.blurSteps.length-1)+`
  9966. `),a.prototype.updateEffect.call(this,e,o,s,c,d,_)},i}(PostProcess),DepthOfFieldEffectBlurLevel;(function(a){a[a.Low=0]="Low",a[a.Medium=1]="Medium",a[a.High=2]="High"})(DepthOfFieldEffectBlurLevel||(DepthOfFieldEffectBlurLevel={}));var DepthOfFieldEffect=function(a){__extends(i,a);function i(e,o,s,c,d){s===void 0&&(s=DepthOfFieldEffectBlurLevel.Low),c===void 0&&(c=0),d===void 0&&(d=!1);var _=a.call(this,e.getEngine(),"depth of field",function(){return _._effects},!0)||this;_._effects=[],_._circleOfConfusion=new CircleOfConfusionPostProcess("circleOfConfusion",o,1,null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,c,d),_._depthOfFieldBlurY=[],_._depthOfFieldBlurX=[];var b=1,k=15;switch(s){case DepthOfFieldEffectBlurLevel.High:{b=3,k=51;break}case DepthOfFieldEffectBlurLevel.Medium:{b=2,k=31;break}default:{k=15,b=1;break}}for(var j=k/Math.pow(2,b-1),$=1,_e=0;_e<b;_e++){var et=new DepthOfFieldBlurPostProcess("vertical blur",e,new Vector2(0,1),j,$,null,_._circleOfConfusion,_e==0?_._circleOfConfusion:null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,c,d);et.autoClear=!1,$=.75/Math.pow(2,_e);var tt=new DepthOfFieldBlurPostProcess("horizontal blur",e,new Vector2(1,0),j,$,null,_._circleOfConfusion,null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,c,d);tt.autoClear=!1,_._depthOfFieldBlurY.push(et),_._depthOfFieldBlurX.push(tt)}_._effects=[_._circleOfConfusion];for(var _e=0;_e<_._depthOfFieldBlurX.length;_e++)_._effects.push(_._depthOfFieldBlurY[_e]),_._effects.push(_._depthOfFieldBlurX[_e]);return _._dofMerge=new DepthOfFieldMergePostProcess("dofMerge",_._circleOfConfusion,_._circleOfConfusion,_._depthOfFieldBlurX,$,null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,c,d),_._dofMerge.autoClear=!1,_._effects.push(_._dofMerge),_}return Object.defineProperty(i.prototype,"focalLength",{get:function(){return this._circleOfConfusion.focalLength},set:function(e){this._circleOfConfusion.focalLength=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"fStop",{get:function(){return this._circleOfConfusion.fStop},set:function(e){this._circleOfConfusion.fStop=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"focusDistance",{get:function(){return this._circleOfConfusion.focusDistance},set:function(e){this._circleOfConfusion.focusDistance=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lensSize",{get:function(){return this._circleOfConfusion.lensSize},set:function(e){this._circleOfConfusion.lensSize=e},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"DepthOfFieldEffect"},Object.defineProperty(i.prototype,"depthTexture",{set:function(e){this._circleOfConfusion.depthTexture=e},enumerable:!1,configurable:!0}),i.prototype.disposeEffects=function(e){for(var o=0;o<this._effects.length;o++)this._effects[o].dispose(e)},i.prototype._updateEffects=function(){for(var e=0;e<this._effects.length;e++)this._effects[e].updateEffect()},i.prototype._isReady=function(){for(var e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0},i}(PostProcessRenderEffect),name$q="extractHighlightsPixelShader",shader$q=`#include<helperFunctions>
  9967. varying vec2 vUV;
  9968. uniform sampler2D textureSampler;
  9969. uniform float threshold;
  9970. uniform float exposure;
  9971. void main(void)
  9972. {
  9973. gl_FragColor=texture2D(textureSampler,vUV);
  9974. float luma=getLuminance(gl_FragColor.rgb*exposure);
  9975. gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;
  9976. }`;ShaderStore.ShadersStore[name$q]=shader$q;var ExtractHighlightsPostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k){b===void 0&&(b=0),k===void 0&&(k=!1);var j=a.call(this,e,"extractHighlights",["threshold","exposure"],null,o,s,c,d,_,null,b,void 0,null,k)||this;return j.threshold=.9,j._exposure=1,j._inputPostProcess=null,j.onApplyObservable.add(function($){j.externalTextureSamplerBinding=!!j._inputPostProcess,j._inputPostProcess&&$.setTextureFromPostProcess("textureSampler",j._inputPostProcess),$.setFloat("threshold",Math.pow(j.threshold,ToGammaSpace)),$.setFloat("exposure",j._exposure)}),j}return i.prototype.getClassName=function(){return"ExtractHighlightsPostProcess"},__decorate([serialize()],i.prototype,"threshold",void 0),i}(PostProcess);RegisterClass("BABYLON.ExtractHighlightsPostProcess",ExtractHighlightsPostProcess);var name$p="bloomMergePixelShader",shader$p=`uniform sampler2D textureSampler;
  9977. uniform sampler2D bloomBlur;
  9978. varying vec2 vUV;
  9979. uniform float bloomWeight;
  9980. void main(void)
  9981. {
  9982. gl_FragColor=texture2D(textureSampler,vUV);
  9983. vec3 blurred=texture2D(bloomBlur,vUV).rgb;
  9984. gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight);
  9985. }
  9986. `;ShaderStore.ShadersStore[name$p]=shader$p;var BloomMergePostProcess=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$,_e){$===void 0&&($=0),_e===void 0&&(_e=!1);var et=a.call(this,e,"bloomMerge",["bloomWeight"],["bloomBlur"],d,_,b,k,j,null,$,void 0,null,!0)||this;return et.weight=1,et.weight=c,et.externalTextureSamplerBinding=!0,et.onApplyObservable.add(function(tt){tt.setTextureFromPostProcess("textureSampler",o),tt.setTextureFromPostProcessOutput("bloomBlur",s),tt.setFloat("bloomWeight",et.weight)}),_e||et.updateEffect(),et}return i.prototype.getClassName=function(){return"BloomMergePostProcess"},__decorate([serialize()],i.prototype,"weight",void 0),i}(PostProcess);RegisterClass("BABYLON.BloomMergePostProcess",BloomMergePostProcess);var BloomEffect=function(a){__extends(i,a);function i(e,o,s,c,d,_){d===void 0&&(d=0),_===void 0&&(_=!1);var b=a.call(this,e.getEngine(),"bloom",function(){return b._effects},!0)||this;return b.bloomScale=o,b._effects=[],b._downscale=new ExtractHighlightsPostProcess("highlights",1,null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,d,_),b._blurX=new BlurPostProcess("horizontal blur",new Vector2(1,0),10,o,null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,d,void 0,_),b._blurX.alwaysForcePOT=!0,b._blurX.autoClear=!1,b._blurY=new BlurPostProcess("vertical blur",new Vector2(0,1),10,o,null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,d,void 0,_),b._blurY.alwaysForcePOT=!0,b._blurY.autoClear=!1,b.kernel=c,b._effects=[b._downscale,b._blurX,b._blurY],b._merge=new BloomMergePostProcess("bloomMerge",b._downscale,b._blurY,s,o,null,Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,d,_),b._merge.autoClear=!1,b._effects.push(b._merge),b}return Object.defineProperty(i.prototype,"threshold",{get:function(){return this._downscale.threshold},set:function(e){this._downscale.threshold=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"weight",{get:function(){return this._merge.weight},set:function(e){this._merge.weight=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"kernel",{get:function(){return this._blurX.kernel/this.bloomScale},set:function(e){this._blurX.kernel=e*this.bloomScale,this._blurY.kernel=e*this.bloomScale},enumerable:!1,configurable:!0}),i.prototype.disposeEffects=function(e){for(var o=0;o<this._effects.length;o++)this._effects[o].dispose(e)},i.prototype._updateEffects=function(){for(var e=0;e<this._effects.length;e++)this._effects[e].updateEffect()},i.prototype._isReady=function(){for(var e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0},i}(PostProcessRenderEffect),PostProcessRenderPipelineManager=function(){function a(){this._renderPipelines={}}return Object.defineProperty(a.prototype,"supportedPipelines",{get:function(){var i=[];for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var o=this._renderPipelines[e];o.isSupported&&i.push(o)}return i},enumerable:!1,configurable:!0}),a.prototype.addPipeline=function(i){this._renderPipelines[i._name]=i},a.prototype.attachCamerasToRenderPipeline=function(i,e,o){o===void 0&&(o=!1);var s=this._renderPipelines[i];!s||s._attachCameras(e,o)},a.prototype.detachCamerasFromRenderPipeline=function(i,e){var o=this._renderPipelines[i];!o||o._detachCameras(e)},a.prototype.enableEffectInPipeline=function(i,e,o){var s=this._renderPipelines[i];!s||s._enableEffect(e,o)},a.prototype.disableEffectInPipeline=function(i,e,o){var s=this._renderPipelines[i];!s||s._disableEffect(e,o)},a.prototype.update=function(){for(var i in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(i)){var e=this._renderPipelines[i];e.isSupported?e._update():(e.dispose(),delete this._renderPipelines[i])}},a.prototype._rebuild=function(){for(var i in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(i)){var e=this._renderPipelines[i];e._rebuild()}},a.prototype.dispose=function(){for(var i in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(i)){var e=this._renderPipelines[i];e.dispose()}},a}();Object.defineProperty(Scene.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){var a=this._getComponent(SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);a||(a=new PostProcessRenderPipelineManagerSceneComponent(this),this._addComponent(a)),this._postProcessRenderPipelineManager=new PostProcessRenderPipelineManager}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});var PostProcessRenderPipelineManagerSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=i}return a.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)},a.prototype.rebuild=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()},a.prototype.dispose=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()},a.prototype._gatherRenderTargets=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()},a}(),DefaultRenderingPipeline=function(a){__extends(i,a);function i(e,o,s,c,d){e===void 0&&(e=""),o===void 0&&(o=!0),s===void 0&&(s=EngineStore.LastCreatedScene),d===void 0&&(d=!0);var _=a.call(this,s.getEngine(),e)||this;_._camerasToBeAttached=[],_.SharpenPostProcessId="SharpenPostProcessEffect",_.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",_.FxaaPostProcessId="FxaaPostProcessEffect",_.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",_.GrainPostProcessId="GrainPostProcessEffect",_._glowLayer=null,_.animations=[],_._imageProcessingConfigurationObserver=null,_._sharpenEnabled=!1,_._bloomEnabled=!1,_._depthOfFieldEnabled=!1,_._depthOfFieldBlurLevel=DepthOfFieldEffectBlurLevel.Low,_._fxaaEnabled=!1,_._imageProcessingEnabled=!0,_._bloomScale=.5,_._chromaticAberrationEnabled=!1,_._grainEnabled=!1,_._buildAllowed=!0,_.onBuildObservable=new Observable,_._resizeObserver=null,_._hardwareScaleLevel=1,_._bloomKernel=64,_._bloomWeight=.15,_._bloomThreshold=.9,_._samples=1,_._hasCleared=!1,_._prevPostProcess=null,_._prevPrevPostProcess=null,_._depthOfFieldSceneObserver=null,_._cameras=c||s.cameras,_._cameras=_._cameras.slice(),_._camerasToBeAttached=_._cameras.slice(),_._buildAllowed=d,_._scene=s;var b=_._scene.getEngine().getCaps();_._hdr=o&&(b.textureHalfFloatRender||b.textureFloatRender),_._hdr?b.textureHalfFloatRender?_._defaultPipelineTextureType=2:b.textureFloatRender&&(_._defaultPipelineTextureType=1):_._defaultPipelineTextureType=0,s.postProcessRenderPipelineManager.addPipeline(_);var k=_._scene.getEngine();return _.sharpen=new SharpenPostProcess("sharpen",1,null,Texture.BILINEAR_SAMPLINGMODE,k,!1,_._defaultPipelineTextureType,!0),_._sharpenEffect=new PostProcessRenderEffect(k,_.SharpenPostProcessId,function(){return _.sharpen},!0),_.depthOfField=new DepthOfFieldEffect(_._scene,null,_._depthOfFieldBlurLevel,_._defaultPipelineTextureType,!0),_.bloom=new BloomEffect(_._scene,_._bloomScale,_._bloomWeight,_.bloomKernel,_._defaultPipelineTextureType,!0),_.chromaticAberration=new ChromaticAberrationPostProcess("ChromaticAberration",k.getRenderWidth(),k.getRenderHeight(),1,null,Texture.BILINEAR_SAMPLINGMODE,k,!1,_._defaultPipelineTextureType,!0),_._chromaticAberrationEffect=new PostProcessRenderEffect(k,_.ChromaticAberrationPostProcessId,function(){return _.chromaticAberration},!0),_.grain=new GrainPostProcess("Grain",1,null,Texture.BILINEAR_SAMPLINGMODE,k,!1,_._defaultPipelineTextureType,!0),_._grainEffect=new PostProcessRenderEffect(k,_.GrainPostProcessId,function(){return _.grain},!0),_._resizeObserver=k.onResizeObservable.add(function(){_._hardwareScaleLevel=k.getHardwareScalingLevel(),_.bloomKernel=_.bloomKernel}),_._imageProcessingConfigurationObserver=_._scene.imageProcessingConfiguration.onUpdateParameters.add(function(){_.bloom._downscale._exposure=_._scene.imageProcessingConfiguration.exposure,_.imageProcessingEnabled!==_._scene.imageProcessingConfiguration.isEnabled&&(_._imageProcessingEnabled=_._scene.imageProcessingConfiguration.isEnabled,_._buildPipeline())}),_._buildPipeline(),_}return Object.defineProperty(i.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sharpenEnabled",{get:function(){return this._sharpenEnabled},set:function(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bloomKernel",{get:function(){return this._bloomKernel},set:function(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bloomWeight",{get:function(){return this._bloomWeight},set:function(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bloomThreshold",{get:function(){return this._bloomThreshold},set:function(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bloomScale",{get:function(){return this._bloomScale},set:function(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"bloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),i.prototype._rebuildBloom=function(){var e=this.bloom;this.bloom=new BloomEffect(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(var o=0;o<this._cameras.length;o++)e.disposeEffects(this._cameras[o])},Object.defineProperty(i.prototype,"depthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"depthOfFieldBlurLevel",{get:function(){return this._depthOfFieldBlurLevel},set:function(e){if(this._depthOfFieldBlurLevel!==e){this._depthOfFieldBlurLevel=e;var o=this.depthOfField;this.depthOfField=new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=o.focalLength,this.depthOfField.focusDistance=o.focusDistance,this.depthOfField.fStop=o.fStop,this.depthOfField.lensSize=o.lensSize;for(var s=0;s<this._cameras.length;s++)o.disposeEffects(this._cameras[s]);this._buildPipeline()}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingEnabled",{get:function(){return this._imageProcessingEnabled},set:function(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"glowLayerEnabled",{get:function(){return this._glowLayer!=null},set:function(e){e&&!this._glowLayer?this._glowLayer=new GlowLayer("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"glowLayer",{get:function(){return this._glowLayer},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"chromaticAberrationEnabled",{get:function(){return this._chromaticAberrationEnabled},set:function(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"grainEnabled",{get:function(){return this._grainEnabled},set:function(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"DefaultRenderingPipeline"},i.prototype.prepare=function(){var e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e},i.prototype._setAutoClearAndTextureSharing=function(e,o){o===void 0&&(o=!1),this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),o||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)},i.prototype._buildPipeline=function(){var e=this;if(!!this._buildAllowed){this._scene.autoClear=!0;var o=this._scene.getEngine();if(this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(var s=0,c=this._cameras;s<c.length;s++){var d=c[s],_=this._scene.enableDepthRenderer(d);_.useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(function(b){e._cameras.indexOf(b.activeCamera)>-1&&(e.depthOfField.depthTexture=b.enableDepthRenderer(b.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);var _=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=_.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new ImageProcessingPostProcess("imageProcessing",1,null,Texture.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType),this._hdr?(this.addEffect(new PostProcessRenderEffect(o,this.ImageProcessingPostProcessId,function(){return e.imageProcessing},!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,(!this.cameras||this.cameras.length===0)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new FxaaPostProcess("fxaa",1,null,Texture.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType),this.addEffect(new PostProcessRenderEffect(o,this.FxaaPostProcessId,function(){return e.fxaa},!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&Logger$2.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}},i.prototype._disposePostProcesses=function(e){e===void 0&&(e=!1);for(var o=0;o<this._cameras.length;o++){var s=this._cameras[o];this.imageProcessing&&this.imageProcessing.dispose(s),this.fxaa&&this.fxaa.dispose(s),e&&(this.sharpen&&this.sharpen.dispose(s),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(s)),this.bloom&&this.bloom.disposeEffects(s),this.chromaticAberration&&this.chromaticAberration.dispose(s),this.grain&&this.grain.dispose(s),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)},i.prototype.addCamera=function(e){this._camerasToBeAttached.push(e),this._buildPipeline()},i.prototype.removeCamera=function(e){var o=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(o,1),this._buildPipeline()},i.prototype.dispose=function(){this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),a.prototype.dispose.call(this)},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);return e.customType="DefaultRenderingPipeline",e},i.Parse=function(e,o,s){return SerializationHelper.Parse(function(){return new i(e._name,e._name._hdr,o)},e,o,s)},__decorate([serialize()],i.prototype,"sharpenEnabled",null),__decorate([serialize()],i.prototype,"bloomKernel",null),__decorate([serialize()],i.prototype,"_bloomWeight",void 0),__decorate([serialize()],i.prototype,"_bloomThreshold",void 0),__decorate([serialize()],i.prototype,"_hdr",void 0),__decorate([serialize()],i.prototype,"bloomWeight",null),__decorate([serialize()],i.prototype,"bloomThreshold",null),__decorate([serialize()],i.prototype,"bloomScale",null),__decorate([serialize()],i.prototype,"bloomEnabled",null),__decorate([serialize()],i.prototype,"depthOfFieldEnabled",null),__decorate([serialize()],i.prototype,"depthOfFieldBlurLevel",null),__decorate([serialize()],i.prototype,"fxaaEnabled",null),__decorate([serialize()],i.prototype,"samples",null),__decorate([serialize()],i.prototype,"imageProcessingEnabled",null),__decorate([serialize()],i.prototype,"glowLayerEnabled",null),__decorate([serialize()],i.prototype,"chromaticAberrationEnabled",null),__decorate([serialize()],i.prototype,"grainEnabled",null),i}(PostProcessRenderPipeline);RegisterClass("BABYLON.DefaultRenderingPipeline",DefaultRenderingPipeline);var name$o="imageProcessingCompatibility",shader$o=`#ifdef IMAGEPROCESSINGPOSTPROCESS
  9987. gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));
  9988. #endif`;ShaderStore.IncludesShadersStore[name$o]=shader$o;var name$n="gridPixelShader",shader$n=`#extension GL_OES_standard_derivatives : enable
  9989. #define SQRT2 1.41421356
  9990. #define PI 3.14159
  9991. precision highp float;
  9992. uniform float visibility;
  9993. uniform vec3 mainColor;
  9994. uniform vec3 lineColor;
  9995. uniform vec4 gridControl;
  9996. uniform vec3 gridOffset;
  9997. varying vec3 vPosition;
  9998. varying vec3 vNormal;
  9999. #include<fogFragmentDeclaration>
  10000. #ifdef OPACITY
  10001. varying vec2 vOpacityUV;
  10002. uniform sampler2D opacitySampler;
  10003. uniform vec2 vOpacityInfos;
  10004. #endif
  10005. float getDynamicVisibility(float position) {
  10006. float majorGridFrequency=gridControl.y;
  10007. if (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)
  10008. {
  10009. return 1.0;
  10010. }
  10011. return gridControl.z;
  10012. }
  10013. float getAnisotropicAttenuation(float differentialLength) {
  10014. const float maxNumberOfLines=10.0;
  10015. return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);
  10016. }
  10017. float isPointOnLine(float position,float differentialLength) {
  10018. float fractionPartOfPosition=position-floor(position+0.5);
  10019. fractionPartOfPosition/=differentialLength;
  10020. fractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);
  10021. float result=0.5+0.5*cos(fractionPartOfPosition*PI);
  10022. return result;
  10023. }
  10024. float contributionOnAxis(float position) {
  10025. float differentialLength=length(vec2(dFdx(position),dFdy(position)));
  10026. differentialLength*=SQRT2;
  10027. float result=isPointOnLine(position,differentialLength);
  10028. float dynamicVisibility=getDynamicVisibility(position);
  10029. result*=dynamicVisibility;
  10030. float anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);
  10031. result*=anisotropicAttenuation;
  10032. return result;
  10033. }
  10034. float normalImpactOnAxis(float x) {
  10035. float normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);
  10036. return normalImpact;
  10037. }
  10038. void main(void) {
  10039. float gridRatio=gridControl.x;
  10040. vec3 gridPos=(vPosition+gridOffset.xyz)/gridRatio;
  10041. float x=contributionOnAxis(gridPos.x);
  10042. float y=contributionOnAxis(gridPos.y);
  10043. float z=contributionOnAxis(gridPos.z);
  10044. vec3 normal=normalize(vNormal);
  10045. x*=normalImpactOnAxis(normal.x);
  10046. y*=normalImpactOnAxis(normal.y);
  10047. z*=normalImpactOnAxis(normal.z);
  10048. #ifdef MAX_LINE
  10049. float grid=clamp(max(max(x,y),z),0.,1.);
  10050. #else
  10051. float grid=clamp(x+y+z,0.,1.);
  10052. #endif
  10053. vec3 color=mix(mainColor,lineColor,grid);
  10054. #ifdef FOG
  10055. #include<fogFragment>
  10056. #endif
  10057. float opacity=1.0;
  10058. #ifdef TRANSPARENT
  10059. opacity=clamp(grid,0.08,gridControl.w*grid);
  10060. #endif
  10061. #ifdef OPACITY
  10062. opacity*=texture2D(opacitySampler,vOpacityUV).a;
  10063. #endif
  10064. gl_FragColor=vec4(color.rgb,opacity*visibility);
  10065. #ifdef TRANSPARENT
  10066. #ifdef PREMULTIPLYALPHA
  10067. gl_FragColor.rgb*=opacity;
  10068. #endif
  10069. #else
  10070. #endif
  10071. #include<imageProcessingCompatibility>
  10072. }
  10073. `;ShaderStore.ShadersStore[name$n]=shader$n;var name$m="gridVertexShader",shader$m=`precision highp float;
  10074. attribute vec3 position;
  10075. attribute vec3 normal;
  10076. #ifdef UV1
  10077. attribute vec2 uv;
  10078. #endif
  10079. #ifdef UV2
  10080. attribute vec2 uv2;
  10081. #endif
  10082. #include<instancesDeclaration>
  10083. uniform mat4 projection;
  10084. uniform mat4 view;
  10085. varying vec3 vPosition;
  10086. varying vec3 vNormal;
  10087. #include<fogVertexDeclaration>
  10088. #ifdef OPACITY
  10089. varying vec2 vOpacityUV;
  10090. uniform mat4 opacityMatrix;
  10091. uniform vec2 vOpacityInfos;
  10092. #endif
  10093. void main(void) {
  10094. #include<instancesVertex>
  10095. vec4 worldPos=finalWorld*vec4(position,1.0);
  10096. #include<fogVertex>
  10097. vec4 cameraSpacePosition=view*worldPos;
  10098. gl_Position=projection*cameraSpacePosition;
  10099. #ifdef OPACITY
  10100. #ifndef UV1
  10101. vec2 uv=vec2(0.,0.);
  10102. #endif
  10103. #ifndef UV2
  10104. vec2 uv2=vec2(0.,0.);
  10105. #endif
  10106. if (vOpacityInfos.x == 0.)
  10107. {
  10108. vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));
  10109. }
  10110. else
  10111. {
  10112. vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));
  10113. }
  10114. #endif
  10115. vPosition=position;
  10116. vNormal=normal;
  10117. }`;ShaderStore.ShadersStore[name$m]=shader$m;var GridMaterialDefines=function(a){__extends(i,a);function i(){var e=a.call(this)||this;return e.OPACITY=!1,e.TRANSPARENT=!1,e.FOG=!1,e.PREMULTIPLYALPHA=!1,e.MAX_LINE=!1,e.UV1=!1,e.UV2=!1,e.INSTANCES=!1,e.THIN_INSTANCES=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.SKIPFINALCOLORCLAMP=!1,e.rebuild(),e}return i}(MaterialDefines),GridMaterial=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s.mainColor=Color3.Black(),s.lineColor=Color3.Teal(),s.gridRatio=1,s.gridOffset=Vector3.Zero(),s.majorUnitFrequency=10,s.minorUnitVisibility=.33,s.opacity=1,s.preMultiplyAlpha=!1,s.useMaxLine=!1,s._gridControl=new Vector4(s.gridRatio,s.majorUnitFrequency,s.minorUnitVisibility,s.opacity),s}return i.prototype.needAlphaBlending=function(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()},i.prototype.needAlphaBlendingForMesh=function(e){return e.visibility<1||this.needAlphaBlending()},i.prototype.isReadyForSubMesh=function(e,o,s){if(this.isFrozen&&o.effect&&o.effect._wasPreviouslyReady)return!0;o.materialDefines||(o.materialDefines=new GridMaterialDefines);var c=o.materialDefines,d=this.getScene();if(this._isReadyForSubMesh(o))return!0;if(c.TRANSPARENT!==this.opacity<1&&(c.TRANSPARENT=!c.TRANSPARENT,c.markAsUnprocessed()),c.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(c.PREMULTIPLYALPHA=!c.PREMULTIPLYALPHA,c.markAsUnprocessed()),c.MAX_LINE!==this.useMaxLine&&(c.MAX_LINE=!c.MAX_LINE,c.markAsUnprocessed()),c._areTexturesDirty&&(c._needUVs=!1,d.texturesEnabled&&this._opacityTexture&&MaterialFlags.OpacityTextureEnabled))if(this._opacityTexture.isReady())c._needUVs=!0,c.OPACITY=!0;else return!1;if(MaterialHelper.PrepareDefinesForMisc(e,d,!1,!1,this.fogEnabled,!1,c),MaterialHelper.PrepareDefinesForFrameBoundValues(d,d.getEngine(),c,!!s),c.isDirty){c.markAsProcessed(),d.resetCachedMaterial(),MaterialHelper.PrepareDefinesForAttributes(e,c,!1,!1);var _=[VertexBuffer.PositionKind,VertexBuffer.NormalKind];c.UV1&&_.push(VertexBuffer.UVKind),c.UV2&&_.push(VertexBuffer.UV2Kind),c.IMAGEPROCESSINGPOSTPROCESS=d.imageProcessingConfiguration.applyByPostProcess,MaterialHelper.PrepareAttributesForInstances(_,c);var b=c.toString();o.setEffect(d.getEngine().createEffect("grid",_,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility"],["opacitySampler"],b,void 0,this.onCompiled,this.onError),c,this._materialContext)}return!o.effect||!o.effect.isReady()?!1:(c._renderId=d.getRenderId(),o.effect._wasPreviouslyReady=!0,!0)},i.prototype.bindForSubMesh=function(e,o,s){var c=this.getScene(),d=s.materialDefines;if(!!d){var _=s.effect;!_||(this._activeEffect=_,this._activeEffect.setFloat("visibility",o.visibility),(!d.INSTANCES||d.THIN_INSTANCE)&&this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",c.getViewMatrix()),this._activeEffect.setMatrix("projection",c.getProjectionMatrix()),this._mustRebind(c,_)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix()))),MaterialHelper.BindFogParameters(c,o,this._activeEffect),this._afterBind(o,this._activeEffect))}},i.prototype.dispose=function(e){a.prototype.dispose.call(this,e)},i.prototype.clone=function(e){var o=this;return SerializationHelper.Clone(function(){return new i(e,o.getScene())},this)},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);return e.customType="BABYLON.GridMaterial",e},i.prototype.getClassName=function(){return"GridMaterial"},i.Parse=function(e,o,s){return SerializationHelper.Parse(function(){return new i(e.name,o)},e,o,s)},__decorate([serializeAsColor3()],i.prototype,"mainColor",void 0),__decorate([serializeAsColor3()],i.prototype,"lineColor",void 0),__decorate([serialize()],i.prototype,"gridRatio",void 0),__decorate([serializeAsVector3()],i.prototype,"gridOffset",void 0),__decorate([serialize()],i.prototype,"majorUnitFrequency",void 0),__decorate([serialize()],i.prototype,"minorUnitVisibility",void 0),__decorate([serialize()],i.prototype,"opacity",void 0),__decorate([serialize()],i.prototype,"preMultiplyAlpha",void 0),__decorate([serialize()],i.prototype,"useMaxLine",void 0),__decorate([serializeAsTexture("opacityTexture")],i.prototype,"_opacityTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"opacityTexture",void 0),i}(PushMaterial);RegisterClass("BABYLON.GridMaterial",GridMaterial);var SceneInstrumentation=function(){function a(i){var e=this;this.scene=i,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new PerfCounter,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new PerfCounter,this._registerBeforeRenderTime=new PerfCounter,this._onBeforeRegisterBeforeRenderObserver=null,this._onAfterRegisterBeforeRenderObserver=null,this._RTT1Time=new PerfCounter,this._onBeforeRTT1Observer=null,this._onAfterRTT1Observer=null,this._registerAfterRenderTime=new PerfCounter,this._onBeforeRegisterAfterRenderObserver=null,this._onAfterRegisterAfterRenderObserver=null,this._captureFrameTime=!1,this._frameTime=new PerfCounter,this._captureRenderTime=!1,this._renderTime=new PerfCounter,this._captureInterFrameTime=!1,this._interFrameTime=new PerfCounter,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new PerfCounter,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new PerfCounter,this._capturePhysicsTime=!1,this._physicsTime=new PerfCounter,this._captureAnimationsTime=!1,this._animationsTime=new PerfCounter,this._captureCameraRenderTime=!1,this._cameraRenderTime=new PerfCounter,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=i.onBeforeAnimationsObservable.add(function(){e._captureActiveMeshesEvaluationTime&&e._activeMeshesEvaluationTime.fetchNewFrame(),e._captureRenderTargetsRenderTime&&e._renderTargetsRenderTime.fetchNewFrame(),e._captureFrameTime&&(Tools.StartPerformanceCounter("Scene rendering"),e._frameTime.beginMonitoring()),e._captureInterFrameTime&&e._interFrameTime.endMonitoring(),e._captureParticlesRenderTime&&e._particlesRenderTime.fetchNewFrame(),e._captureSpritesRenderTime&&e._spritesRenderTime.fetchNewFrame(),e._captureAnimationsTime&&e._animationsTime.beginMonitoring(),e.scene.getEngine()._drawCalls.fetchNewFrame()}),this._onAfterRenderObserver=i.onAfterRenderObservable.add(function(){e._captureFrameTime&&(Tools.EndPerformanceCounter("Scene rendering"),e._frameTime.endMonitoring()),e._captureRenderTime&&e._renderTime.endMonitoring(!1),e._captureInterFrameTime&&e._interFrameTime.beginMonitoring()}),this._onBeforeRegisterBeforeRenderObserver=i.onBeforeRunRegisterBeforeRenderObservable.add(function(){e._registerBeforeRenderTime.beginMonitoring()}),this._onAfterRegisterBeforeRenderObserver=i.onAfterRunRegisterBeforeRenderObservable.add(function(){e._registerBeforeRenderTime.endMonitoring()}),this._onBeforeRegisterAfterRenderObserver=i.onBeforeRunRegisterAfterRenderObservable.add(function(){e._registerAfterRenderTime.beginMonitoring()}),this._onAfterRegisterAfterRenderObserver=i.onAfterRunRegisterAfterRenderObservable.add(function(){e._registerAfterRenderTime.endMonitoring()}),this._onBeforeRTT1Observer=i.onBeforeRTT1Observable.add(function(){e._RTT1Time.beginMonitoring()}),this._onAfterRTT1Observer=i.onAfterRTT1Observable.add(function(){e._RTT1Time.endMonitoring()})}return Object.defineProperty(a.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(i){var e=this;i!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=i,i?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add(function(){Tools.StartPerformanceCounter("Active meshes evaluation"),e._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(function(){Tools.EndPerformanceCounter("Active meshes evaluation"),e._activeMeshesEvaluationTime.endMonitoring()})):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"registerBeforeTimeCounter",{get:function(){return this._registerBeforeRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"getRTT1TimeCounter",{get:function(){return this._RTT1Time},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"registerAfterTimeCounter",{get:function(){return this._registerAfterRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(i){var e=this;i!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=i,i?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add(function(){Tools.StartPerformanceCounter("Render targets rendering"),e._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(function(){Tools.EndPerformanceCounter("Render targets rendering"),e._renderTargetsRenderTime.endMonitoring(!1)})):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(i){var e=this;i!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=i,i?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add(function(){Tools.StartPerformanceCounter("Particles"),e._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(function(){Tools.EndPerformanceCounter("Particles"),e._particlesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(i){var e=this;i!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=i,this.scene.spriteManagers&&(i?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add(function(){Tools.StartPerformanceCounter("Sprites"),e._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(function(){Tools.EndPerformanceCounter("Sprites"),e._spritesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(i){var e=this;i!==this._capturePhysicsTime&&(!this.scene.onBeforePhysicsObservable||(this._capturePhysicsTime=i,i?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add(function(){Tools.StartPerformanceCounter("Physics"),e._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(function(){Tools.EndPerformanceCounter("Physics"),e._physicsTime.endMonitoring()})):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null)))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(i){var e=this;i!==this._captureAnimationsTime&&(this._captureAnimationsTime=i,i?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add(function(){e._animationsTime.endMonitoring()}):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(i){this._captureFrameTime=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(i){this._captureInterFrameTime=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(i){var e=this;i!==this._captureRenderTime&&(this._captureRenderTime=i,i?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add(function(){e._renderTime.beginMonitoring(),Tools.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(function(){e._renderTime.endMonitoring(!1),Tools.EndPerformanceCounter("Main render")})):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(i){var e=this;i!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=i,i?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add(function(o){e._cameraRenderTime.beginMonitoring(),Tools.StartPerformanceCounter("Rendering camera "+o.name)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(function(o){e._cameraRenderTime.endMonitoring(!1),Tools.EndPerformanceCounter("Rendering camera "+o.name)})):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this.scene.onBeforeRunRegisterBeforeRenderObservable.remove(this._onBeforeRegisterBeforeRenderObserver),this._onBeforeRegisterBeforeRenderObserver=null,this.scene.onAfterRunRegisterBeforeRenderObservable.remove(this._onAfterRegisterBeforeRenderObserver),this._onAfterRegisterBeforeRenderObserver=null,this.scene.onBeforeRunRegisterAfterRenderObservable.remove(this._onBeforeRegisterAfterRenderObserver),this._onBeforeRegisterAfterRenderObserver=null,this.scene.onAfterRunRegisterAfterRenderObservable.remove(this._onAfterRegisterAfterRenderObserver),this._onAfterRegisterAfterRenderObserver=null,this.scene.onBeforeRTT1Observable.remove(this._onBeforeRTT1Observer),this._onBeforeRTT1Observer=null,this.scene.onAfterRTT1Observable.remove(this._onAfterRTT1Observer),this._onAfterRTT1Observer=null,this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},a}(),EngineInstrumentation=function(){function a(i){this.engine=i,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new PerfCounter,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(a.prototype,"gpuFrameTimeCounter",{get:function(){return this.engine.getGPUFrameTimeCounter()},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(i){i!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=i,this.engine.captureGPUFrameTime(i))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(i){var e=this;i!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=i,i?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add(function(){e._shaderCompilationTime.fetchNewFrame(),e._shaderCompilationTime.beginMonitoring()}),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add(function(){e._shaderCompilationTime.endMonitoring()})):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null},a}(),KeepAssets=function(a){__extends(i,a);function i(){return a!==null&&a.apply(this,arguments)||this}return i}(AbstractScene),InstantiatedEntries=function(){function a(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}return a}(),AssetContainer=function(a){__extends(i,a);function i(e){var o=a.call(this)||this;return o._wasAddedToScene=!1,o.scene=e,o.sounds=[],o.effectLayers=[],o.layers=[],o.lensFlareSystems=[],o.proceduralTextures=[],o.reflectionProbes=[],o._onDisposeObservable=e.onDisposeObservable.add(function(){o._wasAddedToScene||o.dispose()}),o._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(function(){for(var s=0,c=o.geometries;s<c.length;s++){var d=c[s];d._rebuild()}for(var _=0,b=o.meshes;_<b.length;_++){var k=b[_];k._rebuild()}for(var j=0,$=o.particleSystems;j<$.length;j++){var _e=$[j];_e.rebuild()}for(var et=0,tt=o.textures;et<tt.length;et++){var rt=tt[et];rt._rebuild()}}),o}return i.prototype.instantiateModelsToScene=function(e,o,s){var c=this;o===void 0&&(o=!1);var d={},_={},b=new InstantiatedEntries,k=[],j=[];s||(s={doNotInstantiate:!0});var $=function(_e,et){if(d[_e.uniqueId]=et.uniqueId,_[et.uniqueId]=et,e&&(et.name=e(_e.name)),et instanceof Mesh){var tt=et;if(tt.morphTargetManager){var rt=_e.morphTargetManager;tt.morphTargetManager=rt.clone();for(var it=0;it<rt.numTargets;it++){var nt=rt.getTarget(it),ot=tt.morphTargetManager.getTarget(it);d[nt.uniqueId]=ot.uniqueId,_[ot.uniqueId]=ot}}}};return this.transformNodes.forEach(function(_e){if(!_e.parent){var et=_e.instantiateHierarchy(null,s,function(tt,rt){$(tt,rt)});et&&b.rootNodes.push(et)}}),this.meshes.forEach(function(_e){if(!_e.parent){var et=_e.instantiateHierarchy(null,s,function(tt,rt){if($(tt,rt),rt.material){var it=rt;if(it.material)if(o){var nt=tt.material;if(j.indexOf(nt)===-1){var ot=nt.clone(e?e(nt.name):"Clone of "+nt.name);if(j.push(nt),d[nt.uniqueId]=ot.uniqueId,_[ot.uniqueId]=ot,nt.getClassName()==="MultiMaterial"){for(var at=nt,st=0,ut=at.subMaterials;st<ut.length;st++){var ft=ut[st];!ft||(ot=ft.clone(e?e(ft.name):"Clone of "+ft.name),j.push(ft),d[ft.uniqueId]=ot.uniqueId,_[ot.uniqueId]=ot)}at.subMaterials=at.subMaterials.map(function(lt){return lt&&_[d[lt.uniqueId]]})}}it.getClassName()!=="InstancedMesh"&&(it.material=_[d[nt.uniqueId]])}else it.material.getClassName()==="MultiMaterial"?c.scene.multiMaterials.indexOf(it.material)===-1&&c.scene.addMultiMaterial(it.material):c.scene.materials.indexOf(it.material)===-1&&c.scene.addMaterial(it.material)}});et&&b.rootNodes.push(et)}}),this.skeletons.forEach(function(_e){var et=_e.clone(e?e(_e.name):"Clone of "+_e.name);_e.overrideMesh&&(et.overrideMesh=_[d[_e.overrideMesh.uniqueId]]);for(var tt=0,rt=c.meshes;tt<rt.length;tt++){var it=rt[tt];if(it.skeleton===_e&&!it.isAnInstance){var nt=_[d[it.uniqueId]];if(nt.isAnInstance||(nt.skeleton=et,k.indexOf(et)!==-1))continue;k.push(et);for(var ot=0,at=et.bones;ot<at.length;ot++){var st=at[ot];st._linkedTransformNode&&(st._linkedTransformNode=_[d[st._linkedTransformNode.uniqueId]])}}}b.skeletons.push(et)}),this.animationGroups.forEach(function(_e){var et=_e.clone(_e.name,function(tt){var rt=_[d[tt.uniqueId]];return rt||tt});b.animationGroups.push(et)}),b},i.prototype.addAllToScene=function(){var e=this;this._wasAddedToScene=!0,this.cameras.forEach(function(d){e.scene.addCamera(d)}),this.lights.forEach(function(d){e.scene.addLight(d)}),this.meshes.forEach(function(d){e.scene.addMesh(d)}),this.skeletons.forEach(function(d){e.scene.addSkeleton(d)}),this.animations.forEach(function(d){e.scene.addAnimation(d)}),this.animationGroups.forEach(function(d){e.scene.addAnimationGroup(d)}),this.multiMaterials.forEach(function(d){e.scene.addMultiMaterial(d)}),this.materials.forEach(function(d){e.scene.addMaterial(d)}),this.morphTargetManagers.forEach(function(d){e.scene.addMorphTargetManager(d)}),this.geometries.forEach(function(d){e.scene.addGeometry(d)}),this.transformNodes.forEach(function(d){e.scene.addTransformNode(d)}),this.actionManagers.forEach(function(d){e.scene.addActionManager(d)}),this.textures.forEach(function(d){e.scene.addTexture(d)}),this.reflectionProbes.forEach(function(d){e.scene.addReflectionProbe(d)}),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(var o=0,s=this.scene._serializableComponents;o<s.length;o++){var c=s[o];c.addFromContainer(this)}this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null},i.prototype.removeAllFromScene=function(){var e=this;this._wasAddedToScene=!1,this.cameras.forEach(function(d){e.scene.removeCamera(d)}),this.lights.forEach(function(d){e.scene.removeLight(d)}),this.meshes.forEach(function(d){e.scene.removeMesh(d)}),this.skeletons.forEach(function(d){e.scene.removeSkeleton(d)}),this.animations.forEach(function(d){e.scene.removeAnimation(d)}),this.animationGroups.forEach(function(d){e.scene.removeAnimationGroup(d)}),this.multiMaterials.forEach(function(d){e.scene.removeMultiMaterial(d)}),this.materials.forEach(function(d){e.scene.removeMaterial(d)}),this.morphTargetManagers.forEach(function(d){e.scene.removeMorphTargetManager(d)}),this.geometries.forEach(function(d){e.scene.removeGeometry(d)}),this.transformNodes.forEach(function(d){e.scene.removeTransformNode(d)}),this.actionManagers.forEach(function(d){e.scene.removeActionManager(d)}),this.textures.forEach(function(d){e.scene.removeTexture(d)}),this.reflectionProbes.forEach(function(d){e.scene.removeReflectionProbe(d)}),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(var o=0,s=this.scene._serializableComponents;o<s.length;o++){var c=s[o];c.removeFromContainer(this)}},i.prototype.dispose=function(){this.cameras.slice(0).forEach(function(c){c.dispose()}),this.cameras=[],this.lights.slice(0).forEach(function(c){c.dispose()}),this.lights=[],this.meshes.slice(0).forEach(function(c){c.dispose()}),this.meshes=[],this.skeletons.slice(0).forEach(function(c){c.dispose()}),this.skeletons=[],this.animationGroups.slice(0).forEach(function(c){c.dispose()}),this.animationGroups=[],this.multiMaterials.slice(0).forEach(function(c){c.dispose()}),this.multiMaterials=[],this.materials.slice(0).forEach(function(c){c.dispose()}),this.materials=[],this.geometries.slice(0).forEach(function(c){c.dispose()}),this.geometries=[],this.transformNodes.slice(0).forEach(function(c){c.dispose()}),this.transformNodes=[],this.actionManagers.slice(0).forEach(function(c){c.dispose()}),this.actionManagers=[],this.textures.slice(0).forEach(function(c){c.dispose()}),this.textures=[],this.reflectionProbes.slice(0).forEach(function(c){c.dispose()}),this.reflectionProbes=[],this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(var e=0,o=this.scene._serializableComponents;e<o.length;e++){var s=o[e];s.removeFromContainer(this,!0)}this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this._onDisposeObservable&&(this.scene.onDisposeObservable.remove(this._onDisposeObservable),this._onDisposeObservable=null)},i.prototype._moveAssets=function(e,o,s){if(!!e)for(var c=0,d=e;c<d.length;c++){var _=d[c],b=!0;if(s)for(var k=0,j=s;k<j.length;k++){var $=j[k];if(_===$){b=!1;break}}b&&(o.push(_),_._parentContainer=this)}},i.prototype.moveAllFromScene=function(e){this._wasAddedToScene=!1,e===void 0&&(e=new KeepAssets);for(var o in this)this.hasOwnProperty(o)&&(this[o]=this[o]||(o==="environmentTexture"?null:[]),this._moveAssets(this.scene[o],this[o],e[o]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()},i.prototype.createRootMesh=function(){var e=new Mesh("assetContainerRootMesh",this.scene);return this.meshes.forEach(function(o){o.parent||e.addChild(o)}),this.meshes.unshift(e),e},i.prototype.mergeAnimationsTo=function(e,o,s){if(e===void 0&&(e=EngineStore.LastCreatedScene),s===void 0&&(s=null),!e)return Logger$2.Error("No scene available to merge animations to"),[];var c=s||function(b){var k=null,j=b.animations.length?b.animations[0].targetProperty:"",$=b.name.split(".").join("").split("_primitive")[0];switch(j){case"position":case"rotationQuaternion":k=e.getTransformNodeByName(b.name)||e.getTransformNodeByName($);break;case"influence":k=e.getMorphTargetByName(b.name)||e.getMorphTargetByName($);break;default:k=e.getNodeByName(b.name)||e.getNodeByName($)}return k},d=this.getNodes();d.forEach(function(b){var k=c(b);if(k!==null){for(var j=function(tt){for(var rt=k.animations.filter(function(st){return st.targetProperty===tt.targetProperty}),it=0,nt=rt;it<nt.length;it++){var ot=nt[it],at=k.animations.indexOf(ot,0);at>-1&&k.animations.splice(at,1)}},$=0,_e=b.animations;$<_e.length;$++){var et=_e[$];j(et)}k.animations=k.animations.concat(b.animations)}});var _=new Array;return this.animationGroups.slice().forEach(function(b){_.push(b.clone(b.name,c)),b.animatables.forEach(function(k){k.stop()})}),o.forEach(function(b){var k=c(b.target);k&&(e.beginAnimation(k,b.fromFrame,b.toFrame,b.loopAnimation,b.speedRatio,b.onAnimationEnd?b.onAnimationEnd:void 0,void 0,!0,void 0,b.onAnimationLoop?b.onAnimationLoop:void 0),e.stopAnimation(b.target))}),_},i}(AbstractScene),Sound=function(){function a(i,e,o,s,c){var d=this;s===void 0&&(s=null);var _,b,k,j,$;if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.spatialSound=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new Observable,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._startOffset=0,this._position=Vector3.Zero(),this._localDirection=new Vector3(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=i,this._scene=o,a._SceneComponentInitialization(o),this._readyToPlayCallback=s,this._customAttenuationFunction=function(nt,ot,at,st,ut){return ot<at?nt*(1-ot/at):0},c&&(this.autoplay=c.autoplay||!1,this._loop=c.loop||!1,c.volume!==void 0&&(this._volume=c.volume),this.spatialSound=(_=c.spatialSound)!==null&&_!==void 0?_:!1,this.maxDistance=(b=c.maxDistance)!==null&&b!==void 0?b:100,this.useCustomAttenuation=(k=c.useCustomAttenuation)!==null&&k!==void 0?k:!1,this.rolloffFactor=c.rolloffFactor||1,this.refDistance=c.refDistance||1,this.distanceModel=c.distanceModel||"linear",this._playbackRate=c.playbackRate||1,this._streaming=(j=c.streaming)!==null&&j!==void 0?j:!1,this._length=c.length,this._offset=c.offset),(($=Engine.audioEngine)===null||$===void 0?void 0:$.canUseWebAudio)&&Engine.audioEngine.audioContext){this._soundGain=Engine.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this.spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);var _e=!0;if(e)try{typeof e=="string"?this._urlType="String":e instanceof ArrayBuffer?this._urlType="ArrayBuffer":e instanceof HTMLMediaElement?this._urlType="MediaElement":e instanceof MediaStream?this._urlType="MediaStream":Array.isArray(e)&&(this._urlType="Array");var et=[],tt=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=Engine.audioEngine.audioContext.createMediaElementSource(e),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=Engine.audioEngine.audioContext.createMediaStreamSource(e),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":e.byteLength>0&&(tt=!0,this._soundLoaded(e));break;case"String":et.push(e);case"Array":et.length===0&&(et=e);for(var rt=0;rt<et.length;rt++){var it=et[rt];if(tt=c&&c.skipCodecCheck||it.indexOf(".mp3",it.length-4)!==-1&&Engine.audioEngine.isMP3supported||it.indexOf(".ogg",it.length-4)!==-1&&Engine.audioEngine.isOGGsupported||it.indexOf(".wav",it.length-4)!==-1||it.indexOf(".m4a",it.length-4)!==-1||it.indexOf("blob:")!==-1,tt){this._streaming?(this._htmlAudioElement=new Audio(it),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,Tools.SetCorsBehavior(it,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",function(){d._isReadyToPlay=!0,d.autoplay&&d.play(0,d._offset,d._length),d._readyToPlayCallback&&d._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(it,function(nt){d._soundLoaded(nt)},void 0,!0,!0,function(nt){nt&&Logger$2.Error("XHR "+nt.status+" error on: "+it+"."),Logger$2.Error("Sound creation aborted."),d._scene.mainSoundTrack.removeSound(d)});break}}break;default:_e=!1;break}_e?tt||(this._isReadyToPlay=!0,this._readyToPlayCallback&&window.setTimeout(function(){d._readyToPlayCallback&&d._readyToPlayCallback()},1e3)):Logger$2.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{Logger$2.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Engine.audioEngine&&!Engine.audioEngine.WarnedWebAudioUnsupported&&(Logger$2.Error("Web Audio is not supported by your browser."),Engine.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&window.setTimeout(function(){d._readyToPlayCallback&&d._readyToPlayCallback()},1e3)}return Object.defineProperty(a.prototype,"loop",{get:function(){return this._loop},set:function(i){i!==this._loop&&(this._loop=i,this.updateOptions({loop:i}))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"currentTime",{get:function(){var i;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;var e=this._startOffset;return this.isPlaying&&((i=Engine.audioEngine)===null||i===void 0?void 0:i.audioContext)&&(e+=Engine.audioEngine.audioContext.currentTime-this._startTime),e},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){var i;!((i=Engine.audioEngine)===null||i===void 0)&&i.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,this.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null))},a.prototype.isReady=function(){return this._isReadyToPlay},a.prototype.getClassName=function(){return"Sound"},a.prototype._soundLoaded=function(i){var e=this,o;!(!((o=Engine.audioEngine)===null||o===void 0)&&o.audioContext)||Engine.audioEngine.audioContext.decodeAudioData(i,function(s){e._audioBuffer=s,e._isReadyToPlay=!0,e.autoplay&&e.play(0,e._offset,e._length),e._readyToPlayCallback&&e._readyToPlayCallback()},function(s){Logger$2.Error("Error while decoding audio data for: "+e.name+" / Error: "+s)})},a.prototype.setAudioBuffer=function(i){var e;!((e=Engine.audioEngine)===null||e===void 0)&&e.canUseWebAudio&&(this._audioBuffer=i,this._isReadyToPlay=!0)},a.prototype.updateOptions=function(i){var e,o,s,c,d,_,b,k,j;i&&(this.loop=(e=i.loop)!==null&&e!==void 0?e:this.loop,this.maxDistance=(o=i.maxDistance)!==null&&o!==void 0?o:this.maxDistance,this.useCustomAttenuation=(s=i.useCustomAttenuation)!==null&&s!==void 0?s:this.useCustomAttenuation,this.rolloffFactor=(c=i.rolloffFactor)!==null&&c!==void 0?c:this.rolloffFactor,this.refDistance=(d=i.refDistance)!==null&&d!==void 0?d:this.refDistance,this.distanceModel=(_=i.distanceModel)!==null&&_!==void 0?_:this.distanceModel,this._playbackRate=(b=i.playbackRate)!==null&&b!==void 0?b:this._playbackRate,this._length=(k=i.length)!==null&&k!==void 0?k:void 0,this._offset=(j=i.offset)!==null&&j!==void 0?j:void 0,this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),this._offset!==void 0&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),this._length!==void 0&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(this._offset|0)+this._length))))},a.prototype._createSpatialParameters=function(){var i;((i=Engine.audioEngine)===null||i===void 0?void 0:i.canUseWebAudio)&&Engine.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=Engine.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))},a.prototype._updateSpatialParameters=function(){this.spatialSound&&this._soundPanner&&(this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel))},a.prototype.switchPanningModelToHRTF=function(){this._panningModel="HRTF",this._switchPanningModel()},a.prototype.switchPanningModelToEqualPower=function(){this._panningModel="equalpower",this._switchPanningModel()},a.prototype._switchPanningModel=function(){var i;((i=Engine.audioEngine)===null||i===void 0?void 0:i.canUseWebAudio)&&this.spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)},a.prototype.connectToSoundTrackAudioNode=function(i){var e;((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(i),this._isOutputConnected=!0)},a.prototype.setDirectionalCone=function(i,e,o){if(e<i){Logger$2.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=i,this._coneOuterAngle=e,this._coneOuterGain=o,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))},Object.defineProperty(a.prototype,"directionalConeInnerAngle",{get:function(){return this._coneInnerAngle},set:function(i){var e;if(i!=this._coneInnerAngle){if(this._coneOuterAngle<i){Logger$2.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=i,((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this.spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"directionalConeOuterAngle",{get:function(){return this._coneOuterAngle},set:function(i){var e;if(i!=this._coneOuterAngle){if(i<this._coneInnerAngle){Logger$2.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneOuterAngle=i,((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this.spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}},enumerable:!1,configurable:!0}),a.prototype.setPosition=function(i){var e;i.equals(this._position)||(this._position.copyFrom(i),((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this.spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z))},a.prototype.setLocalDirectionToMesh=function(i){var e;this._localDirection=i,((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()},a.prototype._updateDirection=function(){if(!(!this._connectedTransformNode||!this._soundPanner)){var i=this._connectedTransformNode.getWorldMatrix(),e=Vector3.TransformNormal(this._localDirection,i);e.normalize(),this._soundPanner.setOrientation(e.x,e.y,e.z)}},a.prototype.updateDistanceFromListener=function(){var i;if(((i=Engine.audioEngine)===null||i===void 0?void 0:i.canUseWebAudio)&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){var e=this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}},a.prototype.setAttenuationFunction=function(i){this._customAttenuationFunction=i},a.prototype.play=function(i,e,o){var s=this,c,d,_,b;if(this._isReadyToPlay&&this._scene.audioEnabled&&((c=Engine.audioEngine)===null||c===void 0?void 0:c.audioContext))try{this._startOffset<0&&(i=-this._startOffset,this._startOffset=0);var k=i?((d=Engine.audioEngine)===null||d===void 0?void 0:d.audioContext.currentTime)+i:(_=Engine.audioEngine)===null||_===void 0?void 0:_.audioContext.currentTime;if((!this._soundSource||!this._streamingSource)&&this.spatialSound&&this._soundPanner&&(!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=function(){s._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){var j=function(){var $,_e;if(!(($=Engine.audioEngine)===null||$===void 0)&&$.unlocked){var et=s._htmlAudioElement.play();et!==void 0&&et.catch(function(tt){var rt,it;(rt=Engine.audioEngine)===null||rt===void 0||rt.lock(),(s.loop||s.autoplay)&&((it=Engine.audioEngine)===null||it===void 0||it.onAudioUnlockedObservable.addOnce(function(){j()}))})}else(s.loop||s.autoplay)&&((_e=Engine.audioEngine)===null||_e===void 0||_e.onAudioUnlockedObservable.addOnce(function(){j()}))};j()}}else{var j=function(){var _e,et,tt;if(!((_e=Engine.audioEngine)===null||_e===void 0)&&_e.audioContext){if(o=o||s._length,e=e||s._offset,s._soundSource){var rt=s._soundSource;rt.onended=function(){rt.disconnect()}}if(s._soundSource=(et=Engine.audioEngine)===null||et===void 0?void 0:et.audioContext.createBufferSource(),s._soundSource&&s._inputAudioNode){s._soundSource.buffer=s._audioBuffer,s._soundSource.connect(s._inputAudioNode),s._soundSource.loop=s.loop,e!==void 0&&(s._soundSource.loopStart=e),o!==void 0&&(s._soundSource.loopEnd=(e|0)+o),s._soundSource.playbackRate.value=s._playbackRate,s._soundSource.onended=function(){s._onended()},k=i?((tt=Engine.audioEngine)===null||tt===void 0?void 0:tt.audioContext.currentTime)+i:Engine.audioEngine.audioContext.currentTime;var it=s.isPaused?s._startOffset%s._soundSource.buffer.duration:e||0;s._soundSource.start(k,it,s.loop?void 0:o)}}};((b=Engine.audioEngine)===null||b===void 0?void 0:b.audioContext.state)==="suspended"?setTimeout(function(){var _e;((_e=Engine.audioEngine)===null||_e===void 0?void 0:_e.audioContext.state)==="suspended"?(Engine.audioEngine.lock(),(s.loop||s.autoplay)&&Engine.audioEngine.onAudioUnlockedObservable.addOnce(function(){j()})):j()},500):j()}this._startTime=k,this.isPlaying=!0,this.isPaused=!1}catch($){Logger$2.Error("Error while trying to play audio: "+this.name+", "+$.message)}},a.prototype._onended=function(){this.isPlaying=!1,this._startOffset=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)},a.prototype.stop=function(i){var e=this,o;if(this.isPlaying){if(this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(((o=Engine.audioEngine)===null||o===void 0?void 0:o.audioContext)&&this._soundSource){var s=i?Engine.audioEngine.audioContext.currentTime+i:void 0;this._soundSource.stop(s),s===void 0?(this.isPlaying=!1,this._soundSource.onended=function(){}):this._soundSource.onended=function(){e.isPlaying=!1},this.isPaused||(this._startOffset=0)}}},a.prototype.pause=function(){var i;this.isPlaying&&(this.isPaused=!0,this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1):!((i=Engine.audioEngine)===null||i===void 0)&&i.audioContext&&(this.stop(0),this._startOffset+=Engine.audioEngine.audioContext.currentTime-this._startTime))},a.prototype.setVolume=function(i,e){var o;((o=Engine.audioEngine)===null||o===void 0?void 0:o.canUseWebAudio)&&this._soundGain&&(e&&Engine.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(i,Engine.audioEngine.audioContext.currentTime+e)):this._soundGain.gain.value=i),this._volume=i},a.prototype.setPlaybackRate=function(i){this._playbackRate=i,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},a.prototype.getVolume=function(){return this._volume},a.prototype.attachToMesh=function(i){var e=this;this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=i,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=function(o){return e._onRegisterAfterWorldMatrixUpdate(o)},this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)},a.prototype.detachFromMesh=function(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)},a.prototype._onRegisterAfterWorldMatrixUpdate=function(i){var e;if(!i.getBoundingInfo)this.setPosition(i.absolutePosition);else{var o=i,s=o.getBoundingInfo();this.setPosition(s.boundingSphere.centerWorld)}((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()},a.prototype.clone=function(){var i=this;if(this._streaming)return null;var e=function(){i._isReadyToPlay?(s._audioBuffer=i.getAudioBuffer(),s._isReadyToPlay=!0,s.autoplay&&s.play(0,i._offset,i._length)):window.setTimeout(e,300)},o={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},s=new a(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,o);return this.useCustomAttenuation&&s.setAttenuationFunction(this._customAttenuationFunction),s.setPosition(this._position),s.setPlaybackRate(this._playbackRate),e(),s},a.prototype.getAudioBuffer=function(){return this._audioBuffer},a.prototype.getSoundSource=function(){return this._soundSource},a.prototype.getSoundGain=function(){return this._soundGain},a.prototype.serialize=function(){var i={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this.spatialSound&&(this._connectedTransformNode&&(i.connectedMeshId=this._connectedTransformNode.id),i.position=this._position.asArray(),i.refDistance=this.refDistance,i.distanceModel=this.distanceModel,i.isDirectional=this._isDirectional,i.localDirectionToMesh=this._localDirection.asArray(),i.coneInnerAngle=this._coneInnerAngle,i.coneOuterAngle=this._coneOuterAngle,i.coneOuterGain=this._coneOuterGain),i},a.Parse=function(i,e,o,s){var c=i.name,d;i.url?d=o+i.url:d=o+c;var _={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate},b;if(!s)b=new a(c,d,e,function(){e._removePendingData(b)},_),e._addPendingData(b);else{var k=function(){s._isReadyToPlay?(b._audioBuffer=s.getAudioBuffer(),b._isReadyToPlay=!0,b.autoplay&&b.play(0,b._offset,b._length)):window.setTimeout(k,300)};b=new a(c,new ArrayBuffer(0),e,null,_),k()}if(i.position){var j=Vector3.FromArray(i.position);b.setPosition(j)}if(i.isDirectional&&(b.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var $=Vector3.FromArray(i.localDirectionToMesh);b.setLocalDirectionToMesh($)}if(i.connectedMeshId){var _e=e.getMeshById(i.connectedMeshId);_e&&b.attachToMesh(_e)}return i.metadata&&(b.metadata=i.metadata),b},a._SceneComponentInitialization=function(i){throw _WarnImport("AudioSceneComponent")},a}(),ThinSprite=function(){function a(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}return Object.defineProperty(a.prototype,"animationStarted",{get:function(){return this._animationStarted},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"fromIndex",{get:function(){return this._fromIndex},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"toIndex",{get:function(){return this._toIndex},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"loopAnimation",{get:function(){return this._loopAnimation},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"delay",{get:function(){return Math.max(this._delay,1)},enumerable:!1,configurable:!0}),a.prototype.playAnimation=function(i,e,o,s,c){this._fromIndex=i,this._toIndex=e,this._loopAnimation=o,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=c,i<e?this._direction=1:(this._direction=-1,this._toIndex=i,this._fromIndex=e),this.cellIndex=i,this._time=0},a.prototype.stopAnimation=function(){this._animationStarted=!1},a.prototype._animate=function(i){!this._animationStarted||(this._time+=i,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))},a}(),Sprite=function(a){__extends(i,a);function i(e,o){var s=a.call(this)||this;return s.name=e,s.animations=new Array,s.isPickable=!1,s.useAlphaForPicking=!1,s.onDisposeObservable=new Observable,s._onAnimationEnd=null,s._endAnimation=function(){s._onAnimationEnd&&s._onAnimationEnd(),s.disposeWhenFinishedAnimating&&s.dispose()},s.color=new Color4(1,1,1,1),s.position=Vector3.Zero(),s._manager=o,s._manager.sprites.push(s),s.uniqueId=s._manager.scene.getUniqueId(),s}return Object.defineProperty(i.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"manager",{get:function(){return this._manager},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"Sprite"},Object.defineProperty(i.prototype,"fromIndex",{get:function(){return this._fromIndex},set:function(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"toIndex",{get:function(){return this._toIndex},set:function(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"loopAnimation",{get:function(){return this._loopAnimation},set:function(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"delay",{get:function(){return Math.max(this._delay,1)},set:function(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)},enumerable:!1,configurable:!0}),i.prototype.playAnimation=function(e,o,s,c,d){d===void 0&&(d=null),this._onAnimationEnd=d,a.prototype.playAnimation.call(this,e,o,s,c,this._endAnimation)},i.prototype.dispose=function(){for(var e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1);this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},i.prototype.serialize=function(){var e={};return e.name=this.name,e.position=this.position.asArray(),e.color=this.color.asArray(),e.width=this.width,e.height=this.height,e.angle=this.angle,e.cellIndex=this.cellIndex,e.cellRef=this.cellRef,e.invertU=this.invertU,e.invertV=this.invertV,e.disposeWhenFinishedAnimating=this.disposeWhenFinishedAnimating,e.isPickable=this.isPickable,e.isVisible=this.isVisible,e.useAlphaForPicking=this.useAlphaForPicking,e.animationStarted=this.animationStarted,e.fromIndex=this.fromIndex,e.toIndex=this.toIndex,e.loopAnimation=this.loopAnimation,e.delay=this.delay,e},i.Parse=function(e,o){var s=new i(e.name,o);return s.position=Vector3.FromArray(e.position),s.color=Color4.FromArray(e.color),s.width=e.width,s.height=e.height,s.angle=e.angle,s.cellIndex=e.cellIndex,s.cellRef=e.cellRef,s.invertU=e.invertU,s.invertV=e.invertV,s.disposeWhenFinishedAnimating=e.disposeWhenFinishedAnimating,s.isPickable=e.isPickable,s.isVisible=e.isVisible,s.useAlphaForPicking=e.useAlphaForPicking,s.fromIndex=e.fromIndex,s.toIndex=e.toIndex,s.loopAnimation=e.loopAnimation,s.delay=e.delay,e.animationStarted&&s.playAnimation(s.fromIndex,s.toIndex,s.loopAnimation,s.delay),s},i}(ThinSprite);Scene.prototype._internalPickSprites=function(a,i,e,o){if(!PickingInfo)return null;var s=null;if(!o){if(!this.activeCamera)return null;o=this.activeCamera}if(this.spriteManagers.length>0)for(var c=0;c<this.spriteManagers.length;c++){var d=this.spriteManagers[c];if(!!d.isPickable){var _=d.intersects(a,o,i,e);if(!(!_||!_.hit)&&!(!e&&s!=null&&_.distance>=s.distance)&&(s=_,e))break}}return s||new PickingInfo};Scene.prototype._internalMultiPickSprites=function(a,i,e){if(!PickingInfo)return null;var o=new Array;if(!e){if(!this.activeCamera)return null;e=this.activeCamera}if(this.spriteManagers.length>0)for(var s=0;s<this.spriteManagers.length;s++){var c=this.spriteManagers[s];if(!!c.isPickable){var d=c.multiIntersects(a,e,i);d!==null&&(o=o.concat(d))}}return o};Scene.prototype.pickSprite=function(a,i,e,o,s){if(!this._tempSpritePickingRay)return null;this.createPickingRayInCameraSpaceToRef(a,i,this._tempSpritePickingRay,s);var c=this._internalPickSprites(this._tempSpritePickingRay,e,o,s);return c&&(c.ray=this.createPickingRayInCameraSpace(a,i,s)),c};Scene.prototype.pickSpriteWithRay=function(a,i,e,o){if(!this._tempSpritePickingRay)return null;if(!o){if(!this.activeCamera)return null;o=this.activeCamera}Ray.TransformToRef(a,o.getViewMatrix(),this._tempSpritePickingRay);var s=this._internalPickSprites(this._tempSpritePickingRay,i,e,o);return s&&(s.ray=a),s};Scene.prototype.multiPickSprite=function(a,i,e,o){return this.createPickingRayInCameraSpaceToRef(a,i,this._tempSpritePickingRay,o),this._internalMultiPickSprites(this._tempSpritePickingRay,e,o)};Scene.prototype.multiPickSpriteWithRay=function(a,i,e){if(!this._tempSpritePickingRay)return null;if(!e){if(!this.activeCamera)return null;e=this.activeCamera}return Ray.TransformToRef(a,e.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,i,e)};Scene.prototype.setPointerOverSprite=function(a){this._pointerOverSprite!==a&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(10,ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=a,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(9,ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))};Scene.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};var SpriteSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_SPRITE,this.scene=i,this.scene.spriteManagers=new Array,this.scene._tempSpritePickingRay=Ray?Ray.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new Observable,this.scene.onAfterSpritesRenderingObservable=new Observable,this._spritePredicate=function(e){return e.actionManager?e.isPickable&&e.actionManager.hasPointerTriggers:!1}}return a.prototype.register=function(){this.scene._pointerMoveStage.registerStep(SceneComponentConstants.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(SceneComponentConstants.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(SceneComponentConstants.STEP_POINTERUP_SPRITE,this,this._pointerUp)},a.prototype.rebuild=function(){},a.prototype.dispose=function(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();for(var i=this.scene.spriteManagers;i.length;)i[0].dispose()},a.prototype._pickSpriteButKeepRay=function(i,e,o,s,c){var d=this.scene.pickSprite(e,o,this._spritePredicate,s,c);return d&&(d.ray=i?i.ray:null),d},a.prototype._pointerMove=function(i,e,o,s,c){var d=this.scene;return s?d.setPointerOverSprite(null):(o=this._pickSpriteButKeepRay(o,i,e,!1,d.cameraToUseForPointers||void 0),o&&o.hit&&o.pickedSprite?(d.setPointerOverSprite(o.pickedSprite),!d.doNotHandleCursors&&c&&(d._pointerOverSprite&&d._pointerOverSprite.actionManager&&d._pointerOverSprite.actionManager.hoverCursor?c.style.cursor=d._pointerOverSprite.actionManager.hoverCursor:c.style.cursor=d.hoverCursor)):d.setPointerOverSprite(null)),o},a.prototype._pointerDown=function(i,e,o,s){var c=this.scene;if(c._pickedDownSprite=null,c.spriteManagers.length>0&&(o=c.pickSprite(i,e,this._spritePredicate,!1,c.cameraToUseForPointers||void 0),o&&o.hit&&o.pickedSprite&&o.pickedSprite.actionManager)){switch(c._pickedDownSprite=o.pickedSprite,s.button){case 0:o.pickedSprite.actionManager.processTrigger(2,ActionEvent.CreateNewFromSprite(o.pickedSprite,c,s));break;case 1:o.pickedSprite.actionManager.processTrigger(4,ActionEvent.CreateNewFromSprite(o.pickedSprite,c,s));break;case 2:o.pickedSprite.actionManager.processTrigger(3,ActionEvent.CreateNewFromSprite(o.pickedSprite,c,s));break}o.pickedSprite.actionManager&&o.pickedSprite.actionManager.processTrigger(5,ActionEvent.CreateNewFromSprite(o.pickedSprite,c,s))}return o},a.prototype._pointerUp=function(i,e,o,s){var c=this.scene;if(c.spriteManagers.length>0){var d=c.pickSprite(i,e,this._spritePredicate,!1,c.cameraToUseForPointers||void 0);d&&(d.hit&&d.pickedSprite&&d.pickedSprite.actionManager&&(d.pickedSprite.actionManager.processTrigger(7,ActionEvent.CreateNewFromSprite(d.pickedSprite,c,s)),d.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||d.pickedSprite.actionManager.processTrigger(1,ActionEvent.CreateNewFromSprite(d.pickedSprite,c,s)))),c._pickedDownSprite&&c._pickedDownSprite.actionManager&&c._pickedDownSprite!==d.pickedSprite&&c._pickedDownSprite.actionManager.processTrigger(16,ActionEvent.CreateNewFromSprite(c._pickedDownSprite,c,s)))}return o},a}(),name$l="spritesPixelShader",shader$l=`uniform bool alphaTest;
  10118. varying vec4 vColor;
  10119. varying vec2 vUV;
  10120. uniform sampler2D diffuseSampler;
  10121. #include<fogFragmentDeclaration>
  10122. void main(void) {
  10123. vec4 color=texture2D(diffuseSampler,vUV);
  10124. if (alphaTest)
  10125. {
  10126. if (color.a<0.95)
  10127. discard;
  10128. }
  10129. color*=vColor;
  10130. #include<fogFragment>
  10131. gl_FragColor=color;
  10132. #include<imageProcessingCompatibility>
  10133. }`;ShaderStore.ShadersStore[name$l]=shader$l;var name$k="spritesVertexShader",shader$k=`
  10134. attribute vec4 position;
  10135. attribute vec2 options;
  10136. attribute vec2 offsets;
  10137. attribute vec2 inverts;
  10138. attribute vec4 cellInfo;
  10139. attribute vec4 color;
  10140. uniform mat4 view;
  10141. uniform mat4 projection;
  10142. varying vec2 vUV;
  10143. varying vec4 vColor;
  10144. #include<fogVertexDeclaration>
  10145. void main(void) {
  10146. vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz;
  10147. vec2 cornerPos;
  10148. float angle=position.w;
  10149. vec2 size=vec2(options.x,options.y);
  10150. vec2 offset=offsets.xy;
  10151. cornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;
  10152. vec3 rotatedCorner;
  10153. rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
  10154. rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
  10155. rotatedCorner.z=0.;
  10156. viewPos+=rotatedCorner;
  10157. gl_Position=projection*vec4(viewPos,1.0);
  10158. vColor=color;
  10159. vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));
  10160. vec2 uvPlace=cellInfo.xy;
  10161. vec2 uvSize=cellInfo.zw;
  10162. vUV.x=uvPlace.x+uvSize.x*uvOffset.x;
  10163. vUV.y=uvPlace.y+uvSize.y*uvOffset.y;
  10164. #ifdef FOG
  10165. vFogDistance=viewPos;
  10166. #endif
  10167. }`;ShaderStore.ShadersStore[name$k]=shader$k;var SpriteRenderer=function(){function a(i,e,o,s){o===void 0&&(o=.01),s===void 0&&(s=null),this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=e,this._epsilon=o,this._engine=i,this._useInstancing=i.getCaps().instancedArrays,this._useVAO=i.getCaps().vertexArrayObject&&!i.disableVertexArrayObjects,this._scene=s,this._drawWrapperBase=new DrawWrapper(i),this._drawWrapperFog=new DrawWrapper(i),this._drawWrapperDepth=new DrawWrapper(i,!1),this._drawWrapperFogDepth=new DrawWrapper(i,!1),this._useInstancing||this._buildIndexBuffer(),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(e*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Buffer(i,this._vertexData,!0,this._vertexBufferSize);var c=this._buffer.createVertexBuffer(VertexBuffer.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),d=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),_=6,b;if(this._useInstancing){var k=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Buffer(i,k,!1,2),b=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else b=this._buffer.createVertexBuffer("offsets",_,2,this._vertexBufferSize,this._useInstancing),_+=2;var j=this._buffer.createVertexBuffer("inverts",_,2,this._vertexBufferSize,this._useInstancing),$=this._buffer.createVertexBuffer("cellInfo",_+2,4,this._vertexBufferSize,this._useInstancing),_e=this._buffer.createVertexBuffer(VertexBuffer.ColorKind,_+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[VertexBuffer.PositionKind]=c,this._vertexBuffers.options=d,this._vertexBuffers.offsets=b,this._vertexBuffers.inverts=j,this._vertexBuffers.cellInfo=$,this._vertexBuffers[VertexBuffer.ColorKind]=_e,this._drawWrapperBase.effect=this._engine.createEffect("sprites",[VertexBuffer.PositionKind,"options","offsets","inverts","cellInfo",VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],""),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[VertexBuffer.PositionKind,"options","offsets","inverts","cellInfo",VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}return Object.defineProperty(a.prototype,"capacity",{get:function(){return this._capacity},enumerable:!1,configurable:!0}),a.prototype.render=function(i,e,o,s,c){if(c===void 0&&(c=null),!(!this.texture||!this.texture.isReady()||!i.length)){var d=this._drawWrapperBase,_=this._drawWrapperDepth,b=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&this._scene.fogMode!==0&&(d=this._drawWrapperFog,_=this._drawWrapperFogDepth,b=!0);var k=d.effect;if(!!k.isReady()){for(var j=this._engine,$=!!(this._scene&&this._scene.useRightHandedSystem),_e=this.texture.getBaseSize(),et=Math.min(this._capacity,i.length),tt=0,rt=!0,it=0;it<et;it++){var nt=i[it];!nt||!nt.isVisible||(rt=!1,nt._animate(e),this._appendSpriteVertex(tt++,nt,0,0,_e,$,c),this._useInstancing||(this._appendSpriteVertex(tt++,nt,1,0,_e,$,c),this._appendSpriteVertex(tt++,nt,1,1,_e,$,c),this._appendSpriteVertex(tt++,nt,0,1,_e,$,c)))}if(!rt){this._buffer.update(this._vertexData);var ot=j.depthCullingState.cull||!0,at=j.depthCullingState.zOffset,st=j.depthCullingState.zOffsetUnits;if(j.setState(ot,at,!1,!1,void 0,void 0,st),j.enableEffect(d),k.setTexture("diffuseSampler",this.texture),k.setMatrix("view",o),k.setMatrix("projection",s),b){var ut=this._scene;k.setFloat4("vFogInfos",ut.fogMode,ut.fogStart,ut.fogEnd,ut.fogDensity),k.setColor3("vFogColor",ut.fogColor)}this._useVAO?(this._vertexArrayObject||(this._vertexArrayObject=j.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,k)),j.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):j.bindBuffers(this._vertexBuffers,this._indexBuffer,k),j.depthCullingState.depthFunc=j.useReverseDepthBuffer?518:515,this.disableDepthWrite||(k.setBool("alphaTest",!0),j.setColorWrite(!1),j.enableEffect(_),this._useInstancing?j.drawArraysType(7,0,4,tt):j.drawElementsType(0,0,tt/4*6),j.enableEffect(d),j.setColorWrite(!0),k.setBool("alphaTest",!1)),j.setAlphaMode(this.blendMode),this._useInstancing?j.drawArraysType(7,0,4,tt):j.drawElementsType(0,0,tt/4*6),this.autoResetAlpha&&j.setAlphaMode(0),$&&this._scene.getEngine().setState(ot,at,!1,!0,void 0,void 0,st),j.unbindInstanceAttributes()}}}},a.prototype._appendSpriteVertex=function(i,e,o,s,c,d,_){var b=i*this._vertexBufferSize;if(o===0?o=this._epsilon:o===1&&(o=1-this._epsilon),s===0?s=this._epsilon:s===1&&(s=1-this._epsilon),_)_(e,c);else{e.cellIndex||(e.cellIndex=0);var k=c.width/this.cellWidth,j=e.cellIndex/k>>0;e._xOffset=(e.cellIndex-j*k)*this.cellWidth/c.width,e._yOffset=j*this.cellHeight/c.height,e._xSize=this.cellWidth,e._ySize=this.cellHeight}this._vertexData[b]=e.position.x,this._vertexData[b+1]=e.position.y,this._vertexData[b+2]=e.position.z,this._vertexData[b+3]=e.angle,this._vertexData[b+4]=e.width,this._vertexData[b+5]=e.height,this._useInstancing?b-=2:(this._vertexData[b+6]=o,this._vertexData[b+7]=s),d?this._vertexData[b+8]=e.invertU?0:1:this._vertexData[b+8]=e.invertU?1:0,this._vertexData[b+9]=e.invertV?1:0,this._vertexData[b+10]=e._xOffset,this._vertexData[b+11]=e._yOffset,this._vertexData[b+12]=e._xSize/c.width,this._vertexData[b+13]=e._ySize/c.height,this._vertexData[b+14]=e.color.r,this._vertexData[b+15]=e.color.g,this._vertexData[b+16]=e.color.b,this._vertexData[b+17]=e.color.a},a.prototype._buildIndexBuffer=function(){for(var i=[],e=0,o=0;o<this._capacity;o++)i.push(e),i.push(e+1),i.push(e+2),i.push(e),i.push(e+2),i.push(e+3),e+=4;this._indexBuffer=this._engine.createIndexBuffer(i)},a.prototype.rebuild=function(){var i;this._indexBuffer&&this._buildIndexBuffer(),this._useVAO&&(this._vertexArrayObject=void 0),this._buffer._rebuild();for(var e in this._vertexBuffers){var o=this._vertexBuffers[e];o._rebuild()}(i=this._spriteBuffer)===null||i===void 0||i._rebuild()},a.prototype.dispose=function(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this.texture&&(this.texture.dispose(),this.texture=null),this._drawWrapperBase.dispose(),this._drawWrapperFog.dispose(),this._drawWrapperDepth.dispose(),this._drawWrapperFogDepth.dispose()},a}(),SpriteManager=function(){function a(i,e,o,s,c,d,_,b,k){var j=this;d===void 0&&(d=.01),_===void 0&&(_=Texture.TRILINEAR_SAMPLINGMODE),b===void 0&&(b=!1),k===void 0&&(k=null),this.name=i,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.onDisposeObservable=new Observable,this._disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=function(_e,et){_e.cellRef||(_e.cellIndex=0);var tt=_e.cellIndex;typeof tt=="number"&&isFinite(tt)&&Math.floor(tt)===tt&&(_e.cellRef=j._spriteMap[_e.cellIndex]),_e._xOffset=j._cellData[_e.cellRef].frame.x/et.width,_e._yOffset=j._cellData[_e.cellRef].frame.y/et.height,_e._xSize=j._cellData[_e.cellRef].frame.w,_e._ySize=j._cellData[_e.cellRef].frame.h},c||(c=Engine.LastCreatedScene),c._getComponent(SceneComponentConstants.NAME_SPRITE)||c._addComponent(new SpriteSceneComponent(c)),this._fromPacked=b,this._scene=c;var $=this._scene.getEngine();if(this._spriteRenderer=new SpriteRenderer($,o,d,c),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else if(s!==void 0)this.cellWidth=s,this.cellHeight=s;else{this._spriteRenderer=null;return}this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),e&&(this.texture=new Texture(e,c,!0,!1,_)),this._fromPacked&&this._makePacked(e,k)}return Object.defineProperty(a.prototype,"onDispose",{set:function(i){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"children",{get:function(){return this.sprites},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"capacity",{get:function(){return this._spriteRenderer.capacity},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"texture",{get:function(){return this._spriteRenderer.texture},set:function(i){i.wrapU=Texture.CLAMP_ADDRESSMODE,i.wrapV=Texture.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=i,this._textureContent=null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"cellWidth",{get:function(){return this._spriteRenderer.cellWidth},set:function(i){this._spriteRenderer.cellWidth=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"cellHeight",{get:function(){return this._spriteRenderer.cellHeight},set:function(i){this._spriteRenderer.cellHeight=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"fogEnabled",{get:function(){return this._spriteRenderer.fogEnabled},set:function(i){this._spriteRenderer.fogEnabled=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"blendMode",{get:function(){return this._spriteRenderer.blendMode},set:function(i){this._spriteRenderer.blendMode=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"disableDepthWrite",{get:function(){return this._disableDepthWrite},set:function(i){this._disableDepthWrite=i,this._spriteRenderer.disableDepthWrite=i},enumerable:!1,configurable:!0}),a.prototype.getClassName=function(){return"SpriteManager"},a.prototype._makePacked=function(i,e){var o=this;if(e!==null)try{var s=void 0;if(typeof e=="string"?s=JSON.parse(e):s=e,s.frames.length){for(var c={},d=0;d<s.frames.length;d++){var _=s.frames[d];if(typeof Object.keys(_)[0]!="string")throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");var b=_[Object.keys(_)[0]];c[b]=_}s.frames=c}var k=Reflect.ownKeys(s.frames);this._spriteMap=k,this._packedAndReady=!0,this._cellData=s.frames}catch{throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{var j=/\./g,$=void 0;do $=j.lastIndex,j.test(i);while(j.lastIndex>0);var _e=i.substring(0,$-1)+".json",et=new XMLHttpRequest;et.open("GET",_e,!0),et.onerror=function(){Logger$2.Error("JSON ERROR: Unable to load JSON file."),o._fromPacked=!1,o._packedAndReady=!1},et.onload=function(){try{var tt=JSON.parse(et.response),rt=Reflect.ownKeys(tt.frames);o._spriteMap=rt,o._packedAndReady=!0,o._cellData=tt.frames}catch{throw o._fromPacked=!1,o._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}},et.send()}},a.prototype._checkTextureAlpha=function(i,e,o,s,c){if(!i.useAlphaForPicking||!this.texture)return!0;var d=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(d.width*d.height*4),this.texture.readPixels(0,0,this._textureContent));var _=TmpVectors.Vector3[0];_.copyFrom(e.direction),_.normalize(),_.scaleInPlace(o),_.addInPlace(e.origin);var b=(_.x-s.x)/(c.x-s.x)-.5,k=1-(_.y-s.y)/(c.y-s.y)-.5,j=i.angle,$=.5+(b*Math.cos(j)-k*Math.sin(j)),_e=.5+(b*Math.sin(j)+k*Math.cos(j)),et=i._xOffset*d.width+$*i._xSize|0,tt=i._yOffset*d.height+_e*i._ySize|0,rt=this._textureContent[(et+tt*d.width)*4+3];return rt>.5},a.prototype.intersects=function(i,e,o,s){for(var c=Math.min(this.capacity,this.sprites.length),d=Vector3.Zero(),_=Vector3.Zero(),b=Number.MAX_VALUE,k=null,j=TmpVectors.Vector3[0],$=TmpVectors.Vector3[1],_e=e.getViewMatrix(),et=i,tt=i,rt=0;rt<c;rt++){var it=this.sprites[rt];if(!!it){if(o){if(!o(it))continue}else if(!it.isPickable)continue;if(Vector3.TransformCoordinatesToRef(it.position,_e,$),it.angle?(Matrix.TranslationToRef(-$.x,-$.y,0,TmpVectors.Matrix[1]),Matrix.TranslationToRef($.x,$.y,0,TmpVectors.Matrix[2]),Matrix.RotationZToRef(it.angle,TmpVectors.Matrix[3]),TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3],TmpVectors.Matrix[4]),TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2],TmpVectors.Matrix[0]),et=i.clone(),Vector3.TransformCoordinatesToRef(i.origin,TmpVectors.Matrix[0],et.origin),Vector3.TransformNormalToRef(i.direction,TmpVectors.Matrix[0],et.direction)):et=i,d.copyFromFloats($.x-it.width/2,$.y-it.height/2,$.z),_.copyFromFloats($.x+it.width/2,$.y+it.height/2,$.z),et.intersectsBoxMinMax(d,_)){var nt=Vector3.Distance($,et.origin);if(b>nt){if(!this._checkTextureAlpha(it,et,nt,d,_))continue;if(tt=et,b=nt,k=it,s)break}}}}if(k){var ot=new PickingInfo;_e.invertToRef(TmpVectors.Matrix[0]),ot.hit=!0,ot.pickedSprite=k,ot.distance=b;var at=TmpVectors.Vector3[2];return at.copyFrom(tt.direction),at.normalize(),at.scaleInPlace(b),tt.origin.addToRef(at,j),ot.pickedPoint=Vector3.TransformCoordinates(j,TmpVectors.Matrix[0]),ot}return null},a.prototype.multiIntersects=function(i,e,o){for(var s=Math.min(this.capacity,this.sprites.length),c=Vector3.Zero(),d=Vector3.Zero(),_,b=[],k=TmpVectors.Vector3[0].copyFromFloats(0,0,0),j=TmpVectors.Vector3[1].copyFromFloats(0,0,0),$=e.getViewMatrix(),_e=0;_e<s;_e++){var et=this.sprites[_e];if(!!et){if(o){if(!o(et))continue}else if(!et.isPickable)continue;if(Vector3.TransformCoordinatesToRef(et.position,$,j),c.copyFromFloats(j.x-et.width/2,j.y-et.height/2,j.z),d.copyFromFloats(j.x+et.width/2,j.y+et.height/2,j.z),i.intersectsBoxMinMax(c,d)){if(_=Vector3.Distance(j,i.origin),!this._checkTextureAlpha(et,i,_,c,d))continue;var tt=new PickingInfo;b.push(tt),$.invertToRef(TmpVectors.Matrix[0]),tt.hit=!0,tt.pickedSprite=et,tt.distance=_;var rt=TmpVectors.Vector3[2];rt.copyFrom(i.direction),rt.normalize(),rt.scaleInPlace(_),i.origin.addToRef(rt,k),tt.pickedPoint=Vector3.TransformCoordinates(k,TmpVectors.Matrix[0])}}}return b},a.prototype.render=function(){if(!(this._fromPacked&&(!this._packedAndReady||!this._spriteMap||!this._cellData))){var i=16.6;this._packedAndReady?this._spriteRenderer.render(this.sprites,i,this._scene.getViewMatrix(),this._scene.getProjectionMatrix(),this._customUpdate):this._spriteRenderer.render(this.sprites,i,this._scene.getViewMatrix(),this._scene.getProjectionMatrix())}},a.prototype.rebuild=function(){var i;(i=this._spriteRenderer)===null||i===void 0||i.rebuild()},a.prototype.dispose=function(){this._spriteRenderer&&(this._spriteRenderer.dispose(),this._spriteRenderer=null),this._textureContent=null;var i=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},a.prototype.serialize=function(i){i===void 0&&(i=!1);var e={};e.name=this.name,e.capacity=this.capacity,e.cellWidth=this.cellWidth,e.cellHeight=this.cellHeight,this.texture&&(i?e.texture=this.texture.serialize():(e.textureUrl=this.texture.name,e.invertY=this.texture._invertY)),e.sprites=[];for(var o=0,s=this.sprites;o<s.length;o++){var c=s[o];e.sprites.push(c.serialize())}return e},a.Parse=function(i,e,o){var s=new a(i.name,"",i.capacity,{width:i.cellWidth,height:i.cellHeight},e);i.texture?s.texture=Texture.Parse(i.texture,e,o):i.textureName&&(s.texture=new Texture(o+i.textureUrl,e,!1,i.invertY!==void 0?i.invertY:!0));for(var c=0,d=i.sprites;c<d.length;c++){var _=d[c];Sprite.Parse(_,s)}return s},a.ParseFromFileAsync=function(i,e,o,s){return s===void 0&&(s=""),new Promise(function(c,d){var _=new WebRequest;_.addEventListener("readystatechange",function(){if(_.readyState==4)if(_.status==200){var b=JSON.parse(_.responseText),k=a.Parse(b,o||Engine.LastCreatedScene,s);i&&(k.name=i),c(k)}else d("Unable to load the sprite manager")}),_.open("GET",e),_.send()})},a.CreateFromSnippetAsync=function(i,e,o){var s=this;return o===void 0&&(o=""),i==="_BLANK"?Promise.resolve(new a("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,e)):new Promise(function(c,d){var _=new WebRequest;_.addEventListener("readystatechange",function(){if(_.readyState==4)if(_.status==200){var b=JSON.parse(JSON.parse(_.responseText).jsonPayload),k=JSON.parse(b.spriteManager),j=a.Parse(k,e||Engine.LastCreatedScene,o);j.snippetId=i,c(j)}else d("Unable to load the snippet "+i)}),_.open("GET",s.SnippetUrl+"/"+i.replace(/#/g,"/")),_.send()})},a.SnippetUrl="https://snippet.babylonjs.com",a}(),UtilityLayerRenderer=function(){function a(i,e){var o=this;e===void 0&&(e=!0),this.originalScene=i,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new Observable,this.utilityLayerScene=new Scene(i.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=i.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.detachControl(),e&&(this._originalPointerObserver=i.onPrePointerObservable.add(function(s,c){if(!!o.utilityLayerScene.activeCamera&&!!o.pickingEnabled&&!(!o.processAllEvents&&s.type!==PointerEventTypes.POINTERMOVE&&s.type!==PointerEventTypes.POINTERUP&&s.type!==PointerEventTypes.POINTERDOWN&&s.type!==PointerEventTypes.POINTERDOUBLETAP)){o.utilityLayerScene.pointerX=i.pointerX,o.utilityLayerScene.pointerY=i.pointerY;var d=s.event;if(i.isPointerCaptured(d.pointerId)){o._pointerCaptures[d.pointerId]=!1;return}var _=function($){var _e=null;if(s.nearInteractionPickingInfo)s.nearInteractionPickingInfo.pickedMesh.getScene()==$?_e=s.nearInteractionPickingInfo:_e=new PickingInfo;else{var et=null;o._renderCamera&&(et=$._activeCamera,$._activeCamera=o._renderCamera,s.ray=null),_e=s.ray?$.pickWithRay(s.ray):$.pick(i.pointerX,i.pointerY),et&&($._activeCamera=et)}return _e},b=_(o.utilityLayerScene);if(!s.ray&&b&&(s.ray=b.ray),o.utilityLayerScene.onPrePointerObservable.notifyObservers(s),o.onlyCheckPointerDownEvents&&s.type!=PointerEventTypes.POINTERDOWN){s.skipOnPointerObservable||o.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(s.type,s.event,b),s.type),s.type===PointerEventTypes.POINTERUP&&o._pointerCaptures[d.pointerId]&&(o._pointerCaptures[d.pointerId]=!1);return}if(o.utilityLayerScene.autoClearDepthAndStencil||o.pickUtilitySceneFirst)b&&b.hit&&(s.skipOnPointerObservable||o.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(s.type,s.event,b),s.type),s.skipOnPointerObservable=!0);else{var k=_(i),j=s.event;k&&b&&(b.distance===0&&k.pickedMesh?o.mainSceneTrackerPredicate&&o.mainSceneTrackerPredicate(k.pickedMesh)?(o._notifyObservers(s,k,j),s.skipOnPointerObservable=!0):s.type===PointerEventTypes.POINTERDOWN?o._pointerCaptures[j.pointerId]=!0:(s.type===PointerEventTypes.POINTERMOVE||s.type===PointerEventTypes.POINTERUP)&&(o._lastPointerEvents[j.pointerId]&&(o.onPointerOutObservable.notifyObservers(j.pointerId),delete o._lastPointerEvents[j.pointerId]),o._notifyObservers(s,k,j)):!o._pointerCaptures[j.pointerId]&&(b.distance<k.distance||k.distance===0)?(o._notifyObservers(s,b,j),s.skipOnPointerObservable||(s.skipOnPointerObservable=b.distance>0)):!o._pointerCaptures[j.pointerId]&&b.distance>k.distance&&(o.mainSceneTrackerPredicate&&o.mainSceneTrackerPredicate(k.pickedMesh)?(o._notifyObservers(s,k,j),s.skipOnPointerObservable=!0):(s.type===PointerEventTypes.POINTERMOVE||s.type===PointerEventTypes.POINTERUP)&&(o._lastPointerEvents[j.pointerId]&&(o.onPointerOutObservable.notifyObservers(j.pointerId),delete o._lastPointerEvents[j.pointerId]),o._notifyObservers(s,b,j))),s.type===PointerEventTypes.POINTERUP&&o._pointerCaptures[j.pointerId]&&(o._pointerCaptures[j.pointerId]=!1))}}}),this._originalPointerObserver&&i.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterCameraRenderObservable.add(function(s){o.shouldRender&&s==o.getRenderCamera()&&o.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(function(){o.dispose()}),this._updateCamera()}return a.prototype.getRenderCamera=function(i){if(this._renderCamera)return this._renderCamera;var e=void 0;return this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?e=this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:e=this.originalScene.activeCamera,i&&e&&e.isRigCamera?e.rigParent:e},a.prototype.setRenderCamera=function(i){this._renderCamera=i},a.prototype._getSharedGizmoLight=function(){return this._sharedGizmoLight||(this._sharedGizmoLight=new HemisphericLight("shared gizmo light",new Vector3(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Color3.Gray()),this._sharedGizmoLight},Object.defineProperty(a,"DefaultUtilityLayer",{get:function(){return a._DefaultUtilityLayer==null?a._CreateDefaultUtilityLayerFromScene(EngineStore.LastCreatedScene):a._DefaultUtilityLayer},enumerable:!1,configurable:!0}),a._CreateDefaultUtilityLayerFromScene=function(i){return a._DefaultUtilityLayer=new a(i),a._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){a._DefaultUtilityLayer=null}),a._DefaultUtilityLayer},Object.defineProperty(a,"DefaultKeepDepthUtilityLayer",{get:function(){return a._DefaultKeepDepthUtilityLayer==null&&(a._DefaultKeepDepthUtilityLayer=new a(EngineStore.LastCreatedScene),a._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,a._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){a._DefaultKeepDepthUtilityLayer=null})),a._DefaultKeepDepthUtilityLayer},enumerable:!1,configurable:!0}),a.prototype._notifyObservers=function(i,e,o){i.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(i.type,i.event,e),i.type),this._lastPointerEvents[o.pointerId]=!0)},a.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var i=this.utilityLayerScene.activeCamera.getScene(),e=this.utilityLayerScene.activeCamera;e._scene=this.utilityLayerScene,e.leftCamera&&(e.leftCamera._scene=this.utilityLayerScene),e.rightCamera&&(e.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),e._scene=i,e.leftCamera&&(e.leftCamera._scene=i),e.rightCamera&&(e.rightCamera._scene=i)}},a.prototype.dispose=function(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()},a.prototype._updateCamera=function(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()},a._DefaultUtilityLayer=null,a._DefaultKeepDepthUtilityLayer=null,a}(),BaseSixDofDragBehavior=function(){function a(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new Vector3,this._tmpQuaternion=new Quaternion,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new Observable,this.onDragObservable=new Observable,this.onDragEndObservable=new Observable,this.allowMultiPointer=!0}return Object.defineProperty(a.prototype,"currentDraggingPointerId",{get:function(){return this.currentDraggingPointerIds[0]!==void 0?this.currentDraggingPointerIds[0]:-1},set:function(i){this.currentDraggingPointerIds[0]=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"currentDraggingPointerID",{get:function(){return this.currentDraggingPointerId},set:function(i){this.currentDraggingPointerId=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"name",{get:function(){return"BaseSixDofDrag"},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isMoving",{get:function(){return this._moving},enumerable:!1,configurable:!0}),a.prototype.init=function(){},Object.defineProperty(a.prototype,"_pointerCamera",{get:function(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera},enumerable:!1,configurable:!0}),a.prototype._createVirtualMeshInfo=function(){var i=new AbstractMesh("",a._virtualScene);i.rotationQuaternion=new Quaternion;var e=new AbstractMesh("",a._virtualScene);e.rotationQuaternion=new Quaternion;var o=new AbstractMesh("",a._virtualScene);return o.rotationQuaternion=new Quaternion,{dragging:!1,moving:!1,dragMesh:i,originMesh:e,pivotMesh:o,startingPivotPosition:new Vector3,startingPivotOrientation:new Quaternion,startingPosition:new Vector3,startingOrientation:new Quaternion,lastOriginPosition:new Vector3,lastDragPosition:new Vector3}},a.prototype._resetVirtualMeshesPosition=function(){for(var i=0;i<this.currentDraggingPointerIds.length;i++)this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingPivotPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.position),this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingPivotOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.rotationQuaternion),this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].dragMesh.position),this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].dragMesh.rotationQuaternion)},a.prototype._pointerUpdate2D=function(i,e,o){this._pointerCamera&&this._pointerCamera.cameraRigMode==Camera$1.RIG_MODE_NONE&&!this._pointerCamera._isLeftCamera&&!this._pointerCamera._isRightCamera&&(i.origin.copyFrom(this._pointerCamera.globalPosition),o=0);var s=this._virtualMeshesInfo[e],c=TmpVectors.Vector3[0];i.origin.subtractToRef(s.lastOriginPosition,c),s.lastOriginPosition.copyFrom(i.origin);var d=-Vector3.Dot(c,i.direction);s.originMesh.addChild(s.dragMesh),s.originMesh.addChild(s.pivotMesh),this._applyZOffset(s.dragMesh,d,o),this._applyZOffset(s.pivotMesh,d,o),s.originMesh.position.copyFrom(i.origin);var _=TmpVectors.Vector3[0];i.origin.addToRef(i.direction,_),s.originMesh.lookAt(_),s.originMesh.removeChild(s.dragMesh),s.originMesh.removeChild(s.pivotMesh)},a.prototype._pointerUpdateXR=function(i,e,o,s){var c=this._virtualMeshesInfo[o];c.originMesh.position.copyFrom(i.position),this._dragging===this._dragType.NEAR_DRAG&&e?c.originMesh.rotationQuaternion.copyFrom(e.rotationQuaternion):c.originMesh.rotationQuaternion.copyFrom(i.rotationQuaternion);var d=TmpVectors.Vector3[0],_=TmpVectors.Vector3[1];d.copyFrom(this._pointerCamera.getForwardRay().direction),c.originMesh.position.subtractToRef(c.lastOriginPosition,_),c.lastOriginPosition.copyFrom(c.originMesh.position);var b=_.length();_.normalize(),c.pivotMesh.computeWorldMatrix(!0),c.dragMesh.computeWorldMatrix(!0);var k=TmpVectors.Vector3[2],j=TmpVectors.Vector3[3];c.dragMesh.absolutePosition.subtractToRef(this._pointerCamera.globalPosition,k),c.dragMesh.absolutePosition.subtractToRef(c.originMesh.position,j);var $=j.length();k.normalize(),j.normalize();var _e=Math.abs(Vector3.Dot(_,j))*Vector3.Dot(_,d),et=_e*s*b*$;et+$<.1&&(et=Math.min($,.1)),j.scaleInPlace(et),j.addToRef(c.pivotMesh.absolutePosition,this._tmpVector),c.pivotMesh.setAbsolutePosition(this._tmpVector),j.addToRef(c.dragMesh.absolutePosition,this._tmpVector),c.dragMesh.setAbsolutePosition(this._tmpVector)},a.prototype.attach=function(i){var e=this;this._ownerNode=i,this._scene=this._ownerNode.getScene(),a._virtualScene||(a._virtualScene=new Scene(this._scene.getEngine(),{virtual:!0}),a._virtualScene.detachControl());var o=function(s){return e._ownerNode===s||s.isDescendantOf(e._ownerNode)&&(!e.draggableMeshes||e.draggableMeshes.indexOf(s)!==-1)};this._pointerObserver=this._scene.onPointerObservable.add(function(s,c){var d=s.event.pointerId;e._virtualMeshesInfo[d]||(e._virtualMeshesInfo[d]=e._createVirtualMeshInfo());var _=e._virtualMeshesInfo[d],b=s.event.pointerType==="xr";if(s.type==PointerEventTypes.POINTERDOWN){if(!_.dragging&&s.pickInfo&&s.pickInfo.hit&&s.pickInfo.pickedMesh&&s.pickInfo.pickedPoint&&s.pickInfo.ray&&(!b||s.pickInfo.aimTransform)&&o(s.pickInfo.pickedMesh)){if(!e.allowMultiPointer&&e.currentDraggingPointerIds.length>0)return;e._pointerCamera&&e._pointerCamera.cameraRigMode===Camera$1.RIG_MODE_NONE&&!e._pointerCamera._isLeftCamera&&!e._pointerCamera._isRightCamera&&s.pickInfo.ray.origin.copyFrom(e._pointerCamera.globalPosition),e._ownerNode.computeWorldMatrix(!0);var k=e._virtualMeshesInfo[d];b?(e._dragging=s.pickInfo.originMesh?e._dragType.NEAR_DRAG:e._dragType.DRAG_WITH_CONTROLLER,k.originMesh.position.copyFrom(s.pickInfo.aimTransform.position),e._dragging===e._dragType.NEAR_DRAG&&s.pickInfo.gripTransform?k.originMesh.rotationQuaternion.copyFrom(s.pickInfo.gripTransform.rotationQuaternion):k.originMesh.rotationQuaternion.copyFrom(s.pickInfo.aimTransform.rotationQuaternion)):(e._dragging=e._dragType.DRAG,k.originMesh.position.copyFrom(s.pickInfo.ray.origin)),k.lastOriginPosition.copyFrom(k.originMesh.position),k.dragMesh.position.copyFrom(s.pickInfo.pickedPoint),k.lastDragPosition.copyFrom(s.pickInfo.pickedPoint),k.pivotMesh.position.copyFrom(e._ownerNode.getAbsolutePivotPoint()),k.pivotMesh.rotationQuaternion.copyFrom(e._ownerNode.absoluteRotationQuaternion),k.startingPosition.copyFrom(k.dragMesh.position),k.startingPivotPosition.copyFrom(k.pivotMesh.position),k.startingOrientation.copyFrom(k.dragMesh.rotationQuaternion),k.startingPivotOrientation.copyFrom(k.pivotMesh.rotationQuaternion),b?(k.originMesh.addChild(k.dragMesh),k.originMesh.addChild(k.pivotMesh)):k.originMesh.lookAt(k.dragMesh.position),k.dragging=!0,e.currentDraggingPointerIds.indexOf(d)===-1&&e.currentDraggingPointerIds.push(d),e.detachCameraControls&&e._pointerCamera&&!e._pointerCamera.leftCamera&&(e._pointerCamera.inputs&&e._pointerCamera.inputs.attachedToElement?(e._pointerCamera.detachControl(),e._attachedToElement=!0):e._attachedToElement=!1),e._targetDragStart(k.pivotMesh.position,k.pivotMesh.rotationQuaternion,d),e.onDragStartObservable.notifyObservers({position:k.pivotMesh.position})}}else if(s.type==PointerEventTypes.POINTERUP||s.type==PointerEventTypes.POINTERDOUBLETAP){var j=e.currentDraggingPointerIds.indexOf(d);_.dragging=!1,j!==-1&&(e.currentDraggingPointerIds.splice(j,1),e.currentDraggingPointerIds.length===0&&(e._moving=!1,e._dragging=e._dragType.NONE,e.detachCameraControls&&e._attachedToElement&&e._pointerCamera&&!e._pointerCamera.leftCamera&&(e._pointerCamera.attachControl(!0),e._attachedToElement=!1)),_.originMesh.removeChild(_.dragMesh),_.originMesh.removeChild(_.pivotMesh),e._targetDragEnd(d),e.onDragEndObservable.notifyObservers({}))}else if(s.type==PointerEventTypes.POINTERMOVE){var j=e.currentDraggingPointerIds.indexOf(d);if(j!==-1&&_.dragging&&s.pickInfo&&(s.pickInfo.ray||s.pickInfo.aimTransform)){var $=e.zDragFactor;(e.currentDraggingPointerIds.length>1||s.pickInfo.originMesh)&&($=0),e._ownerNode.computeWorldMatrix(!0),b?e._pointerUpdateXR(s.pickInfo.aimTransform,s.pickInfo.gripTransform,d,$):e._pointerUpdate2D(s.pickInfo.ray,d,$),e._tmpQuaternion.copyFrom(_.startingPivotOrientation),e._tmpQuaternion.x=-e._tmpQuaternion.x,e._tmpQuaternion.y=-e._tmpQuaternion.y,e._tmpQuaternion.z=-e._tmpQuaternion.z,_.pivotMesh.absoluteRotationQuaternion.multiplyToRef(e._tmpQuaternion,e._tmpQuaternion),_.pivotMesh.absolutePosition.subtractToRef(_.startingPivotPosition,e._tmpVector),e.onDragObservable.notifyObservers({delta:e._tmpVector,position:_.pivotMesh.position,pickInfo:s.pickInfo}),e._targetDrag(e._tmpVector,e._tmpQuaternion,d),_.lastDragPosition.copyFrom(_.dragMesh.absolutePosition),e._moving=!0}}})},a.prototype._applyZOffset=function(i,e,o){i.position.z-=i.position.z<1?e*o:e*o*i.position.z,i.position.z<0&&(i.position.z=0)},a.prototype._targetDragStart=function(i,e,o){},a.prototype._targetDrag=function(i,e,o){},a.prototype._targetDragEnd=function(i){},a.prototype.detach=function(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.attachControl(!0),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(var i in this._virtualMeshesInfo)this._virtualMeshesInfo[i].originMesh.dispose(),this._virtualMeshesInfo[i].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()},a}(),SixDofDragBehavior=function(a){__extends(i,a);function i(){var e=a!==null&&a.apply(this,arguments)||this;return e._sceneRenderObserver=null,e._targetPosition=new Vector3(0,0,0),e._targetOrientation=new Quaternion,e._targetScaling=new Vector3(1,1,1),e._startingPosition=new Vector3(0,0,0),e._startingOrientation=new Quaternion,e._startingScaling=new Vector3(1,1,1),e.onPositionChangedObservable=new Observable,e.dragDeltaRatio=.2,e.rotateDraggedObject=!0,e.rotateAroundYOnly=!1,e.rotateWithMotionController=!0,e.disableMovement=!1,e.faceCameraOnDragStart=!1,e}return Object.defineProperty(i.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!1,configurable:!0}),i.prototype.attach=function(e){var o=this;a.prototype.attach.call(this,e),e.isNearGrabbable=!0,this._virtualTransformNode=new TransformNode("virtual_sixDof",BaseSixDofDragBehavior._virtualScene),this._virtualTransformNode.rotationQuaternion=Quaternion.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(function(){if(o.currentDraggingPointerIds.length===1&&o._moving&&!o.disableMovement){var s=e.parent;e.setParent(null),e.position.addInPlace(o._targetPosition.subtract(e.position).scale(o.dragDeltaRatio)),o.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),(!s||s.scaling&&!s.scaling.isNonUniformWithinEpsilon(.001))&&Quaternion.SlerpToRef(e.rotationQuaternion,o._targetOrientation,o.dragDeltaRatio,e.rotationQuaternion),e.setParent(s)}})},i.prototype._getPositionOffsetAround=function(e,o,s){var c=TmpVectors.Matrix[0],d=TmpVectors.Matrix[1],_=TmpVectors.Matrix[2],b=TmpVectors.Matrix[3],k=TmpVectors.Matrix[4];return Matrix.TranslationToRef(e.x,e.y,e.z,c),Matrix.TranslationToRef(-e.x,-e.y,-e.z,d),Matrix.FromQuaternionToRef(s,_),Matrix.ScalingToRef(o,o,o,b),d.multiplyToRef(_,k),k.multiplyToRef(b,k),k.multiplyToRef(c,k),k.getTranslation()},i.prototype._onePointerPositionUpdated=function(e,o){var s=TmpVectors.Vector3[0];s.setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?Quaternion.RotationYawPitchRollToRef(o.toEulerAngles().y,0,0,TmpVectors.Quaternion[0]):TmpVectors.Quaternion[0].copyFrom(o),TmpVectors.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&o.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)},i.prototype._twoPointersPositionUpdated=function(){var e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,o=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,s=TmpVectors.Vector3[0];e.addToRef(o,s),s.scaleInPlace(.5);var c=TmpVectors.Vector3[1];o.subtractToRef(e,c);var d=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,_=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,b=TmpVectors.Vector3[2];d.addToRef(_,b),b.scaleInPlace(.5);var k=TmpVectors.Vector3[3];_.subtractToRef(d,k);var j=k.length()/c.length(),$=b.subtract(s),_e=Quaternion.FromEulerAngles(0,Vector3.GetAngleBetweenVectorsOnPlane(c.normalize(),k.normalize(),Vector3.UpReadOnly),0),et=this._ownerNode.parent;this._ownerNode.setParent(null);var tt=this._getPositionOffsetAround(s.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),j,_e);this._virtualTransformNode.rotationQuaternion.multiplyToRef(_e,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(j,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef($.addInPlace(tt),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(et)},i.prototype._targetDragStart=function(){var e=this.currentDraggingPointerIds.length,o=this._ownerNode.parent;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=Quaternion.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));var s=this._ownerNode.getAbsolutePivotPoint();if(this._ownerNode.setParent(null),e===1){if(this._targetPosition.copyFrom(this._ownerNode.position),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.scaling),this.faceCameraOnDragStart&&this._scene.activeCamera){var c=TmpVectors.Vector3[0];this._scene.activeCamera.position.subtractToRef(s,c),c.normalize();var d=TmpVectors.Quaternion[0];this._scene.useRightHandedSystem?Quaternion.FromLookDirectionRHToRef(c,new Vector3(0,1,0),d):Quaternion.FromLookDirectionLHToRef(c,new Vector3(0,1,0),d),d.normalize(),Quaternion.RotationYawPitchRollToRef(d.toEulerAngles().y,0,0,TmpVectors.Quaternion[0]),this._targetOrientation.copyFrom(TmpVectors.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else e===2&&(this._virtualTransformNode.setPivotPoint(new Vector3(0,0,0),Space.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.position),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.scaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),this._virtualTransformNode.setPivotPoint(s,Space.WORLD),this._resetVirtualMeshesPosition());this._ownerNode.setParent(o)},i.prototype._targetDrag=function(e,o,s){this.currentDraggingPointerIds.length===1?this._onePointerPositionUpdated(e,o):this.currentDraggingPointerIds.length===2&&this._twoPointersPositionUpdated()},i.prototype._targetDragEnd=function(){if(this.currentDraggingPointerIds.length===1){this._resetVirtualMeshesPosition();var e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}},i.prototype.detach=function(){a.prototype.detach.call(this),this._ownerNode&&(this._ownerNode.isNearGrabbable=!1,this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver)),this._virtualTransformNode&&this._virtualTransformNode.dispose()},i}(BaseSixDofDragBehavior),Gizmo=function(){function a(i){var e=this;i===void 0&&(i=UtilityLayerRenderer.DefaultUtilityLayer),this.gizmoLayer=i,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this.updateGizmoPositionToMatchAttachedMesh=!0,this.updateScale=!0,this._interactionsEnabled=!0,this._tempQuaternion=new Quaternion(0,0,0,1),this._tempVector=new Vector3,this._tempVector2=new Vector3,this._tempMatrix1=new Matrix,this._tempMatrix2=new Matrix,this._rightHandtoLeftHandMatrix=Matrix.RotationY(Math.PI),this._rootMesh=new Mesh("gizmoRootNode",i.utilityLayerScene),this._rootMesh.rotationQuaternion=Quaternion.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function(){e._update()})}return Object.defineProperty(a.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(i){this._scaleRatio=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isHovered",{get:function(){return this._isHovered},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"attachedMesh",{get:function(){return this._attachedMesh},set:function(i){this._attachedMesh=i,i&&(this._attachedNode=i),this._rootMesh.setEnabled(!!i),this._attachedNodeChanged(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"attachedNode",{get:function(){return this._attachedNode},set:function(i){this._attachedNode=i,this._attachedMesh=null,this._rootMesh.setEnabled(!!i),this._attachedNodeChanged(i)},enumerable:!1,configurable:!0}),a.prototype.setCustomMesh=function(i){if(i.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(function(e){e.dispose()}),i.parent=this._rootMesh,this._customMeshSet=!0},Object.defineProperty(a.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(i){this._updateGizmoRotationToMatchAttachedMesh=i},enumerable:!1,configurable:!0}),a.prototype._attachedNodeChanged=function(i){},Object.defineProperty(a.prototype,"customRotationQuaternion",{get:function(){return this._customRotationQuaternion},set:function(i){this._customRotationQuaternion=i},enumerable:!1,configurable:!0}),a.prototype._update=function(){if(this.attachedNode){var i=this.attachedNode;if(this.attachedMesh&&(i=this.attachedMesh._effectiveMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh){var e=i.getWorldMatrix().getRow(3),o=e?e.toVector3():new Vector3(0,0,0);this._rootMesh.position.copyFrom(o)}if(this.updateGizmoRotationToMatchAttachedMesh?i.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion):this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1),this.updateScale){var s=this.gizmoLayer.utilityLayerScene.activeCamera,c=s.globalPosition;s.devicePosition&&(c=s.devicePosition),this._rootMesh.position.subtractToRef(c,this._tempVector);var d=this._tempVector.length()*this.scaleRatio;this._rootMesh.scaling.set(d,d,d),i._getWorldMatrixDeterminant()<0&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}},a.prototype._handlePivot=function(){var i=this._attachedNode;i.isUsingPivotMatrix&&i.isUsingPivotMatrix()&&i.position&&i.getWorldMatrix().setTranslation(i.position)},a.prototype._matrixChanged=function(){if(!!this._attachedNode)if(this._attachedNode._isCamera){var i=this._attachedNode,e,o;if(i.parent){var s=this._tempMatrix2;i.parent._worldMatrix.invertToRef(s),this._attachedNode._worldMatrix.multiplyToRef(s,this._tempMatrix1),e=this._tempMatrix1}else e=this._attachedNode._worldMatrix;i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,this._tempMatrix2),o=this._tempMatrix2):o=e,o.decompose(this._tempVector2,this._tempQuaternion,this._tempVector);var c=this._attachedNode.getClassName()==="FreeCamera"||this._attachedNode.getClassName()==="FlyCamera"||this._attachedNode.getClassName()==="ArcFollowCamera"||this._attachedNode.getClassName()==="TargetCamera"||this._attachedNode.getClassName()==="TouchCamera"||this._attachedNode.getClassName()==="UniversalCamera";if(c){var d=this._attachedNode;d.rotation=this._tempQuaternion.toEulerAngles(),d.rotationQuaternion&&(d.rotationQuaternion.copyFrom(this._tempQuaternion),d.rotationQuaternion.normalize())}i.position.copyFrom(this._tempVector)}else if(this._attachedNode._isMesh||this._attachedNode.getClassName()==="AbstractMesh"||this._attachedNode.getClassName()==="TransformNode"||this._attachedNode.getClassName()==="InstancedMesh"){var _=this._attachedNode;if(_.parent){var s=this._tempMatrix1,b=this._tempMatrix2;_.parent.getWorldMatrix().invertToRef(s),this._attachedNode.getWorldMatrix().multiplyToRef(s,b),b.decompose(_.scaling,this._tempQuaternion,_.position)}else this._attachedNode._worldMatrix.decompose(_.scaling,this._tempQuaternion,_.position);_.billboardMode||(_.rotationQuaternion?(_.rotationQuaternion.copyFrom(this._tempQuaternion),_.rotationQuaternion.normalize()):_.rotation=this._tempQuaternion.toEulerAngles())}else if(this._attachedNode.getClassName()==="Bone"){var k=this._attachedNode,j=k.getParent();if(j){var $=this._tempMatrix1,_e=this._tempMatrix2;j.getWorldMatrix().invertToRef($),k.getWorldMatrix().multiplyToRef($,_e);var et=k.getLocalMatrix();et.copyFrom(_e)}else{var et=k.getLocalMatrix();et.copyFrom(k.getWorldMatrix())}k.markAsDirty()}else{var tt=this._attachedNode;if(tt.getTypeID){var rt=tt.getTypeID();if(rt===Light.LIGHTTYPEID_DIRECTIONALLIGHT||rt===Light.LIGHTTYPEID_SPOTLIGHT||rt===Light.LIGHTTYPEID_POINTLIGHT){var it=tt.parent;if(it){var $=this._tempMatrix1,nt=this._tempMatrix2;it.getWorldMatrix().invertToRef($),tt.getWorldMatrix().multiplyToRef($,nt),nt.decompose(void 0,this._tempQuaternion,this._tempVector)}else this._attachedNode._worldMatrix.decompose(void 0,this._tempQuaternion,this._tempVector);tt.position=new Vector3(this._tempVector.x,this._tempVector.y,this._tempVector.z),Vector3.Backward(!1).rotateByQuaternionToRef(this._tempQuaternion,this._tempVector),tt.direction=new Vector3(this._tempVector.x,this._tempVector.y,this._tempVector.z)}}}},a.prototype._setGizmoMeshMaterial=function(i,e){i&&i.forEach(function(o){o.material=e,o.color&&(o.color=e.diffuseColor)})},a.GizmoAxisPointerObserver=function(i,e){var o=!1,s=i.utilityLayerScene.onPointerObservable.add(function(c){var d,_;if(c.pickInfo){if(c.type===PointerEventTypes.POINTERMOVE){if(o)return;e.forEach(function(k){var j,$;if(k.colliderMeshes&&k.gizmoMeshes){var _e=((j=k.colliderMeshes)===null||j===void 0?void 0:j.indexOf(($=c==null?void 0:c.pickInfo)===null||$===void 0?void 0:$.pickedMesh))!=-1,et=k.dragBehavior.enabled?_e||k.active?k.hoverMaterial:k.material:k.disableMaterial;k.gizmoMeshes.forEach(function(tt){tt.material=et,tt.color&&(tt.color=et.diffuseColor)})}})}if(c.type===PointerEventTypes.POINTERDOWN&&e.has((d=c.pickInfo.pickedMesh)===null||d===void 0?void 0:d.parent)){o=!0;var b=e.get((_=c.pickInfo.pickedMesh)===null||_===void 0?void 0:_.parent);b.active=!0,e.forEach(function(k){var j,$,_e=((j=k.colliderMeshes)===null||j===void 0?void 0:j.indexOf(($=c==null?void 0:c.pickInfo)===null||$===void 0?void 0:$.pickedMesh))!=-1,et=(_e||k.active)&&k.dragBehavior.enabled?k.hoverMaterial:k.disableMaterial;k.gizmoMeshes.forEach(function(tt){tt.material=et,tt.color&&(tt.color=et.diffuseColor)})})}c.type===PointerEventTypes.POINTERUP&&e.forEach(function(k){k.active=!1,o=!1,k.gizmoMeshes.forEach(function(j){j.material=k.dragBehavior.enabled?k.material:k.disableMaterial,j.color&&(j.color=k.material.diffuseColor)})})}});return s},a.prototype.dispose=function(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)},a}(),PivotTools=function(){function a(){}return a._RemoveAndStorePivotPoint=function(i){i&&a._PivotCached===0&&(i.getPivotPointToRef(a._OldPivotPoint),a._PivotPostMultiplyPivotMatrix=i._postMultiplyPivotMatrix,a._OldPivotPoint.equalsToFloats(0,0,0)||(i.setPivotMatrix(Matrix.IdentityReadOnly),a._OldPivotPoint.subtractToRef(i.getPivotPoint(),a._PivotTranslation),a._PivotTmpVector.copyFromFloats(1,1,1),a._PivotTmpVector.subtractInPlace(i.scaling),a._PivotTmpVector.multiplyInPlace(a._PivotTranslation),i.position.addInPlace(a._PivotTmpVector))),a._PivotCached++},a._RestorePivotPoint=function(i){i&&!a._OldPivotPoint.equalsToFloats(0,0,0)&&a._PivotCached===1&&(i.setPivotPoint(a._OldPivotPoint),i._postMultiplyPivotMatrix=a._PivotPostMultiplyPivotMatrix,a._PivotTmpVector.copyFromFloats(1,1,1),a._PivotTmpVector.subtractInPlace(i.scaling),a._PivotTmpVector.multiplyInPlace(a._PivotTranslation),i.position.subtractInPlace(a._PivotTmpVector)),this._PivotCached--},a._PivotCached=0,a._OldPivotPoint=new Vector3,a._PivotTranslation=new Vector3,a._PivotTmpVector=new Vector3,a._PivotPostMultiplyPivotMatrix=!1,a}(),PointerDragBehavior=function(){function a(i){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new Observable,this.onDragStartObservable=new Observable,this.onDragEndObservable=new Observable,this.onEnabledObservable=new Observable,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=function(o){return!0},this._tmpVector=new Vector3(0,0,0),this._alternatePickedPoint=new Vector3(0,0,0),this._worldDragAxis=new Vector3(0,0,0),this._targetPosition=new Vector3(0,0,0),this._attachedToElement=!1,this._startDragRay=new Ray(new Vector3,new Vector3),this._lastPointerRay={},this._dragDelta=new Vector3,this._pointA=new Vector3(0,0,0),this._pointC=new Vector3(0,0,0),this._localAxis=new Vector3(0,0,0),this._lookAt=new Vector3(0,0,0),this._options=i||{};var e=0;if(this._options.dragAxis&&e++,this._options.dragPlaneNormal&&e++,e>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(a.prototype,"currentDraggingPointerID",{get:function(){return this.currentDraggingPointerId},set:function(i){this.currentDraggingPointerId=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"enabled",{get:function(){return this._enabled},set:function(i){i!=this._enabled&&this.onEnabledObservable.notifyObservers(i),this._enabled=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"options",{get:function(){return this._options},set:function(i){this._options=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!1,configurable:!0}),a.prototype.init=function(){},a.prototype.attach=function(i,e){var o=this;this._scene=i.getScene(),i.isNearGrabbable=!0,this.attachedNode=i,a._planeScene||(this._debugMode?a._planeScene=this._scene:(a._planeScene=new Scene(this._scene.getEngine(),{virtual:!0}),a._planeScene.detachControl(),this._scene.onDisposeObservable.addOnce(function(){a._planeScene.dispose(),a._planeScene=null}))),this._dragPlane=CreatePlane("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Mesh.DOUBLESIDE},a._planeScene),this.lastDragPosition=new Vector3(0,0,0);var s=e||function(c){return o.attachedNode==c||c.isDescendantOf(o.attachedNode)};this._pointerObserver=this._scene.onPointerObservable.add(function(c,d){if(!o.enabled){o._attachedToElement&&o.releaseDrag();return}if(c.type==PointerEventTypes.POINTERDOWN)o.startAndReleaseDragOnPointerEvents&&!o.dragging&&c.pickInfo&&c.pickInfo.hit&&c.pickInfo.pickedMesh&&c.pickInfo.pickedPoint&&c.pickInfo.ray&&s(c.pickInfo.pickedMesh)&&o._startDrag(c.event.pointerId,c.pickInfo.ray,c.pickInfo.pickedPoint);else if(c.type==PointerEventTypes.POINTERUP)o.startAndReleaseDragOnPointerEvents&&o.currentDraggingPointerId==c.event.pointerId&&o.releaseDrag();else if(c.type==PointerEventTypes.POINTERMOVE){var _=c.event.pointerId;if(o.currentDraggingPointerId===a._AnyMouseId&&_!==a._AnyMouseId){var b=c.event,k=b.pointerType==="mouse"||!o._scene.getEngine().hostInformation.isMobile&&b instanceof MouseEvent;k&&(o._lastPointerRay[o.currentDraggingPointerId]&&(o._lastPointerRay[_]=o._lastPointerRay[o.currentDraggingPointerId],delete o._lastPointerRay[o.currentDraggingPointerId]),o.currentDraggingPointerId=_)}o._lastPointerRay[_]||(o._lastPointerRay[_]=new Ray(new Vector3,new Vector3)),c.pickInfo&&c.pickInfo.ray&&(o._lastPointerRay[_].origin.copyFrom(c.pickInfo.ray.origin),o._lastPointerRay[_].direction.copyFrom(c.pickInfo.ray.direction),o.currentDraggingPointerId==_&&o.dragging&&o._moveDrag(c.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(function(){o._moving&&o.moveAttached&&(PivotTools._RemoveAndStorePivotPoint(o.attachedNode),o._targetPosition.subtractToRef(o.attachedNode.absolutePosition,o._tmpVector),o._tmpVector.scaleInPlace(o.dragDeltaRatio),o.attachedNode.getAbsolutePosition().addToRef(o._tmpVector,o._tmpVector),o.validateDrag(o._tmpVector)&&o.attachedNode.setAbsolutePosition(o._tmpVector),PivotTools._RestorePivotPoint(o.attachedNode))})},a.prototype.releaseDrag=function(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId})),this.currentDraggingPointerId=-1,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if(this._scene.activeCamera.getClassName()==="ArcRotateCamera"){var i=this._scene.activeCamera;i.attachControl(i.inputs?i.inputs.noPreventDefault:!0,i._useCtrlForPanning,i._panningMouseButton)}else this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs?this._scene.activeCamera.inputs.noPreventDefault:!0);this._attachedToElement=!1}},a.prototype.startDrag=function(i,e,o){i===void 0&&(i=a._AnyMouseId),this._startDrag(i,e,o);var s=this._lastPointerRay[i];i===a._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)},a.prototype._startDrag=function(i,e,o){if(!(!this._scene.activeCamera||this.dragging||!this.attachedNode)){PivotTools._RemoveAndStorePivotPoint(this.attachedNode),e?(this._startDragRay.direction.copyFrom(e.direction),this._startDragRay.origin.copyFrom(e.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,o||this._tmpVector);var s=this._pickWithRayOnDragPlane(this._startDragRay);s&&(this.dragging=!0,this.currentDraggingPointerId=i,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,pointerId:this.currentDraggingPointerId}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)),PivotTools._RestorePivotPoint(this.attachedNode)}},a.prototype._moveDrag=function(i){this._moving=!0;var e=this._pickWithRayOnDragPlane(i);if(e){this.updateDragPlane&&this._updateDragPlanePosition(i,e);var o=0;this._options.dragAxis?(this.useObjectOrientationForDragging?Vector3.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),e.subtractToRef(this.lastDragPosition,this._tmpVector),o=Vector3.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(o,this._dragDelta)):(o=this._dragDelta.length(),e.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:o,delta:this._dragDelta,dragPlanePoint:e,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId}),this.lastDragPosition.copyFrom(e)}},a.prototype._pickWithRayOnDragPlane=function(i){var e=this;if(!i)return null;var o=Math.acos(Vector3.Dot(this._dragPlane.forward,i.direction));if(o>Math.PI/2&&(o=Math.PI-o),this.maxDragAngle>0&&o>this.maxDragAngle)if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(i.direction),this.attachedNode.absolutePosition.subtractToRef(i.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*Vector3.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var s=Vector3.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-s,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}else return null;var c=a._planeScene.pickWithRay(i,function(d){return d==e._dragPlane});return c&&c.hit&&c.pickedMesh&&c.pickedPoint?c.pickedPoint:null},a.prototype._updateDragPlanePosition=function(i,e){this._pointA.copyFrom(e),this._options.dragAxis?(this.useObjectOrientationForDragging?Vector3.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),i.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(Vector3.Dot(this._localAxis,this._pointC))>.999?Math.abs(Vector3.Dot(Vector3.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(Vector3.Right()):this._lookAt.copyFrom(Vector3.UpReadOnly):(Vector3.CrossToRef(this._localAxis,this._pointC,this._lookAt),Vector3.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(i.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)},a.prototype.detach=function(){this.attachedNode.isNearGrabbable=!1,this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane.dispose(),this.releaseDrag()},a._AnyMouseId=-2,a}(),PlaneRotationGizmo=function(a){__extends(i,a);function i(e,o,s,c,d,_,b){o===void 0&&(o=Color3.Gray()),s===void 0&&(s=UtilityLayerRenderer.DefaultUtilityLayer),c===void 0&&(c=32),d===void 0&&(d=null),b===void 0&&(b=1);var k,j=a.call(this,s)||this;j._pointerObserver=null,j.snapDistance=0,j.onSnapObservable=new Observable,j.angle=0,j._isEnabled=!0,j._parent=null,j._dragging=!1,j._angles=new Vector3,j._parent=d,j._coloredMaterial=new StandardMaterial("",s.utilityLayerScene),j._coloredMaterial.diffuseColor=o,j._coloredMaterial.specularColor=o.subtract(new Color3(.1,.1,.1)),j._hoverMaterial=new StandardMaterial("",s.utilityLayerScene),j._hoverMaterial.diffuseColor=Color3.Yellow(),j._disableMaterial=new StandardMaterial("",s.utilityLayerScene),j._disableMaterial.diffuseColor=Color3.Gray(),j._disableMaterial.alpha=.4,j._gizmoMesh=new Mesh("",s.utilityLayerScene);var $=j._createGizmoMesh(j._gizmoMesh,b,c),_e=$.rotationMesh,et=$.collider;j._rotationDisplayPlane=CreatePlane("rotationDisplay",{size:.6,updatable:!1},j.gizmoLayer.utilityLayerScene),j._rotationDisplayPlane.rotation.z=Math.PI*.5,j._rotationDisplayPlane.parent=j._gizmoMesh,j._rotationDisplayPlane.setEnabled(!1),Effect$1.ShadersStore.rotationGizmoVertexShader=i._rotationGizmoVertexShader,Effect$1.ShadersStore.rotationGizmoFragmentShader=i._rotationGizmoFragmentShader,j._rotationShaderMaterial=new ShaderMaterial("shader",j.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles"]}),j._rotationShaderMaterial.backFaceCulling=!1,j._rotationDisplayPlane.material=j._rotationShaderMaterial,j._rotationDisplayPlane.visibility=.999,j._gizmoMesh.lookAt(j._rootMesh.position.add(e)),j._rootMesh.addChild(j._gizmoMesh),j._gizmoMesh.scaling.scaleInPlace(1/3),j.dragBehavior=new PointerDragBehavior({dragPlaneNormal:e}),j.dragBehavior.moveAttached=!1,j.dragBehavior.maxDragAngle=i.MaxDragAngle,j.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,j._rootMesh.addBehavior(j.dragBehavior);var tt=new Vector3,rt=new Matrix,it=new Vector3,nt=new Vector3;j.dragBehavior.onDragStartObservable.add(function(ht){j.attachedNode&&(tt.copyFrom(ht.dragPlanePoint),j._rotationDisplayPlane.setEnabled(!0),j._rotationDisplayPlane.getWorldMatrix().invertToRef(rt),Vector3.TransformCoordinatesToRef(ht.dragPlanePoint,rt,tt),j._angles.x=Math.atan2(tt.y,tt.x)+Math.PI,j._angles.y=0,j._angles.z=j.updateGizmoRotationToMatchAttachedMesh?1:0,j._dragging=!0,tt.copyFrom(ht.dragPlanePoint),j._rotationShaderMaterial.setVector3("angles",j._angles),j.angle=0)}),j.dragBehavior.onDragEndObservable.add(function(){j._dragging=!1,j._rotationDisplayPlane.setEnabled(!1)});var ot={snapDistance:0},at=0,st=new Matrix,ut=new Quaternion;j.dragBehavior.onDragObservable.add(function(ht){if(j.attachedNode){var pt=new Vector3(1,1,1),mt=new Quaternion(0,0,0,1),dt=new Vector3(0,0,0);j._handlePivot(),j.attachedNode.getWorldMatrix().decompose(pt,mt,dt);var gt=ht.dragPlanePoint.subtract(dt).normalize(),_t=tt.subtract(dt).normalize(),yt=Vector3.Cross(gt,_t),Tt=Vector3.Dot(gt,_t),St=Math.atan2(yt.length(),Tt);it.copyFrom(e),nt.copyFrom(e),j.updateGizmoRotationToMatchAttachedMesh&&(mt.toRotationMatrix(rt),nt=Vector3.TransformCoordinates(it,rt));var At=!1;if(s.utilityLayerScene.activeCamera){var vt=s.utilityLayerScene.activeCamera.position.subtract(dt).normalize();Vector3.Dot(vt,nt)>0&&(it.scaleInPlace(-1),nt.scaleInPlace(-1),At=!0)}var Et=Vector3.Dot(nt,yt)>0;Et&&(St=-St);var xt=!1;if(j.snapDistance!=0)if(at+=St,Math.abs(at)>j.snapDistance){var bt=Math.floor(Math.abs(at)/j.snapDistance);at<0&&(bt*=-1),at=at%j.snapDistance,St=j.snapDistance*bt,xt=!0}else St=0;var Mt=Math.sin(St/2);if(ut.set(it.x*Mt,it.y*Mt,it.z*Mt,Math.cos(St/2)),st.determinant()>0){var Rt=new Vector3;ut.toEulerAnglesToRef(Rt),Quaternion.RotationYawPitchRollToRef(Rt.y,-Rt.x,-Rt.z,ut)}j.updateGizmoRotationToMatchAttachedMesh?mt.multiplyToRef(ut,mt):ut.multiplyToRef(mt,mt),j.attachedNode.getWorldMatrix().copyFrom(Matrix.Compose(pt,mt,dt)),tt.copyFrom(ht.dragPlanePoint),xt&&(ot.snapDistance=St,j.onSnapObservable.notifyObservers(ot)),j._angles.y+=St,j.angle+=At?-St:St,j._rotationShaderMaterial.setVector3("angles",j._angles),j._matrixChanged()}});var ft=s._getSharedGizmoLight();ft.includedOnlyMeshes=ft.includedOnlyMeshes.concat(j._rootMesh.getChildMeshes(!1));var lt={colliderMeshes:[et],gizmoMeshes:[_e],material:j._coloredMaterial,hoverMaterial:j._hoverMaterial,disableMaterial:j._disableMaterial,active:!1,dragBehavior:j.dragBehavior};return(k=j._parent)===null||k===void 0||k.addToAxisCache(j._gizmoMesh,lt),j._pointerObserver=s.utilityLayerScene.onPointerObservable.add(function(ht){var pt;if(!j._customMeshSet&&(j.dragBehavior.maxDragAngle=i.MaxDragAngle,j._isHovered=lt.colliderMeshes.indexOf((pt=ht==null?void 0:ht.pickInfo)===null||pt===void 0?void 0:pt.pickedMesh)!=-1,!j._parent)){var mt=lt.dragBehavior.enabled?j._isHovered||j._dragging?j._hoverMaterial:j._coloredMaterial:j._disableMaterial;j._setGizmoMeshMaterial(lt.gizmoMeshes,mt)}}),j.dragBehavior.onEnabledObservable.add(function(ht){j._setGizmoMeshMaterial(lt.gizmoMeshes,ht?j._coloredMaterial:j._disableMaterial)}),j}return i.prototype._createGizmoMesh=function(e,o,s){var c=CreateTorus("ignore",{diameter:.6,thickness:.03*o,tessellation:s},this.gizmoLayer.utilityLayerScene);c.visibility=0;var d=CreateTorus("",{diameter:.6,thickness:.005*o,tessellation:s},this.gizmoLayer.utilityLayerScene);return d.material=this._coloredMaterial,d.rotation.x=Math.PI/2,c.rotation.x=Math.PI/2,e.addChild(d),e.addChild(c),{rotationMesh:d,collider:c}},i.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(i.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null},enumerable:!1,configurable:!0}),i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(e){e&&e.dispose()}),a.prototype.dispose.call(this)},i.MaxDragAngle=Math.PI*9/20,i._rotationGizmoVertexShader=`
  10168. precision highp float;
  10169. attribute vec3 position;
  10170. attribute vec2 uv;
  10171. uniform mat4 worldViewProjection;
  10172. varying vec3 vPosition;
  10173. varying vec2 vUV;
  10174. void main(void) {
  10175. gl_Position = worldViewProjection * vec4(position, 1.0);
  10176. vUV = uv;
  10177. }`,i._rotationGizmoFragmentShader=`
  10178. precision highp float;
  10179. varying vec2 vUV;
  10180. varying vec3 vPosition;
  10181. uniform vec3 angles;
  10182. #define twopi 6.283185307
  10183. void main(void) {
  10184. vec2 uv = vUV - vec2(0.5);
  10185. float angle = atan(uv.y, uv.x) + 3.141592;
  10186. float delta = gl_FrontFacing ? angles.y : -angles.y;
  10187. float begin = angles.x - delta * angles.z;
  10188. float start = (begin < (begin + delta)) ? begin : (begin + delta);
  10189. float end = (begin > (begin + delta)) ? begin : (begin + delta);
  10190. float len = sqrt(dot(uv,uv));
  10191. float opacity = 1. - step(0.5, len);
  10192. float base = abs(floor(start / twopi)) * twopi;
  10193. start += base;
  10194. end += base;
  10195. float intensity = 0.;
  10196. for (int i = 0; i < 5; i++)
  10197. {
  10198. intensity += max(step(start, angle) - step(end, angle), 0.);
  10199. angle += twopi;
  10200. }
  10201. gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity;
  10202. }`,i}(Gizmo),RotationGizmo=function(a){__extends(i,a);function i(e,o,s,c,d,_){e===void 0&&(e=UtilityLayerRenderer.DefaultUtilityLayer),o===void 0&&(o=32),s===void 0&&(s=!1),c===void 0&&(c=1);var b=a.call(this,e)||this;b.onDragStartObservable=new Observable,b.onDragEndObservable=new Observable,b._observables=[],b._gizmoAxisCache=new Map;var k=_&&_.xOptions&&_.xOptions.color?_.xOptions.color:Color3.Red().scale(.5),j=_&&_.yOptions&&_.yOptions.color?_.yOptions.color:Color3.Green().scale(.5),$=_&&_.zOptions&&_.zOptions.color?_.zOptions.color:Color3.Blue().scale(.5);return b.xGizmo=new PlaneRotationGizmo(new Vector3(1,0,0),k,e,o,b,s,c),b.yGizmo=new PlaneRotationGizmo(new Vector3(0,1,0),j,e,o,b,s,c),b.zGizmo=new PlaneRotationGizmo(new Vector3(0,0,1),$,e,o,b,s,c),[b.xGizmo,b.yGizmo,b.zGizmo].forEach(function(_e){_&&_.updateScale!=null&&(_e.updateScale=_.updateScale),_e.dragBehavior.onDragStartObservable.add(function(){b.onDragStartObservable.notifyObservers({})}),_e.dragBehavior.onDragEndObservable.add(function(){b.onDragEndObservable.notifyObservers({})})}),b.attachedMesh=null,b.attachedNode=null,d?d.addToAxisCache(b._gizmoAxisCache):Gizmo.GizmoAxisPointerObserver(e,b._gizmoAxisCache),b}return Object.defineProperty(i.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(o){o.isEnabled?o.attachedMesh=e:o.attachedMesh=null})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(o){o.isEnabled?o.attachedNode=e:o.attachedNode=null})},enumerable:!1,configurable:!0}),i.prototype._checkBillboardTransform=function(){this._nodeAttached&&this._nodeAttached.billboardMode&&console.log("Rotation Gizmo will not work with transforms in billboard mode.")},Object.defineProperty(i.prototype,"isHovered",{get:function(){var e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(o){e=e||o.isHovered}),e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"snapDistance",{get:function(){return this.xGizmo.snapDistance},set:function(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"scaleRatio",{get:function(){return this.xGizmo.scaleRatio},set:function(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)},enumerable:!1,configurable:!0}),i.prototype.addToAxisCache=function(e,o){this._gizmoAxisCache.set(e,o)},i.prototype.dispose=function(){var e=this;this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach(function(o){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(o)})},i.prototype.setCustomMesh=function(e){Logger$2.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},i}(Gizmo),AxisDragGizmo=function(a){__extends(i,a);function i(e,o,s,c,d){o===void 0&&(o=Color3.Gray()),s===void 0&&(s=UtilityLayerRenderer.DefaultUtilityLayer),c===void 0&&(c=null),d===void 0&&(d=1);var _,b=a.call(this,s)||this;b._pointerObserver=null,b.snapDistance=0,b.onSnapObservable=new Observable,b._isEnabled=!0,b._parent=null,b._dragging=!1,b._parent=c,b._coloredMaterial=new StandardMaterial("",s.utilityLayerScene),b._coloredMaterial.diffuseColor=o,b._coloredMaterial.specularColor=o.subtract(new Color3(.1,.1,.1)),b._hoverMaterial=new StandardMaterial("",s.utilityLayerScene),b._hoverMaterial.diffuseColor=Color3.Yellow(),b._disableMaterial=new StandardMaterial("",s.utilityLayerScene),b._disableMaterial.diffuseColor=Color3.Gray(),b._disableMaterial.alpha=.4;var k=i._CreateArrow(s.utilityLayerScene,b._coloredMaterial,d),j=i._CreateArrow(s.utilityLayerScene,b._coloredMaterial,d+4,!0);b._gizmoMesh=new Mesh("",s.utilityLayerScene),b._gizmoMesh.addChild(k),b._gizmoMesh.addChild(j),b._gizmoMesh.lookAt(b._rootMesh.position.add(e)),b._gizmoMesh.scaling.scaleInPlace(1/3),b._gizmoMesh.parent=b._rootMesh;var $=0,_e=new Vector3,et=new Vector3,tt={snapDistance:0};b.dragBehavior=new PointerDragBehavior({dragAxis:e}),b.dragBehavior.moveAttached=!1,b._rootMesh.addBehavior(b.dragBehavior),b.dragBehavior.onDragObservable.add(function(nt){if(b.attachedNode){b._handlePivot();var ot=!1;if(b.snapDistance==0)b.attachedNode.getWorldMatrix().getTranslationToRef(et),et.addInPlace(nt.delta),b.dragBehavior.validateDrag(et)&&(b.attachedNode.position&&b.attachedNode.position.addInPlaceFromFloats(nt.delta.x,nt.delta.y,nt.delta.z),b.attachedNode.getWorldMatrix().addTranslationFromFloats(nt.delta.x,nt.delta.y,nt.delta.z),b.attachedNode.updateCache(),ot=!0);else if($+=nt.dragDistance,Math.abs($)>b.snapDistance){var at=Math.floor(Math.abs($)/b.snapDistance);$=$%b.snapDistance,nt.delta.normalizeToRef(_e),_e.scaleInPlace(b.snapDistance*at),b.attachedNode.getWorldMatrix().getTranslationToRef(et),et.addInPlace(_e),b.dragBehavior.validateDrag(et)&&(b.attachedNode.getWorldMatrix().addTranslationFromFloats(_e.x,_e.y,_e.z),b.attachedNode.updateCache(),tt.snapDistance=b.snapDistance*at,b.onSnapObservable.notifyObservers(tt),ot=!0)}ot&&b._matrixChanged()}}),b.dragBehavior.onDragStartObservable.add(function(){b._dragging=!0}),b.dragBehavior.onDragEndObservable.add(function(){b._dragging=!1});var rt=s._getSharedGizmoLight();rt.includedOnlyMeshes=rt.includedOnlyMeshes.concat(b._rootMesh.getChildMeshes(!1));var it={gizmoMeshes:k.getChildMeshes(),colliderMeshes:j.getChildMeshes(),material:b._coloredMaterial,hoverMaterial:b._hoverMaterial,disableMaterial:b._disableMaterial,active:!1,dragBehavior:b.dragBehavior};return(_=b._parent)===null||_===void 0||_.addToAxisCache(j,it),b._pointerObserver=s.utilityLayerScene.onPointerObservable.add(function(nt){var ot;if(!b._customMeshSet&&(b._isHovered=it.colliderMeshes.indexOf((ot=nt==null?void 0:nt.pickInfo)===null||ot===void 0?void 0:ot.pickedMesh)!=-1,!b._parent)){var at=b.dragBehavior.enabled?b._isHovered||b._dragging?b._hoverMaterial:b._coloredMaterial:b._disableMaterial;b._setGizmoMeshMaterial(it.gizmoMeshes,at)}}),b.dragBehavior.onEnabledObservable.add(function(nt){b._setGizmoMeshMaterial(it.gizmoMeshes,nt?it.material:it.disableMaterial)}),b}return i._CreateArrow=function(e,o,s,c){s===void 0&&(s=1),c===void 0&&(c=!1);var d=new TransformNode("arrow",e),_=CreateCylinder("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(s-1)/4),tessellation:96},e),b=CreateCylinder("cylinder",{diameterTop:.005*s,height:.275,diameterBottom:.005*s,tessellation:96},e);return _.parent=d,_.material=o,_.rotation.x=Math.PI/2,_.position.z+=.3,b.parent=d,b.material=o,b.position.z+=.275/2,b.rotation.x=Math.PI/2,c&&(b.visibility=0,_.visibility=0),d},i._CreateArrowInstance=function(e,o){for(var s=new TransformNode("arrow",e),c=0,d=o.getChildMeshes();c<d.length;c++){var _=d[c],b=_.createInstance(_.name);b.parent=s}return s},i.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(i.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)},enumerable:!1,configurable:!0}),i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(e){e&&e.dispose()}),a.prototype.dispose.call(this)},i}(Gizmo),PlaneDragGizmo=function(a){__extends(i,a);function i(e,o,s,c){o===void 0&&(o=Color3.Gray()),s===void 0&&(s=UtilityLayerRenderer.DefaultUtilityLayer),c===void 0&&(c=null);var d,_=a.call(this,s)||this;_._pointerObserver=null,_.snapDistance=0,_.onSnapObservable=new Observable,_._isEnabled=!1,_._parent=null,_._dragging=!1,_._parent=c,_._coloredMaterial=new StandardMaterial("",s.utilityLayerScene),_._coloredMaterial.diffuseColor=o,_._coloredMaterial.specularColor=o.subtract(new Color3(.1,.1,.1)),_._hoverMaterial=new StandardMaterial("",s.utilityLayerScene),_._hoverMaterial.diffuseColor=Color3.Yellow(),_._disableMaterial=new StandardMaterial("",s.utilityLayerScene),_._disableMaterial.diffuseColor=Color3.Gray(),_._disableMaterial.alpha=.4,_._gizmoMesh=i._CreatePlane(s.utilityLayerScene,_._coloredMaterial),_._gizmoMesh.lookAt(_._rootMesh.position.add(e)),_._gizmoMesh.scaling.scaleInPlace(1/3),_._gizmoMesh.parent=_._rootMesh;var b=0,k=new Vector3,j={snapDistance:0};_.dragBehavior=new PointerDragBehavior({dragPlaneNormal:e}),_.dragBehavior.moveAttached=!1,_._rootMesh.addBehavior(_.dragBehavior),_.dragBehavior.onDragObservable.add(function(et){if(_.attachedNode){if(_._handlePivot(),_.snapDistance==0)_.attachedNode.getWorldMatrix().addTranslationFromFloats(et.delta.x,et.delta.y,et.delta.z);else if(b+=et.dragDistance,Math.abs(b)>_.snapDistance){var tt=Math.floor(Math.abs(b)/_.snapDistance);b=b%_.snapDistance,et.delta.normalizeToRef(k),k.scaleInPlace(_.snapDistance*tt),_.attachedNode.getWorldMatrix().addTranslationFromFloats(k.x,k.y,k.z),j.snapDistance=_.snapDistance*tt,_.onSnapObservable.notifyObservers(j)}_._matrixChanged()}}),_.dragBehavior.onDragStartObservable.add(function(){_._dragging=!0}),_.dragBehavior.onDragEndObservable.add(function(){_._dragging=!1});var $=s._getSharedGizmoLight();$.includedOnlyMeshes=$.includedOnlyMeshes.concat(_._rootMesh.getChildMeshes(!1));var _e={gizmoMeshes:_._gizmoMesh.getChildMeshes(),colliderMeshes:_._gizmoMesh.getChildMeshes(),material:_._coloredMaterial,hoverMaterial:_._hoverMaterial,disableMaterial:_._disableMaterial,active:!1,dragBehavior:_.dragBehavior};return(d=_._parent)===null||d===void 0||d.addToAxisCache(_._gizmoMesh,_e),_._pointerObserver=s.utilityLayerScene.onPointerObservable.add(function(et){var tt;if(!_._customMeshSet&&(_._isHovered=_e.colliderMeshes.indexOf((tt=et==null?void 0:et.pickInfo)===null||tt===void 0?void 0:tt.pickedMesh)!=-1,!_._parent)){var rt=_e.dragBehavior.enabled?_._isHovered||_._dragging?_._hoverMaterial:_._coloredMaterial:_._disableMaterial;_._setGizmoMeshMaterial(_e.gizmoMeshes,rt)}}),_.dragBehavior.onEnabledObservable.add(function(et){_._setGizmoMeshMaterial(_e.gizmoMeshes,et?_._coloredMaterial:_._disableMaterial)}),_}return i._CreatePlane=function(e,o){var s=new TransformNode("plane",e),c=CreatePlane("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return c.material=o,c.parent=s,s},i.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(i.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null},enumerable:!1,configurable:!0}),i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),a.prototype.dispose.call(this),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(e){e&&e.dispose()})},i}(Gizmo),PositionGizmo=function(a){__extends(i,a);function i(e,o,s){e===void 0&&(e=UtilityLayerRenderer.DefaultUtilityLayer),o===void 0&&(o=1);var c=a.call(this,e)||this;return c._meshAttached=null,c._nodeAttached=null,c._observables=[],c._gizmoAxisCache=new Map,c.onDragStartObservable=new Observable,c.onDragEndObservable=new Observable,c._planarGizmoEnabled=!1,c.xGizmo=new AxisDragGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),e,c,o),c.yGizmo=new AxisDragGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),e,c,o),c.zGizmo=new AxisDragGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),e,c,o),c.xPlaneGizmo=new PlaneDragGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),c.gizmoLayer,c),c.yPlaneGizmo=new PlaneDragGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),c.gizmoLayer,c),c.zPlaneGizmo=new PlaneDragGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),c.gizmoLayer,c),[c.xGizmo,c.yGizmo,c.zGizmo,c.xPlaneGizmo,c.yPlaneGizmo,c.zPlaneGizmo].forEach(function(d){d.dragBehavior.onDragStartObservable.add(function(){c.onDragStartObservable.notifyObservers({})}),d.dragBehavior.onDragEndObservable.add(function(){c.onDragEndObservable.notifyObservers({})})}),c.attachedMesh=null,s?s.addToAxisCache(c._gizmoAxisCache):Gizmo.GizmoAxisPointerObserver(e,c._gizmoAxisCache),c}return Object.defineProperty(i.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(o){o.isEnabled?o.attachedMesh=e:o.attachedMesh=null})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(o){o.isEnabled?o.attachedNode=e:o.attachedNode=null})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isHovered",{get:function(){var e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(o){e=e||o.isHovered}),e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"planarGizmoEnabled",{get:function(){return this._planarGizmoEnabled},set:function(e){var o=this;this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(s){s&&(s.isEnabled=e,e&&(s.attachedMesh?s.attachedMesh=o.attachedMesh:s.attachedNode=o.attachedNode))},this)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(o){o&&(o.updateGizmoRotationToMatchAttachedMesh=e)})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"snapDistance",{get:function(){return this._snapDistance},set:function(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(o){o&&(o.snapDistance=e)})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(o){o&&(o.scaleRatio=e)})},enumerable:!1,configurable:!0}),i.prototype.addToAxisCache=function(e,o){this._gizmoAxisCache.set(e,o)},i.prototype.dispose=function(){var e=this;[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(o){o&&o.dispose()}),this._observables.forEach(function(o){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(o)}),this.onDragStartObservable.clear(),this.onDragEndObservable.clear()},i.prototype.setCustomMesh=function(e){Logger$2.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")},i}(Gizmo),AxisScaleGizmo=function(a){__extends(i,a);function i(e,o,s,c,d){o===void 0&&(o=Color3.Gray()),s===void 0&&(s=UtilityLayerRenderer.DefaultUtilityLayer),c===void 0&&(c=null),d===void 0&&(d=1);var _,b,k,j,$,_e,et,tt=a.call(this,s)||this;tt._pointerObserver=null,tt.snapDistance=0,tt.onSnapObservable=new Observable,tt.uniformScaling=!1,tt.sensitivity=1,tt.dragScale=1,tt._isEnabled=!0,tt._parent=null,tt._dragging=!1,tt._tmpVector=new Vector3,tt._tmpMatrix=new Matrix,tt._tmpMatrix2=new Matrix,tt._parent=c,tt._coloredMaterial=new StandardMaterial("",s.utilityLayerScene),tt._coloredMaterial.diffuseColor=o,tt._coloredMaterial.specularColor=o.subtract(new Color3(.1,.1,.1)),tt._hoverMaterial=new StandardMaterial("",s.utilityLayerScene),tt._hoverMaterial.diffuseColor=Color3.Yellow(),tt._disableMaterial=new StandardMaterial("",s.utilityLayerScene),tt._disableMaterial.diffuseColor=Color3.Gray(),tt._disableMaterial.alpha=.4,tt._gizmoMesh=new Mesh("axis",s.utilityLayerScene);var rt=tt._createGizmoMesh(tt._gizmoMesh,d),it=rt.arrowMesh,nt=rt.arrowTail,ot=tt._createGizmoMesh(tt._gizmoMesh,d+4,!0);tt._gizmoMesh.lookAt(tt._rootMesh.position.add(e)),tt._rootMesh.addChild(tt._gizmoMesh),tt._gizmoMesh.scaling.scaleInPlace(1/3);var at=it.position.clone(),st=nt.position.clone(),ut=nt.scaling.clone(),ft=function(_t){var yt=_t*(3/tt._rootMesh.scaling.length())*6;it.position.z+=yt/3.5,nt.scaling.y+=yt,tt.dragScale=nt.scaling.y,nt.position.z=it.position.z/2},lt=function(){it.position.set(at.x,at.y,at.z),nt.position.set(st.x,st.y,st.z),nt.scaling.set(ut.x,ut.y,ut.z),tt.dragScale=nt.scaling.y,tt._dragging=!1};tt.dragBehavior=new PointerDragBehavior({dragAxis:e}),tt.dragBehavior.moveAttached=!1,tt._rootMesh.addBehavior(tt.dragBehavior);var ht=0,pt=new Vector3,mt={snapDistance:0};tt.dragBehavior.onDragObservable.add(function(_t){if(tt.attachedNode){tt._handlePivot();var yt=tt.sensitivity*_t.dragDistance*(tt.scaleRatio*3/tt._rootMesh.scaling.length()),Tt=!1,St=0;tt.uniformScaling?pt.setAll(.57735):pt.copyFrom(e),tt.snapDistance==0?pt.scaleToRef(yt,pt):(ht+=yt,Math.abs(ht)>tt.snapDistance?(St=Math.floor(Math.abs(ht)/tt.snapDistance),ht<0&&(St*=-1),ht=ht%tt.snapDistance,pt.scaleToRef(tt.snapDistance*St,pt),Tt=!0):pt.scaleInPlace(0)),Matrix.ScalingToRef(1+pt.x,1+pt.y,1+pt.z,tt._tmpMatrix2),tt._tmpMatrix2.multiplyToRef(tt.attachedNode.getWorldMatrix(),tt._tmpMatrix),tt._tmpMatrix.decompose(tt._tmpVector);var At=1e5;Math.abs(tt._tmpVector.x)<At&&Math.abs(tt._tmpVector.y)<At&&Math.abs(tt._tmpVector.z)<At&&tt.attachedNode.getWorldMatrix().copyFrom(tt._tmpMatrix),Tt&&(mt.snapDistance=tt.snapDistance*St,tt.onSnapObservable.notifyObservers(mt)),tt._matrixChanged()}}),tt.dragBehavior.onDragStartObservable.add(function(){tt._dragging=!0}),tt.dragBehavior.onDragObservable.add(function(_t){return ft(_t.dragDistance)}),tt.dragBehavior.onDragEndObservable.add(lt),(k=(b=(_=c==null?void 0:c.uniformScaleGizmo)===null||_===void 0?void 0:_.dragBehavior)===null||b===void 0?void 0:b.onDragObservable)===null||k===void 0||k.add(function(_t){return ft(_t.delta.y)}),(_e=($=(j=c==null?void 0:c.uniformScaleGizmo)===null||j===void 0?void 0:j.dragBehavior)===null||$===void 0?void 0:$.onDragEndObservable)===null||_e===void 0||_e.add(lt);var dt={gizmoMeshes:[it,nt],colliderMeshes:[ot.arrowMesh,ot.arrowTail],material:tt._coloredMaterial,hoverMaterial:tt._hoverMaterial,disableMaterial:tt._disableMaterial,active:!1,dragBehavior:tt.dragBehavior};(et=tt._parent)===null||et===void 0||et.addToAxisCache(tt._gizmoMesh,dt),tt._pointerObserver=s.utilityLayerScene.onPointerObservable.add(function(_t){var yt;if(!tt._customMeshSet&&(tt._isHovered=dt.colliderMeshes.indexOf((yt=_t==null?void 0:_t.pickInfo)===null||yt===void 0?void 0:yt.pickedMesh)!=-1,!tt._parent)){var Tt=tt.dragBehavior.enabled?tt._isHovered||tt._dragging?tt._hoverMaterial:tt._coloredMaterial:tt._disableMaterial;tt._setGizmoMeshMaterial(dt.gizmoMeshes,Tt)}}),tt.dragBehavior.onEnabledObservable.add(function(_t){tt._setGizmoMeshMaterial(dt.gizmoMeshes,_t?tt._coloredMaterial:tt._disableMaterial)});var gt=s._getSharedGizmoLight();return gt.includedOnlyMeshes=gt.includedOnlyMeshes.concat(tt._rootMesh.getChildMeshes()),tt}return i.prototype._createGizmoMesh=function(e,o,s){s===void 0&&(s=!1);var c=CreateBox("yPosMesh",{size:.4*(1+(o-1)/4)},this.gizmoLayer.utilityLayerScene),d=CreateCylinder("cylinder",{diameterTop:.005*o,height:.275,diameterBottom:.005*o,tessellation:96},this.gizmoLayer.utilityLayerScene);return c.scaling.scaleInPlace(.1),c.material=this._coloredMaterial,c.rotation.x=Math.PI/2,c.position.z+=.3,d.material=this._coloredMaterial,d.position.z+=.275/2,d.rotation.x=Math.PI/2,s&&(c.visibility=0,d.visibility=0),e.addChild(c),e.addChild(d),{arrowMesh:c,arrowTail:d}},i.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(i.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)},enumerable:!1,configurable:!0}),i.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(e){e&&e.dispose()}),a.prototype.dispose.call(this)},i.prototype.setCustomMesh=function(e,o){var s=this;o===void 0&&(o=!1),a.prototype.setCustomMesh.call(this,e),o&&(this._rootMesh.getChildMeshes().forEach(function(c){c.material=s._coloredMaterial,c.color&&(c.color=s._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)},i}(Gizmo),ScaleGizmo=function(a){__extends(i,a);function i(e,o,s){e===void 0&&(e=UtilityLayerRenderer.DefaultUtilityLayer),o===void 0&&(o=1);var c=a.call(this,e)||this;return c._meshAttached=null,c._nodeAttached=null,c._sensitivity=1,c._observables=[],c._gizmoAxisCache=new Map,c.onDragStartObservable=new Observable,c.onDragEndObservable=new Observable,c.uniformScaleGizmo=c._createUniformScaleMesh(),c.xGizmo=new AxisScaleGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),e,c,o),c.yGizmo=new AxisScaleGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),e,c,o),c.zGizmo=new AxisScaleGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),e,c,o),[c.xGizmo,c.yGizmo,c.zGizmo,c.uniformScaleGizmo].forEach(function(d){d.dragBehavior.onDragStartObservable.add(function(){c.onDragStartObservable.notifyObservers({})}),d.dragBehavior.onDragEndObservable.add(function(){c.onDragEndObservable.notifyObservers({})})}),c.attachedMesh=null,c.attachedNode=null,s?s.addToAxisCache(c._gizmoAxisCache):Gizmo.GizmoAxisPointerObserver(e,c._gizmoAxisCache),c}return Object.defineProperty(i.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(o){o.isEnabled?o.attachedMesh=e:o.attachedMesh=null})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(o){o.isEnabled?o.attachedNode=e:o.attachedNode=null})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isHovered",{get:function(){var e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(o){e=e||o.isHovered}),e},enumerable:!1,configurable:!0}),i.prototype._createUniformScaleMesh=function(){this._coloredMaterial=new StandardMaterial("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Color3.Gray(),this._hoverMaterial=new StandardMaterial("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Color3.Yellow(),this._disableMaterial=new StandardMaterial("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Color3.Gray(),this._disableMaterial.alpha=.4;var e=new AxisScaleGizmo(new Vector3(0,1,0),Color3.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=CreatePolyhedron("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=CreatePolyhedron("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);var o=this.gizmoLayer._getSharedGizmoLight();o.includedOnlyMeshes=o.includedOnlyMeshes.concat(this._octahedron);var s={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,s),e},Object.defineProperty(i.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(o){o&&(o.updateGizmoRotationToMatchAttachedMesh=e)})):Logger$2.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"snapDistance",{get:function(){return this._snapDistance},set:function(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(o){o&&(o.snapDistance=e)})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(o){o&&(o.scaleRatio=e)})},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sensitivity",{get:function(){return this._sensitivity},set:function(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(o){o&&(o.sensitivity=e)})},enumerable:!1,configurable:!0}),i.prototype.addToAxisCache=function(e,o){this._gizmoAxisCache.set(e,o)},i.prototype.dispose=function(){var e=this;[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(function(o){o&&o.dispose()}),this._observables.forEach(function(o){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(o)}),this.onDragStartObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach(function(o){o&&o.dispose()}),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(o){o&&o.dispose()})},i}(Gizmo),BoundingBoxGizmo=function(a){__extends(i,a);function i(e,o){e===void 0&&(e=Color3.Gray()),o===void 0&&(o=UtilityLayerRenderer.DefaultKeepDepthUtilityLayer);var s=a.call(this,o)||this;s._boundingDimensions=new Vector3(1,1,1),s._renderObserver=null,s._pointerObserver=null,s._scaleDragSpeed=.2,s._tmpQuaternion=new Quaternion,s._tmpVector=new Vector3(0,0,0),s._tmpRotationMatrix=new Matrix,s.ignoreChildren=!1,s.includeChildPredicate=null,s.rotationSphereSize=.1,s.scaleBoxSize=.1,s.fixedDragMeshScreenSize=!1,s.fixedDragMeshBoundsSize=!1,s.fixedDragMeshScreenSizeDistanceFactor=10,s.onDragStartObservable=new Observable,s.onScaleBoxDragObservable=new Observable,s.onScaleBoxDragEndObservable=new Observable,s.onRotationSphereDragObservable=new Observable,s.onRotationSphereDragEndObservable=new Observable,s.scalePivot=null,s._axisFactor=new Vector3(1,1,1),s._existingMeshScale=new Vector3,s._dragMesh=null,s.pointerDragBehavior=new PointerDragBehavior,s.updateScale=!1,s._anchorMesh=new AbstractMesh("anchor",o.utilityLayerScene),s.coloredMaterial=new StandardMaterial("",o.utilityLayerScene),s.coloredMaterial.disableLighting=!0,s.hoverColoredMaterial=new StandardMaterial("",o.utilityLayerScene),s.hoverColoredMaterial.disableLighting=!0,s._lineBoundingBox=new AbstractMesh("",o.utilityLayerScene),s._lineBoundingBox.rotationQuaternion=new Quaternion;var c=[];c.push(CreateLines("lines",{points:[new Vector3(0,0,0),new Vector3(s._boundingDimensions.x,0,0)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(0,0,0),new Vector3(0,s._boundingDimensions.y,0)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(0,0,0),new Vector3(0,0,s._boundingDimensions.z)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(s._boundingDimensions.x,0,0),new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,0)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(s._boundingDimensions.x,0,0),new Vector3(s._boundingDimensions.x,0,s._boundingDimensions.z)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(0,s._boundingDimensions.y,0),new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,0)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(0,s._boundingDimensions.y,0),new Vector3(0,s._boundingDimensions.y,s._boundingDimensions.z)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(0,0,s._boundingDimensions.z),new Vector3(s._boundingDimensions.x,0,s._boundingDimensions.z)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(0,0,s._boundingDimensions.z),new Vector3(0,s._boundingDimensions.y,s._boundingDimensions.z)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,s._boundingDimensions.z),new Vector3(0,s._boundingDimensions.y,s._boundingDimensions.z)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,s._boundingDimensions.z),new Vector3(s._boundingDimensions.x,0,s._boundingDimensions.z)]},o.utilityLayerScene)),c.push(CreateLines("lines",{points:[new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,s._boundingDimensions.z),new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,0)]},o.utilityLayerScene)),c.forEach(function(it){it.color=e,it.position.addInPlace(new Vector3(-s._boundingDimensions.x/2,-s._boundingDimensions.y/2,-s._boundingDimensions.z/2)),it.isPickable=!1,s._lineBoundingBox.addChild(it)}),s._rootMesh.addChild(s._lineBoundingBox),s.setColor(e),s._rotateSpheresParent=new AbstractMesh("",o.utilityLayerScene),s._rotateSpheresParent.rotationQuaternion=new Quaternion;for(var d=function(it){var nt=CreateSphere("",{diameter:1},o.utilityLayerScene);nt.rotationQuaternion=new Quaternion,nt.material=_.coloredMaterial,nt.isNearGrabbable=!0,b=new PointerDragBehavior({}),b.moveAttached=!1,b.updateDragPlane=!1,nt.addBehavior(b);var ot=new Vector3(1,0,0),at=0;b.onDragStartObservable.add(function(){ot.copyFrom(nt.forward),at=0}),b.onDragObservable.add(function(st){if(s.onRotationSphereDragObservable.notifyObservers({}),s.attachedMesh){var ut=s.attachedMesh.parent;if(ut&&ut.scaling&&ut.scaling.isNonUniformWithinEpsilon(.001)){Logger$2.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}PivotTools._RemoveAndStorePivotPoint(s.attachedMesh);var ft=ot,lt=st.dragPlaneNormal.scale(Vector3.Dot(st.dragPlaneNormal,ft)),ht=ft.subtract(lt).normalizeToNew(),pt=Vector3.Dot(ht,st.delta)<0?Math.abs(st.delta.length()):-Math.abs(st.delta.length());pt=pt/s._boundingDimensions.length()*s._anchorMesh.scaling.length(),s.attachedMesh.rotationQuaternion||(s.attachedMesh.rotationQuaternion=Quaternion.RotationYawPitchRoll(s.attachedMesh.rotation.y,s.attachedMesh.rotation.x,s.attachedMesh.rotation.z)),s._anchorMesh.rotationQuaternion||(s._anchorMesh.rotationQuaternion=Quaternion.RotationYawPitchRoll(s._anchorMesh.rotation.y,s._anchorMesh.rotation.x,s._anchorMesh.rotation.z)),at+=pt,Math.abs(at)<=2*Math.PI&&(it>=8?Quaternion.RotationYawPitchRollToRef(0,0,pt,s._tmpQuaternion):it>=4?Quaternion.RotationYawPitchRollToRef(pt,0,0,s._tmpQuaternion):Quaternion.RotationYawPitchRollToRef(0,pt,0,s._tmpQuaternion),s._anchorMesh.addChild(s.attachedMesh),s._anchorMesh.rotationQuaternion.multiplyToRef(s._tmpQuaternion,s._anchorMesh.rotationQuaternion),s._anchorMesh.removeChild(s.attachedMesh),s.attachedMesh.setParent(ut)),s.updateBoundingBox(),PivotTools._RestorePivotPoint(s.attachedMesh)}s._updateDummy()}),b.onDragStartObservable.add(function(){s.onDragStartObservable.notifyObservers({}),s._selectNode(nt)}),b.onDragEndObservable.add(function(){s.onRotationSphereDragEndObservable.notifyObservers({}),s._selectNode(null),s._updateDummy()}),_._rotateSpheresParent.addChild(nt)},_=this,b,k=0;k<12;k++)d(k);s._rootMesh.addChild(s._rotateSpheresParent),s._scaleBoxesParent=new AbstractMesh("",o.utilityLayerScene),s._scaleBoxesParent.rotationQuaternion=new Quaternion;for(var j=0;j<3;j++)for(var $=0;$<3;$++)for(var _e=function(){var nt=(j===1?1:0)+($===1?1:0)+(tt===1?1:0);if(nt===1||nt===3)return"continue";var ot=CreateBox("",{size:1},o.utilityLayerScene);ot.material=et.coloredMaterial,ot.metadata=nt===2,ot.isNearGrabbable=!0;var at=new Vector3(j-1,$-1,tt-1).normalize();b=new PointerDragBehavior({dragAxis:at}),b.updateDragPlane=!1,b.moveAttached=!1,ot.addBehavior(b),b.onDragObservable.add(function(st){if(s.onScaleBoxDragObservable.notifyObservers({}),s.attachedMesh){var ut=s.attachedMesh.parent;if(ut&&ut.scaling&&ut.scaling.isNonUniformWithinEpsilon(.001)){Logger$2.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}PivotTools._RemoveAndStorePivotPoint(s.attachedMesh);var ft=st.dragDistance/s._boundingDimensions.length()*s._anchorMesh.scaling.length(),lt=new Vector3(ft,ft,ft);nt===2&&(lt.x*=Math.abs(at.x),lt.y*=Math.abs(at.y),lt.z*=Math.abs(at.z)),lt.scaleInPlace(s._scaleDragSpeed),lt.multiplyInPlace(s._axisFactor),s.updateBoundingBox(),s.scalePivot?(s.attachedMesh.getWorldMatrix().getRotationMatrixToRef(s._tmpRotationMatrix),s._boundingDimensions.scaleToRef(.5,s._tmpVector),Vector3.TransformCoordinatesToRef(s._tmpVector,s._tmpRotationMatrix,s._tmpVector),s._anchorMesh.position.subtractInPlace(s._tmpVector),s._boundingDimensions.multiplyToRef(s.scalePivot,s._tmpVector),Vector3.TransformCoordinatesToRef(s._tmpVector,s._tmpRotationMatrix,s._tmpVector),s._anchorMesh.position.addInPlace(s._tmpVector)):(ot.absolutePosition.subtractToRef(s._anchorMesh.position,s._tmpVector),s._anchorMesh.position.subtractInPlace(s._tmpVector)),s._anchorMesh.addChild(s.attachedMesh),s._anchorMesh.scaling.addInPlace(lt),(s._anchorMesh.scaling.x<0||s._anchorMesh.scaling.y<0||s._anchorMesh.scaling.z<0)&&s._anchorMesh.scaling.subtractInPlace(lt),s._anchorMesh.removeChild(s.attachedMesh),s.attachedMesh.setParent(ut),PivotTools._RestorePivotPoint(s.attachedMesh)}s._updateDummy()}),b.onDragStartObservable.add(function(){s.onDragStartObservable.notifyObservers({}),s._selectNode(ot)}),b.onDragEndObservable.add(function(){s.onScaleBoxDragEndObservable.notifyObservers({}),s._selectNode(null),s._updateDummy()}),et._scaleBoxesParent.addChild(ot)},et=this,b,tt=0;tt<3;tt++)_e();s._rootMesh.addChild(s._scaleBoxesParent);var rt=new Array;return s._pointerObserver=o.utilityLayerScene.onPointerObservable.add(function(it){rt[it.event.pointerId]?it.pickInfo&&it.pickInfo.pickedMesh!=rt[it.event.pointerId]&&(rt[it.event.pointerId].material=s.coloredMaterial,delete rt[it.event.pointerId]):s._rotateSpheresParent.getChildMeshes().concat(s._scaleBoxesParent.getChildMeshes()).forEach(function(nt){it.pickInfo&&it.pickInfo.pickedMesh==nt&&(rt[it.event.pointerId]=nt,nt.material=s.hoverColoredMaterial)})}),s._renderObserver=s.gizmoLayer.originalScene.onBeforeRenderObservable.add(function(){s.attachedMesh&&!s._existingMeshScale.equals(s.attachedMesh.scaling)?s.updateBoundingBox():(s.fixedDragMeshScreenSize||s.fixedDragMeshBoundsSize)&&(s._updateRotationSpheres(),s._updateScaleBoxes()),s._dragMesh&&s.attachedMesh&&s.pointerDragBehavior.dragging&&(s._lineBoundingBox.position.rotateByQuaternionToRef(s._rootMesh.rotationQuaternion,s._tmpVector),s.attachedMesh.setAbsolutePosition(s._dragMesh.position.add(s._tmpVector.scale(-1))))}),s.updateBoundingBox(),s}return Object.defineProperty(i.prototype,"axisFactor",{get:function(){return this._axisFactor},set:function(e){this._axisFactor=e;for(var o=this._scaleBoxesParent.getChildMeshes(),s=0,c=0;c<3;c++)for(var d=0;d<3;d++)for(var _=0;_<3;_++){var b=(c===1?1:0)+(d===1?1:0)+(_===1?1:0);if(!(b===1||b===3)){if(o[s]){var k=new Vector3(c-1,d-1,_-1);k.multiplyInPlace(this._axisFactor),o[s].setEnabled(k.lengthSquared()>Epsilon)}s++}}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"scaleDragSpeed",{get:function(){return this._scaleDragSpeed},set:function(e){this._scaleDragSpeed=e},enumerable:!1,configurable:!0}),i.prototype.setColor=function(e){this.coloredMaterial.emissiveColor=e,this.hoverColoredMaterial.emissiveColor=e.clone().add(new Color3(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(function(o){o.color&&(o.color=e)})},i.prototype._attachedNodeChanged=function(e){var o=this;if(e){this._anchorMesh.scaling.setAll(1),PivotTools._RemoveAndStorePivotPoint(e);var s=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(s),PivotTools._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach(function(c){c.markAsDirty("scaling")}),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function(){o._updateDummy()})}},i.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(function(o){o.isVisible=!e||o==e})},i.prototype.updateBoundingBox=function(){if(this.attachedMesh){PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);var e=this.attachedMesh.parent;this.attachedMesh.setParent(null);var o=null;this.attachedMesh.skeleton&&(o=this.attachedMesh.skeleton.overrideMesh,this.attachedMesh.skeleton.overrideMesh=null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var s=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);s.max.subtractToRef(s.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((s.max.x+s.min.x)/2,(s.max.y+s.min.y)/2,(s.max.z+s.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e),this.attachedMesh.skeleton&&(this.attachedMesh.skeleton.overrideMesh=o)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),PivotTools._RestorePivotPoint(this.attachedMesh))},i.prototype._updateRotationSpheres=function(){for(var e=this._rotateSpheresParent.getChildMeshes(),o=0;o<3;o++)for(var s=0;s<2;s++)for(var c=0;c<2;c++){var d=o*4+s*2+c;if(o==0&&(e[d].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*s,this._boundingDimensions.z*c),e[d].position.addInPlace(new Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[d].lookAt(Vector3.Cross(e[d].position.normalizeToNew(),Vector3.Right()).normalizeToNew().add(e[d].position))),o==1&&(e[d].position.set(this._boundingDimensions.x*s,this._boundingDimensions.y/2,this._boundingDimensions.z*c),e[d].position.addInPlace(new Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[d].lookAt(Vector3.Cross(e[d].position.normalizeToNew(),Vector3.Up()).normalizeToNew().add(e[d].position))),o==2&&(e[d].position.set(this._boundingDimensions.x*s,this._boundingDimensions.y*c,this._boundingDimensions.z/2),e[d].position.addInPlace(new Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[d].lookAt(Vector3.Cross(e[d].position.normalizeToNew(),Vector3.Forward()).normalizeToNew().add(e[d].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[d].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var _=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[d].scaling.set(_,_,_)}else this.fixedDragMeshBoundsSize?e[d].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[d].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}},i.prototype._updateScaleBoxes=function(){for(var e=this._scaleBoxesParent.getChildMeshes(),o=0,s=0;s<3;s++)for(var c=0;c<3;c++)for(var d=0;d<3;d++){var _=(s===1?1:0)+(c===1?1:0)+(d===1?1:0);if(!(_===1||_===3)){if(e[o])if(e[o].position.set(this._boundingDimensions.x*(s/2),this._boundingDimensions.y*(c/2),this._boundingDimensions.z*(d/2)),e[o].position.addInPlace(new Vector3(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[o].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var b=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[o].scaling.set(b,b,b)}else this.fixedDragMeshBoundsSize?e[o].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[o].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);o++}}},i.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach(function(o,s){s<4?o.setEnabled(e.indexOf("x")!=-1):s<8?o.setEnabled(e.indexOf("y")!=-1):o.setEnabled(e.indexOf("z")!=-1)})},i.prototype.setEnabledScaling=function(e,o){o===void 0&&(o=!1),this._scaleBoxesParent.getChildMeshes().forEach(function(s,c){var d=e;o&&s.metadata===!0&&(d=!1),s.setEnabled(d)})},i.prototype._updateDummy=function(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))},i.prototype.enableDragBehavior=function(){this._dragMesh=CreateBox("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new Quaternion,this.pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this.pointerDragBehavior)},i.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),a.prototype.dispose.call(this)},i.MakeNotPickableAndWrapInBoundingBox=function(e){var o=function(b){b.isPickable=!1,b.getChildMeshes().forEach(function(k){o(k)})};o(e),e.rotationQuaternion||(e.rotationQuaternion=Quaternion.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));var s=e.position.clone(),c=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);var d=CreateBox("box",{size:1},e.getScene()),_=e.getHierarchyBoundingVectors();return _.max.subtractToRef(_.min,d.scaling),d.scaling.y===0&&(d.scaling.y=Epsilon),d.scaling.x===0&&(d.scaling.x=Epsilon),d.scaling.z===0&&(d.scaling.z=Epsilon),d.position.set((_.max.x+_.min.x)/2,(_.max.y+_.min.y)/2,(_.max.z+_.min.z)/2),e.addChild(d),e.rotationQuaternion.copyFrom(c),e.position.copyFrom(s),e.removeChild(d),d.addChild(e),d.visibility=0,d},i.prototype.setCustomMesh=function(e){Logger$2.Error("Custom meshes are not supported on this gizmo")},i}(Gizmo);(function(){function a(i,e,o,s){e===void 0&&(e=1),o===void 0&&(o=UtilityLayerRenderer.DefaultUtilityLayer),s===void 0&&(s=UtilityLayerRenderer.DefaultKeepDepthUtilityLayer),this.scene=i,this.clearGizmoOnEmptyPointerEvent=!1,this.onAttachedToMeshObservable=new Observable,this.onAttachedToNodeObservable=new Observable,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Color3.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new SixDofDragBehavior,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=o,this._defaultKeepDepthUtilityLayer=s,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=e,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};var c=this._attachToMeshPointerObserver(i),d=Gizmo.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[c,d]}return Object.defineProperty(a.prototype,"keepDepthUtilityLayer",{get:function(){return this._defaultKeepDepthUtilityLayer},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"utilityLayer",{get:function(){return this._defaultUtilityLayer},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isHovered",{get:function(){var i=!1;for(var e in this.gizmos){var o=this.gizmos[e];if(o&&o.isHovered){i=!0;break}}return i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(i){this._scaleRatio=i,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach(function(e){e&&(e.scaleRatio=i)})},enumerable:!1,configurable:!0}),a.prototype._attachToMeshPointerObserver=function(i){var e=this,o=i.onPointerObservable.add(function(s){if(!!e.usePointerToAttachGizmos&&s.type==PointerEventTypes.POINTERDOWN)if(s.pickInfo&&s.pickInfo.pickedMesh){var c=s.pickInfo.pickedMesh;if(e.attachableMeshes==null)for(;c&&c.parent!=null;)c=c.parent;else{var d=!1;e.attachableMeshes.forEach(function(_){c&&(c==_||c.isDescendantOf(_))&&(c=_,d=!0)}),d||(c=null)}c instanceof AbstractMesh?e._attachedMesh!=c&&e.attachToMesh(c):e.clearGizmoOnEmptyPointerEvent&&e.attachToMesh(null)}else e.clearGizmoOnEmptyPointerEvent&&e.attachToMesh(null)});return o},a.prototype.attachToMesh=function(i){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=i,this._attachedNode=null;for(var e in this.gizmos){var o=this.gizmos[e];o&&this._gizmosEnabled[e]&&(o.attachedMesh=i)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(i)},a.prototype.attachToNode=function(i){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=i;for(var e in this.gizmos){var o=this.gizmos[e];o&&this._gizmosEnabled[e]&&(o.attachedNode=i)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(i)},Object.defineProperty(a.prototype,"positionGizmoEnabled",{get:function(){return this._gizmosEnabled.positionGizmo},set:function(i){i?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new PositionGizmo(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rotationGizmoEnabled",{get:function(){return this._gizmosEnabled.rotationGizmo},set:function(i){i?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new RotationGizmo(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"scaleGizmoEnabled",{get:function(){return this._gizmosEnabled.scaleGizmo},set:function(i){i?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new ScaleGizmo(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"boundingBoxGizmoEnabled",{get:function(){return this._gizmosEnabled.boundingBoxGizmo},set:function(i){i?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new BoundingBoxGizmo(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=i},enumerable:!1,configurable:!0}),a.prototype.addToAxisCache=function(i){var e=this;i.size>0&&i.forEach(function(o,s){e._gizmoAxisCache.set(s,o)})},a.prototype.dispose=function(){var i=this,e,o;this._pointerObservers.forEach(function(d){i.scene.onPointerObservable.remove(d)});for(var s in this.gizmos){var c=this.gizmos[s];c&&c.dispose()}this._defaultKeepDepthUtilityLayer!==UtilityLayerRenderer._DefaultKeepDepthUtilityLayer&&((e=this._defaultKeepDepthUtilityLayer)===null||e===void 0||e.dispose()),this._defaultUtilityLayer!==UtilityLayerRenderer._DefaultUtilityLayer&&((o=this._defaultUtilityLayer)===null||o===void 0||o.dispose()),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()},a})();var LayerSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_LAYER,this.scene=i,this._engine=i.getEngine(),i.layers=new Array}return a.prototype.register=function(){this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER,this,this._drawCameraBackground),this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER,this,this._drawCameraForeground),this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER,this,this._drawRenderTargetBackground),this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER,this,this._drawRenderTargetForeground)},a.prototype.rebuild=function(){for(var i=this.scene.layers,e=0,o=i;e<o.length;e++){var s=o[e];s._rebuild()}},a.prototype.dispose=function(){for(var i=this.scene.layers;i.length;)i[0].dispose()},a.prototype._draw=function(i){var e=this.scene.layers;if(e.length){this._engine.setDepthBuffer(!1);for(var o=0,s=e;o<s.length;o++){var c=s[o];i(c)&&c.render()}this._engine.setDepthBuffer(!0)}},a.prototype._drawCameraPredicate=function(i,e,o){return!i.renderOnlyInRenderTargetTextures&&i.isBackground===e&&(i.layerMask&o)!==0},a.prototype._drawCameraBackground=function(i){var e=this;this._draw(function(o){return e._drawCameraPredicate(o,!0,i.layerMask)})},a.prototype._drawCameraForeground=function(i){var e=this;this._draw(function(o){return e._drawCameraPredicate(o,!1,i.layerMask)})},a.prototype._drawRenderTargetPredicate=function(i,e,o,s){return i.renderTargetTextures.length>0&&i.isBackground===e&&i.renderTargetTextures.indexOf(s)>-1&&(i.layerMask&o)!==0},a.prototype._drawRenderTargetBackground=function(i){var e=this;this._draw(function(o){return e._drawRenderTargetPredicate(o,!0,e.scene.activeCamera.layerMask,i)})},a.prototype._drawRenderTargetForeground=function(i){var e=this;this._draw(function(o){return e._drawRenderTargetPredicate(o,!1,e.scene.activeCamera.layerMask,i)})},a.prototype.addFromContainer=function(i){var e=this;!i.layers||i.layers.forEach(function(o){e.scene.layers.push(o)})},a.prototype.removeFromContainer=function(i,e){var o=this;e===void 0&&(e=!1),i.layers&&i.layers.forEach(function(s){var c=o.scene.layers.indexOf(s);c!==-1&&o.scene.layers.splice(c,1),e&&s.dispose()})},a}(),name$j="layerPixelShader",shader$j=`
  10203. varying vec2 vUV;
  10204. uniform sampler2D textureSampler;
  10205. uniform vec4 color;
  10206. #include<helperFunctions>
  10207. void main(void) {
  10208. vec4 baseColor=texture2D(textureSampler,vUV);
  10209. #ifdef LINEAR
  10210. baseColor.rgb=toGammaSpace(baseColor.rgb);
  10211. #endif
  10212. #ifdef ALPHATEST
  10213. if (baseColor.a<0.4)
  10214. discard;
  10215. #endif
  10216. gl_FragColor=baseColor*color;
  10217. }`;ShaderStore.ShadersStore[name$j]=shader$j;var name$i="layerVertexShader",shader$i=`
  10218. attribute vec2 position;
  10219. uniform vec2 scale;
  10220. uniform vec2 offset;
  10221. uniform mat4 textureMatrix;
  10222. varying vec2 vUV;
  10223. const vec2 madd=vec2(0.5,0.5);
  10224. void main(void) {
  10225. vec2 shiftedPosition=position*scale+offset;
  10226. vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));
  10227. gl_Position=vec4(shiftedPosition,0.0,1.0);
  10228. }`;ShaderStore.ShadersStore[name$i]=shader$i;var Layer=function(){function a(i,e,o,s,c){this.name=i,this.scale=new Vector2(1,1),this.offset=new Vector2(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new Observable,this.onBeforeRenderObservable=new Observable,this.onAfterRenderObservable=new Observable,this.texture=e?new Texture(e,o,!0):null,this.isBackground=s===void 0?!0:s,this.color=c===void 0?new Color4(1,1,1,1):c,this._scene=o||EngineStore.LastCreatedScene;var d=this._scene._getComponent(SceneComponentConstants.NAME_LAYER);d||(d=new LayerSceneComponent(this._scene),this._scene._addComponent(d)),this._scene.layers.push(this);var _=this._scene.getEngine();this._drawWrapper=new DrawWrapper(_);var b=[];b.push(1,1),b.push(-1,1),b.push(-1,-1),b.push(1,-1);var k=new VertexBuffer(_,b,VertexBuffer.PositionKind,!1,!1,2);this._vertexBuffers[VertexBuffer.PositionKind]=k,this._createIndexBuffer()}return Object.defineProperty(a.prototype,"onDispose",{set:function(i){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onBeforeRender",{set:function(i){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onAfterRender",{set:function(i){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(i)},enumerable:!1,configurable:!0}),a.prototype._createIndexBuffer=function(){var i=this._scene.getEngine(),e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=i.createIndexBuffer(e)},a.prototype._rebuild=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&i._rebuild(),this._createIndexBuffer()},a.prototype.render=function(){if(!!this.isEnabled){var o=this._scene.getEngine(),i="";this.alphaTest&&(i="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(i+=`\r
  10229. #define LINEAR`),this._previousDefines!==i&&(this._previousDefines=i,this._drawWrapper.effect=o.createEffect("layer",[VertexBuffer.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],i));var e=this._drawWrapper.effect;if(!(!e||!e.isReady()||!this.texture||!this.texture.isReady())){var o=this._scene.getEngine();this.onBeforeRenderObservable.notifyObservers(this),o.enableEffect(this._drawWrapper),o.setState(!1),e.setTexture("textureSampler",this.texture),e.setMatrix("textureMatrix",this.texture.getTextureMatrix()),e.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),e.setVector2("offset",this.offset),e.setVector2("scale",this.scale),o.bindBuffers(this._vertexBuffers,this._indexBuffer,e),this.alphaTest?o.drawElementsType(Material.TriangleFillMode,0,6):(o.setAlphaMode(this.alphaBlendingMode),o.drawElementsType(Material.TriangleFillMode,0,6),o.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}}},a.prototype.dispose=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&(i.dispose(),this._vertexBuffers[VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];var e=this._scene.layers.indexOf(this);this._scene.layers.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},a}(),name$h="boundingBoxRendererFragmentDeclaration",shader$h=`uniform vec4 color;
  10230. `;ShaderStore.IncludesShadersStore[name$h]=shader$h;var name$g="boundingBoxRendererUboDeclaration",shader$g=`layout(std140,column_major) uniform;
  10231. uniform BoundingBoxRenderer {
  10232. vec4 color;
  10233. mat4 world;
  10234. mat4 viewProjection;
  10235. mat4 viewProjectionR;
  10236. };
  10237. `;ShaderStore.IncludesShadersStore[name$g]=shader$g;var name$f="boundingBoxRendererPixelShader",shader$f=`#include<__decl__boundingBoxRendererFragment>
  10238. void main(void) {
  10239. gl_FragColor=color;
  10240. }`;ShaderStore.ShadersStore[name$f]=shader$f;var name$e="boundingBoxRendererVertexDeclaration",shader$e=`uniform mat4 world;
  10241. uniform mat4 viewProjection;
  10242. #ifdef MULTIVIEW
  10243. uniform mat4 viewProjectionR;
  10244. #endif
  10245. `;ShaderStore.IncludesShadersStore[name$e]=shader$e;var name$d="boundingBoxRendererVertexShader",shader$d=`
  10246. attribute vec3 position;
  10247. #include<__decl__boundingBoxRendererVertex>
  10248. void main(void) {
  10249. vec4 worldPos=world*vec4(position,1.0);
  10250. #ifdef MULTIVIEW
  10251. if (gl_ViewID_OVR == 0u) {
  10252. gl_Position=viewProjection*worldPos;
  10253. } else {
  10254. gl_Position=viewProjectionR*worldPos;
  10255. }
  10256. #else
  10257. gl_Position=viewProjection*worldPos;
  10258. #endif
  10259. }
  10260. `;ShaderStore.ShadersStore[name$d]=shader$d;Object.defineProperty(Scene.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(a){this._forceShowBoundingBoxes=a,a&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});Scene.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new BoundingBoxRenderer(this)),this._boundingBoxRenderer};Object.defineProperty(AbstractMesh.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(a){this._showBoundingBox=a,a&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});var BoundingBoxRenderer=function(){function a(i){this.name=SceneComponentConstants.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Color3(1,1,1),this.backColor=new Color3(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new Observable,this.onAfterBoxRenderingObservable=new Observable,this.onResourcesReadyObservable=new Observable,this.enabled=!0,this.renderList=new SmartArray(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=i,i._addComponent(this),this._uniformBufferFront=new UniformBuffer(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront"),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new UniformBuffer(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack"),this._buildUniformLayout(this._uniformBufferBack)}return a.prototype._buildUniformLayout=function(i){i.addUniform("color",4),i.addUniform("world",16),i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.create()},a.prototype.register=function(){this.scene._beforeEvaluateActiveMeshStage.registerStep(SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)},a.prototype._evaluateSubMesh=function(i,e){if(i.showSubMeshesBoundingBox){var o=e.getBoundingInfo();o!=null&&(o.boundingBox._tag=i.renderingGroupId,this.renderList.push(o.boundingBox))}},a.prototype._preActiveMesh=function(i){if(i.showBoundingBox||this.scene.forceShowBoundingBoxes){var e=i.getBoundingInfo();e.boundingBox._tag=i.renderingGroupId,this.renderList.push(e.boundingBox)}},a.prototype._prepareResources=function(){if(!this._colorShader){this._colorShader=new ShaderMaterial("colorShader",this.scene,"boundingBoxRenderer",{attributes:[VertexBuffer.PositionKind],uniforms:["world","viewProjection","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new ShaderMaterial("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[VertexBuffer.PositionKind],uniforms:["world","viewProjection","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};var i=this.scene.getEngine(),e=CreateBoxVertexData({size:1});this._vertexBuffers[VertexBuffer.PositionKind]=new VertexBuffer(i,e.positions,VertexBuffer.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=e.indices,this.onResourcesReadyObservable.notifyObservers(this)}},a.prototype._createIndexBuffer=function(){var i=this.scene.getEngine();this._indexBuffer=i.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])},a.prototype.rebuild=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&i._rebuild(),this._createIndexBuffer()},a.prototype.reset=function(){this.renderList.reset()},a.prototype.render=function(i){var e,o;if(!(this.renderList.length===0||!this.enabled)&&(this._prepareResources(),!!this._colorShader.isReady())){var s=this.scene.getEngine();s.setDepthWrite(!1);for(var c=this.frontColor.toColor4(),d=this.backColor.toColor4(),_=this.scene.getTransformMatrix(),b=0;b<this.renderList.length;b++){var k=this.renderList.data[b];if(k._tag===i){this._createWrappersForBoundingBox(k),this.onBeforeBoxRenderingObservable.notifyObservers(k);var j=k.minimum,$=k.maximum,_e=$.subtract(j),et=j.add(_e.scale(.5)),tt=Matrix.Scaling(_e.x,_e.y,_e.z).multiply(Matrix.Translation(et.x,et.y,et.z)).multiply(k.getWorldMatrix()),rt=s.useReverseDepthBuffer;if(this.showBackLines){var it=(e=k._drawWrapperBack)!==null&&e!==void 0?e:this._colorShader._getDrawWrapper();this._colorShader._preBind(it),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),rt?s.setDepthFunctionToLessOrEqual():s.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(it.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateDirectColor4("color",d),this._uniformBufferBack.updateMatrix("world",tt),this._uniformBufferBack.updateMatrix("viewProjection",_),this._uniformBufferBack.update(),s.drawElementsType(Material.LineListDrawMode,0,24)}var nt=(o=k._drawWrapperFront)!==null&&o!==void 0?o:this._colorShader._getDrawWrapper();this._colorShader._preBind(nt),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),rt?s.setDepthFunctionToGreater():s.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(nt.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateDirectColor4("color",c),this._uniformBufferFront.updateMatrix("world",tt),this._uniformBufferFront.updateMatrix("viewProjection",_),this._uniformBufferFront.update(),s.drawElementsType(Material.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(k)}}this._colorShader.unbind(),s.setDepthFunctionToLessOrEqual(),s.setDepthWrite(!0)}},a.prototype._createWrappersForBoundingBox=function(i){if(!i._drawWrapperFront){var e=this.scene.getEngine();i._drawWrapperFront=new DrawWrapper(e),i._drawWrapperBack=new DrawWrapper(e),i._drawWrapperFront.setEffect(this._colorShader.getEffect()),i._drawWrapperBack.setEffect(this._colorShader.getEffect())}},a.prototype.renderOcclusionBoundingBox=function(i){var e=this.scene.getEngine();this._renderPassIdForOcclusionQuery===void 0&&(this._renderPassIdForOcclusionQuery=e.createRenderPassId("Render pass for occlusion query"));var o=e.currentRenderPassId;e.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();var s=i.subMeshes[0];if(!this._colorShaderForOcclusionQuery.isReady(i,void 0,s)||!i.hasBoundingInfo){e.currentRenderPassId=o;return}this._fillIndexBuffer||(this._fillIndexBuffer=e.createIndexBuffer(this._fillIndexData));var c=e.useReverseDepthBuffer;e.setDepthWrite(!1),e.setColorWrite(!1);var d=i.getBoundingInfo().boundingBox,_=d.minimum,b=d.maximum,k=b.subtract(_),j=_.add(k.scale(.5)),$=Matrix.Scaling(k.x,k.y,k.z).multiply(Matrix.Translation(j.x,j.y,j.z)).multiply(d.getWorldMatrix()),_e=s._drawWrapper;this._colorShaderForOcclusionQuery._preBind(_e),e.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,_e.effect),c?e.setDepthFunctionToGreater():e.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(_e.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",$),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),e.drawElementsType(Material.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),e.setDepthFunctionToLessOrEqual(),e.setDepthWrite(!0),e.setColorWrite(!0),e.currentRenderPassId=o},a.prototype.dispose=function(){if(this._renderPassIdForOcclusionQuery!==void 0&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),!!this._colorShader){this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&(i.dispose(),this._vertexBuffers[VertexBuffer.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}},a}(),DataReader=function(){function a(i){this.byteOffset=0,this.buffer=i}return a.prototype.loadAsync=function(i){var e=this;return this.buffer.readAsync(this.byteOffset,i).then(function(o){e._dataView=new DataView(o.buffer,o.byteOffset,o.byteLength),e._dataByteOffset=0})},a.prototype.readUint32=function(){var i=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,i},a.prototype.readUint8Array=function(i){var e=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,i);return this._dataByteOffset+=i,this.byteOffset+=i,e},a.prototype.readString=function(i){return Decode(this.readUint8Array(i))},a.prototype.skipBytes=function(i){this._dataByteOffset+=i,this.byteOffset+=i},a}();function validateAsync(a,i,e,o){var s={externalResourceFunction:function(c){return o(c).then(function(d){return new Uint8Array(d)})}};return e&&(s.uri=i==="file:"?e:i+e),a instanceof ArrayBuffer?GLTFValidator.validateBytes(new Uint8Array(a),s):GLTFValidator.validateString(a,s)}function workerFunc$1(){var a=[];onmessage=function(i){var e=i.data;switch(e.id){case"init":{importScripts(e.url);break}case"validate":{validateAsync(e.data,e.rootUrl,e.fileName,function(o){return new Promise(function(s,c){var d=a.length;a.push({resolve:s,reject:c}),postMessage({id:"getExternalResource",index:d,uri:o})})}).then(function(o){postMessage({id:"validate.resolve",value:o})},function(o){postMessage({id:"validate.reject",reason:o})});break}case"getExternalResource.resolve":{a[e.index].resolve(e.value);break}case"getExternalResource.reject":{a[e.index].reject(e.reason);break}}}}var GLTFValidation=function(){function a(){}return a.ValidateAsync=function(i,e,o,s){var c=this;return typeof Worker=="function"?new Promise(function(d,_){var b=validateAsync+"("+workerFunc$1+")()",k=URL.createObjectURL(new Blob([b],{type:"application/javascript"})),j=new Worker(k),$=function(et){j.removeEventListener("error",$),j.removeEventListener("message",_e),_(et)},_e=function(et){var tt=et.data;switch(tt.id){case"getExternalResource":{s(tt.uri).then(function(rt){j.postMessage({id:"getExternalResource.resolve",index:tt.index,value:rt},[rt])},function(rt){j.postMessage({id:"getExternalResource.reject",index:tt.index,reason:rt})});break}case"validate.resolve":{j.removeEventListener("error",$),j.removeEventListener("message",_e),d(tt.value);break}case"validate.reject":j.removeEventListener("error",$),j.removeEventListener("message",_e),_(tt.reason)}};j.addEventListener("error",$),j.addEventListener("message",_e),j.postMessage({id:"init",url:c.Configuration.url}),j.postMessage({id:"validate",data:i,rootUrl:e,fileName:o})}):(this._LoadScriptPromise||(this._LoadScriptPromise=Tools.LoadScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(function(){return validateAsync(i,e,o,s)}))},a.Configuration={url:"https://preview.babylonjs.com/gltf_validator.js"},a}();function readAsync(a,i,e){try{return Promise.resolve(new Uint8Array(a,i,e))}catch(o){return Promise.reject(o)}}var GLTFLoaderCoordinateSystemMode;(function(a){a[a.AUTO=0]="AUTO",a[a.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})(GLTFLoaderCoordinateSystemMode||(GLTFLoaderCoordinateSystemMode={}));var GLTFLoaderAnimationStartMode;(function(a){a[a.NONE=0]="NONE",a[a.FIRST=1]="FIRST",a[a.ALL=2]="ALL"})(GLTFLoaderAnimationStartMode||(GLTFLoaderAnimationStartMode={}));var GLTFLoaderState;(function(a){a[a.LOADING=0]="LOADING",a[a.READY=1]="READY",a[a.COMPLETE=2]="COMPLETE"})(GLTFLoaderState||(GLTFLoaderState={}));var GLTFFileLoader=function(){function a(){this.onParsedObservable=new Observable,this.coordinateSystemMode=GLTFLoaderCoordinateSystemMode.AUTO,this.animationStartMode=GLTFLoaderAnimationStartMode.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.useSRGBBuffers=!0,this.preprocessUrlAsync=function(i){return Promise.resolve(i)},this.onMeshLoadedObservable=new Observable,this.onTextureLoadedObservable=new Observable,this.onMaterialLoadedObservable=new Observable,this.onCameraLoadedObservable=new Observable,this.onCompleteObservable=new Observable,this.onErrorObservable=new Observable,this.onDisposeObservable=new Observable,this.onExtensionLoadedObservable=new Observable,this.validate=!1,this.onValidatedObservable=new Observable,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new Observable,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}return Object.defineProperty(a.prototype,"onParsed",{set:function(i){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onMeshLoaded",{set:function(i){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onTextureLoaded",{set:function(i){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onMaterialLoaded",{set:function(i){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onCameraLoaded",{set:function(i){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onComplete",{set:function(i){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onError",{set:function(i){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onDispose",{set:function(i){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onExtensionLoaded",{set:function(i){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"loggingEnabled",{get:function(){return this._loggingEnabled},set:function(i){this._loggingEnabled!==i&&(this._loggingEnabled=i,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"capturePerformanceCounters",{get:function(){return this._capturePerformanceCounters},set:function(i){this._capturePerformanceCounters!==i&&(this._capturePerformanceCounters=i,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onValidated",{set:function(i){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(i)},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this._loader&&(this._loader.dispose(),this._loader=null);for(var i=0,e=this._requests;i<e.length;i++){var o=e[i];o.abort()}this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=function(s){return Promise.resolve(s)},this.onMeshLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()},a.prototype.loadFile=function(i,e,o,s,c,d){var _=this;if(this._progressCallback=s,c){if(this.useRangeRequests){this.validate&&Logger$2.Warn("glTF validation is not supported when range requests are enabled");var b={abort:function(){},onCompleteObservable:new Observable},k={readAsync:function(j,$){return new Promise(function(_e,et){_._loadFile(i,e,function(tt){_e(new Uint8Array(tt))},!0,function(tt){et(tt)},function(tt){tt.setRequestHeader("Range","bytes="+j+"-"+(j+$-1))})})},byteLength:0};return this._unpackBinaryAsync(new DataReader(k)).then(function(j){b.onCompleteObservable.notifyObservers(b),o(j)},d?function(j){return d(void 0,j)}:void 0),b}return this._loadFile(i,e,function(j){var $=j;_._unpackBinaryAsync(new DataReader({readAsync:function(_e,et){return readAsync($,_e,et)},byteLength:$.byteLength})).then(function(_e){o(_e)},d?function(_e){return d(void 0,_e)}:void 0)},!0,d)}return this._loadFile(i,e,function(j){if(e.name)_._validate(i,j,"file:",e.name);else{var $=e;_._validate(i,j,Tools.GetFolderPath($),Tools.GetFilename($))}o({json:_._parseJson(j)})},c,d)},a.prototype.importMeshAsync=function(i,e,o,s,c,d){var _=this;return Promise.resolve().then(function(){return _.onParsedObservable.notifyObservers(o),_.onParsedObservable.clear(),_._log("Loading "+(d||"")),_._loader=_._getLoader(o),_._loader.importMeshAsync(i,e,null,o,s,c,d)})},a.prototype.loadAsync=function(i,e,o,s,c){var d=this;return Promise.resolve().then(function(){return d.onParsedObservable.notifyObservers(e),d.onParsedObservable.clear(),d._log("Loading "+(c||"")),d._loader=d._getLoader(e),d._loader.loadAsync(i,e,o,s,c)})},a.prototype.loadAssetContainerAsync=function(i,e,o,s,c){var d=this;return Promise.resolve().then(function(){d.onParsedObservable.notifyObservers(e),d.onParsedObservable.clear(),d._log("Loading "+(c||"")),d._loader=d._getLoader(e);var _=new AssetContainer(i),b=[];d.onMaterialLoadedObservable.add(function($){b.push($)});var k=[];d.onTextureLoadedObservable.add(function($){k.push($)});var j=[];return d.onCameraLoadedObservable.add(function($){j.push($)}),d._loader.importMeshAsync(null,i,_,e,o,s,c).then(function($){return Array.prototype.push.apply(_.geometries,$.geometries),Array.prototype.push.apply(_.meshes,$.meshes),Array.prototype.push.apply(_.particleSystems,$.particleSystems),Array.prototype.push.apply(_.skeletons,$.skeletons),Array.prototype.push.apply(_.animationGroups,$.animationGroups),Array.prototype.push.apply(_.materials,b),Array.prototype.push.apply(_.textures,k),Array.prototype.push.apply(_.lights,$.lights),Array.prototype.push.apply(_.transformNodes,$.transformNodes),Array.prototype.push.apply(_.cameras,j),_})})},a.prototype.canDirectLoad=function(i){return i.indexOf("asset")!==-1&&i.indexOf("version")!==-1||StringTools.StartsWith(i,"data:base64,"+a.magicBase64Encoded)||StringTools.StartsWith(i,"data:;base64,"+a.magicBase64Encoded)||StringTools.StartsWith(i,"data:application/octet-stream;base64,"+a.magicBase64Encoded)||StringTools.StartsWith(i,"data:model/gltf-binary;base64,"+a.magicBase64Encoded)},a.prototype.directLoad=function(i,e){if(StringTools.StartsWith(e,"base64,"+a.magicBase64Encoded)||StringTools.StartsWith(e,";base64,"+a.magicBase64Encoded)||StringTools.StartsWith(e,"application/octet-stream;base64,"+a.magicBase64Encoded)||StringTools.StartsWith(e,"model/gltf-binary;base64,"+a.magicBase64Encoded)){var o=DecodeBase64UrlToBinary(e);return this._validate(i,o),this._unpackBinaryAsync(new DataReader({readAsync:function(s,c){return readAsync(o,s,c)},byteLength:o.byteLength}))}return this._validate(i,e),Promise.resolve({json:this._parseJson(e)})},a.prototype.createPlugin=function(){return new a},Object.defineProperty(a.prototype,"loaderState",{get:function(){return this._state},enumerable:!1,configurable:!0}),a.prototype.whenCompleteAsync=function(){var i=this;return new Promise(function(e,o){i.onCompleteObservable.addOnce(function(){e()}),i.onErrorObservable.addOnce(function(s){o(s)})})},a.prototype._setState=function(i){this._state!==i&&(this._state=i,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(GLTFLoaderState[this._state]))},a.prototype._loadFile=function(i,e,o,s,c,d){var _=this,b=i._loadFile(e,o,function(k){_._onProgress(k,b)},!0,s,c,d);return b.onCompleteObservable.add(function(k){_._requests.splice(_._requests.indexOf(k),1)}),this._requests.push(b),b},a.prototype._onProgress=function(i,e){if(!!this._progressCallback){e._lengthComputable=i.lengthComputable,e._loaded=i.loaded,e._total=i.total;for(var o=!0,s=0,c=0,d=0,_=this._requests;d<_.length;d++){var b=_[d];if(b._lengthComputable===void 0||b._loaded===void 0||b._total===void 0)return;o=o&&b._lengthComputable,s+=b._loaded,c+=b._total}this._progressCallback({lengthComputable:o,loaded:s,total:o?c:0})}},a.prototype._validate=function(i,e,o,s){var c=this;o===void 0&&(o=""),s===void 0&&(s=""),this.validate&&(this._startPerformanceCounter("Validate JSON"),GLTFValidation.ValidateAsync(e,o,s,function(d){return c.preprocessUrlAsync(o+d).then(function(_){return i._loadFileAsync(_,void 0,!0,!0)})}).then(function(d){c._endPerformanceCounter("Validate JSON"),c.onValidatedObservable.notifyObservers(d),c.onValidatedObservable.clear()},function(d){c._endPerformanceCounter("Validate JSON"),Tools.Warn("Failed to validate: "+d.message),c.onValidatedObservable.clear()}))},a.prototype._getLoader=function(i){var e=i.json.asset||{};this._log("Asset version: "+e.version),e.minVersion&&this._log("Asset minimum version: "+e.minVersion),e.generator&&this._log("Asset generator: "+e.generator);var o=a._parseVersion(e.version);if(!o)throw new Error("Invalid version: "+e.version);if(e.minVersion!==void 0){var s=a._parseVersion(e.minVersion);if(!s)throw new Error("Invalid minimum version: "+e.minVersion);if(a._compareVersion(s,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+e.minVersion)}var c={1:a._CreateGLTF1Loader,2:a._CreateGLTF2Loader},d=c[o.major];if(!d)throw new Error("Unsupported version: "+e.version);return d(this)},a.prototype._parseJson=function(i){this._startPerformanceCounter("Parse JSON"),this._log("JSON length: "+i.length);var e=JSON.parse(i);return this._endPerformanceCounter("Parse JSON"),e},a.prototype._unpackBinaryAsync=function(i){var e=this;return this._startPerformanceCounter("Unpack Binary"),i.loadAsync(20).then(function(){var o={Magic:1179937895},s=i.readUint32();if(s!==o.Magic)throw new Error("Unexpected magic: "+s);var c=i.readUint32();e.loggingEnabled&&e._log("Binary version: "+c);var d=i.readUint32();if(i.buffer.byteLength!==0&&d!==i.buffer.byteLength)throw new Error("Length in header does not match actual data length: "+d+" != "+i.buffer.byteLength);var _;switch(c){case 1:{_=e._unpackBinaryV1Async(i,d);break}case 2:{_=e._unpackBinaryV2Async(i,d);break}default:throw new Error("Unsupported version: "+c)}return e._endPerformanceCounter("Unpack Binary"),_})},a.prototype._unpackBinaryV1Async=function(i,e){var o={JSON:0},s=i.readUint32(),c=i.readUint32();if(c!==o.JSON)throw new Error("Unexpected content format: "+c);var d=e-i.byteOffset,_={json:this._parseJson(i.readString(s)),bin:null};if(d!==0){var b=i.byteOffset;_.bin={readAsync:function(k,j){return i.buffer.readAsync(b+k,j)},byteLength:d}}return Promise.resolve(_)},a.prototype._unpackBinaryV2Async=function(i,e){var o=this,s={JSON:1313821514,BIN:5130562},c=i.readUint32(),d=i.readUint32();if(d!==s.JSON)throw new Error("First chunk format is not JSON");return i.byteOffset+c===e?i.loadAsync(c).then(function(){return{json:o._parseJson(i.readString(c)),bin:null}}):i.loadAsync(c+8).then(function(){var _={json:o._parseJson(i.readString(c)),bin:null},b=function(){var k=i.readUint32(),j=i.readUint32();switch(j){case s.JSON:throw new Error("Unexpected JSON chunk");case s.BIN:{var $=i.byteOffset;_.bin={readAsync:function(_e,et){return i.buffer.readAsync($+_e,et)},byteLength:k},i.skipBytes(k);break}default:{i.skipBytes(k);break}}return i.byteOffset!==e?i.loadAsync(8).then(b):Promise.resolve(_)};return b()})},a._parseVersion=function(i){if(i==="1.0"||i==="1.0.1")return{major:1,minor:0};var e=(i+"").match(/^(\d+)\.(\d+)/);return e?{major:parseInt(e[1]),minor:parseInt(e[2])}:null},a._compareVersion=function(i,e){return i.major>e.major?1:i.major<e.major?-1:i.minor>e.minor?1:i.minor<e.minor?-1:0},a.prototype._logOpen=function(i){this._log(i),this._logIndentLevel++},a.prototype._logClose=function(){--this._logIndentLevel},a.prototype._logEnabled=function(i){var e=a._logSpaces.substr(0,this._logIndentLevel*2);Logger$2.Log(""+e+i)},a.prototype._logDisabled=function(i){},a.prototype._startPerformanceCounterEnabled=function(i){Tools.StartPerformanceCounter(i)},a.prototype._startPerformanceCounterDisabled=function(i){},a.prototype._endPerformanceCounterEnabled=function(i){Tools.EndPerformanceCounter(i)},a.prototype._endPerformanceCounterDisabled=function(i){},a.IncrementalLoading=!0,a.HomogeneousCoordinates=!1,a.magicBase64Encoded="Z2xURg",a._logSpaces=" ",a}();SceneLoader&&SceneLoader.RegisterPlugin(new GLTFFileLoader);var EComponentType;(function(a){a[a.BYTE=5120]="BYTE",a[a.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",a[a.SHORT=5122]="SHORT",a[a.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",a[a.FLOAT=5126]="FLOAT"})(EComponentType||(EComponentType={}));var EShaderType;(function(a){a[a.FRAGMENT=35632]="FRAGMENT",a[a.VERTEX=35633]="VERTEX"})(EShaderType||(EShaderType={}));var EParameterType;(function(a){a[a.BYTE=5120]="BYTE",a[a.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",a[a.SHORT=5122]="SHORT",a[a.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",a[a.INT=5124]="INT",a[a.UNSIGNED_INT=5125]="UNSIGNED_INT",a[a.FLOAT=5126]="FLOAT",a[a.FLOAT_VEC2=35664]="FLOAT_VEC2",a[a.FLOAT_VEC3=35665]="FLOAT_VEC3",a[a.FLOAT_VEC4=35666]="FLOAT_VEC4",a[a.INT_VEC2=35667]="INT_VEC2",a[a.INT_VEC3=35668]="INT_VEC3",a[a.INT_VEC4=35669]="INT_VEC4",a[a.BOOL=35670]="BOOL",a[a.BOOL_VEC2=35671]="BOOL_VEC2",a[a.BOOL_VEC3=35672]="BOOL_VEC3",a[a.BOOL_VEC4=35673]="BOOL_VEC4",a[a.FLOAT_MAT2=35674]="FLOAT_MAT2",a[a.FLOAT_MAT3=35675]="FLOAT_MAT3",a[a.FLOAT_MAT4=35676]="FLOAT_MAT4",a[a.SAMPLER_2D=35678]="SAMPLER_2D"})(EParameterType||(EParameterType={}));var ETextureWrapMode;(function(a){a[a.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",a[a.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",a[a.REPEAT=10497]="REPEAT"})(ETextureWrapMode||(ETextureWrapMode={}));var ETextureFilterType;(function(a){a[a.NEAREST=9728]="NEAREST",a[a.LINEAR=9728]="LINEAR",a[a.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",a[a.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",a[a.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",a[a.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"})(ETextureFilterType||(ETextureFilterType={}));var ETextureFormat;(function(a){a[a.ALPHA=6406]="ALPHA",a[a.RGB=6407]="RGB",a[a.RGBA=6408]="RGBA",a[a.LUMINANCE=6409]="LUMINANCE",a[a.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"})(ETextureFormat||(ETextureFormat={}));var ECullingType;(function(a){a[a.FRONT=1028]="FRONT",a[a.BACK=1029]="BACK",a[a.FRONT_AND_BACK=1032]="FRONT_AND_BACK"})(ECullingType||(ECullingType={}));var EBlendingFunction;(function(a){a[a.ZERO=0]="ZERO",a[a.ONE=1]="ONE",a[a.SRC_COLOR=768]="SRC_COLOR",a[a.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",a[a.DST_COLOR=774]="DST_COLOR",a[a.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",a[a.SRC_ALPHA=770]="SRC_ALPHA",a[a.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",a[a.DST_ALPHA=772]="DST_ALPHA",a[a.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",a[a.CONSTANT_COLOR=32769]="CONSTANT_COLOR",a[a.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",a[a.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",a[a.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",a[a.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"})(EBlendingFunction||(EBlendingFunction={}));var GLTFUtils=function(){function a(){}return a.SetMatrix=function(i,e,o,s,c){var d=null;if(o.semantic==="MODEL")d=e.getWorldMatrix();else if(o.semantic==="PROJECTION")d=i.getProjectionMatrix();else if(o.semantic==="VIEW")d=i.getViewMatrix();else if(o.semantic==="MODELVIEWINVERSETRANSPOSE")d=Matrix.Transpose(e.getWorldMatrix().multiply(i.getViewMatrix()).invert());else if(o.semantic==="MODELVIEW")d=e.getWorldMatrix().multiply(i.getViewMatrix());else if(o.semantic==="MODELVIEWPROJECTION")d=e.getWorldMatrix().multiply(i.getTransformMatrix());else if(o.semantic==="MODELINVERSE")d=e.getWorldMatrix().invert();else if(o.semantic==="VIEWINVERSE")d=i.getViewMatrix().invert();else if(o.semantic==="PROJECTIONINVERSE")d=i.getProjectionMatrix().invert();else if(o.semantic==="MODELVIEWINVERSE")d=e.getWorldMatrix().multiply(i.getViewMatrix()).invert();else if(o.semantic==="MODELVIEWPROJECTIONINVERSE")d=e.getWorldMatrix().multiply(i.getTransformMatrix()).invert();else if(o.semantic==="MODELINVERSETRANSPOSE")d=Matrix.Transpose(e.getWorldMatrix().invert());else debugger;if(d)switch(o.type){case EParameterType.FLOAT_MAT2:c.setMatrix2x2(s,Matrix.GetAsMatrix2x2(d));break;case EParameterType.FLOAT_MAT3:c.setMatrix3x3(s,Matrix.GetAsMatrix3x3(d));break;case EParameterType.FLOAT_MAT4:c.setMatrix(s,d);break}},a.SetUniform=function(i,e,o,s){switch(s){case EParameterType.FLOAT:return i.setFloat(e,o),!0;case EParameterType.FLOAT_VEC2:return i.setVector2(e,Vector2.FromArray(o)),!0;case EParameterType.FLOAT_VEC3:return i.setVector3(e,Vector3.FromArray(o)),!0;case EParameterType.FLOAT_VEC4:return i.setVector4(e,Vector4.FromArray(o)),!0;default:return!1}},a.GetWrapMode=function(i){switch(i){case ETextureWrapMode.CLAMP_TO_EDGE:return Texture.CLAMP_ADDRESSMODE;case ETextureWrapMode.MIRRORED_REPEAT:return Texture.MIRROR_ADDRESSMODE;case ETextureWrapMode.REPEAT:return Texture.WRAP_ADDRESSMODE;default:return Texture.WRAP_ADDRESSMODE}},a.GetByteStrideFromType=function(i){var e=i.type;switch(e){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}},a.GetTextureFilterMode=function(i){switch(i){case ETextureFilterType.LINEAR:case ETextureFilterType.LINEAR_MIPMAP_NEAREST:case ETextureFilterType.LINEAR_MIPMAP_LINEAR:return Texture.TRILINEAR_SAMPLINGMODE;case ETextureFilterType.NEAREST:case ETextureFilterType.NEAREST_MIPMAP_NEAREST:return Texture.NEAREST_SAMPLINGMODE;default:return Texture.BILINEAR_SAMPLINGMODE}},a.GetBufferFromBufferView=function(i,e,d,s,c){var d=e.byteOffset+d,_=i.loadedBufferViews[e.buffer];if(d+s>_.byteLength)throw new Error("Buffer access is out of range");var b=_.buffer;switch(d+=_.byteOffset,c){case EComponentType.BYTE:return new Int8Array(b,d,s);case EComponentType.UNSIGNED_BYTE:return new Uint8Array(b,d,s);case EComponentType.SHORT:return new Int16Array(b,d,s);case EComponentType.UNSIGNED_SHORT:return new Uint16Array(b,d,s);default:return new Float32Array(b,d,s)}},a.GetBufferFromAccessor=function(i,e){var o=i.bufferViews[e.bufferView],s=e.count*a.GetByteStrideFromType(e);return a.GetBufferFromBufferView(i,o,e.byteOffset,s,e.componentType)},a.DecodeBufferToText=function(i){for(var e="",o=i.byteLength,s=0;s<o;++s)e+=String.fromCharCode(i[s]);return e},a.GetDefaultMaterial=function(i){if(!a._DefaultMaterial){Effect$1.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{"," gl_Position = projection * worldView * vec4(position, 1.0);","}"].join(`
  10261. `),Effect$1.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join(`
  10262. `);var e={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},o={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};a._DefaultMaterial=new ShaderMaterial("GLTFDefaultMaterial",i,e,o),a._DefaultMaterial.setColor4("u_emission",new Color4(.5,.5,.5,1))}return a._DefaultMaterial},a._DefaultMaterial=null,a}(),ETokenType;(function(a){a[a.IDENTIFIER=1]="IDENTIFIER",a[a.UNKNOWN=2]="UNKNOWN",a[a.END_OF_INPUT=3]="END_OF_INPUT"})(ETokenType||(ETokenType={}));var Tokenizer=function(){function a(i){this._pos=0,this.currentToken=ETokenType.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=i,this._maxPos=i.length}return a.prototype.getNextToken=function(){if(this.isEnd())return ETokenType.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=ETokenType.UNKNOWN,this.currentString==="_"||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=ETokenType.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||this.currentString==="_");)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken},a.prototype.peek=function(){return this._toParse[this._pos]},a.prototype.read=function(){return this._toParse[this._pos++]},a.prototype.forward=function(){this._pos++},a.prototype.isEnd=function(){return this._pos>=this._maxPos},a}(),glTFTransforms=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],babylonTransforms=["world","view","projection","worldView","worldViewProjection","mBones"],glTFAnimationPaths=["translation","rotation","scale"],babylonAnimationPaths=["position","rotationQuaternion","scaling"],parseBuffers=function(a,i){for(var e in a){var o=a[e];i.buffers[e]=o,i.buffersCount++}},parseShaders=function(a,i){for(var e in a){var o=a[e];i.shaders[e]=o,i.shaderscount++}},parseObject=function(a,i,e){for(var o in a){var s=a[o];e[i][o]=s}},normalizeUVs=function(a){if(!!a)for(var i=0;i<a.length/2;i++)a[i*2+1]=1-a[i*2+1]},getAttribute=function(a){if(a.semantic==="NORMAL")return"normal";if(a.semantic==="POSITION")return"position";if(a.semantic==="JOINT")return"matricesIndices";if(a.semantic==="WEIGHT")return"matricesWeights";if(a.semantic==="COLOR")return"color";if(a.semantic&&a.semantic.indexOf("TEXCOORD_")!==-1){var i=Number(a.semantic.split("_")[1]);return"uv"+(i===0?"":i+1)}return null},loadAnimations=function(a){for(var i in a.animations){var e=a.animations[i];if(!(!e.channels||!e.samplers))for(var o=null,s=0;s<e.channels.length;s++){var c=e.channels[s],d=e.samplers[c.sampler];if(!!d){var _=null,b=null;e.parameters?(_=e.parameters[d.input],b=e.parameters[d.output]):(_=d.input,b=d.output);var k=GLTFUtils.GetBufferFromAccessor(a,a.accessors[_]),j=GLTFUtils.GetBufferFromAccessor(a,a.accessors[b]),$=c.target.id,_e=a.scene.getNodeById($);if(_e===null&&(_e=a.scene.getNodeByName($)),_e===null){Tools.Warn("Creating animation named "+i+". But cannot find node named "+$+" to attach to");continue}var et=_e instanceof Bone,tt=c.target.path,rt=glTFAnimationPaths.indexOf(tt);rt!==-1&&(tt=babylonAnimationPaths[rt]);var it=Animation.ANIMATIONTYPE_MATRIX;et||(tt==="rotationQuaternion"?(it=Animation.ANIMATIONTYPE_QUATERNION,_e.rotationQuaternion=new Quaternion):it=Animation.ANIMATIONTYPE_VECTOR3);var nt=null,ot=[],at=0,st=!1;et&&o&&o.getKeys().length===k.length&&(nt=o,st=!0),st||(a.scene._blockEntityCollection=!!a.assetContainer,nt=new Animation(i,et?"_matrix":tt,1,it,Animation.ANIMATIONLOOPMODE_CYCLE),a.scene._blockEntityCollection=!1);for(var ut=0;ut<k.length;ut++){var ft=null;if(tt==="rotationQuaternion"?(ft=Quaternion.FromArray([j[at],j[at+1],j[at+2],j[at+3]]),at+=4):(ft=Vector3.FromArray([j[at],j[at+1],j[at+2]]),at+=3),et){var lt=_e,ht=Vector3.Zero(),pt=new Quaternion,mt=Vector3.Zero(),dt=lt.getBaseMatrix();st&&o&&(dt=o.getKeys()[ut].value),dt.decompose(mt,pt,ht),tt==="position"?ht=ft:tt==="rotationQuaternion"?pt=ft:mt=ft,ft=Matrix.Compose(mt,pt,ht)}st?o&&(o.getKeys()[ut].value=ft):ot.push({frame:k[ut],value:ft})}!st&&nt&&(nt.setKeys(ot),_e.animations.push(nt)),o=nt,a.scene.stopAnimation(_e),a.scene.beginAnimation(_e,0,k[k.length-1],!0,1)}}}},configureBoneTransformation=function(a){var i=null;if(a.translation||a.rotation||a.scale){var e=Vector3.FromArray(a.scale||[1,1,1]),o=Quaternion.FromArray(a.rotation||[0,0,0,1]),s=Vector3.FromArray(a.translation||[0,0,0]);i=Matrix.Compose(e,o,s)}else i=Matrix.FromArray(a.matrix);return i},getParentBone=function(a,i,e,o){for(var s=0;s<o.bones.length;s++)if(o.bones[s].name===e)return o.bones[s];var c=a.nodes;for(var d in c){var _=c[d];if(!!_.jointName)for(var b=_.children,s=0;s<b.length;s++){var k=a.nodes[b[s]];if(!!k.jointName&&k.jointName===e){var j=configureBoneTransformation(_),$=new Bone(_.name||"",o,getParentBone(a,i,_.jointName,o),j);return $.id=d,$}}}return null},getNodeToRoot=function(a,i){for(var e=0;e<a.length;e++)for(var o=a[e],s=0;s<o.node.children.length;s++){var c=o.node.children[s];if(c===i)return o.bone}return null},getJointNode=function(a,i){var e=a.nodes,o=e[i];if(o)return{node:o,id:i};for(var s in e)if(o=e[s],o.jointName===i)return{node:o,id:s};return null},nodeIsInJoints=function(a,i){for(var e=0;e<a.jointNames.length;e++)if(a.jointNames[e]===i)return!0;return!1},getNodesToRoot=function(a,i,e,o){for(var s in a.nodes){var c=a.nodes[s],d=s;if(!(!c.jointName||nodeIsInJoints(e,c.jointName))){var _=configureBoneTransformation(c),b=new Bone(c.name||"",i,null,_);b.id=d,o.push({bone:b,node:c,id:d})}}for(var k=0;k<o.length;k++)for(var j=o[k],$=j.node.children,_e=0;_e<$.length;_e++){for(var et=null,tt=0;tt<o.length;tt++)if(o[tt].id===$[_e]){et=o[tt];break}et&&(et.bone._parent=j.bone,j.bone.children.push(et.bone))}},importSkeleton=function(a,i,e,o,s){if(o||(o=new Skeleton(i.name||"","",a.scene)),!i.babylonSkeleton)return o;var c=[],d=[];getNodesToRoot(a,o,i,c),o.bones=[];for(var _=0;_<i.jointNames.length;_++){var b=getJointNode(a,i.jointNames[_]);if(!!b){var k=b.node;if(!k){Tools.Warn("Joint named "+i.jointNames[_]+" does not exist");continue}var s=b.id,j=a.scene.getBoneById(s);if(j){o.bones.push(j);continue}for(var $=!1,_e=null,et=0;et<_;et++){var tt=getJointNode(a,i.jointNames[et]);if(!!tt){var rt=tt.node;if(!rt){Tools.Warn("Joint named "+i.jointNames[et]+" does not exist when looking for parent");continue}var it=rt.children;if(!!it){$=!1;for(var nt=0;nt<it.length;nt++)if(it[nt]===s){_e=getParentBone(a,i,i.jointNames[et],o),$=!0;break}if($)break}}}var ot=configureBoneTransformation(k);!_e&&c.length>0&&(_e=getNodeToRoot(c,s),_e&&d.indexOf(_e)===-1&&d.push(_e));var at=new Bone(k.jointName||"",o,_e,ot);at.id=s}}var st=o.bones;o.bones=[];for(var _=0;_<i.jointNames.length;_++){var b=getJointNode(a,i.jointNames[_]);if(!!b){for(var et=0;et<st.length;et++)if(st[et].id===b.id){o.bones.push(st[et]);break}}}o.prepare();for(var _=0;_<d.length;_++)o.bones.push(d[_]);return o},importMesh=function(a,i,e,o,s){if(s||(a.scene._blockEntityCollection=!!a.assetContainer,s=new Mesh(i.name||"",a.scene),s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,s.id=o),!i.babylonNode)return s;for(var c=[],d=null,_=new Array,b=new Array,k=new Array,j=new Array,$=0;$<e.length;$++){var _e=e[$],et=a.meshes[_e];if(!!et)for(var tt=0;tt<et.primitives.length;tt++){var rt=new VertexData,it=et.primitives[tt];it.mode;var nt=it.attributes,ot=null,at=null;for(var st in nt)if(ot=a.accessors[nt[st]],at=GLTFUtils.GetBufferFromAccessor(a,ot),st==="NORMAL")rt.normals=new Float32Array(at.length),rt.normals.set(at);else if(st==="POSITION"){if(GLTFFileLoader.HomogeneousCoordinates){rt.positions=new Float32Array(at.length-at.length/4);for(var ut=0;ut<at.length;ut+=4)rt.positions[ut]=at[ut],rt.positions[ut+1]=at[ut+1],rt.positions[ut+2]=at[ut+2]}else rt.positions=new Float32Array(at.length),rt.positions.set(at);b.push(rt.positions.length)}else if(st.indexOf("TEXCOORD_")!==-1){var ft=Number(st.split("_")[1]),lt=VertexBuffer.UVKind+(ft===0?"":ft+1),ht=new Float32Array(at.length);ht.set(at),normalizeUVs(ht),rt.set(ht,lt)}else st==="JOINT"?(rt.matricesIndices=new Float32Array(at.length),rt.matricesIndices.set(at)):st==="WEIGHT"?(rt.matricesWeights=new Float32Array(at.length),rt.matricesWeights.set(at)):st==="COLOR"&&(rt.colors=new Float32Array(at.length),rt.colors.set(at));if(ot=a.accessors[it.indices],ot)at=GLTFUtils.GetBufferFromAccessor(a,ot),rt.indices=new Int32Array(at.length),rt.indices.set(at),j.push(rt.indices.length);else{for(var pt=[],ut=0;ut<rt.positions.length/3;ut++)pt.push(ut);rt.indices=new Int32Array(pt),j.push(rt.indices.length)}d?d.merge(rt):d=rt;var mt=a.scene.getMaterialById(it.material);c.push(mt===null?GLTFUtils.GetDefaultMaterial(a.scene):mt),_.push(_.length===0?0:_[_.length-1]+b[b.length-2]),k.push(k.length===0?0:k[k.length-1]+j[j.length-2])}}var dt;a.scene._blockEntityCollection=!!a.assetContainer,c.length>1?(dt=new MultiMaterial("multimat"+o,a.scene),dt.subMaterials=c):dt=new StandardMaterial("multimat"+o,a.scene),c.length===1&&(dt=c[0]),dt._parentContainer=a.assetContainer,s.material||(s.material=dt),new Geometry(o,a.scene,d,!1,s),s.computeWorldMatrix(!0),a.scene._blockEntityCollection=!1,s.subMeshes=[];for(var gt=0,$=0;$<e.length;$++){var _e=e[$],et=a.meshes[_e];if(!!et)for(var tt=0;tt<et.primitives.length;tt++)et.primitives[tt].mode,SubMesh.AddToMesh(gt,_[gt],b[gt],k[gt],j[gt],s,s,!0),gt++}return s},configureNode=function(a,i,e,o){a.position&&(a.position=i),(a.rotationQuaternion||a.rotation)&&(a.rotationQuaternion=e),a.scaling&&(a.scaling=o)},configureNodeFromMatrix=function(a,i,e){if(i.matrix){var o=new Vector3(0,0,0),s=new Quaternion,c=new Vector3(0,0,0),d=Matrix.FromArray(i.matrix);d.decompose(c,s,o),configureNode(a,o,s,c)}else i.translation&&i.rotation&&i.scale&&configureNode(a,Vector3.FromArray(i.translation),Quaternion.FromArray(i.rotation),Vector3.FromArray(i.scale));a.computeWorldMatrix(!0)},importNode$1=function(a,i,e,o){var s=null;if(a.importOnlyMeshes&&(i.skin||i.meshes)&&a.importMeshesNames&&a.importMeshesNames.length>0&&a.importMeshesNames.indexOf(i.name||"")===-1)return null;if(i.skin){if(i.meshes){var c=a.skins[i.skin],d=importMesh(a,i,i.meshes,e,i.babylonNode);d.skeleton=a.scene.getLastSkeletonById(i.skin),d.skeleton===null&&(d.skeleton=importSkeleton(a,c,d,c.babylonSkeleton,i.skin),c.babylonSkeleton||(c.babylonSkeleton=d.skeleton)),s=d}}else if(i.meshes){var d=importMesh(a,i,i.mesh?[i.mesh]:i.meshes,e,i.babylonNode);s=d}else if(i.light&&!i.babylonNode&&!a.importOnlyMeshes){var _=a.lights[i.light];if(_){if(_.type==="ambient"){var b=_[_.type],k=new HemisphericLight(i.light,Vector3.Zero(),a.scene);k.name=i.name||"",b.color&&(k.diffuse=Color3.FromArray(b.color)),s=k}else if(_.type==="directional"){var j=_[_.type],$=new DirectionalLight(i.light,Vector3.Zero(),a.scene);$.name=i.name||"",j.color&&($.diffuse=Color3.FromArray(j.color)),s=$}else if(_.type==="point"){var _e=_[_.type],et=new PointLight(i.light,Vector3.Zero(),a.scene);et.name=i.name||"",_e.color&&(et.diffuse=Color3.FromArray(_e.color)),s=et}else if(_.type==="spot"){var tt=_[_.type],rt=new SpotLight(i.light,Vector3.Zero(),Vector3.Zero(),0,0,a.scene);rt.name=i.name||"",tt.color&&(rt.diffuse=Color3.FromArray(tt.color)),tt.fallOfAngle&&(rt.angle=tt.fallOfAngle),tt.fallOffExponent&&(rt.exponent=tt.fallOffExponent),s=rt}}}else if(i.camera&&!i.babylonNode&&!a.importOnlyMeshes){var it=a.cameras[i.camera];if(it){if(a.scene._blockEntityCollection=!!a.assetContainer,it.type==="orthographic"){var nt=new FreeCamera(i.camera,Vector3.Zero(),a.scene,!1);nt.name=i.name||"",nt.mode=Camera$1.ORTHOGRAPHIC_CAMERA,nt.attachControl(),s=nt,nt._parentContainer=a.assetContainer}else if(it.type==="perspective"){var ot=it[it.type],at=new FreeCamera(i.camera,Vector3.Zero(),a.scene,!1);at.name=i.name||"",at.attachControl(),ot.aspectRatio||(ot.aspectRatio=a.scene.getEngine().getRenderWidth()/a.scene.getEngine().getRenderHeight()),ot.znear&&ot.zfar&&(at.maxZ=ot.zfar,at.minZ=ot.znear),s=at,at._parentContainer=a.assetContainer}a.scene._blockEntityCollection=!1}}if(!i.jointName){if(i.babylonNode)return i.babylonNode;if(s===null){a.scene._blockEntityCollection=!!a.assetContainer;var st=new Mesh(i.name||"",a.scene);st._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,i.babylonNode=st,s=st}}if(s!==null){if(i.matrix&&s instanceof Mesh)configureNodeFromMatrix(s,i);else{var ut=i.translation||[0,0,0],ft=i.rotation||[0,0,0,1],lt=i.scale||[1,1,1];configureNode(s,Vector3.FromArray(ut),Quaternion.FromArray(ft),Vector3.FromArray(lt))}s.updateCache(!0),i.babylonNode=s}return s},traverseNodes=function(a,i,e,o){o===void 0&&(o=!1);var s=a.nodes[i],c=null;if(a.importOnlyMeshes&&!o&&a.importMeshesNames?a.importMeshesNames.indexOf(s.name||"")!==-1||a.importMeshesNames.length===0?o=!0:o=!1:o=!0,!s.jointName&&o&&(c=importNode$1(a,s,i),c!==null&&(c.id=i,c.parent=e)),s.children)for(var d=0;d<s.children.length;d++)traverseNodes(a,s.children[d],c,o)},postLoad=function(a){var i=a.currentScene;if(i)for(var e=0;e<i.nodes.length;e++)traverseNodes(a,i.nodes[e],null);else for(var o in a.scenes){i=a.scenes[o];for(var e=0;e<i.nodes.length;e++)traverseNodes(a,i.nodes[e],null)}loadAnimations(a);for(var e=0;e<a.scene.skeletons.length;e++){var s=a.scene.skeletons[e];a.scene.beginAnimation(s,0,Number.MAX_VALUE,!0,1)}},onBindShaderMaterial=function(a,i,e,o,s,c,d){var _=c.values||s.parameters;for(var b in e){var k=e[b],j=k.type;if(j===EParameterType.FLOAT_MAT2||j===EParameterType.FLOAT_MAT3||j===EParameterType.FLOAT_MAT4){if(k.semantic&&!k.source&&!k.node)GLTFUtils.SetMatrix(i.scene,a,k,b,o.getEffect());else if(k.semantic&&(k.source||k.node)){var $=i.scene.getNodeByName(k.source||k.node||"");if($===null&&($=i.scene.getNodeById(k.source||k.node||"")),$===null)continue;GLTFUtils.SetMatrix(i.scene,$,k,b,o.getEffect())}}else{var _e=_[s.uniforms[b]];if(!_e)continue;if(j===EParameterType.SAMPLER_2D){var et=i.textures[c.values?_e:k.value].babylonTexture;if(et==null)continue;o.getEffect().setTexture(b,et)}else GLTFUtils.SetUniform(o.getEffect(),b,_e,j)}}d(o)},prepareShaderMaterialUniforms=function(a,i,e,o,s){var c=o.values||e.parameters,d=e.uniforms;for(var _ in s){var b=s[_],k=b.type,j=c[d[_]];if(j===void 0&&(j=b.value),!!j){var $=function(_e){return function(et){b.value&&_e&&(i.setTexture(_e,et),delete s[_e])}};k===EParameterType.SAMPLER_2D?GLTFLoaderExtension.LoadTextureAsync(a,o.values?j:b.value,$(_),function(){return $(null)}):b.value&&GLTFUtils.SetUniform(i,_,o.values?j:b.value,k)&&delete s[_]}}},onShaderCompileError=function(a,i,e){return function(o,s){i.dispose(!0),e("Cannot compile program named "+a.name+". Error: "+s+". Default material will be applied")}},onShaderCompileSuccess=function(a,i,e,o,s,c){return function(d){prepareShaderMaterialUniforms(a,i,e,o,s),i.onBind=function(_){onBindShaderMaterial(_,a,s,i,e,o,c)}}},parseShaderUniforms=function(a,i,e){for(var o in i.uniforms){var s=i.uniforms[o],c=i.parameters[s];if(a.currentIdentifier===o&&c.semantic&&!c.source&&!c.node){var d=glTFTransforms.indexOf(c.semantic);if(d!==-1)return delete e[o],babylonTransforms[d]}}return a.currentIdentifier},importMaterials=function(a){for(var i in a.materials)GLTFLoaderExtension.LoadMaterialAsync(a,i,function(e){},function(){})},GLTFLoaderBase=function(){function a(){}return a.CreateRuntime=function(i,e,o){var s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:e,rootUrl:o,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return i.extensions&&parseObject(i.extensions,"extensions",s),i.extensionsUsed&&parseObject(i.extensionsUsed,"extensionsUsed",s),i.buffers&&parseBuffers(i.buffers,s),i.bufferViews&&parseObject(i.bufferViews,"bufferViews",s),i.accessors&&parseObject(i.accessors,"accessors",s),i.meshes&&parseObject(i.meshes,"meshes",s),i.lights&&parseObject(i.lights,"lights",s),i.cameras&&parseObject(i.cameras,"cameras",s),i.nodes&&parseObject(i.nodes,"nodes",s),i.images&&parseObject(i.images,"images",s),i.textures&&parseObject(i.textures,"textures",s),i.shaders&&parseShaders(i.shaders,s),i.programs&&parseObject(i.programs,"programs",s),i.samplers&&parseObject(i.samplers,"samplers",s),i.techniques&&parseObject(i.techniques,"techniques",s),i.materials&&parseObject(i.materials,"materials",s),i.animations&&parseObject(i.animations,"animations",s),i.skins&&parseObject(i.skins,"skins",s),i.scenes&&(s.scenes=i.scenes),i.scene&&i.scenes&&(s.currentScene=i.scenes[i.scene]),s},a.LoadBufferAsync=function(i,e,o,s,c){var d=i.buffers[e];Tools.IsBase64(d.uri)?setTimeout(function(){return o(new Uint8Array(Tools.DecodeBase64(d.uri)))}):Tools.LoadFile(i.rootUrl+d.uri,function(_){return o(new Uint8Array(_))},c,void 0,!0,function(_){_&&s(_.status+" "+_.statusText)})},a.LoadTextureBufferAsync=function(i,e,o,s){var c=i.textures[e];if(!c||!c.source){s("");return}if(c.babylonTexture){o(null);return}var d=i.images[c.source];Tools.IsBase64(d.uri)?setTimeout(function(){return o(new Uint8Array(Tools.DecodeBase64(d.uri)))}):Tools.LoadFile(i.rootUrl+d.uri,function(_){return o(new Uint8Array(_))},void 0,void 0,!0,function(_){_&&s(_.status+" "+_.statusText)})},a.CreateTextureAsync=function(i,e,o,s,c){var d=i.textures[e];if(d.babylonTexture){s(d.babylonTexture);return}var _=i.samplers[d.sampler],b=_.minFilter===ETextureFilterType.NEAREST_MIPMAP_NEAREST||_.minFilter===ETextureFilterType.NEAREST_MIPMAP_LINEAR||_.minFilter===ETextureFilterType.LINEAR_MIPMAP_NEAREST||_.minFilter===ETextureFilterType.LINEAR_MIPMAP_LINEAR,k=Texture.BILINEAR_SAMPLINGMODE,j=o==null?new Blob:new Blob([o]),$=URL.createObjectURL(j),_e=function(){return URL.revokeObjectURL($)},et=new Texture($,i.scene,!b,!0,k,_e,_e);_.wrapS!==void 0&&(et.wrapU=GLTFUtils.GetWrapMode(_.wrapS)),_.wrapT!==void 0&&(et.wrapV=GLTFUtils.GetWrapMode(_.wrapT)),et.name=e,d.babylonTexture=et,s(et)},a.LoadShaderStringAsync=function(i,e,o,s){var c=i.shaders[e];if(Tools.IsBase64(c.uri)){var d=atob(c.uri.split(",")[1]);o&&o(d)}else Tools.LoadFile(i.rootUrl+c.uri,o,void 0,void 0,!1,function(_){_&&s&&s(_.status+" "+_.statusText)})},a.LoadMaterialAsync=function(i,e,o,s){var c=i.materials[e];if(!c.technique){s&&s("No technique found.");return}var d=i.techniques[c.technique];if(!d){i.scene._blockEntityCollection=!!i.assetContainer;var _=new StandardMaterial(e,i.scene);_._parentContainer=i.assetContainer,i.scene._blockEntityCollection=!1,_.diffuseColor=new Color3(.5,.5,.5),_.sideOrientation=Material.CounterClockWiseSideOrientation,o(_);return}var b=i.programs[d.program],k=d.states,j=Effect$1.ShadersStore[b.vertexShader+"VertexShader"],$=Effect$1.ShadersStore[b.fragmentShader+"PixelShader"],_e="",et="",tt=new Tokenizer(j),rt=new Tokenizer($),it={},nt=[],ot=[],at=[];for(var st in d.uniforms){var ut=d.uniforms[st],ft=d.parameters[ut];if(it[st]=ft,ft.semantic&&!ft.node&&!ft.source){var lt=glTFTransforms.indexOf(ft.semantic);lt!==-1?(nt.push(babylonTransforms[lt]),delete it[st]):nt.push(st)}else ft.type===EParameterType.SAMPLER_2D?at.push(st):nt.push(st)}for(var ht in d.attributes){var pt=d.attributes[ht],mt=d.parameters[pt];if(mt.semantic){var dt=getAttribute(mt);dt&&ot.push(dt)}}for(;!tt.isEnd()&&tt.getNextToken();){var gt=tt.currentToken;if(gt!==ETokenType.IDENTIFIER){_e+=tt.currentString;continue}var _t=!1;for(var ht in d.attributes){var pt=d.attributes[ht],mt=d.parameters[pt];if(tt.currentIdentifier===ht&&mt.semantic){_e+=getAttribute(mt),_t=!0;break}}_t||(_e+=parseShaderUniforms(tt,d,it))}for(;!rt.isEnd()&&rt.getNextToken();){var gt=rt.currentToken;if(gt!==ETokenType.IDENTIFIER){et+=rt.currentString;continue}et+=parseShaderUniforms(rt,d,it)}var yt={vertex:b.vertexShader+e,fragment:b.fragmentShader+e},Tt={attributes:ot,uniforms:nt,samplers:at,needAlphaBlending:k&&k.enable&&k.enable.indexOf(3042)!==-1};Effect$1.ShadersStore[b.vertexShader+e+"VertexShader"]=_e,Effect$1.ShadersStore[b.fragmentShader+e+"PixelShader"]=et;var St=new ShaderMaterial(e,i.scene,yt,Tt);if(St.onError=onShaderCompileError(b,St,s),St.onCompiled=onShaderCompileSuccess(i,St,d,c,it,o),St.sideOrientation=Material.CounterClockWiseSideOrientation,k&&k.functions){var At=k.functions;At.cullFace&&At.cullFace[0]!==ECullingType.BACK&&(St.backFaceCulling=!1);var vt=At.blendFuncSeparate;vt&&(vt[0]===EBlendingFunction.SRC_ALPHA&&vt[1]===EBlendingFunction.ONE_MINUS_SRC_ALPHA&&vt[2]===EBlendingFunction.ONE&&vt[3]===EBlendingFunction.ONE?St.alphaMode=Constants.ALPHA_COMBINE:vt[0]===EBlendingFunction.ONE&&vt[1]===EBlendingFunction.ONE&&vt[2]===EBlendingFunction.ZERO&&vt[3]===EBlendingFunction.ONE?St.alphaMode=Constants.ALPHA_ONEONE:vt[0]===EBlendingFunction.SRC_ALPHA&&vt[1]===EBlendingFunction.ONE&&vt[2]===EBlendingFunction.ZERO&&vt[3]===EBlendingFunction.ONE?St.alphaMode=Constants.ALPHA_ADD:vt[0]===EBlendingFunction.ZERO&&vt[1]===EBlendingFunction.ONE_MINUS_SRC_COLOR&&vt[2]===EBlendingFunction.ONE&&vt[3]===EBlendingFunction.ONE?St.alphaMode=Constants.ALPHA_SUBTRACT:vt[0]===EBlendingFunction.DST_COLOR&&vt[1]===EBlendingFunction.ZERO&&vt[2]===EBlendingFunction.ONE&&vt[3]===EBlendingFunction.ONE?St.alphaMode=Constants.ALPHA_MULTIPLY:vt[0]===EBlendingFunction.SRC_ALPHA&&vt[1]===EBlendingFunction.ONE_MINUS_SRC_COLOR&&vt[2]===EBlendingFunction.ONE&&vt[3]===EBlendingFunction.ONE&&(St.alphaMode=Constants.ALPHA_MAXIMIZED))}},a}(),GLTFLoader$1=function(){function a(){}return a.RegisterExtension=function(i){if(a.Extensions[i.name]){Tools.Error('Tool with the same name "'+i.name+'" already exists');return}a.Extensions[i.name]=i},a.prototype.dispose=function(){},a.prototype._importMeshAsync=function(i,e,o,s,c,d,_,b){var k=this;return e.useRightHandedSystem=!0,GLTFLoaderExtension.LoadRuntimeAsync(e,o,s,function(j){j.assetContainer=c,j.importOnlyMeshes=!0,i===""?j.importMeshesNames=[]:typeof i=="string"?j.importMeshesNames=[i]:i&&!(i instanceof Array)?j.importMeshesNames=[i]:(j.importMeshesNames=[],Tools.Warn("Argument meshesNames must be of type string or string[]")),k._createNodes(j);var $=new Array,_e=new Array;for(var et in j.nodes){var tt=j.nodes[et];tt.babylonNode instanceof AbstractMesh&&$.push(tt.babylonNode)}for(var rt in j.skins){var it=j.skins[rt];it.babylonSkeleton instanceof Skeleton&&_e.push(it.babylonSkeleton)}k._loadBuffersAsync(j,function(){k._loadShadersAsync(j,function(){importMaterials(j),postLoad(j),!GLTFFileLoader.IncrementalLoading&&d&&d($,_e)})},_),GLTFFileLoader.IncrementalLoading&&d&&d($,_e)},b),!0},a.prototype.importMeshAsync=function(i,e,o,s,c,d){var _=this;return new Promise(function(b,k){_._importMeshAsync(i,e,s,c,o,function(j,$){b({meshes:j,particleSystems:[],skeletons:$,animationGroups:[],lights:[],transformNodes:[],geometries:[]})},d,function(j){k(new Error(j))})})},a.prototype._loadAsync=function(i,e,o,s,c,d){var _=this;i.useRightHandedSystem=!0,GLTFLoaderExtension.LoadRuntimeAsync(i,e,o,function(b){GLTFLoaderExtension.LoadRuntimeExtensionsAsync(b,function(){_._createNodes(b),_._loadBuffersAsync(b,function(){_._loadShadersAsync(b,function(){importMaterials(b),postLoad(b),GLTFFileLoader.IncrementalLoading||s()})}),GLTFFileLoader.IncrementalLoading&&s()},d)},d)},a.prototype.loadAsync=function(i,e,o,s){var c=this;return new Promise(function(d,_){c._loadAsync(i,e,o,function(){d()},s,function(b){_(new Error(b))})})},a.prototype._loadShadersAsync=function(i,e){var o=!1,s=function(_,b){GLTFLoaderExtension.LoadShaderStringAsync(i,_,function(k){k instanceof ArrayBuffer||(i.loadedShaderCount++,k&&(Effect$1.ShadersStore[_+(b.type===EShaderType.VERTEX?"VertexShader":"PixelShader")]=k),i.loadedShaderCount===i.shaderscount&&e())},function(){Tools.Error("Error when loading shader program named "+_+" located at "+b.uri)})};for(var c in i.shaders){o=!0;var d=i.shaders[c];d?s.bind(this,c,d)():Tools.Error("No shader named: "+c)}o||e()},a.prototype._loadBuffersAsync=function(i,e,o){var s=!1,c=function(b,k){GLTFLoaderExtension.LoadBufferAsync(i,b,function(j){i.loadedBufferCount++,j&&(j.byteLength!=i.buffers[b].byteLength&&Tools.Error("Buffer named "+b+" is length "+j.byteLength+". Expected: "+k.byteLength),i.loadedBufferViews[b]=j),i.loadedBufferCount===i.buffersCount&&e()},function(){Tools.Error("Error when loading buffer named "+b+" located at "+k.uri)})};for(var d in i.buffers){s=!0;var _=i.buffers[d];_?c.bind(this,d,_)():Tools.Error("No buffer named: "+d)}s||e()},a.prototype._createNodes=function(i){var e=i.currentScene;if(e)for(var o=0;o<e.nodes.length;o++)traverseNodes(i,e.nodes[o],null);else for(var s in i.scenes){e=i.scenes[s];for(var o=0;o<e.nodes.length;o++)traverseNodes(i,e.nodes[o],null)}},a.Extensions={},a}(),GLTFLoaderExtension=function(){function a(i){this._name=i}return Object.defineProperty(a.prototype,"name",{get:function(){return this._name},enumerable:!1,configurable:!0}),a.prototype.loadRuntimeAsync=function(i,e,o,s,c){return!1},a.prototype.loadRuntimeExtensionsAsync=function(i,e,o){return!1},a.prototype.loadBufferAsync=function(i,e,o,s,c){return!1},a.prototype.loadTextureBufferAsync=function(i,e,o,s){return!1},a.prototype.createTextureAsync=function(i,e,o,s,c){return!1},a.prototype.loadShaderStringAsync=function(i,e,o,s){return!1},a.prototype.loadMaterialAsync=function(i,e,o,s){return!1},a.LoadRuntimeAsync=function(i,e,o,s,c){a.ApplyExtensions(function(d){return d.loadRuntimeAsync(i,e,o,s,c)},function(){setTimeout(function(){!s||s(GLTFLoaderBase.CreateRuntime(e.json,i,o))})})},a.LoadRuntimeExtensionsAsync=function(i,e,o){a.ApplyExtensions(function(s){return s.loadRuntimeExtensionsAsync(i,e,o)},function(){setTimeout(function(){e()})})},a.LoadBufferAsync=function(i,e,o,s,c){a.ApplyExtensions(function(d){return d.loadBufferAsync(i,e,o,s,c)},function(){GLTFLoaderBase.LoadBufferAsync(i,e,o,s,c)})},a.LoadTextureAsync=function(i,e,o,s){a.LoadTextureBufferAsync(i,e,function(c){c&&a.CreateTextureAsync(i,e,c,o,s)},s)},a.LoadShaderStringAsync=function(i,e,o,s){a.ApplyExtensions(function(c){return c.loadShaderStringAsync(i,e,o,s)},function(){GLTFLoaderBase.LoadShaderStringAsync(i,e,o,s)})},a.LoadMaterialAsync=function(i,e,o,s){a.ApplyExtensions(function(c){return c.loadMaterialAsync(i,e,o,s)},function(){GLTFLoaderBase.LoadMaterialAsync(i,e,o,s)})},a.LoadTextureBufferAsync=function(i,e,o,s){a.ApplyExtensions(function(c){return c.loadTextureBufferAsync(i,e,o,s)},function(){GLTFLoaderBase.LoadTextureBufferAsync(i,e,o,s)})},a.CreateTextureAsync=function(i,e,o,s,c){a.ApplyExtensions(function(d){return d.createTextureAsync(i,e,o,s,c)},function(){GLTFLoaderBase.CreateTextureAsync(i,e,o,s,c)})},a.ApplyExtensions=function(i,e){for(var o in GLTFLoader$1.Extensions){var s=GLTFLoader$1.Extensions[o];if(i(s))return}e()},a}();GLTFFileLoader._CreateGLTF1Loader=function(){return new GLTFLoader$1};var BinaryExtensionBufferName="binary_glTF",GLTFBinaryExtension=function(a){__extends(i,a);function i(){return a.call(this,"KHR_binary_glTF")||this}return i.prototype.loadRuntimeAsync=function(e,o,s,c,d){var _=o.json.extensionsUsed;return!_||_.indexOf(this.name)===-1||!o.bin?!1:(this._bin=o.bin,c(GLTFLoaderBase.CreateRuntime(o.json,e,s)),!0)},i.prototype.loadBufferAsync=function(e,o,s,c){return e.extensionsUsed.indexOf(this.name)===-1||o!==BinaryExtensionBufferName?!1:(this._bin.readAsync(0,this._bin.byteLength).then(s,function(d){return c(d.message)}),!0)},i.prototype.loadTextureBufferAsync=function(e,o,s,c){var d=e.textures[o],_=e.images[d.source];if(!_.extensions||!(this.name in _.extensions))return!1;var b=_.extensions[this.name],k=e.bufferViews[b.bufferView],j=GLTFUtils.GetBufferFromBufferView(e,k,0,k.byteLength,EComponentType.UNSIGNED_BYTE);return s(j),!0},i.prototype.loadShaderStringAsync=function(e,o,s,c){var d=e.shaders[o];if(!d.extensions||!(this.name in d.extensions))return!1;var _=d.extensions[this.name],b=e.bufferViews[_.bufferView],k=GLTFUtils.GetBufferFromBufferView(e,b,0,b.byteLength,EComponentType.UNSIGNED_BYTE);return setTimeout(function(){var j=GLTFUtils.DecodeBufferToText(k);s(j)}),!0},i}(GLTFLoaderExtension);GLTFLoader$1.RegisterExtension(new GLTFBinaryExtension);var GLTFMaterialsCommonExtension=function(a){__extends(i,a);function i(){return a.call(this,"KHR_materials_common")||this}return i.prototype.loadRuntimeExtensionsAsync=function(e,o,s){if(!e.extensions)return!1;var c=e.extensions[this.name];if(!c)return!1;var d=c.lights;if(d)for(var _ in d){var b=d[_];switch(b.type){case"ambient":var k=new HemisphericLight(b.name,new Vector3(0,1,0),e.scene),j=b.ambient;j&&(k.diffuse=Color3.FromArray(j.color||[1,1,1]));break;case"point":var $=new PointLight(b.name,new Vector3(10,10,10),e.scene),_e=b.point;_e&&($.diffuse=Color3.FromArray(_e.color||[1,1,1]));break;case"directional":var et=new DirectionalLight(b.name,new Vector3(0,-1,0),e.scene),tt=b.directional;tt&&(et.diffuse=Color3.FromArray(tt.color||[1,1,1]));break;case"spot":var rt=b.spot;if(rt){var it=new SpotLight(b.name,new Vector3(0,10,0),new Vector3(0,-1,0),rt.fallOffAngle||Math.PI,rt.fallOffExponent||0,e.scene);it.diffuse=Color3.FromArray(rt.color||[1,1,1])}break;default:Tools.Warn('GLTF Material Common extension: light type "'+b.type+"\u201D not supported");break}}return!1},i.prototype.loadMaterialAsync=function(e,o,s,c){var d=e.materials[o];if(!d||!d.extensions)return!1;var _=d.extensions[this.name];if(!_)return!1;var b=new StandardMaterial(o,e.scene);return b.sideOrientation=Material.CounterClockWiseSideOrientation,_.technique==="CONSTANT"&&(b.disableLighting=!0),b.backFaceCulling=_.doubleSided===void 0?!1:!_.doubleSided,b.alpha=_.values.transparency===void 0?1:_.values.transparency,b.specularPower=_.values.shininess===void 0?0:_.values.shininess,typeof _.values.ambient=="string"?this._loadTexture(e,_.values.ambient,b,"ambientTexture",c):b.ambientColor=Color3.FromArray(_.values.ambient||[0,0,0]),typeof _.values.diffuse=="string"?this._loadTexture(e,_.values.diffuse,b,"diffuseTexture",c):b.diffuseColor=Color3.FromArray(_.values.diffuse||[0,0,0]),typeof _.values.emission=="string"?this._loadTexture(e,_.values.emission,b,"emissiveTexture",c):b.emissiveColor=Color3.FromArray(_.values.emission||[0,0,0]),typeof _.values.specular=="string"?this._loadTexture(e,_.values.specular,b,"specularTexture",c):b.specularColor=Color3.FromArray(_.values.specular||[0,0,0]),!0},i.prototype._loadTexture=function(e,o,s,c,d){GLTFLoaderBase.LoadTextureBufferAsync(e,o,function(_){GLTFLoaderBase.CreateTextureAsync(e,o,_,function(b){return s[c]=b},d)},d)},i}(GLTFLoaderExtension);GLTFLoader$1.RegisterExtension(new GLTFMaterialsCommonExtension);var Deferred=function(){function a(){var i=this;this.promise=new Promise(function(e,o){i._resolve=e,i._reject=o})}return Object.defineProperty(a.prototype,"resolve",{get:function(){return this._resolve},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"reject",{get:function(){return this._reject},enumerable:!1,configurable:!0}),a}(),PBRMaterial=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s.directIntensity=1,s.emissiveIntensity=1,s.environmentIntensity=1,s.specularIntensity=1,s.disableBumpMap=!1,s.ambientTextureStrength=1,s.ambientTextureImpactOnAnalyticalLights=i.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,s.metallicF0Factor=1,s.metallicReflectanceColor=Color3.White(),s.useOnlyMetallicFromMetallicReflectanceTexture=!1,s.ambientColor=new Color3(0,0,0),s.albedoColor=new Color3(1,1,1),s.reflectivityColor=new Color3(1,1,1),s.reflectionColor=new Color3(1,1,1),s.emissiveColor=new Color3(0,0,0),s.microSurface=1,s.useLightmapAsShadowmap=!1,s.useAlphaFromAlbedoTexture=!1,s.forceAlphaTest=!1,s.alphaCutOff=.4,s.useSpecularOverAlpha=!0,s.useMicroSurfaceFromReflectivityMapAlpha=!1,s.useRoughnessFromMetallicTextureAlpha=!0,s.useRoughnessFromMetallicTextureGreen=!1,s.useMetallnessFromMetallicTextureBlue=!1,s.useAmbientOcclusionFromMetallicTextureRed=!1,s.useAmbientInGrayScale=!1,s.useAutoMicroSurfaceFromReflectivityMap=!1,s.useRadianceOverAlpha=!0,s.useObjectSpaceNormalMap=!1,s.useParallax=!1,s.useParallaxOcclusion=!1,s.parallaxScaleBias=.05,s.disableLighting=!1,s.forceIrradianceInFragment=!1,s.maxSimultaneousLights=4,s.invertNormalMapX=!1,s.invertNormalMapY=!1,s.twoSidedLighting=!1,s.useAlphaFresnel=!1,s.useLinearAlphaFresnel=!1,s.environmentBRDFTexture=null,s.forceNormalForward=!1,s.enableSpecularAntiAliasing=!1,s.useHorizonOcclusion=!0,s.useRadianceOcclusion=!0,s.unlit=!1,s._environmentBRDFTexture=GetEnvironmentBRDFTexture(o),s}return Object.defineProperty(i.prototype,"refractionTexture",{get:function(){return this.subSurface.refractionTexture},set:function(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"indexOfRefraction",{get:function(){return this.subSurface.indexOfRefraction},set:function(e){this.subSurface.indexOfRefraction=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"invertRefractionY",{get:function(){return this.subSurface.invertRefractionY},set:function(e){this.subSurface.invertRefractionY=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"linkRefractionWithTransparency",{get:function(){return this.subSurface.linkRefractionWithTransparency},set:function(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"usePhysicalLightFalloff",{get:function(){return this._lightFalloff===PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL},set:function(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=PBRBaseMaterial.LIGHTFALLOFF_STANDARD)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"useGLTFLightFalloff",{get:function(){return this._lightFalloff===PBRBaseMaterial.LIGHTFALLOFF_GLTF},set:function(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=PBRBaseMaterial.LIGHTFALLOFF_GLTF:this._lightFalloff=PBRBaseMaterial.LIGHTFALLOFF_STANDARD)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"PBRMaterial"},i.prototype.clone=function(e){var o=this,s=SerializationHelper.Clone(function(){return new i(e,o.getScene())},this);return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this.clearCoat.copyTo(s.clearCoat),this.anisotropy.copyTo(s.anisotropy),this.brdf.copyTo(s.brdf),this.sheen.copyTo(s.sheen),this.subSurface.copyTo(s.subSurface),s},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);return e.customType="BABYLON.PBRMaterial",e.stencil=this.stencil.serialize(),e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e},i.Parse=function(e,o,s){var c=SerializationHelper.Parse(function(){return new i(e.name,o)},e,o,s);return e.stencil&&c.stencil.parse(e.stencil,o,s),e.clearCoat&&c.clearCoat.parse(e.clearCoat,o,s),e.anisotropy&&c.anisotropy.parse(e.anisotropy,o,s),e.brdf&&c.brdf.parse(e.brdf,o,s),e.sheen&&c.sheen.parse(e.sheen,o,s),e.subSurface&&c.subSurface.parse(e.subSurface,o,s),c},i.PBRMATERIAL_OPAQUE=PBRBaseMaterial.PBRMATERIAL_OPAQUE,i.PBRMATERIAL_ALPHATEST=PBRBaseMaterial.PBRMATERIAL_ALPHATEST,i.PBRMATERIAL_ALPHABLEND=PBRBaseMaterial.PBRMATERIAL_ALPHABLEND,i.PBRMATERIAL_ALPHATESTANDBLEND=PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND,i.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"directIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"specularIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"disableBumpMap",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTextureStrength",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"opacityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallic",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"roughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicF0Factor",void 0),__decorate([serializeAsColor3(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicReflectanceColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"metallicReflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurfaceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"bumpTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],i.prototype,"lightmapTexture",void 0),__decorate([serializeAsColor3("ambient"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"ambientColor",void 0),__decorate([serializeAsColor3("albedo"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"albedoColor",void 0),__decorate([serializeAsColor3("reflectivity"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectivityColor",void 0),__decorate([serializeAsColor3("reflection"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionColor",void 0),__decorate([serializeAsColor3("emissive"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"emissiveColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"microSurface",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLightmapAsShadowmap",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"useAlphaFromAlbedoTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"forceAlphaTest",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],i.prototype,"alphaCutOff",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useSpecularOverAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRoughnessFromMetallicTextureGreen",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useMetallnessFromMetallicTextureBlue",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAmbientInGrayScale",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),__decorate([serialize()],i.prototype,"usePhysicalLightFalloff",null),__decorate([serialize()],i.prototype,"useGLTFLightFalloff",null),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOverAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useObjectSpaceNormalMap",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallax",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useParallaxOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"parallaxScaleBias",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"disableLighting",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceIrradianceInFragment",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"maxSimultaneousLights",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapX",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"invertNormalMapY",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"twoSidedLighting",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useAlphaFresnel",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useLinearAlphaFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"environmentBRDFTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"forceNormalForward",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"enableSpecularAntiAliasing",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useHorizonOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRadianceOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],i.prototype,"unlit",void 0),i}(PBRBaseMaterial);RegisterClass("BABYLON.PBRMaterial",PBRMaterial);var MorphTarget=function(){function a(i,e,o){e===void 0&&(e=0),o===void 0&&(o=null),this.name=i,this.animations=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new Observable,this._onDataLayoutChanged=new Observable,this._animationPropertiesOverride=null,this._scene=o||EngineStore.LastCreatedScene,this.influence=e,this._scene&&(this._uniqueId=this._scene.getUniqueId())}return Object.defineProperty(a.prototype,"influence",{get:function(){return this._influence},set:function(i){if(this._influence!==i){var e=this._influence;this._influence=i,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(e===0||i===0)}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(i){this._animationPropertiesOverride=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasUVs",{get:function(){return!!this._uvs},enumerable:!1,configurable:!0}),a.prototype.setPositions=function(i){var e=this.hasPositions;this._positions=i,e!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)},a.prototype.getPositions=function(){return this._positions},a.prototype.setNormals=function(i){var e=this.hasNormals;this._normals=i,e!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)},a.prototype.getNormals=function(){return this._normals},a.prototype.setTangents=function(i){var e=this.hasTangents;this._tangents=i,e!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)},a.prototype.getTangents=function(){return this._tangents},a.prototype.setUVs=function(i){var e=this.hasUVs;this._uvs=i,e!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)},a.prototype.getUVs=function(){return this._uvs},a.prototype.clone=function(){var i=this,e=SerializationHelper.Clone(function(){return new a(i.name,i.influence,i._scene)},this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e},a.prototype.serialize=function(){var i={};return i.name=this.name,i.influence=this.influence,i.positions=Array.prototype.slice.call(this.getPositions()),this.id!=null&&(i.id=this.id),this.hasNormals&&(i.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(i.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(i.uvs=Array.prototype.slice.call(this.getUVs())),SerializationHelper.AppendSerializedAnimations(this,i),i},a.prototype.getClassName=function(){return"MorphTarget"},a.Parse=function(i){var e=new a(i.name,i.influence);if(e.setPositions(i.positions),i.id!=null&&(e.id=i.id),i.normals&&e.setNormals(i.normals),i.tangents&&e.setTangents(i.tangents),i.uvs&&e.setUVs(i.uvs),i.animations)for(var o=0;o<i.animations.length;o++){var s=i.animations[o],c=GetClass("BABYLON.Animation");c&&e.animations.push(c.Parse(s))}return e},a.FromMesh=function(i,e,o){e||(e=i.name);var s=new a(e,o,i.getScene());return s.setPositions(i.getVerticesData(VertexBuffer.PositionKind)),i.isVerticesDataPresent(VertexBuffer.NormalKind)&&s.setNormals(i.getVerticesData(VertexBuffer.NormalKind)),i.isVerticesDataPresent(VertexBuffer.TangentKind)&&s.setTangents(i.getVerticesData(VertexBuffer.TangentKind)),i.isVerticesDataPresent(VertexBuffer.UVKind)&&s.setUVs(i.getVerticesData(VertexBuffer.UVKind)),s},__decorate([serialize()],a.prototype,"id",void 0),a}(),RawTexture2DArray=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j,$){b===void 0&&(b=!0),k===void 0&&(k=!1),j===void 0&&(j=Texture.TRILINEAR_SAMPLINGMODE),$===void 0&&($=0);var _e=a.call(this,null,_,!b,k)||this;return _e.format=d,_e._texture=_.getEngine().createRawTexture2DArray(e,o,s,c,d,b,k,j,null,$),_e._depth=c,_e.is2DArray=!0,_e}return Object.defineProperty(i.prototype,"depth",{get:function(){return this._depth},enumerable:!1,configurable:!0}),i.prototype.update=function(e){!this._texture||this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},i.CreateRGBATexture=function(e,o,s,c,d,_,b,k,j){return _===void 0&&(_=!0),b===void 0&&(b=!1),k===void 0&&(k=3),j===void 0&&(j=0),new i(e,o,s,c,5,d,_,b,k,j)},i}(Texture),MorphTargetManager=function(){function a(i){if(i===void 0&&(i=null),this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new SmartArray(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,i||(i=EngineStore.LastCreatedScene),this._scene=i,this._scene){this._scene.morphTargetManagers.push(this),this._uniqueId=this._scene.getUniqueId();var e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0}}return Object.defineProperty(a.prototype,"areUpdatesFrozen",{get:function(){return this._blockCounter>0},set:function(i){i?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"vertexCount",{get:function(){return this._vertexCount},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"supportsNormals",{get:function(){return this._supportsNormals&&this.enableNormalMorphing},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"supportsTangents",{get:function(){return this._supportsTangents&&this.enableTangentMorphing},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"supportsUVs",{get:function(){return this._supportsUVs&&this.enableUVMorphing},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"numTargets",{get:function(){return this._targets.length},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"numInfluencers",{get:function(){return this._activeTargets.length},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"influences",{get:function(){return this._influences},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"useTextureToStoreTargets",{get:function(){return this._useTextureToStoreTargets},set:function(i){this._useTextureToStoreTargets=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isUsingTextureForTargets",{get:function(){return a.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets},enumerable:!1,configurable:!0}),a.prototype.getActiveTarget=function(i){return this._activeTargets.data[i]},a.prototype.getTarget=function(i){return this._targets[i]},a.prototype.addTarget=function(i){var e=this;this._targets.push(i),this._targetInfluenceChangedObservers.push(i.onInfluenceChanged.add(function(o){e._syncActiveTargets(o)})),this._targetDataLayoutChangedObservers.push(i._onDataLayoutChanged.add(function(){e._syncActiveTargets(!0)})),this._syncActiveTargets(!0)},a.prototype.removeTarget=function(i){var e=this._targets.indexOf(i);e>=0&&(this._targets.splice(e,1),i.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(e,1)[0]),i._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(e,1)[0]),this._syncActiveTargets(!0))},a.prototype._bind=function(i){i.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),i.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),i.setTexture("morphTargets",this._targetStoreTexture)},a.prototype.clone=function(){for(var i=new a(this._scene),e=0,o=this._targets;e<o.length;e++){var s=o[e];i.addTarget(s.clone())}return i.enableNormalMorphing=this.enableNormalMorphing,i.enableTangentMorphing=this.enableTangentMorphing,i.enableUVMorphing=this.enableUVMorphing,i},a.prototype.serialize=function(){var i={};i.id=this.uniqueId,i.targets=[];for(var e=0,o=this._targets;e<o.length;e++){var s=o[e];i.targets.push(s.serialize())}return i},a.prototype._syncActiveTargets=function(i){if(!this.areUpdatesFrozen){var e=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,(!this._morphTargetTextureIndices||this._morphTargetTextureIndices.length!==this._targets.length)&&(this._morphTargetTextureIndices=new Float32Array(this._targets.length));for(var o=-1,s=0,c=this._targets;s<c.length;s++){var d=c[s];if(o++,!(d.influence===0&&this.optimizeInfluencers)){this._activeTargets.push(d),this._morphTargetTextureIndices[e]=o,this._tempInfluences[e++]=d.influence,this._supportsNormals=this._supportsNormals&&d.hasNormals,this._supportsTangents=this._supportsTangents&&d.hasTangents,this._supportsUVs=this._supportsUVs&&d.hasUVs;var _=d.getPositions();if(_){var b=_.length/3;if(this._vertexCount===0)this._vertexCount=b;else if(this._vertexCount!==b){Logger$2.Error("Incompatible target. Targets must all have the same vertices count.");return}}}}(!this._influences||this._influences.length!==e)&&(this._influences=new Float32Array(e));for(var k=0;k<e;k++)this._influences[k]=this._tempInfluences[k];i&&this.synchronize()}},a.prototype.synchronize=function(){if(!(!this._scene||this.areUpdatesFrozen)){if(this.isUsingTextureForTargets&&this._vertexCount){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride,this._textureHeight=1;var i=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>i&&(this._textureHeight=Math.ceil(this._textureWidth/i),this._textureWidth=i);var e=!0;if(this._targetStoreTexture){var o=this._targetStoreTexture.getSize();o.width===this._textureWidth&&o.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(e=!1)}if(e){this._targetStoreTexture&&this._targetStoreTexture.dispose();for(var s=this._targets.length,c=new Float32Array(s*this._textureWidth*this._textureHeight*4),d=0,_=0;_<s;_++){var b=this._targets[_],k=b.getPositions(),j=b.getNormals(),$=b.getUVs(),_e=b.getTangents();if(!k){_===0&&Logger$2.Error("Invalid morph target. Target must have positions.");return}d=_*this._textureWidth*this._textureHeight*4;for(var et=0;et<this._vertexCount;et++)c[d]=k[et*3],c[d+1]=k[et*3+1],c[d+2]=k[et*3+2],d+=4,j&&(c[d]=j[et*3],c[d+1]=j[et*3+1],c[d+2]=j[et*3+2],d+=4),$&&(c[d]=$[et*2],c[d+1]=$[et*2+1],d+=4),_e&&(c[d]=_e[et*3],c[d+1]=_e[et*3+1],c[d+2]=_e[et*3+2],d+=4)}this._targetStoreTexture=RawTexture2DArray.CreateRGBATexture(c,this._textureWidth,this._textureHeight,s,this._scene,!1,!1,1,1)}}for(var tt=0,rt=this._scene.meshes;tt<rt.length;tt++){var it=rt[tt];it.morphTargetManager===this&&it._syncGeometryWithMorphTargetManager()}}},a.prototype.dispose=function(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene&&(this._scene.removeMorphTargetManager(this),this._parentContainer)){var i=this._parentContainer.morphTargetManagers.indexOf(this);i>-1&&this._parentContainer.morphTargetManagers.splice(i,1),this._parentContainer=null}},a.Parse=function(i,e){var o=new a(e);o._uniqueId=i.id;for(var s=0,c=i.targets;s<c.length;s++){var d=c[s];o.addTarget(MorphTarget.Parse(d))}return o},a.EnableTextureStorage=!0,a}(),ArrayItem=function(){function a(){}return a.Get=function(i,e,o){if(!e||o==null||!e[o])throw new Error(i+": Failed to find index ("+o+")");return e[o]},a.Assign=function(i){if(i)for(var e=0;e<i.length;e++)i[e].index=e},a}(),GLTFLoader=function(){function a(i){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._disposed=!1,this._extensions=new Array,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._parent=i}return a.RegisterExtension=function(i,e){a.UnregisterExtension(i)&&Logger$2.Warn("Extension with the name '"+i+"' already exists"),a._RegisteredExtensions[i]={factory:e}},a.UnregisterExtension=function(i){return a._RegisteredExtensions[i]?(delete a._RegisteredExtensions[i],!0):!1},Object.defineProperty(a.prototype,"gltf",{get:function(){return this._gltf},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"bin",{get:function(){return this._bin},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"parent",{get:function(){return this._parent},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"babylonScene",{get:function(){return this._babylonScene},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rootBabylonMesh",{get:function(){return this._rootBabylonMesh},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){if(!this._disposed){this._disposed=!0,this._completePromises.length=0;for(var i in this._extensions){var e=this._extensions[i];e.dispose&&e.dispose(),delete this._extensions[i]}this._gltf=null,this._babylonScene=null,this._rootBabylonMesh=null,this._parent.dispose()}},a.prototype.importMeshAsync=function(i,e,o,s,c,d,_){var b=this;return _===void 0&&(_=""),Promise.resolve().then(function(){b._babylonScene=e,b._assetContainer=o,b._loadData(s);var k=null;if(i){var j={};if(b._gltf.nodes)for(var $=0,_e=b._gltf.nodes;$<_e.length;$++){var et=_e[$];et.name&&(j[et.name]=et.index)}var tt=i instanceof Array?i:[i];k=tt.map(function(rt){var it=j[rt];if(it===void 0)throw new Error("Failed to find node '"+rt+"'");return it})}return b._loadAsync(c,_,k,function(){return{meshes:b._getMeshes(),particleSystems:[],skeletons:b._getSkeletons(),animationGroups:b._getAnimationGroups(),lights:b._babylonLights,transformNodes:b._getTransformNodes(),geometries:b._getGeometries()}})})},a.prototype.loadAsync=function(i,e,o,s,c){var d=this;return c===void 0&&(c=""),Promise.resolve().then(function(){return d._babylonScene=i,d._loadData(e),d._loadAsync(o,c,null,function(){})})},a.prototype._loadAsync=function(i,e,o,s){var c=this;return Promise.resolve().then(function(){c._rootUrl=i,c._uniqueRootUrl=!StringTools.StartsWith(i,"file:")&&e?i:""+i+Date.now()+"/",c._fileName=e,c._loadExtensions(),c._checkExtensions();var d=GLTFLoaderState[GLTFLoaderState.LOADING]+" => "+GLTFLoaderState[GLTFLoaderState.READY],_=GLTFLoaderState[GLTFLoaderState.LOADING]+" => "+GLTFLoaderState[GLTFLoaderState.COMPLETE];c._parent._startPerformanceCounter(d),c._parent._startPerformanceCounter(_),c._parent._setState(GLTFLoaderState.LOADING),c._extensionsOnLoading();var b=new Array,k=c._babylonScene.blockMaterialDirtyMechanism;if(c._babylonScene.blockMaterialDirtyMechanism=!0,o)b.push(c.loadSceneAsync("/nodes",{nodes:o,index:-1}));else if(c._gltf.scene!=null||c._gltf.scenes&&c._gltf.scenes[0]){var j=ArrayItem.Get("/scene",c._gltf.scenes,c._gltf.scene||0);b.push(c.loadSceneAsync("/scenes/"+j.index,j))}if(c.parent.loadAllMaterials&&c._gltf.materials)for(var $=0;$<c._gltf.materials.length;++$){var _e=c._gltf.materials[$],et="/materials/"+$,tt=Material.TriangleFillMode;b.push(c._loadMaterialAsync(et,_e,null,tt,function(it){}))}c._babylonScene.blockMaterialDirtyMechanism=k,c._parent.compileMaterials&&b.push(c._compileMaterialsAsync()),c._parent.compileShadowGenerators&&b.push(c._compileShadowGeneratorsAsync());var rt=Promise.all(b).then(function(){return c._rootBabylonMesh&&c._rootBabylonMesh.setEnabled(!0),c._extensionsOnReady(),c._parent._setState(GLTFLoaderState.READY),c._startAnimations(),s()});return rt.then(function(it){return c._parent._endPerformanceCounter(d),Tools.SetImmediate(function(){c._disposed||Promise.all(c._completePromises).then(function(){c._parent._endPerformanceCounter(_),c._parent._setState(GLTFLoaderState.COMPLETE),c._parent.onCompleteObservable.notifyObservers(void 0),c._parent.onCompleteObservable.clear(),c.dispose()},function(nt){c._parent.onErrorObservable.notifyObservers(nt),c._parent.onErrorObservable.clear(),c.dispose()})}),it})}).catch(function(d){throw c._disposed||(c._parent.onErrorObservable.notifyObservers(d),c._parent.onErrorObservable.clear(),c.dispose()),d})},a.prototype._loadData=function(i){if(this._gltf=i.json,this._setupData(),i.bin){var e=this._gltf.buffers;if(e&&e[0]&&!e[0].uri){var o=e[0];(o.byteLength<i.bin.byteLength-3||o.byteLength>i.bin.byteLength)&&Logger$2.Warn("Binary buffer length ("+o.byteLength+") from JSON does not match chunk length ("+i.bin.byteLength+")"),this._bin=i.bin}else Logger$2.Warn("Unexpected BIN chunk")}},a.prototype._setupData=function(){if(ArrayItem.Assign(this._gltf.accessors),ArrayItem.Assign(this._gltf.animations),ArrayItem.Assign(this._gltf.buffers),ArrayItem.Assign(this._gltf.bufferViews),ArrayItem.Assign(this._gltf.cameras),ArrayItem.Assign(this._gltf.images),ArrayItem.Assign(this._gltf.materials),ArrayItem.Assign(this._gltf.meshes),ArrayItem.Assign(this._gltf.nodes),ArrayItem.Assign(this._gltf.samplers),ArrayItem.Assign(this._gltf.scenes),ArrayItem.Assign(this._gltf.skins),ArrayItem.Assign(this._gltf.textures),this._gltf.nodes){for(var i={},e=0,o=this._gltf.nodes;e<o.length;e++){var s=o[e];if(s.children)for(var c=0,d=s.children;c<d.length;c++){var _=d[c];i[_]=s.index}}for(var b=this._createRootNode(),k=0,j=this._gltf.nodes;k<j.length;k++){var s=j[k],$=i[s.index];s.parent=$===void 0?b:this._gltf.nodes[$]}}},a.prototype._loadExtensions=function(){for(var i in a._RegisteredExtensions){var e=a._RegisteredExtensions[i].factory(this);e.name!==i&&Logger$2.Warn("The name of the glTF loader extension instance does not match the registered name: "+e.name+" !== "+i),this._extensions.push(e),this._parent.onExtensionLoadedObservable.notifyObservers(e)}this._extensions.sort(function(o,s){return(o.order||Number.MAX_VALUE)-(s.order||Number.MAX_VALUE)}),this._parent.onExtensionLoadedObservable.clear()},a.prototype._checkExtensions=function(){if(this._gltf.extensionsRequired)for(var i=function(d){var _=e._extensions.some(function(b){return b.name===d&&b.enabled});if(!_)throw new Error("Require extension "+d+" is not available")},e=this,o=0,s=this._gltf.extensionsRequired;o<s.length;o++){var c=s[o];i(c)}},a.prototype._createRootNode=function(){this._babylonScene._blockEntityCollection=!!this._assetContainer,this._rootBabylonMesh=new Mesh("__root__",this._babylonScene),this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);var i={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case GLTFLoaderCoordinateSystemMode.AUTO:{this._babylonScene.useRightHandedSystem||(i.rotation=[0,1,0,0],i.scale=[1,1,-1],a._LoadTransform(i,this._rootBabylonMesh));break}case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error("Invalid coordinate system mode ("+this._parent.coordinateSystemMode+")")}return this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh),i},a.prototype.loadSceneAsync=function(i,e){var o=this,s=this._extensionsLoadSceneAsync(i,e);if(s)return s;var c=new Array;if(this.logOpen(i+" "+(e.name||"")),e.nodes)for(var d=0,_=e.nodes;d<_.length;d++){var b=_[d],k=ArrayItem.Get(i+"/nodes/"+b,this._gltf.nodes,b);c.push(this.loadNodeAsync("/nodes/"+k.index,k,function(rt){rt.parent=o._rootBabylonMesh}))}if(this._gltf.nodes)for(var j=0,$=this._gltf.nodes;j<$.length;j++){var k=$[j];if(k._babylonTransformNode&&k._babylonBones)for(var _e=0,et=k._babylonBones;_e<et.length;_e++){var tt=et[_e];tt.linkTransformNode(k._babylonTransformNode)}}return c.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(c).then(function(){})},a.prototype._forEachPrimitive=function(i,e){if(i._primitiveBabylonMeshes)for(var o=0,s=i._primitiveBabylonMeshes;o<s.length;o++){var c=s[o];e(c)}},a.prototype._getGeometries=function(){var i=new Array,e=this._gltf.nodes;if(e)for(var o=0,s=e;o<s.length;o++){var c=s[o];this._forEachPrimitive(c,function(d){var _=d.geometry;_&&i.indexOf(_)===-1&&i.push(_)})}return i},a.prototype._getMeshes=function(){var i=new Array;this._rootBabylonMesh&&i.push(this._rootBabylonMesh);var e=this._gltf.nodes;if(e)for(var o=0,s=e;o<s.length;o++){var c=s[o];this._forEachPrimitive(c,function(d){i.push(d)})}return i},a.prototype._getTransformNodes=function(){var i=new Array,e=this._gltf.nodes;if(e)for(var o=0,s=e;o<s.length;o++){var c=s[o];c._babylonTransformNode&&c._babylonTransformNode.getClassName()==="TransformNode"&&i.push(c._babylonTransformNode)}return i},a.prototype._getSkeletons=function(){var i=new Array,e=this._gltf.skins;if(e)for(var o=0,s=e;o<s.length;o++){var c=s[o];c._data&&i.push(c._data.babylonSkeleton)}return i},a.prototype._getAnimationGroups=function(){var i=new Array,e=this._gltf.animations;if(e)for(var o=0,s=e;o<s.length;o++){var c=s[o];c._babylonAnimationGroup&&i.push(c._babylonAnimationGroup)}return i},a.prototype._startAnimations=function(){switch(this._parent.animationStartMode){case GLTFLoaderAnimationStartMode.NONE:break;case GLTFLoaderAnimationStartMode.FIRST:{var i=this._getAnimationGroups();i.length!==0&&i[0].start(!0);break}case GLTFLoaderAnimationStartMode.ALL:{for(var i=this._getAnimationGroups(),e=0,o=i;e<o.length;e++){var s=o[e];s.start(!0)}break}default:{Logger$2.Error("Invalid animation start mode ("+this._parent.animationStartMode+")");return}}},a.prototype.loadNodeAsync=function(i,e,o){var s=this;o===void 0&&(o=function(){});var c=this._extensionsLoadNodeAsync(i,e,o);if(c)return c;if(e._babylonTransformNode)throw new Error(i+": Invalid recursive node hierarchy");var d=new Array;this.logOpen(i+" "+(e.name||""));var _=function(j){if(a.AddPointerMetadata(j,i),a._LoadTransform(e,j),e.camera!=null){var $=ArrayItem.Get(i+"/camera",s._gltf.cameras,e.camera);d.push(s.loadCameraAsync("/cameras/"+$.index,$,function(it){it.parent=j}))}if(e.children)for(var _e=0,et=e.children;_e<et.length;_e++){var tt=et[_e],rt=ArrayItem.Get(i+"/children/"+tt,s._gltf.nodes,tt);d.push(s.loadNodeAsync("/nodes/"+rt.index,rt,function(it){it.parent=j}))}o(j)};if(e.mesh==null){var b=e.name||"node"+e.index;this._babylonScene._blockEntityCollection=!!this._assetContainer,e._babylonTransformNode=new TransformNode(b,this._babylonScene),e._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,_(e._babylonTransformNode)}else{var k=ArrayItem.Get(i+"/mesh",this._gltf.meshes,e.mesh);d.push(this._loadMeshAsync("/meshes/"+k.index,e,k,_))}return this.logClose(),Promise.all(d).then(function(){return s._forEachPrimitive(e,function(j){j.geometry&&j.geometry.useBoundingInfoFromGeometry?j._updateBoundingInfo():j.refreshBoundingInfo(!0)}),e._babylonTransformNode})},a.prototype._loadMeshAsync=function(i,e,o,s){var c=o.primitives;if(!c||!c.length)throw new Error(i+": Primitives are missing");c[0].index==null&&ArrayItem.Assign(c);var d=new Array;this.logOpen(i+" "+(o.name||""));var _=e.name||"node"+e.index;if(c.length===1){var b=o.primitives[0];d.push(this._loadMeshPrimitiveAsync(i+"/primitives/"+b.index,_,e,o,b,function(_e){e._babylonTransformNode=_e,e._primitiveBabylonMeshes=[_e]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,e._babylonTransformNode=new TransformNode(_,this._babylonScene),e._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,e._primitiveBabylonMeshes=[];for(var k=0,j=c;k<j.length;k++){var b=j[k];d.push(this._loadMeshPrimitiveAsync(i+"/primitives/"+b.index,_+"_primitive"+b.index,e,o,b,function(et){et.parent=e._babylonTransformNode,e._primitiveBabylonMeshes.push(et)}))}}if(e.skin!=null){var $=ArrayItem.Get(i+"/skin",this._gltf.skins,e.skin);d.push(this._loadSkinAsync("/skins/"+$.index,e,$))}return s(e._babylonTransformNode),this.logClose(),Promise.all(d).then(function(){return e._babylonTransformNode})},a.prototype._loadMeshPrimitiveAsync=function(i,e,o,s,c,d){var _=this,b=this._extensionsLoadMeshPrimitiveAsync(i,e,o,s,c,d);if(b)return b;this.logOpen(""+i);var k=this._disableInstancedMesh===0&&this._parent.createInstances&&o.skin==null&&!s.primitives[0].targets,j,$;if(k&&c._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,j=c._instanceData.babylonSourceMesh.createInstance(e),j._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,$=c._instanceData.promise;else{var _e=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;var et=new Mesh(e,this._babylonScene);et._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,et.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?Material.CounterClockWiseSideOrientation:Material.ClockWiseSideOrientation,this._createMorphTargets(i,o,s,c,et),_e.push(this._loadVertexDataAsync(i,c,et).then(function(nt){return _._loadMorphTargetsAsync(i,c,et,nt).then(function(){_._babylonScene._blockEntityCollection=!!_._assetContainer,nt.applyToMesh(et),nt._parentContainer=_._assetContainer,_._babylonScene._blockEntityCollection=!1})}));var tt=a._GetDrawMode(i,c.mode);if(c.material==null){var rt=this._defaultBabylonMaterialData[tt];rt||(rt=this._createDefaultMaterial("__GLTFLoader._default",tt),this._parent.onMaterialLoadedObservable.notifyObservers(rt),this._defaultBabylonMaterialData[tt]=rt),et.material=rt}else{var it=ArrayItem.Get(i+"/material",this._gltf.materials,c.material);_e.push(this._loadMaterialAsync("/materials/"+it.index,it,et,tt,function(nt){et.material=nt}))}$=Promise.all(_e),k&&(c._instanceData={babylonSourceMesh:et,promise:$}),j=et}return a.AddPointerMetadata(j,i),this._parent.onMeshLoadedObservable.notifyObservers(j),d(j),this.logClose(),$.then(function(){return j})},a.prototype._loadVertexDataAsync=function(i,e,o){var s=this,c=this._extensionsLoadVertexDataAsync(i,e,o);if(c)return c;var d=e.attributes;if(!d)throw new Error(i+": Attributes are missing");var _=new Array,b=new Geometry(o.name,this._babylonScene);if(e.indices==null)o.isUnIndexed=!0;else{var k=ArrayItem.Get(i+"/indices",this._gltf.accessors,e.indices);_.push(this._loadIndicesAccessorAsync("/accessors/"+k.index,k).then(function($){b.setIndices($)}))}var j=function($,_e,et){if(d[$]!=null){o._delayInfo=o._delayInfo||[],o._delayInfo.indexOf(_e)===-1&&o._delayInfo.push(_e);var tt=ArrayItem.Get(i+"/attributes/"+$,s._gltf.accessors,d[$]);_.push(s._loadVertexAccessorAsync("/accessors/"+tt.index,tt,_e).then(function(rt){if(rt.getKind()===VertexBuffer.PositionKind&&!s.parent.alwaysComputeBoundingBox&&!o.skeleton){var it=tt.min,nt=tt.max;if(it!==void 0&&nt!==void 0){if(tt.normalized&&tt.componentType!==5126){var ot=1;switch(tt.componentType){case 5120:ot=127;break;case 5121:ot=255;break;case 5122:ot=32767;break;case 5123:ot=65535;break}for(var at=0;at<3;++at)it[at]=Math.max(it[at]/ot,-1),nt[at]=Math.max(nt[at]/ot,-1)}var st=TmpVectors.Vector3[0],ut=TmpVectors.Vector3[1];st.copyFromFloats.apply(st,it),ut.copyFromFloats.apply(ut,nt),b._boundingInfo=new BoundingInfo(st,ut),b.useBoundingInfoFromGeometry=!0}}b.setVerticesBuffer(rt,tt.count)})),_e==VertexBuffer.MatricesIndicesExtraKind&&(o.numBoneInfluencers=8),et&&et(tt)}};return j("POSITION",VertexBuffer.PositionKind),j("NORMAL",VertexBuffer.NormalKind),j("TANGENT",VertexBuffer.TangentKind),j("TEXCOORD_0",VertexBuffer.UVKind),j("TEXCOORD_1",VertexBuffer.UV2Kind),j("TEXCOORD_2",VertexBuffer.UV3Kind),j("TEXCOORD_3",VertexBuffer.UV4Kind),j("TEXCOORD_4",VertexBuffer.UV5Kind),j("TEXCOORD_5",VertexBuffer.UV6Kind),j("JOINTS_0",VertexBuffer.MatricesIndicesKind),j("WEIGHTS_0",VertexBuffer.MatricesWeightsKind),j("JOINTS_1",VertexBuffer.MatricesIndicesExtraKind),j("WEIGHTS_1",VertexBuffer.MatricesWeightsExtraKind),j("COLOR_0",VertexBuffer.ColorKind,function($){$.type==="VEC4"&&(o.hasVertexAlpha=!0)}),Promise.all(_).then(function(){return b})},a.prototype._createMorphTargets=function(i,e,o,s,c){if(!!s.targets){if(e._numMorphTargets==null)e._numMorphTargets=s.targets.length;else if(s.targets.length!==e._numMorphTargets)throw new Error(i+": Primitives do not have the same number of targets");var d=o.extras?o.extras.targetNames:null;c.morphTargetManager=new MorphTargetManager(c.getScene()),c.morphTargetManager.areUpdatesFrozen=!0;for(var _=0;_<s.targets.length;_++){var b=e.weights?e.weights[_]:o.weights?o.weights[_]:0,k=d?d[_]:"morphTarget"+_;c.morphTargetManager.addTarget(new MorphTarget(k,b,c.getScene()))}}},a.prototype._loadMorphTargetsAsync=function(i,e,o,s){if(!e.targets)return Promise.resolve();for(var c=new Array,d=o.morphTargetManager,_=0;_<d.numTargets;_++){var b=d.getTarget(_);c.push(this._loadMorphTargetVertexDataAsync(i+"/targets/"+_,s,e.targets[_],b))}return Promise.all(c).then(function(){d.areUpdatesFrozen=!1})},a.prototype._loadMorphTargetVertexDataAsync=function(i,e,o,s){var c=this,d=new Array,_=function(b,k,j){if(o[b]!=null){var $=e.getVertexBuffer(k);if(!!$){var _e=ArrayItem.Get(i+"/"+b,c._gltf.accessors,o[b]);d.push(c._loadFloatAccessorAsync("/accessors/"+_e.index,_e).then(function(et){j($,et)}))}}};return _("POSITION",VertexBuffer.PositionKind,function(b,k){var j=new Float32Array(k.length);b.forEach(k.length,function($,_e){j[_e]=k[_e]+$}),s.setPositions(j)}),_("NORMAL",VertexBuffer.NormalKind,function(b,k){var j=new Float32Array(k.length);b.forEach(j.length,function($,_e){j[_e]=k[_e]+$}),s.setNormals(j)}),_("TANGENT",VertexBuffer.TangentKind,function(b,k){var j=new Float32Array(k.length/3*4),$=0;b.forEach(k.length/3*4,function(_e,et){(et+1)%4!==0&&(j[$]=k[$]+_e,$++)}),s.setTangents(j)}),Promise.all(d).then(function(){})},a._LoadTransform=function(i,e){if(i.skin==null){var o=Vector3.Zero(),s=Quaternion.Identity(),c=Vector3.One();if(i.matrix){var d=Matrix.FromArray(i.matrix);d.decompose(c,s,o)}else i.translation&&(o=Vector3.FromArray(i.translation)),i.rotation&&(s=Quaternion.FromArray(i.rotation)),i.scale&&(c=Vector3.FromArray(i.scale));e.position=o,e.rotationQuaternion=s,e.scaling=c}},a.prototype._loadSkinAsync=function(i,e,o){var s=this,c=this._extensionsLoadSkinAsync(i,e,o);if(c)return c;var d=function(j){s._forEachPrimitive(e,function($){$.skeleton=j})};if(o._data)return d(o._data.babylonSkeleton),o._data.promise;var _="skeleton"+o.index;this._babylonScene._blockEntityCollection=!!this._assetContainer;var b=new Skeleton(o.name||_,_,this._babylonScene);b._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,b.overrideMesh=this._rootBabylonMesh,this._loadBones(i,o,b),d(b);var k=this._loadSkinInverseBindMatricesDataAsync(i,o).then(function(j){s._updateBoneMatrices(b,j)});return o._data={babylonSkeleton:b,promise:k},k},a.prototype._loadBones=function(i,e,o){for(var s={},c=0,d=e.joints;c<d.length;c++){var _=d[c],b=ArrayItem.Get(i+"/joints/"+_,this._gltf.nodes,_);this._loadBone(b,e,o,s)}},a.prototype._loadBone=function(i,e,o,s){var c=s[i.index];if(c)return c;var d=null;i.parent&&i.parent._babylonTransformNode!==this._rootBabylonMesh&&(d=this._loadBone(i.parent,e,o,s));var _=e.joints.indexOf(i.index);return c=new Bone(i.name||"joint"+i.index,o,d,this._getNodeMatrix(i),null,null,_),s[i.index]=c,i._babylonBones=i._babylonBones||[],i._babylonBones.push(c),c},a.prototype._loadSkinInverseBindMatricesDataAsync=function(i,e){if(e.inverseBindMatrices==null)return Promise.resolve(null);var o=ArrayItem.Get(i+"/inverseBindMatrices",this._gltf.accessors,e.inverseBindMatrices);return this._loadFloatAccessorAsync("/accessors/"+o.index,o)},a.prototype._updateBoneMatrices=function(i,e){for(var o=0,s=i.bones;o<s.length;o++){var c=s[o],d=Matrix.Identity(),_=c._index;e&&_!==-1&&(Matrix.FromArrayToRef(e,_*16,d),d.invertToRef(d));var b=c.getParent();b&&d.multiplyToRef(b.getInvertedAbsoluteTransform(),d),c.updateMatrix(d,!1,!1),c._updateDifferenceMatrix(void 0,!1)}},a.prototype._getNodeMatrix=function(i){return i.matrix?Matrix.FromArray(i.matrix):Matrix.Compose(i.scale?Vector3.FromArray(i.scale):Vector3.One(),i.rotation?Quaternion.FromArray(i.rotation):Quaternion.Identity(),i.translation?Vector3.FromArray(i.translation):Vector3.Zero())},a.prototype.loadCameraAsync=function(i,e,o){o===void 0&&(o=function(){});var s=this._extensionsLoadCameraAsync(i,e,o);if(s)return s;var c=new Array;this.logOpen(i+" "+(e.name||"")),this._babylonScene._blockEntityCollection=!!this._assetContainer;var d=new FreeCamera(e.name||"camera"+e.index,Vector3.Zero(),this._babylonScene,!1);switch(d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.ignoreParentScaling=!0,d.rotation=new Vector3(0,Math.PI,0),e.type){case"perspective":{var _=e.perspective;if(!_)throw new Error(i+": Camera perspective properties are missing");d.fov=_.yfov,d.minZ=_.znear,d.maxZ=_.zfar||0;break}case"orthographic":{if(!e.orthographic)throw new Error(i+": Camera orthographic properties are missing");d.mode=Camera$1.ORTHOGRAPHIC_CAMERA,d.orthoLeft=-e.orthographic.xmag,d.orthoRight=e.orthographic.xmag,d.orthoBottom=-e.orthographic.ymag,d.orthoTop=e.orthographic.ymag,d.minZ=e.orthographic.znear,d.maxZ=e.orthographic.zfar;break}default:throw new Error(i+": Invalid camera type ("+e.type+")")}return a.AddPointerMetadata(d,i),this._parent.onCameraLoadedObservable.notifyObservers(d),o(d),this.logClose(),Promise.all(c).then(function(){return d})},a.prototype._loadAnimationsAsync=function(){var i=this._gltf.animations;if(!i)return Promise.resolve();for(var e=new Array,o=0;o<i.length;o++){var s=i[o];e.push(this.loadAnimationAsync("/animations/"+s.index,s).then(function(c){c.targetedAnimations.length===0&&c.dispose()}))}return Promise.all(e).then(function(){})},a.prototype.loadAnimationAsync=function(i,e){var o=this._extensionsLoadAnimationAsync(i,e);if(o)return o;this._babylonScene._blockEntityCollection=!!this._assetContainer;var s=new AnimationGroup(e.name||"animation"+e.index,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,e._babylonAnimationGroup=s;var c=new Array;ArrayItem.Assign(e.channels),ArrayItem.Assign(e.samplers);for(var d=0,_=e.channels;d<_.length;d++){var b=_[d];c.push(this._loadAnimationChannelAsync(i+"/channels/"+b.index,i,e,b,s))}return Promise.all(c).then(function(){return s.normalize(0),s})},a.prototype._loadAnimationChannelAsync=function(i,e,o,s,c,d){var _=this;if(d===void 0&&(d=null),s.target.node==null)return Promise.resolve();var b=ArrayItem.Get(i+"/target/node",this._gltf.nodes,s.target.node);if(s.target.path==="weights"&&!b._numMorphTargets||s.target.path!=="weights"&&!b._babylonTransformNode)return Promise.resolve();var k=ArrayItem.Get(i+"/sampler",o.samplers,s.sampler);return this._loadAnimationSamplerAsync(e+"/samplers/"+s.sampler,k).then(function(j){var $,_e;switch(s.target.path){case"translation":{$="position",_e=Animation.ANIMATIONTYPE_VECTOR3;break}case"rotation":{$="rotationQuaternion",_e=Animation.ANIMATIONTYPE_QUATERNION;break}case"scale":{$="scaling",_e=Animation.ANIMATIONTYPE_VECTOR3;break}case"weights":{$="influence",_e=Animation.ANIMATIONTYPE_FLOAT;break}default:throw new Error(i+"/target/path: Invalid value ("+s.target.path+")")}var et=0,tt;switch($){case"position":{tt=function(){var ft=Vector3.FromArray(j.output,et);return et+=3,ft};break}case"rotationQuaternion":{tt=function(){var ft=Quaternion.FromArray(j.output,et);return et+=4,ft};break}case"scaling":{tt=function(){var ft=Vector3.FromArray(j.output,et);return et+=3,ft};break}case"influence":{tt=function(){for(var ft=new Array(b._numMorphTargets),lt=0;lt<b._numMorphTargets;lt++)ft[lt]=j.output[et++];return ft};break}}var rt;switch(j.interpolation){case"STEP":{rt=function(ft){return{frame:j.input[ft],value:tt(),interpolation:AnimationKeyInterpolation.STEP}};break}case"LINEAR":{rt=function(ft){return{frame:j.input[ft],value:tt()}};break}case"CUBICSPLINE":{rt=function(ft){return{frame:j.input[ft],inTangent:tt(),value:tt(),outTangent:tt()}};break}}for(var it=new Array(j.input.length),nt=0;nt<j.input.length;nt++)it[nt]=rt(nt);if($==="influence")for(var ot=function(ft){var lt=c.name+"_channel"+c.targetedAnimations.length,ht=new Animation(lt,$,1,_e);ht.setKeys(it.map(function(pt){return{frame:pt.frame,inTangent:pt.inTangent?pt.inTangent[ft]:void 0,value:pt.value[ft],outTangent:pt.outTangent?pt.outTangent[ft]:void 0}})),_._forEachPrimitive(b,function(pt){var mt=pt,dt=mt.morphTargetManager.getTarget(ft),gt=ht.clone();dt.animations.push(gt),c.addTargetedAnimation(gt,dt)})},at=0;at<b._numMorphTargets;at++)ot(at);else{var st=c.name+"_channel"+c.targetedAnimations.length,ut=new Animation(st,$,1,_e);ut.setKeys(it),d!=null&&d.animations!=null?(d.animations.push(ut),c.addTargetedAnimation(ut,d)):(b._babylonTransformNode.animations.push(ut),c.addTargetedAnimation(ut,b._babylonTransformNode))}})},a.prototype._loadAnimationSamplerAsync=function(i,e){if(e._data)return e._data;var o=e.interpolation||"LINEAR";switch(o){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(i+"/interpolation: Invalid value ("+e.interpolation+")")}var s=ArrayItem.Get(i+"/input",this._gltf.accessors,e.input),c=ArrayItem.Get(i+"/output",this._gltf.accessors,e.output);return e._data=Promise.all([this._loadFloatAccessorAsync("/accessors/"+s.index,s),this._loadFloatAccessorAsync("/accessors/"+c.index,c)]).then(function(d){var _=d[0],b=d[1];return{input:_,interpolation:o,output:b}}),e._data},a.prototype.loadBufferAsync=function(i,e,o,s){var c=this._extensionsLoadBufferAsync(i,e,o,s);if(c)return c;if(!e._data)if(e.uri)e._data=this.loadUriAsync(i+"/uri",e,e.uri);else{if(!this._bin)throw new Error(i+": Uri is missing or the binary glTF is missing its binary chunk");e._data=this._bin.readAsync(0,e.byteLength)}return e._data.then(function(d){try{return new Uint8Array(d.buffer,d.byteOffset+o,s)}catch(_){throw new Error(i+": "+_.message)}})},a.prototype.loadBufferViewAsync=function(i,e){var o=this._extensionsLoadBufferViewAsync(i,e);if(o)return o;if(e._data)return e._data;var s=ArrayItem.Get(i+"/buffer",this._gltf.buffers,e.buffer);return e._data=this.loadBufferAsync("/buffers/"+s.index,s,e.byteOffset||0,e.byteLength),e._data},a.prototype._loadAccessorAsync=function(i,e,o){var s=this;if(e._data)return e._data;var c=a._GetNumComponents(i,e.type),d=c*VertexBuffer.GetTypeByteLength(e.componentType),_=c*e.count;if(e.bufferView==null)e._data=Promise.resolve(new o(_));else{var b=ArrayItem.Get(i+"/bufferView",this._gltf.bufferViews,e.bufferView);e._data=this.loadBufferViewAsync("/bufferViews/"+b.index,b).then(function(j){if(e.componentType===5126&&!e.normalized&&(!b.byteStride||b.byteStride===d))return a._GetTypedArray(i,e.componentType,j,e.byteOffset,_);var $=new o(_);return VertexBuffer.ForEach(j,e.byteOffset||0,b.byteStride||d,c,e.componentType,$.length,e.normalized||!1,function(_e,et){$[et]=_e}),$})}if(e.sparse){var k=e.sparse;e._data=e._data.then(function(j){var $=j,_e=ArrayItem.Get(i+"/sparse/indices/bufferView",s._gltf.bufferViews,k.indices.bufferView),et=ArrayItem.Get(i+"/sparse/values/bufferView",s._gltf.bufferViews,k.values.bufferView);return Promise.all([s.loadBufferViewAsync("/bufferViews/"+_e.index,_e),s.loadBufferViewAsync("/bufferViews/"+et.index,et)]).then(function(tt){var rt=tt[0],it=tt[1],nt=a._GetTypedArray(i+"/sparse/indices",k.indices.componentType,rt,k.indices.byteOffset,k.count),ot=c*k.count,at;if(e.componentType===5126&&!e.normalized)at=a._GetTypedArray(i+"/sparse/values",e.componentType,it,k.values.byteOffset,ot);else{var st=a._GetTypedArray(i+"/sparse/values",e.componentType,it,k.values.byteOffset,ot);at=new o(ot),VertexBuffer.ForEach(st,0,d,c,e.componentType,at.length,e.normalized||!1,function(pt,mt){at[mt]=pt})}for(var ut=0,ft=0;ft<nt.length;ft++)for(var lt=nt[ft]*c,ht=0;ht<c;ht++)$[lt++]=at[ut++];return $})})}return e._data},a.prototype._loadFloatAccessorAsync=function(i,e){return this._loadAccessorAsync(i,e,Float32Array)},a.prototype._loadIndicesAccessorAsync=function(i,e){if(e.type!=="SCALAR")throw new Error(i+"/type: Invalid value "+e.type);if(e.componentType!==5121&&e.componentType!==5123&&e.componentType!==5125)throw new Error(i+"/componentType: Invalid value "+e.componentType);if(e._data)return e._data;if(e.sparse){var o=a._GetTypedArrayConstructor(i+"/componentType",e.componentType);e._data=this._loadAccessorAsync(i,e,o)}else{var s=ArrayItem.Get(i+"/bufferView",this._gltf.bufferViews,e.bufferView);e._data=this.loadBufferViewAsync("/bufferViews/"+s.index,s).then(function(c){return a._GetTypedArray(i,e.componentType,c,e.byteOffset,e.count)})}return e._data},a.prototype._loadVertexBufferViewAsync=function(i,e){var o=this;return i._babylonBuffer||(i._babylonBuffer=this.loadBufferViewAsync("/bufferViews/"+i.index,i).then(function(s){return new Buffer(o._babylonScene.getEngine(),s,!1)})),i._babylonBuffer},a.prototype._loadVertexAccessorAsync=function(i,e,o){var s=this,c;if(!((c=e._babylonVertexBuffer)===null||c===void 0)&&c[o])return e._babylonVertexBuffer[o];if(e._babylonVertexBuffer||(e._babylonVertexBuffer={}),e.sparse)e._babylonVertexBuffer[o]=this._loadFloatAccessorAsync(i,e).then(function(_){return new VertexBuffer(s._babylonScene.getEngine(),_,o,!1)});else if(o===VertexBuffer.MatricesIndicesKind||o===VertexBuffer.MatricesIndicesExtraKind)e._babylonVertexBuffer[o]=this._loadFloatAccessorAsync(i,e).then(function(_){return new VertexBuffer(s._babylonScene.getEngine(),_,o,!1)});else{var d=ArrayItem.Get(i+"/bufferView",this._gltf.bufferViews,e.bufferView);e._babylonVertexBuffer[o]=this._loadVertexBufferViewAsync(d,o).then(function(_){var b=a._GetNumComponents(i,e.type);return new VertexBuffer(s._babylonScene.getEngine(),_,o,!1,!1,d.byteStride,!1,e.byteOffset,b,e.componentType,e.normalized,!0,1,!0)})}return e._babylonVertexBuffer[o]},a.prototype._loadMaterialMetallicRoughnessPropertiesAsync=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var s=new Array;return e&&(e.baseColorFactor?(o.albedoColor=Color3.FromArray(e.baseColorFactor),o.alpha=e.baseColorFactor[3]):o.albedoColor=Color3.White(),o.metallic=e.metallicFactor==null?1:e.metallicFactor,o.roughness=e.roughnessFactor==null?1:e.roughnessFactor,e.baseColorTexture&&s.push(this.loadTextureInfoAsync(i+"/baseColorTexture",e.baseColorTexture,function(c){c.name=o.name+" (Base Color)",o.albedoTexture=c})),e.metallicRoughnessTexture&&(e.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(i+"/metallicRoughnessTexture",e.metallicRoughnessTexture,function(c){c.name=o.name+" (Metallic Roughness)",o.metallicTexture=c})),o.useMetallnessFromMetallicTextureBlue=!0,o.useRoughnessFromMetallicTextureGreen=!0,o.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then(function(){})},a.prototype._loadMaterialAsync=function(i,e,o,s,c){c===void 0&&(c=function(){});var d=this._extensionsLoadMaterialAsync(i,e,o,s,c);if(d)return d;e._data=e._data||{};var _=e._data[s];if(!_){this.logOpen(i+" "+(e.name||""));var b=this.createMaterial(i,e,s);_={babylonMaterial:b,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(i,e,b)},e._data[s]=_,a.AddPointerMetadata(b,i),this._parent.onMaterialLoadedObservable.notifyObservers(b),this.logClose()}return o&&(_.babylonMeshes.push(o),o.onDisposeObservable.addOnce(function(){var k=_.babylonMeshes.indexOf(o);k!==-1&&_.babylonMeshes.splice(k,1)})),c(_.babylonMaterial),_.promise.then(function(){return _.babylonMaterial})},a.prototype._createDefaultMaterial=function(i,e){this._babylonScene._blockEntityCollection=!!this._assetContainer;var o=new PBRMaterial(i,this._babylonScene);return o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.fillMode=e,o.enableSpecularAntiAliasing=!0,o.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,o.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,o.transparencyMode=PBRMaterial.PBRMATERIAL_OPAQUE,o.metallic=1,o.roughness=1,o},a.prototype.createMaterial=function(i,e,o){var s=this._extensionsCreateMaterial(i,e,o);if(s)return s;var c=e.name||"material"+e.index,d=this._createDefaultMaterial(c,o);return d},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this._extensionsLoadMaterialPropertiesAsync(i,e,o);if(s)return s;var c=new Array;return c.push(this.loadMaterialBasePropertiesAsync(i,e,o)),e.pbrMetallicRoughness&&c.push(this._loadMaterialMetallicRoughnessPropertiesAsync(i+"/pbrMetallicRoughness",e.pbrMetallicRoughness,o)),this.loadMaterialAlphaProperties(i,e,o),Promise.all(c).then(function(){})},a.prototype.loadMaterialBasePropertiesAsync=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var s=new Array;return o.emissiveColor=e.emissiveFactor?Color3.FromArray(e.emissiveFactor):new Color3(0,0,0),e.doubleSided&&(o.backFaceCulling=!1,o.twoSidedLighting=!0),e.normalTexture&&(e.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(i+"/normalTexture",e.normalTexture,function(c){c.name=o.name+" (Normal)",o.bumpTexture=c})),o.invertNormalMapX=!this._babylonScene.useRightHandedSystem,o.invertNormalMapY=this._babylonScene.useRightHandedSystem,e.normalTexture.scale!=null&&(o.bumpTexture.level=e.normalTexture.scale),o.forceIrradianceInFragment=!0),e.occlusionTexture&&(e.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(i+"/occlusionTexture",e.occlusionTexture,function(c){c.name=o.name+" (Occlusion)",o.ambientTexture=c})),o.useAmbientInGrayScale=!0,e.occlusionTexture.strength!=null&&(o.ambientTextureStrength=e.occlusionTexture.strength)),e.emissiveTexture&&s.push(this.loadTextureInfoAsync(i+"/emissiveTexture",e.emissiveTexture,function(c){c.name=o.name+" (Emissive)",o.emissiveTexture=c})),Promise.all(s).then(function(){})},a.prototype.loadMaterialAlphaProperties=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var s=e.alphaMode||"OPAQUE";switch(s){case"OPAQUE":{o.transparencyMode=PBRMaterial.PBRMATERIAL_OPAQUE;break}case"MASK":{o.transparencyMode=PBRMaterial.PBRMATERIAL_ALPHATEST,o.alphaCutOff=e.alphaCutoff==null?.5:e.alphaCutoff,o.albedoTexture&&(o.albedoTexture.hasAlpha=!0);break}case"BLEND":{o.transparencyMode=PBRMaterial.PBRMATERIAL_ALPHABLEND,o.albedoTexture&&(o.albedoTexture.hasAlpha=!0,o.useAlphaFromAlbedoTexture=!0);break}default:throw new Error(i+"/alphaMode: Invalid value ("+e.alphaMode+")")}},a.prototype.loadTextureInfoAsync=function(i,e,o){var s=this;o===void 0&&(o=function(){});var c=this._extensionsLoadTextureInfoAsync(i,e,o);if(c)return c;if(this.logOpen(""+i),e.texCoord>=6)throw new Error(i+"/texCoord: Invalid value ("+e.texCoord+")");var d=ArrayItem.Get(i+"/index",this._gltf.textures,e.index);d._textureInfo=e;var _=this._loadTextureAsync("/textures/"+e.index,d,function(b){b.coordinatesIndex=e.texCoord||0,a.AddPointerMetadata(b,i),s._parent.onTextureLoadedObservable.notifyObservers(b),o(b)});return this.logClose(),_},a.prototype._loadTextureAsync=function(i,e,o){o===void 0&&(o=function(){});var s=this._extensionsLoadTextureAsync(i,e,o);if(s)return s;this.logOpen(i+" "+(e.name||""));var c=e.sampler==null?a.DefaultSampler:ArrayItem.Get(i+"/sampler",this._gltf.samplers,e.sampler),d=ArrayItem.Get(i+"/source",this._gltf.images,e.source),_=this._createTextureAsync(i,c,d,o,void 0,!e._textureInfo.nonColorData);return this.logClose(),_},a.prototype._createTextureAsync=function(i,e,o,s,c,d){var _=this;s===void 0&&(s=function(){});var b=this._loadSampler("/samplers/"+e.index,e),k=new Array,j=new Deferred;this._babylonScene._blockEntityCollection=!!this._assetContainer;var $={noMipmap:b.noMipMaps,invertY:!1,samplingMode:b.samplingMode,onLoad:function(){_._disposed||j.resolve()},onError:function(et,tt){_._disposed||j.reject(new Error(i+": "+(tt&&tt.message?tt.message:et||"Failed to load texture")))},mimeType:o.mimeType,loaderOptions:c,useSRGBBuffer:!!d&&this._parent.useSRGBBuffers},_e=new Texture(null,this._babylonScene,$);return _e._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,k.push(j.promise),k.push(this.loadImageAsync("/images/"+o.index,o).then(function(et){var tt=o.uri||_._fileName+"#image"+o.index,rt="data:"+_._uniqueRootUrl+tt;_e.updateURL(rt,et)})),_e.wrapU=b.wrapU,_e.wrapV=b.wrapV,s(_e),Promise.all(k).then(function(){return _e})},a.prototype._loadSampler=function(i,e){return e._data||(e._data={noMipMaps:e.minFilter===9728||e.minFilter===9729,samplingMode:a._GetTextureSamplingMode(i,e),wrapU:a._GetTextureWrapMode(i+"/wrapS",e.wrapS),wrapV:a._GetTextureWrapMode(i+"/wrapT",e.wrapT)}),e._data},a.prototype.loadImageAsync=function(i,e){if(!e._data){if(this.logOpen(i+" "+(e.name||"")),e.uri)e._data=this.loadUriAsync(i+"/uri",e,e.uri);else{var o=ArrayItem.Get(i+"/bufferView",this._gltf.bufferViews,e.bufferView);e._data=this.loadBufferViewAsync("/bufferViews/"+o.index,o)}this.logClose()}return e._data},a.prototype.loadUriAsync=function(i,e,o){var s=this,c=this._extensionsLoadUriAsync(i,e,o);if(c)return c;if(!a._ValidateUri(o))throw new Error(i+": '"+o+"' is invalid");if(IsBase64DataUrl(o)){var d=new Uint8Array(DecodeBase64UrlToBinary(o));return this.log(i+": Decoded "+o.substr(0,64)+"... ("+d.length+" bytes)"),Promise.resolve(d)}return this.log(i+": Loading "+o),this._parent.preprocessUrlAsync(this._rootUrl+o).then(function(_){return new Promise(function(b,k){s._parent._loadFile(s._babylonScene,_,function(j){s._disposed||(s.log(i+": Loaded "+o+" ("+j.byteLength+" bytes)"),b(new Uint8Array(j)))},!0,function(j){k(new LoadFileError(i+": Failed to load '"+o+"'"+(j?": "+j.status+" "+j.statusText:""),j))})})})},a.AddPointerMetadata=function(i,e){var o=i.metadata=i.metadata||{},s=o.gltf=o.gltf||{},c=s.pointers=s.pointers||[];c.push(e)},a._GetTextureWrapMode=function(i,e){switch(e=e==null?10497:e,e){case 33071:return Texture.CLAMP_ADDRESSMODE;case 33648:return Texture.MIRROR_ADDRESSMODE;case 10497:return Texture.WRAP_ADDRESSMODE;default:return Logger$2.Warn(i+": Invalid value ("+e+")"),Texture.WRAP_ADDRESSMODE}},a._GetTextureSamplingMode=function(i,e){var o=e.magFilter==null?9729:e.magFilter,s=e.minFilter==null?9987:e.minFilter;if(o===9729)switch(s){case 9728:return Texture.LINEAR_NEAREST;case 9729:return Texture.LINEAR_LINEAR;case 9984:return Texture.LINEAR_NEAREST_MIPNEAREST;case 9985:return Texture.LINEAR_LINEAR_MIPNEAREST;case 9986:return Texture.LINEAR_NEAREST_MIPLINEAR;case 9987:return Texture.LINEAR_LINEAR_MIPLINEAR;default:return Logger$2.Warn(i+"/minFilter: Invalid value ("+s+")"),Texture.LINEAR_LINEAR_MIPLINEAR}else switch(o!==9728&&Logger$2.Warn(i+"/magFilter: Invalid value ("+o+")"),s){case 9728:return Texture.NEAREST_NEAREST;case 9729:return Texture.NEAREST_LINEAR;case 9984:return Texture.NEAREST_NEAREST_MIPNEAREST;case 9985:return Texture.NEAREST_LINEAR_MIPNEAREST;case 9986:return Texture.NEAREST_NEAREST_MIPLINEAR;case 9987:return Texture.NEAREST_LINEAR_MIPLINEAR;default:return Logger$2.Warn(i+"/minFilter: Invalid value ("+s+")"),Texture.NEAREST_NEAREST_MIPNEAREST}},a._GetTypedArrayConstructor=function(i,e){switch(e){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(i+": Invalid component type "+e)}},a._GetTypedArray=function(i,e,o,s,c){var d=o.buffer;s=o.byteOffset+(s||0);var _=a._GetTypedArrayConstructor(i+"/componentType",e),b=VertexBuffer.GetTypeByteLength(e);return s%b!==0?(Logger$2.Warn(i+": Copying buffer as byte offset ("+s+") is not a multiple of component type byte length ("+b+")"),new _(d.slice(s,s+c*b),0)):new _(d,s,c)},a._GetNumComponents=function(i,e){switch(e){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(i+": Invalid type ("+e+")")},a._ValidateUri=function(i){return Tools.IsBase64(i)||i.indexOf("..")===-1},a._GetDrawMode=function(i,e){switch(e==null&&(e=4),e){case 0:return Material.PointListDrawMode;case 1:return Material.LineListDrawMode;case 2:return Material.LineLoopDrawMode;case 3:return Material.LineStripDrawMode;case 4:return Material.TriangleFillMode;case 5:return Material.TriangleStripDrawMode;case 6:return Material.TriangleFanDrawMode}throw new Error(i+": Invalid mesh primitive mode ("+e+")")},a.prototype._compileMaterialsAsync=function(){var i=this;this._parent._startPerformanceCounter("Compile materials");var e=new Array;if(this._gltf.materials)for(var o=0,s=this._gltf.materials;o<s.length;o++){var c=s[o];if(c._data)for(var d in c._data)for(var _=c._data[d],b=0,k=_.babylonMeshes;b<k.length;b++){var j=k[b];j.computeWorldMatrix(!0);var $=_.babylonMaterial;e.push($.forceCompilationAsync(j)),e.push($.forceCompilationAsync(j,{useInstances:!0})),this._parent.useClipPlane&&(e.push($.forceCompilationAsync(j,{clipPlane:!0})),e.push($.forceCompilationAsync(j,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then(function(){i._parent._endPerformanceCounter("Compile materials")})},a.prototype._compileShadowGeneratorsAsync=function(){var i=this;this._parent._startPerformanceCounter("Compile shadow generators");for(var e=new Array,o=this._babylonScene.lights,s=0,c=o;s<c.length;s++){var d=c[s],_=d.getShadowGenerator();_&&e.push(_.forceCompilationAsync())}return Promise.all(e).then(function(){i._parent._endPerformanceCounter("Compile shadow generators")})},a.prototype._forEachExtensions=function(i){for(var e=0,o=this._extensions;e<o.length;e++){var s=o[e];s.enabled&&i(s)}},a.prototype._applyExtensions=function(i,e,o){for(var s=0,c=this._extensions;s<c.length;s++){var d=c[s];if(d.enabled){var _=d.name+"."+e,b=i;b._activeLoaderExtensionFunctions=b._activeLoaderExtensionFunctions||{};var k=b._activeLoaderExtensionFunctions;if(!k[_]){k[_]=!0;try{var j=o(d);if(j)return j}finally{delete k[_]}}}}return null},a.prototype._extensionsOnLoading=function(){this._forEachExtensions(function(i){return i.onLoading&&i.onLoading()})},a.prototype._extensionsOnReady=function(){this._forEachExtensions(function(i){return i.onReady&&i.onReady()})},a.prototype._extensionsLoadSceneAsync=function(i,e){return this._applyExtensions(e,"loadScene",function(o){return o.loadSceneAsync&&o.loadSceneAsync(i,e)})},a.prototype._extensionsLoadNodeAsync=function(i,e,o){return this._applyExtensions(e,"loadNode",function(s){return s.loadNodeAsync&&s.loadNodeAsync(i,e,o)})},a.prototype._extensionsLoadCameraAsync=function(i,e,o){return this._applyExtensions(e,"loadCamera",function(s){return s.loadCameraAsync&&s.loadCameraAsync(i,e,o)})},a.prototype._extensionsLoadVertexDataAsync=function(i,e,o){return this._applyExtensions(e,"loadVertexData",function(s){return s._loadVertexDataAsync&&s._loadVertexDataAsync(i,e,o)})},a.prototype._extensionsLoadMeshPrimitiveAsync=function(i,e,o,s,c,d){return this._applyExtensions(c,"loadMeshPrimitive",function(_){return _._loadMeshPrimitiveAsync&&_._loadMeshPrimitiveAsync(i,e,o,s,c,d)})},a.prototype._extensionsLoadMaterialAsync=function(i,e,o,s,c){return this._applyExtensions(e,"loadMaterial",function(d){return d._loadMaterialAsync&&d._loadMaterialAsync(i,e,o,s,c)})},a.prototype._extensionsCreateMaterial=function(i,e,o){return this._applyExtensions(e,"createMaterial",function(s){return s.createMaterial&&s.createMaterial(i,e,o)})},a.prototype._extensionsLoadMaterialPropertiesAsync=function(i,e,o){return this._applyExtensions(e,"loadMaterialProperties",function(s){return s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(i,e,o)})},a.prototype._extensionsLoadTextureInfoAsync=function(i,e,o){return this._applyExtensions(e,"loadTextureInfo",function(s){return s.loadTextureInfoAsync&&s.loadTextureInfoAsync(i,e,o)})},a.prototype._extensionsLoadTextureAsync=function(i,e,o){return this._applyExtensions(e,"loadTexture",function(s){return s._loadTextureAsync&&s._loadTextureAsync(i,e,o)})},a.prototype._extensionsLoadAnimationAsync=function(i,e){return this._applyExtensions(e,"loadAnimation",function(o){return o.loadAnimationAsync&&o.loadAnimationAsync(i,e)})},a.prototype._extensionsLoadSkinAsync=function(i,e,o){return this._applyExtensions(o,"loadSkin",function(s){return s._loadSkinAsync&&s._loadSkinAsync(i,e,o)})},a.prototype._extensionsLoadUriAsync=function(i,e,o){return this._applyExtensions(e,"loadUri",function(s){return s._loadUriAsync&&s._loadUriAsync(i,e,o)})},a.prototype._extensionsLoadBufferViewAsync=function(i,e){return this._applyExtensions(e,"loadBufferView",function(o){return o.loadBufferViewAsync&&o.loadBufferViewAsync(i,e)})},a.prototype._extensionsLoadBufferAsync=function(i,e,o,s){return this._applyExtensions(e,"loadBuffer",function(c){return c.loadBufferAsync&&c.loadBufferAsync(i,e,o,s)})},a.LoadExtensionAsync=function(i,e,o,s){if(!e.extensions)return null;var c=e.extensions,d=c[o];return d?s(i+"/extensions/"+o,d):null},a.LoadExtraAsync=function(i,e,o,s){if(!e.extras)return null;var c=e.extras,d=c[o];return d?s(i+"/extras/"+o,d):null},a.prototype.isExtensionUsed=function(i){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(i)!==-1},a.prototype.logOpen=function(i){this._parent._logOpen(i)},a.prototype.logClose=function(){this._parent._logClose()},a.prototype.log=function(i){this._parent._log(i)},a.prototype.startPerformanceCounter=function(i){this._parent._startPerformanceCounter(i)},a.prototype.endPerformanceCounter=function(i){this._parent._endPerformanceCounter(i)},a._RegisteredExtensions={},a.DefaultSampler={index:-1},a}();GLTFFileLoader._CreateGLTF2Loader=function(a){return new GLTFLoader(a)};var RawCubeTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j){c===void 0&&(c=5),d===void 0&&(d=0),_===void 0&&(_=!1),b===void 0&&(b=!1),k===void 0&&(k=3),j===void 0&&(j=null);var $=a.call(this,"",e)||this;return $._texture=e.getEngine().createRawCubeTexture(o,s,c,d,_,b,k,j),$}return i.prototype.update=function(e,o,s,c,d){d===void 0&&(d=null),this._texture.getEngine().updateRawCubeTexture(this._texture,e,o,s,c,d)},i.prototype.updateRGBDAsync=function(e,o,s,c){return o===void 0&&(o=null),s===void 0&&(s=.8),c===void 0&&(c=0),_UpdateRGBDAsync(this._texture,e,o,s,c).then(function(){})},i.prototype.clone=function(){var e=this;return SerializationHelper.Clone(function(){var o=e.getScene(),s=e._texture,c=new i(o,s._bufferViewArray,s.width,s.format,s.type,s.generateMipMaps,s.invertY,s.samplingMode,s._compression);return s.source===InternalTextureSource.CubeRawRGBD&&c.updateRGBDAsync(s._bufferViewArrayArray,s._sphericalPolynomial,s._lodGenerationScale,s._lodGenerationOffset),c},this)},i}(CubeTexture),NAME$u="EXT_lights_image_based",EXT_lights_image_based=function(){function a(i){this.name=NAME$u,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$u)}return a.prototype.dispose=function(){this._loader=null,delete this._lights},a.prototype.onLoading=function(){var i=this._loader.gltf.extensions;if(i&&i[this.name]){var e=i[this.name];this._lights=e.lights}},a.prototype.loadSceneAsync=function(i,e){var o=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(s,c){var d=new Array;d.push(o._loader.loadSceneAsync(i,e)),o._loader.logOpen(""+s);var _=ArrayItem.Get(s+"/light",o._lights,c.light);return d.push(o._loadLightAsync("/extensions/"+o.name+"/lights/"+c.light,_).then(function(b){o._loader.babylonScene.environmentTexture=b})),o._loader.logClose(),Promise.all(d).then(function(){})})},a.prototype._loadLightAsync=function(i,e){var o=this;if(!e._loaded){var s=new Array;this._loader.logOpen(""+i);for(var c=new Array(e.specularImages.length),d=function(k){var j=e.specularImages[k];c[k]=new Array(j.length);for(var $=function(et){var tt=i+"/specularImages/"+k+"/"+et;_._loader.logOpen(""+tt);var rt=j[et],it=ArrayItem.Get(tt,_._loader.gltf.images,rt);s.push(_._loader.loadImageAsync("/images/"+rt,it).then(function(nt){c[k][et]=nt})),_._loader.logClose()},_e=0;_e<j.length;_e++)$(_e)},_=this,b=0;b<e.specularImages.length;b++)d(b);this._loader.logClose(),e._loaded=Promise.all(s).then(function(){var k=new RawCubeTexture(o._loader.babylonScene,null,e.specularImageSize);if(k.name=e.name||"environment",e._babylonTexture=k,e.intensity!=null&&(k.level=e.intensity),e.rotation){var j=Quaternion.FromArray(e.rotation);o._loader.babylonScene.useRightHandedSystem||(j=Quaternion.Inverse(j)),Matrix.FromQuaternionToRef(j,k.getReflectionTextureMatrix())}if(!e.irradianceCoefficients)throw new Error(i+": Irradiance coefficients are missing");var $=SphericalHarmonics.FromArray(e.irradianceCoefficients);$.scaleInPlace(e.intensity),$.convertIrradianceToLambertianRadiance();var _e=SphericalPolynomial.FromHarmonics($),et=(c.length-1)/Scalar.Log2(e.specularImageSize);return k.updateRGBDAsync(c,_e,et)})}return e._loaded.then(function(){return e._babylonTexture})},a}();GLTFLoader.RegisterExtension(NAME$u,function(a){return new EXT_lights_image_based(a)});var NAME$t="EXT_mesh_gpu_instancing",EXT_mesh_gpu_instancing=function(){function a(i){this.name=NAME$t,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$t)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadNodeAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){s._loader._disableInstancedMesh++;var _=s._loader.loadNodeAsync("/nodes/"+e.index,e,o);if(s._loader._disableInstancedMesh--,!e._primitiveBabylonMeshes)return _;var b=new Array,k=0,j=function($){if(d.attributes[$]==null){b.push(Promise.resolve(null));return}var _e=ArrayItem.Get(c+"/attributes/"+$,s._loader.gltf.accessors,d.attributes[$]);if(b.push(s._loader._loadFloatAccessorAsync("/accessors/"+_e.bufferView,_e)),k===0)k=_e.count;else if(k!==_e.count)throw new Error(c+"/attributes: Instance buffer accessors do not have the same count.")};return j("TRANSLATION"),j("ROTATION"),j("SCALE"),_.then(function($){return Promise.all(b).then(function(_e){var et=_e[0],tt=_e[1],rt=_e[2],it=new Float32Array(k*16);TmpVectors.Vector3[0].copyFromFloats(0,0,0),TmpVectors.Quaternion[0].copyFromFloats(0,0,0,1),TmpVectors.Vector3[1].copyFromFloats(1,1,1);for(var nt=0;nt<k;++nt)et&&Vector3.FromArrayToRef(et,nt*3,TmpVectors.Vector3[0]),tt&&Quaternion.FromArrayToRef(tt,nt*4,TmpVectors.Quaternion[0]),rt&&Vector3.FromArrayToRef(rt,nt*3,TmpVectors.Vector3[1]),Matrix.ComposeToRef(TmpVectors.Vector3[1],TmpVectors.Quaternion[0],TmpVectors.Vector3[0],TmpVectors.Matrix[0]),TmpVectors.Matrix[0].copyToArray(it,nt*16);for(var ot=0,at=e._primitiveBabylonMeshes;ot<at.length;ot++){var st=at[ot];st.thinInstanceSetBuffer("matrix",it,16,!0)}return $})})})},a}();GLTFLoader.RegisterExtension(NAME$t,function(a){return new EXT_mesh_gpu_instancing(a)});var MeshoptCompression=function(){function a(){var i=a.Configuration.decoder;this._decoderModulePromise=Tools.LoadScriptAsync(Tools.GetAbsoluteUrl(i.url)).then(function(){return MeshoptDecoder.ready})}return Object.defineProperty(a,"Default",{get:function(){return a._Default||(a._Default=new a),a._Default},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){delete this._decoderModulePromise},a.prototype.decodeGltfBufferAsync=function(i,e,o,s,c){return this._decoderModulePromise.then(function(){var d=new Uint8Array(e*o);return MeshoptDecoder.decodeGltfBuffer(d,e,o,i,s,c),d})},a.Configuration={decoder:{url:"https://preview.babylonjs.com/meshopt_decoder.js"}},a._Default=null,a}(),NAME$s="EXT_meshopt_compression",EXT_meshopt_compression=function(){function a(i){this.name=NAME$s,this.enabled=i.isExtensionUsed(NAME$s),this._loader=i}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadBufferViewAsync=function(i,e){var o=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(s,c){var d=e;if(d._meshOptData)return d._meshOptData;var _=ArrayItem.Get(i+"/buffer",o._loader.gltf.buffers,c.buffer);return d._meshOptData=o._loader.loadBufferAsync("/buffers/"+_.index,_,c.byteOffset||0,c.byteLength).then(function(b){return MeshoptCompression.Default.decodeGltfBufferAsync(b,c.count,c.byteStride,c.mode,c.filter)}),d._meshOptData})},a}();GLTFLoader.RegisterExtension(NAME$s,function(a){return new EXT_meshopt_compression(a)});var NAME$r="EXT_texture_webp",EXT_texture_webp=function(){function a(i){this.name=NAME$r,this._loader=i,this.enabled=i.isExtensionUsed(NAME$r)}return a.prototype.dispose=function(){this._loader=null},a.prototype._loadTextureAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=e.sampler==null?GLTFLoader.DefaultSampler:ArrayItem.Get(i+"/sampler",s._loader.gltf.samplers,e.sampler),b=ArrayItem.Get(c+"/source",s._loader.gltf.images,d.source);return s._loader._createTextureAsync(i,_,b,function(k){o(k)},void 0,!e._textureInfo.nonColorData)})},a}();GLTFLoader.RegisterExtension(NAME$r,function(a){return new EXT_texture_webp(a)});var WorkerPool=function(){function a(i){this._pendingActions=new Array,this._workerInfos=i.map(function(e){return{worker:e,active:!1}})}return a.prototype.dispose=function(){for(var i=0,e=this._workerInfos;i<e.length;i++){var o=e[i];o.worker.terminate()}this._workerInfos=[],this._pendingActions=[]},a.prototype.push=function(i){for(var e=0,o=this._workerInfos;e<o.length;e++){var s=o[e];if(!s.active){this._execute(s,i);return}}this._pendingActions.push(i)},a.prototype._execute=function(i,e){var o=this;i.active=!0,e(i.worker,function(){i.active=!1;var s=o._pendingActions.shift();s&&o._execute(i,s)})},a}();function createDecoderAsync(a){return new Promise(function(i){DracoDecoderModule({wasmBinary:a}).then(function(e){i({module:e})})})}function decodeMesh(a,i,e,o,s){var c=new a.DecoderBuffer;c.Init(i,i.byteLength);var d=new a.Decoder,_,b;try{var k=d.GetEncodedGeometryType(c);switch(k){case a.TRIANGULAR_MESH:_=new a.Mesh,b=d.DecodeBufferToMesh(c,_);break;case a.POINT_CLOUD:_=new a.PointCloud,b=d.DecodeBufferToPointCloud(c,_);break;default:throw new Error("Invalid geometry type "+k)}if(!b.ok()||!_.ptr)throw new Error(b.error_msg());if(k===a.TRIANGULAR_MESH){var j=_.num_faces(),$=j*3,_e=$*4,et=a._malloc(_e);try{d.GetTrianglesUInt32Array(_,_e,et);var tt=new Uint32Array($);tt.set(new Uint32Array(a.HEAPF32.buffer,et,$)),o(tt)}finally{a._free(et)}}var rt=function(st,ut){var ft=ut.num_components(),lt=_.num_points(),ht=lt*ft,pt=ht*Float32Array.BYTES_PER_ELEMENT,mt=a._malloc(pt);try{d.GetAttributeDataArrayForAllPoints(_,ut,a.DT_FLOAT32,pt,mt);var dt=new Float32Array(a.HEAPF32.buffer,mt,ht);if(st==="color"&&ft===3){for(var gt=new Float32Array(lt*4),_t=0,yt=0;_t<gt.length;_t+=4,yt+=ft)gt[_t+0]=dt[yt+0],gt[_t+1]=dt[yt+1],gt[_t+2]=dt[yt+2],gt[_t+3]=1;s(st,gt)}else{var gt=new Float32Array(ht);gt.set(new Float32Array(a.HEAPF32.buffer,mt,ht)),s(st,gt)}}finally{a._free(mt)}};if(e)for(var it in e){var nt=e[it],ot=d.GetAttributeByUniqueId(_,nt);rt(it,ot)}else{var at={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"};for(var it in at){var nt=d.GetAttributeId(_,a[at[it]]);if(nt!==-1){var ot=d.GetAttribute(_,nt);rt(it,ot)}}}}finally{_&&a.destroy(_),a.destroy(d),a.destroy(c)}}function worker$1(){var a;onmessage=function(i){var e=i.data;switch(e.id){case"init":{var o=e.decoder;o.url&&(importScripts(o.url),a=DracoDecoderModule({wasmBinary:o.wasmBinary})),postMessage("done");break}case"decodeMesh":{if(!a)throw new Error("Draco decoder module is not available");a.then(function(s){decodeMesh(s,e.dataView,e.attributes,function(c){postMessage({id:"indices",value:c},[c.buffer])},function(c,d){postMessage({id:c,value:d},[d.buffer])}),postMessage("done")});break}}}}var DracoCompression=function(){function a(i){i===void 0&&(i=a.DefaultNumWorkers);var e=a.Configuration.decoder,o=e.wasmUrl&&e.wasmBinaryUrl&&typeof WebAssembly=="object"?{url:Tools.GetAbsoluteUrl(e.wasmUrl),wasmBinaryPromise:Tools.LoadFileAsync(Tools.GetAbsoluteUrl(e.wasmBinaryUrl))}:{url:Tools.GetAbsoluteUrl(e.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};i&&typeof Worker=="function"?this._workerPoolPromise=o.wasmBinaryPromise.then(function(s){for(var c=decodeMesh+"("+worker$1+")()",d=URL.createObjectURL(new Blob([c],{type:"application/javascript"})),_=new Array(i),b=0;b<_.length;b++)_[b]=new Promise(function(k,j){var $=new Worker(d),_e=function(tt){$.removeEventListener("error",_e),$.removeEventListener("message",et),j(tt)},et=function(tt){tt.data==="done"&&($.removeEventListener("error",_e),$.removeEventListener("message",et),k($))};$.addEventListener("error",_e),$.addEventListener("message",et),$.postMessage({id:"init",decoder:{url:o.url,wasmBinary:s}})});return Promise.all(_).then(function(k){return new WorkerPool(k)})}):this._decoderModulePromise=o.wasmBinaryPromise.then(function(s){if(!o.url)throw new Error("Draco decoder module is not available");return Tools.LoadScriptAsync(o.url).then(function(){return createDecoderAsync(s)})})}return Object.defineProperty(a,"DecoderAvailable",{get:function(){var i=a.Configuration.decoder;return!!(i.wasmUrl&&i.wasmBinaryUrl&&typeof WebAssembly=="object"||i.fallbackUrl)},enumerable:!1,configurable:!0}),a.GetDefaultNumWorkers=function(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)},Object.defineProperty(a,"Default",{get:function(){return a._Default||(a._Default=new a),a._Default},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this._workerPoolPromise&&this._workerPoolPromise.then(function(i){i.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise},a.prototype.whenReadyAsync=function(){return this._workerPoolPromise?this._workerPoolPromise.then(function(){}):this._decoderModulePromise?this._decoderModulePromise.then(function(){}):Promise.resolve()},a.prototype.decodeMeshAsync=function(i,e){var o=i instanceof ArrayBuffer?new Uint8Array(i):i;if(this._workerPoolPromise)return this._workerPoolPromise.then(function(s){return new Promise(function(c,d){s.push(function(_,b){var k=new VertexData,j=function(et){_.removeEventListener("error",j),_.removeEventListener("message",$),d(et),b()},$=function(et){et.data==="done"?(_.removeEventListener("error",j),_.removeEventListener("message",$),c(k),b()):et.data.id==="indices"?k.indices=et.data.value:k.set(et.data.value,et.data.id)};_.addEventListener("error",j),_.addEventListener("message",$);var _e=new Uint8Array(o.byteLength);_e.set(new Uint8Array(o.buffer,o.byteOffset,o.byteLength)),_.postMessage({id:"decodeMesh",dataView:_e,attributes:e},[_e.buffer])})})});if(this._decoderModulePromise)return this._decoderModulePromise.then(function(s){var c=new VertexData;return decodeMesh(s.module,o,e,function(d){c.indices=d},function(d,_){c.set(_,d)}),c});throw new Error("Draco decoder module is not available")},a.Configuration={decoder:{wasmUrl:"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://preview.babylonjs.com/draco_decoder_gltf.wasm",fallbackUrl:"https://preview.babylonjs.com/draco_decoder_gltf.js"}},a.DefaultNumWorkers=a.GetDefaultNumWorkers(),a._Default=null,a}(),NAME$q="KHR_draco_mesh_compression",KHR_draco_mesh_compression=function(){function a(i){this.name=NAME$q,this._loader=i,this.enabled=DracoCompression.DecoderAvailable&&this._loader.isExtensionUsed(NAME$q)}return a.prototype.dispose=function(){delete this.dracoCompression,this._loader=null},a.prototype._loadVertexDataAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){if(e.mode!=null){if(e.mode!==5&&e.mode!==4)throw new Error(i+": Unsupported mode "+e.mode);if(e.mode===5)throw new Error(i+": Mode "+e.mode+" is not currently supported")}var _={},b=function(j,$){var _e=d.attributes[j];_e!=null&&(o._delayInfo=o._delayInfo||[],o._delayInfo.indexOf($)===-1&&o._delayInfo.push($),_[$]=_e)};b("POSITION",VertexBuffer.PositionKind),b("NORMAL",VertexBuffer.NormalKind),b("TANGENT",VertexBuffer.TangentKind),b("TEXCOORD_0",VertexBuffer.UVKind),b("TEXCOORD_1",VertexBuffer.UV2Kind),b("TEXCOORD_2",VertexBuffer.UV3Kind),b("TEXCOORD_3",VertexBuffer.UV4Kind),b("TEXCOORD_4",VertexBuffer.UV5Kind),b("TEXCOORD_5",VertexBuffer.UV6Kind),b("JOINTS_0",VertexBuffer.MatricesIndicesKind),b("WEIGHTS_0",VertexBuffer.MatricesWeightsKind),b("COLOR_0",VertexBuffer.ColorKind);var k=ArrayItem.Get(c,s._loader.gltf.bufferViews,d.bufferView);return k._dracoBabylonGeometry||(k._dracoBabylonGeometry=s._loader.loadBufferViewAsync("/bufferViews/"+k.index,k).then(function(j){var $=s.dracoCompression||DracoCompression.Default;return $.decodeMeshAsync(j,_).then(function(_e){var et=new Geometry(o.name,s._loader.babylonScene);return _e.applyToGeometry(et),et}).catch(function(_e){throw new Error(i+": "+_e.message)})})),k._dracoBabylonGeometry})},a}();GLTFLoader.RegisterExtension(NAME$q,function(a){return new KHR_draco_mesh_compression(a)});var NAME$p="KHR_lights_punctual",KHR_lights=function(){function a(i){this.name=NAME$p,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$p)}return a.prototype.dispose=function(){this._loader=null,delete this._lights},a.prototype.onLoading=function(){var i=this._loader.gltf.extensions;if(i&&i[this.name]){var e=i[this.name];this._lights=e.lights}},a.prototype.loadNodeAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){return s._loader.loadNodeAsync(i,e,function(_){var b,k=ArrayItem.Get(c,s._lights,d.light),j=k.name||_.name;switch(s._loader.babylonScene._blockEntityCollection=!!s._loader._assetContainer,k.type){case"directional":{b=new DirectionalLight(j,Vector3.Backward(),s._loader.babylonScene);break}case"point":{b=new PointLight(j,Vector3.Zero(),s._loader.babylonScene);break}case"spot":{var $=new SpotLight(j,Vector3.Zero(),Vector3.Backward(),0,1,s._loader.babylonScene);$.angle=(k.spot&&k.spot.outerConeAngle||Math.PI/4)*2,$.innerAngle=(k.spot&&k.spot.innerConeAngle||0)*2,b=$;break}default:throw s._loader.babylonScene._blockEntityCollection=!1,new Error(c+": Invalid light type ("+k.type+")")}b._parentContainer=s._loader._assetContainer,s._loader.babylonScene._blockEntityCollection=!1,b.falloffType=Light.FALLOFF_GLTF,b.diffuse=k.color?Color3.FromArray(k.color):Color3.White(),b.intensity=k.intensity==null?1:k.intensity,b.range=k.range==null?Number.MAX_VALUE:k.range,b.parent=_,s._loader._babylonLights.push(b),GLTFLoader.AddPointerMetadata(b,c),o(_)})})},a}();GLTFLoader.RegisterExtension(NAME$p,function(a){return new KHR_lights(a)});var NAME$o="KHR_materials_pbrSpecularGlossiness",KHR_materials_pbrSpecularGlossiness=function(){function a(i){this.name=NAME$o,this.order=200,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$o)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialBasePropertiesAsync(i,e,o)),_.push(s._loadSpecularGlossinessPropertiesAsync(c,e,d,o)),s._loader.loadMaterialAlphaProperties(i,e,o),Promise.all(_).then(function(){})})},a.prototype._loadSpecularGlossinessPropertiesAsync=function(i,e,o,s){if(!(s instanceof PBRMaterial))throw new Error(i+": Material type not supported");var c=new Array;return s.metallic=null,s.roughness=null,o.diffuseFactor?(s.albedoColor=Color3.FromArray(o.diffuseFactor),s.alpha=o.diffuseFactor[3]):s.albedoColor=Color3.White(),s.reflectivityColor=o.specularFactor?Color3.FromArray(o.specularFactor):Color3.White(),s.microSurface=o.glossinessFactor==null?1:o.glossinessFactor,o.diffuseTexture&&c.push(this._loader.loadTextureInfoAsync(i+"/diffuseTexture",o.diffuseTexture,function(d){d.name=s.name+" (Diffuse)",s.albedoTexture=d})),o.specularGlossinessTexture&&(c.push(this._loader.loadTextureInfoAsync(i+"/specularGlossinessTexture",o.specularGlossinessTexture,function(d){d.name=s.name+" (Specular Glossiness)",s.reflectivityTexture=d})),s.reflectivityTexture.hasAlpha=!0,s.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(c).then(function(){})},a}();GLTFLoader.RegisterExtension(NAME$o,function(a){return new KHR_materials_pbrSpecularGlossiness(a)});var NAME$n="KHR_materials_unlit",KHR_materials_unlit$1=function(){function a(i){this.name=NAME$n,this.order=210,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$n)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(){return s._loadUnlitPropertiesAsync(i,e,o)})},a.prototype._loadUnlitPropertiesAsync=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var s=new Array;o.unlit=!0;var c=e.pbrMetallicRoughness;return c&&(c.baseColorFactor?(o.albedoColor=Color3.FromArray(c.baseColorFactor),o.alpha=c.baseColorFactor[3]):o.albedoColor=Color3.White(),c.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(i+"/baseColorTexture",c.baseColorTexture,function(d){d.name=o.name+" (Base Color)",o.albedoTexture=d}))),e.doubleSided&&(o.backFaceCulling=!1,o.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(i,e,o),Promise.all(s).then(function(){})},a}();GLTFLoader.RegisterExtension(NAME$n,function(a){return new KHR_materials_unlit$1(a)});var NAME$m="KHR_materials_clearcoat",KHR_materials_clearcoat$1=function(){function a(i){this.name=NAME$m,this.order=190,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$m)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialPropertiesAsync(i,e,o)),_.push(s._loadClearCoatPropertiesAsync(c,d,o)),Promise.all(_).then(function(){})})},a.prototype._loadClearCoatPropertiesAsync=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var s=new Array;return o.clearCoat.isEnabled=!0,o.clearCoat.useRoughnessFromMainTexture=!1,o.clearCoat.remapF0OnInterfaceChange=!1,e.clearcoatFactor!=null?o.clearCoat.intensity=e.clearcoatFactor:o.clearCoat.intensity=0,e.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(i+"/clearcoatTexture",e.clearcoatTexture,function(c){c.name=o.name+" (ClearCoat Intensity)",o.clearCoat.texture=c})),e.clearcoatRoughnessFactor!=null?o.clearCoat.roughness=e.clearcoatRoughnessFactor:o.clearCoat.roughness=0,e.clearcoatRoughnessTexture&&(e.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(i+"/clearcoatRoughnessTexture",e.clearcoatRoughnessTexture,function(c){c.name=o.name+" (ClearCoat Roughness)",o.clearCoat.textureRoughness=c}))),e.clearcoatNormalTexture&&(e.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(i+"/clearcoatNormalTexture",e.clearcoatNormalTexture,function(c){c.name=o.name+" (ClearCoat Normal)",o.clearCoat.bumpTexture=c})),o.invertNormalMapX=!o.getScene().useRightHandedSystem,o.invertNormalMapY=o.getScene().useRightHandedSystem,e.clearcoatNormalTexture.scale!=null&&(o.clearCoat.bumpTexture.level=e.clearcoatNormalTexture.scale)),Promise.all(s).then(function(){})},a}();GLTFLoader.RegisterExtension(NAME$m,function(a){return new KHR_materials_clearcoat$1(a)});var NAME$l="KHR_materials_emissive_strength",KHR_materials_emissive_strength=function(){function a(i){this.name=NAME$l,this.order=170,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$l)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){return s._loader.loadMaterialPropertiesAsync(i,e,o).then(function(){s._loadEmissiveProperties(c,d,o)})})},a.prototype._loadEmissiveProperties=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");e.emissiveStrength!==void 0&&o.emissiveColor.scaleToRef(e.emissiveStrength,o.emissiveColor)},a}();GLTFLoader.RegisterExtension(NAME$l,function(a){return new KHR_materials_emissive_strength(a)});var NAME$k="KHR_materials_sheen",KHR_materials_sheen$1=function(){function a(i){this.name=NAME$k,this.order=190,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$k)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialPropertiesAsync(i,e,o)),_.push(s._loadSheenPropertiesAsync(c,d,o)),Promise.all(_).then(function(){})})},a.prototype._loadSheenPropertiesAsync=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var s=new Array;return o.sheen.isEnabled=!0,o.sheen.intensity=1,e.sheenColorFactor!=null?o.sheen.color=Color3.FromArray(e.sheenColorFactor):o.sheen.color=Color3.Black(),e.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(i+"/sheenColorTexture",e.sheenColorTexture,function(c){c.name=o.name+" (Sheen Color)",o.sheen.texture=c})),e.sheenRoughnessFactor!==void 0?o.sheen.roughness=e.sheenRoughnessFactor:o.sheen.roughness=0,e.sheenRoughnessTexture&&(e.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(i+"/sheenRoughnessTexture",e.sheenRoughnessTexture,function(c){c.name=o.name+" (Sheen Roughness)",o.sheen.textureRoughness=c}))),o.sheen.albedoScaling=!0,o.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then(function(){})},a}();GLTFLoader.RegisterExtension(NAME$k,function(a){return new KHR_materials_sheen$1(a)});var NAME$j="KHR_materials_specular",KHR_materials_specular=function(){function a(i){this.name=NAME$j,this.order=190,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$j)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialPropertiesAsync(i,e,o)),_.push(s._loadSpecularPropertiesAsync(c,d,o)),Promise.all(_).then(function(){})})},a.prototype._loadSpecularPropertiesAsync=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var s=new Array;return e.specularFactor!==void 0&&(o.metallicF0Factor=e.specularFactor),e.specularColorFactor!==void 0&&(o.metallicReflectanceColor=Color3.FromArray(e.specularColorFactor)),e.specularTexture&&(e.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(i+"/specularTexture",e.specularTexture,function(c){c.name=o.name+" (Specular F0 Strength)",o.metallicReflectanceTexture=c,o.useOnlyMetallicFromMetallicReflectanceTexture=!0}))),e.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(i+"/specularColorTexture",e.specularColorTexture,function(c){c.name=o.name+" (Specular F0 Color)",o.reflectanceTexture=c})),Promise.all(s).then(function(){})},a}();GLTFLoader.RegisterExtension(NAME$j,function(a){return new KHR_materials_specular(a)});var NAME$i="KHR_materials_ior",KHR_materials_ior=function(){function a(i){this.name=NAME$i,this.order=180,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$i)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialPropertiesAsync(i,e,o)),_.push(s._loadIorPropertiesAsync(c,d,o)),Promise.all(_).then(function(){})})},a.prototype._loadIorPropertiesAsync=function(i,e,o){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");return e.ior!==void 0?o.indexOfRefraction=e.ior:o.indexOfRefraction=a._DEFAULT_IOR,Promise.resolve()},a._DEFAULT_IOR=1.5,a}();GLTFLoader.RegisterExtension(NAME$i,function(a){return new KHR_materials_ior(a)});var NAME$h="KHR_materials_variants",KHR_materials_variants=function(){function a(i){this.name=NAME$h,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$h)}return a.prototype.dispose=function(){this._loader=null},a.GetAvailableVariants=function(i){var e=this._GetExtensionMetadata(i);return e?Object.keys(e.variants):[]},a.prototype.getAvailableVariants=function(i){return a.GetAvailableVariants(i)},a.SelectVariant=function(i,e){var o=this._GetExtensionMetadata(i);if(!o)throw new Error("Cannot select variant on a glTF mesh that does not have the "+NAME$h+" extension");var s=function(b){var k=o.variants[b];if(k)for(var j=0,$=k;j<$.length;j++){var _e=$[j];_e.mesh.material=_e.material}};if(e instanceof Array)for(var c=0,d=e;c<d.length;c++){var _=d[c];s(_)}else s(e);o.lastSelected=e},a.prototype.selectVariant=function(i,e){return a.SelectVariant(i,e)},a.Reset=function(i){var e=this._GetExtensionMetadata(i);if(!e)throw new Error("Cannot reset on a glTF mesh that does not have the "+NAME$h+" extension");for(var o=0,s=e.original;o<s.length;o++){var c=s[o];c.mesh.material=c.material}e.lastSelected=null},a.prototype.reset=function(i){return a.Reset(i)},a.GetLastSelectedVariant=function(i){var e=this._GetExtensionMetadata(i);if(!e)throw new Error("Cannot get the last selected variant on a glTF mesh that does not have the "+NAME$h+" extension");return e.lastSelected},a.prototype.getLastSelectedVariant=function(i){return a.GetLastSelectedVariant(i)},a._GetExtensionMetadata=function(i){var e,o;return((o=(e=i==null?void 0:i.metadata)===null||e===void 0?void 0:e.gltf)===null||o===void 0?void 0:o[NAME$h])||null},a.prototype.onLoading=function(){var i=this._loader.gltf.extensions;if(i&&i[this.name]){var e=i[this.name];this._variants=e.variants}},a.prototype._loadMeshPrimitiveAsync=function(i,e,o,s,c,d){var _=this;return GLTFLoader.LoadExtensionAsync(i,c,this.name,function(b,k){var j=new Array;return j.push(_._loader._loadMeshPrimitiveAsync(i,e,o,s,c,function($){if(d($),$ instanceof Mesh){var _e=GLTFLoader._GetDrawMode(i,c.mode),et=_._loader.rootBabylonMesh,tt=et?et.metadata=et.metadata||{}:{},rt=tt.gltf=tt.gltf||{},it=rt[NAME$h]=rt[NAME$h]||{lastSelected:null,original:[],variants:{}};it.original.push({mesh:$,material:$.material});for(var nt=function(at){var st=k.mappings[at],ut=ArrayItem.Get(b+"/mappings/"+at+"/material",_._loader.gltf.materials,st.material);j.push(_._loader._loadMaterialAsync("#/materials/"+st.material,ut,$,_e,function(ft){for(var lt=function(pt){var mt=st.variants[pt],dt=ArrayItem.Get("/extensions/"+NAME$h+"/variants/"+mt,_._variants,mt);it.variants[dt.name]=it.variants[dt.name]||[],it.variants[dt.name].push({mesh:$,material:ft}),$.onClonedObservable.add(function(gt){var _t=gt,yt=null,Tt=_t;do{if(Tt=Tt.parent,!Tt)return;yt=a._GetExtensionMetadata(Tt)}while(yt===null);if(et&&yt===a._GetExtensionMetadata(et)){Tt.metadata={};for(var St in et.metadata)Tt.metadata[St]=et.metadata[St];Tt.metadata.gltf=[];for(var St in et.metadata.gltf)Tt.metadata.gltf[St]=et.metadata.gltf[St];Tt.metadata.gltf[NAME$h]={lastSelected:null,original:[],variants:{}};for(var At=0,vt=yt.original;At<vt.length;At++){var Et=vt[At];Tt.metadata.gltf[NAME$h].original.push({mesh:Et.mesh,material:Et.material})}for(var St in yt.variants)if(yt.variants.hasOwnProperty(St)){Tt.metadata.gltf[NAME$h].variants[St]=[];for(var xt=0,bt=yt.variants[St];xt<bt.length;xt++){var Mt=bt[xt];Tt.metadata.gltf[NAME$h].variants[St].push({mesh:Mt.mesh,material:Mt.material})}}yt=Tt.metadata.gltf[NAME$h]}for(var Rt=0,Pt=yt.original;Rt<Pt.length;Rt++){var It=Pt[Rt];It.mesh===$&&(It.mesh=_t)}for(var Dt=0,Ct=yt.variants[dt.name];Dt<Ct.length;Dt++){var It=Ct[Dt];It.mesh===$&&(It.mesh=_t)}})},ht=0;ht<st.variants.length;++ht)lt(ht)}))},ot=0;ot<k.mappings.length;++ot)nt(ot)}})),Promise.all(j).then(function($){var _e=$[0];return _e})})},a}();GLTFLoader.RegisterExtension(NAME$h,function(a){return new KHR_materials_variants(a)});var TransmissionHelper=function(){function a(i,e){var o=this;this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options=__assign(__assign({},a._getDefaultOptions()),i),this._scene=e,this._scene._transmissionHelper=this,this.onErrorObservable=new Observable,this._scene.onDisposeObservable.addOnce(function(s){o.dispose()}),this._parseScene(),this._setupRenderTargets()}return a._getDefaultOptions=function(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Constants.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}},a.prototype.updateOptions=function(i){var e=this,o=Object.keys(i).filter(function(d){return e._options[d]!==i[d]});if(!!o.length){var s=__assign(__assign({},this._options),i),c=this._options;this._options=s,s.renderSize!==c.renderSize||s.renderTargetTextureType!==c.renderTargetTextureType||s.generateMipmaps!==c.generateMipmaps||!this._opaqueRenderTarget?this._setupRenderTargets():(this._opaqueRenderTarget.samples=s.samples,this._opaqueRenderTarget.lodGenerationScale=s.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=s.lodGenerationOffset)}},a.prototype.getOpaqueTarget=function(){return this._opaqueRenderTarget},a.prototype.shouldRenderAsTransmission=function(i){return i?!!(i instanceof PBRMaterial&&i.subSurface.isRefractionEnabled):!1},a.prototype._addMesh=function(i){var e=this;this._materialObservers[i.uniqueId]=i.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Tools.SetImmediate(function(){e.shouldRenderAsTransmission(i.material)?(i.material.refractionTexture=e._opaqueRenderTarget,e._transparentMeshesCache.push(i)):e._opaqueMeshesCache.push(i)})},a.prototype._removeMesh=function(i){i.onMaterialChangedObservable.remove(this._materialObservers[i.uniqueId]),delete this._materialObservers[i.uniqueId];var e=this._transparentMeshesCache.indexOf(i);e!==-1&&this._transparentMeshesCache.splice(e,1),e=this._opaqueMeshesCache.indexOf(i),e!==-1&&this._opaqueMeshesCache.splice(e,1)},a.prototype._parseScene=function(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))},a.prototype._onMeshMaterialChanged=function(i){var e=this._transparentMeshesCache.indexOf(i),o=this._opaqueMeshesCache.indexOf(i),s=this.shouldRenderAsTransmission(i.material);s?(i.material instanceof PBRMaterial&&(i.material.subSurface.refractionTexture=this._opaqueRenderTarget),o!==-1?(this._opaqueMeshesCache.splice(o,1),this._transparentMeshesCache.push(i)):e===-1&&this._transparentMeshesCache.push(i)):e!==-1?(this._transparentMeshesCache.splice(e,1),this._opaqueMeshesCache.push(i)):o===-1&&this._opaqueMeshesCache.push(i)},a.prototype._setupRenderTargets=function(){var i=this,e,o;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new RenderTargetTexture("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=(o=(e=this._options.clearColor)===null||e===void 0?void 0:e.clone())!==null&&o!==void 0?o:this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples;var s,c;this._opaqueRenderTarget.onBeforeBindObservable.add(function(d){c=i._scene.environmentIntensity,i._scene.environmentIntensity=1,s=i._scene.imageProcessingConfiguration.applyByPostProcess,i._options.clearColor?d.clearColor.copyFrom(i._options.clearColor):i._scene.clearColor.toLinearSpaceToRef(d.clearColor),i._scene.imageProcessingConfiguration._applyByPostProcess=!0}),this._opaqueRenderTarget.onAfterUnbindObservable.add(function(){i._scene.environmentIntensity=c,i._scene.imageProcessingConfiguration._applyByPostProcess=s}),this._transparentMeshesCache.forEach(function(d){i.shouldRenderAsTransmission(d.material)&&(d.material.refractionTexture=i._opaqueRenderTarget)})},a.prototype.dispose=function(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]},a}(),NAME$g="KHR_materials_transmission",KHR_materials_transmission=function(){function a(i){this.name=NAME$g,this.order=175,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$g),this.enabled&&(i.parent.transparencyAsCoverage=!0)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialBasePropertiesAsync(i,e,o)),_.push(s._loader.loadMaterialPropertiesAsync(i,e,o)),_.push(s._loadTransparentPropertiesAsync(c,e,o,d)),Promise.all(_).then(function(){})})},a.prototype._loadTransparentPropertiesAsync=function(i,e,o,s){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var c=o;if(c.subSurface.isRefractionEnabled=!0,c.subSurface.volumeIndexOfRefraction=1,c.subSurface.useAlbedoToTintRefraction=!0,s.transmissionFactor!==void 0){c.subSurface.refractionIntensity=s.transmissionFactor;var d=c.getScene();c.subSurface.refractionIntensity&&!d._transmissionHelper&&new TransmissionHelper({},c.getScene())}else return c.subSurface.refractionIntensity=0,c.subSurface.isRefractionEnabled=!1,Promise.resolve();return c.subSurface.minimumThickness=0,c.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(i+"/transmissionTexture",s.transmissionTexture,void 0).then(function(_){c.subSurface.refractionIntensityTexture=_,c.subSurface.useGltfStyleTextures=!0})):Promise.resolve()},a}();GLTFLoader.RegisterExtension(NAME$g,function(a){return new KHR_materials_transmission(a)});var NAME$f="KHR_materials_translucency",KHR_materials_translucency=function(){function a(i){this.name=NAME$f,this.order=174,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$f),this.enabled&&(i.parent.transparencyAsCoverage=!0)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialBasePropertiesAsync(i,e,o)),_.push(s._loader.loadMaterialPropertiesAsync(i,e,o)),_.push(s._loadTranslucentPropertiesAsync(c,e,o,d)),Promise.all(_).then(function(){})})},a.prototype._loadTranslucentPropertiesAsync=function(i,e,o,s){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");var c=o;if(c.subSurface.isTranslucencyEnabled=!0,c.subSurface.volumeIndexOfRefraction=1,c.subSurface.minimumThickness=0,c.subSurface.maximumThickness=0,c.subSurface.useAlbedoToTintTranslucency=!0,s.translucencyFactor!==void 0)c.subSurface.translucencyIntensity=s.translucencyFactor;else return c.subSurface.translucencyIntensity=0,c.subSurface.isTranslucencyEnabled=!1,Promise.resolve();return s.translucencyTexture?(s.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(i+"/translucencyTexture",s.translucencyTexture).then(function(d){c.subSurface.translucencyIntensityTexture=d})):Promise.resolve()},a}();GLTFLoader.RegisterExtension(NAME$f,function(a){return new KHR_materials_translucency(a)});var NAME$e="KHR_materials_volume",KHR_materials_volume=function(){function a(i){this.name=NAME$e,this.order=173,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$e),this.enabled&&this._loader._disableInstancedMesh++}return a.prototype.dispose=function(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return _.push(s._loader.loadMaterialBasePropertiesAsync(i,e,o)),_.push(s._loader.loadMaterialPropertiesAsync(i,e,o)),_.push(s._loadVolumePropertiesAsync(c,e,o,d)),Promise.all(_).then(function(){})})},a.prototype._loadVolumePropertiesAsync=function(i,e,o,s){if(!(o instanceof PBRMaterial))throw new Error(i+": Material type not supported");if(!o.subSurface.isRefractionEnabled&&!o.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();o.subSurface.volumeIndexOfRefraction=o.indexOfRefraction;var c=s.attenuationDistance!==void 0?s.attenuationDistance:Number.MAX_VALUE;return o.subSurface.tintColorAtDistance=c,s.attenuationColor!==void 0&&s.attenuationColor.length==3&&o.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),o.subSurface.minimumThickness=0,o.subSurface.maximumThickness=s.thicknessFactor,o.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(i+"/thicknessTexture",s.thicknessTexture).then(function(d){o.subSurface.thicknessTexture=d,o.subSurface.useGltfStyleTextures=!0})):Promise.resolve()},a}();GLTFLoader.RegisterExtension(NAME$e,function(a){return new KHR_materials_volume(a)});var NAME$d="KHR_mesh_quantization",KHR_mesh_quantization=function(){function a(i){this.name=NAME$d,this.enabled=i.isExtensionUsed(NAME$d)}return a.prototype.dispose=function(){},a}();GLTFLoader.RegisterExtension(NAME$d,function(a){return new KHR_mesh_quantization(a)});var NAME$c="KHR_texture_basisu",KHR_texture_basisu=function(){function a(i){this.name=NAME$c,this._loader=i,this.enabled=i.isExtensionUsed(NAME$c)}return a.prototype.dispose=function(){this._loader=null},a.prototype._loadTextureAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=e.sampler==null?GLTFLoader.DefaultSampler:ArrayItem.Get(i+"/sampler",s._loader.gltf.samplers,e.sampler),b=ArrayItem.Get(c+"/source",s._loader.gltf.images,d.source);return s._loader._createTextureAsync(i,_,b,function(k){o(k)},e._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!e._textureInfo.nonColorData)})},a}();GLTFLoader.RegisterExtension(NAME$c,function(a){return new KHR_texture_basisu(a)});var NAME$b="KHR_texture_transform",KHR_texture_transform$1=function(){function a(i){this.name=NAME$b,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$b)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadTextureInfoAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){return s._loader.loadTextureInfoAsync(i,e,function(_){if(!(_ instanceof Texture))throw new Error(c+": Texture type not supported");d.offset&&(_.uOffset=d.offset[0],_.vOffset=d.offset[1]),_.uRotationCenter=0,_.vRotationCenter=0,d.rotation&&(_.wAng=-d.rotation),d.scale&&(_.uScale=d.scale[0],_.vScale=d.scale[1]),d.texCoord!=null&&(_.coordinatesIndex=d.texCoord),o(_)})})},a}();GLTFLoader.RegisterExtension(NAME$b,function(a){return new KHR_texture_transform$1(a)});var NAME$a="KHR_xmp_json_ld",KHR_xmp_json_ld=function(){function a(i){this.name=NAME$a,this.order=100,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$a)}return a.prototype.dispose=function(){this._loader=null},a.prototype.onLoading=function(){var i,e,o;if(this._loader.rootBabylonMesh!==null){var s=(i=this._loader.gltf.extensions)===null||i===void 0?void 0:i.KHR_xmp_json_ld,c=(o=(e=this._loader.gltf.asset)===null||e===void 0?void 0:e.extensions)===null||o===void 0?void 0:o.KHR_xmp_json_ld;if(s&&c){var d=+c.packet;s.packets&&d<s.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=s.packets[d])}}},a}();GLTFLoader.RegisterExtension(NAME$a,function(a){return new KHR_xmp_json_ld(a)});var AnimationEvent=function(){function a(i,e,o){this.frame=i,this.action=e,this.onlyOnce=o,this.isDone=!1}return a.prototype._clone=function(){return new a(this.frame,this.action,this.onlyOnce)},a}(),WeightedSound=function(){function a(i,e,o){var s=this;if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],e.length!==o.length)throw new Error("Sounds length does not equal weights length");this.loop=i,this._weights=o;for(var c=0,d=0,_=o;d<_.length;d++){var b=_[d];c+=b}for(var k=c>0?1/c:0,j=0;j<this._weights.length;j++)this._weights[j]*=k;this._sounds=e;for(var $=0,_e=this._sounds;$<_e.length;$++){var et=_e[$];et.onEndedObservable.add(function(){s._onended()})}}return Object.defineProperty(a.prototype,"directionalConeInnerAngle",{get:function(){return this._coneInnerAngle},set:function(i){if(i!==this._coneInnerAngle){if(this._coneOuterAngle<i){Logger$2.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=i;for(var e=0,o=this._sounds;e<o.length;e++){var s=o[e];s.directionalConeInnerAngle=i}}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"directionalConeOuterAngle",{get:function(){return this._coneOuterAngle},set:function(i){if(i!==this._coneOuterAngle){if(i<this._coneInnerAngle){Logger$2.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneOuterAngle=i;for(var e=0,o=this._sounds;e<o.length;e++){var s=o[e];s.directionalConeOuterAngle=i}}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"volume",{get:function(){return this._volume},set:function(i){if(i!==this._volume)for(var e=0,o=this._sounds;e<o.length;e++){var s=o[e];s.setVolume(i)}},enumerable:!1,configurable:!0}),a.prototype._onended=function(){this._currentIndex!==void 0&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1},a.prototype.pause=function(){this.isPaused=!0,this._currentIndex!==void 0&&this._sounds[this._currentIndex].pause()},a.prototype.stop=function(){this.isPlaying=!1,this._currentIndex!==void 0&&this._sounds[this._currentIndex].stop()},a.prototype.play=function(i){if(!this.isPaused){this.stop();for(var e=Math.random(),o=0,s=0;s<this._weights.length;s++)if(o+=this._weights[s],e<=o){this._currentIndex=s;break}}var c=this._sounds[this._currentIndex];c.isReady()?c.play(0,this.isPaused?void 0:i):c.autoplay=!0,this.isPlaying=!0,this.isPaused=!1},a}(),NAME$9="MSFT_audio_emitter",MSFT_audio_emitter=function(){function a(i){this.name=NAME$9,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$9)}return a.prototype.dispose=function(){this._loader=null,this._clips=null,this._emitters=null},a.prototype.onLoading=function(){var i=this._loader.gltf.extensions;if(i&&i[this.name]){var e=i[this.name];this._clips=e.clips,this._emitters=e.emitters,ArrayItem.Assign(this._clips),ArrayItem.Assign(this._emitters)}},a.prototype.loadSceneAsync=function(i,e){var o=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(s,c){var d=new Array;d.push(o._loader.loadSceneAsync(i,e));for(var _=0,b=c.emitters;_<b.length;_++){var k=b[_],j=ArrayItem.Get(s+"/emitters",o._emitters,k);if(j.refDistance!=null||j.maxDistance!=null||j.rolloffFactor!=null||j.distanceModel!=null||j.innerAngle!=null||j.outerAngle!=null)throw new Error(s+": Direction or Distance properties are not allowed on emitters attached to a scene");d.push(o._loadEmitterAsync(s+"/emitters/"+j.index,j))}return Promise.all(d).then(function(){})})},a.prototype.loadNodeAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _=new Array;return s._loader.loadNodeAsync(c,e,function(b){for(var k=function(et){var tt=ArrayItem.Get(c+"/emitters",s._emitters,et);_.push(s._loadEmitterAsync(c+"/emitters/"+tt.index,tt).then(function(){for(var rt=0,it=tt._babylonSounds;rt<it.length;rt++){var nt=it[rt];nt.attachToMesh(b),(tt.innerAngle!=null||tt.outerAngle!=null)&&(nt.setLocalDirectionToMesh(Vector3.Forward()),nt.setDirectionalCone(2*Tools.ToDegrees(tt.innerAngle==null?Math.PI:tt.innerAngle),2*Tools.ToDegrees(tt.outerAngle==null?Math.PI:tt.outerAngle),0))}}))},j=0,$=d.emitters;j<$.length;j++){var _e=$[j];k(_e)}o(b)}).then(function(b){return Promise.all(_).then(function(){return b})})})},a.prototype.loadAnimationAsync=function(i,e){var o=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(s,c){return o._loader.loadAnimationAsync(i,e).then(function(d){var _=new Array;ArrayItem.Assign(c.events);for(var b=0,k=c.events;b<k.length;b++){var j=k[b];_.push(o._loadAnimationEventAsync(s+"/events/"+j.index,i,e,j,d))}return Promise.all(_).then(function(){return d})})})},a.prototype._loadClipAsync=function(i,e){if(e._objectURL)return e._objectURL;var o;if(e.uri)o=this._loader.loadUriAsync(i,e,e.uri);else{var s=ArrayItem.Get(i+"/bufferView",this._loader.gltf.bufferViews,e.bufferView);o=this._loader.loadBufferViewAsync("/bufferViews/"+s.index,s)}return e._objectURL=o.then(function(c){return URL.createObjectURL(new Blob([c],{type:e.mimeType}))}),e._objectURL},a.prototype._loadEmitterAsync=function(i,e){var o=this;if(e._babylonSounds=e._babylonSounds||[],!e._babylonData){for(var s=new Array,c=e.name||"emitter"+e.index,d={loop:!1,autoplay:!1,volume:e.volume==null?1:e.volume},_=function($){var _e="/extensions/"+b.name+"/clips",et=ArrayItem.Get(_e,b._clips,e.clips[$].clip);s.push(b._loadClipAsync(_e+"/"+e.clips[$].clip,et).then(function(tt){var rt=e._babylonSounds[$]=new Sound(c,tt,o._loader.babylonScene,null,d);rt.refDistance=e.refDistance||1,rt.maxDistance=e.maxDistance||256,rt.rolloffFactor=e.rolloffFactor||1,rt.distanceModel=e.distanceModel||"exponential"}))},b=this,k=0;k<e.clips.length;k++)_(k);var j=Promise.all(s).then(function(){var $=e.clips.map(function(et){return et.weight||1}),_e=new WeightedSound(e.loop||!1,e._babylonSounds,$);e.innerAngle&&(_e.directionalConeInnerAngle=2*Tools.ToDegrees(e.innerAngle)),e.outerAngle&&(_e.directionalConeOuterAngle=2*Tools.ToDegrees(e.outerAngle)),e.volume&&(_e.volume=e.volume),e._babylonData.sound=_e});e._babylonData={loaded:j}}return e._babylonData.loaded},a.prototype._getEventAction=function(i,e,o,s,c){switch(o){case"play":return function(d){var _=(c||0)+(d-s);e.play(_)};case"stop":return function(d){e.stop()};case"pause":return function(d){e.pause()};default:throw new Error(i+": Unsupported action "+o)}},a.prototype._loadAnimationEventAsync=function(i,e,o,s,c){var d=this;if(c.targetedAnimations.length==0)return Promise.resolve();var _=c.targetedAnimations[0],b=s.emitter,k=ArrayItem.Get("/extensions/"+this.name+"/emitters",this._emitters,b);return this._loadEmitterAsync(i,k).then(function(){var j=k._babylonData.sound;if(j){var $=new AnimationEvent(s.time,d._getEventAction(i,j,s.action,s.time,s.startOffset));_.animation.addEvent($),c.onAnimationGroupEndObservable.add(function(){j.stop()}),c.onAnimationGroupPauseObservable.add(function(){j.pause()})}})},a}();GLTFLoader.RegisterExtension(NAME$9,function(a){return new MSFT_audio_emitter(a)});var NAME$8="MSFT_lod",MSFT_lod=function(){function a(i){this.name=NAME$8,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new Observable,this.onMaterialLODsLoadedObservable=new Observable,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$8)}return a.prototype.dispose=function(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()},a.prototype.onReady=function(){for(var i=this,e=function(_){var b=Promise.all(o._nodePromiseLODs[_]).then(function(){_!==0&&(i._loader.endPerformanceCounter("Node LOD "+_),i._loader.log("Loaded node LOD "+_)),i.onNodeLODsLoadedObservable.notifyObservers(_),_!==i._nodePromiseLODs.length-1&&(i._loader.startPerformanceCounter("Node LOD "+(_+1)),i._loadBufferLOD(i._nodeBufferLODs,_+1),i._nodeSignalLODs[_]&&i._nodeSignalLODs[_].resolve())});o._loader._completePromises.push(b)},o=this,s=0;s<this._nodePromiseLODs.length;s++)e(s);for(var c=function(_){var b=Promise.all(d._materialPromiseLODs[_]).then(function(){_!==0&&(i._loader.endPerformanceCounter("Material LOD "+_),i._loader.log("Loaded material LOD "+_)),i.onMaterialLODsLoadedObservable.notifyObservers(_),_!==i._materialPromiseLODs.length-1&&(i._loader.startPerformanceCounter("Material LOD "+(_+1)),i._loadBufferLOD(i._materialBufferLODs,_+1),i._materialSignalLODs[_]&&i._materialSignalLODs[_].resolve())});d._loader._completePromises.push(b)},d=this,s=0;s<this._materialPromiseLODs.length;s++)c(s)},a.prototype.loadSceneAsync=function(i,e){var o=this._loader.loadSceneAsync(i,e);return this._loadBufferLOD(this._bufferLODs,0),o},a.prototype.loadNodeAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtensionAsync(i,e,this.name,function(c,d){var _,b=s._getLODs(c,e,s._loader.gltf.nodes,d.ids);s._loader.logOpen(""+c);for(var k=[],j=0;j<b.length;j++)k.push(null);for(var $=function(_e){var et=b[_e];_e!==0&&(s._nodeIndexLOD=_e,s._nodeSignalLODs[_e]=s._nodeSignalLODs[_e]||new Deferred);var tt=function(it,nt){var ot,at,st;it.setEnabled(!1),k[nt]=it;for(var ut=!0,ft=0;ft<k.length;ft++)k[ft]||(ut=!1);var lt=k[k.length-1];if(ut&&lt&&s._isMesh(lt)){var ht=(st=(at=(ot=lt.metadata)===null||ot===void 0?void 0:ot.gltf)===null||at===void 0?void 0:at.extras)===null||st===void 0?void 0:st.MSFT_screencoverage;if(ht&&ht.length){ht.reverse(),lt.useLODScreenCoverage=!0;for(var ft=0;ft<k.length-1;ft++){var pt=k[ft];pt&&s._isMesh(pt)&&lt.addLODLevel(ht[ft+1],pt)}ht[0]>0&&lt.addLODLevel(ht[0],null)}}},rt=s._loader.loadNodeAsync("/nodes/"+et.index,et,function(it){return tt(it,_e)}).then(function(it){var nt,ot,at,st=(at=(ot=(nt=b[b.length-1]._babylonTransformNode.metadata)===null||nt===void 0?void 0:nt.gltf)===null||ot===void 0?void 0:ot.extras)===null||at===void 0?void 0:at.MSFT_screencoverage;if(_e!==0&&!st){var ut=b[_e-1];ut._babylonTransformNode&&(s._disposeTransformNode(ut._babylonTransformNode),delete ut._babylonTransformNode)}return o(it),it.setEnabled(!0),it});s._nodePromiseLODs[_e]=s._nodePromiseLODs[_e]||[],_e===0?_=rt:(s._nodeIndexLOD=null,s._nodePromiseLODs[_e].push(rt))},j=0;j<b.length;j++)$(j);return s._loader.logClose(),_})},a.prototype._loadMaterialAsync=function(i,e,o,s,c){var d=this;return this._nodeIndexLOD?null:GLTFLoader.LoadExtensionAsync(i,e,this.name,function(_,b){var k,j=d._getLODs(_,e,d._loader.gltf.materials,b.ids);d._loader.logOpen(""+_);for(var $=function(et){var tt=j[et];et!==0&&(d._materialIndexLOD=et);var rt=d._loader._loadMaterialAsync("/materials/"+tt.index,tt,o,s,function(it){et===0&&c(it)}).then(function(it){if(et!==0){c(it);var nt=j[et-1]._data;nt[s]&&(d._disposeMaterials([nt[s].babylonMaterial]),delete nt[s])}return it});d._materialPromiseLODs[et]=d._materialPromiseLODs[et]||[],et===0?k=rt:(d._materialIndexLOD=null,d._materialPromiseLODs[et].push(rt))},_e=0;_e<j.length;_e++)$(_e);return d._loader.logClose(),k})},a.prototype._loadUriAsync=function(i,e,o){var s=this;if(this._nodeIndexLOD!==null){this._loader.log("deferred");var c=this._nodeIndexLOD-1;return this._nodeSignalLODs[c]=this._nodeSignalLODs[c]||new Deferred,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(function(){return s._loader.loadUriAsync(i,e,o)})}else if(this._materialIndexLOD!==null){this._loader.log("deferred");var c=this._materialIndexLOD-1;return this._materialSignalLODs[c]=this._materialSignalLODs[c]||new Deferred,this._materialSignalLODs[c].promise.then(function(){return s._loader.loadUriAsync(i,e,o)})}return null},a.prototype.loadBufferAsync=function(i,e,o,s){if(this._loader.parent.useRangeRequests&&!e.uri){if(!this._loader.bin)throw new Error(i+": Uri is missing or the binary glTF is missing its binary chunk");var c=function(d,_){var b=o,k=b+s-1,j=d[_];return j?(j.start=Math.min(j.start,b),j.end=Math.max(j.end,k)):(j={start:b,end:k,loaded:new Deferred},d[_]=j),j.loaded.promise.then(function($){return new Uint8Array($.buffer,$.byteOffset+o-j.start,s)})};return this._loader.log("deferred"),this._nodeIndexLOD!==null?c(this._nodeBufferLODs,this._nodeIndexLOD):this._materialIndexLOD!==null?c(this._materialBufferLODs,this._materialIndexLOD):c(this._bufferLODs,0)}return null},a.prototype._isMesh=function(i){return!!i.addLODLevel},a.prototype._loadBufferLOD=function(i,e){var o=i[e];o&&(this._loader.log("Loading buffer range ["+o.start+"-"+o.end+"]"),this._loader.bin.readAsync(o.start,o.end-o.start+1).then(function(s){o.loaded.resolve(s)},function(s){o.loaded.reject(s)}))},a.prototype._getLODs=function(i,e,o,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");for(var c=new Array,d=s.length-1;d>=0;d--)if(c.push(ArrayItem.Get(i+"/ids/"+s[d],o,s[d])),c.length===this.maxLODsToLoad)return c;return c.push(e),c},a.prototype._disposeTransformNode=function(i){var e=this,o=new Array,s=i.material;s&&o.push(s);for(var c=0,d=i.getChildMeshes();c<d.length;c++){var _=d[c];_.material&&o.push(_.material)}i.dispose();var b=o.filter(function(k){return e._loader.babylonScene.meshes.every(function(j){return j.material!=k})});this._disposeMaterials(b)},a.prototype._disposeMaterials=function(i){for(var e={},o=0,s=i;o<s.length;o++){for(var c=s[o],d=0,_=c.getActiveTextures();d<_.length;d++){var b=_[d];e[b.uniqueId]=b}c.dispose()}for(var k in e)for(var j=0,$=this._loader.babylonScene.materials;j<$.length;j++){var c=$[j];c.hasTexture(e[k])&&delete e[k]}for(var k in e)e[k].dispose()},a}();GLTFLoader.RegisterExtension(NAME$8,function(a){return new MSFT_lod(a)});var NAME$7="MSFT_minecraftMesh",MSFT_minecraftMesh=function(){function a(i){this.name=NAME$7,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$7)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtraAsync(i,e,this.name,function(c,d){if(d){if(!(o instanceof PBRMaterial))throw new Error(c+": Material type not supported");var _=s._loader.loadMaterialPropertiesAsync(i,e,o);return o.needAlphaBlending()&&(o.forceDepthWrite=!0,o.separateCullingPass=!0),o.backFaceCulling=o.forceDepthWrite,o.twoSidedLighting=!0,_}return null})},a}();GLTFLoader.RegisterExtension(NAME$7,function(a){return new MSFT_minecraftMesh(a)});var NAME$6="MSFT_sRGBFactors",MSFT_sRGBFactors=function(){function a(i){this.name=NAME$6,this._loader=i,this.enabled=this._loader.isExtensionUsed(NAME$6)}return a.prototype.dispose=function(){this._loader=null},a.prototype.loadMaterialPropertiesAsync=function(i,e,o){var s=this;return GLTFLoader.LoadExtraAsync(i,e,this.name,function(c,d){if(d){if(!(o instanceof PBRMaterial))throw new Error(c+": Material type not supported");var _=s._loader.loadMaterialPropertiesAsync(i,e,o);return o.albedoTexture||o.albedoColor.toLinearSpaceToRef(o.albedoColor),o.reflectivityTexture||o.reflectivityColor.toLinearSpaceToRef(o.reflectivityColor),_}return null})},a}();GLTFLoader.RegisterExtension(NAME$6,function(a){return new MSFT_sRGBFactors(a)});var NAME$5="ExtrasAsMetadata",ExtrasAsMetadata=function(){function a(i){this.name=NAME$5,this.enabled=!0,this._loader=i}return a.prototype._assignExtras=function(i,e){if(e.extras&&Object.keys(e.extras).length>0){var o=i.metadata=i.metadata||{},s=o.gltf=o.gltf||{};s.extras=e.extras}},a.prototype.dispose=function(){this._loader=null},a.prototype.loadNodeAsync=function(i,e,o){var s=this;return this._loader.loadNodeAsync(i,e,function(c){s._assignExtras(c,e),o(c)})},a.prototype.loadCameraAsync=function(i,e,o){var s=this;return this._loader.loadCameraAsync(i,e,function(c){s._assignExtras(c,e),o(c)})},a.prototype.createMaterial=function(i,e,o){var s=this._loader.createMaterial(i,e,o);return this._assignExtras(s,e),s},a}();GLTFLoader.RegisterExtension(NAME$5,function(a){return new ExtrasAsMetadata(a)});var MTLFileLoader=function(){function a(){this.materials=[]}return a.prototype.parseMTL=function(i,e,o,s){if(!(e instanceof ArrayBuffer)){for(var c=e.split(`
  10263. `),d=/\s+/,_,b=null,k=0;k<c.length;k++){var j=c[k].trim();if(!(j.length===0||j.charAt(0)==="#")){var $=j.indexOf(" "),_e=$>=0?j.substring(0,$):j;_e=_e.toLowerCase();var et=$>=0?j.substring($+1).trim():"";_e==="newmtl"?(b&&this.materials.push(b),i._blockEntityCollection=!!s,b=new StandardMaterial(et,i),b._parentContainer=s,i._blockEntityCollection=!1):_e==="kd"&&b?(_=et.split(d,3).map(parseFloat),b.diffuseColor=Color3.FromArray(_)):_e==="ka"&&b?(_=et.split(d,3).map(parseFloat),b.ambientColor=Color3.FromArray(_)):_e==="ks"&&b?(_=et.split(d,3).map(parseFloat),b.specularColor=Color3.FromArray(_)):_e==="ke"&&b?(_=et.split(d,3).map(parseFloat),b.emissiveColor=Color3.FromArray(_)):_e==="ns"&&b?b.specularPower=parseFloat(et):_e==="d"&&b?b.alpha=parseFloat(et):_e==="map_ka"&&b?b.ambientTexture=a._getTexture(o,et,i):_e==="map_kd"&&b?b.diffuseTexture=a._getTexture(o,et,i):_e==="map_ks"&&b?b.specularTexture=a._getTexture(o,et,i):_e==="map_ns"||(_e==="map_bump"&&b?b.bumpTexture=a._getTexture(o,et,i):_e==="map_d"&&b&&(b.opacityTexture=a._getTexture(o,et,i)))}}b&&this.materials.push(b)}},a._getTexture=function(i,e,o){if(!e)return null;var s=i;if(i==="file:"){var c=e.lastIndexOf("\\");c===-1&&(c=e.lastIndexOf("/")),c>-1?s+=e.substr(c+1):s+=e}else s+=e;return new Texture(s,o,!1,a.INVERT_TEXTURE_Y)},a.INVERT_TEXTURE_Y=!0,a}(),SolidParser=function(){function a(i,e,o){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new Color4(.5,.5,.5,1),this._materialToUse=i,this._babylonMeshesArray=e,this._loadingOptions=o}return a.prototype._isInArray=function(i,e){i[e[0]]||(i[e[0]]={normals:[],idx:[]});var o=i[e[0]].normals.indexOf(e[1]);return o===-1?-1:i[e[0]].idx[o]},a.prototype._isInArrayUV=function(i,e){i[e[0]]||(i[e[0]]={normals:[],idx:[],uv:[]});var o=i[e[0]].normals.indexOf(e[1]);return o!=1&&e[2]===i[e[0]].uv[o]?i[e[0]].idx[o]:-1},a.prototype._setData=function(i,e,o,s,c,d,_){var b;this._loadingOptions.optimizeWithUV?b=this._isInArrayUV(this._tuplePosNorm,[i,o,e]):b=this._isInArray(this._tuplePosNorm,[i,o]),b===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(c),this._wrappedNormalsForBabylon.push(d),_!==void 0&&this._wrappedColorsForBabylon.push(_),this._tuplePosNorm[i].normals.push(o),this._tuplePosNorm[i].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[i].uv.push(e)):this._indicesForBabylon.push(b)},a.prototype._unwrapData=function(){for(var i=0;i<this._wrappedPositionForBabylon.length;i++)this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[i].x,this._wrappedPositionForBabylon[i].y,this._wrappedPositionForBabylon[i].z),this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[i].x,this._wrappedNormalsForBabylon[i].y,this._wrappedNormalsForBabylon[i].z),this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[i].x,this._wrappedUvsForBabylon[i].y),this._loadingOptions.importVertexColors&&this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[i].r,this._wrappedColorsForBabylon[i].g,this._wrappedColorsForBabylon[i].b,this._wrappedColorsForBabylon[i].a);this._wrappedPositionForBabylon=[],this._wrappedNormalsForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0},a.prototype._getTriangles=function(i,e){for(var o=e;o<i.length-1;o++)this._triangles.push(i[0],i[o],i[o+1])},a.prototype._setDataForCurrentFaceWithPattern1=function(i,e){this._getTriangles(i,e);for(var o=0;o<this._triangles.length;o++){var s=parseInt(this._triangles[o])-1;this._setData(s,0,0,this._positions[s],Vector2.Zero(),Vector3.Up(),this._loadingOptions.importVertexColors?this._colors[s]:void 0)}this._triangles=[]},a.prototype._setDataForCurrentFaceWithPattern2=function(i,e){this._getTriangles(i,e);for(var o=0;o<this._triangles.length;o++){var s=this._triangles[o].split("/"),c=parseInt(s[0])-1,d=parseInt(s[1])-1;this._setData(c,d,0,this._positions[c],this._uvs[d],Vector3.Up(),this._loadingOptions.importVertexColors?this._colors[c]:void 0)}this._triangles=[]},a.prototype._setDataForCurrentFaceWithPattern3=function(i,e){this._getTriangles(i,e);for(var o=0;o<this._triangles.length;o++){var s=this._triangles[o].split("/"),c=parseInt(s[0])-1,d=parseInt(s[1])-1,_=parseInt(s[2])-1;this._setData(c,d,_,this._positions[c],this._uvs[d],this._normals[_])}this._triangles=[]},a.prototype._setDataForCurrentFaceWithPattern4=function(i,e){this._getTriangles(i,e);for(var o=0;o<this._triangles.length;o++){var s=this._triangles[o].split("//"),c=parseInt(s[0])-1,d=parseInt(s[1])-1;this._setData(c,1,d,this._positions[c],Vector2.Zero(),this._normals[d],this._loadingOptions.importVertexColors?this._colors[c]:void 0)}this._triangles=[]},a.prototype._setDataForCurrentFaceWithPattern5=function(i,e){this._getTriangles(i,e);for(var o=0;o<this._triangles.length;o++){var s=this._triangles[o].split("/"),c=this._positions.length+parseInt(s[0]),d=this._uvs.length+parseInt(s[1]),_=this._normals.length+parseInt(s[2]);this._setData(c,d,_,this._positions[c],this._uvs[d],this._normals[_],this._loadingOptions.importVertexColors?this._colors[c]:void 0)}this._triangles=[]},a.prototype._addPreviousObjMesh=function(){this._meshesFromObj.length>0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon=[],this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[])},a.prototype._optimizeNormals=function(i){var e=i.getVerticesData(VertexBuffer.PositionKind),o=i.getVerticesData(VertexBuffer.NormalKind),s={};if(!(!e||!o)){for(var c=0;c<e.length/3;c++){var d=e[c*3+0],_=e[c*3+1],b=e[c*3+2],k=d+"_"+_+"_"+b,j=s[k];j||(j=[],s[k]=j),j.push(c)}var $=new Vector3;for(var k in s){var j=s[k];if(!(j.length<2)){for(var _e=j[0],c=1;c<j.length;++c){var et=j[c];o[_e*3+0]+=o[et*3+0],o[_e*3+1]+=o[et*3+1],o[_e*3+2]+=o[et*3+2]}$.copyFromFloats(o[_e*3+0],o[_e*3+1],o[_e*3+2]),$.normalize();for(var c=0;c<j.length;++c){var et=j[c];o[et*3+0]=$.x,o[et*3+1]=$.y,o[et*3+2]=$.z}}}i.setVerticesData(VertexBuffer.NormalKind,o)}},a.prototype.parse=function(i,e,o,s,c){for(var d,_=e.split(`
  10264. `),b=0;b<_.length;b++){var k=_[b].trim().replace(/\s\s/g," "),j;if(!(k.length===0||k.charAt(0)==="#"))if(a.VertexPattern.test(k)){if(j=k.match(/[^ ]+/g),this._positions.push(new Vector3(parseFloat(j[1]),parseFloat(j[2]),parseFloat(j[3]))),this._loadingOptions.importVertexColors)if(j.length>=7){var $=parseFloat(j[4]),_e=parseFloat(j[5]),et=parseFloat(j[6]);this._colors.push(new Color4($>1?$/255:$,_e>1?_e/255:_e,et>1?et/255:et,j.length===7||j[7]===void 0?1:parseFloat(j[7])))}else this._colors.push(this._grayColor)}else if((j=a.NormalPattern.exec(k))!==null)this._normals.push(new Vector3(parseFloat(j[1]),parseFloat(j[2]),parseFloat(j[3])));else if((j=a.UVPattern.exec(k))!==null)this._uvs.push(new Vector2(parseFloat(j[1])*this._loadingOptions.UVScaling.x,parseFloat(j[2])*this._loadingOptions.UVScaling.y));else if((j=a.FacePattern3.exec(k))!==null)this._setDataForCurrentFaceWithPattern3(j[1].trim().split(" "),1);else if((j=a.FacePattern4.exec(k))!==null)this._setDataForCurrentFaceWithPattern4(j[1].trim().split(" "),1);else if((j=a.FacePattern5.exec(k))!==null)this._setDataForCurrentFaceWithPattern5(j[1].trim().split(" "),1);else if((j=a.FacePattern2.exec(k))!==null)this._setDataForCurrentFaceWithPattern2(j[1].trim().split(" "),1);else if((j=a.FacePattern1.exec(k))!==null)this._setDataForCurrentFaceWithPattern1(j[1].trim().split(" "),1);else if(a.GroupDescriptor.test(k)||a.ObjectDescriptor.test(k)){var tt={name:k.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:""};this._addPreviousObjMesh(),this._meshesFromObj.push(tt),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(a.UseMtlDescriptor.test(k)){if(this._materialNameFromObj=k.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();var tt={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:this._materialNameFromObj};this._increment++,this._meshesFromObj.push(tt),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else a.MtlLibGroupDescriptor.test(k)?c(k.substring(7).trim()):a.SmoothDescriptor.test(k)||console.log("Unhandled expression at line : "+k)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){var rt=null;if(this._indicesForBabylon.length)this._indicesForBabylon.reverse(),this._unwrapData();else{for(var it=0,nt=this._positions;it<nt.length;it++){var ot=nt[it];this._unwrappedPositionsForBabylon.push(ot.x,ot.y,ot.z)}if(this._normals.length)for(var at=0,st=this._normals;at<st.length;at++){var ut=st[at];this._unwrappedNormalsForBabylon.push(ut.x,ut.y,ut.z)}if(this._uvs.length)for(var ft=0,lt=this._uvs;ft<lt.length;ft++){var ht=lt[ft];this._unwrappedUVForBabylon.push(ht.x,ht.y)}if(this._colors.length)for(var pt=0,mt=this._colors;pt<mt.length;pt++){var dt=mt[pt];this._unwrappedColorsForBabylon.push(dt.r,dt.g,dt.b,dt.a)}this._materialNameFromObj||(rt=new StandardMaterial(Geometry.RandomId(),o),rt.pointsCloud=!0,this._materialNameFromObj=rt.name,this._normals.length||(rt.disableLighting=!0,rt.emissiveColor=Color3.White()))}this._meshesFromObj.push({name:Geometry.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:rt})}for(var gt=0;gt<this._meshesFromObj.length;gt++){if(i&&this._meshesFromObj[gt].name){if(i instanceof Array){if(i.indexOf(this._meshesFromObj[gt].name)===-1)continue}else if(this._meshesFromObj[gt].name!==i)continue}this._handledMesh=this._meshesFromObj[gt],o._blockEntityCollection=!!s;var _t=new Mesh(this._meshesFromObj[gt].name,o);if(_t._parentContainer=s,o._blockEntityCollection=!1,this._materialToUse.push(this._meshesFromObj[gt].materialName),((d=this._handledMesh.positions)===null||d===void 0?void 0:d.length)===0){this._babylonMeshesArray.push(_t);continue}var yt=new VertexData;if(yt.uvs=this._handledMesh.uvs,yt.indices=this._handledMesh.indices,yt.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){var Tt=new Array;VertexData.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,Tt),yt.normals=Tt}else yt.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(yt.colors=this._handledMesh.colors),yt.applyToMesh(_t),this._loadingOptions.invertY&&(_t.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(_t),this._babylonMeshesArray.push(_t),this._handledMesh.directMaterial&&(_t.material=this._handledMesh.directMaterial)}},a.ObjectDescriptor=/^o/,a.GroupDescriptor=/^g/,a.MtlLibGroupDescriptor=/^mtllib /,a.UseMtlDescriptor=/^usemtl /,a.SmoothDescriptor=/^s /,a.VertexPattern=/v(\s+[\d|\.|\+|\-|e|E]+){3,7}/,a.NormalPattern=/vn(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,a.UVPattern=/vt(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,a.FacePattern1=/f\s+(([\d]{1,}[\s]?){3,})+/,a.FacePattern2=/f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,a.FacePattern3=/f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,a.FacePattern4=/f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,a.FacePattern5=/f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,a}(),OBJFileLoader=function(){function a(i){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=i||a.DefaultLoadingOptions}return Object.defineProperty(a,"INVERT_TEXTURE_Y",{get:function(){return MTLFileLoader.INVERT_TEXTURE_Y},set:function(i){MTLFileLoader.INVERT_TEXTURE_Y=i},enumerable:!1,configurable:!0}),Object.defineProperty(a,"DefaultLoadingOptions",{get:function(){return{computeNormals:a.COMPUTE_NORMALS,optimizeNormals:a.OPTIMIZE_NORMALS,importVertexColors:a.IMPORT_VERTEX_COLORS,invertY:a.INVERT_Y,invertTextureY:a.INVERT_TEXTURE_Y,UVScaling:a.UV_SCALING,materialLoadingFailsSilently:a.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:a.OPTIMIZE_WITH_UV,skipMaterials:a.SKIP_MATERIALS}},enumerable:!1,configurable:!0}),a.prototype._loadMTL=function(i,e,o,s){var c=e+i;Tools.LoadFile(c,o,void 0,void 0,!1,function(d,_){s(c,_)})},a.prototype.createPlugin=function(){return new a(a.DefaultLoadingOptions)},a.prototype.canDirectLoad=function(i){return!1},a.prototype.importMeshAsync=function(i,e,o,s,c,d){return this._parseSolid(i,e,o,s).then(function(_){return{meshes:_,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[]}})},a.prototype.loadAsync=function(i,e,o,s,c){return this.importMeshAsync(null,i,e,o,s).then(function(){})},a.prototype.loadAssetContainerAsync=function(i,e,o,s,c){var d=this,_=new AssetContainer(i);return this._assetContainer=_,this.importMeshAsync(null,i,e,o).then(function(b){return b.meshes.forEach(function(k){return _.meshes.push(k)}),b.meshes.forEach(function(k){var j=k.material;if(j&&_.materials.indexOf(j)==-1){_.materials.push(j);var $=j.getActiveTextures();$.forEach(function(_e){_.textures.indexOf(_e)==-1&&_.textures.push(_e)})}}),d._assetContainer=null,_}).catch(function(b){throw d._assetContainer=null,b})},a.prototype._parseSolid=function(i,e,o,s){var c=this,d="",_=new MTLFileLoader,b=new Array,k=[],j=new SolidParser(b,k,this._loadingOptions);j.parse(i,o,e,this._assetContainer,function(_e){d=_e});var $=[];return d!==""&&!this._loadingOptions.skipMaterials&&$.push(new Promise(function(_e,et){c._loadMTL(d,s,function(tt){try{_.parseMTL(e,tt,s,c._assetContainer);for(var rt=0;rt<_.materials.length;rt++){for(var it=0,nt=[],ot;(ot=b.indexOf(_.materials[rt].name,it))>-1;)nt.push(ot),it=ot+1;if(ot===-1&&nt.length===0)_.materials[rt].dispose();else for(var at=0;at<nt.length;at++){var st=k[nt[at]],ut=_.materials[rt];st.material=ut,st.getTotalIndices()||(ut.pointsCloud=!0)}}_e()}catch(ft){Tools.Warn("Error processing MTL file: '"+d+"'"),c._loadingOptions.materialLoadingFailsSilently?_e():et(ft)}},function(tt,rt){Tools.Warn("Error downloading MTL file: '"+d+"'"),c._loadingOptions.materialLoadingFailsSilently?_e():et(rt)})})),Promise.all($).then(function(){return k})},a.OPTIMIZE_WITH_UV=!0,a.INVERT_Y=!1,a.IMPORT_VERTEX_COLORS=!1,a.COMPUTE_NORMALS=!1,a.OPTIMIZE_NORMALS=!1,a.UV_SCALING=new Vector2(1,1),a.SKIP_MATERIALS=!1,a.MATERIAL_LOADING_FAILS_SILENTLY=!0,a}();SceneLoader&&SceneLoader.RegisterPlugin(new OBJFileLoader);var STLFileLoader=function(){function a(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,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,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,this.name="stl",this.extensions={".stl":{isBinary:!0}}}return a.prototype.importMesh=function(i,e,o,s,c,d,_){var b;if(typeof o!="string"){if(this._isBinary(o)){var k=new Mesh("stlmesh",e);return this._parseBinary(k,o),c&&c.push(k),!0}for(var j=new Uint8Array(o),$="",_e=0;_e<o.byteLength;_e++)$+=String.fromCharCode(j[_e]);o=$}for(;b=this.solidPattern.exec(o);){var et=b[1],tt=b[3];if(et!=tt)return Tools.Error("Error in STL, solid name != endsolid name"),!1;if(i&&et){if(i instanceof Array){if(!i.indexOf(et))continue}else if(et!==i)continue}et=et||"stlmesh";var k=new Mesh(et,e);this._parseASCII(k,b[2]),c&&c.push(k)}return!0},a.prototype.load=function(i,e,o){var s=this.importMesh(null,i,e,o,null,null,null);return s},a.prototype.loadAssetContainer=function(i,e,o,s){var c=new AssetContainer(i);return i._blockEntityCollection=!0,this.importMesh(null,i,e,o,c.meshes,null,null),i._blockEntityCollection=!1,c},a.prototype._isBinary=function(i){var e,o,s;if(s=new DataView(i),s.byteLength<=80)return!1;if(e=32/8*3+32/8*3*3+16/8,o=s.getUint32(80,!0),80+32/8+o*e===s.byteLength)return!0;for(var c=s.byteLength,d=0;d<c;d++)if(s.getUint8(d)>127)return!0;return!1},a.prototype._parseBinary=function(i,e){for(var o=new DataView(e),s=o.getUint32(80,!0),c=84,d=12*4+2,_=0,b=new Float32Array(s*3*3),k=new Float32Array(s*3*3),j=new Uint32Array(s*3),$=0,_e=0;_e<s;_e++){for(var et=c+_e*d,tt=o.getFloat32(et,!0),rt=o.getFloat32(et+4,!0),it=o.getFloat32(et+8,!0),nt=1;nt<=3;nt++){var ot=et+nt*12;b[_]=o.getFloat32(ot,!0),k[_]=tt,a.DO_NOT_ALTER_FILE_COORDINATES?(b[_+1]=o.getFloat32(ot+4,!0),b[_+2]=o.getFloat32(ot+8,!0),k[_+1]=rt,k[_+2]=it):(b[_+2]=o.getFloat32(ot+4,!0),b[_+1]=o.getFloat32(ot+8,!0),k[_+2]=rt,k[_+1]=it),_+=3}j[$]=$++,j[$]=$++,j[$]=$++}i.setVerticesData(VertexBuffer.PositionKind,b),i.setVerticesData(VertexBuffer.NormalKind,k),i.setIndices(j),i.computeWorldMatrix(!0)},a.prototype._parseASCII=function(i,e){for(var o=[],s=[],c=[],d=0,_;_=this.facetsPattern.exec(e);){var b=_[1],k=this.normalPattern.exec(b);if(this.normalPattern.lastIndex=0,!!k){for(var j=[Number(k[1]),Number(k[5]),Number(k[3])],$;$=this.vertexPattern.exec(b);)a.DO_NOT_ALTER_FILE_COORDINATES?(o.push(Number($[1]),Number($[3]),Number($[5])),s.push(j[0],j[2],j[1])):(o.push(Number($[1]),Number($[5]),Number($[3])),s.push(j[0],j[1],j[2]));c.push(d++,d++,d++),this.vertexPattern.lastIndex=0}}this.facetsPattern.lastIndex=0,i.setVerticesData(VertexBuffer.PositionKind,o),i.setVerticesData(VertexBuffer.NormalKind,s),i.setIndices(c),i.computeWorldMatrix(!0)},a.DO_NOT_ALTER_FILE_COORDINATES=!1,a}();SceneLoader&&SceneLoader.RegisterPlugin(new STLFileLoader);var SoundTrack=function(){function a(i,e){e===void 0&&(e={}),this.id=-1,this._isInitialized=!1,this._scene=i,this.soundCollection=new Array,this._options=e,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return a.prototype._initializeSoundTrackAudioGraph=function(){var i;((i=Engine.audioEngine)===null||i===void 0?void 0:i.canUseWebAudio)&&Engine.audioEngine.audioContext&&(this._outputAudioNode=Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Engine.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)},a.prototype.dispose=function(){if(Engine.audioEngine&&Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},a.prototype.addSound=function(i){var e;this._isInitialized||this._initializeSoundTrackAudioGraph(),((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this._outputAudioNode&&i.connectToSoundTrackAudioNode(this._outputAudioNode),i.soundTrackId&&(i.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(i):this._scene.soundTracks&&this._scene.soundTracks[i.soundTrackId].removeSound(i)),this.soundCollection.push(i),i.soundTrackId=this.id},a.prototype.removeSound=function(i){var e=this.soundCollection.indexOf(i);e!==-1&&this.soundCollection.splice(e,1)},a.prototype.setVolume=function(i){var e;((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=i)},a.prototype.switchPanningModelToHRTF=function(){var i;if(!((i=Engine.audioEngine)===null||i===void 0)&&i.canUseWebAudio)for(var e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToHRTF()},a.prototype.switchPanningModelToEqualPower=function(){var i;if(!((i=Engine.audioEngine)===null||i===void 0)&&i.canUseWebAudio)for(var e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToEqualPower()},a.prototype.connectToAnalyser=function(i){var e;this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=i,((e=Engine.audioEngine)===null||e===void 0?void 0:e.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,Engine.audioEngine.masterGain))},a}();Engine.AudioEngineFactory=function(a,i,e){return new AudioEngine(a,i,e)};var AudioEngine=function(){function a(i,e,o){var s=this;if(i===void 0&&(i=null),e===void 0&&(e=null),o===void 0&&(o=null),this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!0,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new Observable,this.onAudioLockedObservable=new Observable,this._tryToRun=!1,this._onResize=function(){s._moveButtonToTopLeft()},!!IsWindowObjectExist()){(typeof window.AudioContext!="undefined"||typeof window.webkitAudioContext!="undefined")&&(window.AudioContext=window.AudioContext||window.webkitAudioContext,this.canUseWebAudio=!0);var c=document.createElement("audio");this._hostElement=i,this._audioContext=e,this._audioDestination=o;try{c&&!!c.canPlayType&&(c.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||c.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{c&&!!c.canPlayType&&c.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch{}}}return Object.defineProperty(a.prototype,"audioContext",{get:function(){return this._audioContextInitialized?!this.unlocked&&!this._muteButton&&this._displayMuteButton():this._initializeAudioContext(),this._audioContext},enumerable:!1,configurable:!0}),a.prototype.lock=function(){this._triggerSuspendedState()},a.prototype.unlock=function(){this._triggerRunningState()},a.prototype._resumeAudioContext=function(){var i;return this._audioContext.resume!==void 0&&(i=this._audioContext.resume()),i||Promise.resolve()},a.prototype._initializeAudioContext=function(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,this._audioContext.state==="running"&&this._triggerRunningState())}catch(i){this.canUseWebAudio=!1,Logger$2.Error("Web Audio: "+i.message)}},a.prototype._triggerRunningState=function(){var i=this;this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then(function(){i._tryToRun=!1,i._muteButton&&i._hideMuteButton(),i.unlocked=!0,i.onAudioUnlockedObservable.notifyObservers(i)}).catch(function(){i._tryToRun=!1,i.unlocked=!1}))},a.prototype._triggerSuspendedState=function(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()},a.prototype._displayMuteButton=function(){var i=this;if(!(this.useCustomUnlockedButton||this._muteButton)){this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";var e=window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png",o=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",s=document.createElement("style");s.appendChild(document.createTextNode(o)),document.getElementsByTagName("head")[0].appendChild(s),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",function(){i._triggerRunningState()},!0),this._muteButton.addEventListener("click",function(){i._triggerRunningState()},!0),window.addEventListener("resize",this._onResize)}},a.prototype._moveButtonToTopLeft=function(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")},a.prototype._hideMuteButton=function(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)},a.prototype.dispose=function(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()},a.prototype.getGlobalVolume=function(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1},a.prototype.setGlobalVolume=function(i){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=i)},a.prototype.connectToAnalyser=function(i){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=i,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))},a}();AbstractScene.AddParser(SceneComponentConstants.NAME_AUDIO,function(a,i,e,o){var s,c=[],d;if(e.sounds=e.sounds||[],a.sounds!==void 0&&a.sounds!==null)for(var _=0,b=a.sounds.length;_<b;_++){var k=a.sounds[_];!((s=Engine.audioEngine)===null||s===void 0)&&s.canUseWebAudio?(k.url||(k.url=k.name),c[k.url]?e.sounds.push(Sound.Parse(k,i,o,c[k.url])):(d=Sound.Parse(k,i,o),c[k.url]=d,e.sounds.push(d))):e.sounds.push(new Sound(k.name,null,i))}c=[]});Object.defineProperty(Scene.prototype,"mainSoundTrack",{get:function(){var a=this._getComponent(SceneComponentConstants.NAME_AUDIO);return a||(a=new AudioSceneComponent(this),this._addComponent(a)),this._mainSoundTrack||(this._mainSoundTrack=new SoundTrack(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0});Scene.prototype.getSoundByName=function(a){var i;for(i=0;i<this.mainSoundTrack.soundCollection.length;i++)if(this.mainSoundTrack.soundCollection[i].name===a)return this.mainSoundTrack.soundCollection[i];if(this.soundTracks){for(var e=0;e<this.soundTracks.length;e++)for(i=0;i<this.soundTracks[e].soundCollection.length;i++)if(this.soundTracks[e].soundCollection[i].name===a)return this.soundTracks[e].soundCollection[i]}return null};Object.defineProperty(Scene.prototype,"audioEnabled",{get:function(){var a=this._getComponent(SceneComponentConstants.NAME_AUDIO);return a||(a=new AudioSceneComponent(this),this._addComponent(a)),a.audioEnabled},set:function(a){var i=this._getComponent(SceneComponentConstants.NAME_AUDIO);i||(i=new AudioSceneComponent(this),this._addComponent(i)),a?i.enableAudio():i.disableAudio()},enumerable:!0,configurable:!0});Object.defineProperty(Scene.prototype,"headphone",{get:function(){var a=this._getComponent(SceneComponentConstants.NAME_AUDIO);return a||(a=new AudioSceneComponent(this),this._addComponent(a)),a.headphone},set:function(a){var i=this._getComponent(SceneComponentConstants.NAME_AUDIO);i||(i=new AudioSceneComponent(this),this._addComponent(i)),a?i.switchAudioModeForHeadphones():i.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0});Object.defineProperty(Scene.prototype,"audioListenerPositionProvider",{get:function(){var a=this._getComponent(SceneComponentConstants.NAME_AUDIO);return a||(a=new AudioSceneComponent(this),this._addComponent(a)),a.audioListenerPositionProvider},set:function(a){var i=this._getComponent(SceneComponentConstants.NAME_AUDIO);if(i||(i=new AudioSceneComponent(this),this._addComponent(i)),typeof a!="function")throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");i.audioListenerPositionProvider=a},enumerable:!0,configurable:!0});Object.defineProperty(Scene.prototype,"audioPositioningRefreshRate",{get:function(){var a=this._getComponent(SceneComponentConstants.NAME_AUDIO);return a||(a=new AudioSceneComponent(this),this._addComponent(a)),a.audioPositioningRefreshRate},set:function(a){var i=this._getComponent(SceneComponentConstants.NAME_AUDIO);i||(i=new AudioSceneComponent(this),this._addComponent(i)),i.audioPositioningRefreshRate=a},enumerable:!0,configurable:!0});var AudioSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this._audioListenerPositionProvider=null,this._cachedCameraDirection=new Vector3,this._cachedCameraPosition=new Vector3,this._lastCheck=0,this.scene=i,i.soundTracks=new Array,i.sounds=new Array}return Object.defineProperty(a.prototype,"audioEnabled",{get:function(){return this._audioEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"headphone",{get:function(){return this._headphone},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"audioListenerPositionProvider",{get:function(){return this._audioListenerPositionProvider},set:function(i){this._audioListenerPositionProvider=i},enumerable:!1,configurable:!0}),a.prototype.register=function(){this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO,this,this._afterRender)},a.prototype.rebuild=function(){},a.prototype.serialize=function(i){if(i.sounds=[],this.scene.soundTracks)for(var e=0;e<this.scene.soundTracks.length;e++)for(var o=this.scene.soundTracks[e],s=0;s<o.soundCollection.length;s++)i.sounds.push(o.soundCollection[s].serialize())},a.prototype.addFromContainer=function(i){var e=this;!i.sounds||i.sounds.forEach(function(o){o.play(),o.autoplay=!0,e.scene.mainSoundTrack.addSound(o)})},a.prototype.removeFromContainer=function(i,e){var o=this;e===void 0&&(e=!1),i.sounds&&i.sounds.forEach(function(s){s.stop(),s.autoplay=!1,o.scene.mainSoundTrack.removeSound(s),e&&s.dispose()})},a.prototype.dispose=function(){var i=this.scene;if(i._mainSoundTrack&&i.mainSoundTrack.dispose(),i.soundTracks)for(var e=0;e<i.soundTracks.length;e++)i.soundTracks[e].dispose()},a.prototype.disableAudio=function(){var i=this.scene;this._audioEnabled=!1,Engine.audioEngine&&Engine.audioEngine.audioContext&&Engine.audioEngine.audioContext.suspend();var e;for(e=0;e<i.mainSoundTrack.soundCollection.length;e++)i.mainSoundTrack.soundCollection[e].pause();if(i.soundTracks)for(e=0;e<i.soundTracks.length;e++)for(var o=0;o<i.soundTracks[e].soundCollection.length;o++)i.soundTracks[e].soundCollection[o].pause()},a.prototype.enableAudio=function(){var i=this.scene;this._audioEnabled=!0,Engine.audioEngine&&Engine.audioEngine.audioContext&&Engine.audioEngine.audioContext.resume();var e;for(e=0;e<i.mainSoundTrack.soundCollection.length;e++)i.mainSoundTrack.soundCollection[e].isPaused&&i.mainSoundTrack.soundCollection[e].play();if(i.soundTracks)for(e=0;e<i.soundTracks.length;e++)for(var o=0;o<i.soundTracks[e].soundCollection.length;o++)i.soundTracks[e].soundCollection[o].isPaused&&i.soundTracks[e].soundCollection[o].play()},a.prototype.switchAudioModeForHeadphones=function(){var i=this.scene;if(this._headphone=!0,i.mainSoundTrack.switchPanningModelToHRTF(),i.soundTracks)for(var e=0;e<i.soundTracks.length;e++)i.soundTracks[e].switchPanningModelToHRTF()},a.prototype.switchAudioModeForNormalSpeakers=function(){var i=this.scene;if(this._headphone=!1,i.mainSoundTrack.switchPanningModelToEqualPower(),i.soundTracks)for(var e=0;e<i.soundTracks.length;e++)i.soundTracks[e].switchPanningModelToEqualPower()},a.prototype._afterRender=function(){var i=PrecisionDate.Now;if(!(this._lastCheck&&i-this._lastCheck<this.audioPositioningRefreshRate)){this._lastCheck=i;var e=this.scene;if(!(!this._audioEnabled||!e._mainSoundTrack||!e.soundTracks||e._mainSoundTrack.soundCollection.length===0&&e.soundTracks.length===1)){var o=Engine.audioEngine;if(!!o&&o.audioContext){if(this._audioListenerPositionProvider){var s=this._audioListenerPositionProvider();s.x=s.x||0,s.y=s.y||0,s.z=s.z||0,o.audioContext.listener.setPosition(s.x,s.y,s.z)}else{var c;if(e.activeCameras&&e.activeCameras.length>0?c=e.activeCameras[0]:c=e.activeCamera,c){this._cachedCameraPosition.equals(c.globalPosition)||(this._cachedCameraPosition.copyFrom(c.globalPosition),o.audioContext.listener.setPosition(c.globalPosition.x,c.globalPosition.y,c.globalPosition.z)),c.rigCameras&&c.rigCameras.length>0&&(c=c.rigCameras[0]);var d=Matrix.Invert(c.getViewMatrix()),_=Vector3.TransformNormal(a._CameraDirection,d);_.normalize(),!isNaN(_.x)&&!isNaN(_.y)&&!isNaN(_.z)&&(this._cachedCameraDirection.equals(_)||(this._cachedCameraDirection.copyFrom(_),o.audioContext.listener.setOrientation(_.x,_.y,_.z,0,1,0)))}else o.audioContext.listener.setPosition(0,0,0)}var b;for(b=0;b<e.mainSoundTrack.soundCollection.length;b++){var k=e.mainSoundTrack.soundCollection[b];k.useCustomAttenuation&&k.updateDistanceFromListener()}if(e.soundTracks)for(b=0;b<e.soundTracks.length;b++)for(var j=0;j<e.soundTracks[b].soundCollection.length;j++)k=e.soundTracks[b].soundCollection[j],k.useCustomAttenuation&&k.updateDistanceFromListener()}}}},a._CameraDirection=new Vector3(0,0,-1),a}();Sound._SceneComponentInitialization=function(a){var i=a._getComponent(SceneComponentConstants.NAME_AUDIO);i||(i=new AudioSceneComponent(a),a._addComponent(i))};var DefaultLoadingScreen=function(){function a(i,e,o){var s=this;e===void 0&&(e=""),o===void 0&&(o="black"),this._renderingCanvas=i,this._loadingText=e,this._loadingDivBackgroundColor=o,this._resizeLoadingUI=function(){var c=s._renderingCanvas.getBoundingClientRect(),d=window.getComputedStyle(s._renderingCanvas).position;!s._loadingDiv||(s._loadingDiv.style.position=d==="fixed"?"fixed":"absolute",s._loadingDiv.style.left=c.left+"px",s._loadingDiv.style.top=c.top+"px",s._loadingDiv.style.width=c.width+"px",s._loadingDiv.style.height=c.height+"px")}}return a.prototype.displayLoadingUI=function(){if(!this._loadingDiv){this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";var i=`@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}
  10265. 100% { -webkit-transform: rotate(360deg);}
  10266. } @keyframes spin1 { 0% { transform: rotate(0deg);}
  10267. 100% { transform: rotate(360deg);}
  10268. }`;this._style.innerHTML=i,document.getElementsByTagName("head")[0].appendChild(this._style);var e=!!window.SVGSVGElement,o=new Image;a.DefaultLogoUrl?o.src=a.DefaultLogoUrl:o.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",o.style.width="150px",o.style.gridColumn="1",o.style.gridRow="1",o.style.top="50%",o.style.left="50%",o.style.transform="translate(-50%, -50%)",o.style.position="absolute";var s=document.createElement("div");s.style.width="300px",s.style.gridColumn="1",s.style.gridRow="1",s.style.top="50%",s.style.left="50%",s.style.transform="translate(-50%, -50%)",s.style.position="absolute";var c=new Image;if(a.DefaultSpinnerUrl?c.src=a.DefaultSpinnerUrl:c.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",c.style.animation="spin1 0.75s infinite linear",c.style.webkitAnimation="spin1 0.75s infinite linear",c.style.transformOrigin="50% 50%",c.style.webkitTransformOrigin="50% 50%",!e){var d={w:16,h:18.5},_={w:30,h:30};o.style.width=d.w+"vh",o.style.height=d.h+"vh",o.style.left="calc(50% - "+d.w/2+"vh)",o.style.top="calc(50% - "+d.h/2+"vh)",c.style.width=_.w+"vh",c.style.height=_.h+"vh",c.style.left="calc(50% - "+_.w/2+"vh)",c.style.top="calc(50% - "+_.h/2+"vh)"}s.appendChild(c),this._loadingDiv.appendChild(o),this._loadingDiv.appendChild(s),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}},a.prototype.hideLoadingUI=function(){var i=this;if(!!this._loadingDiv){var e=function(){i._loadingDiv&&(i._loadingDiv.parentElement&&i._loadingDiv.parentElement.removeChild(i._loadingDiv),i._loadingDiv=null),i._style&&(i._style.parentElement&&i._style.parentElement.removeChild(i._style),i._style=null),window.removeEventListener("resize",i._resizeLoadingUI)};this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",e)}},Object.defineProperty(a.prototype,"loadingUIText",{get:function(){return this._loadingText},set:function(i){this._loadingText=i,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"loadingUIBackgroundColor",{get:function(){return this._loadingDivBackgroundColor},set:function(i){this._loadingDivBackgroundColor=i,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)},enumerable:!1,configurable:!0}),a.DefaultLogoUrl="",a.DefaultSpinnerUrl="",a}();Engine.DefaultLoadingScreenFactory=function(a){return new DefaultLoadingScreen(a)};var PanoramaToCubeMapTools=function(){function a(){}return a.ConvertPanoramaToCubemap=function(i,e,o,s){if(!i)throw"ConvertPanoramaToCubemap: input cannot be null";if(i.length!=e*o*3)throw"ConvertPanoramaToCubemap: input size is wrong";var c=this.CreateCubemapTexture(s,this.FACE_FRONT,i,e,o),d=this.CreateCubemapTexture(s,this.FACE_BACK,i,e,o),_=this.CreateCubemapTexture(s,this.FACE_LEFT,i,e,o),b=this.CreateCubemapTexture(s,this.FACE_RIGHT,i,e,o),k=this.CreateCubemapTexture(s,this.FACE_UP,i,e,o),j=this.CreateCubemapTexture(s,this.FACE_DOWN,i,e,o);return{front:c,back:d,left:_,right:b,up:k,down:j,size:s,type:1,format:4,gammaSpace:!1}},a.CreateCubemapTexture=function(i,e,o,s,c){for(var d=new ArrayBuffer(i*i*4*3),_=new Float32Array(d),b=e[1].subtract(e[0]).scale(1/i),k=e[3].subtract(e[2]).scale(1/i),j=1/i,$=0,_e=0;_e<i;_e++){for(var et=e[0],tt=e[2],rt=0;rt<i;rt++){var it=tt.subtract(et).scale($).add(et);it.normalize();var nt=this.CalcProjectionSpherical(it,o,s,c);_[_e*i*3+rt*3+0]=nt.r,_[_e*i*3+rt*3+1]=nt.g,_[_e*i*3+rt*3+2]=nt.b,et=et.add(b),tt=tt.add(k)}$+=j}return _},a.CalcProjectionSpherical=function(i,e,o,s){for(var c=Math.atan2(i.z,i.x),d=Math.acos(i.y);c<-Math.PI;)c+=2*Math.PI;for(;c>Math.PI;)c-=2*Math.PI;var _=c/Math.PI,b=d/Math.PI;_=_*.5+.5;var k=Math.round(_*o);k<0?k=0:k>=o&&(k=o-1);var j=Math.round(b*s);j<0?j=0:j>=s&&(j=s-1);var $=s-j-1,_e=e[$*o*3+k*3+0],et=e[$*o*3+k*3+1],tt=e[$*o*3+k*3+2];return{r:_e,g:et,b:tt}},a.FACE_LEFT=[new Vector3(-1,-1,-1),new Vector3(1,-1,-1),new Vector3(-1,1,-1),new Vector3(1,1,-1)],a.FACE_RIGHT=[new Vector3(1,-1,1),new Vector3(-1,-1,1),new Vector3(1,1,1),new Vector3(-1,1,1)],a.FACE_FRONT=[new Vector3(1,-1,-1),new Vector3(1,-1,1),new Vector3(1,1,-1),new Vector3(1,1,1)],a.FACE_BACK=[new Vector3(-1,-1,1),new Vector3(-1,-1,-1),new Vector3(-1,1,1),new Vector3(-1,1,-1)],a.FACE_DOWN=[new Vector3(1,1,-1),new Vector3(1,1,1),new Vector3(-1,1,-1),new Vector3(-1,1,1)],a.FACE_UP=[new Vector3(-1,-1,-1),new Vector3(-1,-1,1),new Vector3(1,-1,-1),new Vector3(1,-1,1)],a}(),HDRTools=function(){function a(){}return a.Ldexp=function(i,e){return e>1023?i*Math.pow(2,1023)*Math.pow(2,e-1023):e<-1074?i*Math.pow(2,-1074)*Math.pow(2,e+1074):i*Math.pow(2,e)},a.Rgbe2float=function(i,e,o,s,c,d){c>0?(c=this.Ldexp(1,c-(128+8)),i[d+0]=e*c,i[d+1]=o*c,i[d+2]=s*c):(i[d+0]=0,i[d+1]=0,i[d+2]=0)},a.readStringLine=function(i,e){for(var o="",s="",c=e;c<i.length-e&&(s=String.fromCharCode(i[c]),s!=`
  10269. `);c++)o+=s;return o},a.RGBE_ReadHeader=function(i){var e=0,o=0,s=this.readStringLine(i,0);if(s[0]!="#"||s[1]!="?")throw"Bad HDR Format.";var c=!1,d=!1,_=0;do _+=s.length+1,s=this.readStringLine(i,_),s=="FORMAT=32-bit_rle_rgbe"?d=!0:s.length==0&&(c=!0);while(!c);if(!d)throw"HDR Bad header format, unsupported FORMAT";_+=s.length+1,s=this.readStringLine(i,_);var b=/^\-Y (.*) \+X (.*)$/g,k=b.exec(s);if(!k||k.length<3)throw"HDR Bad header format, no size";if(o=parseInt(k[2]),e=parseInt(k[1]),o<8||o>32767)throw"HDR Bad header format, unsupported size";return _+=s.length+1,{height:e,width:o,dataPosition:_}},a.GetCubeMapTextureData=function(i,e){var o=new Uint8Array(i),s=this.RGBE_ReadHeader(o),c=this.RGBE_ReadPixels(o,s),d=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(c,s.width,s.height,e);return d},a.RGBE_ReadPixels=function(i,e){return this.RGBE_ReadPixels_RLE(i,e)},a.RGBE_ReadPixels_RLE=function(i,e){for(var o=e.height,s=e.width,c,d,_,b,k,j=e.dataPosition,$=0,_e=0,et=0,tt=new ArrayBuffer(s*4),rt=new Uint8Array(tt),it=new ArrayBuffer(e.width*e.height*4*3),nt=new Float32Array(it);o>0;){if(c=i[j++],d=i[j++],_=i[j++],b=i[j++],c!=2||d!=2||_&128||e.width<8||e.width>32767)return this.RGBE_ReadPixels_NOT_RLE(i,e);if((_<<8|b)!=s)throw"HDR Bad header format, wrong scan line width";for($=0,et=0;et<4;et++)for(_e=(et+1)*s;$<_e;)if(c=i[j++],d=i[j++],c>128){if(k=c-128,k==0||k>_e-$)throw"HDR Bad Format, bad scanline data (run)";for(;k-- >0;)rt[$++]=d}else{if(k=c,k==0||k>_e-$)throw"HDR Bad Format, bad scanline data (non-run)";if(rt[$++]=d,--k>0)for(var ot=0;ot<k;ot++)rt[$++]=i[j++]}for(et=0;et<s;et++)c=rt[et],d=rt[et+s],_=rt[et+2*s],b=rt[et+3*s],this.Rgbe2float(nt,c,d,_,b,(e.height-o)*s*3+et*3);o--}return nt},a.RGBE_ReadPixels_NOT_RLE=function(i,e){for(var o=e.height,s=e.width,c,d,_,b,k,j=e.dataPosition,$=new ArrayBuffer(e.width*e.height*4*3),_e=new Float32Array($);o>0;){for(k=0;k<e.width;k++)c=i[j++],d=i[j++],_=i[j++],b=i[j++],this.Rgbe2float(_e,c,d,_,b,(e.height-o)*s*3+k*3);o--}return _e},a}(),EffectRenderer=function(){function a(i,e){var o,s=this;e===void 0&&(e=a._DefaultOptions),this.engine=i,this._fullscreenViewport=new Viewport(0,0,1,1),e=__assign(__assign({},a._DefaultOptions),e),this._vertexBuffers=(o={},o[VertexBuffer.PositionKind]=new VertexBuffer(i,e.positions,VertexBuffer.PositionKind,!1,!1,2),o),this._indexBuffer=i.createIndexBuffer(e.indices),this._onContextRestoredObserver=i.onContextRestoredObservable.add(function(){s._indexBuffer=i.createIndexBuffer(e.indices);for(var c in s._vertexBuffers){var d=s._vertexBuffers[c];d._rebuild()}})}return a.prototype.setViewport=function(i){i===void 0&&(i=this._fullscreenViewport),this.engine.setViewport(i)},a.prototype.bindBuffers=function(i){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,i)},a.prototype.applyEffectWrapper=function(i){this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(i._drawWrapper),this.bindBuffers(i.effect),i.onApplyObservable.notifyObservers({})},a.prototype.restoreStates=function(){this.engine.depthCullingState.depthTest=!0,this.engine.stencilState.stencilTest=!0},a.prototype.draw=function(){this.engine.drawElementsType(0,0,6)},a.prototype.isRenderTargetTexture=function(i){return i.renderTarget!==void 0},a.prototype.render=function(i,e){if(e===void 0&&(e=null),!!i.effect.isReady()){this.setViewport();var o=e===null?null:this.isRenderTargetTexture(e)?e.renderTarget:e;o&&this.engine.bindFramebuffer(o),this.applyEffectWrapper(i),this.draw(),o&&this.engine.unBindFramebuffer(o),this.restoreStates()}},a.prototype.dispose=function(){var i=this._vertexBuffers[VertexBuffer.PositionKind];i&&(i.dispose(),delete this._vertexBuffers[VertexBuffer.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)},a._DefaultOptions={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]},a}(),EffectWrapper=function(){function a(i){var e=this;this.onApplyObservable=new Observable;var o,s=i.uniformNames||[];i.vertexShader?o={fragmentSource:i.fragmentShader,vertexSource:i.vertexShader,spectorName:i.name||"effectWrapper"}:(s.push("scale"),o={fragmentSource:i.fragmentShader,vertex:"postprocess",spectorName:i.name||"effectWrapper"},this.onApplyObservable.add(function(){e.effect.setFloat2("scale",1,1)}));var c=i.defines?i.defines.join(`
  10270. `):"";this._drawWrapper=new DrawWrapper(i.engine),i.useShaderStore?(o.fragment=o.fragmentSource,o.vertex||(o.vertex=o.vertexSource),delete o.fragmentSource,delete o.vertexSource,this.effect=i.engine.createEffect(o,i.attributeNames||["position"],s,i.samplerNames,c,void 0,i.onCompiled,void 0,void 0,i.shaderLanguage)):(this.effect=new Effect$1(o,i.attributeNames||["position"],s,i.samplerNames,i.engine,c,void 0,i.onCompiled,void 0,void 0,void 0,i.shaderLanguage),this._onContextRestoredObserver=i.engine.onContextRestoredObservable.add(function(){e.effect._pipelineContext=null,e.effect._wasPreviouslyReady=!1,e.effect._prepareEffect()}))}return Object.defineProperty(a.prototype,"effect",{get:function(){return this._drawWrapper.effect},set:function(i){this._drawWrapper.effect=i},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()},a}(),name$c="hdrFilteringVertexShader",shader$c=`
  10271. attribute vec2 position;
  10272. varying vec3 direction;
  10273. uniform vec3 up;
  10274. uniform vec3 right;
  10275. uniform vec3 front;
  10276. void main(void) {
  10277. mat3 view=mat3(up,right,front);
  10278. direction=view*vec3(position,1.0);
  10279. gl_Position=vec4(position,0.0,1.0);
  10280. }`;ShaderStore.ShadersStore[name$c]=shader$c;var name$b="hdrFilteringPixelShader",shader$b=`#include<helperFunctions>
  10281. #include<importanceSampling>
  10282. #include<pbrBRDFFunctions>
  10283. #include<hdrFilteringFunctions>
  10284. uniform float alphaG;
  10285. uniform samplerCube inputTexture;
  10286. uniform vec2 vFilteringInfo;
  10287. uniform float hdrScale;
  10288. varying vec3 direction;
  10289. void main() {
  10290. vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);
  10291. gl_FragColor=vec4(color*hdrScale,1.0);
  10292. }`;ShaderStore.ShadersStore[name$b]=shader$b;var HDRFiltering=function(){function a(i,e){e===void 0&&(e={}),this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=i,this.hdrScale=e.hdrScale||this.hdrScale,this.quality=e.hdrScale||this.quality}return a.prototype._createRenderTarget=function(i){var e=0;this._engine.getCaps().textureHalfFloatRender?e=2:this._engine.getCaps().textureFloatRender&&(e=1);var o=this._engine.createRenderTargetCubeTexture(i,{format:5,type:e,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(o.texture,0,0,0),this._engine.updateTextureSamplingMode(3,o.texture,!0),o},a.prototype._prefilterInternal=function(i){var e=i.getSize().width,o=Scalar.ILog2(e)+1,s=this._effectWrapper.effect,c=this._createRenderTarget(e);this._effectRenderer.setViewport();var d=i.getInternalTexture();d&&this._engine.updateTextureSamplingMode(3,d,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);var _=[[new Vector3(0,0,-1),new Vector3(0,-1,0),new Vector3(1,0,0)],[new Vector3(0,0,1),new Vector3(0,-1,0),new Vector3(-1,0,0)],[new Vector3(1,0,0),new Vector3(0,0,1),new Vector3(0,1,0)],[new Vector3(1,0,0),new Vector3(0,0,-1),new Vector3(0,-1,0)],[new Vector3(1,0,0),new Vector3(0,-1,0),new Vector3(0,0,1)],[new Vector3(-1,0,0),new Vector3(0,-1,0),new Vector3(0,0,-1)]];s.setFloat("hdrScale",this.hdrScale),s.setFloat2("vFilteringInfo",i.getSize().width,o),s.setTexture("inputTexture",i);for(var b=0;b<6;b++){s.setVector3("up",_[b][0]),s.setVector3("right",_[b][1]),s.setVector3("front",_[b][2]);for(var k=0;k<o;k++){this._engine.bindFramebuffer(c,b,void 0,void 0,!0,k),this._effectRenderer.applyEffectWrapper(this._effectWrapper);var j=Math.pow(2,(k-this._lodGenerationOffset)/this._lodGenerationScale)/e;k===0&&(j=0),s.setFloat("alphaG",j),this._effectRenderer.draw()}}return this._effectRenderer.restoreStates(),this._engine.restoreDefaultFramebuffer(),this._engine._releaseTexture(i._texture),c._swapAndDie(i._texture),i._prefiltered=!0,i},a.prototype._createEffect=function(i,e){var o=[];i.gammaSpace&&o.push("#define GAMMA_INPUT"),o.push("#define NUM_SAMPLES "+this.quality+"u");var s=new EffectWrapper({engine:this._engine,name:"hdrFiltering",vertexShader:"hdrFiltering",fragmentShader:"hdrFiltering",samplerNames:["inputTexture"],uniformNames:["vSampleDirections","vWeights","up","right","front","vFilteringInfo","hdrScale","alphaG"],useShaderStore:!0,defines:o,onCompiled:e});return s},a.prototype.isReady=function(i){return i.isReady()&&this._effectWrapper.effect.isReady()},a.prototype.prefilter=function(i,e){var o=this;return e===void 0&&(e=null),this._engine._features.allowTexturePrefiltering?new Promise(function(s){o._effectRenderer=new EffectRenderer(o._engine),o._effectWrapper=o._createEffect(i),o._effectWrapper.effect.executeWhenCompiled(function(){o._prefilterInternal(i),o._effectRenderer.dispose(),o._effectWrapper.dispose(),s(),e&&e()})}):(Logger$2.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))},a}(),HDRCubeTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b,k,j){c===void 0&&(c=!1),d===void 0&&(d=!0),_===void 0&&(_=!1),b===void 0&&(b=!1),k===void 0&&(k=null),j===void 0&&(j=null);var $,_e=a.call(this,o)||this;return _e._generateHarmonics=!0,_e._onError=null,_e._isBlocking=!0,_e._rotationY=0,_e.boundingBoxPosition=Vector3.Zero(),_e.onLoadObservable=new Observable,e&&(_e._coordinatesMode=Texture.CUBIC_MODE,_e.name=e,_e.url=e,_e.hasAlpha=!1,_e.isCube=!0,_e._textureMatrix=Matrix.Identity(),_e._prefilterOnLoad=b,_e._onLoad=function(){_e.onLoadObservable.notifyObservers(_e),k&&k()},_e._onError=j,_e.gammaSpace=_,_e._noMipmap=c,_e._size=s,_e._generateHarmonics=d,_e._texture=_e._getFromCache(e,_e._noMipmap),_e._texture?_e._texture.isReady?Tools.SetImmediate(function(){return _e._onLoad()}):_e._texture.onLoadedObservable.add(_e._onLoad):!(($=_e.getScene())===null||$===void 0)&&$.useDelayedTextureLoading?_e.delayLoadState=4:_e.loadTexture()),_e}return Object.defineProperty(i.prototype,"isBlocking",{get:function(){return this._isBlocking},set:function(e){this._isBlocking=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rotationY",{get:function(){return this._rotationY},set:function(e){this._rotationY=e,this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY))},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!(this._boundingBoxSize&&this._boundingBoxSize.equals(e))){this._boundingBoxSize=e;var o=this.getScene();o&&o.markAllMaterialsAsDirty(1)}},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"HDRCubeTexture"},i.prototype.loadTexture=function(){var e=this,o=this._getEngine(),s=o.getCaps(),c=0;s.textureFloat&&s.textureFloatLinearFiltering?c=1:s.textureHalfFloat&&s.textureHalfFloatLinearFiltering&&(c=2);var d=function(k){e.lodGenerationOffset=0,e.lodGenerationScale=.8;var j=HDRTools.GetCubeMapTextureData(k,e._size);if(e._generateHarmonics){var $=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(j);e.sphericalPolynomial=$}for(var _e=[],et=null,tt=null,rt=0;rt<6;rt++){c===2?tt=new Uint16Array(e._size*e._size*3):c===0&&(et=new Uint8Array(e._size*e._size*3));var it=j[i._facesMapping[rt]];if(e.gammaSpace||tt||et){for(var nt=0;nt<e._size*e._size;nt++)if(e.gammaSpace&&(it[nt*3+0]=Math.pow(it[nt*3+0],ToGammaSpace),it[nt*3+1]=Math.pow(it[nt*3+1],ToGammaSpace),it[nt*3+2]=Math.pow(it[nt*3+2],ToGammaSpace)),tt&&(tt[nt*3+0]=ToHalfFloat(it[nt*3+0]),tt[nt*3+1]=ToHalfFloat(it[nt*3+1]),tt[nt*3+2]=ToHalfFloat(it[nt*3+2])),et){var ot=Math.max(it[nt*3+0]*255,0),at=Math.max(it[nt*3+1]*255,0),st=Math.max(it[nt*3+2]*255,0),ut=Math.max(Math.max(ot,at),st);if(ut>255){var ft=255/ut;ot*=ft,at*=ft,st*=ft}et[nt*3+0]=ot,et[nt*3+1]=at,et[nt*3+2]=st}}tt?_e.push(tt):et?_e.push(et):_e.push(it)}return _e};if(o._features.allowTexturePrefiltering&&this._prefilterOnLoad){var _=this._onLoad,b=new HDRFiltering(o);this._onLoad=function(){b.prefilter(e,_)}}this._texture=o.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,c,this._noMipmap,d,null,this._onLoad,this._onError)},i.prototype.clone=function(){var e=new i(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e},i.prototype.delayLoad=function(){this.delayLoadState===4&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.prototype.setReflectionTextureMatrix=function(e){var o=this,s;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&((s=this.getScene())===null||s===void 0||s.markAllMaterialsAsDirty(1,function(c){return c.getActiveTextures().indexOf(o)!==-1}))},i.prototype.dispose=function(){this.onLoadObservable.clear(),a.prototype.dispose.call(this)},i.Parse=function(e,o,s){var c=null;return e.name&&!e.isRenderTarget&&(c=new i(s+e.name,o,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),c.name=e.name,c.hasAlpha=e.hasAlpha,c.level=e.level,c.coordinatesMode=e.coordinatesMode,c.isBlocking=e.isBlocking),c&&(e.boundingBoxPosition&&(c.boundingBoxPosition=Vector3.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(c.boundingBoxSize=Vector3.FromArray(e.boundingBoxSize)),e.rotationY&&(c.rotationY=e.rotationY)),c},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e},i._facesMapping=["right","left","up","down","front","back"],i}(BaseTexture);RegisterClass("BABYLON.HDRCubeTexture",HDRCubeTexture);var PhysicsJoint=function(){function a(i,e){this.type=i,this.jointData=e,e.nativeParams=e.nativeParams||{}}return Object.defineProperty(a.prototype,"physicsJoint",{get:function(){return this._physicsJoint},set:function(i){this._physicsJoint,this._physicsJoint=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"physicsPlugin",{set:function(i){this._physicsPlugin=i},enumerable:!1,configurable:!0}),a.prototype.executeNativeFunction=function(i){i(this._physicsPlugin.world,this._physicsJoint)},a.DistanceJoint=0,a.HingeJoint=1,a.BallAndSocketJoint=2,a.WheelJoint=3,a.SliderJoint=4,a.PrismaticJoint=5,a.UniversalJoint=6,a.Hinge2Joint=a.WheelJoint,a.PointToPointJoint=8,a.SpringJoint=9,a.LockJoint=10,a}();(function(a){__extends(i,a);function i(e){return a.call(this,PhysicsJoint.DistanceJoint,e)||this}return i.prototype.updateDistance=function(e,o){this._physicsPlugin.updateDistanceJoint(this,e,o)},i})(PhysicsJoint);var MotorEnabledJoint=function(a){__extends(i,a);function i(e,o){return a.call(this,e,o)||this}return i.prototype.setMotor=function(e,o){this._physicsPlugin.setMotor(this,e||0,o)},i.prototype.setLimit=function(e,o){this._physicsPlugin.setLimit(this,e,o)},i}(PhysicsJoint);(function(a){__extends(i,a);function i(e){return a.call(this,PhysicsJoint.HingeJoint,e)||this}return i.prototype.setMotor=function(e,o){this._physicsPlugin.setMotor(this,e||0,o)},i.prototype.setLimit=function(e,o){this._physicsPlugin.setLimit(this,e,o)},i})(MotorEnabledJoint);(function(a){__extends(i,a);function i(e){return a.call(this,PhysicsJoint.Hinge2Joint,e)||this}return i.prototype.setMotor=function(e,o,s){s===void 0&&(s=0),this._physicsPlugin.setMotor(this,e||0,o,s)},i.prototype.setLimit=function(e,o,s){s===void 0&&(s=0),this._physicsPlugin.setLimit(this,e,o,s)},i})(MotorEnabledJoint);Mesh._PhysicsImpostorParser=function(a,i,e){return new PhysicsImpostor(i,e.physicsImpostor,{mass:e.physicsMass,friction:e.physicsFriction,restitution:e.physicsRestitution},a)};var PhysicsImpostor=function(){function a(i,e,o,s){var c=this;if(o===void 0&&(o={mass:0}),this.object=i,this.type=e,this._options=o,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=Vector3.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new Quaternion,this._tmpQuat2=new Quaternion,this.beforeStep=function(){!c._physicsEngine||(c.object.translate(c._deltaPosition,-1),c._deltaRotationConjugated&&c.object.rotationQuaternion&&c.object.rotationQuaternion.multiplyToRef(c._deltaRotationConjugated,c.object.rotationQuaternion),c.object.computeWorldMatrix(!1),c.object.parent&&c.object.rotationQuaternion?(c.getParentsRotation(),c._tmpQuat.multiplyToRef(c.object.rotationQuaternion,c._tmpQuat)):c._tmpQuat.copyFrom(c.object.rotationQuaternion||new Quaternion),c._options.disableBidirectionalTransformation||c.object.rotationQuaternion&&c._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(c,c.object.getAbsolutePosition(),c._tmpQuat),c._onBeforePhysicsStepCallbacks.forEach(function(d){d(c)}))},this.afterStep=function(){!c._physicsEngine||(c._onAfterPhysicsStepCallbacks.forEach(function(d){d(c)}),c._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(c),c.object.parent&&c.object.rotationQuaternion&&(c.getParentsRotation(),c._tmpQuat.conjugateInPlace(),c._tmpQuat.multiplyToRef(c.object.rotationQuaternion,c.object.rotationQuaternion)),c.object.setAbsolutePosition(c.object.position),c._deltaRotation&&c.object.rotationQuaternion&&c.object.rotationQuaternion.multiplyToRef(c._deltaRotation,c.object.rotationQuaternion),c.object.translate(c._deltaPosition,1))},this.onCollideEvent=null,this.onCollide=function(d){if(!(!c._onPhysicsCollideCallbacks.length&&!c.onCollideEvent)&&!!c._physicsEngine){var _=c._physicsEngine.getImpostorWithPhysicsBody(d.body);_&&(c.onCollideEvent&&c.onCollideEvent(c,_),c._onPhysicsCollideCallbacks.filter(function(b){return b.otherImpostors.indexOf(_)!==-1}).forEach(function(b){b.callback(c,_,d.point)}))}},!this.object){Logger$2.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&o.mass!==0&&Logger$2.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&i.getScene&&(this._scene=i.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=Quaternion.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new Quaternion),this._options.mass=o.mass===void 0?0:o.mass,this._options.friction=o.friction===void 0?.2:o.friction,this._options.restitution=o.restitution===void 0?.2:o.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=o.pressure===void 0?200:o.pressure,this._options.stiffness=o.stiffness===void 0?1:o.stiffness,this._options.velocityIterations=o.velocityIterations===void 0?20:o.velocityIterations,this._options.positionIterations=o.positionIterations===void 0?20:o.positionIterations,this._options.fixedPoints=o.fixedPoints===void 0?0:o.fixedPoints,this._options.margin=o.margin===void 0?0:o.margin,this._options.damping=o.damping===void 0?0:o.damping,this._options.path=o.path===void 0?null:o.path,this._options.shape=o.shape===void 0?null:o.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&Logger$2.Warn("You must affect impostors to children before affecting impostor to parent.")):Logger$2.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))}return Object.defineProperty(a.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"mass",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0},set:function(i){this.setMass(i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"friction",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0},set:function(i){!this._physicsEngine||this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"restitution",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0},set:function(i){!this._physicsEngine||this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"pressure",{get:function(){if(!this._physicsEngine)return 0;var i=this._physicsEngine.getPhysicsPlugin();return i.setBodyPressure?i.getBodyPressure(this):0},set:function(i){if(!!this._physicsEngine){var e=this._physicsEngine.getPhysicsPlugin();!e.setBodyPressure||e.setBodyPressure(this,i)}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"stiffness",{get:function(){if(!this._physicsEngine)return 0;var i=this._physicsEngine.getPhysicsPlugin();return i.getBodyStiffness?i.getBodyStiffness(this):0},set:function(i){if(!!this._physicsEngine){var e=this._physicsEngine.getPhysicsPlugin();!e.setBodyStiffness||e.setBodyStiffness(this,i)}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"velocityIterations",{get:function(){if(!this._physicsEngine)return 0;var i=this._physicsEngine.getPhysicsPlugin();return i.getBodyVelocityIterations?i.getBodyVelocityIterations(this):0},set:function(i){if(!!this._physicsEngine){var e=this._physicsEngine.getPhysicsPlugin();!e.setBodyVelocityIterations||e.setBodyVelocityIterations(this,i)}},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"positionIterations",{get:function(){if(!this._physicsEngine)return 0;var i=this._physicsEngine.getPhysicsPlugin();return i.getBodyPositionIterations?i.getBodyPositionIterations(this):0},set:function(i){if(!!this._physicsEngine){var e=this._physicsEngine.getPhysicsPlugin();!e.setBodyPositionIterations||e.setBodyPositionIterations(this,i)}},enumerable:!1,configurable:!0}),a.prototype._init=function(){!this._physicsEngine||(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),!this._isDisposed&&(!this.parent||this._options.ignoreParent)&&this._physicsEngine.addImpostor(this))},a.prototype._getPhysicsParent=function(){if(this.object.parent instanceof AbstractMesh){var i=this.object.parent;return i.physicsImpostor}return null},a.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&!this._parent},a.prototype.setScalingUpdated=function(){this.forceUpdate()},a.prototype.forceUpdate=function(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()},Object.defineProperty(a.prototype,"physicsBody",{get:function(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody},set:function(i){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=i,this.resetUpdateFlags()},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"parent",{get:function(){return!this._options.ignoreParent&&this._parent?this._parent:null},set:function(i){this._parent=i},enumerable:!1,configurable:!0}),a.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},a.prototype.getObjectExtendSize=function(){if(this.object.getBoundingInfo){var i=this.object.rotationQuaternion,e=this.object.scaling.clone();this.object.rotationQuaternion=a.IDENTITY_QUATERNION;var o=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);o&&o.decompose(e,void 0,void 0);var s=this.object.getBoundingInfo(),c=s.boundingBox.extendSize.scale(2).multiplyInPlace(e);return c.x=Math.abs(c.x),c.y=Math.abs(c.y),c.z=Math.abs(c.z),this.object.rotationQuaternion=i,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),c}else return a.DEFAULT_OBJECT_SIZE},a.prototype.getObjectCenter=function(){if(this.object.getBoundingInfo){var i=this.object.getBoundingInfo();return i.boundingBox.centerWorld}else return this.object.position},a.prototype.getParam=function(i){return this._options[i]},a.prototype.setParam=function(i,e){this._options[i]=e,this._bodyUpdateRequired=!0},a.prototype.setMass=function(i){this.getParam("mass")!==i&&this.setParam("mass",i),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,i)},a.prototype.getLinearVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):Vector3.Zero()},a.prototype.setLinearVelocity=function(i){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,i)},a.prototype.getAngularVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):Vector3.Zero()},a.prototype.setAngularVelocity=function(i){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,i)},a.prototype.executeNativeFunction=function(i){this._physicsEngine&&i(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},a.prototype.registerBeforePhysicsStep=function(i){this._onBeforePhysicsStepCallbacks.push(i)},a.prototype.unregisterBeforePhysicsStep=function(i){var e=this._onBeforePhysicsStepCallbacks.indexOf(i);e>-1?this._onBeforePhysicsStepCallbacks.splice(e,1):Logger$2.Warn("Function to remove was not found")},a.prototype.registerAfterPhysicsStep=function(i){this._onAfterPhysicsStepCallbacks.push(i)},a.prototype.unregisterAfterPhysicsStep=function(i){var e=this._onAfterPhysicsStepCallbacks.indexOf(i);e>-1?this._onAfterPhysicsStepCallbacks.splice(e,1):Logger$2.Warn("Function to remove was not found")},a.prototype.registerOnPhysicsCollide=function(i,e){var o=i instanceof Array?i:[i];this._onPhysicsCollideCallbacks.push({callback:e,otherImpostors:o})},a.prototype.unregisterOnPhysicsCollide=function(i,e){var o=i instanceof Array?i:[i],s=-1,c=this._onPhysicsCollideCallbacks.some(function(d,_){if(d.callback===e&&d.otherImpostors.length===o.length){var b=d.otherImpostors.every(function(k){return o.indexOf(k)>-1});return b&&(s=_),b}return!1});c?this._onPhysicsCollideCallbacks.splice(s,1):Logger$2.Warn("Function to remove was not found")},a.prototype.getParentsRotation=function(){var i=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);i;)i.rotationQuaternion?this._tmpQuat2.copyFrom(i.rotationQuaternion):Quaternion.RotationYawPitchRollToRef(i.rotation.y,i.rotation.x,i.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),i=i.parent;return this._tmpQuat},a.prototype.applyForce=function(i,e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,i,e),this},a.prototype.applyImpulse=function(i,e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,i,e),this},a.prototype.createJoint=function(i,e,o){var s=new PhysicsJoint(e,o);return this.addJoint(i,s),this},a.prototype.addJoint=function(i,e){return this._joints.push({otherImpostor:i,joint:e}),this._physicsEngine&&this._physicsEngine.addJoint(this,i,e),this},a.prototype.addAnchor=function(i,e,o,s,c){if(!this._physicsEngine)return this;var d=this._physicsEngine.getPhysicsPlugin();return d.appendAnchor?(this._physicsEngine&&d.appendAnchor(this,i,e,o,s,c),this):this},a.prototype.addHook=function(i,e,o,s){if(!this._physicsEngine)return this;var c=this._physicsEngine.getPhysicsPlugin();return c.appendAnchor?(this._physicsEngine&&c.appendHook(this,i,e,o,s),this):this},a.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},a.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},a.prototype.clone=function(i){return i?new a(i,this.type,this._options,this._scene):null},a.prototype.dispose=function(){var i=this;!this._physicsEngine||(this._joints.forEach(function(e){i._physicsEngine&&i._physicsEngine.removeJoint(i,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},a.prototype.setDeltaPosition=function(i){this._deltaPosition.copyFrom(i)},a.prototype.setDeltaRotation=function(i){this._deltaRotation||(this._deltaRotation=new Quaternion),this._deltaRotation.copyFrom(i),this._deltaRotationConjugated=this._deltaRotation.conjugate()},a.prototype.getBoxSizeToRef=function(i){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,i),this},a.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},a.prototype.syncBoneWithImpostor=function(i,e,o,s,c){var d=a._tmpVecs[0],_=this.object;if(_.rotationQuaternion)if(c){var b=a._tmpQuat;_.rotationQuaternion.multiplyToRef(c,b),i.setRotationQuaternion(b,Space.WORLD,e)}else i.setRotationQuaternion(_.rotationQuaternion,Space.WORLD,e);d.x=0,d.y=0,d.z=0,o&&(d.x=o.x,d.y=o.y,d.z=o.z,i.getDirectionToRef(d,e,d),s==null&&(s=o.length()),d.x*=s,d.y*=s,d.z*=s),i.getParent()?(d.addInPlace(_.getAbsolutePosition()),i.setAbsolutePosition(d,e)):(e.setAbsolutePosition(_.getAbsolutePosition()),e.position.x-=d.x,e.position.y-=d.y,e.position.z-=d.z)},a.prototype.syncImpostorWithBone=function(i,e,o,s,c,d){var _=this.object;if(_.rotationQuaternion)if(c){var b=a._tmpQuat;i.getRotationQuaternionToRef(Space.WORLD,e,b),b.multiplyToRef(c,_.rotationQuaternion)}else i.getRotationQuaternionToRef(Space.WORLD,e,_.rotationQuaternion);var k=a._tmpVecs[0],j=a._tmpVecs[1];d||(d=a._tmpVecs[2],d.x=0,d.y=1,d.z=0),i.getDirectionToRef(d,e,j),i.getAbsolutePositionToRef(e,k),s==null&&o&&(s=o.length()),s!=null&&(k.x+=j.x*s,k.y+=j.y*s,k.z+=j.z*s),_.setAbsolutePosition(k)},a.DEFAULT_OBJECT_SIZE=new Vector3(1,1,1),a.IDENTITY_QUATERNION=Quaternion.Identity(),a._tmpVecs=ArrayTools.BuildArray(3,Vector3.Zero),a._tmpQuat=Quaternion.Identity(),a.NoImpostor=0,a.SphereImpostor=1,a.BoxImpostor=2,a.PlaneImpostor=3,a.MeshImpostor=4,a.CapsuleImpostor=6,a.CylinderImpostor=7,a.ParticleImpostor=8,a.HeightmapImpostor=9,a.ConvexHullImpostor=10,a.CustomImpostor=100,a.RopeImpostor=101,a.ClothImpostor=102,a.SoftbodyImpostor=103,a}(),PhysicsEngine=function(){function a(i,e){if(e===void 0&&(e=a.DefaultPluginFactory()),this._physicsPlugin=e,this._impostors=[],this._joints=[],this._subTimeStep=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");i=i||new Vector3(0,-9.807,0),this.setGravity(i),this.setTimeStep()}return a.DefaultPluginFactory=function(){throw _WarnImport("CannonJSPlugin")},a.prototype.setGravity=function(i){this.gravity=i,this._physicsPlugin.setGravity(this.gravity)},a.prototype.setTimeStep=function(i){i===void 0&&(i=1/60),this._physicsPlugin.setTimeStep(i)},a.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},a.prototype.setSubTimeStep=function(i){i===void 0&&(i=0),this._subTimeStep=i},a.prototype.getSubTimeStep=function(){return this._subTimeStep},a.prototype.dispose=function(){this._impostors.forEach(function(i){i.dispose()}),this._physicsPlugin.dispose()},a.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},a.prototype.addImpostor=function(i){i.uniqueId=this._impostors.push(i),i.parent||this._physicsPlugin.generatePhysicsBody(i)},a.prototype.removeImpostor=function(i){var e=this._impostors.indexOf(i);if(e>-1){var o=this._impostors.splice(e,1);o.length&&this.getPhysicsPlugin().removePhysicsBody(i)}},a.prototype.addJoint=function(i,e,o){var s={mainImpostor:i,connectedImpostor:e,joint:o};o.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)},a.prototype.removeJoint=function(i,e,o){var s=this._joints.filter(function(c){return c.connectedImpostor===e&&c.joint===o&&c.mainImpostor===i});s.length&&this._physicsPlugin.removeJoint(s[0])},a.prototype._step=function(i){var e=this;this._impostors.forEach(function(o){o.isBodyInitRequired()&&e._physicsPlugin.generatePhysicsBody(o)}),i>.1?i=.1:i<=0&&(i=1/60),this._physicsPlugin.executeStep(i,this._impostors)},a.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},a.prototype.getImpostors=function(){return this._impostors},a.prototype.getImpostorForPhysicsObject=function(i){for(var e=0;e<this._impostors.length;++e)if(this._impostors[e].object===i)return this._impostors[e];return null},a.prototype.getImpostorWithPhysicsBody=function(i){for(var e=0;e<this._impostors.length;++e)if(this._impostors[e].physicsBody===i)return this._impostors[e];return null},a.prototype.raycast=function(i,e){return this._physicsPlugin.raycast(i,e)},a.Epsilon=.001,a}(),PhysicsRaycastResult=function(){function a(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=Vector3.Zero(),this._hitPointWorld=Vector3.Zero(),this._rayFromWorld=Vector3.Zero(),this._rayToWorld=Vector3.Zero()}return Object.defineProperty(a.prototype,"hasHit",{get:function(){return this._hasHit},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hitDistance",{get:function(){return this._hitDistance},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hitNormalWorld",{get:function(){return this._hitNormalWorld},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hitPointWorld",{get:function(){return this._hitPointWorld},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rayFromWorld",{get:function(){return this._rayFromWorld},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rayToWorld",{get:function(){return this._rayToWorld},enumerable:!1,configurable:!0}),a.prototype.setHitData=function(i,e){this._hasHit=!0,this._hitNormalWorld=new Vector3(i.x,i.y,i.z),this._hitPointWorld=new Vector3(e.x,e.y,e.z)},a.prototype.setHitDistance=function(i){this._hitDistance=i},a.prototype.calculateHitDistance=function(){this._hitDistance=Vector3.Distance(this._rayFromWorld,this._hitPointWorld)},a.prototype.reset=function(i,e){i===void 0&&(i=Vector3.Zero()),e===void 0&&(e=Vector3.Zero()),this._rayFromWorld=i,this._rayToWorld=e,this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=Vector3.Zero(),this._hitPointWorld=Vector3.Zero()},a}(),CannonJSPlugin=function(){function a(i,e,o){if(i===void 0&&(i=!0),e===void 0&&(e=10),o===void 0&&(o=CANNON),this._useDeltaForWorldStep=i,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this._physicsBodysToRemoveAfterStep=new Array,this._firstFrame=!0,this._tmpQuaternion=new Quaternion,this._minus90X=new Quaternion(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=Vector3.Zero(),this._tmpDeltaPosition=Vector3.Zero(),this._tmpUnityRotation=new Quaternion,this.BJSCANNON=o,!this.isSupported()){Logger$2.Error("CannonJS is not available. Please make sure you included the js file.");return}this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=e,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new PhysicsRaycastResult}return a.prototype.setGravity=function(i){var e=i;this.world.gravity.set(e.x,e.y,e.z)},a.prototype.setTimeStep=function(i){this._fixedTimeStep=i},a.prototype.getTimeStep=function(){return this._fixedTimeStep},a.prototype.executeStep=function(i,e){if(this._firstFrame){this._firstFrame=!1;for(var o=0,s=e;o<s.length;o++){var c=s[o];c.type==PhysicsImpostor.HeightmapImpostor||c.type===PhysicsImpostor.PlaneImpostor||c.beforeStep()}}this.world.step(this._useDeltaForWorldStep?i:this._fixedTimeStep),this._removeMarkedPhysicsBodiesFromWorld()},a.prototype._removeMarkedPhysicsBodiesFromWorld=function(){var i=this;this._physicsBodysToRemoveAfterStep.length>0&&(this._physicsBodysToRemoveAfterStep.forEach(function(e){typeof i.world.removeBody=="function"?i.world.removeBody(e):i.world.remove(e)}),this._physicsBodysToRemoveAfterStep=[])},a.prototype.applyImpulse=function(i,e,o){var s=new this.BJSCANNON.Vec3(o.x,o.y,o.z),c=new this.BJSCANNON.Vec3(e.x,e.y,e.z);i.physicsBody.applyImpulse(c,s)},a.prototype.applyForce=function(i,e,o){var s=new this.BJSCANNON.Vec3(o.x,o.y,o.z),c=new this.BJSCANNON.Vec3(e.x,e.y,e.z);i.physicsBody.applyForce(c,s)},a.prototype.generatePhysicsBody=function(i){if(this._removeMarkedPhysicsBodiesFromWorld(),i.parent){i.physicsBody&&(this.removePhysicsBody(i),i.forceUpdate());return}if(i.isBodyInitRequired()){var e=this._createShape(i),o=i.physicsBody;o&&this.removePhysicsBody(i);var s=this._addMaterial("mat-"+i.uniqueId,i.getParam("friction"),i.getParam("restitution")),c={mass:i.getParam("mass"),material:s},d=i.getParam("nativeOptions");for(var _ in d)d.hasOwnProperty(_)&&(c[_]=d[_]);i.physicsBody=new this.BJSCANNON.Body(c),i.physicsBody.addEventListener("collide",i.onCollide),this.world.addEventListener("preStep",i.beforeStep),this.world.addEventListener("postStep",i.afterStep),i.physicsBody.addShape(e),typeof this.world.addBody=="function"?this.world.addBody(i.physicsBody):this.world.add(i.physicsBody),o&&["force","torque","velocity","angularVelocity"].forEach(function(b){var k=o[b];i.physicsBody[b].set(k.x,k.y,k.z)}),this._processChildMeshes(i)}this._updatePhysicsBodyTransformation(i)},a.prototype._processChildMeshes=function(i){var e=this,o=i.object.getChildMeshes?i.object.getChildMeshes(!0):[],s=i.object.rotationQuaternion;if(s?s.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),o.length){var c=function(d){if(!!d.rotationQuaternion){var _=d.getPhysicsImpostor();if(_){var b=_.parent;if(b!==i&&d.parent){var k=d.getAbsolutePosition().subtract(d.parent.getAbsolutePosition()),j=d.rotationQuaternion.multiply(e._tmpQuaternion);_.physicsBody&&(e.removePhysicsBody(_),_.physicsBody=null),_.parent=i,_.resetUpdateFlags(),i.physicsBody.addShape(e._createShape(_),new e.BJSCANNON.Vec3(k.x,k.y,k.z),new e.BJSCANNON.Quaternion(j.x,j.y,j.z,j.w)),i.physicsBody.mass+=_.getParam("mass")}}d.getChildMeshes(!0).filter(function($){return!!$.physicsImpostor}).forEach(c)}};o.filter(function(d){return!!d.physicsImpostor}).forEach(c)}},a.prototype.removePhysicsBody=function(i){i.physicsBody.removeEventListener("collide",i.onCollide),this.world.removeEventListener("preStep",i.beforeStep),this.world.removeEventListener("postStep",i.afterStep),this._physicsBodysToRemoveAfterStep.indexOf(i.physicsBody)===-1&&this._physicsBodysToRemoveAfterStep.push(i.physicsBody)},a.prototype.generateJoint=function(i){var e=i.mainImpostor.physicsBody,o=i.connectedImpostor.physicsBody;if(!(!e||!o)){var s,c=i.joint.jointData,d={pivotA:c.mainPivot?new this.BJSCANNON.Vec3().set(c.mainPivot.x,c.mainPivot.y,c.mainPivot.z):null,pivotB:c.connectedPivot?new this.BJSCANNON.Vec3().set(c.connectedPivot.x,c.connectedPivot.y,c.connectedPivot.z):null,axisA:c.mainAxis?new this.BJSCANNON.Vec3().set(c.mainAxis.x,c.mainAxis.y,c.mainAxis.z):null,axisB:c.connectedAxis?new this.BJSCANNON.Vec3().set(c.connectedAxis.x,c.connectedAxis.y,c.connectedAxis.z):null,maxForce:c.nativeParams.maxForce,collideConnected:!!c.collision};switch(i.joint.type){case PhysicsJoint.HingeJoint:case PhysicsJoint.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(e,o,d);break;case PhysicsJoint.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(e,o,c.maxDistance||2);break;case PhysicsJoint.SpringJoint:var _=c;s=new this.BJSCANNON.Spring(e,o,{restLength:_.length,stiffness:_.stiffness,damping:_.damping,localAnchorA:d.pivotA,localAnchorB:d.pivotB});break;case PhysicsJoint.LockJoint:s=new this.BJSCANNON.LockConstraint(e,o,d);break;case PhysicsJoint.PointToPointJoint:case PhysicsJoint.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(e,d.pivotA,o,d.pivotB,d.maxForce);break}s.collideConnected=!!c.collision,i.joint.physicsJoint=s,i.joint.type!==PhysicsJoint.SpringJoint?this.world.addConstraint(s):(i.joint.jointData.forceApplicationCallback=i.joint.jointData.forceApplicationCallback||function(){s.applyForce()},i.mainImpostor.registerAfterPhysicsStep(i.joint.jointData.forceApplicationCallback))}},a.prototype.removeJoint=function(i){i.joint.type!==PhysicsJoint.SpringJoint?this.world.removeConstraint(i.joint.physicsJoint):i.mainImpostor.unregisterAfterPhysicsStep(i.joint.jointData.forceApplicationCallback)},a.prototype._addMaterial=function(i,e,o){var s,c;for(s=0;s<this._physicsMaterials.length;s++)if(c=this._physicsMaterials[s],c.friction===e&&c.restitution===o)return c;var d=new this.BJSCANNON.Material(i);return d.friction=e,d.restitution=o,this._physicsMaterials.push(d),d},a.prototype._checkWithEpsilon=function(i){return i<PhysicsEngine.Epsilon?PhysicsEngine.Epsilon:i},a.prototype._createShape=function(i){var e=i.object,o,s=i.getObjectExtendSize();switch(i.type){case PhysicsImpostor.SphereImpostor:var c=s.x,d=s.y,_=s.z;o=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(c),this._checkWithEpsilon(d),this._checkWithEpsilon(_))/2);break;case PhysicsImpostor.CylinderImpostor:var b=i.getParam("nativeOptions");b||(b={});var k=b.radiusTop!==void 0?b.radiusTop:this._checkWithEpsilon(s.x)/2,j=b.radiusBottom!==void 0?b.radiusBottom:this._checkWithEpsilon(s.x)/2,$=b.height!==void 0?b.height:this._checkWithEpsilon(s.y),_e=b.numSegments!==void 0?b.numSegments:16;o=new this.BJSCANNON.Cylinder(k,j,$,_e);var et=new this.BJSCANNON.Quaternion;et.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);var tt=new this.BJSCANNON.Vec3(0,0,0);o.transformAllPoints(tt,et);break;case PhysicsImpostor.BoxImpostor:var rt=s.scale(.5);o=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(rt.x),this._checkWithEpsilon(rt.y),this._checkWithEpsilon(rt.z)));break;case PhysicsImpostor.PlaneImpostor:Logger$2.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),o=new this.BJSCANNON.Plane;break;case PhysicsImpostor.MeshImpostor:var it=e.getVerticesData?e.getVerticesData(VertexBuffer.PositionKind):[],nt=e.getIndices?e.getIndices():[];if(!it)return;var ot=e.position.clone(),at=e.rotation&&e.rotation.clone(),st=e.rotationQuaternion&&e.rotationQuaternion.clone();e.position.copyFromFloats(0,0,0),e.rotation&&e.rotation.copyFromFloats(0,0,0),e.rotationQuaternion&&e.rotationQuaternion.copyFrom(i.getParentsRotation()),e.rotationQuaternion&&e.parent&&e.rotationQuaternion.conjugateInPlace();var ut=e.computeWorldMatrix(!0),ft=new Array,lt;for(lt=0;lt<it.length;lt+=3)Vector3.TransformCoordinates(Vector3.FromArray(it,lt),ut).toArray(ft,lt);Logger$2.Warn("MeshImpostor only collides against spheres."),o=new this.BJSCANNON.Trimesh(ft,nt),e.position.copyFrom(ot),at&&e.rotation&&e.rotation.copyFrom(at),st&&e.rotationQuaternion&&e.rotationQuaternion.copyFrom(st);break;case PhysicsImpostor.HeightmapImpostor:var ht=e.position.clone(),pt=e.rotation&&e.rotation.clone(),mt=e.rotationQuaternion&&e.rotationQuaternion.clone();e.position.copyFromFloats(0,0,0),e.rotation&&e.rotation.copyFromFloats(0,0,0),e.rotationQuaternion&&e.rotationQuaternion.copyFrom(i.getParentsRotation()),e.rotationQuaternion&&e.parent&&e.rotationQuaternion.conjugateInPlace(),e.rotationQuaternion&&e.rotationQuaternion.multiplyInPlace(this._minus90X),o=this._createHeightmap(e),e.position.copyFrom(ht),pt&&e.rotation&&e.rotation.copyFrom(pt),mt&&e.rotationQuaternion&&e.rotationQuaternion.copyFrom(mt),e.computeWorldMatrix(!0);break;case PhysicsImpostor.ParticleImpostor:o=new this.BJSCANNON.Particle;break;case PhysicsImpostor.NoImpostor:o=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0));break}return o},a.prototype._createHeightmap=function(i,e){var o=i.getVerticesData(VertexBuffer.PositionKind),s=i.computeWorldMatrix(!0),c=new Array,d;for(d=0;d<o.length;d+=3)Vector3.TransformCoordinates(Vector3.FromArray(o,d),s).toArray(c,d);o=c;for(var _=new Array,b=e||~~(Math.sqrt(o.length/3)-1),k=i.getBoundingInfo(),j=Math.min(k.boundingBox.extendSizeWorld.x,k.boundingBox.extendSizeWorld.y),$=k.boundingBox.extendSizeWorld.z,_e=j*2/b,et=0;et<o.length;et=et+3){var tt=Math.round(o[et+0]/_e+b/2),rt=Math.round((o[et+1]/_e-b/2)*-1),it=-o[et+2]+$;_[tt]||(_[tt]=[]),_[tt][rt]||(_[tt][rt]=it),_[tt][rt]=Math.max(it,_[tt][rt])}for(var tt=0;tt<=b;++tt){if(!_[tt]){for(var nt=1;!_[(tt+nt)%b];)nt++;_[tt]=_[(tt+nt)%b].slice()}for(var rt=0;rt<=b;++rt)if(!_[tt][rt]){for(var nt=1,ot;ot===void 0;)ot=_[tt][(rt+nt++)%b];_[tt][rt]=ot}}var at=new this.BJSCANNON.Heightfield(_,{elementSize:_e});return at.minY=$,at},a.prototype._updatePhysicsBodyTransformation=function(i){var e=i.object;if(e.computeWorldMatrix&&e.computeWorldMatrix(!0),!!e.getBoundingInfo()){var o=i.getObjectCenter();this._tmpDeltaPosition.copyFrom(e.getAbsolutePivotPoint().subtract(o)),this._tmpDeltaPosition.divideInPlace(i.object.scaling),this._tmpPosition.copyFrom(o);var s=e.rotationQuaternion;if(!!s){if((i.type===PhysicsImpostor.PlaneImpostor||i.type===PhysicsImpostor.HeightmapImpostor)&&(s=s.multiply(this._minus90X),i.setDeltaRotation(this._plus90X)),i.type===PhysicsImpostor.HeightmapImpostor){var c=e,d=c.getBoundingInfo(),_=c.rotationQuaternion;c.rotationQuaternion=this._tmpUnityRotation,c.computeWorldMatrix(!0);var b=o.clone(),k=c.getPivotMatrix();k?k=k.clone():k=Matrix.Identity();var j=Matrix.Translation(d.boundingBox.extendSizeWorld.x,0,-d.boundingBox.extendSizeWorld.z);c.setPreTransformMatrix(j),c.computeWorldMatrix(!0),d=c.getBoundingInfo();var $=d.boundingBox.centerWorld.subtract(o).subtract(c.position).negate();this._tmpPosition.copyFromFloats($.x,$.y-d.boundingBox.extendSizeWorld.y,$.z),this._tmpDeltaPosition.copyFrom(d.boundingBox.centerWorld.subtract(b)),this._tmpDeltaPosition.y+=d.boundingBox.extendSizeWorld.y,c.rotationQuaternion=_,c.setPreTransformMatrix(k),c.computeWorldMatrix(!0)}else i.type===PhysicsImpostor.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);i.setDeltaPosition(this._tmpDeltaPosition),i.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),i.physicsBody.quaternion.set(s.x,s.y,s.z,s.w)}}},a.prototype.setTransformationFromPhysicsBody=function(i){if(i.object.position.set(i.physicsBody.position.x,i.physicsBody.position.y,i.physicsBody.position.z),i.object.rotationQuaternion){var e=i.physicsBody.quaternion;i.object.rotationQuaternion.set(e.x,e.y,e.z,e.w)}},a.prototype.setPhysicsBodyTransformation=function(i,e,o){i.physicsBody.position.set(e.x,e.y,e.z),i.physicsBody.quaternion.set(o.x,o.y,o.z,o.w)},a.prototype.isSupported=function(){return this.BJSCANNON!==void 0},a.prototype.setLinearVelocity=function(i,e){i.physicsBody.velocity.set(e.x,e.y,e.z)},a.prototype.setAngularVelocity=function(i,e){i.physicsBody.angularVelocity.set(e.x,e.y,e.z)},a.prototype.getLinearVelocity=function(i){var e=i.physicsBody.velocity;return e?new Vector3(e.x,e.y,e.z):null},a.prototype.getAngularVelocity=function(i){var e=i.physicsBody.angularVelocity;return e?new Vector3(e.x,e.y,e.z):null},a.prototype.setBodyMass=function(i,e){i.physicsBody.mass=e,i.physicsBody.updateMassProperties()},a.prototype.getBodyMass=function(i){return i.physicsBody.mass},a.prototype.getBodyFriction=function(i){return i.physicsBody.material.friction},a.prototype.setBodyFriction=function(i,e){i.physicsBody.material.friction=e},a.prototype.getBodyRestitution=function(i){return i.physicsBody.material.restitution},a.prototype.setBodyRestitution=function(i,e){i.physicsBody.material.restitution=e},a.prototype.sleepBody=function(i){i.physicsBody.sleep()},a.prototype.wakeUpBody=function(i){i.physicsBody.wakeUp()},a.prototype.updateDistanceJoint=function(i,e){i.physicsJoint.distance=e},a.prototype.setMotor=function(i,e,o,s){s||(i.physicsJoint.enableMotor(),i.physicsJoint.setMotorSpeed(e),o&&this.setLimit(i,o))},a.prototype.setLimit=function(i,e,o){i.physicsJoint.motorEquation.maxForce=e,i.physicsJoint.motorEquation.minForce=o===void 0?-e:o},a.prototype.syncMeshWithImpostor=function(i,e){var o=e.physicsBody;i.position.x=o.position.x,i.position.y=o.position.y,i.position.z=o.position.z,i.rotationQuaternion&&(i.rotationQuaternion.x=o.quaternion.x,i.rotationQuaternion.y=o.quaternion.y,i.rotationQuaternion.z=o.quaternion.z,i.rotationQuaternion.w=o.quaternion.w)},a.prototype.getRadius=function(i){var e=i.physicsBody.shapes[0];return e.boundingSphereRadius},a.prototype.getBoxSizeToRef=function(i,e){var o=i.physicsBody.shapes[0];e.x=o.halfExtents.x*2,e.y=o.halfExtents.y*2,e.z=o.halfExtents.z*2},a.prototype.dispose=function(){},a.prototype._extendNamespace=function(){var i=new this.BJSCANNON.Vec3,e=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(o,s,c){if(c=c||10,s=s||0,s===0)this.internalStep(o),this.time+=o;else{var d=Math.floor((this.time+s)/o)-Math.floor(this.time/o);d=Math.min(d,c)||1;for(var _=performance.now(),b=0;b!==d&&(this.internalStep(o),!(performance.now()-_>o*1e3));b++);this.time+=s;for(var k=this.time%o,j=k/o,$=i,_e=this.bodies,et=0;et!==_e.length;et++){var tt=_e[et];tt.type!==e.Body.STATIC&&tt.sleepState!==e.Body.SLEEPING?(tt.position.vsub(tt.previousPosition,$),$.scale(j,$),tt.position.vadd($,tt.interpolatedPosition)):(tt.interpolatedPosition.set(tt.position.x,tt.position.y,tt.position.z),tt.interpolatedQuaternion.set(tt.quaternion.x,tt.quaternion.y,tt.quaternion.z,tt.quaternion.w))}}}},a.prototype.raycast=function(i,e){return this._cannonRaycastResult.reset(),this.world.raycastClosest(i,e,{},this._cannonRaycastResult),this._raycastResult.reset(i,e),this._cannonRaycastResult.hasHit&&(this._raycastResult.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),this._raycastResult.setHitDistance(this._cannonRaycastResult.distance)),this._raycastResult},a}();PhysicsEngine.DefaultPluginFactory=function(){return new CannonJSPlugin};var OimoJSPlugin=function(){function a(i,e,o){i===void 0&&(i=!0),o===void 0&&(o=OIMO),this._useDeltaForWorldStep=i,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=Vector3.Zero(),this.BJSOIMO=o,this.world=new this.BJSOIMO.World({iterations:e}),this.world.clear(),this._raycastResult=new PhysicsRaycastResult}return a.prototype.setGravity=function(i){this.world.gravity.set(i.x,i.y,i.z)},a.prototype.setTimeStep=function(i){this.world.timeStep=i},a.prototype.getTimeStep=function(){return this.world.timeStep},a.prototype.executeStep=function(i,e){var o=this;e.forEach(function(_){_.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?i:this._fixedTimeStep,this.world.step(),e.forEach(function(_){_.afterStep(),o._tmpImpostorsArray[_.uniqueId]=_});for(var s=this.world.contacts;s!==null;){if(s.touching&&!s.body1.sleeping&&!s.body2.sleeping){s=s.next;continue}var c=this._tmpImpostorsArray[+s.body1.name],d=this._tmpImpostorsArray[+s.body2.name];if(!c||!d){s=s.next;continue}c.onCollide({body:d.physicsBody,point:null}),d.onCollide({body:c.physicsBody,point:null}),s=s.next}},a.prototype.applyImpulse=function(i,e,o){var s=i.physicsBody.mass;i.physicsBody.applyImpulse(o.scale(this.world.invScale),e.scale(this.world.invScale*s))},a.prototype.applyForce=function(i,e,o){Logger$2.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(i,e,o)},a.prototype.generatePhysicsBody=function(i){var e=this;if(i.parent){i.physicsBody&&(this.removePhysicsBody(i),i.forceUpdate());return}if(i.isBodyInitRequired()){var o={name:i.uniqueId,config:[i.getParam("mass")||.001,i.getParam("friction"),i.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:i.getParam("mass")!==0,density:i.getParam("mass"),friction:i.getParam("friction"),restitution:i.getParam("restitution"),world:this.world},s=[i],c=function(b){!b.getChildMeshes||b.getChildMeshes().forEach(function(k){k.physicsImpostor&&s.push(k.physicsImpostor)})};c(i.object);var d=function(b){return Math.max(b,PhysicsEngine.Epsilon)},_=new Quaternion;s.forEach(function(b){if(!!b.object.rotationQuaternion){var k=b.object.rotationQuaternion;_.copyFrom(k),b.object.rotationQuaternion.set(0,0,0,1),b.object.computeWorldMatrix(!0);var j=_.toEulerAngles(),$=b.getObjectExtendSize(),_e=57.29577951308232;if(b===i){var et=i.getObjectCenter();i.object.getAbsolutePivotPoint().subtractToRef(et,e._tmpPositionVector),e._tmpPositionVector.divideInPlace(i.object.scaling),o.pos.push(et.x),o.pos.push(et.y),o.pos.push(et.z),o.posShape.push(0,0,0),o.rotShape.push(0,0,0)}else{var tt=b.object.position.clone();o.posShape.push(tt.x),o.posShape.push(tt.y),o.posShape.push(tt.z),o.rotShape.push(j.x*_e,j.y*_e,j.z*_e)}switch(b.object.rotationQuaternion.copyFrom(_),b.type){case PhysicsImpostor.ParticleImpostor:Logger$2.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case PhysicsImpostor.SphereImpostor:var rt=$.x,it=$.y,nt=$.z,ot=Math.max(d(rt),d(it),d(nt))/2;o.type.push("sphere"),o.size.push(ot),o.size.push(ot),o.size.push(ot);break;case PhysicsImpostor.CylinderImpostor:var at=d($.x)/2,st=d($.y);o.type.push("cylinder"),o.size.push(at),o.size.push(st),o.size.push(st);break;case PhysicsImpostor.PlaneImpostor:case PhysicsImpostor.BoxImpostor:default:var at=d($.x),st=d($.y),ut=d($.z);o.type.push("box"),o.size.push(at),o.size.push(st),o.size.push(ut);break}b.object.rotationQuaternion=k}}),i.physicsBody=this.world.add(o),i.physicsBody.resetQuaternion(_),i.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);i.setDeltaPosition(this._tmpPositionVector)},a.prototype.removePhysicsBody=function(i){this.world.removeRigidBody(i.physicsBody)},a.prototype.generateJoint=function(i){var e=i.mainImpostor.physicsBody,o=i.connectedImpostor.physicsBody;if(!(!e||!o)){var s=i.joint.jointData,c=s.nativeParams||{},d,_={body1:e,body2:o,axe1:c.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:c.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:c.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:c.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:c.min,max:c.max,collision:c.collision||s.collision,spring:c.spring,world:this.world};switch(i.joint.type){case PhysicsJoint.BallAndSocketJoint:d="jointBall";break;case PhysicsJoint.SpringJoint:Logger$2.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var b=s;_.min=b.length||_.min,_.max=Math.max(_.min,_.max);case PhysicsJoint.DistanceJoint:d="jointDistance",_.max=s.maxDistance;break;case PhysicsJoint.PrismaticJoint:d="jointPrisme";break;case PhysicsJoint.SliderJoint:d="jointSlide";break;case PhysicsJoint.WheelJoint:d="jointWheel";break;case PhysicsJoint.HingeJoint:default:d="jointHinge";break}_.type=d,i.joint.physicsJoint=this.world.add(_)}},a.prototype.removeJoint=function(i){try{this.world.removeJoint(i.joint.physicsJoint)}catch(e){Logger$2.Warn(e)}},a.prototype.isSupported=function(){return this.BJSOIMO!==void 0},a.prototype.setTransformationFromPhysicsBody=function(i){if(!i.physicsBody.sleeping){if(i.physicsBody.shapes.next){for(var e=i.physicsBody.shapes;e.next;)e=e.next;i.object.position.set(e.position.x,e.position.y,e.position.z)}else{var o=i.physicsBody.getPosition();i.object.position.set(o.x,o.y,o.z)}if(i.object.rotationQuaternion){var s=i.physicsBody.getQuaternion();i.object.rotationQuaternion.set(s.x,s.y,s.z,s.w)}}},a.prototype.setPhysicsBodyTransformation=function(i,e,o){var s=i.physicsBody;i.physicsBody.shapes.next||(s.position.set(e.x,e.y,e.z),s.orientation.set(o.x,o.y,o.z,o.w),s.syncShapes(),s.awake())},a.prototype.setLinearVelocity=function(i,e){i.physicsBody.linearVelocity.set(e.x,e.y,e.z)},a.prototype.setAngularVelocity=function(i,e){i.physicsBody.angularVelocity.set(e.x,e.y,e.z)},a.prototype.getLinearVelocity=function(i){var e=i.physicsBody.linearVelocity;return e?new Vector3(e.x,e.y,e.z):null},a.prototype.getAngularVelocity=function(i){var e=i.physicsBody.angularVelocity;return e?new Vector3(e.x,e.y,e.z):null},a.prototype.setBodyMass=function(i,e){var o=e===0;i.physicsBody.shapes.density=o?1:e,i.physicsBody.setupMass(o?2:1)},a.prototype.getBodyMass=function(i){return i.physicsBody.shapes.density},a.prototype.getBodyFriction=function(i){return i.physicsBody.shapes.friction},a.prototype.setBodyFriction=function(i,e){i.physicsBody.shapes.friction=e},a.prototype.getBodyRestitution=function(i){return i.physicsBody.shapes.restitution},a.prototype.setBodyRestitution=function(i,e){i.physicsBody.shapes.restitution=e},a.prototype.sleepBody=function(i){i.physicsBody.sleep()},a.prototype.wakeUpBody=function(i){i.physicsBody.awake()},a.prototype.updateDistanceJoint=function(i,e,o){i.physicsJoint.limitMotor.upperLimit=e,o!==void 0&&(i.physicsJoint.limitMotor.lowerLimit=o)},a.prototype.setMotor=function(i,e,o,s){o!==void 0?Logger$2.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):o=1e6,e*=-1;var c=s?i.physicsJoint.rotationalLimitMotor2:i.physicsJoint.rotationalLimitMotor1||i.physicsJoint.rotationalLimitMotor||i.physicsJoint.limitMotor;c&&c.setMotor(e,o)},a.prototype.setLimit=function(i,e,o,s){var c=s?i.physicsJoint.rotationalLimitMotor2:i.physicsJoint.rotationalLimitMotor1||i.physicsJoint.rotationalLimitMotor||i.physicsJoint.limitMotor;c&&c.setLimit(e,o===void 0?-e:o)},a.prototype.syncMeshWithImpostor=function(i,e){var o=e.physicsBody;i.position.x=o.position.x,i.position.y=o.position.y,i.position.z=o.position.z,i.rotationQuaternion&&(i.rotationQuaternion.x=o.orientation.x,i.rotationQuaternion.y=o.orientation.y,i.rotationQuaternion.z=o.orientation.z,i.rotationQuaternion.w=o.orientation.s)},a.prototype.getRadius=function(i){return i.physicsBody.shapes.radius},a.prototype.getBoxSizeToRef=function(i,e){var o=i.physicsBody.shapes;e.x=o.halfWidth*2,e.y=o.halfHeight*2,e.z=o.halfDepth*2},a.prototype.dispose=function(){this.world.clear()},a.prototype.raycast=function(i,e){return Logger$2.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(i,e),this._raycastResult},a}(),AmmoJSPlugin=function(){function a(i,e,o){var s=this;if(i===void 0&&(i=!0),e===void 0&&(e=Ammo),o===void 0&&(o=null),this._useDeltaForWorldStep=i,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new Quaternion,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new Vector3,this._tmpVec3=new Vector3,this._tmpMatrix=new Matrix,typeof e=="function"){Logger$2.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=e;if(!this.isSupported()){Logger$2.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=o||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=function(c,d,_,b){c=s.bjsAMMO.wrapPointer(c,s.bjsAMMO.btManifoldPoint);var k=c.getPositionWorldOnA();s._tmpContactPoint.x=k.x(),s._tmpContactPoint.y=k.y(),s._tmpContactPoint.z=k.z(),s._tmpContactCallbackResult=!0},this._raycastResult=new PhysicsRaycastResult,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}return a.prototype.setGravity=function(i){this._tmpAmmoVectorA.setValue(i.x,i.y,i.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)},a.prototype.setTimeStep=function(i){this._timeStep=i},a.prototype.setFixedTimeStep=function(i){this._fixedTimeStep=i},a.prototype.setMaxSteps=function(i){this._maxSteps=i},a.prototype.getTimeStep=function(){return this._timeStep},a.prototype._isImpostorInContact=function(i){return this._tmpContactCallbackResult=!1,this.world.contactTest(i.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},a.prototype._isImpostorPairInContact=function(i,e){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(i.physicsBody,e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},a.prototype._stepSimulation=function(i,e,o){if(i===void 0&&(i=1/60),e===void 0&&(e=10),o===void 0&&(o=1/60),e==0)this.world.stepSimulation(i,0);else for(;e>0&&i>0;)i-o<o?(this.world.stepSimulation(i,0),i=0):(i-=o,this.world.stepSimulation(o,0)),e--},a.prototype.executeStep=function(i,e){for(var o=0,s=e;o<s.length;o++){var c=s[o];c.soft||c.beforeStep()}this._stepSimulation(this._useDeltaForWorldStep?i:this._timeStep,this._maxSteps,this._fixedTimeStep);for(var d=0,_=e;d<_.length;d++){var b=_[d];if(b.soft?this._afterSoftStep(b):b.afterStep(),b._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(b))for(var k=0,j=b._onPhysicsCollideCallbacks;k<j.length;k++)for(var $=j[k],_e=0,et=$.otherImpostors;_e<et.length;_e++){var tt=et[_e];(b.physicsBody.isActive()||tt.physicsBody.isActive())&&this._isImpostorPairInContact(b,tt)&&(b.onCollide({body:tt.physicsBody,point:this._tmpContactPoint}),tt.onCollide({body:b.physicsBody,point:this._tmpContactPoint}))}}},a.prototype._afterSoftStep=function(i){i.type===PhysicsImpostor.RopeImpostor?this._ropeStep(i):this._softbodyOrClothStep(i)},a.prototype._ropeStep=function(i){for(var e=i.physicsBody.get_m_nodes(),o=e.size(),s,c,d,_,b,k=new Array,j=0;j<o;j++)s=e.at(j),c=s.get_m_x(),d=c.x(),_=c.y(),b=c.z(),k.push(new Vector3(d,_,b));var $=i.object,_e=i.getParam("shape");i._isFromLine?i.object=CreateLines("lines",{points:k,instance:$}):i.object=ExtrudeShape("ext",{shape:_e,path:k,instance:$})},a.prototype._softbodyOrClothStep=function(i){var e=i.type===PhysicsImpostor.ClothImpostor?1:-1,o=i.object,s=o.getVerticesData(VertexBuffer.PositionKind);s||(s=[]);var c=o.getVerticesData(VertexBuffer.NormalKind);c||(c=[]);for(var d=s.length/3,_=i.physicsBody.get_m_nodes(),b,k,j,$,_e,et,tt,rt,it,nt=0;nt<d;nt++){b=_.at(nt),k=b.get_m_x(),$=k.x(),_e=k.y(),et=k.z()*e;var j=b.get_m_n();tt=j.x(),rt=j.y(),it=j.z()*e,s[3*nt]=$,s[3*nt+1]=_e,s[3*nt+2]=et,c[3*nt]=tt,c[3*nt+1]=rt,c[3*nt+2]=it}var ot=new VertexData;ot.positions=s,ot.normals=c,ot.uvs=o.getVerticesData(VertexBuffer.UVKind),ot.colors=o.getVerticesData(VertexBuffer.ColorKind),o&&o.getIndices&&(ot.indices=o.getIndices()),ot.applyToMesh(o)},a.prototype.applyImpulse=function(i,e,o){if(i.soft)Logger$2.Warn("Cannot be applied to a soft body");else{i.physicsBody.activate();var s=this._tmpAmmoVectorA,c=this._tmpAmmoVectorB;i.object&&i.object.getWorldMatrix&&o.subtractInPlace(i.object.getWorldMatrix().getTranslation()),s.setValue(o.x,o.y,o.z),c.setValue(e.x,e.y,e.z),i.physicsBody.applyImpulse(c,s)}},a.prototype.applyForce=function(i,e,o){if(i.soft)Logger$2.Warn("Cannot be applied to a soft body");else{i.physicsBody.activate();var s=this._tmpAmmoVectorA,c=this._tmpAmmoVectorB;if(s.setValue(o.x,o.y,o.z),i.object&&i.object.getWorldMatrix){var d=i.object.getWorldMatrix().getTranslation();s.x-=d.x,s.y-=d.y,s.z-=d.z}c.setValue(e.x,e.y,e.z),i.physicsBody.applyForce(c,s)}},a.prototype.generatePhysicsBody=function(i){if(i._pluginData.toDispose=[],i.parent){i.physicsBody&&(this.removePhysicsBody(i),i.forceUpdate());return}if(i.isBodyInitRequired()){var e=this._createShape(i),o=i.getParam("mass");if(i._pluginData.mass=o,i.soft)e.get_m_cfg().set_collisions(17),e.get_m_cfg().set_kDP(i.getParam("damping")),this.bjsAMMO.castObject(e,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(i.getParam("margin")),e.setActivationState(a.DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(e,1,-1),i.physicsBody=e,i._pluginData.toDispose.push(e),this.setBodyPressure(i,0),i.type===PhysicsImpostor.SoftbodyImpostor&&this.setBodyPressure(i,i.getParam("pressure")),this.setBodyStiffness(i,i.getParam("stiffness")),this.setBodyVelocityIterations(i,i.getParam("velocityIterations")),this.setBodyPositionIterations(i,i.getParam("positionIterations"));else{var s=new this.bjsAMMO.btVector3(0,0,0),c=new this.bjsAMMO.btTransform;i.object.computeWorldMatrix(!0),c.setIdentity(),o!==0&&e.calculateLocalInertia(o,s),this._tmpAmmoVectorA.setValue(i.object.position.x,i.object.position.y,i.object.position.z),this._tmpAmmoQuaternion.setValue(i.object.rotationQuaternion.x,i.object.rotationQuaternion.y,i.object.rotationQuaternion.z,i.object.rotationQuaternion.w),c.setOrigin(this._tmpAmmoVectorA),c.setRotation(this._tmpAmmoQuaternion);var d=new this.bjsAMMO.btDefaultMotionState(c),_=new this.bjsAMMO.btRigidBodyConstructionInfo(o,d,e,s),b=new this.bjsAMMO.btRigidBody(_);if(o===0&&(b.setCollisionFlags(b.getCollisionFlags()|a.KINEMATIC_FLAG),b.setActivationState(a.DISABLE_DEACTIVATION_FLAG)),i.type==PhysicsImpostor.NoImpostor&&!e.getChildShape&&b.setCollisionFlags(b.getCollisionFlags()|a.DISABLE_COLLISION_FLAG),i.type!==PhysicsImpostor.MeshImpostor&&i.type!==PhysicsImpostor.NoImpostor){var k=i.object.getBoundingInfo();this._tmpVec3.copyFrom(i.object.getAbsolutePosition()),this._tmpVec3.subtractInPlace(k.boundingBox.centerWorld),this._tmpVec3.x/=i.object.scaling.x,this._tmpVec3.y/=i.object.scaling.y,this._tmpVec3.z/=i.object.scaling.z,i.setDeltaPosition(this._tmpVec3)}var j=i.getParam("group"),$=i.getParam("mask");j&&$?this.world.addRigidBody(b,j,$):this.world.addRigidBody(b),i.physicsBody=b,i._pluginData.toDispose=i._pluginData.toDispose.concat([b,_,d,c,s,e])}this.setBodyRestitution(i,i.getParam("restitution")),this.setBodyFriction(i,i.getParam("friction"))}},a.prototype.removePhysicsBody=function(i){var e=this;this.world&&(i.soft?this.world.removeSoftBody(i.physicsBody):this.world.removeRigidBody(i.physicsBody),i._pluginData&&(i._pluginData.toDispose.forEach(function(o){e.bjsAMMO.destroy(o)}),i._pluginData.toDispose=[]))},a.prototype.generateJoint=function(i){var e=i.mainImpostor.physicsBody,o=i.connectedImpostor.physicsBody;if(!(!e||!o)){var s=i.joint.jointData;s.mainPivot||(s.mainPivot=new Vector3(0,0,0)),s.connectedPivot||(s.connectedPivot=new Vector3(0,0,0));var c;switch(i.joint.type){case PhysicsJoint.DistanceJoint:var d=s.maxDistance;d&&(s.mainPivot=new Vector3(0,-d/2,0),s.connectedPivot=new Vector3(0,d/2,0)),c=new this.bjsAMMO.btPoint2PointConstraint(e,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;case PhysicsJoint.HingeJoint:s.mainAxis||(s.mainAxis=new Vector3(0,0,0)),s.connectedAxis||(s.connectedAxis=new Vector3(0,0,0));var _=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),b=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);c=new this.bjsAMMO.btHingeConstraint(e,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),_,b);break;case PhysicsJoint.BallAndSocketJoint:c=new this.bjsAMMO.btPoint2PointConstraint(e,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:Logger$2.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),c=new this.bjsAMMO.btPoint2PointConstraint(e,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}this.world.addConstraint(c,!i.joint.jointData.collision),i.joint.physicsJoint=c}},a.prototype.removeJoint=function(i){this.world&&this.world.removeConstraint(i.joint.physicsJoint)},a.prototype._addMeshVerts=function(i,e,o){var s=this,c=0;if(o&&o.getIndices&&o.getWorldMatrix&&o.getChildMeshes){var d=o.getIndices();d||(d=[]);var _=o.getVerticesData(VertexBuffer.PositionKind);_||(_=[]);var b=void 0;if(e&&e!==o){var k=void 0;e.rotationQuaternion?k=e.rotationQuaternion:e.rotation?k=Quaternion.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z):k=Quaternion.Identity();var j=Matrix.Compose(Vector3.One(),k,e.position);j.invertToRef(this._tmpMatrix);var $=o.computeWorldMatrix(!1);b=$.multiply(this._tmpMatrix)}else Matrix.ScalingToRef(o.scaling.x,o.scaling.y,o.scaling.z,this._tmpMatrix),b=this._tmpMatrix;for(var _e=d.length/3,et=0;et<_e;et++){for(var tt=[],rt=0;rt<3;rt++){var it=new Vector3(_[d[et*3+rt]*3+0],_[d[et*3+rt]*3+1],_[d[et*3+rt]*3+2]);it=Vector3.TransformCoordinates(it,b);var nt;rt==0?nt=this._tmpAmmoVectorA:rt==1?nt=this._tmpAmmoVectorB:nt=this._tmpAmmoVectorC,nt.setValue(it.x,it.y,it.z),tt.push(nt)}i.addTriangle(tt[0],tt[1],tt[2]),c++}o.getChildMeshes().forEach(function(ot){c+=s._addMeshVerts(i,e,ot)})}return c},a.prototype._softVertexData=function(i){var e=i.object;if(e&&e.getIndices&&e.getWorldMatrix&&e.getChildMeshes){e.getIndices();var o=e.getVerticesData(VertexBuffer.PositionKind);o||(o=[]);var s=e.getVerticesData(VertexBuffer.NormalKind);s||(s=[]),e.computeWorldMatrix(!1);for(var c=[],d=[],_=0;_<o.length;_+=3){var b=new Vector3(o[_],o[_+1],o[_+2]),k=new Vector3(s[_],s[_+1],s[_+2]);b=Vector3.TransformCoordinates(b,e.getWorldMatrix()),k=Vector3.TransformNormal(k,e.getWorldMatrix()),c.push(b.x,b.y,b.z),d.push(k.x,k.y,k.z)}var j=new VertexData;return j.positions=c,j.normals=d,j.uvs=e.getVerticesData(VertexBuffer.UVKind),j.colors=e.getVerticesData(VertexBuffer.ColorKind),e&&e.getIndices&&(j.indices=e.getIndices()),j.applyToMesh(e),e.position=Vector3.Zero(),e.rotationQuaternion=null,e.rotation=Vector3.Zero(),e.computeWorldMatrix(!0),j}return VertexData.ExtractFromMesh(e)},a.prototype._createSoftbody=function(i){var e=i.object;if(e&&e.getIndices){var o=e.getIndices();o||(o=[]);var s=this._softVertexData(i),c=s.positions,d=s.normals;if(c===null||d===null)return new this.bjsAMMO.btCompoundShape;for(var _=[],b=[],k=0;k<c.length;k+=3){var j=new Vector3(c[k],c[k+1],c[k+2]),$=new Vector3(d[k],d[k+1],d[k+2]);_.push(j.x,j.y,-j.z),b.push($.x,$.y,-$.z)}for(var _e=new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(),_,e.getIndices(),o.length/3,!0),et=c.length/3,tt=_e.get_m_nodes(),rt,it,k=0;k<et;k++){rt=tt.at(k);var it=rt.get_m_n();it.setX(b[3*k]),it.setY(b[3*k+1]),it.setZ(b[3*k+2])}return _e}},a.prototype._createCloth=function(i){var e=i.object;if(e&&e.getIndices){e.getIndices();var o=this._softVertexData(i),s=o.positions,c=o.normals;if(s===null||c===null)return new this.bjsAMMO.btCompoundShape;var d=s.length,_=Math.sqrt(d/3);i.segments=_;var b=_-1;this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[3*b],s[3*b+1],s[3*b+2]),this._tmpAmmoVectorD.setValue(s[d-3],s[d-2],s[d-1]),this._tmpAmmoVectorC.setValue(s[d-3-3*b],s[d-2-3*b],s[d-1-3*b]);var k=new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,_,_,i.getParam("fixedPoints"),!0);return k}},a.prototype._createRope=function(i){var e,o,s=this._softVertexData(i),c=s.positions,d=s.normals;if(c===null||d===null)return new this.bjsAMMO.btCompoundShape;s.applyToMesh(i.object,!0),i._isFromLine=!0;var _=d.map(function(tt){return tt*tt}),b=function(tt,rt){return tt+rt},k=_.reduce(b);if(k===0)e=c.length,o=e/3-1,this._tmpAmmoVectorA.setValue(c[0],c[1],c[2]),this._tmpAmmoVectorB.setValue(c[e-3],c[e-2],c[e-1]);else{i._isFromLine=!1;var j=i.getParam("path"),$=i.getParam("shape");if($===null)return Logger$2.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;e=j.length,o=e-1,this._tmpAmmoVectorA.setValue(j[0].x,j[0].y,j[0].z),this._tmpAmmoVectorB.setValue(j[e-1].x,j[e-1].y,j[e-1].z)}i.segments=o;var _e=i.getParam("fixedPoints");_e=_e>3?3:_e;var et=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,o-1,_e);return et.get_m_cfg().set_collisions(17),et},a.prototype._createCustom=function(i){var e=null;return this.onCreateCustomShape&&(e=this.onCreateCustomShape(i)),e==null&&(e=new this.bjsAMMO.btCompoundShape),e},a.prototype._addHullVerts=function(i,e,o){var s=this,c=0;if(o&&o.getIndices&&o.getWorldMatrix&&o.getChildMeshes){var d=o.getIndices();d||(d=[]);var _=o.getVerticesData(VertexBuffer.PositionKind);_||(_=[]),o.computeWorldMatrix(!1);for(var b=d.length/3,k=0;k<b;k++){for(var j=[],$=0;$<3;$++){var _e=new Vector3(_[d[k*3+$]*3+0],_[d[k*3+$]*3+1],_[d[k*3+$]*3+2]);Matrix.ScalingToRef(o.scaling.x,o.scaling.y,o.scaling.z,this._tmpMatrix),_e=Vector3.TransformCoordinates(_e,this._tmpMatrix);var et;$==0?et=this._tmpAmmoVectorA:$==1?et=this._tmpAmmoVectorB:et=this._tmpAmmoVectorC,et.setValue(_e.x,_e.y,_e.z),j.push(et)}i.addPoint(j[0],!0),i.addPoint(j[1],!0),i.addPoint(j[2],!0),c++}o.getChildMeshes().forEach(function(tt){c+=s._addHullVerts(i,e,tt)})}return c},a.prototype._createShape=function(i,e){var o=this;e===void 0&&(e=!1);var s=i.object,c,d=i.getObjectExtendSize();if(!e){var _=i.object.getChildMeshes?i.object.getChildMeshes(!0):[];c=new this.bjsAMMO.btCompoundShape;var b=0;if(_.forEach(function(it){var nt=it.getPhysicsImpostor();if(nt){if(nt.type==PhysicsImpostor.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";var ot=o._createShape(nt),at=it.parent.getWorldMatrix().clone(),st=new Vector3;at.decompose(st),o._tmpAmmoTransform.getOrigin().setValue(it.position.x*st.x,it.position.y*st.y,it.position.z*st.z),o._tmpAmmoQuaternion.setValue(it.rotationQuaternion.x,it.rotationQuaternion.y,it.rotationQuaternion.z,it.rotationQuaternion.w),o._tmpAmmoTransform.setRotation(o._tmpAmmoQuaternion),c.addChildShape(o._tmpAmmoTransform,ot),nt.dispose(),b++}}),b>0){if(i.type!=PhysicsImpostor.NoImpostor){var k=this._createShape(i,!0);k&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),c.addChildShape(this._tmpAmmoTransform,k))}return c}else this.bjsAMMO.destroy(c),c=null}switch(i.type){case PhysicsImpostor.SphereImpostor:if(Scalar.WithinEpsilon(d.x,d.y,1e-4)&&Scalar.WithinEpsilon(d.x,d.z,1e-4))c=new this.bjsAMMO.btSphereShape(d.x/2);else{var j=[new this.bjsAMMO.btVector3(0,0,0)],$=[1];c=new this.bjsAMMO.btMultiSphereShape(j,$,1),c.setLocalScaling(new this.bjsAMMO.btVector3(d.x/2,d.y/2,d.z/2))}break;case PhysicsImpostor.CapsuleImpostor:var _e=d.x/2;c=new this.bjsAMMO.btCapsuleShape(_e,d.y-_e*2);break;case PhysicsImpostor.CylinderImpostor:this._tmpAmmoVectorA.setValue(d.x/2,d.y/2,d.z/2),c=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case PhysicsImpostor.PlaneImpostor:case PhysicsImpostor.BoxImpostor:this._tmpAmmoVectorA.setValue(d.x/2,d.y/2,d.z/2),c=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case PhysicsImpostor.MeshImpostor:if(i.getParam("mass")==0){var et=new this.bjsAMMO.btTriangleMesh;i._pluginData.toDispose.push(et);var rt=this._addMeshVerts(et,s,s);rt==0?c=new this.bjsAMMO.btCompoundShape:c=new this.bjsAMMO.btBvhTriangleMeshShape(et);break}case PhysicsImpostor.ConvexHullImpostor:var tt=new this.bjsAMMO.btConvexHullShape,rt=this._addHullVerts(tt,s,s);rt==0?(i._pluginData.toDispose.push(tt),c=new this.bjsAMMO.btCompoundShape):c=tt;break;case PhysicsImpostor.NoImpostor:c=new this.bjsAMMO.btSphereShape(d.x/2);break;case PhysicsImpostor.CustomImpostor:c=this._createCustom(i);break;case PhysicsImpostor.SoftbodyImpostor:c=this._createSoftbody(i);break;case PhysicsImpostor.ClothImpostor:c=this._createCloth(i);break;case PhysicsImpostor.RopeImpostor:c=this._createRope(i);break;default:Logger$2.Warn("The impostor type is not currently supported by the ammo plugin.");break}return c},a.prototype.setTransformationFromPhysicsBody=function(i){i.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),i.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),i.object.rotationQuaternion?i.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):i.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(i.object.rotation))},a.prototype.setPhysicsBodyTransformation=function(i,e,o){var s=i.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-e.x)>Epsilon||Math.abs(s.getOrigin().y()-e.y)>Epsilon||Math.abs(s.getOrigin().z()-e.z)>Epsilon||Math.abs(s.getRotation().x()-o.x)>Epsilon||Math.abs(s.getRotation().y()-o.y)>Epsilon||Math.abs(s.getRotation().z()-o.z)>Epsilon||Math.abs(s.getRotation().w()-o.w)>Epsilon)if(this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(o.x,o.y,o.z,o.w),s.setRotation(this._tmpAmmoQuaternion),i.physicsBody.setWorldTransform(s),i.mass==0){var c=i.physicsBody.getMotionState();c&&c.setWorldTransform(s)}else i.physicsBody.activate()},a.prototype.isSupported=function(){return this.bjsAMMO!==void 0},a.prototype.setLinearVelocity=function(i,e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),i.soft?i.physicsBody.linearVelocity(this._tmpAmmoVectorA):i.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)},a.prototype.setAngularVelocity=function(i,e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),i.soft?i.physicsBody.angularVelocity(this._tmpAmmoVectorA):i.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)},a.prototype.getLinearVelocity=function(i){if(i.soft)var e=i.physicsBody.linearVelocity();else var e=i.physicsBody.getLinearVelocity();if(!e)return null;var o=new Vector3(e.x(),e.y(),e.z());return this.bjsAMMO.destroy(e),o},a.prototype.getAngularVelocity=function(i){if(i.soft)var e=i.physicsBody.angularVelocity();else var e=i.physicsBody.getAngularVelocity();if(!e)return null;var o=new Vector3(e.x(),e.y(),e.z());return this.bjsAMMO.destroy(e),o},a.prototype.setBodyMass=function(i,e){i.soft?i.physicsBody.setTotalMass(e,!1):i.physicsBody.setMassProps(e),i._pluginData.mass=e},a.prototype.getBodyMass=function(i){return i._pluginData.mass||0},a.prototype.getBodyFriction=function(i){return i._pluginData.friction||0},a.prototype.setBodyFriction=function(i,e){i.soft?i.physicsBody.get_m_cfg().set_kDF(e):i.physicsBody.setFriction(e),i._pluginData.friction=e},a.prototype.getBodyRestitution=function(i){return i._pluginData.restitution||0},a.prototype.setBodyRestitution=function(i,e){i.physicsBody.setRestitution(e),i._pluginData.restitution=e},a.prototype.getBodyPressure=function(i){return i.soft?i._pluginData.pressure||0:(Logger$2.Warn("Pressure is not a property of a rigid body"),0)},a.prototype.setBodyPressure=function(i,e){i.soft?i.type===PhysicsImpostor.SoftbodyImpostor?(i.physicsBody.get_m_cfg().set_kPR(e),i._pluginData.pressure=e):(i.physicsBody.get_m_cfg().set_kPR(0),i._pluginData.pressure=0):Logger$2.Warn("Pressure can only be applied to a softbody")},a.prototype.getBodyStiffness=function(i){return i.soft?i._pluginData.stiffness||0:(Logger$2.Warn("Stiffness is not a property of a rigid body"),0)},a.prototype.setBodyStiffness=function(i,e){i.soft?(e=e<0?0:e,e=e>1?1:e,i.physicsBody.get_m_materials().at(0).set_m_kLST(e),i._pluginData.stiffness=e):Logger$2.Warn("Stiffness cannot be applied to a rigid body")},a.prototype.getBodyVelocityIterations=function(i){return i.soft?i._pluginData.velocityIterations||0:(Logger$2.Warn("Velocity iterations is not a property of a rigid body"),0)},a.prototype.setBodyVelocityIterations=function(i,e){i.soft?(e=e<0?0:e,i.physicsBody.get_m_cfg().set_viterations(e),i._pluginData.velocityIterations=e):Logger$2.Warn("Velocity iterations cannot be applied to a rigid body")},a.prototype.getBodyPositionIterations=function(i){return i.soft?i._pluginData.positionIterations||0:(Logger$2.Warn("Position iterations is not a property of a rigid body"),0)},a.prototype.setBodyPositionIterations=function(i,e){i.soft?(e=e<0?0:e,i.physicsBody.get_m_cfg().set_piterations(e),i._pluginData.positionIterations=e):Logger$2.Warn("Position iterations cannot be applied to a rigid body")},a.prototype.appendAnchor=function(i,e,o,s,c,d){c===void 0&&(c=1),d===void 0&&(d=!1);var _=i.segments,b=Math.round((_-1)*o),k=Math.round((_-1)*s),j=_-1-k,$=b+_*j;i.physicsBody.appendAnchor($,e.physicsBody,d,c)},a.prototype.appendHook=function(i,e,o,s,c){s===void 0&&(s=1),c===void 0&&(c=!1);var d=Math.round(i.segments*o);i.physicsBody.appendAnchor(d,e.physicsBody,c,s)},a.prototype.sleepBody=function(i){i.physicsBody.forceActivationState(0)},a.prototype.wakeUpBody=function(i){i.physicsBody.activate()},a.prototype.updateDistanceJoint=function(i,e,o){Logger$2.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")},a.prototype.setMotor=function(i,e,o,s){i.physicsJoint.enableAngularMotor(!0,e,o)},a.prototype.setLimit=function(i,e,o){Logger$2.Warn("setLimit is not currently supported by the Ammo physics plugin")},a.prototype.syncMeshWithImpostor=function(i,e){var o=e.physicsBody;o.getMotionState().getWorldTransform(this._tmpAmmoTransform),i.position.x=this._tmpAmmoTransform.getOrigin().x(),i.position.y=this._tmpAmmoTransform.getOrigin().y(),i.position.z=this._tmpAmmoTransform.getOrigin().z(),i.rotationQuaternion&&(i.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),i.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),i.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),i.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())},a.prototype.getRadius=function(i){var e=i.getObjectExtendSize();return e.x/2},a.prototype.getBoxSizeToRef=function(i,e){var o=i.getObjectExtendSize();e.x=o.x,e.y=o.y,e.z=o.z},a.prototype.dispose=function(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null},a.prototype.raycast=function(i,e){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(i.x,i.y,i.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(e.x,e.y,e.z);var o=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);return this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,o),this._raycastResult.reset(i,e),o.hasHit()&&(this._raycastResult.setHitData({x:o.get_m_hitNormalWorld().x(),y:o.get_m_hitNormalWorld().y(),z:o.get_m_hitNormalWorld().z()},{x:o.get_m_hitPointWorld().x(),y:o.get_m_hitPointWorld().y(),z:o.get_m_hitPointWorld().z()}),this._raycastResult.calculateHitDistance()),this.bjsAMMO.destroy(o),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB),this._raycastResult},a.DISABLE_COLLISION_FLAG=4,a.KINEMATIC_FLAG=2,a.DISABLE_DEACTIVATION_FLAG=4,a}();AbstractScene.prototype.removeReflectionProbe=function(a){if(!this.reflectionProbes)return-1;var i=this.reflectionProbes.indexOf(a);return i!==-1&&this.reflectionProbes.splice(i,1),i};AbstractScene.prototype.addReflectionProbe=function(a){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(a)};var ReflectionProbe=function(){function a(i,e,o,s,c,d){var _=this;if(s===void 0&&(s=!0),c===void 0&&(c=!1),d===void 0&&(d=!1),this.name=i,this._viewMatrix=Matrix.Identity(),this._target=Vector3.Zero(),this._add=Vector3.Zero(),this._invertYAxis=!1,this.position=Vector3.Zero(),this._parentContainer=null,this._scene=o,o.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(var b=0;b<6;++b)this._sceneUBOs.push(o.createSceneUniformBuffer('Scene for Reflection Probe (name "'+i+'") face #'+b))}this._scene.reflectionProbes||(this._scene.reflectionProbes=new Array),this._scene.reflectionProbes.push(this);var k=0;if(c){var j=this._scene.getEngine().getCaps();j.textureHalfFloatRender?k=2:j.textureFloatRender&&(k=1)}this._renderTargetTexture=new RenderTargetTexture(i,e,o,s,!0,k,!0),this._renderTargetTexture.gammaSpace=!d;var $=o.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(function(et){switch(_._sceneUBOs&&(o.setSceneUniformBuffer(_._sceneUBOs[et]),o.getSceneUniformBuffer().unbindEffect()),et){case 0:_._add.copyFromFloats(1,0,0);break;case 1:_._add.copyFromFloats(-1,0,0);break;case 2:_._add.copyFromFloats(0,_._invertYAxis?1:-1,0);break;case 3:_._add.copyFromFloats(0,_._invertYAxis?-1:1,0);break;case 4:_._add.copyFromFloats(0,0,o.useRightHandedSystem?-1:1);break;case 5:_._add.copyFromFloats(0,0,o.useRightHandedSystem?1:-1);break}_._attachedMesh&&_.position.copyFrom(_._attachedMesh.getAbsolutePosition()),_.position.addToRef(_._add,_._target);var tt=o.useRightHandedSystem?Matrix.LookAtRHToRef:Matrix.LookAtLHToRef,rt=o.useRightHandedSystem?Matrix.PerspectiveFovRH:Matrix.PerspectiveFovLH;tt(_.position,_._target,Vector3.Up(),_._viewMatrix),o.activeCamera&&(_._projectionMatrix=rt(Math.PI/2,1,$?o.activeCamera.maxZ:o.activeCamera.minZ,$?o.activeCamera.minZ:o.activeCamera.maxZ,_._scene.getEngine().isNDCHalfZRange),o.setTransformMatrix(_._viewMatrix,_._projectionMatrix),o.activeCamera.isRigCamera&&!_._renderTargetTexture.activeCamera&&(_._renderTargetTexture.activeCamera=o.activeCamera.rigParent||null)),o._forcedViewPosition=_.position});var _e;this._renderTargetTexture.onBeforeBindObservable.add(function(){var et,tt;_._currentSceneUBO=o.getSceneUniformBuffer(),(tt=(et=o.getEngine())._debugPushGroup)===null||tt===void 0||tt.call(et,"reflection probe generation for "+i,1),_e=_._scene.imageProcessingConfiguration.applyByPostProcess,d&&(o.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(function(){var et,tt;o.imageProcessingConfiguration.applyByPostProcess=_e,o._forcedViewPosition=null,_._sceneUBOs&&o.setSceneUniformBuffer(_._currentSceneUBO),o.updateTransformMatrix(!0),(tt=(et=o.getEngine())._debugPopGroup)===null||tt===void 0||tt.call(et,1)})}return Object.defineProperty(a.prototype,"samples",{get:function(){return this._renderTargetTexture.samples},set:function(i){this._renderTargetTexture.samples=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"refreshRate",{get:function(){return this._renderTargetTexture.refreshRate},set:function(i){this._renderTargetTexture.refreshRate=i},enumerable:!1,configurable:!0}),a.prototype.getScene=function(){return this._scene},Object.defineProperty(a.prototype,"cubeTexture",{get:function(){return this._renderTargetTexture},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"renderList",{get:function(){return this._renderTargetTexture.renderList},enumerable:!1,configurable:!0}),a.prototype.attachToMesh=function(i){this._attachedMesh=i},a.prototype.setRenderingAutoClearDepthStencil=function(i,e){this._renderTargetTexture.setRenderingAutoClearDepthStencil(i,e)},a.prototype.dispose=function(){var i=this._scene.reflectionProbes.indexOf(this);if(i!==-1&&this._scene.reflectionProbes.splice(i,1),this._parentContainer){var e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(var o=0,s=this._sceneUBOs;o<s.length;o++){var c=s[o];c.dispose()}this._sceneUBOs=[]}},a.prototype.toString=function(i){var e="Name: "+this.name;return i&&(e+=", position: "+this.position.toString(),this._attachedMesh&&(e+=", attached mesh: "+this._attachedMesh.name)),e},a.prototype.getClassName=function(){return"ReflectionProbe"},a.prototype.serialize=function(){var i=SerializationHelper.Serialize(this,this._renderTargetTexture.serialize());return i.isReflectionProbe=!0,i},a.Parse=function(i,e,o){var s=null;if(e.reflectionProbes)for(var c=0;c<e.reflectionProbes.length;c++){var d=e.reflectionProbes[c];if(d.name===i.name){s=d;break}}return s=SerializationHelper.Parse(function(){return s||new a(i.name,i.renderTargetSize,e,i._generateMipMaps)},i,e,o),s.cubeTexture._waitingRenderList=i.renderList,i._attachedMesh&&s.attachToMesh(e.getMeshById(i._attachedMesh)),s},__decorate([serializeAsMeshReference()],a.prototype,"_attachedMesh",void 0),__decorate([serializeAsVector3()],a.prototype,"position",void 0),a}(),BabylonFileLoaderConfiguration=function(){function a(){}return a.LoaderInjectedPhysicsEngine=void 0,a}(),tempIndexContainer={},parseMaterialById=function(a,i,e,o){if(!i.materials)return null;for(var s=0,c=i.materials.length;s<c;s++){var d=i.materials[s];if(d.id===a)return Material.Parse(d,e,o)}return null},isDescendantOf=function(a,i,e){for(var o in i)if(a.name===i[o])return e.push(a.id),!0;return a.parentId&&e.indexOf(a.parentId)!==-1?(e.push(a.id),!0):!1},logOperation=function(a,i){return a+" of "+(i?i.file+" from "+i.name+" version: "+i.version+", exporter version: "+i.exporter_version:"unknown")},loadDetailLevels=function(a,i){var e=i;if(i._waitingData.lods){if(i._waitingData.lods.ids&&i._waitingData.lods.ids.length>0){var o=i._waitingData.lods.ids,s=e.isEnabled(!1);if(i._waitingData.lods.distances){var c=i._waitingData.lods.distances;if(c.length>=o.length){var d=c.length>o.length?c[c.length-1]:0;e.setEnabled(!1);for(var _=0;_<o.length;_++){var b=o[_],k=a.getMeshById(b);k!=null&&e.addLODLevel(c[_],k)}d>0&&e.addLODLevel(d,null),s===!0&&e.setEnabled(!0)}else Tools.Warn("Invalid level of detail distances for "+i.name)}}i._waitingData.lods=null}},findParent=function(a,i){if(typeof a!="number")return i.getLastEntryById(a);var e=tempIndexContainer[a];return e},loadAssetContainer=function(a,i,e,o,s){s===void 0&&(s=!1);var c=new AssetContainer(a),d="importScene has failed JSON parse";try{var _=JSON.parse(i);d="";var b=SceneLoader.loggingLevel===SceneLoader.DETAILED_LOGGING,k,j;if(_.environmentTexture!==void 0&&_.environmentTexture!==null){var $=_.isPBR!==void 0?_.isPBR:!0;if(_.environmentTextureType&&_.environmentTextureType==="BABYLON.HDRCubeTexture"){var _e=_.environmentTextureSize?_.environmentTextureSize:128,et=new HDRCubeTexture((_.environmentTexture.match(/https?:\/\//g)?"":e)+_.environmentTexture,a,_e,!0,!$);_.environmentTextureRotationY&&(et.rotationY=_.environmentTextureRotationY),a.environmentTexture=et}else if(EndsWith(_.environmentTexture,".env")){var tt=new CubeTexture((_.environmentTexture.match(/https?:\/\//g)?"":e)+_.environmentTexture,a);_.environmentTextureRotationY&&(tt.rotationY=_.environmentTextureRotationY),a.environmentTexture=tt}else{var rt=CubeTexture.CreateFromPrefilteredData((_.environmentTexture.match(/https?:\/\//g)?"":e)+_.environmentTexture,a);_.environmentTextureRotationY&&(rt.rotationY=_.environmentTextureRotationY),a.environmentTexture=rt}if(_.createDefaultSkybox===!0){var it=a.activeCamera!==void 0&&a.activeCamera!==null?(a.activeCamera.maxZ-a.activeCamera.minZ)/2:1e3,nt=_.skyboxBlurLevel||0;a.createDefaultSkybox(a.environmentTexture,$,it,nt)}c.environmentTexture=a.environmentTexture}if(_.environmentIntensity!==void 0&&_.environmentIntensity!==null&&(a.environmentIntensity=_.environmentIntensity),_.lights!==void 0&&_.lights!==null)for(k=0,j=_.lights.length;k<j;k++){var ot=_.lights[k],at=Light.Parse(ot,a);at&&(tempIndexContainer[ot.uniqueId]=at,c.lights.push(at),at._parentContainer=c,d+=k===0?`
  10293. Lights:`:"",d+=`
  10294. `+at.toString(b))}if(_.reflectionProbes!==void 0&&_.reflectionProbes!==null)for(k=0,j=_.reflectionProbes.length;k<j;k++){var st=_.reflectionProbes[k],ut=ReflectionProbe.Parse(st,a,e);ut&&(c.reflectionProbes.push(ut),ut._parentContainer=c,d+=k===0?`
  10295. Reflection Probes:`:"",d+=`
  10296. `+ut.toString(b))}if(_.animations!==void 0&&_.animations!==null)for(k=0,j=_.animations.length;k<j;k++){var ft=_.animations[k],lt=GetClass("BABYLON.Animation");if(lt){var ht=lt.Parse(ft);a.animations.push(ht),c.animations.push(ht),d+=k===0?`
  10297. Animations:`:"",d+=`
  10298. `+ht.toString(b)}}if(_.materials!==void 0&&_.materials!==null)for(k=0,j=_.materials.length;k<j;k++){var pt=_.materials[k],mt=Material.Parse(pt,a,e);if(mt){c.materials.push(mt),mt._parentContainer=c,d+=k===0?`
  10299. Materials:`:"",d+=`
  10300. `+mt.toString(b);var dt=mt.getActiveTextures();dt.forEach(function(tr){c.textures.indexOf(tr)==-1&&(c.textures.push(tr),tr._parentContainer=c)})}}if(_.multiMaterials!==void 0&&_.multiMaterials!==null)for(k=0,j=_.multiMaterials.length;k<j;k++){var gt=_.multiMaterials[k],_t=MultiMaterial.ParseMultiMaterial(gt,a);c.multiMaterials.push(_t),_t._parentContainer=c,d+=k===0?`
  10301. MultiMaterials:`:"",d+=`
  10302. `+_t.toString(b);var dt=_t.getActiveTextures();dt.forEach(function(Jt){c.textures.indexOf(Jt)==-1&&(c.textures.push(Jt),Jt._parentContainer=c)})}if(_.morphTargetManagers!==void 0&&_.morphTargetManagers!==null)for(var yt=0,Tt=_.morphTargetManagers;yt<Tt.length;yt++){var St=Tt[yt],At=MorphTargetManager.Parse(St,a);c.morphTargetManagers.push(At),At._parentContainer=c}if(_.skeletons!==void 0&&_.skeletons!==null)for(k=0,j=_.skeletons.length;k<j;k++){var vt=_.skeletons[k],Et=Skeleton.Parse(vt,a);c.skeletons.push(Et),Et._parentContainer=c,d+=k===0?`
  10303. Skeletons:`:"",d+=`
  10304. `+Et.toString(b)}var xt=_.geometries;if(xt!=null){var bt=new Array,Mt=xt.vertexData;if(Mt!=null)for(k=0,j=Mt.length;k<j;k++){var Rt=Mt[k];bt.push(Geometry.Parse(Rt,a,e))}bt.forEach(function(tr){tr&&(c.geometries.push(tr),tr._parentContainer=c)})}if(_.transformNodes!==void 0&&_.transformNodes!==null)for(k=0,j=_.transformNodes.length;k<j;k++){var Pt=_.transformNodes[k],It=TransformNode.Parse(Pt,a,e);tempIndexContainer[Pt.uniqueId]=It,c.transformNodes.push(It),It._parentContainer=c}if(_.meshes!==void 0&&_.meshes!==null)for(k=0,j=_.meshes.length;k<j;k++){var Dt=_.meshes[k],Ct=Mesh.Parse(Dt,a,e);if(tempIndexContainer[Dt.uniqueId]=Ct,c.meshes.push(Ct),Ct._parentContainer=c,Ct.hasInstances)for(var Ot=0,Ft=Ct.instances;Ot<Ft.length;Ot++){var wt=Ft[Ot];c.meshes.push(wt),wt._parentContainer=c}d+=k===0?`
  10305. Meshes:`:"",d+=`
  10306. `+Ct.toString(b)}if(_.cameras!==void 0&&_.cameras!==null)for(k=0,j=_.cameras.length;k<j;k++){var Bt=_.cameras[k],Ut=Camera$1.Parse(Bt,a);tempIndexContainer[Bt.uniqueId]=Ut,c.cameras.push(Ut),Ut._parentContainer=c,d+=k===0?`
  10307. Cameras:`:"",d+=`
  10308. `+Ut.toString(b)}if(_.postProcesses!==void 0&&_.postProcesses!==null)for(k=0,j=_.postProcesses.length;k<j;k++){var Vt=_.postProcesses[k],Gt=PostProcess.Parse(Vt,a,e);Gt&&(c.postProcesses.push(Gt),Gt._parentContainer=c,d+=k===0?`
  10309. Postprocesses:`:"",d+=`
  10310. `+Gt.toString())}if(_.animationGroups!==void 0&&_.animationGroups!==null)for(k=0,j=_.animationGroups.length;k<j;k++){var Lt=_.animationGroups[k],Ht=AnimationGroup.Parse(Lt,a);c.animationGroups.push(Ht),Ht._parentContainer=c,d+=k===0?`
  10311. AnimationGroups:`:"",d+=`
  10312. `+Ht.toString(b)}for(k=0,j=a.cameras.length;k<j;k++){var Ut=a.cameras[k];Ut._waitingParentId&&(Ut.parent=findParent(Ut._waitingParentId,a),Ut._waitingParentId=null)}for(k=0,j=a.lights.length;k<j;k++){var Wt=a.lights[k];Wt&&Wt._waitingParentId&&(Wt.parent=findParent(Wt._waitingParentId,a),Wt._waitingParentId=null)}for(k=0,j=a.transformNodes.length;k<j;k++){var Yt=a.transformNodes[k];Yt._waitingParentId&&(Yt.parent=findParent(Yt._waitingParentId,a),Yt._waitingParentId=null)}for(k=0,j=a.meshes.length;k<j;k++){var Ct=a.meshes[k];Ct._waitingParentId&&(Ct.parent=findParent(Ct._waitingParentId,a),Ct._waitingParentId=null),Ct._waitingData.lods&&loadDetailLevels(a,Ct)}for(k=0,j=a.skeletons.length;k<j;k++){var Et=a.skeletons[k];Et._hasWaitingData&&(Et.bones!=null&&Et.bones.forEach(function(Jt){if(Jt._waitingTransformNodeId){var hr=a.getLastEntryById(Jt._waitingTransformNodeId);hr&&Jt.linkTransformNode(hr),Jt._waitingTransformNodeId=null}}),Et._waitingOverrideMeshId&&(Et.overrideMesh=a.getMeshById(Et._waitingOverrideMeshId),Et._waitingOverrideMeshId=null),Et._hasWaitingData=null)}for(k=0,j=a.meshes.length;k<j;k++){var jt=a.meshes[k];jt._waitingData.freezeWorldMatrix?(jt.freezeWorldMatrix(),jt._waitingData.freezeWorldMatrix=null):jt.computeWorldMatrix(!0)}for(k=0,j=a.lights.length;k<j;k++){var $t=a.lights[k];if($t._excludedMeshesIds.length>0){for(var Qt=0;Qt<$t._excludedMeshesIds.length;Qt++){var ir=a.getMeshById($t._excludedMeshesIds[Qt]);ir&&$t.excludedMeshes.push(ir)}$t._excludedMeshesIds=[]}if($t._includedOnlyMeshesIds.length>0){for(var nr=0;nr<$t._includedOnlyMeshesIds.length;nr++){var rr=a.getMeshById($t._includedOnlyMeshesIds[nr]);rr&&$t.includedOnlyMeshes.push(rr)}$t._includedOnlyMeshesIds=[]}}for(AbstractScene.Parse(_,a,c,e),k=0,j=a.meshes.length;k<j;k++){var Ct=a.meshes[k];Ct._waitingData.actions&&(ActionManager.Parse(Ct._waitingData.actions,Ct,a),Ct._waitingData.actions=null)}_.actions!==void 0&&_.actions!==null&&ActionManager.Parse(_.actions,null,a)}catch(tr){var or=logOperation("loadAssets",_?_.producer:"Unknown")+d;if(o)o(or,tr);else throw Logger$2.Log(or),tr}finally{tempIndexContainer={},s||c.removeAllFromScene(),d!==null&&SceneLoader.loggingLevel!==SceneLoader.NO_LOGGING&&Logger$2.Log(logOperation("loadAssets",_?_.producer:"Unknown")+(SceneLoader.loggingLevel!==SceneLoader.MINIMAL_LOGGING?d:""))}return c};SceneLoader.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:function(a){return a.indexOf("babylon")!==-1},importMesh:function(a,i,e,o,s,c,d,_){var b="importMesh has failed JSON parse";try{var k=JSON.parse(e);b="";var j=SceneLoader.loggingLevel===SceneLoader.DETAILED_LOGGING;a?Array.isArray(a)||(a=[a]):a=null;var $=new Array;if(k.meshes!==void 0&&k.meshes!==null){var _e=[],et=[],tt,rt;for(tt=0,rt=k.meshes.length;tt<rt;tt++){var it=k.meshes[tt];if(a===null||isDescendantOf(it,a,$)){if(a!==null&&delete a[a.indexOf(it.name)],it.geometryId!==void 0&&it.geometryId!==null&&k.geometries!==void 0&&k.geometries!==null){var nt=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach(function(Pt){nt===!0||!k.geometries[Pt]||!Array.isArray(k.geometries[Pt])||k.geometries[Pt].forEach(function(It){if(It.id===it.geometryId){switch(Pt){case"vertexData":Geometry.Parse(It,i,o);break}nt=!0}})}),nt===!1&&Logger$2.Warn("Geometry not found for mesh "+it.id)}if(it.materialId){var ot=et.indexOf(it.materialId)!==-1;if(ot===!1&&k.multiMaterials!==void 0&&k.multiMaterials!==null)for(var at=0,st=k.multiMaterials.length;at<st;at++){var ut=k.multiMaterials[at];if(ut.id===it.materialId){for(var ft=0,lt=ut.materials.length;ft<lt;ft++){var ht=ut.materials[ft];et.push(ht);var pt=parseMaterialById(ht,k,i,o);pt&&(b+=`
  10313. Material `+pt.toString(j))}et.push(ut.id);var mt=MultiMaterial.ParseMultiMaterial(ut,i);mt&&(ot=!0,b+=`
  10314. Multi-Material `+mt.toString(j));break}}if(ot===!1){et.push(it.materialId);var pt=parseMaterialById(it.materialId,k,i,o);pt?b+=`
  10315. Material `+pt.toString(j):Logger$2.Warn("Material not found for mesh "+it.id)}}if(it.skeletonId>-1&&k.skeletons!==void 0&&k.skeletons!==null){var dt=_e.indexOf(it.skeletonId)>-1;if(dt===!1)for(var gt=0,_t=k.skeletons.length;gt<_t;gt++){var yt=k.skeletons[gt];if(yt.id===it.skeletonId){var Tt=Skeleton.Parse(yt,i);d.push(Tt),_e.push(yt.id),b+=`
  10316. Skeleton `+Tt.toString(j)}}}if(k.morphTargetManagers!==void 0&&k.morphTargetManagers!==null)for(var St=0,At=k.morphTargetManagers;St<At.length;St++){var vt=At[St];MorphTargetManager.Parse(vt,i)}var Et=Mesh.Parse(it,i,o);s.push(Et),b+=`
  10317. Mesh `+Et.toString(j)}}var xt;for(tt=0,rt=i.meshes.length;tt<rt;tt++)xt=i.meshes[tt],xt._waitingParentId&&(xt.parent=i.getLastEntryById(xt._waitingParentId),xt._waitingParentId=null),xt._waitingData.lods&&loadDetailLevels(i,xt);for(tt=0,rt=i.skeletons.length;tt<rt;tt++){var Tt=i.skeletons[tt];Tt._hasWaitingData&&(Tt.bones!=null&&Tt.bones.forEach(function(It){if(It._waitingTransformNodeId){var Dt=i.getLastEntryById(It._waitingTransformNodeId);Dt&&It.linkTransformNode(Dt),It._waitingTransformNodeId=null}}),Tt._waitingOverrideMeshId&&(Tt.overrideMesh=i.getMeshById(Tt._waitingOverrideMeshId),Tt._waitingOverrideMeshId=null),Tt._hasWaitingData=null)}for(tt=0,rt=i.meshes.length;tt<rt;tt++)xt=i.meshes[tt],xt._waitingData.freezeWorldMatrix?(xt.freezeWorldMatrix(),xt._waitingData.freezeWorldMatrix=null):xt.computeWorldMatrix(!0)}if(k.particleSystems!==void 0&&k.particleSystems!==null){var bt=AbstractScene.GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);if(bt)for(tt=0,rt=k.particleSystems.length;tt<rt;tt++){var Mt=k.particleSystems[tt];$.indexOf(Mt.emitterId)!==-1&&c.push(bt(Mt,i,o))}}return!0}catch(Pt){var Rt=logOperation("importMesh",k?k.producer:"Unknown")+b;if(_)_(Rt,Pt);else throw Logger$2.Log(Rt),Pt}finally{b!==null&&SceneLoader.loggingLevel!==SceneLoader.NO_LOGGING&&Logger$2.Log(logOperation("importMesh",k?k.producer:"Unknown")+(SceneLoader.loggingLevel!==SceneLoader.MINIMAL_LOGGING?b:""))}return!1},load:function(a,i,e,o){var s="importScene has failed JSON parse";try{var c=JSON.parse(i);if(s="",c.useDelayedTextureLoading!==void 0&&c.useDelayedTextureLoading!==null&&(a.useDelayedTextureLoading=c.useDelayedTextureLoading&&!SceneLoader.ForceFullSceneLoadingForIncremental),c.autoClear!==void 0&&c.autoClear!==null&&(a.autoClear=c.autoClear),c.clearColor!==void 0&&c.clearColor!==null&&(a.clearColor=Color4.FromArray(c.clearColor)),c.ambientColor!==void 0&&c.ambientColor!==null&&(a.ambientColor=Color3.FromArray(c.ambientColor)),c.gravity!==void 0&&c.gravity!==null&&(a.gravity=Vector3.FromArray(c.gravity)),c.fogMode&&c.fogMode!==0)switch(a.fogMode=c.fogMode,a.fogColor=Color3.FromArray(c.fogColor),a.fogStart=c.fogStart,a.fogEnd=c.fogEnd,a.fogDensity=c.fogDensity,s+=" Fog mode for scene: ",a.fogMode){case 1:s+=`exp
  10318. `;break;case 2:s+=`exp2
  10319. `;break;case 3:s+=`linear
  10320. `;break}if(c.physicsEnabled){var d;c.physicsEngine==="cannon"?d=new CannonJSPlugin(void 0,void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):c.physicsEngine==="oimo"?d=new OimoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):c.physicsEngine==="ammo"&&(d=new AmmoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(c.physicsEngine?c.physicsEngine:"oimo")+` enabled
  10321. `;var _=c.physicsGravity?Vector3.FromArray(c.physicsGravity):null;a.enablePhysics(_,d)}c.metadata!==void 0&&c.metadata!==null&&(a.metadata=c.metadata),c.collisionsEnabled!==void 0&&c.collisionsEnabled!==null&&(a.collisionsEnabled=c.collisionsEnabled);var b=loadAssetContainer(a,i,e,o,!0);return b?(c.autoAnimate&&a.beginAnimation(a,c.autoAnimateFrom,c.autoAnimateTo,c.autoAnimateLoop,c.autoAnimateSpeed||1),c.activeCameraID!==void 0&&c.activeCameraID!==null&&a.setActiveCameraById(c.activeCameraID),!0):!1}catch(j){var k=logOperation("importScene",c?c.producer:"Unknown")+s;if(o)o(k,j);else throw Logger$2.Log(k),j}finally{s!==null&&SceneLoader.loggingLevel!==SceneLoader.NO_LOGGING&&Logger$2.Log(logOperation("importScene",c?c.producer:"Unknown")+(SceneLoader.loggingLevel!==SceneLoader.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:function(a,i,e,o){var s=loadAssetContainer(a,i,e,o);return s}});var name$a="depthPixelShader",shader$a=`#ifdef ALPHATEST
  10322. varying vec2 vUV;
  10323. uniform sampler2D diffuseSampler;
  10324. #endif
  10325. varying float vDepthMetric;
  10326. #ifdef PACKED
  10327. #include<packingFunctions>
  10328. #endif
  10329. void main(void)
  10330. {
  10331. #ifdef ALPHATEST
  10332. if (texture2D(diffuseSampler,vUV).a<0.4)
  10333. discard;
  10334. #endif
  10335. #ifdef NONLINEARDEPTH
  10336. #ifdef PACKED
  10337. gl_FragColor=pack(gl_FragCoord.z);
  10338. #else
  10339. gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
  10340. #endif
  10341. #else
  10342. #ifdef PACKED
  10343. gl_FragColor=pack(vDepthMetric);
  10344. #else
  10345. gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
  10346. #endif
  10347. #endif
  10348. }`;ShaderStore.ShadersStore[name$a]=shader$a;var name$9="depthVertexShader",shader$9=`
  10349. attribute vec3 position;
  10350. #include<bonesDeclaration>
  10351. #include<bakedVertexAnimationDeclaration>
  10352. #include<morphTargetsVertexGlobalDeclaration>
  10353. #include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
  10354. #include<instancesDeclaration>
  10355. uniform mat4 viewProjection;
  10356. uniform vec2 depthValues;
  10357. #if defined(ALPHATEST) || defined(NEED_UV)
  10358. varying vec2 vUV;
  10359. uniform mat4 diffuseMatrix;
  10360. #ifdef UV1
  10361. attribute vec2 uv;
  10362. #endif
  10363. #ifdef UV2
  10364. attribute vec2 uv2;
  10365. #endif
  10366. #endif
  10367. varying float vDepthMetric;
  10368. void main(void)
  10369. {
  10370. vec3 positionUpdated=position;
  10371. #ifdef UV1
  10372. vec2 uvUpdated=uv;
  10373. #endif
  10374. #include<morphTargetsVertexGlobal>
  10375. #include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
  10376. #include<instancesVertex>
  10377. #include<bonesVertex>
  10378. #include<bakedVertexAnimation>
  10379. gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);
  10380. #ifdef USE_REVERSE_DEPTHBUFFER
  10381. vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
  10382. #else
  10383. vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
  10384. #endif
  10385. #if defined(ALPHATEST) || defined(BASIC_RENDER)
  10386. #ifdef UV1
  10387. vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
  10388. #endif
  10389. #ifdef UV2
  10390. vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
  10391. #endif
  10392. #endif
  10393. }
  10394. `;ShaderStore.ShadersStore[name$9]=shader$9;var DepthRenderer=function(){function a(i,e,o,s,c){var d=this;e===void 0&&(e=1),o===void 0&&(o=null),s===void 0&&(s=!1),c===void 0&&(c=Texture.TRILINEAR_SAMPLINGMODE),this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this._scene=i,this._storeNonLinearDepth=s,this.isPacked=e===0,this.isPacked?this._clearColor=new Color4(1,1,1,1):this._clearColor=new Color4(1,0,0,1),a._SceneComponentInitialization(this._scene);var _=i.getEngine();this._camera=o,c!==Texture.NEAREST_SAMPLINGMODE&&(e===1&&!_._caps.textureFloatLinearFiltering&&(c=Texture.NEAREST_SAMPLINGMODE),e===2&&!_._caps.textureHalfFloatLinearFiltering&&(c=Texture.NEAREST_SAMPLINGMODE));var b=this.isPacked||!_._features.supportExtendedTextureFormats?5:6;this._depthMap=new RenderTargetTexture("DepthRenderer",{width:_.getRenderWidth(),height:_.getRenderHeight()},this._scene,!1,!0,e,!1,c,void 0,void 0,void 0,b),this._depthMap.wrapU=Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(function(j){j.clear(d._clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(function(){var j;(j=_._debugPushGroup)===null||j===void 0||j.call(_,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(function(){var j;(j=_._debugPopGroup)===null||j===void 0||j.call(_,1)});var k=function(j){var $,_e,et=j.getRenderingMesh(),tt=j.getEffectiveMesh(),rt=d._scene,it=rt.getEngine(),nt=j.getMaterial();if(tt._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!(!nt||tt.infiniteDistance||nt.disableDepthWrite||j.verticesCount===0||j._renderId===rt.getRenderId())){var ot=tt._getWorldMatrixDeterminant()<0,at=($=et.overrideMaterialSideOrientation)!==null&&$!==void 0?$:nt.sideOrientation;(rt.useRightHandedSystem&&!ot||!rt.useRightHandedSystem&&ot)&&(at=at===0?1:0);var st=at===0;it.setState(nt.backFaceCulling,0,!1,st,nt.cullBackFaces);var ut=et._getInstancesRenderList(j._id,!!j.getReplacementMesh());if(!ut.mustReturn){var ft=it.getCaps().instancedArrays&&(ut.visibleInstances[j._id]!==null&&ut.visibleInstances[j._id]!==void 0||et.hasThinInstances),lt=d._camera||rt.activeCamera;if(d.isReady(j,ft)&&lt){j._renderId=rt.getRenderId();var ht=(_e=tt._internalAbstractMeshDataInfo._materialForRenderPass)===null||_e===void 0?void 0:_e[it.currentRenderPassId],pt=j._getDrawWrapper();!pt&&ht&&(pt=ht._getDrawWrapper());var mt=lt.mode===Camera$1.ORTHOGRAPHIC_CAMERA;if(!pt)return;var dt=pt.effect;it.enableEffect(pt),ft||et._bind(j,dt,nt.fillMode),ht?ht.bindForSubMesh(tt.getWorldMatrix(),tt,j):(dt.setMatrix("viewProjection",rt.getTransformMatrix()),dt.setMatrix("world",tt.getWorldMatrix()));var gt=void 0,_t=void 0;if(mt?(gt=!it.useReverseDepthBuffer&&it.isNDCHalfZRange?0:1,_t=it.useReverseDepthBuffer&&it.isNDCHalfZRange?0:1):(gt=it.useReverseDepthBuffer&&it.isNDCHalfZRange?lt.minZ:it.isNDCHalfZRange?0:lt.minZ,_t=it.useReverseDepthBuffer&&it.isNDCHalfZRange?0:lt.maxZ),dt.setFloat2("depthValues",gt,gt+_t),!ht){if(nt&&nt.needAlphaTesting()){var yt=nt.getAlphaTestTexture();yt&&(dt.setTexture("diffuseSampler",yt),dt.setMatrix("diffuseMatrix",yt.getTextureMatrix()))}if(et.useBones&&et.computeBonesUsingShaders&&et.skeleton){var Tt=et.skeleton;if(Tt.isUsingTextureForMatrices){var St=Tt.getTransformMatrixTexture(et);if(!St)return;dt.setTexture("boneSampler",St),dt.setFloat("boneTextureWidth",4*(Tt.bones.length+1))}else dt.setMatrices("mBones",Tt.getTransformMatrices(et))}MaterialHelper.BindMorphTargetParameters(et,dt),et.morphTargetManager&&et.morphTargetManager.isUsingTextureForTargets&&et.morphTargetManager._bind(dt)}et._processRendering(tt,j,dt,nt.fillMode,ut,ft,function(At,vt){return dt.setMatrix("world",vt)})}}}};this._depthMap.customRenderFunction=function(j,$,_e,et){var tt;if(et.length)for(tt=0;tt<et.length;tt++)k(et.data[tt]);for(tt=0;tt<j.length;tt++)k(j.data[tt]);for(tt=0;tt<$.length;tt++)k($.data[tt]);if(d.forceDepthWriteTransparentMeshes)for(tt=0;tt<_e.length;tt++)k(_e.data[tt]);else for(tt=0;tt<_e.length;tt++)_e.data[tt].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}return a.prototype.setMaterialForRendering=function(i,e){this._depthMap.setMaterialForRendering(i,e)},a.prototype.isReady=function(i,e){var o,s=this._scene.getEngine(),c=i.getMesh(),d=(o=c._internalAbstractMeshDataInfo._materialForRenderPass)===null||o===void 0?void 0:o[s.currentRenderPassId];if(d)return d.isReadyForSubMesh(c,i,e);var _=i.getMaterial();if(!_||_.disableDepthWrite)return!1;var b=[],k=[VertexBuffer.PositionKind];if(_&&_.needAlphaTesting()&&_.getAlphaTestTexture()&&(b.push("#define ALPHATEST"),c.isVerticesDataPresent(VertexBuffer.UVKind)&&(k.push(VertexBuffer.UVKind),b.push("#define UV1")),c.isVerticesDataPresent(VertexBuffer.UV2Kind)&&(k.push(VertexBuffer.UV2Kind),b.push("#define UV2"))),c.useBones&&c.computeBonesUsingShaders){k.push(VertexBuffer.MatricesIndicesKind),k.push(VertexBuffer.MatricesWeightsKind),c.numBoneInfluencers>4&&(k.push(VertexBuffer.MatricesIndicesExtraKind),k.push(VertexBuffer.MatricesWeightsExtraKind)),b.push("#define NUM_BONE_INFLUENCERS "+c.numBoneInfluencers),b.push("#define BonesPerMesh "+(c.skeleton?c.skeleton.bones.length+1:0));var j=i.getRenderingMesh().skeleton;j!=null&&j.isUsingTextureForMatrices&&b.push("#define BONETEXTURE")}else b.push("#define NUM_BONE_INFLUENCERS 0");var $=c.morphTargetManager,_e=0;$&&$.numInfluencers>0&&(_e=$.numInfluencers,b.push("#define MORPHTARGETS"),b.push("#define NUM_MORPH_INFLUENCERS "+_e),$.isUsingTextureForTargets&&b.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(k,c,_e)),e&&(b.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(k),i.getRenderingMesh().hasThinInstances&&b.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&b.push("#define NONLINEARDEPTH"),this.isPacked&&b.push("#define PACKED");var et=i._getDrawWrapper(void 0,!0),tt=et.defines,rt=b.join(`
  10395. `);return tt!==rt&&et.setEffect(s.createEffect("depth",k,["world","mBones","boneTextureWidth","viewProjection","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"],["diffuseSampler","morphTargets","boneSampler"],rt,void 0,void 0,void 0,{maxSimultaneousMorphTargets:_e}),rt),et.effect.isReady()},a.prototype.getDepthMap=function(){return this._depthMap},a.prototype.dispose=function(){var i=[];for(var e in this._scene._depthRenderer){var o=this._scene._depthRenderer[e];o===this&&i.push(e)}if(i.length>0){this._depthMap.dispose();for(var s=0,c=i;s<c.length;s++){var d=c[s];delete this._scene._depthRenderer[d]}}},a._SceneComponentInitialization=function(i){throw _WarnImport("DepthRendererSceneComponent")},a}(),name$8="minmaxReduxPixelShader",shader$8=`varying vec2 vUV;
  10396. uniform sampler2D textureSampler;
  10397. #if defined(INITIAL)
  10398. uniform sampler2D sourceTexture;
  10399. uniform vec2 texSize;
  10400. void main(void)
  10401. {
  10402. ivec2 coord=ivec2(vUV*(texSize-1.0));
  10403. float f1=texelFetch(sourceTexture,coord,0).r;
  10404. float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;
  10405. float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;
  10406. float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;
  10407. float minz=min(min(min(f1,f2),f3),f4);
  10408. #ifdef DEPTH_REDUX
  10409. float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
  10410. #else
  10411. float maxz=max(max(max(f1,f2),f3),f4);
  10412. #endif
  10413. glFragColor=vec4(minz,maxz,0.,0.);
  10414. }
  10415. #elif defined(MAIN)
  10416. uniform vec2 texSize;
  10417. void main(void)
  10418. {
  10419. ivec2 coord=ivec2(vUV*(texSize-1.0));
  10420. vec2 f1=texelFetch(textureSampler,coord,0).rg;
  10421. vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;
  10422. vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;
  10423. vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;
  10424. float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);
  10425. float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);
  10426. glFragColor=vec4(minz,maxz,0.,0.);
  10427. }
  10428. #elif defined(ONEBEFORELAST)
  10429. uniform ivec2 texSize;
  10430. void main(void)
  10431. {
  10432. ivec2 coord=ivec2(vUV*vec2(texSize-1));
  10433. vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;
  10434. vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;
  10435. vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;
  10436. vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;
  10437. float minz=min(f1.x,f2.x);
  10438. float maxz=max(f1.y,f2.y);
  10439. glFragColor=vec4(minz,maxz,0.,0.);
  10440. }
  10441. #elif defined(LAST)
  10442. void main(void)
  10443. {
  10444. glFragColor=vec4(0.);
  10445. discard;
  10446. }
  10447. #endif
  10448. `;ShaderStore.ShadersStore[name$8]=shader$8;var MinMaxReducer=function(){function a(i){var e=this;this.onAfterReductionPerformed=new Observable,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=i,this._postProcessManager=new PostProcessManager(i.getScene()),this._onContextRestoredObserver=i.getEngine().onContextRestoredObservable.add(function(){e._postProcessManager._rebuild()})}return Object.defineProperty(a.prototype,"sourceTexture",{get:function(){return this._sourceTexture},enumerable:!1,configurable:!0}),a.prototype.setSourceTexture=function(i,e,o,s){var c=this;if(o===void 0&&(o=2),s===void 0&&(s=!0),i!==this._sourceTexture){this.dispose(!1),this._sourceTexture=i,this._reductionSteps=[],this._forceFullscreenViewport=s;var d=this._camera.getScene(),_=new PostProcess("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,d.getEngine(),!1,"#define INITIAL"+(e?`
  10449. #define DEPTH_REDUX`:""),o,void 0,void 0,void 0,7);_.autoClear=!1,_.forceFullscreenViewport=s;var b=this._sourceTexture.getRenderWidth(),k=this._sourceTexture.getRenderHeight();_.onApply=function(et,tt){return function(rt){rt.setTexture("sourceTexture",c._sourceTexture),rt.setFloat2("texSize",et,tt)}}(b,k),this._reductionSteps.push(_);for(var j=1;b>1||k>1;){b=Math.max(Math.round(b/2),1),k=Math.max(Math.round(k/2),1);var $=new PostProcess("Reduction phase "+j,"minmaxRedux",["texSize"],null,{width:b,height:k},null,1,d.getEngine(),!1,"#define "+(b==1&&k==1?"LAST":b==1||k==1?"ONEBEFORELAST":"MAIN"),o,void 0,void 0,void 0,7);if($.autoClear=!1,$.forceFullscreenViewport=s,$.onApply=function(et,tt){return function(rt){et==1||tt==1?rt.setInt2("texSize",et,tt):rt.setFloat2("texSize",et,tt)}}(b,k),this._reductionSteps.push($),j++,b==1&&k==1){var _e=function(et,tt,rt){var it=new Float32Array(4*et*tt),nt={min:0,max:0};return function(){d.getEngine()._readTexturePixels(rt.inputTexture.texture,et,tt,-1,0,it,!1),nt.min=it[0],nt.max=it[1],c.onAfterReductionPerformed.notifyObservers(nt)}};$.onAfterRenderObservable.add(_e(b,k,$))}}}},Object.defineProperty(a.prototype,"refreshRate",{get:function(){return this._sourceTexture?this._sourceTexture.refreshRate:-1},set:function(i){this._sourceTexture&&(this._sourceTexture.refreshRate=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"activated",{get:function(){return this._activated},enumerable:!1,configurable:!0}),a.prototype.activate=function(){var i=this;this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(function(){var e,o,s=i._camera.getScene().getEngine();(e=s._debugPushGroup)===null||e===void 0||e.call(s,"min max reduction",1),i._reductionSteps[0].activate(i._camera),i._postProcessManager.directRender(i._reductionSteps,i._reductionSteps[0].inputTexture,i._forceFullscreenViewport),s.unBindFramebuffer(i._reductionSteps[0].inputTexture,!1),(o=s._debugPopGroup)===null||o===void 0||o.call(s,1)}),this._activated=!0)},a.prototype.deactivate=function(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)},a.prototype.dispose=function(i){if(i===void 0&&(i=!0),i&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(var e=0;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps=null}this._postProcessManager&&i&&this._postProcessManager.dispose(),this._sourceTexture=null},a}(),DepthReducer=function(a){__extends(i,a);function i(e){return a.call(this,e)||this}return Object.defineProperty(i.prototype,"depthRenderer",{get:function(){return this._depthRenderer},enumerable:!1,configurable:!0}),i.prototype.setDepthRenderer=function(e,o,s){e===void 0&&(e=null),o===void 0&&(o=2),s===void 0&&(s=!0);var c=this._camera.getScene();this._depthRenderer&&(delete c._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),e===null&&(c._depthRenderer||(c._depthRenderer={}),e=this._depthRenderer=new DepthRenderer(c,o,this._camera,!1,1),e.enabled=!1,this._depthRendererId="minmax"+this._camera.id,c._depthRenderer[this._depthRendererId]=e),a.prototype.setSourceTexture.call(this,e.getDepthMap(),!0,o,s)},i.prototype.setSourceTexture=function(e,o,s,c){s===void 0&&(s=2),c===void 0&&(c=!0),a.prototype.setSourceTexture.call(this,e,o,s,c)},i.prototype.activate=function(){this._depthRenderer&&(this._depthRenderer.enabled=!0),a.prototype.activate.call(this)},i.prototype.deactivate=function(){a.prototype.deactivate.call(this),this._depthRenderer&&(this._depthRenderer.enabled=!1)},i.prototype.dispose=function(e){if(e===void 0&&(e=!0),a.prototype.dispose.call(this,e),this._depthRenderer&&e){var o=this._depthRenderer.getDepthMap().getScene();o&&delete o._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null}},i}(MinMaxReducer),UpDir=Vector3.Up(),ZeroVec=Vector3.Zero(),tmpv1=new Vector3,tmpv2=new Vector3,tmpMatrix=new Matrix,CascadedShadowGenerator=function(a){__extends(i,a);function i(e,o,s){var c=this;if(!i.IsSupported){Logger$2.Error("CascadedShadowMap is not supported by the current engine.");return}return c=a.call(this,e,o,s)||this,c.usePercentageCloserFiltering=!0,c}return i.prototype._validateFilter=function(e){return e===ShadowGenerator.FILTER_NONE||e===ShadowGenerator.FILTER_PCF||e===ShadowGenerator.FILTER_PCSS?e:(console.error('Unsupported filter "'+e+'"!'),ShadowGenerator.FILTER_NONE)},Object.defineProperty(i.prototype,"numCascades",{get:function(){return this._numCascades},set:function(e){e=Math.min(Math.max(e,i.MIN_CASCADES_COUNT),i.MAX_CASCADES_COUNT),e!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"freezeShadowCastersBoundingInfo",{get:function(){return this._freezeShadowCastersBoundingInfo},set:function(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),!this._freezeShadowCastersBoundingInfoObservable&&!e&&(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()},enumerable:!1,configurable:!0}),i.prototype._computeShadowCastersBoundingInfo=function(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._shadowMap&&this._shadowMap.renderList){for(var e=this._shadowMap.renderList,o=0;o<e.length;o++){var s=e[o];if(!!s){var c=s.getBoundingInfo(),d=c.boundingBox;this._scbiMin.minimizeInPlace(d.minimumWorld),this._scbiMax.maximizeInPlace(d.maximumWorld)}}for(var _=this._scene.meshes,o=0;o<_.length;o++){var s=_[o];if(!(!s||!s.isVisible||!s.isEnabled||!s.receiveShadows)){var c=s.getBoundingInfo(),d=c.boundingBox;this._scbiMin.minimizeInPlace(d.minimumWorld),this._scbiMax.maximizeInPlace(d.maximumWorld)}}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)},Object.defineProperty(i.prototype,"shadowCastersBoundingInfo",{get:function(){return this._shadowCastersBoundingInfo},set:function(e){this._shadowCastersBoundingInfo=e},enumerable:!1,configurable:!0}),i.prototype.setMinMaxDistance=function(e,o){this._minDistance===e&&this._maxDistance===o||(e>o&&(e=0,o=1),e<0&&(e=0),o>1&&(o=1),this._minDistance=e,this._maxDistance=o,this._breaksAreDirty=!0)},Object.defineProperty(i.prototype,"minDistance",{get:function(){return this._minDistance},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"maxDistance",{get:function(){return this._maxDistance},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return i.CLASSNAME},i.prototype.getCascadeMinExtents=function(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null},i.prototype.getCascadeMaxExtents=function(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null},Object.defineProperty(i.prototype,"shadowMaxZ",{get:function(){return!this._scene||!this._scene.activeCamera?0:this._shadowMaxZ},set:function(e){if(!this._scene||!this._scene.activeCamera){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<this._scene.activeCamera.minZ||e>this._scene.activeCamera.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"debug",{get:function(){return this._debug},set:function(e){this._debug=e,this._light._markMeshesAsLightDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"depthClamp",{get:function(){return this._depthClamp},set:function(e){this._depthClamp=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cascadeBlendPercentage",{get:function(){return this._cascadeBlendPercentage},set:function(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"lambda",{get:function(){return this._lambda},set:function(e){var o=Math.min(Math.max(e,0),1);this._lambda!=o&&(this._lambda=o,this._breaksAreDirty=!0)},enumerable:!1,configurable:!0}),i.prototype.getCascadeViewMatrix=function(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null},i.prototype.getCascadeProjectionMatrix=function(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null},i.prototype.getCascadeTransformMatrix=function(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null},i.prototype.setDepthRenderer=function(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)},Object.defineProperty(i.prototype,"autoCalcDepthBounds",{get:function(){return this._autoCalcDepthBounds},set:function(e){var o=this,s=this._scene.activeCamera;if(!!s){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new DepthReducer(s),this._depthReducer.onAfterReductionPerformed.add(function(c){var d=c.min,_=c.max;d>=_&&(d=0,_=1),(d!=o._minDistance||_!=o._maxDistance)&&o.setMinMaxDistance(d,_)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"autoCalcDepthBoundsRefreshRate",{get:function(){var e,o,s;return(s=(o=(e=this._depthReducer)===null||e===void 0?void 0:e.depthRenderer)===null||o===void 0?void 0:o.getDepthMap().refreshRate)!==null&&s!==void 0?s:-1},set:function(e){var o;!((o=this._depthReducer)===null||o===void 0)&&o.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)},enumerable:!1,configurable:!0}),i.prototype.splitFrustum=function(){this._breaksAreDirty=!0},i.prototype._splitFrustum=function(){var e=this._scene.activeCamera;if(!!e){for(var o=e.minZ,s=e.maxZ,c=s-o,d=this._minDistance,_=this._shadowMaxZ<s&&this._shadowMaxZ>=o?Math.min((this._shadowMaxZ-o)/(s-o),this._maxDistance):this._maxDistance,b=o+d*c,k=o+_*c,j=k-b,$=k/b,_e=0;_e<this._cascades.length;++_e){var et=(_e+1)/this._numCascades,tt=b*Math.pow($,et),rt=b+j*et,it=this._lambda*(tt-rt)+rt;this._cascades[_e].prevBreakDistance=_e===0?d:this._cascades[_e-1].breakDistance,this._cascades[_e].breakDistance=(it-o)/c,this._viewSpaceFrustumsZ[_e]=it,this._frustumLengths[_e]=(this._cascades[_e].breakDistance-this._cascades[_e].prevBreakDistance)*c}this._breaksAreDirty=!1}},i.prototype._computeMatrices=function(){var e=this._scene,o=e.activeCamera;if(!!o){Vector3.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),Math.abs(Vector3.Dot(this._lightDirection,Vector3.Up()))===1&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);for(var s=e.getEngine().useReverseDepthBuffer,c=0;c<this._numCascades;++c){this._computeFrustumInWorldSpace(c),this._computeCascadeFrustum(c),this._cascadeMaxExtents[c].subtractToRef(this._cascadeMinExtents[c],tmpv1),this._frustumCenter[c].addToRef(this._lightDirection.scale(this._cascadeMinExtents[c].z),this._shadowCameraPos[c]),Matrix.LookAtLHToRef(this._shadowCameraPos[c],this._frustumCenter[c],UpDir,this._viewMatrices[c]);var d=0,_=tmpv1.z,b=this._shadowCastersBoundingInfo;b.update(this._viewMatrices[c]),_=Math.min(_,b.boundingBox.maximumWorld.z),!this._depthClamp||this.filter===ShadowGenerator.FILTER_PCSS?d=Math.min(d,b.boundingBox.minimumWorld.z):d=Math.max(d,b.boundingBox.minimumWorld.z),Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[c].x,this._cascadeMaxExtents[c].x,this._cascadeMinExtents[c].y,this._cascadeMaxExtents[c].y,s?_:d,s?d:_,this._projectionMatrices[c],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[c].z=d,this._cascadeMaxExtents[c].z=_,this._viewMatrices[c].multiplyToRef(this._projectionMatrices[c],this._transformMatrices[c]),Vector3.TransformCoordinatesToRef(ZeroVec,this._transformMatrices[c],tmpv1),tmpv1.scaleInPlace(this._mapSize/2),tmpv2.copyFromFloats(Math.round(tmpv1.x),Math.round(tmpv1.y),Math.round(tmpv1.z)),tmpv2.subtractInPlace(tmpv1).scaleInPlace(2/this._mapSize),Matrix.TranslationToRef(tmpv2.x,tmpv2.y,0,tmpMatrix),this._projectionMatrices[c].multiplyToRef(tmpMatrix,this._projectionMatrices[c]),this._viewMatrices[c].multiplyToRef(this._projectionMatrices[c],this._transformMatrices[c]),this._transformMatrices[c].copyToArray(this._transformMatricesAsArray,c*16)}}},i.prototype._computeFrustumInWorldSpace=function(e){if(!!this._scene.activeCamera){var o=this._cascades[e].prevBreakDistance,s=this._cascades[e].breakDistance,c=this._scene.getEngine().isNDCHalfZRange;this._scene.activeCamera.getViewMatrix();for(var d=Matrix.Invert(this._scene.activeCamera.getTransformationMatrix()),_=this._scene.getEngine().useReverseDepthBuffer?4:0,b=0;b<i.frustumCornersNDCSpace.length;++b)tmpv1.copyFrom(i.frustumCornersNDCSpace[(b+_)%i.frustumCornersNDCSpace.length]),c&&tmpv1.z===-1&&(tmpv1.z=0),Vector3.TransformCoordinatesToRef(tmpv1,d,this._frustumCornersWorldSpace[e][b]);for(var b=0;b<i.frustumCornersNDCSpace.length/2;++b)tmpv1.copyFrom(this._frustumCornersWorldSpace[e][b+4]).subtractInPlace(this._frustumCornersWorldSpace[e][b]),tmpv2.copyFrom(tmpv1).scaleInPlace(o),tmpv1.scaleInPlace(s),tmpv1.addInPlace(this._frustumCornersWorldSpace[e][b]),this._frustumCornersWorldSpace[e][b+4].copyFrom(tmpv1),this._frustumCornersWorldSpace[e][b].addInPlace(tmpv2)}},i.prototype._computeCascadeFrustum=function(e){this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0);var o=this._scene.activeCamera;if(!!o){for(var s=0;s<this._frustumCornersWorldSpace[e].length;++s)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][s]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){for(var c=0,s=0;s<this._frustumCornersWorldSpace[e].length;++s){var d=this._frustumCornersWorldSpace[e][s].subtractToRef(this._frustumCenter[e],tmpv1).length();c=Math.max(c,d)}c=Math.ceil(c*16)/16,this._cascadeMaxExtents[e].copyFromFloats(c,c,c),this._cascadeMinExtents[e].copyFromFloats(-c,-c,-c)}else{var _=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,tmpv1),Matrix.LookAtLHToRef(_,tmpv1,UpDir,tmpMatrix);for(var s=0;s<this._frustumCornersWorldSpace[e].length;++s)Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][s],tmpMatrix,tmpv1),this._cascadeMinExtents[e].minimizeInPlace(tmpv1),this._cascadeMaxExtents[e].maximizeInPlace(tmpv1)}}},i.prototype._recreateSceneUBOs=function(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(var e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer('Scene for CSM Shadow Generator (light "'+this._light.name+'" cascade #'+e+")"))},Object.defineProperty(i,"IsSupported",{get:function(){var e=EngineStore.LastCreatedEngine;return e?e._features.supportCSM:!1},enumerable:!1,configurable:!0}),i.prototype._initializeGenerator=function(){var e,o,s,c,d,_,b,k,j,$,_e,et,tt,rt,it,nt,ot,at,st,ut;this.penumbraDarkness=(e=this.penumbraDarkness)!==null&&e!==void 0?e:1,this._numCascades=(o=this._numCascades)!==null&&o!==void 0?o:i.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=(s=this.stabilizeCascades)!==null&&s!==void 0?s:!1,this._freezeShadowCastersBoundingInfoObservable=(c=this._freezeShadowCastersBoundingInfoObservable)!==null&&c!==void 0?c:null,this.freezeShadowCastersBoundingInfo=(d=this.freezeShadowCastersBoundingInfo)!==null&&d!==void 0?d:!1,this._scbiMin=(_=this._scbiMin)!==null&&_!==void 0?_:new Vector3(0,0,0),this._scbiMax=(b=this._scbiMax)!==null&&b!==void 0?b:new Vector3(0,0,0),this._shadowCastersBoundingInfo=(k=this._shadowCastersBoundingInfo)!==null&&k!==void 0?k:new BoundingInfo(new Vector3(0,0,0),new Vector3(0,0,0)),this._breaksAreDirty=(j=this._breaksAreDirty)!==null&&j!==void 0?j:!0,this._minDistance=($=this._minDistance)!==null&&$!==void 0?$:0,this._maxDistance=(_e=this._maxDistance)!==null&&_e!==void 0?_e:1,this._currentLayer=(et=this._currentLayer)!==null&&et!==void 0?et:0,this._shadowMaxZ=(it=(tt=this._shadowMaxZ)!==null&&tt!==void 0?tt:(rt=this._scene.activeCamera)===null||rt===void 0?void 0:rt.maxZ)!==null&&it!==void 0?it:1e4,this._debug=(nt=this._debug)!==null&&nt!==void 0?nt:!1,this._depthClamp=(ot=this._depthClamp)!==null&&ot!==void 0?ot:!0,this._cascadeBlendPercentage=(at=this._cascadeBlendPercentage)!==null&&at!==void 0?at:.1,this._lambda=(st=this._lambda)!==null&&st!==void 0?st:.5,this._autoCalcDepthBounds=(ut=this._autoCalcDepthBounds)!==null&&ut!==void 0?ut:!1,this._recreateSceneUBOs(),a.prototype._initializeGenerator.call(this)},i.prototype._createTargetRenderTexture=function(){var e=this._scene.getEngine(),o={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new RenderTargetTexture(this._light.name+"_CSMShadowMap",o,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)},i.prototype._initializeShadowMap=function(){var e=this;if(a.prototype._initializeShadowMap.call(this),this._shadowMap!==null){this._transformMatricesAsArray=new Float32Array(this._numCascades*16),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(this._numCascades*2),this._depthCorrection=new Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(var o=0;o<this._numCascades;++o){this._cascades[o]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[o]=Matrix.Zero(),this._projectionMatrices[o]=Matrix.Zero(),this._transformMatrices[o]=Matrix.Zero(),this._cascadeMinExtents[o]=new Vector3,this._cascadeMaxExtents[o]=new Vector3,this._frustumCenter[o]=new Vector3,this._shadowCameraPos[o]=new Vector3,this._frustumCornersWorldSpace[o]=new Array(i.frustumCornersNDCSpace.length);for(var s=0;s<i.frustumCornersNDCSpace.length;++s)this._frustumCornersWorldSpace[o][s]=new Vector3}var c=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(function(d){e._sceneUBOs&&e._scene.setSceneUniformBuffer(e._sceneUBOs[d]),e._currentLayer=d,e._filter===ShadowGenerator.FILTER_PCF&&c.setColorWrite(!1),e._scene.setTransformMatrix(e.getCascadeViewMatrix(d),e.getCascadeProjectionMatrix(d)),e._useUBO&&(e._scene.getSceneUniformBuffer().unbindEffect(),e._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(function(){var d;e._currentSceneUBO=e._scene.getSceneUniformBuffer(),(d=c._debugPushGroup)===null||d===void 0||d.call(c,"cascaded shadow map generation for pass id "+c.currentRenderPassId,1),e._breaksAreDirty&&e._splitFrustum(),e._computeMatrices()}),this._splitFrustum()}},i.prototype._bindCustomEffectForRenderSubMeshForShadowMap=function(e,o,s){o.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))},i.prototype._isReadyCustomDefines=function(e,o,s){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==ShadowGenerator.FILTER_PCSS?"1":"0"))},i.prototype.prepareDefines=function(e,o){a.prototype.prepareDefines.call(this,e,o);var s=this._scene,c=this._light;if(!(!s.shadowsEnabled||!c.shadowEnabled)){e["SHADOWCSM"+o]=!0,e["SHADOWCSMDEBUG"+o]=this.debug,e["SHADOWCSMNUM_CASCADES"+o]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+o]=s.useRightHandedSystem;var d=s.activeCamera;d&&this._shadowMaxZ<d.maxZ&&(e["SHADOWCSMUSESHADOWMAXZ"+o]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+o]=!0)}},i.prototype.bindShadowLight=function(e,o){var s=this._light,c=this._scene;if(!(!c.shadowsEnabled||!s.shadowEnabled)){var d=c.activeCamera;if(!!d){var _=this.getShadowMap();if(!!_){var b=_.getSize().width;if(o.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),o.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),o.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),o.setArray("frustumLengths"+e,this._frustumLengths),this._filter===ShadowGenerator.FILTER_PCF)o.setDepthStencilTexture("shadowSampler"+e,_),s._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),b,1/b,this.frustumEdgeFalloff,e);else if(this._filter===ShadowGenerator.FILTER_PCSS){for(var k=0;k<this._numCascades;++k)this._lightSizeUVCorrection[k*2+0]=k===0?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[k].x-this._cascadeMinExtents[k].x),this._lightSizeUVCorrection[k*2+1]=k===0?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[k].y-this._cascadeMinExtents[k].y),this._depthCorrection[k]=k===0?1:(this._cascadeMaxExtents[k].z-this._cascadeMinExtents[k].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);o.setDepthStencilTexture("shadowSampler"+e,_),o.setTexture("depthSampler"+e,_),o.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),o.setArray("depthCorrection"+e,this._depthCorrection),o.setFloat("penumbraDarkness"+e,this.penumbraDarkness),s._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/b,this._contactHardeningLightSizeUVRatio*b,this.frustumEdgeFalloff,e)}else o.setTexture("shadowSampler"+e,_),s._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),b,1/b,this.frustumEdgeFalloff,e);s._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(d),this.getLight().getDepthMinZ(d)+this.getLight().getDepthMaxZ(d),e)}}}},i.prototype.getTransformMatrix=function(){return this.getCascadeTransformMatrix(0)},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)},i.prototype.serialize=function(){var e=a.prototype.serialize.call(this),o=this.getShadowMap();if(!o)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],o.renderList)for(var s=0;s<o.renderList.length;s++){var c=o.renderList[s];e.renderList.push(c.id)}return e},i.Parse=function(e,o){var s=ShadowGenerator.Parse(e,o,function(c,d){return new i(c,d)});return e.numCascades!==void 0&&(s.numCascades=e.numCascades),e.debug!==void 0&&(s.debug=e.debug),e.stabilizeCascades!==void 0&&(s.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(s.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(s.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(s.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(s.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(s.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(s.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(s.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&s.setMinMaxDistance(e.minDistance,e.maxDistance),s},i.frustumCornersNDCSpace=[new Vector3(-1,1,-1),new Vector3(1,1,-1),new Vector3(1,-1,-1),new Vector3(-1,-1,-1),new Vector3(-1,1,1),new Vector3(1,1,1),new Vector3(1,-1,1),new Vector3(-1,-1,1)],i.CLASSNAME="CascadedShadowGenerator",i.DEFAULT_CASCADES_COUNT=4,i.MIN_CASCADES_COUNT=2,i.MAX_CASCADES_COUNT=4,i._SceneComponentInitialization=function(e){throw _WarnImport("ShadowGeneratorSceneComponent")},i}(ShadowGenerator);AbstractScene.AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR,function(a,i){if(a.shadowGenerators!==void 0&&a.shadowGenerators!==null)for(var e=0,o=a.shadowGenerators.length;e<o;e++){var s=a.shadowGenerators[e];s.className===CascadedShadowGenerator.CLASSNAME?CascadedShadowGenerator.Parse(s,i):ShadowGenerator.Parse(s,i)}});var ShadowGeneratorSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_SHADOWGENERATOR,this.scene=i}return a.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)},a.prototype.rebuild=function(){},a.prototype.serialize=function(i){i.shadowGenerators=[];for(var e=this.scene.lights,o=0,s=e;o<s.length;o++){var c=s[o],d=c.getShadowGenerator();d&&i.shadowGenerators.push(d.serialize())}},a.prototype.addFromContainer=function(i){},a.prototype.removeFromContainer=function(i,e){},a.prototype.dispose=function(){},a.prototype._gatherRenderTargets=function(i){var e=this.scene;if(this.scene.shadowsEnabled)for(var o=0;o<e.lights.length;o++){var s=e.lights[o],c=s.getShadowGenerator();if(s.isEnabled()&&s.shadowEnabled&&c){var d=c.getShadowMap();e.textures.indexOf(d)!==-1&&i.push(d)}}},a}();ShadowGenerator._SceneComponentInitialization=function(a){var i=a._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR);i||(i=new ShadowGeneratorSceneComponent(a),a._addComponent(i))};var DDS_MAGIC=542327876,DDSD_MIPMAPCOUNT=131072,DDSCAPS2_CUBEMAP=512,DDPF_FOURCC=4,DDPF_RGB=64,DDPF_LUMINANCE=131072;function FourCCToInt32(a){return a.charCodeAt(0)+(a.charCodeAt(1)<<8)+(a.charCodeAt(2)<<16)+(a.charCodeAt(3)<<24)}function Int32ToFourCC(a){return String.fromCharCode(a&255,a>>8&255,a>>16&255,a>>24&255)}var FOURCC_DXT1=FourCCToInt32("DXT1"),FOURCC_DXT3=FourCCToInt32("DXT3"),FOURCC_DXT5=FourCCToInt32("DXT5"),FOURCC_DX10=FourCCToInt32("DX10"),FOURCC_D3DFMT_R16G16B16A16F=113,FOURCC_D3DFMT_R32G32B32A32F=116,DXGI_FORMAT_R32G32B32A32_FLOAT=2,DXGI_FORMAT_R16G16B16A16_FLOAT=10,DXGI_FORMAT_B8G8R8X8_UNORM=88,headerLengthInt=31,off_magic=0,off_size=1,off_flags=2,off_height=3,off_width=4,off_mipmapCount=7,off_pfFlags=20,off_pfFourCC=21,off_RGBbpp=22,off_RMask=23,off_GMask=24,off_BMask=25,off_AMask=26,off_caps2=28,off_dxgiFormat=32,DDSTools=function(){function a(){}return a.GetDDSInfo=function(i){var e=new Int32Array(i.buffer,i.byteOffset,headerLengthInt),o=new Int32Array(i.buffer,i.byteOffset,headerLengthInt+4),s=1;e[off_flags]&DDSD_MIPMAPCOUNT&&(s=Math.max(1,e[off_mipmapCount]));var c=e[off_pfFourCC],d=c===FOURCC_DX10?o[off_dxgiFormat]:0,_=0;switch(c){case FOURCC_D3DFMT_R16G16B16A16F:_=2;break;case FOURCC_D3DFMT_R32G32B32A32F:_=1;break;case FOURCC_DX10:if(d===DXGI_FORMAT_R16G16B16A16_FLOAT){_=2;break}if(d===DXGI_FORMAT_R32G32B32A32_FLOAT){_=1;break}}return{width:e[off_width],height:e[off_height],mipmapCount:s,isFourCC:(e[off_pfFlags]&DDPF_FOURCC)===DDPF_FOURCC,isRGB:(e[off_pfFlags]&DDPF_RGB)===DDPF_RGB,isLuminance:(e[off_pfFlags]&DDPF_LUMINANCE)===DDPF_LUMINANCE,isCube:(e[off_caps2]&DDSCAPS2_CUBEMAP)===DDSCAPS2_CUBEMAP,isCompressed:c===FOURCC_DXT1||c===FOURCC_DXT3||c===FOURCC_DXT5,dxgiFormat:d,textureType:_}},a._GetHalfFloatAsFloatRGBAArrayBuffer=function(i,e,o,s,c,d){for(var _=new Float32Array(s),b=new Uint16Array(c,o),k=0,j=0;j<e;j++)for(var $=0;$<i;$++){var _e=($+j*i)*4;_[k]=FromHalfFloat(b[_e]),_[k+1]=FromHalfFloat(b[_e+1]),_[k+2]=FromHalfFloat(b[_e+2]),a.StoreLODInAlphaChannel?_[k+3]=d:_[k+3]=FromHalfFloat(b[_e+3]),k+=4}return _},a._GetHalfFloatRGBAArrayBuffer=function(i,e,o,s,c,d){if(a.StoreLODInAlphaChannel){for(var _=new Uint16Array(s),b=new Uint16Array(c,o),k=0,j=0;j<e;j++)for(var $=0;$<i;$++){var _e=($+j*i)*4;_[k]=b[_e],_[k+1]=b[_e+1],_[k+2]=b[_e+2],_[k+3]=ToHalfFloat(d),k+=4}return _}return new Uint16Array(c,o,s)},a._GetFloatRGBAArrayBuffer=function(i,e,o,s,c,d){if(a.StoreLODInAlphaChannel){for(var _=new Float32Array(s),b=new Float32Array(c,o),k=0,j=0;j<e;j++)for(var $=0;$<i;$++){var _e=($+j*i)*4;_[k]=b[_e],_[k+1]=b[_e+1],_[k+2]=b[_e+2],_[k+3]=d,k+=4}return _}return new Float32Array(c,o,s)},a._GetFloatAsHalfFloatRGBAArrayBuffer=function(i,e,o,s,c,d){for(var _=new Uint16Array(s),b=new Float32Array(c,o),k=0,j=0;j<e;j++)for(var $=0;$<i;$++)_[k]=ToHalfFloat(b[k]),_[k+1]=ToHalfFloat(b[k+1]),_[k+2]=ToHalfFloat(b[k+2]),a.StoreLODInAlphaChannel?_[k+3]=ToHalfFloat(d):_[k+3]=ToHalfFloat(b[k+3]),k+=4;return _},a._GetFloatAsUIntRGBAArrayBuffer=function(i,e,o,s,c,d){for(var _=new Uint8Array(s),b=new Float32Array(c,o),k=0,j=0;j<e;j++)for(var $=0;$<i;$++){var _e=($+j*i)*4;_[k]=Scalar.Clamp(b[_e])*255,_[k+1]=Scalar.Clamp(b[_e+1])*255,_[k+2]=Scalar.Clamp(b[_e+2])*255,a.StoreLODInAlphaChannel?_[k+3]=d:_[k+3]=Scalar.Clamp(b[_e+3])*255,k+=4}return _},a._GetHalfFloatAsUIntRGBAArrayBuffer=function(i,e,o,s,c,d){for(var _=new Uint8Array(s),b=new Uint16Array(c,o),k=0,j=0;j<e;j++)for(var $=0;$<i;$++){var _e=($+j*i)*4;_[k]=Scalar.Clamp(FromHalfFloat(b[_e]))*255,_[k+1]=Scalar.Clamp(FromHalfFloat(b[_e+1]))*255,_[k+2]=Scalar.Clamp(FromHalfFloat(b[_e+2]))*255,a.StoreLODInAlphaChannel?_[k+3]=d:_[k+3]=Scalar.Clamp(FromHalfFloat(b[_e+3]))*255,k+=4}return _},a._GetRGBAArrayBuffer=function(i,e,o,s,c,d,_,b,k){for(var j=new Uint8Array(s),$=new Uint8Array(c,o),_e=0,et=0;et<e;et++)for(var tt=0;tt<i;tt++){var rt=(tt+et*i)*4;j[_e]=$[rt+d],j[_e+1]=$[rt+_],j[_e+2]=$[rt+b],j[_e+3]=$[rt+k],_e+=4}return j},a._ExtractLongWordOrder=function(i){return i===0||i===255||i===-16777216?0:1+a._ExtractLongWordOrder(i>>8)},a._GetRGBArrayBuffer=function(i,e,o,s,c,d,_,b){for(var k=new Uint8Array(s),j=new Uint8Array(c,o),$=0,_e=0;_e<e;_e++)for(var et=0;et<i;et++){var tt=(et+_e*i)*3;k[$]=j[tt+d],k[$+1]=j[tt+_],k[$+2]=j[tt+b],$+=3}return k},a._GetLuminanceArrayBuffer=function(i,e,o,s,c){for(var d=new Uint8Array(s),_=new Uint8Array(c,o),b=0,k=0;k<e;k++)for(var j=0;j<i;j++){var $=j+k*i;d[b]=_[$],b++}return d},a.UploadDDSLevels=function(i,e,o,s,c,d,_,b,k){_===void 0&&(_=-1),k===void 0&&(k=!0);var j=null;s.sphericalPolynomial&&(j=new Array);var $=!!i.getCaps().s3tc;e.generateMipMaps=c;var _e=new Int32Array(o.buffer,o.byteOffset,headerLengthInt),et,tt,rt,it=0,nt,ot,at,st,ut=0,ft=1;if(_e[off_magic]!==DDS_MAGIC){Logger$2.Error("Invalid magic number in DDS header");return}if(!s.isFourCC&&!s.isRGB&&!s.isLuminance){Logger$2.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");return}if(s.isCompressed&&!$){Logger$2.Error("Compressed textures are not supported on this platform.");return}var lt=_e[off_RGBbpp];nt=_e[off_size]+4;var ht=!1;if(s.isFourCC)switch(et=_e[off_pfFourCC],et){case FOURCC_DXT1:ft=8,ut=33777;break;case FOURCC_DXT3:ft=16,ut=33778;break;case FOURCC_DXT5:ft=16,ut=33779;break;case FOURCC_D3DFMT_R16G16B16A16F:ht=!0;break;case FOURCC_D3DFMT_R32G32B32A32F:ht=!0;break;case FOURCC_DX10:nt+=5*4;var pt=!1;switch(s.dxgiFormat){case DXGI_FORMAT_R16G16B16A16_FLOAT:case DXGI_FORMAT_R32G32B32A32_FLOAT:ht=!0,pt=!0;break;case DXGI_FORMAT_B8G8R8X8_UNORM:s.isRGB=!0,s.isFourCC=!1,lt=32,pt=!0;break}if(pt)break;default:console.error("Unsupported FourCC code:",Int32ToFourCC(et));return}var mt=a._ExtractLongWordOrder(_e[off_RMask]),dt=a._ExtractLongWordOrder(_e[off_GMask]),gt=a._ExtractLongWordOrder(_e[off_BMask]),_t=a._ExtractLongWordOrder(_e[off_AMask]);ht&&(ut=i._getRGBABufferInternalSizedFormat(s.textureType)),at=1,_e[off_flags]&DDSD_MIPMAPCOUNT&&c!==!1&&(at=Math.max(1,_e[off_mipmapCount]));for(var yt=b||0,Tt=i.getCaps(),St=yt;St<d;St++){for(tt=_e[off_width],rt=_e[off_height],st=0;st<at;++st){if(_===-1||_===st){var At=_===-1?st:0;if(!s.isCompressed&&s.isFourCC){e.format=5,it=tt*rt*4;var vt=null;if(i._badOS||i._badDesktopOS||!Tt.textureHalfFloat&&!Tt.textureFloat)lt===128?(vt=a._GetFloatAsUIntRGBAArrayBuffer(tt,rt,o.byteOffset+nt,it,o.buffer,At),j&&At==0&&j.push(a._GetFloatRGBAArrayBuffer(tt,rt,o.byteOffset+nt,it,o.buffer,At))):lt===64&&(vt=a._GetHalfFloatAsUIntRGBAArrayBuffer(tt,rt,o.byteOffset+nt,it,o.buffer,At),j&&At==0&&j.push(a._GetHalfFloatAsFloatRGBAArrayBuffer(tt,rt,o.byteOffset+nt,it,o.buffer,At))),e.type=0;else{var Et=Tt.textureFloat&&(k&&Tt.textureFloatLinearFiltering||!k),xt=Tt.textureHalfFloat&&(k&&Tt.textureHalfFloatLinearFiltering||!k),bt=(lt===128||lt===64&&!xt)&&Et?1:(lt===64||lt===128&&!Et)&&xt?2:0,Mt=void 0,Rt=null;switch(lt){case 128:{switch(bt){case 1:Mt=a._GetFloatRGBAArrayBuffer,Rt=null;break;case 2:Mt=a._GetFloatAsHalfFloatRGBAArrayBuffer,Rt=a._GetFloatRGBAArrayBuffer;break;case 0:Mt=a._GetFloatAsUIntRGBAArrayBuffer,Rt=a._GetFloatRGBAArrayBuffer;break}break}default:{switch(bt){case 1:Mt=a._GetHalfFloatAsFloatRGBAArrayBuffer,Rt=null;break;case 2:Mt=a._GetHalfFloatRGBAArrayBuffer,Rt=a._GetHalfFloatAsFloatRGBAArrayBuffer;break;case 0:Mt=a._GetHalfFloatAsUIntRGBAArrayBuffer,Rt=a._GetHalfFloatAsFloatRGBAArrayBuffer;break}break}}e.type=bt,vt=Mt(tt,rt,o.byteOffset+nt,it,o.buffer,At),j&&At==0&&j.push(Rt?Rt(tt,rt,o.byteOffset+nt,it,o.buffer,At):vt)}vt&&i._uploadDataToTextureDirectly(e,vt,St,At)}else if(s.isRGB)e.type=0,lt===24?(e.format=4,it=tt*rt*3,ot=a._GetRGBArrayBuffer(tt,rt,o.byteOffset+nt,it,o.buffer,mt,dt,gt),i._uploadDataToTextureDirectly(e,ot,St,At)):(e.format=5,it=tt*rt*4,ot=a._GetRGBAArrayBuffer(tt,rt,o.byteOffset+nt,it,o.buffer,mt,dt,gt,_t),i._uploadDataToTextureDirectly(e,ot,St,At));else if(s.isLuminance){var Pt=i._getUnpackAlignement(),It=tt,Dt=Math.floor((tt+Pt-1)/Pt)*Pt;it=Dt*(rt-1)+It,ot=a._GetLuminanceArrayBuffer(tt,rt,o.byteOffset+nt,it,o.buffer),e.format=1,e.type=0,i._uploadDataToTextureDirectly(e,ot,St,At)}else it=Math.max(4,tt)/4*Math.max(4,rt)/4*ft,ot=new Uint8Array(o.buffer,o.byteOffset+nt,it),e.type=0,i._uploadCompressedDataToTextureDirectly(e,ut,tt,rt,ot,St,At)}nt+=lt?tt*rt*(lt/8):it,tt*=.5,rt*=.5,tt=Math.max(1,tt),rt=Math.max(1,rt)}if(b!==void 0)break}j&&j.length>0?s.sphericalPolynomial=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:_e[off_width],right:j[0],left:j[1],up:j[2],down:j[3],front:j[4],back:j[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0},a.StoreLODInAlphaChannel=!1,a}();ThinEngine.prototype.createPrefilteredCubeTexture=function(a,i,e,o,s,c,d,_,b){var k=this;s===void 0&&(s=null),c===void 0&&(c=null),_===void 0&&(_=null),b===void 0&&(b=!0);var j=function($){if(!$){s&&s(null);return}var _e=$.texture;if(b?$.info.sphericalPolynomial&&(_e._sphericalPolynomial=$.info.sphericalPolynomial):_e._sphericalPolynomial=new SphericalPolynomial,_e._source=InternalTextureSource.CubePrefiltered,k.getCaps().textureLOD){s&&s(_e);return}var et=3,tt=k._gl,rt=$.width;if(!!rt){for(var it=[],nt=0;nt<et;nt++){var ot=nt/(et-1),at=1-ot,st=o,ut=Scalar.Log2(rt)*e+o,ft=st+(ut-st)*at,lt=Math.round(Math.min(Math.max(ft,0),ut)),ht=new InternalTexture(k,InternalTextureSource.Temp);if(ht.type=_e.type,ht.format=_e.format,ht.width=Math.pow(2,Math.max(Scalar.Log2(rt)-lt,0)),ht.height=ht.width,ht.isCube=!0,ht._cachedWrapU=0,ht._cachedWrapV=0,k._bindTextureDirectly(tt.TEXTURE_CUBE_MAP,ht,!0),ht.samplingMode=2,tt.texParameteri(tt.TEXTURE_CUBE_MAP,tt.TEXTURE_MAG_FILTER,tt.LINEAR),tt.texParameteri(tt.TEXTURE_CUBE_MAP,tt.TEXTURE_MIN_FILTER,tt.LINEAR),tt.texParameteri(tt.TEXTURE_CUBE_MAP,tt.TEXTURE_WRAP_S,tt.CLAMP_TO_EDGE),tt.texParameteri(tt.TEXTURE_CUBE_MAP,tt.TEXTURE_WRAP_T,tt.CLAMP_TO_EDGE),$.isDDS){var pt=$.info,mt=$.data;k._unpackFlipY(pt.isCompressed),DDSTools.UploadDDSLevels(k,ht,mt,pt,!0,6,lt)}else Logger$2.Warn("DDS is the only prefiltered cube map supported so far.");k._bindTextureDirectly(tt.TEXTURE_CUBE_MAP,null);var dt=new BaseTexture(i);dt.isCube=!0,dt._texture=ht,ht.isReady=!0,it.push(dt)}_e._lodTextureHigh=it[2],_e._lodTextureMid=it[1],_e._lodTextureLow=it[0],s&&s(_e)}};return this.createCubeTexture(a,i,null,!1,j,c,d,_,b,e,o)};var _DDSTextureLoader=function(){function a(){this.supportCascades=!0}return a.prototype.canLoad=function(i){return EndsWith(i,".dds")},a.prototype.loadCubeData=function(i,e,o,s,c){var d=e.getEngine(),_,b=!1;if(Array.isArray(i))for(var k=0;k<i.length;k++){var j=i[k];_=DDSTools.GetDDSInfo(j),e.width=_.width,e.height=_.height,b=(_.isRGB||_.isLuminance||_.mipmapCount>1)&&e.generateMipMaps,d._unpackFlipY(_.isCompressed),DDSTools.UploadDDSLevels(d,e,j,_,b,6,-1,k),!_.isFourCC&&_.mipmapCount===1&&d.generateMipMapsForCubemap(e)}else{var $=i;_=DDSTools.GetDDSInfo($),e.width=_.width,e.height=_.height,o&&(_.sphericalPolynomial=new SphericalPolynomial),b=(_.isRGB||_.isLuminance||_.mipmapCount>1)&&e.generateMipMaps,d._unpackFlipY(_.isCompressed),DDSTools.UploadDDSLevels(d,e,$,_,b,6),!_.isFourCC&&_.mipmapCount===1&&d.generateMipMapsForCubemap(e,!1)}d._setCubeMapTextureParams(e,b),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s({isDDS:!0,width:e.width,info:_,data:i,texture:e})},a.prototype.loadData=function(i,e,o){var s=DDSTools.GetDDSInfo(i),c=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&e.generateMipMaps&&s.width>>s.mipmapCount-1===1;o(s.width,s.height,c,s.isFourCC,function(){DDSTools.UploadDDSLevels(e.getEngine(),e,i,s,c,1)})},a}();Engine._TextureLoaders.push(new _DDSTextureLoader);var MirrorTexture=function(a){__extends(i,a);function i(e,o,s,c,d,_,b){d===void 0&&(d=0),_===void 0&&(_=Texture.BILINEAR_SAMPLINGMODE),b===void 0&&(b=!0);var k=a.call(this,e,o,s,c,!0,d,!1,_,b)||this;k.scene=s,k.mirrorPlane=new Plane(0,1,0,1),k._transformMatrix=Matrix.Zero(),k._mirrorMatrix=Matrix.Zero(),k._adaptiveBlurKernel=0,k._blurKernelX=0,k._blurKernelY=0,k._blurRatio=1,k.ignoreCameraViewport=!0,k._updateGammaSpace(),k._imageProcessingConfigChangeObserver=s.imageProcessingConfiguration.onUpdateParameters.add(function(){k._updateGammaSpace()});var j=k.getScene().getEngine();j.supportsUniformBuffers&&(k._sceneUBO=s.createSceneUniformBuffer('Scene for Mirror Texture (name "'+e+'")')),k.onBeforeBindObservable.add(function(){var _e;(_e=j._debugPushGroup)===null||_e===void 0||_e.call(j,"mirror generation for "+e,1)}),k.onAfterUnbindObservable.add(function(){var _e;(_e=j._debugPopGroup)===null||_e===void 0||_e.call(j,1)});var $;return k.onBeforeRenderObservable.add(function(){k._sceneUBO&&(k._currentSceneUBO=s.getSceneUniformBuffer(),s.setSceneUniformBuffer(k._sceneUBO),s.getSceneUniformBuffer().unbindEffect()),Matrix.ReflectionToRef(k.mirrorPlane,k._mirrorMatrix),k._mirrorMatrix.multiplyToRef(s.getViewMatrix(),k._transformMatrix),s.setTransformMatrix(k._transformMatrix,s.getProjectionMatrix()),$=s.clipPlane,s.clipPlane=k.mirrorPlane,s.getEngine().cullBackFaces=!1,s._mirroredCameraPosition=Vector3.TransformCoordinates(s.activeCamera.globalPosition,k._mirrorMatrix)}),k.onAfterRenderObservable.add(function(){k._sceneUBO&&s.setSceneUniformBuffer(k._currentSceneUBO),s.updateTransformMatrix(),s.getEngine().cullBackFaces=null,s._mirroredCameraPosition=null,s.clipPlane=$}),k}return Object.defineProperty(i.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),i.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),o=this.getRenderWidth()/e.getRenderWidth(),s=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*o,this.blurKernelY=this._adaptiveBlurKernel*s},i.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},i.prototype._updateGammaSpace=function(){this.gammaSpace=!this.scene.imageProcessingConfiguration.isEnabled||!this.scene.imageProcessingConfiguration.applyByPostProcess},i.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var e=this.getScene().getEngine(),o=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new BlurPostProcess("horizontal blur",new Vector2(1,0),this._blurKernelX,this._blurRatio,null,Texture.BILINEAR_SAMPLINGMODE,e,!1,o),this._blurX.autoClear=!1,this._blurRatio===1&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new BlurPostProcess("vertical blur",new Vector2(0,1),this._blurKernelY,this._blurRatio,null,Texture.BILINEAR_SAMPLINGMODE,e,!1,o),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=this._blurRatio!==1,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},i.prototype.clone=function(){var e=this.getScene();if(!e)return this;var o=this.getSize(),s=new i(this.name,o.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return s.hasAlpha=this.hasAlpha,s.level=this.level,s.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(s.renderList=this.renderList.slice(0)),s},i.prototype.serialize=function(){if(!this.name)return null;var e=a.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i.prototype.dispose=function(){var e;a.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),(e=this._sceneUBO)===null||e===void 0||e.dispose()},i}(RenderTargetTexture);Texture._CreateMirror=function(a,i,e,o){return new MirrorTexture(a,i,e,o)};var name$7="backgroundFragmentDeclaration",shader$7=` uniform vec4 vEyePosition;
  10450. uniform vec4 vPrimaryColor;
  10451. #ifdef USEHIGHLIGHTANDSHADOWCOLORS
  10452. uniform vec4 vPrimaryColorShadow;
  10453. #endif
  10454. uniform float shadowLevel;
  10455. uniform float alpha;
  10456. #ifdef DIFFUSE
  10457. uniform vec2 vDiffuseInfos;
  10458. #endif
  10459. #ifdef REFLECTION
  10460. uniform vec2 vReflectionInfos;
  10461. uniform mat4 reflectionMatrix;
  10462. uniform vec3 vReflectionMicrosurfaceInfos;
  10463. #endif
  10464. #if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)
  10465. uniform vec3 vBackgroundCenter;
  10466. #endif
  10467. #ifdef REFLECTIONFRESNEL
  10468. uniform vec4 vReflectionControl;
  10469. #endif
  10470. #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)
  10471. uniform mat4 view;
  10472. #endif`;ShaderStore.IncludesShadersStore[name$7]=shader$7;var name$6="backgroundUboDeclaration",shader$6=`layout(std140,column_major) uniform;
  10473. uniform Material
  10474. {
  10475. uniform vec4 vPrimaryColor;
  10476. uniform vec4 vPrimaryColorShadow;
  10477. uniform vec2 vDiffuseInfos;
  10478. uniform vec2 vReflectionInfos;
  10479. uniform mat4 diffuseMatrix;
  10480. uniform mat4 reflectionMatrix;
  10481. uniform vec3 vReflectionMicrosurfaceInfos;
  10482. uniform float fFovMultiplier;
  10483. uniform float pointSize;
  10484. uniform float shadowLevel;
  10485. uniform float alpha;
  10486. #if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)
  10487. uniform vec3 vBackgroundCenter;
  10488. #endif
  10489. #ifdef REFLECTIONFRESNEL
  10490. uniform vec4 vReflectionControl;
  10491. #endif
  10492. };
  10493. #include<sceneUboDeclaration>
  10494. `;ShaderStore.IncludesShadersStore[name$6]=shader$6;var name$5="backgroundPixelShader",shader$5=`#ifdef TEXTURELODSUPPORT
  10495. #extension GL_EXT_shader_texture_lod : enable
  10496. #endif
  10497. precision highp float;
  10498. #include<__decl__backgroundFragment>
  10499. #include<helperFunctions>
  10500. #define RECIPROCAL_PI2 0.15915494
  10501. varying vec3 vPositionW;
  10502. #ifdef MAINUV1
  10503. varying vec2 vMainUV1;
  10504. #endif
  10505. #ifdef MAINUV2
  10506. varying vec2 vMainUV2;
  10507. #endif
  10508. #ifdef NORMAL
  10509. varying vec3 vNormalW;
  10510. #endif
  10511. #ifdef DIFFUSE
  10512. #if DIFFUSEDIRECTUV == 1
  10513. #define vDiffuseUV vMainUV1
  10514. #elif DIFFUSEDIRECTUV == 2
  10515. #define vDiffuseUV vMainUV2
  10516. #else
  10517. varying vec2 vDiffuseUV;
  10518. #endif
  10519. uniform sampler2D diffuseSampler;
  10520. #endif
  10521. #ifdef REFLECTION
  10522. #ifdef REFLECTIONMAP_3D
  10523. #define sampleReflection(s,c) textureCube(s,c)
  10524. uniform samplerCube reflectionSampler;
  10525. #ifdef TEXTURELODSUPPORT
  10526. #define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
  10527. #else
  10528. uniform samplerCube reflectionSamplerLow;
  10529. uniform samplerCube reflectionSamplerHigh;
  10530. #endif
  10531. #else
  10532. #define sampleReflection(s,c) texture2D(s,c)
  10533. uniform sampler2D reflectionSampler;
  10534. #ifdef TEXTURELODSUPPORT
  10535. #define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
  10536. #else
  10537. uniform samplerCube reflectionSamplerLow;
  10538. uniform samplerCube reflectionSamplerHigh;
  10539. #endif
  10540. #endif
  10541. #ifdef REFLECTIONMAP_SKYBOX
  10542. varying vec3 vPositionUVW;
  10543. #else
  10544. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  10545. varying vec3 vDirectionW;
  10546. #endif
  10547. #endif
  10548. #include<reflectionFunction>
  10549. #endif
  10550. #ifndef FROMLINEARSPACE
  10551. #define FROMLINEARSPACE;
  10552. #endif
  10553. #ifndef SHADOWONLY
  10554. #define SHADOWONLY;
  10555. #endif
  10556. #include<imageProcessingDeclaration>
  10557. #include<__decl__lightFragment>[0..maxSimultaneousLights]
  10558. #include<lightsFragmentFunctions>
  10559. #include<shadowsFragmentFunctions>
  10560. #include<imageProcessingFunctions>
  10561. #include<clipPlaneFragmentDeclaration>
  10562. #include<fogFragmentDeclaration>
  10563. #ifdef REFLECTIONFRESNEL
  10564. #define FRESNEL_MAXIMUM_ON_ROUGH 0.25
  10565. vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
  10566. {
  10567. float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);
  10568. return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));
  10569. }
  10570. #endif
  10571. void main(void) {
  10572. #include<clipPlaneFragment>
  10573. vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
  10574. #ifdef NORMAL
  10575. vec3 normalW=normalize(vNormalW);
  10576. #else
  10577. vec3 normalW=vec3(0.0,1.0,0.0);
  10578. #endif
  10579. float shadow=1.;
  10580. float globalShadow=0.;
  10581. float shadowLightCount=0.;
  10582. #include<lightFragment>[0..maxSimultaneousLights]
  10583. #ifdef SHADOWINUSE
  10584. globalShadow/=shadowLightCount;
  10585. #else
  10586. globalShadow=1.0;
  10587. #endif
  10588. #ifndef BACKMAT_SHADOWONLY
  10589. vec4 reflectionColor=vec4(1.,1.,1.,1.);
  10590. #ifdef REFLECTION
  10591. vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
  10592. #ifdef REFLECTIONMAP_OPPOSITEZ
  10593. reflectionVector.z*=-1.0;
  10594. #endif
  10595. #ifdef REFLECTIONMAP_3D
  10596. vec3 reflectionCoords=reflectionVector;
  10597. #else
  10598. vec2 reflectionCoords=reflectionVector.xy;
  10599. #ifdef REFLECTIONMAP_PROJECTION
  10600. reflectionCoords/=reflectionVector.z;
  10601. #endif
  10602. reflectionCoords.y=1.0-reflectionCoords.y;
  10603. #endif
  10604. #ifdef REFLECTIONBLUR
  10605. float reflectionLOD=vReflectionInfos.y;
  10606. #ifdef TEXTURELODSUPPORT
  10607. reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
  10608. reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
  10609. #else
  10610. float lodReflectionNormalized=saturate(reflectionLOD);
  10611. float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;
  10612. vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);
  10613. if(lodReflectionNormalizedDoubled<1.0){
  10614. reflectionColor=mix(
  10615. sampleReflection(reflectionSamplerHigh,reflectionCoords),
  10616. reflectionSpecularMid,
  10617. lodReflectionNormalizedDoubled
  10618. );
  10619. } else {
  10620. reflectionColor=mix(
  10621. reflectionSpecularMid,
  10622. sampleReflection(reflectionSamplerLow,reflectionCoords),
  10623. lodReflectionNormalizedDoubled-1.0
  10624. );
  10625. }
  10626. #endif
  10627. #else
  10628. vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);
  10629. reflectionColor=reflectionSample;
  10630. #endif
  10631. #ifdef RGBDREFLECTION
  10632. reflectionColor.rgb=fromRGBD(reflectionColor);
  10633. #endif
  10634. #ifdef GAMMAREFLECTION
  10635. reflectionColor.rgb=toLinearSpace(reflectionColor.rgb);
  10636. #endif
  10637. #ifdef REFLECTIONBGR
  10638. reflectionColor.rgb=reflectionColor.bgr;
  10639. #endif
  10640. reflectionColor.rgb*=vReflectionInfos.x;
  10641. #endif
  10642. vec3 diffuseColor=vec3(1.,1.,1.);
  10643. float finalAlpha=alpha;
  10644. #ifdef DIFFUSE
  10645. vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);
  10646. #ifdef GAMMADIFFUSE
  10647. diffuseMap.rgb=toLinearSpace(diffuseMap.rgb);
  10648. #endif
  10649. diffuseMap.rgb*=vDiffuseInfos.y;
  10650. #ifdef DIFFUSEHASALPHA
  10651. finalAlpha*=diffuseMap.a;
  10652. #endif
  10653. diffuseColor=diffuseMap.rgb;
  10654. #endif
  10655. #ifdef REFLECTIONFRESNEL
  10656. vec3 colorBase=diffuseColor;
  10657. #else
  10658. vec3 colorBase=reflectionColor.rgb*diffuseColor;
  10659. #endif
  10660. colorBase=max(colorBase,0.0);
  10661. #ifdef USERGBCOLOR
  10662. vec3 finalColor=colorBase;
  10663. #else
  10664. #ifdef USEHIGHLIGHTANDSHADOWCOLORS
  10665. vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);
  10666. #else
  10667. vec3 mainColor=vPrimaryColor.rgb;
  10668. #endif
  10669. vec3 finalColor=colorBase*mainColor;
  10670. #endif
  10671. #ifdef REFLECTIONFRESNEL
  10672. vec3 reflectionAmount=vReflectionControl.xxx;
  10673. vec3 reflectionReflectance0=vReflectionControl.yyy;
  10674. vec3 reflectionReflectance90=vReflectionControl.zzz;
  10675. float VdotN=dot(normalize(vEyePosition.xyz),normalW);
  10676. vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);
  10677. reflectionAmount*=planarReflectionFresnel;
  10678. #ifdef REFLECTIONFALLOFF
  10679. float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);
  10680. reflectionDistanceFalloff*=reflectionDistanceFalloff;
  10681. reflectionAmount*=reflectionDistanceFalloff;
  10682. #endif
  10683. finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));
  10684. #endif
  10685. #ifdef OPACITYFRESNEL
  10686. float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));
  10687. const float startAngle=0.1;
  10688. float fadeFactor=saturate(viewAngleToFloor/startAngle);
  10689. finalAlpha*=fadeFactor*fadeFactor;
  10690. #endif
  10691. #ifdef SHADOWINUSE
  10692. finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);
  10693. #endif
  10694. vec4 color=vec4(finalColor,finalAlpha);
  10695. #else
  10696. vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);
  10697. #endif
  10698. #include<fogFragment>
  10699. #ifdef IMAGEPROCESSINGPOSTPROCESS
  10700. #if !defined(SKIPFINALCOLORCLAMP)
  10701. color.rgb=clamp(color.rgb,0.,30.0);
  10702. #endif
  10703. #else
  10704. color=applyImageProcessing(color);
  10705. #endif
  10706. #ifdef PREMULTIPLYALPHA
  10707. color.rgb*=color.a;
  10708. #endif
  10709. #ifdef NOISE
  10710. color.rgb+=dither(vPositionW.xy,0.5);
  10711. color=max(color,0.0);
  10712. #endif
  10713. gl_FragColor=color;
  10714. }
  10715. `;ShaderStore.ShadersStore[name$5]=shader$5;var name$4="backgroundVertexDeclaration",shader$4=`uniform mat4 view;
  10716. uniform mat4 viewProjection;
  10717. uniform float shadowLevel;
  10718. #ifdef DIFFUSE
  10719. uniform mat4 diffuseMatrix;
  10720. uniform vec2 vDiffuseInfos;
  10721. #endif
  10722. #ifdef REFLECTION
  10723. uniform vec2 vReflectionInfos;
  10724. uniform mat4 reflectionMatrix;
  10725. uniform vec3 vReflectionMicrosurfaceInfos;
  10726. uniform float fFovMultiplier;
  10727. #endif
  10728. #ifdef POINTSIZE
  10729. uniform float pointSize;
  10730. #endif`;ShaderStore.IncludesShadersStore[name$4]=shader$4;var name$3="backgroundVertexShader",shader$3=`precision highp float;
  10731. #include<__decl__backgroundVertex>
  10732. #include<helperFunctions>
  10733. attribute vec3 position;
  10734. #ifdef NORMAL
  10735. attribute vec3 normal;
  10736. #endif
  10737. #include<bonesDeclaration>
  10738. #include<bakedVertexAnimationDeclaration>
  10739. #include<instancesDeclaration>
  10740. varying vec3 vPositionW;
  10741. #ifdef NORMAL
  10742. varying vec3 vNormalW;
  10743. #endif
  10744. #ifdef UV1
  10745. attribute vec2 uv;
  10746. #endif
  10747. #ifdef UV2
  10748. attribute vec2 uv2;
  10749. #endif
  10750. #ifdef MAINUV1
  10751. varying vec2 vMainUV1;
  10752. #endif
  10753. #ifdef MAINUV2
  10754. varying vec2 vMainUV2;
  10755. #endif
  10756. #if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0
  10757. varying vec2 vDiffuseUV;
  10758. #endif
  10759. #include<clipPlaneVertexDeclaration>
  10760. #include<fogVertexDeclaration>
  10761. #include<__decl__lightVxFragment>[0..maxSimultaneousLights]
  10762. #ifdef REFLECTIONMAP_SKYBOX
  10763. varying vec3 vPositionUVW;
  10764. #endif
  10765. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  10766. varying vec3 vDirectionW;
  10767. #endif
  10768. void main(void) {
  10769. #ifdef REFLECTIONMAP_SKYBOX
  10770. vPositionUVW=position;
  10771. #endif
  10772. #include<instancesVertex>
  10773. #include<bonesVertex>
  10774. #include<bakedVertexAnimation>
  10775. #ifdef MULTIVIEW
  10776. if (gl_ViewID_OVR == 0u) {
  10777. gl_Position=viewProjection*finalWorld*vec4(position,1.0);
  10778. } else {
  10779. gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);
  10780. }
  10781. #else
  10782. gl_Position=viewProjection*finalWorld*vec4(position,1.0);
  10783. #endif
  10784. vec4 worldPos=finalWorld*vec4(position,1.0);
  10785. vPositionW=vec3(worldPos);
  10786. #ifdef NORMAL
  10787. mat3 normalWorld=mat3(finalWorld);
  10788. #ifdef NONUNIFORMSCALING
  10789. normalWorld=transposeMat3(inverseMat3(normalWorld));
  10790. #endif
  10791. vNormalW=normalize(normalWorld*normal);
  10792. #endif
  10793. #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
  10794. vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));
  10795. #ifdef EQUIRECTANGULAR_RELFECTION_FOV
  10796. mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));
  10797. vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));
  10798. if (fFovMultiplier<=1.0) {
  10799. vDirectionW=normalize(segment);
  10800. } else {
  10801. vDirectionW=normalize(vDirectionW+(vDirectionW-segment));
  10802. }
  10803. #endif
  10804. #endif
  10805. #ifndef UV1
  10806. vec2 uv=vec2(0.,0.);
  10807. #endif
  10808. #ifndef UV2
  10809. vec2 uv2=vec2(0.,0.);
  10810. #endif
  10811. #ifdef MAINUV1
  10812. vMainUV1=uv;
  10813. #endif
  10814. #ifdef MAINUV2
  10815. vMainUV2=uv2;
  10816. #endif
  10817. #if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0
  10818. if (vDiffuseInfos.x == 0.)
  10819. {
  10820. vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));
  10821. }
  10822. else
  10823. {
  10824. vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
  10825. }
  10826. #endif
  10827. #include<clipPlaneVertex>
  10828. #include<fogVertex>
  10829. #include<shadowsVertex>[0..maxSimultaneousLights]
  10830. #ifdef VERTEXCOLOR
  10831. vColor=color;
  10832. #endif
  10833. #ifdef POINTSIZE
  10834. gl_PointSize=pointSize;
  10835. #endif
  10836. }
  10837. `;ShaderStore.ShadersStore[name$3]=shader$3;var BackgroundMaterialDefines=function(a){__extends(i,a);function i(){var e=a.call(this)||this;return e.DIFFUSE=!1,e.DIFFUSEDIRECTUV=0,e.GAMMADIFFUSE=!1,e.DIFFUSEHASALPHA=!1,e.OPACITYFRESNEL=!1,e.REFLECTIONBLUR=!1,e.REFLECTIONFRESNEL=!1,e.REFLECTIONFALLOFF=!1,e.TEXTURELODSUPPORT=!1,e.PREMULTIPLYALPHA=!1,e.USERGBCOLOR=!1,e.USEHIGHLIGHTANDSHADOWCOLORS=!1,e.BACKMAT_SHADOWONLY=!1,e.NOISE=!1,e.REFLECTIONBGR=!1,e.IMAGEPROCESSING=!1,e.VIGNETTE=!1,e.VIGNETTEBLENDMODEMULTIPLY=!1,e.VIGNETTEBLENDMODEOPAQUE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=!1,e.SAMPLER3DBGRMAP=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.SKIPFINALCOLORCLAMP=!1,e.EXPOSURE=!1,e.MULTIVIEW=!1,e.REFLECTION=!1,e.REFLECTIONMAP_3D=!1,e.REFLECTIONMAP_SPHERICAL=!1,e.REFLECTIONMAP_PLANAR=!1,e.REFLECTIONMAP_CUBIC=!1,e.REFLECTIONMAP_PROJECTION=!1,e.REFLECTIONMAP_SKYBOX=!1,e.REFLECTIONMAP_EXPLICIT=!1,e.REFLECTIONMAP_EQUIRECTANGULAR=!1,e.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,e.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.INVERTCUBICMAP=!1,e.REFLECTIONMAP_OPPOSITEZ=!1,e.LODINREFLECTIONALPHA=!1,e.GAMMAREFLECTION=!1,e.RGBDREFLECTION=!1,e.EQUIRECTANGULAR_RELFECTION_FOV=!1,e.MAINUV1=!1,e.MAINUV2=!1,e.UV1=!1,e.UV2=!1,e.CLIPPLANE=!1,e.CLIPPLANE2=!1,e.CLIPPLANE3=!1,e.CLIPPLANE4=!1,e.CLIPPLANE5=!1,e.CLIPPLANE6=!1,e.POINTSIZE=!1,e.FOG=!1,e.NORMAL=!1,e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.INSTANCES=!1,e.SHADOWFLOAT=!1,e.LOGARITHMICDEPTH=!1,e.NONUNIFORMSCALING=!1,e.ALPHATEST=!1,e.rebuild(),e}return i}(MaterialDefines),BackgroundMaterial=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e,o)||this;return s.primaryColor=Color3.White(),s._primaryColorShadowLevel=0,s._primaryColorHighlightLevel=0,s.reflectionTexture=null,s.reflectionBlur=0,s.diffuseTexture=null,s._shadowLights=null,s.shadowLights=null,s.shadowLevel=0,s.sceneCenter=Vector3.Zero(),s.opacityFresnel=!0,s.reflectionFresnel=!1,s.reflectionFalloffDistance=0,s.reflectionAmount=1,s.reflectionReflectance0=.05,s.reflectionReflectance90=.5,s.useRGBColor=!0,s.enableNoise=!1,s._fovMultiplier=1,s.useEquirectangularFOV=!1,s._maxSimultaneousLights=4,s.maxSimultaneousLights=4,s._shadowOnly=!1,s.shadowOnly=!1,s._imageProcessingObserver=null,s.switchToBGR=!1,s._renderTargets=new SmartArray(16),s._reflectionControls=Vector4.Zero(),s._white=Color3.White(),s._primaryShadowColor=Color3.Black(),s._primaryHighlightColor=Color3.Black(),s._attachImageProcessingConfiguration(null),s.getRenderTargetTextures=function(){return s._renderTargets.reset(),s._diffuseTexture&&s._diffuseTexture.isRenderTarget&&s._renderTargets.push(s._diffuseTexture),s._reflectionTexture&&s._reflectionTexture.isRenderTarget&&s._renderTargets.push(s._reflectionTexture),s._renderTargets},s}return Object.defineProperty(i.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"reflectionStandardFresnelWeight",{set:function(e){var o=e;o<.5?(o=o*2,this.reflectionReflectance0=i.StandardReflectance0*o,this.reflectionReflectance90=i.StandardReflectance90*o):(o=o*2-1,this.reflectionReflectance0=i.StandardReflectance0+(1-i.StandardReflectance0)*o,this.reflectionReflectance90=i.StandardReflectance90+(1-i.StandardReflectance90)*o)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!1,configurable:!0}),i.prototype._attachImageProcessingConfiguration=function(e){var o=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){o._computePrimaryColorFromPerceptualColor(),o._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(i.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"hasRenderTargetTextures",{get:function(){return!!(this._diffuseTexture&&this._diffuseTexture.isRenderTarget||this._reflectionTexture&&this._reflectionTexture.isRenderTarget)},enumerable:!1,configurable:!0}),i.prototype.needAlphaTesting=function(){return!0},i.prototype.needAlphaBlending=function(){return this.alpha<1||this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._shadowOnly},i.prototype.isReadyForSubMesh=function(e,o,s){if(s===void 0&&(s=!1),o.effect&&this.isFrozen&&o.effect._wasPreviouslyReady)return!0;o.materialDefines||(o.materialDefines=new BackgroundMaterialDefines);var c=this.getScene(),d=o.materialDefines;if(this._isReadyForSubMesh(o))return!0;var _=c.getEngine();if(MaterialHelper.PrepareDefinesForLights(c,e,d,!1,this._maxSimultaneousLights),d._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(c,d),d._areTexturesDirty){if(d._needUVs=!1,c.texturesEnabled){if(c.getEngine().getCaps().textureLOD&&(d.TEXTURELODSUPPORT=!0),this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,d,"DIFFUSE"),d.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,d.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,d.OPACITYFRESNEL=this._opacityFresnel}else d.DIFFUSE=!1,d.DIFFUSEHASALPHA=!1,d.GAMMADIFFUSE=!1,d.OPACITYFRESNEL=!1;var b=this._reflectionTexture;if(b&&MaterialFlags.ReflectionTextureEnabled){if(!b.isReadyOrNotBlocking())return!1;switch(d.REFLECTION=!0,d.GAMMAREFLECTION=b.gammaSpace,d.RGBDREFLECTION=b.isRGBD,d.REFLECTIONBLUR=this._reflectionBlur>0,d.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!b.invertZ:b.invertZ,d.LODINREFLECTIONALPHA=b.lodLevelInAlpha,d.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,d.REFLECTIONBGR=this.switchToBGR,b.coordinatesMode===Texture.INVCUBIC_MODE&&(d.INVERTCUBICMAP=!0),d.REFLECTIONMAP_3D=b.isCube,b.coordinatesMode){case Texture.EXPLICIT_MODE:d.REFLECTIONMAP_EXPLICIT=!0;break;case Texture.PLANAR_MODE:d.REFLECTIONMAP_PLANAR=!0;break;case Texture.PROJECTION_MODE:d.REFLECTIONMAP_PROJECTION=!0;break;case Texture.SKYBOX_MODE:d.REFLECTIONMAP_SKYBOX=!0;break;case Texture.SPHERICAL_MODE:d.REFLECTIONMAP_SPHERICAL=!0;break;case Texture.EQUIRECTANGULAR_MODE:d.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Texture.FIXED_EQUIRECTANGULAR_MODE:d.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:d.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Texture.CUBIC_MODE:case Texture.INVCUBIC_MODE:default:d.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(d.REFLECTIONFRESNEL=!0,d.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(d.REFLECTIONFRESNEL=!1,d.REFLECTIONFALLOFF=!1)}else d.REFLECTION=!1,d.REFLECTIONFRESNEL=!1,d.REFLECTIONFALLOFF=!1,d.REFLECTIONBLUR=!1,d.REFLECTIONMAP_3D=!1,d.REFLECTIONMAP_SPHERICAL=!1,d.REFLECTIONMAP_PLANAR=!1,d.REFLECTIONMAP_CUBIC=!1,d.REFLECTIONMAP_PROJECTION=!1,d.REFLECTIONMAP_SKYBOX=!1,d.REFLECTIONMAP_EXPLICIT=!1,d.REFLECTIONMAP_EQUIRECTANGULAR=!1,d.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,d.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,d.INVERTCUBICMAP=!1,d.REFLECTIONMAP_OPPOSITEZ=!1,d.LODINREFLECTIONALPHA=!1,d.GAMMAREFLECTION=!1,d.RGBDREFLECTION=!1}d.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,d.USERGBCOLOR=this._useRGBColor,d.NOISE=this._enableNoise}if(d._areLightsDirty&&(d.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),d.BACKMAT_SHADOWONLY=this._shadowOnly),d._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(d)}if(MaterialHelper.PrepareDefinesForMisc(e,c,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),d),MaterialHelper.PrepareDefinesForFrameBoundValues(c,_,d,s,null,o.getRenderingMesh().hasThinInstances),MaterialHelper.PrepareDefinesForAttributes(e,d,!1,!0,!1)&&e&&!c.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(VertexBuffer.NormalKind)&&(e.createNormals(!0),Logger$2.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),d.isDirty){d.markAsProcessed(),c.resetCachedMaterial();var k=new EffectFallbacks;d.FOG&&k.addFallback(0,"FOG"),d.POINTSIZE&&k.addFallback(1,"POINTSIZE"),d.MULTIVIEW&&k.addFallback(0,"MULTIVIEW"),MaterialHelper.HandleFallbacksForShadows(d,k,this._maxSimultaneousLights);var j=[VertexBuffer.PositionKind];d.NORMAL&&j.push(VertexBuffer.NormalKind),d.UV1&&j.push(VertexBuffer.UVKind),d.UV2&&j.push(VertexBuffer.UV2Kind),MaterialHelper.PrepareAttributesForBones(j,e,d,k),MaterialHelper.PrepareAttributesForInstances(j,d);var $=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],_e=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],et=["Material","Scene"];ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms($,d),ImageProcessingConfiguration.PrepareSamplers(_e,d)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:$,uniformBuffersNames:et,samplers:_e,defines:d,maxSimultaneousLights:this._maxSimultaneousLights});var tt=d.toString(),rt=c.getEngine().createEffect("background",{attributes:j,uniformsNames:$,uniformBuffersNames:et,samplers:_e,defines:tt,fallbacks:k,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},_);o.setEffect(rt,d,this._materialContext),this.buildUniformLayout()}return!o.effect||!o.effect.isReady()?!1:(d._renderId=c.getRenderId(),o.effect._wasPreviouslyReady=!0,!0)},i.prototype._computePrimaryColorFromPerceptualColor=function(){!this.__perceptualColor||(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},i.prototype._computePrimaryColors=function(){this._primaryColorShadowLevel===0&&this._primaryColorHighlightLevel===0||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},i.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()},i.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),a.prototype.unbind.call(this)},i.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},i.prototype.bindForSubMesh=function(e,o,s){var c=this.getScene(),d=s.materialDefines;if(!!d){var _=s.effect;if(!!_){this._activeEffect=_,this.bindOnlyWorldMatrix(e),MaterialHelper.BindBonesParameters(o,this._activeEffect);var b=this._mustRebind(c,_,o.visibility);if(b){this._uniformBuffer.bindToEffect(_,"Material"),this.bindViewProjection(_);var k=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync)&&(c.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),k&&MaterialFlags.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",k.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",k.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",k.getSize().width,k.lodGenerationScale,k.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),d.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),c.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),k&&MaterialFlags.ReflectionTextureEnabled&&(d.REFLECTIONBLUR&&d.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",k):d.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",k._lodTextureMid||k),this._uniformBuffer.setTexture("reflectionSamplerLow",k._lodTextureLow||k),this._uniformBuffer.setTexture("reflectionSamplerHigh",k._lodTextureHigh||k)):this._uniformBuffer.setTexture("reflectionSampler",k),d.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),MaterialHelper.BindClipPlane(this._activeEffect,c),c.bindEyePosition(_)}else c.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(_,"Material"),this._needToBindSceneUbo=!0);(b||!this.isFrozen)&&(c.lightsEnabled&&MaterialHelper.BindLights(c,o,this._activeEffect,d,this._maxSimultaneousLights),this.bindView(_),MaterialHelper.BindFogParameters(c,o,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(o,this._activeEffect),this._uniformBuffer.update()}}},i.prototype.hasTexture=function(e){return!!(a.prototype.hasTexture.call(this,e)||this._reflectionTexture===e||this._diffuseTexture===e)},i.prototype.dispose=function(e,o){e===void 0&&(e=!1),o===void 0&&(o=!1),o&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),a.prototype.dispose.call(this,e)},i.prototype.clone=function(e){var o=this;return SerializationHelper.Clone(function(){return new i(e,o.getScene())},this)},i.prototype.serialize=function(){var e=SerializationHelper.Serialize(this);return e.customType="BABYLON.BackgroundMaterial",e},i.prototype.getClassName=function(){return"BackgroundMaterial"},i.Parse=function(e,o,s){return SerializationHelper.Parse(function(){return new i(e.name,o)},e,o,s)},i.StandardReflectance0=.05,i.StandardReflectance90=.5,__decorate([serializeAsColor3()],i.prototype,"_primaryColor",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"primaryColor",void 0),__decorate([serializeAsColor3()],i.prototype,"__perceptualColor",void 0),__decorate([serialize()],i.prototype,"_primaryColorShadowLevel",void 0),__decorate([serialize()],i.prototype,"_primaryColorHighlightLevel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"primaryColorHighlightLevel",null),__decorate([serializeAsTexture()],i.prototype,"_reflectionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionTexture",void 0),__decorate([serialize()],i.prototype,"_reflectionBlur",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionBlur",void 0),__decorate([serializeAsTexture()],i.prototype,"_diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"shadowLights",void 0),__decorate([serialize()],i.prototype,"_shadowLevel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"shadowLevel",void 0),__decorate([serializeAsVector3()],i.prototype,"_sceneCenter",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"sceneCenter",void 0),__decorate([serialize()],i.prototype,"_opacityFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"opacityFresnel",void 0),__decorate([serialize()],i.prototype,"_reflectionFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionFresnel",void 0),__decorate([serialize()],i.prototype,"_reflectionFalloffDistance",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionFalloffDistance",void 0),__decorate([serialize()],i.prototype,"_reflectionAmount",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionAmount",void 0),__decorate([serialize()],i.prototype,"_reflectionReflectance0",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionReflectance0",void 0),__decorate([serialize()],i.prototype,"_reflectionReflectance90",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"reflectionReflectance90",void 0),__decorate([serialize()],i.prototype,"_useRGBColor",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"useRGBColor",void 0),__decorate([serialize()],i.prototype,"_enableNoise",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"enableNoise",void 0),__decorate([serialize()],i.prototype,"_maxSimultaneousLights",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],i.prototype,"maxSimultaneousLights",void 0),__decorate([serialize()],i.prototype,"_shadowOnly",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],i.prototype,"shadowOnly",void 0),__decorate([serializeAsImageProcessingConfiguration()],i.prototype,"_imageProcessingConfiguration",void 0),i}(PushMaterial);RegisterClass("BABYLON.BackgroundMaterial",BackgroundMaterial);var EnvironmentHelper=function(){function a(i,e){var o=this;this._errorHandler=function(s,c){o.onErrorObservable.notifyObservers({message:s,exception:c})},this._options=__assign(__assign({},a._getDefaultOptions()),i),this._scene=e,this.onErrorObservable=new Observable,this._setupBackground(),this._setupImageProcessing()}return a._getDefaultOptions=function(){return{createGround:!0,groundSize:15,groundTexture:this._groundTextureCDNUrl,groundColor:new Color3(.2,.2,.3).toLinearSpace().scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._skyboxTextureCDNUrl,skyboxColor:new Color3(.2,.2,.3).toLinearSpace().scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:Vector3.Zero(),setupImageProcessing:!0,environmentTexture:this._environmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}},Object.defineProperty(a.prototype,"rootMesh",{get:function(){return this._rootMesh},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"skybox",{get:function(){return this._skybox},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"skyboxTexture",{get:function(){return this._skyboxTexture},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"skyboxMaterial",{get:function(){return this._skyboxMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"ground",{get:function(){return this._ground},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"groundTexture",{get:function(){return this._groundTexture},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"groundMirror",{get:function(){return this._groundMirror},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"groundMirrorRenderList",{get:function(){return this._groundMirror?this._groundMirror.renderList:null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"groundMaterial",{get:function(){return this._groundMaterial},enumerable:!1,configurable:!0}),a.prototype.updateOptions=function(i){var e=__assign(__assign({},this._options),i);this._ground&&!e.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!e.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=e.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!e.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!e.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=e.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!e.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=e.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=e,this._setupBackground(),this._setupImageProcessing()},a.prototype.setMainColor=function(i){this.groundMaterial&&(this.groundMaterial.primaryColor=i),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=i),this.groundMirror&&(this.groundMirror.clearColor=new Color4(i.r,i.g,i.b,1))},a.prototype._setupImageProcessing=function(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())},a.prototype._setupEnvironmentTexture=function(){if(!this._scene.environmentTexture){if(this._options.environmentTexture instanceof BaseTexture){this._scene.environmentTexture=this._options.environmentTexture;return}var i=CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=i}},a.prototype._setupBackground=function(){this._rootMesh||(this._rootMesh=new Mesh("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;var i=this._getSceneSize();this._options.createGround&&(this._setupGround(i),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(i),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(i),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=i.rootPosition.x,this._rootMesh.position.z=i.rootPosition.z,this._rootMesh.position.y=i.rootPosition.y},a.prototype._getSceneSize=function(){var i=this,e=this._options.groundSize,o=this._options.skyboxSize,s=this._options.rootPosition;if(!this._scene.meshes||this._scene.meshes.length===1)return{groundSize:e,skyboxSize:o,rootPosition:s};var c=this._scene.getWorldExtends(function(b){return b!==i._ground&&b!==i._rootMesh&&b!==i._skybox}),d=c.max.subtract(c.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof ArcRotateCamera&&this._scene.activeCamera.upperRadiusLimit&&(e=this._scene.activeCamera.upperRadiusLimit*2,o=e);var _=d.length();_>e&&(e=_*2,o=e),e*=1.1,o*=1.5,s=c.min.add(d.scale(.5)),s.y=c.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:o,rootPosition:s}},a.prototype._setupGround=function(i){var e=this;(!this._ground||this._ground.isDisposed())&&(this._ground=CreatePlane("BackgroundPlane",{size:i.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(function(){e._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow},a.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)},a.prototype._setupGroundDiffuseTexture=function(){if(!!this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof BaseTexture){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}},a.prototype._setupGroundMirrorTexture=function(i){var e=Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Plane(0,-1,0,i.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=e,this._groundMirror.wrapV=e,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var o=0;o<this._scene.meshes.length;o++){var s=this._scene.meshes[o];s!==this._ground&&s!==this._skybox&&s!==this._rootMesh&&this._groundMirror.renderList.push(s)}this._groundMirror.clearColor=new Color4(this._options.groundColor.r,this._options.groundColor.g,this._options.groundColor.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel},a.prototype._setupMirrorInGroundMaterial=function(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)},a.prototype._setupSkybox=function(i){var e=this;(!this._skybox||this._skybox.isDisposed())&&(this._skybox=CreateBox("BackgroundSkybox",{size:i.skyboxSize,sideOrientation:Mesh.BACKSIDE},this._scene),this._skybox.onDisposeObservable.add(function(){e._skybox=null})),this._skybox.parent=this._rootMesh},a.prototype._setupSkyboxMaterial=function(){!this._skybox||(this._skyboxMaterial||(this._skyboxMaterial=new BackgroundMaterial("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)},a.prototype._setupSkyboxReflectionTexture=function(){if(!!this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof BaseTexture){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new CubeTexture(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Texture.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}},a.prototype.dispose=function(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)},a._groundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",a._skyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",a._environmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env",a}();FreeCameraInputsManager.prototype.addDeviceOrientation=function(){return this._deviceOrientationInput||(this._deviceOrientationInput=new FreeCameraDeviceOrientationInput,this.add(this._deviceOrientationInput)),this};var FreeCameraDeviceOrientationInput=function(){function a(){var i=this;this._screenOrientationAngle=0,this._screenQuaternion=new Quaternion,this._alpha=0,this._beta=0,this._gamma=0,this._onDeviceOrientationChangedObservable=new Observable,this._orientationChanged=function(){i._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,i._screenOrientationAngle=-Tools.ToRadians(i._screenOrientationAngle/2),i._screenQuaternion.copyFromFloats(0,Math.sin(i._screenOrientationAngle),0,Math.cos(i._screenOrientationAngle))},this._deviceOrientation=function(e){i._alpha=e.alpha!==null?e.alpha:0,i._beta=e.beta!==null?e.beta:0,i._gamma=e.gamma!==null?e.gamma:0,e.alpha!==null&&i._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}return a.WaitForOrientationChangeAsync=function(i){return new Promise(function(e,o){var s=!1,c=function(){window.removeEventListener("deviceorientation",c),s=!0,e()};i&&setTimeout(function(){s||(window.removeEventListener("deviceorientation",c),o("WaitForOrientationChangeAsync timed out"))},i),typeof DeviceOrientationEvent!="undefined"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(function(d){d=="granted"?window.addEventListener("deviceorientation",c):Tools.Warn("Permission not granted.")}).catch(function(d){Tools.Error(d)}):window.addEventListener("deviceorientation",c)})},Object.defineProperty(a.prototype,"camera",{get:function(){return this._camera},set:function(i){var e=this;this._camera=i,this._camera!=null&&!this._camera.rotationQuaternion&&(this._camera.rotationQuaternion=new Quaternion),this._camera&&this._camera.onDisposeObservable.add(function(){e._onDeviceOrientationChangedObservable.clear()})},enumerable:!1,configurable:!0}),a.prototype.attachControl=function(){var i=this,e=this.camera.getScene().getEngine().getHostWindow();if(e){var o=function(){e.addEventListener("orientationchange",i._orientationChanged),e.addEventListener("deviceorientation",i._deviceOrientation),i._orientationChanged()};typeof DeviceOrientationEvent!="undefined"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(function(s){s==="granted"?o():Tools.Warn("Permission not granted.")}).catch(function(s){Tools.Error(s)}):o()}},a.prototype.detachControl=function(i){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0},a.prototype.checkInputs=function(){!this._alpha||(Quaternion.RotationYawPitchRollToRef(Tools.ToRadians(this._alpha),Tools.ToRadians(this._beta),-Tools.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)},a.prototype.getClassName=function(){return"FreeCameraDeviceOrientationInput"},a.prototype.getSimpleName=function(){return"deviceOrientation"},a}();CameraInputTypes.FreeCameraDeviceOrientationInput=FreeCameraDeviceOrientationInput;Node$2.AddNodeConstructor("DeviceOrientationCamera",function(a,i){return function(){return new DeviceOrientationCamera(a,Vector3.Zero(),i)}});var DeviceOrientationCamera=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o,s)||this;return c._tmpDragQuaternion=new Quaternion,c._disablePointerInputWhenUsingDeviceOrientation=!0,c._dragFactor=0,c._quaternionCache=new Quaternion,c.inputs.addDeviceOrientation(),c.inputs._deviceOrientationInput&&c.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function(){c._disablePointerInputWhenUsingDeviceOrientation&&c.inputs._mouseInput&&(c.inputs._mouseInput._allowCameraRotation=!1,c.inputs._mouseInput.onPointerMovedObservable.add(function(d){c._dragFactor!=0&&(c._initialQuaternion||(c._initialQuaternion=new Quaternion),Quaternion.FromEulerAnglesToRef(0,d.offsetX*c._dragFactor,0,c._tmpDragQuaternion),c._initialQuaternion.multiplyToRef(c._tmpDragQuaternion,c._initialQuaternion))}))}),c}return Object.defineProperty(i.prototype,"disablePointerInputWhenUsingDeviceOrientation",{get:function(){return this._disablePointerInputWhenUsingDeviceOrientation},set:function(e){this._disablePointerInputWhenUsingDeviceOrientation=e},enumerable:!1,configurable:!0}),i.prototype.enableHorizontalDragging=function(e){e===void 0&&(e=1/300),this._dragFactor=e},i.prototype.getClassName=function(){return"DeviceOrientationCamera"},i.prototype._checkInputs=function(){a.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},i.prototype.resetToCurrentRotation=function(e){var o=this;e===void 0&&(e=Axis.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(function(s){e[s]?o._initialQuaternion[s]*=-1:o._initialQuaternion[s]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},i}(FreeCamera),VRCameraMetrics=function(){function a(){this.compensateDistortion=!0,this.multiviewEnabled=!1}return Object.defineProperty(a.prototype,"aspectRatio",{get:function(){return this.hResolution/(2*this.vResolution)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"aspectRatioFov",{get:function(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"leftHMatrix",{get:function(){var i=this.hScreenSize/4-this.lensSeparationDistance/2,e=4*i/this.hScreenSize;return Matrix.Translation(e,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rightHMatrix",{get:function(){var i=this.hScreenSize/4-this.lensSeparationDistance/2,e=4*i/this.hScreenSize;return Matrix.Translation(-e,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"leftPreViewMatrix",{get:function(){return Matrix.Translation(.5*this.interpupillaryDistance,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rightPreViewMatrix",{get:function(){return Matrix.Translation(-.5*this.interpupillaryDistance,0,0)},enumerable:!1,configurable:!0}),a.GetDefault=function(){var i=new a;return i.hResolution=1280,i.vResolution=800,i.hScreenSize=.149759993,i.vScreenSize=.0935999975,i.vScreenCenter=.0467999987,i.eyeToScreenDistance=.0410000011,i.lensSeparationDistance=.063500002,i.interpupillaryDistance=.064000003,i.distortionK=[1,.219999999,.239999995,0],i.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],i.postProcessScaleFactor=1.714605507808412,i.lensCenterOffset=.151976421,i},a}(),name$2="vrDistortionCorrectionPixelShader",shader$2=`
  10838. varying vec2 vUV;
  10839. uniform sampler2D textureSampler;
  10840. uniform vec2 LensCenter;
  10841. uniform vec2 Scale;
  10842. uniform vec2 ScaleIn;
  10843. uniform vec4 HmdWarpParam;
  10844. vec2 HmdWarp(vec2 in01) {
  10845. vec2 theta=(in01-LensCenter)*ScaleIn;
  10846. float rSq=theta.x*theta.x+theta.y*theta.y;
  10847. vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);
  10848. return LensCenter+Scale*rvector;
  10849. }
  10850. void main(void)
  10851. {
  10852. vec2 tc=HmdWarp(vUV);
  10853. if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)
  10854. gl_FragColor=vec4(0.0,0.0,0.0,0.0);
  10855. else{
  10856. gl_FragColor=texture2D(textureSampler,tc);
  10857. }
  10858. }`;ShaderStore.ShadersStore[name$2]=shader$2;var VRDistortionCorrectionPostProcess=function(a){__extends(i,a);function i(e,o,s,c){var d=a.call(this,e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,c.postProcessScaleFactor,o,Texture.BILINEAR_SAMPLINGMODE)||this;return d._isRightEye=s,d._distortionFactors=c.distortionK,d._postProcessScaleFactor=c.postProcessScaleFactor,d._lensCenterOffset=c.lensCenterOffset,d.adaptScaleToCurrentViewport=!0,d.onSizeChangedObservable.add(function(){d._scaleIn=new Vector2(2,2/d.aspectRatio),d._scaleFactor=new Vector2(.5*(1/d._postProcessScaleFactor),.5*(1/d._postProcessScaleFactor)*d.aspectRatio),d._lensCenter=new Vector2(d._isRightEye?.5-d._lensCenterOffset*.5:.5+d._lensCenterOffset*.5,.5)}),d.onApplyObservable.add(function(_){_.setFloat2("LensCenter",d._lensCenter.x,d._lensCenter.y),_.setFloat2("Scale",d._scaleFactor.x,d._scaleFactor.y),_.setFloat2("ScaleIn",d._scaleIn.x,d._scaleIn.y),_.setFloat4("HmdWarpParam",d._distortionFactors[0],d._distortionFactors[1],d._distortionFactors[2],d._distortionFactors[3])}),d}return i.prototype.getClassName=function(){return"VRDistortionCorrectionPostProcess"},i}(PostProcess),name$1="vrMultiviewToSingleviewPixelShader",shader$1=`precision mediump sampler2DArray;
  10859. varying vec2 vUV;
  10860. uniform sampler2DArray multiviewSampler;
  10861. uniform int imageIndex;
  10862. void main(void)
  10863. {
  10864. gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));
  10865. }`;ShaderStore.ShadersStore[name$1]=shader$1;var VRMultiviewToSingleviewPostProcess=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],s,o,Texture.BILINEAR_SAMPLINGMODE)||this;return c.onSizeChangedObservable.add(function(){}),c.onApplyObservable.add(function(d){o._scene.activeCamera&&o._scene.activeCamera.isLeftCamera?d.setInt("imageIndex",0):d.setInt("imageIndex",1),d.setTexture("multiviewSampler",o._multiviewTexture)}),c}return i.prototype.getClassName=function(){return"VRMultiviewToSingleviewPostProcess"},i}(PostProcess);function setVRRigMode(a,i){var e=i.vrCameraMetrics||VRCameraMetrics.GetDefault();a._rigCameras[0]._cameraRigParams.vrMetrics=e,a._rigCameras[0].viewport=new Viewport(0,0,.5,1),a._rigCameras[0]._cameraRigParams.vrWorkMatrix=new Matrix,a._rigCameras[0]._cameraRigParams.vrHMatrix=e.leftHMatrix,a._rigCameras[0]._cameraRigParams.vrPreViewMatrix=e.leftPreViewMatrix,a._rigCameras[0].getProjectionMatrix=a._rigCameras[0]._getVRProjectionMatrix,a._rigCameras[1]._cameraRigParams.vrMetrics=e,a._rigCameras[1].viewport=new Viewport(.5,0,.5,1),a._rigCameras[1]._cameraRigParams.vrWorkMatrix=new Matrix,a._rigCameras[1]._cameraRigParams.vrHMatrix=e.rightHMatrix,a._rigCameras[1]._cameraRigParams.vrPreViewMatrix=e.rightPreViewMatrix,a._rigCameras[1].getProjectionMatrix=a._rigCameras[1]._getVRProjectionMatrix,e.multiviewEnabled&&(a.getScene().getEngine().getCaps().multiview?(a._useMultiviewToSingleView=!0,a._rigPostProcess=new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",a,e.postProcessScaleFactor)):(Logger$2.Warn("Multiview is not supported, falling back to standard rendering"),e.multiviewEnabled=!1)),e.compensateDistortion&&(a._rigCameras[0]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",a._rigCameras[0],!1,e),a._rigCameras[1]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",a._rigCameras[1],!0,e))}Node$2.AddNodeConstructor("VRDeviceOrientationFreeCamera",function(a,i){return function(){return new VRDeviceOrientationFreeCamera(a,Vector3.Zero(),i)}});var VRDeviceOrientationFreeCamera=function(a){__extends(i,a);function i(e,o,s,c,d){c===void 0&&(c=!0),d===void 0&&(d=VRCameraMetrics.GetDefault());var _=a.call(this,e,o,s)||this;return _._setRigMode=setVRRigMode.bind(null,_),d.compensateDistortion=c,_.setCameraRigMode(Camera$1.RIG_MODE_VR,{vrCameraMetrics:d}),_}return i.prototype.getClassName=function(){return"VRDeviceOrientationFreeCamera"},i}(DeviceOrientationCamera),Gamepad=function(){function a(i,e,o,s,c,d,_){s===void 0&&(s=0),c===void 0&&(c=1),d===void 0&&(d=2),_===void 0&&(_=3),this.id=i,this.index=e,this.browserGamepad=o,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=a.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=c,this._rightStickAxisX=d,this._rightStickAxisY=_,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return Object.defineProperty(a.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!1,configurable:!0}),a.prototype.onleftstickchanged=function(i){this._onleftstickchanged=i},a.prototype.onrightstickchanged=function(i){this._onrightstickchanged=i},Object.defineProperty(a.prototype,"leftStick",{get:function(){return this._leftStick},set:function(i){this._onleftstickchanged&&(this._leftStick.x!==i.x||this._leftStick.y!==i.y)&&this._onleftstickchanged(i),this._leftStick=i},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rightStick",{get:function(){return this._rightStick},set:function(i){this._onrightstickchanged&&(this._rightStick.x!==i.x||this._rightStick.y!==i.y)&&this._onrightstickchanged(i),this._rightStick=i},enumerable:!1,configurable:!0}),a.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},a.prototype.dispose=function(){},a.GAMEPAD=0,a.GENERIC=1,a.XBOX=2,a.POSE_ENABLED=3,a.DUALSHOCK=4,a}(),GenericPad=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o,s)||this;return c.onButtonDownObservable=new Observable,c.onButtonUpObservable=new Observable,c.type=Gamepad.GENERIC,c._buttons=new Array(s.buttons.length),c}return i.prototype.onbuttondown=function(e){this._onbuttondown=e},i.prototype.onbuttonup=function(e){this._onbuttonup=e},i.prototype._setButtonValue=function(e,o,s){return e!==o&&(e===1&&(this._onbuttondown&&this._onbuttondown(s),this.onButtonDownObservable.notifyObservers(s)),e===0&&(this._onbuttonup&&this._onbuttonup(s),this.onButtonUpObservable.notifyObservers(s))),e},i.prototype.update=function(){a.prototype.update.call(this);for(var e=0;e<this._buttons.length;e++)this._buttons[e]=this._setButtonValue(this.browserGamepad.buttons[e].value,this._buttons[e],e)},i.prototype.dispose=function(){a.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()},i}(Gamepad),PoseEnabledControllerType;(function(a){a[a.VIVE=0]="VIVE",a[a.OCULUS=1]="OCULUS",a[a.WINDOWS=2]="WINDOWS",a[a.GEAR_VR=3]="GEAR_VR",a[a.DAYDREAM=4]="DAYDREAM",a[a.GENERIC=5]="GENERIC"})(PoseEnabledControllerType||(PoseEnabledControllerType={}));var PoseEnabledControllerHelper=function(){function a(){}return a.InitiateController=function(i){for(var e=0,o=this._ControllerFactories;e<o.length;e++){var s=o[e];if(s.canCreate(i))return s.create(i)}if(this._DefaultControllerFactory)return this._DefaultControllerFactory(i);throw"The type of gamepad you are trying to load needs to be imported first or is not supported."},a._ControllerFactories=[],a._DefaultControllerFactory=null,a}(),PoseEnabledController=function(a){__extends(i,a);function i(e){var o=a.call(this,e.id,e.index,e)||this;return o.isXR=!1,o._deviceRoomPosition=Vector3.Zero(),o._deviceRoomRotationQuaternion=new Quaternion,o.devicePosition=Vector3.Zero(),o.deviceRotationQuaternion=new Quaternion,o.deviceScaleFactor=1,o._trackPosition=!0,o._maxRotationDistFromHeadset=Math.PI/5,o._draggedRoomRotation=0,o._leftHandSystemQuaternion=new Quaternion,o._deviceToWorld=Matrix.Identity(),o._pointingPoseNode=null,o._workingMatrix=Matrix.Identity(),o._meshAttachedObservable=new Observable,o.type=Gamepad.POSE_ENABLED,o.controllerType=PoseEnabledControllerType.GENERIC,o.position=Vector3.Zero(),o.rotationQuaternion=new Quaternion,o._calculatedPosition=Vector3.Zero(),o._calculatedRotation=new Quaternion,Quaternion.RotationYawPitchRollToRef(Math.PI,0,0,o._leftHandSystemQuaternion),o}return i.prototype._disableTrackPosition=function(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)},i.prototype.update=function(){a.prototype.update.call(this),this._updatePoseAndMesh()},i.prototype._updatePoseAndMesh=function(){if(!this.isXR){var e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&EngineStore.LastCreatedScene&&EngineStore.LastCreatedScene.activeCamera&&EngineStore.LastCreatedScene.activeCamera.devicePosition){var o=EngineStore.LastCreatedScene.activeCamera;if(o._computeDevicePosition(),this._deviceToWorld.setTranslation(o.devicePosition),o.deviceRotationQuaternion){var o=o;o._deviceRoomRotationQuaternion.toEulerAnglesToRef(TmpVectors.Vector3[0]);var s=Math.atan2(Math.sin(TmpVectors.Vector3[0].y-this._draggedRoomRotation),Math.cos(TmpVectors.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(s)>this._maxRotationDistFromHeadset){var c=s-(s<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=c;var d=Math.sin(-c),_=Math.cos(-c);this._calculatedPosition.x=this._calculatedPosition.x*_-this._calculatedPosition.z*d,this._calculatedPosition.z=this._calculatedPosition.x*d+this._calculatedPosition.z*_}}}Vector3.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),Quaternion.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),this._mesh&&(this._mesh.position.copyFrom(this.devicePosition),this._mesh.rotationQuaternion&&this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))}},i.prototype.updateFromDevice=function(e){if(!this.isXR&&e){this.rawPose=e,e.position&&(this._deviceRoomPosition.copyFromFloats(e.position[0],e.position[1],-e.position[2]),this._mesh&&this._mesh.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1),this._trackPosition&&this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor,this._calculatedPosition),this._calculatedPosition.addInPlace(this.position));var o=this.rawPose;e.orientation&&o.orientation&&o.orientation.length===4&&(this._deviceRoomRotationQuaternion.copyFromFloats(o.orientation[0],o.orientation[1],-o.orientation[2],-o.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}},i.prototype.attachToMesh=function(e){if(this._mesh&&(this._mesh.parent=null),this._mesh=e,this._poseControlledCamera&&(this._mesh.parent=this._poseControlledCamera),this._mesh.rotationQuaternion||(this._mesh.rotationQuaternion=new Quaternion),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){for(var o=[],s=this._pointingPoseNode;s.parent;)o.push(s.parent),s=s.parent;o.reverse().forEach(function(c){c.computeWorldMatrix(!0)})}this._meshAttachedObservable.notifyObservers(e)},i.prototype.attachToPoseControlledCamera=function(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)},i.prototype.dispose=function(){this._mesh&&this._mesh.dispose(),this._mesh=null,a.prototype.dispose.call(this)},Object.defineProperty(i.prototype,"mesh",{get:function(){return this._mesh},enumerable:!1,configurable:!0}),i.prototype.getForwardRay=function(e){if(e===void 0&&(e=100),!this.mesh)return new Ray(Vector3.Zero(),new Vector3(0,0,1),e);var o=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),s=o.getTranslation(),c=new Vector3(0,0,-1),d=Vector3.TransformNormal(c,o),_=Vector3.Normalize(d);return new Ray(s,_,e)},i.POINTING_POSE="POINTING_POSE",i}(Gamepad);function setWebVRRigMode(a,i){if(i.vrDisplay){var e=i.vrDisplay.getEyeParameters("left"),o=i.vrDisplay.getEyeParameters("right");a._rigCameras[0].viewport=new Viewport(0,0,.5,1),a._rigCameras[0].setCameraRigParameter("left",!0),a._rigCameras[0].setCameraRigParameter("specs",i.specs),a._rigCameras[0].setCameraRigParameter("eyeParameters",e),a._rigCameras[0].setCameraRigParameter("frameData",i.frameData),a._rigCameras[0].setCameraRigParameter("parentCamera",i.parentCamera),a._rigCameras[0]._cameraRigParams.vrWorkMatrix=new Matrix,a._rigCameras[0].getProjectionMatrix=a._getWebVRProjectionMatrix,a._rigCameras[0].parent=a,a._rigCameras[0]._getViewMatrix=a._getWebVRViewMatrix,a._rigCameras[1].viewport=new Viewport(.5,0,.5,1),a._rigCameras[1].setCameraRigParameter("eyeParameters",o),a._rigCameras[1].setCameraRigParameter("specs",i.specs),a._rigCameras[1].setCameraRigParameter("frameData",i.frameData),a._rigCameras[1].setCameraRigParameter("parentCamera",i.parentCamera),a._rigCameras[1]._cameraRigParams.vrWorkMatrix=new Matrix,a._rigCameras[1].getProjectionMatrix=a._getWebVRProjectionMatrix,a._rigCameras[1].parent=a,a._rigCameras[1]._getViewMatrix=a._getWebVRViewMatrix}}Node$2.AddNodeConstructor("WebVRFreeCamera",function(a,i){return function(){return new WebVRFreeCamera(a,Vector3.Zero(),i)}});Node$2.AddNodeConstructor("WebVRGamepadCamera",function(a,i){return function(){return new WebVRFreeCamera(a,Vector3.Zero(),i)}});var WebVRFreeCamera=function(a){__extends(i,a);function i(e,o,s,c){c===void 0&&(c={});var d=a.call(this,e,o,s)||this;d.webVROptions=c,d._vrDevice=null,d.rawPose=null,d._specsVersion="1.1",d._attached=!1,d._descendants=[],d._deviceRoomPosition=Vector3.Zero(),d._deviceRoomRotationQuaternion=Quaternion.Identity(),d._standingMatrix=null,d.devicePosition=Vector3.Zero(),d.deviceRotationQuaternion=Quaternion.Identity(),d.deviceScaleFactor=1,d._deviceToWorld=Matrix.Identity(),d._worldToDevice=Matrix.Identity(),d.controllers=[],d.onControllersAttachedObservable=new Observable,d.onControllerMeshLoadedObservable=new Observable,d.onPoseUpdatedFromDeviceObservable=new Observable,d._poseSet=!1,d.rigParenting=!0,d._defaultHeight=void 0,d._setRigMode=setWebVRRigMode.bind(null,d),d._detachIfAttached=function(){var b=d.getEngine().getVRDevice();b&&!b.isPresenting&&d.detachControl()},d._workingVector=Vector3.Zero(),d._oneVector=Vector3.One(),d._workingMatrix=Matrix.Identity(),d._tmpMatrix=new Matrix,d._cache.position=Vector3.Zero(),c.defaultHeight&&(d._defaultHeight=c.defaultHeight,d.position.y=d._defaultHeight),d.minZ=.1,arguments.length===5&&(d.webVROptions=arguments[4]),d.webVROptions.trackPosition==null&&(d.webVROptions.trackPosition=!0),d.webVROptions.controllerMeshes==null&&(d.webVROptions.controllerMeshes=!0),d.webVROptions.defaultLightingOnControllers==null&&(d.webVROptions.defaultLightingOnControllers=!0),d.rotationQuaternion=new Quaternion,d.webVROptions&&d.webVROptions.positionScale&&(d.deviceScaleFactor=d.webVROptions.positionScale);var _=d.getEngine();return d._onVREnabled=function(b){b&&d.initControllers()},_.onVRRequestPresentComplete.add(d._onVREnabled),_.initWebVR().add(function(b){!b.vrDisplay||d._vrDevice===b.vrDisplay||(d._vrDevice=b.vrDisplay,d.setCameraRigMode(Camera$1.RIG_MODE_WEBVR,{parentCamera:d,vrDisplay:d._vrDevice,frameData:d._frameData,specs:d._specsVersion}),d._attached&&d.getEngine().enableVR(d.webVROptions))}),typeof VRFrameData!="undefined"&&(d._frameData=new VRFrameData),c.useMultiview&&(d.getScene().getEngine().getCaps().multiview?(d._useMultiviewToSingleView=!0,d._rigPostProcess=new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",d,1)):(Logger$2.Warn("Multiview is not supported, falling back to standard rendering"),d._useMultiviewToSingleView=!1)),s.onBeforeCameraRenderObservable.add(function(b){b.parent===d&&d.rigParenting&&(d._descendants=d.getDescendants(!0,function(k){var j=d.controllers.some(function(_e){return _e._mesh===k}),$=d._rigCameras.indexOf(k)!==-1;return!j&&!$}),d._descendants.forEach(function(k){k.parent=b}))}),s.onAfterCameraRenderObservable.add(function(b){b.parent===d&&d.rigParenting&&d._descendants.forEach(function(k){k.parent=d})}),d}return i.prototype.deviceDistanceToRoomGround=function(){return this._standingMatrix?(this._standingMatrix.getTranslationToRef(this._workingVector),this._deviceRoomPosition.y+this._workingVector.y):this._defaultHeight||0},i.prototype.useStandingMatrix=function(e){var o=this;e===void 0&&(e=function(s){}),this.getEngine().initWebVRAsync().then(function(s){!s.vrDisplay||!s.vrDisplay.stageParameters||!s.vrDisplay.stageParameters.sittingToStandingTransform||!o.webVROptions.trackPosition?e(!1):(o._standingMatrix=new Matrix,Matrix.FromFloat32ArrayToRefScaled(s.vrDisplay.stageParameters.sittingToStandingTransform,0,1,o._standingMatrix),o.getScene().useRightHandedSystem||o._standingMatrix&&o._standingMatrix.toggleModelMatrixHandInPlace(),e(!0))})},i.prototype.useStandingMatrixAsync=function(){var e=this;return new Promise(function(o){e.useStandingMatrix(function(s){o(s)})})},i.prototype.dispose=function(){this._detachIfAttached(),this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),this._updateCacheWhenTrackingDisabledObserver&&this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),a.prototype.dispose.call(this)},i.prototype.getControllerByName=function(e){for(var o=0,s=this.controllers;o<s.length;o++){var c=s[o];if(c.hand===e)return c}return null},Object.defineProperty(i.prototype,"leftController",{get:function(){return this._leftController||(this._leftController=this.getControllerByName("left")),this._leftController},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rightController",{get:function(){return this._rightController||(this._rightController=this.getControllerByName("right")),this._rightController},enumerable:!1,configurable:!0}),i.prototype.getForwardRay=function(e){return e===void 0&&(e=100),this.leftCamera?a.prototype.getForwardRay.call(this,e,this.leftCamera.getWorldMatrix(),this.leftCamera.globalPosition):a.prototype.getForwardRay.call(this,e)},i.prototype._checkInputs=function(){this._vrDevice&&this._vrDevice.isPresenting&&(this._vrDevice.getFrameData(this._frameData),this.updateFromDevice(this._frameData.pose)),a.prototype._checkInputs.call(this)},i.prototype.updateFromDevice=function(e){e&&e.orientation&&e.orientation.length===4&&(this.rawPose=e,this._deviceRoomRotationQuaternion.copyFromFloats(e.orientation[0],e.orientation[1],-e.orientation[2],-e.orientation[3]),this.getScene().useRightHandedSystem&&(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1),this.webVROptions.trackPosition&&this.rawPose.position&&(this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2]),this.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1)),this._poseSet=!0)},i.prototype.attachControl=function(e){e=Tools.BackCompatCameraNoPreventDefault(arguments),a.prototype.attachControl.call(this,e),this._attached=!0,e=Camera$1.ForceAttachControlToAlwaysPreventDefault?!1:e,this._vrDevice&&this.getEngine().enableVR(this.webVROptions);var o=this._scene.getEngine().getHostWindow();o&&o.addEventListener("vrdisplaypresentchange",this._detachIfAttached)},i.prototype.detachControl=function(e){this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),a.prototype.detachControl.call(this),this._attached=!1,this.getEngine().disableVR(),window.removeEventListener("vrdisplaypresentchange",this._detachIfAttached)},i.prototype.getClassName=function(){return"WebVRFreeCamera"},i.prototype.resetToCurrentRotation=function(){this._vrDevice.resetPose()},i.prototype._updateRigCameras=function(){var e=this._rigCameras[0],o=this._rigCameras[1];e.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),o.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),e.position.copyFrom(this._deviceRoomPosition),o.position.copyFrom(this._deviceRoomPosition)},i.prototype._correctPositionIfNotTrackPosition=function(e,o){o===void 0&&(o=!1),this.rawPose&&this.rawPose.position&&!this.webVROptions.trackPosition&&(Matrix.TranslationToRef(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2],this._tmpMatrix),o||this._tmpMatrix.invert(),this._tmpMatrix.multiplyToRef(e,e))},i.prototype._updateCache=function(e){var o=this;(!this.rotationQuaternion.equals(this._cache.rotationQuaternion)||!this.position.equals(this._cache.position))&&(this.updateCacheCalled||(this.updateCacheCalled=!0,this.update()),this.rotationQuaternion.toRotationMatrix(this._workingMatrix),Vector3.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),Matrix.ComposeToRef(this._oneVector,this.rotationQuaternion,this._workingVector,this._deviceToWorld),this._deviceToWorld.getTranslationToRef(this._workingVector),this._workingVector.addInPlace(this.position),this._workingVector.subtractInPlace(this._cache.position),this._deviceToWorld.setTranslation(this._workingVector),this._deviceToWorld.invertToRef(this._worldToDevice),this.controllers.forEach(function(s){s._deviceToWorld.copyFrom(o._deviceToWorld),o._correctPositionIfNotTrackPosition(s._deviceToWorld),s.update()})),e||a.prototype._updateCache.call(this),this.updateCacheCalled=!1},i.prototype._computeDevicePosition=function(){Vector3.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)},i.prototype.update=function(){this._computeDevicePosition(),Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),Quaternion.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),a.prototype.update.call(this)},i.prototype._getViewMatrix=function(){return Matrix.Identity()},i.prototype._getWebVRViewMatrix=function(){var e=this._cameraRigParams.parentCamera;e._updateCache();var o=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return Matrix.FromArrayToRef(o,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),e.deviceScaleFactor!==1&&(this._webvrViewMatrix.invert(),e.deviceScaleFactor&&(this._webvrViewMatrix.multiplyAtIndex(12,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(13,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(14,e.deviceScaleFactor)),this._webvrViewMatrix.invert()),e._correctPositionIfNotTrackPosition(this._webvrViewMatrix,!0),e._worldToDevice.multiplyToRef(this._webvrViewMatrix,this._webvrViewMatrix),this._workingMatrix=this._workingMatrix||Matrix.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix},i.prototype._getWebVRProjectionMatrix=function(){var e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;var o=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return Matrix.FromArrayToRef(o,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix},i.prototype.initControllers=function(){var e=this;this.controllers=[];var o=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=o.onGamepadDisconnectedObservable.add(function(s){if(s.type===Gamepad.POSE_ENABLED){var c=s;c.defaultModel&&c.defaultModel.setEnabled(!1),c.hand==="right"&&(e._rightController=null),c.hand==="left"&&(e._leftController=null);var d=e.controllers.indexOf(c);d!==-1&&e.controllers.splice(d,1)}}),this._onGamepadConnectedObserver=o.onGamepadConnectedObservable.add(function(s){if(s.type===Gamepad.POSE_ENABLED){var c=s;if(e.webVROptions.trackPosition||(c._disableTrackPosition(new Vector3(c.hand=="left"?-.15:.15,-.5,.25)),e._updateCacheWhenTrackingDisabledObserver||(e._updateCacheWhenTrackingDisabledObserver=e._scene.onBeforeRenderObservable.add(function(){e._updateCache()}))),c.deviceScaleFactor=e.deviceScaleFactor,c._deviceToWorld.copyFrom(e._deviceToWorld),e._correctPositionIfNotTrackPosition(c._deviceToWorld),e.webVROptions.controllerMeshes&&(c.defaultModel?c.defaultModel.setEnabled(!0):c.initControllerMesh(e.getScene(),function(b){if(b.scaling.scaleInPlace(e.deviceScaleFactor),e.onControllerMeshLoadedObservable.notifyObservers(c),e.webVROptions.defaultLightingOnControllers){e._lightOnControllers||(e._lightOnControllers=new HemisphericLight("vrControllersLight",new Vector3(0,1,0),e.getScene()));var k=function(j,$){var _e=j.getChildren();_e&&_e.length!==0&&_e.forEach(function(et){$.includedOnlyMeshes.push(et),k(et,$)})};e._lightOnControllers.includedOnlyMeshes.push(b),k(b,e._lightOnControllers)}})),c.attachToPoseControlledCamera(e),e.controllers.indexOf(c)===-1){e.controllers.push(c);for(var d=!1,_=0;_<e.controllers.length;_++)e.controllers[_].controllerType===PoseEnabledControllerType.VIVE&&(d?e.controllers[_].hand="right":(d=!0,e.controllers[_].hand="left"));e.controllers.length>=2&&e.onControllersAttachedObservable.notifyObservers(e.controllers)}}})},i}(FreeCamera),WebVRController=function(a){__extends(i,a);function i(e){var o=a.call(this,e)||this;return o.onTriggerStateChangedObservable=new Observable,o.onMainButtonStateChangedObservable=new Observable,o.onSecondaryButtonStateChangedObservable=new Observable,o.onPadStateChangedObservable=new Observable,o.onPadValuesChangedObservable=new Observable,o.pad={x:0,y:0},o._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},o._buttons=new Array(e.buttons.length),o.hand=e.hand,o}return i.prototype.onButtonStateChange=function(e){this._onButtonStateChange=e},Object.defineProperty(i.prototype,"defaultModel",{get:function(){return this._defaultModel},enumerable:!1,configurable:!0}),i.prototype.update=function(){a.prototype.update.call(this);for(var e=0;e<this._buttons.length;e++)this._setButtonValue(this.browserGamepad.buttons[e],this._buttons[e],e);(this.leftStick.x!==this.pad.x||this.leftStick.y!==this.pad.y)&&(this.pad.x=this.leftStick.x,this.pad.y=this.leftStick.y,this.onPadValuesChangedObservable.notifyObservers(this.pad))},i.prototype._setButtonValue=function(e,o,s){if(e||(e={pressed:!1,touched:!1,value:0}),!o){this._buttons[s]={pressed:e.pressed,touched:e.touched,value:e.value};return}this._checkChanges(e,o),this._changes.changed&&(this._onButtonStateChange&&this._onButtonStateChange(this.index,s,e),this._handleButtonChange(s,e,this._changes)),this._buttons[s].pressed=e.pressed,this._buttons[s].touched=e.touched,this._buttons[s].value=e.value<1e-8?0:e.value},i.prototype._checkChanges=function(e,o){return this._changes.pressChanged=e.pressed!==o.pressed,this._changes.touchChanged=e.touched!==o.touched,this._changes.valueChanged=e.value!==o.value,this._changes.changed=this._changes.pressChanged||this._changes.touchChanged||this._changes.valueChanged,this._changes},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._defaultModel=null,this.onTriggerStateChangedObservable.clear(),this.onMainButtonStateChangedObservable.clear(),this.onSecondaryButtonStateChangedObservable.clear(),this.onPadStateChangedObservable.clear(),this.onPadValuesChangedObservable.clear()},i}(PoseEnabledController),Xbox360Button;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(Xbox360Button||(Xbox360Button={}));var Xbox360Dpad;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(Xbox360Dpad||(Xbox360Dpad={}));var Xbox360Pad=function(a){__extends(i,a);function i(e,o,s,c){c===void 0&&(c=!1);var d=a.call(this,e,o,s,0,1,2,3)||this;return d._leftTrigger=0,d._rightTrigger=0,d.onButtonDownObservable=new Observable,d.onButtonUpObservable=new Observable,d.onPadDownObservable=new Observable,d.onPadUpObservable=new Observable,d._buttonA=0,d._buttonB=0,d._buttonX=0,d._buttonY=0,d._buttonBack=0,d._buttonStart=0,d._buttonLB=0,d._buttonRB=0,d._buttonLeftStick=0,d._buttonRightStick=0,d._dPadUp=0,d._dPadDown=0,d._dPadLeft=0,d._dPadRight=0,d._isXboxOnePad=!1,d.type=Gamepad.XBOX,d._isXboxOnePad=c,d}return i.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},i.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(i.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!1,configurable:!0}),i.prototype.onbuttondown=function(e){this._onbuttondown=e},i.prototype.onbuttonup=function(e){this._onbuttonup=e},i.prototype.ondpaddown=function(e){this._ondpaddown=e},i.prototype.ondpadup=function(e){this._ondpadup=e},i.prototype._setButtonValue=function(e,o,s){return e!==o&&(e===1&&(this._onbuttondown&&this._onbuttondown(s),this.onButtonDownObservable.notifyObservers(s)),e===0&&(this._onbuttonup&&this._onbuttonup(s),this.onButtonUpObservable.notifyObservers(s))),e},i.prototype._setDPadValue=function(e,o,s){return e!==o&&(e===1&&(this._ondpaddown&&this._ondpaddown(s),this.onPadDownObservable.notifyObservers(s)),e===0&&(this._ondpadup&&this._ondpadup(s),this.onPadUpObservable.notifyObservers(s))),e},Object.defineProperty(i.prototype,"buttonA",{get:function(){return this._buttonA},set:function(e){this._buttonA=this._setButtonValue(e,this._buttonA,Xbox360Button.A)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonB",{get:function(){return this._buttonB},set:function(e){this._buttonB=this._setButtonValue(e,this._buttonB,Xbox360Button.B)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonX",{get:function(){return this._buttonX},set:function(e){this._buttonX=this._setButtonValue(e,this._buttonX,Xbox360Button.X)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonY",{get:function(){return this._buttonY},set:function(e){this._buttonY=this._setButtonValue(e,this._buttonY,Xbox360Button.Y)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonStart",{get:function(){return this._buttonStart},set:function(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Xbox360Button.Start)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonBack",{get:function(){return this._buttonBack},set:function(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Xbox360Button.Back)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonLB",{get:function(){return this._buttonLB},set:function(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Xbox360Button.LB)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonRB",{get:function(){return this._buttonRB},set:function(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Xbox360Button.RB)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Xbox360Button.LeftStick)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Xbox360Button.RightStick)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Xbox360Dpad.Up)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Xbox360Dpad.Down)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Xbox360Dpad.Left)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Xbox360Dpad.Right)},enumerable:!1,configurable:!0}),i.prototype.update=function(){a.prototype.update.call(this),this._isXboxOnePad?(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value):(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value)},i.prototype.dispose=function(){a.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},i}(Gamepad),DualShockButton;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(DualShockButton||(DualShockButton={}));var DualShockDpad;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(DualShockDpad||(DualShockDpad={}));var DualShockPad=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),o,s,0,1,2,3)||this;return c._leftTrigger=0,c._rightTrigger=0,c.onButtonDownObservable=new Observable,c.onButtonUpObservable=new Observable,c.onPadDownObservable=new Observable,c.onPadUpObservable=new Observable,c._buttonCross=0,c._buttonCircle=0,c._buttonSquare=0,c._buttonTriangle=0,c._buttonShare=0,c._buttonOptions=0,c._buttonL1=0,c._buttonR1=0,c._buttonLeftStick=0,c._buttonRightStick=0,c._dPadUp=0,c._dPadDown=0,c._dPadLeft=0,c._dPadRight=0,c.type=Gamepad.DUALSHOCK,c}return i.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},i.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(i.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!1,configurable:!0}),i.prototype.onbuttondown=function(e){this._onbuttondown=e},i.prototype.onbuttonup=function(e){this._onbuttonup=e},i.prototype.ondpaddown=function(e){this._ondpaddown=e},i.prototype.ondpadup=function(e){this._ondpadup=e},i.prototype._setButtonValue=function(e,o,s){return e!==o&&(e===1&&(this._onbuttondown&&this._onbuttondown(s),this.onButtonDownObservable.notifyObservers(s)),e===0&&(this._onbuttonup&&this._onbuttonup(s),this.onButtonUpObservable.notifyObservers(s))),e},i.prototype._setDPadValue=function(e,o,s){return e!==o&&(e===1&&(this._ondpaddown&&this._ondpaddown(s),this.onPadDownObservable.notifyObservers(s)),e===0&&(this._ondpadup&&this._ondpadup(s),this.onPadUpObservable.notifyObservers(s))),e},Object.defineProperty(i.prototype,"buttonCross",{get:function(){return this._buttonCross},set:function(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,DualShockButton.Cross)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonCircle",{get:function(){return this._buttonCircle},set:function(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,DualShockButton.Circle)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonSquare",{get:function(){return this._buttonSquare},set:function(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,DualShockButton.Square)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonTriangle",{get:function(){return this._buttonTriangle},set:function(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,DualShockButton.Triangle)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonOptions",{get:function(){return this._buttonOptions},set:function(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,DualShockButton.Options)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonShare",{get:function(){return this._buttonShare},set:function(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,DualShockButton.Share)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonL1",{get:function(){return this._buttonL1},set:function(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,DualShockButton.L1)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonR1",{get:function(){return this._buttonR1},set:function(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,DualShockButton.R1)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,DualShockButton.LeftStick)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,DualShockButton.RightStick)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,DualShockDpad.Up)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,DualShockDpad.Down)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,DualShockDpad.Left)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,DualShockDpad.Right)},enumerable:!1,configurable:!0}),i.prototype.update=function(){a.prototype.update.call(this),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value},i.prototype.dispose=function(){a.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},i}(Gamepad),GamepadManager=function(){function a(i){var e=this;if(this._scene=i,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new Observable,IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&(navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads)):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new Observable(function(s){for(var c in e._babylonGamepads){var d=e._babylonGamepads[c];d&&d._isConnected&&e.onGamepadConnectedObservable.notifyObserver(s,d)}}),this._onGamepadConnectedEvent=function(s){var c=s.gamepad;if(!(c.index in e._babylonGamepads&&e._babylonGamepads[c.index].isConnected)){var d;e._babylonGamepads[c.index]?(d=e._babylonGamepads[c.index],d.browserGamepad=c,d._isConnected=!0):d=e._addNewGamepad(c),e.onGamepadConnectedObservable.notifyObservers(d),e._startMonitoringGamepads()}},this._onGamepadDisconnectedEvent=function(s){var c=s.gamepad;for(var d in e._babylonGamepads)if(e._babylonGamepads[d].index===c.index){var _=e._babylonGamepads[d];_._isConnected=!1,e.onGamepadDisconnectedObservable.notifyObservers(_),_.dispose&&_.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){var o=this._scene?this._scene.getEngine().getHostWindow():window;o&&(o.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),o.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}return Object.defineProperty(a.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!1,configurable:!0}),a.prototype.getGamepadByType=function(i){i===void 0&&(i=Gamepad.XBOX);for(var e=0,o=this._babylonGamepads;e<o.length;e++){var s=o[e];if(s&&s.type===i)return s}return null},a.prototype.dispose=function(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(function(i){i.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]},a.prototype._addNewGamepad=function(i){this._oneGamepadConnected||(this._oneGamepadConnected=!0);var e,o=i.id.search("054c")!==-1&&i.id.search("0ce6")===-1,s=i.id.search("Xbox One")!==-1;return s||i.id.search("Xbox 360")!==-1||i.id.search("xinput")!==-1||i.id.search("045e")!==-1&&i.id.search("Surface Dock")===-1?e=new Xbox360Pad(i.id,i.index,i,s):o?e=new DualShockPad(i.id,i.index,i):i.pose?e=PoseEnabledControllerHelper.InitiateController(i):e=new GenericPad(i.id,i.index,i),this._babylonGamepads[e.index]=e,e},a.prototype._startMonitoringGamepads=function(){this._isMonitoring||(this._isMonitoring=!0,this._scene||this._checkGamepadsStatus())},a.prototype._stopMonitoringGamepads=function(){this._isMonitoring=!1},a.prototype._checkGamepadsStatus=function(){var i=this;this._updateGamepadObjects();for(var e in this._babylonGamepads){var o=this._babylonGamepads[e];if(!(!o||!o.isConnected))try{o.update()}catch{this._loggedErrors.indexOf(o.index)===-1&&(Tools.Warn("Error updating gamepad "+o.id),this._loggedErrors.push(o.index))}}this._isMonitoring&&!this._scene&&Engine.QueueNewFrame(function(){i._checkGamepadsStatus()})},a.prototype._updateGamepadObjects=function(){for(var i=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[],e=0;e<i.length;e++){var o=i[e];if(o)if(this._babylonGamepads[o.index])this._babylonGamepads[e].browserGamepad=o,this._babylonGamepads[e].isConnected||(this._babylonGamepads[e]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[e]));else{var s=this._addNewGamepad(o);this.onGamepadConnectedObservable.notifyObservers(s)}}},a}(),FreeCameraGamepadInput=function(){function a(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=Matrix.Identity(),this._deltaTransform=Vector3.Zero(),this._vector3=Vector3.Zero(),this._vector2=Vector2.Zero()}return Object.defineProperty(a.prototype,"invertYAxis",{get:function(){return this._yAxisScale!==1},set:function(i){this._yAxisScale=i?-1:1},enumerable:!1,configurable:!0}),a.prototype.attachControl=function(){var i=this,e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(function(o){o.type!==Gamepad.POSE_ENABLED&&(!i.gamepad||o.type===Gamepad.XBOX)&&(i.gamepad=o)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(function(o){i.gamepad===o&&(i.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])},a.prototype.detachControl=function(i){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},a.prototype.checkInputs=function(){if(this.gamepad&&this.gamepad.leftStick){var i=this.camera,e=this.gamepad.leftStick;this.gamepadMoveSensibility!==0&&(e.x=Math.abs(e.x)>this.deadzoneDelta?e.x/this.gamepadMoveSensibility:0,e.y=Math.abs(e.y)>this.deadzoneDelta?e.y/this.gamepadMoveSensibility:0);var o=this.gamepad.rightStick;o&&this.gamepadAngularSensibility!==0?(o.x=Math.abs(o.x)>this.deadzoneDelta?o.x/this.gamepadAngularSensibility:0,o.y=(Math.abs(o.y)>this.deadzoneDelta?o.y/this.gamepadAngularSensibility:0)*this._yAxisScale):o={x:0,y:0},i.rotationQuaternion?i.rotationQuaternion.toRotationMatrix(this._cameraTransform):Matrix.RotationYawPitchRollToRef(i.rotation.y,i.rotation.x,0,this._cameraTransform);var s=i._computeLocalCameraSpeed()*50;this._vector3.copyFromFloats(e.x*s,0,-e.y*s),Vector3.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),i.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(o.y,o.x),i.cameraRotation.addInPlace(this._vector2)}},a.prototype.getClassName=function(){return"FreeCameraGamepadInput"},a.prototype.getSimpleName=function(){return"gamepad"},__decorate([serialize()],a.prototype,"gamepadAngularSensibility",void 0),__decorate([serialize()],a.prototype,"gamepadMoveSensibility",void 0),a}();CameraInputTypes.FreeCameraGamepadInput=FreeCameraGamepadInput;var ArcRotateCameraGamepadInput=function(){function a(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}return Object.defineProperty(a.prototype,"invertYAxis",{get:function(){return this._yAxisScale!==1},set:function(i){this._yAxisScale=i?-1:1},enumerable:!1,configurable:!0}),a.prototype.attachControl=function(){var i=this,e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(function(o){o.type!==Gamepad.POSE_ENABLED&&(!i.gamepad||o.type===Gamepad.XBOX)&&(i.gamepad=o)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(function(o){i.gamepad===o&&(i.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.XBOX)},a.prototype.detachControl=function(i){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},a.prototype.checkInputs=function(){if(this.gamepad){var i=this.camera,e=this.gamepad.rightStick;if(e){if(e.x!=0){var o=e.x/this.gamepadRotationSensibility;o!=0&&Math.abs(o)>.005&&(i.inertialAlphaOffset+=o)}if(e.y!=0){var s=e.y/this.gamepadRotationSensibility*this._yAxisScale;s!=0&&Math.abs(s)>.005&&(i.inertialBetaOffset+=s)}}var c=this.gamepad.leftStick;if(c&&c.y!=0){var d=c.y/this.gamepadMoveSensibility;d!=0&&Math.abs(d)>.005&&(this.camera.inertialRadiusOffset-=d)}}},a.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},a.prototype.getSimpleName=function(){return"gamepad"},__decorate([serialize()],a.prototype,"gamepadRotationSensibility",void 0),__decorate([serialize()],a.prototype,"gamepadMoveSensibility",void 0),a}();CameraInputTypes.ArcRotateCameraGamepadInput=ArcRotateCameraGamepadInput;Object.defineProperty(Scene.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new GamepadManager(this);var a=this._getComponent(SceneComponentConstants.NAME_GAMEPAD);a||(a=new GamepadSystemSceneComponent(this),this._addComponent(a))}return this._gamepadManager},enumerable:!0,configurable:!0});FreeCameraInputsManager.prototype.addGamepad=function(){return this.add(new FreeCameraGamepadInput),this};ArcRotateCameraInputsManager.prototype.addGamepad=function(){return this.add(new ArcRotateCameraGamepadInput),this};var GamepadSystemSceneComponent=function(){function a(i){this.name=SceneComponentConstants.NAME_GAMEPAD,this.scene=i}return a.prototype.register=function(){this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)},a.prototype.rebuild=function(){},a.prototype.dispose=function(){var i=this.scene._gamepadManager;i&&(i.dispose(),this.scene._gamepadManager=null)},a.prototype._beforeCameraUpdate=function(){var i=this.scene._gamepadManager;i&&i._isMonitoring&&i._checkGamepadsStatus()},a}(),WebXRManagedOutputCanvasOptions=function(){function a(){}return a.GetDefaults=function(i){var e=new a;return e.canvasOptions={antialias:!0,depth:!0,stencil:i?i.isStencilEnable:!0,alpha:!0,multiview:!1,framebufferScaleFactor:1},e.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",e},a}(),WebXRManagedOutputCanvas=function(){function a(i,e){var o=this;if(e===void 0&&(e=WebXRManagedOutputCanvasOptions.GetDefaults()),this._options=e,this._canvas=null,this._engine=null,this.xrLayer=null,this.onXRLayerInitObservable=new Observable,this._engine=i.scene.getEngine(),this._engine.onDisposeObservable.addOnce(function(){o._engine=null}),e.canvasElement)this._setManagedOutputCanvas(e.canvasElement);else{var s=document.createElement("canvas");s.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(s)}i.onXRSessionInit.add(function(){o._addCanvas()}),i.onXRSessionEnded.add(function(){o._removeCanvas()})}return a.prototype.dispose=function(){this._removeCanvas(),this._setManagedOutputCanvas(null)},a.prototype.initializeXRLayerAsync=function(i){var e=this,o=function(){var s=new XRWebGLLayer(i,e.canvasContext,e._options.canvasOptions);return e.onXRLayerInitObservable.notifyObservers(s),s};return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(function(){},function(){Tools.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(function(){return e.xrLayer=o(),e.xrLayer}):(this.xrLayer=o(),Promise.resolve(this.xrLayer))},a.prototype._addCanvas=function(){var i=this;this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(function(e){i._setCanvasSize(!0,e)})},a.prototype._removeCanvas=function(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)},a.prototype._setCanvasSize=function(i,e){i===void 0&&(i=!0),e===void 0&&(e=this.xrLayer),!(!this._canvas||!this._engine)&&(i?e&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=e.framebufferWidth+"px",this._canvas.style.height=e.framebufferHeight+"px"):this._engine.setSize(e.framebufferWidth,e.framebufferHeight)):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))},a.prototype._setManagedOutputCanvas=function(i){this._removeCanvas(),i?(this._originalCanvasSize={width:i.offsetWidth,height:i.offsetHeight},this._canvas=i,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)},a}(),WebXRSessionManager=function(){function a(i){var e=this;this.scene=i,this._sessionEnded=!1,this._baseLayer=null,this._renderTargetTextures=[],this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new Observable,this.onXRReferenceSpaceChanged=new Observable,this.onXRSessionEnded=new Observable,this.onXRSessionInit=new Observable,this._engine=i.getEngine(),this._engine.onDisposeObservable.addOnce(function(){e._engine=null})}return Object.defineProperty(a.prototype,"referenceSpace",{get:function(){return this._referenceSpace},set:function(i){this._referenceSpace=i,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"sessionMode",{get:function(){return this._sessionMode},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this._sessionEnded||this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear()},a.prototype.exitXRAsync=function(){return this.session&&!this._sessionEnded?(this._sessionEnded=!0,this.session.end().catch(function(i){Logger$2.Warn("Could not end XR session.")})):Promise.resolve()},a.prototype.getRenderTargetTextureForEye=function(i){return this._rttProvider.getRenderTargetForEye(i)},a.prototype.getWebXRRenderTarget=function(i){var e=this.scene.getEngine();return this._xrNavigator.xr.native?this._xrNavigator.xr.getWebXRRenderTarget(e):(i=i||WebXRManagedOutputCanvasOptions.GetDefaults(e),i.canvasElement=i.canvasElement||e.getRenderingCanvas()||void 0,new WebXRManagedOutputCanvas(this,i))},a.prototype.initializeAsync=function(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")},a.prototype.initializeSessionAsync=function(i,e){var o=this;return i===void 0&&(i="immersive-vr"),e===void 0&&(e={}),this._xrNavigator.xr.requestSession(i,e).then(function(s){return o.session=s,o._sessionMode=i,o.onXRSessionInit.notifyObservers(s),o._sessionEnded=!1,o.session.addEventListener("end",function(){o._sessionEnded=!0,o.onXRSessionEnded.notifyObservers(null),o._rttProvider=null,o._engine&&(o._engine.framebufferDimensionsObject=null,o._engine.restoreDefaultFramebuffer(),o._engine.customAnimationFrameRequester=null,o._engine._renderLoop()),o.isNative&&(o._renderTargetTextures.forEach(function(c){return c.dispose()}),o._renderTargetTextures.length=0)},{once:!0}),o.session})},a.prototype.isSessionSupportedAsync=function(i){return a.IsSessionSupportedAsync(i)},a.prototype.resetReferenceSpace=function(){this.referenceSpace=this.baseReferenceSpace},a.prototype.runXRRenderLoop=function(){var i=this;if(!(this._sessionEnded||!this._engine)){if(this._engine.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:function(d,_){i._sessionEnded||!i._engine||(i.currentFrame=_,i.currentTimestamp=d,_&&(i._engine.framebufferDimensionsObject=i._baseLayer,i.onXRFrameObservable.notifyObservers(_),i._engine._renderLoop(),i._engine.framebufferDimensionsObject=null))}},this._xrNavigator.xr.native)this._rttProvider=this._xrNavigator.xr.getNativeRenderTargetProvider(this.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this));else{var e,o,s,c;this._rttProvider={getRenderTargetForEye:function(){var d=i._baseLayer;return(d.framebufferWidth!==o||d.framebufferHeight!==s||d.framebuffer!==c)&&(e=i._createRenderTargetTexture(d.framebufferWidth,d.framebufferHeight,d.framebuffer),o=d.framebufferWidth,s=d.framebufferHeight,c=d.framebuffer),e}},this._engine.framebufferDimensionsObject=this._baseLayer}typeof window!="undefined"&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop()}},a.prototype.setReferenceSpaceTypeAsync=function(i){var e=this;return i===void 0&&(i="local-floor"),this.session.requestReferenceSpace(i).then(function(o){return o},function(o){return Logger$2.Error("XR.requestReferenceSpace failed for the following reason: "),Logger$2.Error(o),Logger$2.Log('Defaulting to universally-supported "viewer" reference space type.'),e.session.requestReferenceSpace("viewer").then(function(s){var c=new XRRigidTransform({x:0,y:-e.defaultHeightCompensation,z:0});return s.getOffsetReferenceSpace(c)},function(s){throw Logger$2.Error(s),'XR initialization failed: required "viewer" reference space type not supported.'})}).then(function(o){return e.session.requestReferenceSpace("viewer").then(function(s){return e.viewerReferenceSpace=s,o})}).then(function(o){return e.referenceSpace=e.baseReferenceSpace=o,e.referenceSpace})},a.prototype.updateRenderStateAsync=function(i){return i.baseLayer&&(this._baseLayer=i.baseLayer),this.session.updateRenderState(i)},a.IsSessionSupportedAsync=function(i){if(!navigator.xr)return Promise.resolve(!1);var e=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return e?e.call(navigator.xr,i).then(function(o){var s=typeof o=="undefined"?!0:o;return Promise.resolve(s)}).catch(function(o){return Logger$2.Warn(o),Promise.resolve(!1)}):Promise.resolve(!1)},Object.defineProperty(a.prototype,"isNative",{get:function(){var i;return(i=this._xrNavigator.xr.native)!==null&&i!==void 0?i:!1},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"currentFrameRate",{get:function(){var i;return(i=this.session)===null||i===void 0?void 0:i.frameRate},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"supportedFrameRates",{get:function(){var i;return(i=this.session)===null||i===void 0?void 0:i.supportedFrameRates},enumerable:!1,configurable:!0}),a.prototype.updateTargetFrameRate=function(i){return this.session.updateTargetFrameRate(i)},Object.defineProperty(a.prototype,"isFixedFoveationSupported",{get:function(){var i;return!!(!((i=this._baseLayer)===null||i===void 0)&&i.fixedFoveation)!==null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"fixedFoveation",{get:function(){var i;return((i=this._baseLayer)===null||i===void 0?void 0:i.fixedFoveation)!==void 0?this._baseLayer.fixedFoveation:null},set:function(i){var e,o=Math.max(0,Math.min(1,i||0));((e=this._baseLayer)===null||e===void 0?void 0:e.fixedFoveation)!==void 0&&(this._baseLayer.fixedFoveation=o)},enumerable:!1,configurable:!0}),a.prototype._createRenderTargetTexture=function(i,e,o){if(!this._engine)throw new Error("Engine is disposed");var s=new InternalTexture(this._engine,InternalTextureSource.Unknown,!0);s.width=i,s.height=e;var c=new RenderTargetTexture("XR renderTargetTexture",{width:i,height:e},this.scene),d=c.renderTarget;return d.setTexture(s,0),d._framebuffer=o,c._texture=s,c.disableRescaling(),c.skipInitialClear=!0,this._renderTargetTextures.push(c),c},a.prototype._destroyRenderTargetTexture=function(i){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(i),1),i.dispose()},a}(),WebXRState;(function(a){a[a.ENTERING_XR=0]="ENTERING_XR",a[a.EXITING_XR=1]="EXITING_XR",a[a.IN_XR=2]="IN_XR",a[a.NOT_IN_XR=3]="NOT_IN_XR"})(WebXRState||(WebXRState={}));var WebXRTrackingState;(function(a){a[a.NOT_TRACKING=0]="NOT_TRACKING",a[a.TRACKING_LOST=1]="TRACKING_LOST",a[a.TRACKING=2]="TRACKING"})(WebXRTrackingState||(WebXRTrackingState={}));var VRExperienceHelperGazer=function(){function a(i,e){if(e===void 0&&(e=null),this.scene=i,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=a._idCounter++,e)this._gazeTracker=e.clone("gazeTracker");else{this._gazeTracker=CreateTorus("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},i),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var o=new StandardMaterial("targetMat",i);o.specularColor=Color3.Black(),o.emissiveColor=new Color3(.7,.7,.7),o.backFaceCulling=!1,this._gazeTracker.material=o}}return a.prototype._getForwardRay=function(i){return new Ray(Vector3.Zero(),new Vector3(0,0,i))},a.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},a.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},a.prototype._activatePointer=function(){this._activePointer=!0},a.prototype._deactivatePointer=function(){this._activePointer=!1},a.prototype._updatePointerDistance=function(i){},a.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},a._idCounter=0,a}(),VRExperienceHelperControllerGazer=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,o,s)||this;c.webVRController=e,c._laserPointer=CreateCylinder("laserPointer",{updatable:!1,height:1,diameterTop:.004,diameterBottom:2e-4,tessellation:20,subdivisions:1},o);var d=new StandardMaterial("laserPointerMat",o);if(d.emissiveColor=new Color3(.7,.7,.7),d.alpha=.6,c._laserPointer.material=d,c._laserPointer.rotation.x=Math.PI/2,c._laserPointer.position.z=-.5,c._laserPointer.isVisible=!1,c._laserPointer.isPickable=!1,!e.mesh){var _=new Mesh("preloadControllerMesh",o),b=new Mesh(PoseEnabledController.POINTING_POSE,o);b.rotation.x=-.7,_.addChild(b),e.attachToMesh(_)}return c._setLaserPointerParent(e.mesh),c._meshAttachedObserver=e._meshAttachedObservable.add(function(k){c._setLaserPointerParent(k)}),c}return i.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},i.prototype._activatePointer=function(){a.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},i.prototype._deactivatePointer=function(){a.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},i.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},i.prototype._setLaserPointerLightingDisabled=function(e){this._laserPointer.material.disableLighting=e},i.prototype._setLaserPointerParent=function(e){var o=function(_){_.isPickable=!1,_.getChildMeshes().forEach(function(b){o(b)})};o(e);var s=e.getChildren(void 0,!1),c=e;this.webVRController._pointingPoseNode=null;for(var d=0;d<s.length;d++)if(s[d].name&&s[d].name.indexOf(PoseEnabledController.POINTING_POSE)>=0){c=s[d],this.webVRController._pointingPoseNode=c;break}this._laserPointer.parent=c},i.prototype._updatePointerDistance=function(e){e===void 0&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},i}(VRExperienceHelperGazer),VRExperienceHelperCameraGazer=function(a){__extends(i,a);function i(e,o){var s=a.call(this,o)||this;return s.getCamera=e,s}return i.prototype._getForwardRay=function(e){var o=this.getCamera();return o?o.getForwardRay(e):new Ray(Vector3.Zero(),Vector3.Forward())},i}(VRExperienceHelperGazer),VRExperienceHelper=function(){function a(i,e){var o=this;e===void 0&&(e={}),this.webVROptions=e,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new Observable,this.onAfterEnteringVRObservable=new Observable,this.onExitingVRObservable=new Observable,this.onControllerMeshLoadedObservable=new Observable,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=a.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new Vector3(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new Vector3(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new Color3(.7,.7,.7),this._laserColor=new Color3(.7,.7,.7),this._pickedLaserColor=new Color3(.2,.2,1),this._pickedGazeColor=new Color3(0,0,1),this.onNewMeshSelected=new Observable,this.onMeshSelectedWithController=new Observable,this.onNewMeshPicked=new Observable,this.onBeforeCameraTeleport=new Observable,this.onAfterCameraTeleport=new Observable,this.onSelectedMeshUnselected=new Observable,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=function(){o.moveButtonToBottomRight(),o._fullscreenVRpresenting&&o._webVRready&&o.exitVR()},this._onFullscreenChange=function(){var d=document;d.fullscreen!==void 0?o._fullscreenVRpresenting=document.fullscreen:d.mozFullScreen!==void 0?o._fullscreenVRpresenting=d.mozFullScreen:d.webkitIsFullScreen!==void 0?o._fullscreenVRpresenting=d.webkitIsFullScreen:d.msIsFullScreen!==void 0?o._fullscreenVRpresenting=d.msIsFullScreen:document.msFullscreenElement!==void 0&&(o._fullscreenVRpresenting=document.msFullscreenElement),!o._fullscreenVRpresenting&&o._inputElement&&(o.exitVR(),!o._useCustomVRButton&&o._btnVR&&(o._btnVR.style.top=o._inputElement.offsetTop+o._inputElement.offsetHeight-70+"px",o._btnVR.style.left=o._inputElement.offsetLeft+o._inputElement.offsetWidth-100+"px",o.updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this.beforeRender=function(){o._leftController&&o._leftController._activePointer&&o._castRayAndSelectObject(o._leftController),o._rightController&&o._rightController._activePointer&&o._castRayAndSelectObject(o._rightController),o._noControllerIsActive&&(o._scene.getEngine().isPointerLock||o.enableGazeEvenWhenNoPointerLock)?o._castRayAndSelectObject(o._cameraGazer):o._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(d){if(d.type!==Gamepad.POSE_ENABLED)d.leftStick&&d.onleftstickchanged(function(k){o._teleportationInitialized&&o.teleportationEnabled&&(!o._leftController&&!o._rightController||o._leftController&&!o._leftController._activePointer&&o._rightController&&!o._rightController._activePointer)&&(o._checkTeleportWithRay(k,o._cameraGazer),o._checkTeleportBackwards(k,o._cameraGazer))}),d.rightStick&&d.onrightstickchanged(function(k){o._teleportationInitialized&&o._checkRotate(k,o._cameraGazer)}),d.type===Gamepad.XBOX&&(d.onbuttondown(function(k){o._interactionsEnabled&&k===Xbox360Button.A&&o._cameraGazer._selectionPointerDown()}),d.onbuttonup(function(k){o._interactionsEnabled&&k===Xbox360Button.A&&o._cameraGazer._selectionPointerUp()}));else{var _=d,b=new VRExperienceHelperControllerGazer(_,o._scene,o._cameraGazer._gazeTracker);_.hand==="right"||o._leftController&&o._leftController.webVRController!=_?o._rightController=b:o._leftController=b,o._tryEnableInteractionOnController(b)}},this._tryEnableInteractionOnController=function(d){o._interactionsRequested&&!d._interactionsEnabled&&o._enableInteractionOnController(d),o._teleportationRequested&&!d._teleportationEnabled&&o._enableTeleportationOnController(d)},this._onNewGamepadDisconnected=function(d){d instanceof WebVRController&&(d.hand==="left"&&o._leftController!=null&&(o._leftController.dispose(),o._leftController=null),d.hand==="right"&&o._rightController!=null&&(o._rightController.dispose(),o._rightController=null))},this._workingVector=Vector3.Zero(),this._workingQuaternion=Quaternion.Identity(),this._workingMatrix=Matrix.Identity(),Logger$2.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=i,this._inputElement=i.getEngine().getInputElement();var s="getVRDisplays"in navigator;if(!s&&e.useXR===void 0&&(e.useXR=!0),e.createFallbackVRDeviceOrientationFreeCamera===void 0&&(e.createFallbackVRDeviceOrientationFreeCamera=!0),e.createDeviceOrientationCamera===void 0&&(e.createDeviceOrientationCamera=!0),e.laserToggle===void 0&&(e.laserToggle=!0),e.defaultHeight===void 0&&(e.defaultHeight=1.7),e.useCustomVRButton&&(this._useCustomVRButton=!0,e.customVRButton&&(this._btnVR=e.customVRButton)),e.rayLength&&(this._rayLength=e.rayLength),this._defaultHeight=e.defaultHeight,e.positionScale&&(this._rayLength*=e.positionScale,this._defaultHeight*=e.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new Vector3(0,this._defaultHeight,0),e.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),i),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof TargetCamera&&this._scene.activeCamera.rotation)){var c=this._scene.activeCamera;c.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(c.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(c.rotation.y,c.rotation.x,c.rotation.z)),this._deviceOrientationCamera.rotation=c.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then(function(d){d?(Logger$2.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),i.createDefaultXRExperienceAsync({floorMeshes:e.floorMeshes||[]}).then(function(_){o.xr=_,o.xrTestDone=!0,o._cameraGazer=new VRExperienceHelperCameraGazer(function(){return o.xr.baseExperience.camera},i),o.xr.baseExperience.onStateChangedObservable.add(function(b){switch(b){case WebXRState.ENTERING_XR:o.onEnteringVRObservable.notifyObservers(o),o._interactionsEnabled||o.xr.pointerSelection.detach(),o.xr.pointerSelection.displayLaserPointer=o._displayLaserPointer;break;case WebXRState.EXITING_XR:o.onExitingVRObservable.notifyObservers(o),o._scene.getEngine().resize();break;case WebXRState.IN_XR:o._hasEnteredVR=!0;break;case WebXRState.NOT_IN_XR:o._hasEnteredVR=!1;break}})})):o.completeVRInit(i,e)}):this.completeVRInit(i,e)}return Object.defineProperty(a.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(i){i&&(i.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=i)},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(i){i&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._gazeTracker.dispose(),this._cameraGazer._gazeTracker=i,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"leftControllerGazeTrackerMesh",{get:function(){return this._leftController?this._leftController._gazeTracker:null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"rightControllerGazeTrackerMesh",{get:function(){return this._rightController?this._rightController._gazeTracker:null},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(i){this._displayGaze=i,i||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(i){this._displayLaserPointer=i,i?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"vrButton",{get:function(){return this._btnVR},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"_teleportationRequestInitiated",{get:function(){var i=this._cameraGazer._teleportationRequestInitiated||this._leftController!==null&&this._leftController._teleportationRequestInitiated||this._rightController!==null&&this._rightController._teleportationRequestInitiated;return i},enumerable:!1,configurable:!0}),a.prototype.completeVRInit=function(i,e){var o=this;if(this.xrTestDone=!0,e.createFallbackVRDeviceOrientationFreeCamera&&(e.useMultiview&&(e.vrDeviceOrientationCameraMetrics||(e.vrDeviceOrientationCameraMetrics=VRCameraMetrics.GetDefault()),e.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene,!0,e.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new WebVRFreeCamera("WebVRHelper",this._position,this._scene,e),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new VRExperienceHelperCameraGazer(function(){return o.currentVRCamera},i),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var s=window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png",c=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+s+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";c+=".babylonVRicon.vrdisplaypresenting { display: none; }";var d=document.createElement("style");d.appendChild(document.createTextNode(c)),document.getElementsByTagName("head")[0].appendChild(d),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",function(){o.isInVRMode?o._scene.getEngine().disableVR():o.enterVR()});var _=this._scene.getEngine().getHostWindow();!_||(_.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),document.onmsfullscreenchange=this._onFullscreenChange,e.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add(function(b){b.vrDisplay&&o.displayVRButton()}),this._onKeyDown=function(b){b.keyCode===27&&o.isInVRMode&&o.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(function(){o._hasEnteredVR&&o.exitVROnDoubleTap&&(o.exitVR(),o._fullscreenVRpresenting&&o._scene.getEngine().exitFullscreen())},PointerEventTypes.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(b){return o.onVRDisplayChanged(b)},this._onVrDisplayPresentChange=function(){return o.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){o._webVRrequesting=!0,o.updateButtonVisibility()},this._onVRRequestPresentComplete=function(){o._webVRrequesting=!1,o.updateButtonVisibility()},i.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),i.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),i.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),_.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),i.onDisposeObservable.add(function(){o.dispose()}),this._webVRCamera.onControllerMeshLoadedObservable.add(function(b){return o._onDefaultMeshLoaded(b)}),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new CircleEase,this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,i.onPointerObservable.add(function(b){o._interactionsEnabled&&i.activeCamera===o.vrDeviceOrientationCamera&&b.event.pointerType==="mouse"&&(b.type===PointerEventTypes.POINTERDOWN?o._cameraGazer._selectionPointerDown():b.type===PointerEventTypes.POINTERUP&&o._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))},a.prototype._onDefaultMeshLoaded=function(i){this._leftController&&this._leftController.webVRController==i&&i.mesh&&this._leftController._setLaserPointerParent(i.mesh),this._rightController&&this._rightController.webVRController==i&&i.mesh&&this._rightController._setLaserPointerParent(i.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(i)}catch(e){Logger$2.Warn("Error in your custom logic onControllerMeshLoaded: "+e)}},Object.defineProperty(a.prototype,"isInVRMode",{get:function(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===WebXRState.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!1,configurable:!0}),a.prototype.onVrDisplayPresentChange=function(){var i=this._scene.getEngine().getVRDevice();if(i){var e=this._webVRpresenting;this._webVRpresenting=i.isPresenting,e&&!this._webVRpresenting&&this.exitVR()}else Logger$2.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},a.prototype.onVRDisplayChanged=function(i){this._webVRsupported=i.vrSupported,this._webVRready=!!i.vrDisplay,this._webVRpresenting=i.vrDisplay&&i.vrDisplay.isPresenting,this.updateButtonVisibility()},a.prototype.moveButtonToBottomRight=function(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){var i=this._inputElement.getBoundingClientRect();this._btnVR.style.top=i.top+i.height-70+"px",this._btnVR.style.left=i.left+i.width-100+"px"}},a.prototype.displayVRButton=function(){!this._useCustomVRButton&&!this._btnVRDisplayed&&this._btnVR&&(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},a.prototype.updateButtonVisibility=function(){!this._btnVR||this._useCustomVRButton||(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))},a.prototype.enterVR=function(){var i=this;if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(d){Logger$2.Warn("Error in your custom logic onEnteringVR: "+d)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){var e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,o=Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y,s=o-e,c=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=Quaternion.FromEulerAngles(0,c+s,0)}this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)}this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._scene.getEngine().onVRRequestPresentComplete.addOnce(function(d){i.onAfterEnteringVRObservable.notifyObservers({success:d})}),this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this.updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(function(){i.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this.beforeRender),this._displayLaserPointer&&[this._leftController,this._rightController].forEach(function(d){d&&d._activatePointer()}),this._hasEnteredVR=!0)},a.prototype.exitVR=function(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){Logger$2.Warn("Error in your custom logic onExitingVR: "+e)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this.updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this.beforeRender),this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1)),this._scene.getEngine().resize(),[this._leftController,this._rightController].forEach(function(e){e&&e._deactivatePointer()}),this._hasEnteredVR=!1;var i=this._scene.getEngine();i._onVrDisplayPresentChange&&i._onVrDisplayPresentChange()}},Object.defineProperty(a.prototype,"position",{get:function(){return this._position},set:function(i){this._position=i,this._scene.activeCamera&&(this._scene.activeCamera.position=i)},enumerable:!1,configurable:!0}),a.prototype.enableInteractions=function(){var i=this;if(!this._interactionsEnabled){if(this._interactionsRequested=!0,this.xr){this.xr.baseExperience.state===WebXRState.IN_XR&&this.xr.pointerSelection.attach();return}this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=function(e){return e.isVisible&&(e.isPickable||e.name===i._floorMeshName)},this.meshSelectionPredicate=function(){return!0},this._raySelectionPredicate=function(e){return i._isTeleportationFloor(e)||e.name.indexOf("gazeTracker")===-1&&e.name.indexOf("teleportationTarget")===-1&&e.name.indexOf("torusTeleportation")===-1?i.raySelectionPredicate(e):!1},this._interactionsEnabled=!0}},Object.defineProperty(a.prototype,"_noControllerIsActive",{get:function(){return!(this._leftController&&this._leftController._activePointer)&&!(this._rightController&&this._rightController._activePointer)},enumerable:!1,configurable:!0}),a.prototype._isTeleportationFloor=function(i){for(var e=0;e<this._floorMeshesCollection.length;e++)if(this._floorMeshesCollection[e].id===i.id)return!0;return!!(this._floorMeshName&&i.name===this._floorMeshName)},a.prototype.addFloorMesh=function(i){!this._floorMeshesCollection||this._floorMeshesCollection.indexOf(i)>-1||this._floorMeshesCollection.push(i)},a.prototype.removeFloorMesh=function(i){if(!!this._floorMeshesCollection){var e=this._floorMeshesCollection.indexOf(i);e!==-1&&this._floorMeshesCollection.splice(e,1)}},a.prototype.enableTeleportation=function(i){var e=this;if(i===void 0&&(i={}),!this._teleportationInitialized){if(this._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(i.floorMeshes||i.floorMeshName)){var o=i.floorMeshes||[];if(!o.length){var s=this._scene.getMeshByName(i.floorMeshName);s&&o.push(s)}if(this.xr){o.forEach(function(_){e.xr.teleportation.addFloorMesh(_)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}else if(!this.xrTestDone){var c=function(){e.xrTestDone&&(e._scene.unregisterBeforeRender(c),e.xr?e.xr.teleportation.attached||e.xr.teleportation.attach():e.enableTeleportation(i))};this._scene.registerBeforeRender(c);return}}i.floorMeshName&&(this._floorMeshName=i.floorMeshName),i.floorMeshes&&(this._floorMeshesCollection=i.floorMeshes),i.teleportationMode&&(this._teleportationMode=i.teleportationMode),i.teleportationTime&&i.teleportationTime>0&&(this._teleportationTime=i.teleportationTime),i.teleportationSpeed&&i.teleportationSpeed>0&&(this._teleportationSpeed=i.teleportationSpeed),i.easingFunction!==void 0&&(this._teleportationEasing=i.easingFunction),this._leftController!=null&&this._enableTeleportationOnController(this._leftController),this._rightController!=null&&this._enableTeleportationOnController(this._rightController);var d=new ImageProcessingConfiguration;d.vignetteColor=new Color4(0,0,0,0),d.vignetteEnabled=!0,this._postProcessMove=new ImageProcessingPostProcess("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,d),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},a.prototype._enableInteractionOnController=function(i){var e=this,o=i.webVRController.mesh;o&&(i._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&i._activatePointer(),this.webVROptions.laserToggle&&i.webVRController.onMainButtonStateChangedObservable.add(function(s){e._displayLaserPointer&&s.value===1&&(i._activePointer?i._deactivatePointer():i._activatePointer(),e.displayGaze&&(i._gazeTracker.isVisible=i._activePointer))}),i.webVRController.onTriggerStateChangedObservable.add(function(s){var c=i;e._noControllerIsActive&&(c=e._cameraGazer),c._pointerDownOnMeshAsked?s.value<e._padSensibilityDown&&c._selectionPointerUp():s.value>e._padSensibilityUp&&c._selectionPointerDown()}))},a.prototype._checkTeleportWithRay=function(i,e){this._teleportationRequestInitiated&&!e._teleportationRequestInitiated||(e._teleportationRequestInitiated?Math.sqrt(i.y*i.y+i.x*i.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),e._teleportationRequestInitiated=!1):i.y<-this._padSensibilityUp&&e._dpadPressed&&(e._activatePointer(),e._teleportationRequestInitiated=!0))},a.prototype._checkRotate=function(i,e){e._teleportationRequestInitiated||(e._rotationLeftAsked?i.x>-this._padSensibilityDown&&(e._rotationLeftAsked=!1):i.x<-this._padSensibilityUp&&e._dpadPressed&&(e._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),e._rotationRightAsked?i.x<this._padSensibilityDown&&(e._rotationRightAsked=!1):i.x>this._padSensibilityUp&&e._dpadPressed&&(e._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},a.prototype._checkTeleportBackwards=function(i,e){if(!e._teleportationRequestInitiated)if(i.y>this._padSensibilityUp&&e._dpadPressed){if(!e._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var o=Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),s=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(o=this.currentVRCamera.deviceRotationQuaternion,s=this.currentVRCamera.devicePosition),o.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,Quaternion.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var c=new Ray(s,this._workingVector),d=this._scene.pickWithRay(c,this._raySelectionPredicate);d&&d.pickedPoint&&d.pickedMesh&&this._isTeleportationFloor(d.pickedMesh)&&d.distance<5&&this.teleportCamera(d.pickedPoint),e._teleportationBackRequestInitiated=!0}}else e._teleportationBackRequestInitiated=!1},a.prototype._enableTeleportationOnController=function(i){var e=this,o=i.webVRController.mesh;o&&(i._interactionsEnabled||this._enableInteractionOnController(i),i._interactionsEnabled=!0,i._teleportationEnabled=!0,i.webVRController.controllerType===PoseEnabledControllerType.VIVE&&(i._dpadPressed=!1,i.webVRController.onPadStateChangedObservable.add(function(s){i._dpadPressed=s.pressed,i._dpadPressed||(i._rotationLeftAsked=!1,i._rotationRightAsked=!1,i._teleportationBackRequestInitiated=!1)})),i.webVRController.onPadValuesChangedObservable.add(function(s){e.teleportationEnabled&&(e._checkTeleportBackwards(s,i),e._checkTeleportWithRay(s,i)),e._checkRotate(s,i)}))},a.prototype._createTeleportationCircles=function(){this._teleportationTarget=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;var i=512,e=new DynamicTexture("DynamicTexture",i,this._scene,!0);e.hasAlpha=!0;var o=e.getContext(),s=i/2,c=i/2,d=200;o.beginPath(),o.arc(s,c,d,0,2*Math.PI,!1),o.fillStyle=this._teleportationFillColor,o.fill(),o.lineWidth=10,o.strokeStyle=this._teleportationBorderColor,o.stroke(),o.closePath(),e.update();var _=new StandardMaterial("TextPlaneMaterial",this._scene);_.diffuseTexture=e,this._teleportationTarget.material=_;var b=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);b.isPickable=!1,b.parent=this._teleportationTarget;var k=new Animation("animationInnerCircle","position.y",30,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE),j=[];j.push({frame:0,value:0}),j.push({frame:30,value:.4}),j.push({frame:60,value:0}),k.setKeys(j);var $=new SineEase;$.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),k.setEasingFunction($),b.animations=[],b.animations.push(k),this._scene.beginAnimation(b,0,60,!0),this._hideTeleportationTarget()},a.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},a.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},a.prototype._rotateCamera=function(i){var e=this;if(this.currentVRCamera instanceof FreeCamera){i?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];var o=Quaternion.FromRotationMatrix(Matrix.RotationY(Math.PI/4*this._rotationAngle)),s=new Animation("animationRotation","rotationQuaternion",90,Animation.ANIMATIONTYPE_QUATERNION,Animation.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),c.push({frame:6,value:o}),s.setKeys(c),s.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];var d=new Animation("animationPP","vignetteWeight",90,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT),_=[];_.push({frame:0,value:0}),_.push({frame:3,value:4}),_.push({frame:6,value:0}),d.setKeys(_),d.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(d);var b=new Animation("animationPP2","vignetteStretch",90,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT),k=[];k.push({frame:0,value:0}),k.push({frame:3,value:10}),k.push({frame:6,value:0}),b.setKeys(k),b.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(b),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,function(){e._webVRCamera.detachPostProcess(e._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},a.prototype._moveTeleportationSelectorTo=function(i,e,o){if(i.pickedPoint){e._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(i.pickedPoint),this._teleportationTarget.position.copyFrom(i.pickedPoint));var s=this._convertNormalToDirectionOfRay(i.getNormal(!0,!1),o);if(s){var c=Vector3.Cross(Axis.Y,s),d=Vector3.Cross(s,c);Vector3.RotationFromAxisToRef(d,s,c,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},a.prototype.teleportCamera=function(i){var e=this;if(this.currentVRCamera instanceof FreeCamera){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),i.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(i),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector);var o=90,s,c;if(this._teleportationMode==a.TELEPORTATIONMODE_CONSTANTSPEED){c=o;var d=Vector3.Distance(this.currentVRCamera.position,this._workingVector);s=this._teleportationSpeed/d}else c=Math.round(this._teleportationTime*o/1e3),s=1;this.currentVRCamera.animations=[];var _=new Animation("animationCameraTeleportation","position",o,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT),b=[{frame:0,value:this.currentVRCamera.position},{frame:c,value:this._workingVector}];_.setKeys(b),_.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(_),this._postProcessMove.animations=[];var k=Math.round(c/2),j=new Animation("animationPP","vignetteWeight",o,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT),$=[];$.push({frame:0,value:0}),$.push({frame:k,value:8}),$.push({frame:c,value:0}),j.setKeys($),this._postProcessMove.animations.push(j);var _e=new Animation("animationPP2","vignetteStretch",o,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT),et=[];et.push({frame:0,value:0}),et.push({frame:k,value:10}),et.push({frame:c,value:0}),_e.setKeys(et),this._postProcessMove.animations.push(_e),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,c,!1,s,function(){e._webVRCamera.detachPostProcess(e._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,c,!1,s,function(){e.onAfterCameraTeleport.notifyObservers(e._workingVector)}),this._hideTeleportationTarget()}},a.prototype._convertNormalToDirectionOfRay=function(i,e){if(i){var o=Math.acos(Vector3.Dot(i,e.direction));o<Math.PI/2&&i.scaleInPlace(-1)}return i},a.prototype._castRayAndSelectObject=function(i){if(this.currentVRCamera instanceof FreeCamera){var e=i._getForwardRay(this._rayLength),o=this._scene.pickWithRay(e,this._raySelectionPredicate);if(o&&this._scene.simulatePointerMove(o,{pointerId:i._id}),i._currentHit=o,o&&o.pickedPoint){if(this._displayGaze){var s=1;i._gazeTracker.isVisible=!0,i._isActionableMesh&&(s=3),this.updateGazeTrackerScale&&(i._gazeTracker.scaling.x=o.distance*s,i._gazeTracker.scaling.y=o.distance*s,i._gazeTracker.scaling.z=o.distance*s);var c=this._convertNormalToDirectionOfRay(o.getNormal(),e),d=.002;if(c){var _=Vector3.Cross(Axis.Y,c),b=Vector3.Cross(c,_);Vector3.RotationFromAxisToRef(b,c,_,i._gazeTracker.rotation)}i._gazeTracker.position.copyFrom(o.pickedPoint),i._gazeTracker.position.x<0?i._gazeTracker.position.x+=d:i._gazeTracker.position.x-=d,i._gazeTracker.position.y<0?i._gazeTracker.position.y+=d:i._gazeTracker.position.y-=d,i._gazeTracker.position.z<0?i._gazeTracker.position.z+=d:i._gazeTracker.position.z-=d}i._updatePointerDistance(o.distance)}else i._updatePointerDistance(),i._gazeTracker.isVisible=!1;if(o&&o.pickedMesh){if(this._teleportationInitialized&&this._isTeleportationFloor(o.pickedMesh)&&o.pickedPoint){i._currentMeshSelected&&!this._isTeleportationFloor(i._currentMeshSelected)&&this._notifySelectedMeshUnselected(i._currentMeshSelected),i._currentMeshSelected=null,i._teleportationRequestInitiated&&this._moveTeleportationSelectorTo(o,i,e);return}if(o.pickedMesh!==i._currentMeshSelected)if(this.meshSelectionPredicate(o.pickedMesh)){this.onNewMeshPicked.notifyObservers(o),i._currentMeshSelected=o.pickedMesh,o.pickedMesh.isPickable&&o.pickedMesh.actionManager?(this.changeGazeColor(this._pickedGazeColor),this.changeLaserColor(this._pickedLaserColor),i._isActionableMesh=!0):(this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor),i._isActionableMesh=!1);try{this.onNewMeshSelected.notifyObservers(o.pickedMesh);var k=i;k.webVRController&&this.onMeshSelectedWithController.notifyObservers({mesh:o.pickedMesh,controller:k.webVRController})}catch(j){Logger$2.Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: "+j)}}else this._notifySelectedMeshUnselected(i._currentMeshSelected),i._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}else this._notifySelectedMeshUnselected(i._currentMeshSelected),i._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}},a.prototype._notifySelectedMeshUnselected=function(i){i&&this.onSelectedMeshUnselected.notifyObservers(i)},a.prototype.setLaserColor=function(i,e){e===void 0&&(e=this._pickedLaserColor),this._laserColor=i,this._pickedLaserColor=e},a.prototype.setLaserLightingState=function(i){i===void 0&&(i=!0),this._leftController&&this._leftController._setLaserPointerLightingDisabled(!i),this._rightController&&this._rightController._setLaserPointerLightingDisabled(!i)},a.prototype.setGazeColor=function(i,e){e===void 0&&(e=this._pickedGazeColor),this._gazeColor=i,this._pickedGazeColor=e},a.prototype.changeLaserColor=function(i){!this.updateControllerLaserColor||(this._leftController&&this._leftController._setLaserPointerColor(i),this._rightController&&this._rightController._setLaserPointerColor(i))},a.prototype.changeGazeColor=function(i){!this.updateGazeTrackerColor||!this._cameraGazer._gazeTracker.material||(this._cameraGazer._gazeTracker.material.emissiveColor=i,this._leftController&&(this._leftController._gazeTracker.material.emissiveColor=i),this._rightController&&(this._rightController._gazeTracker.material.emissiveColor=i))},a.prototype.dispose=function(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._webVRCamera&&this._webVRCamera.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._leftController&&this._leftController.dispose(),this._rightController&&this._rightController.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection=[],document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.onmsfullscreenchange=null,this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged),this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart),this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected),this._scene.unregisterBeforeRender(this.beforeRender)},a.prototype.getClassName=function(){return"VRExperienceHelper"},a.TELEPORTATIONMODE_CONSTANTTIME=0,a.TELEPORTATIONMODE_CONSTANTSPEED=1,a}(),_ENVTextureLoader=function(){function a(){this.supportCascades=!1}return a.prototype.canLoad=function(i){return EndsWith(i,".env")},a.prototype.loadCubeData=function(i,e,o,s,c){if(!Array.isArray(i)){var d=GetEnvInfo(i);if(d){e.width=d.width,e.height=d.width;try{UploadEnvSpherical(e,d),UploadEnvLevelsAsync(e,i,d).then(function(){e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},function(_){c==null||c("Can not upload environment levels",_)})}catch(_){c==null||c("Can not upload environment file",_)}}else c&&c("Can not parse the environment file",null)}},a.prototype.loadData=function(i,e,o){throw".env not supported in 2d."},a}();Engine._TextureLoaders.push(new _ENVTextureLoader);var KhronosTextureContainer=function(){function a(i,e,o,s){if(this.data=i,this.isInvalid=!1,!a.IsValid(i)){this.isInvalid=!0,Logger$2.Error("texture missing KTX identifier");return}var c=Uint32Array.BYTES_PER_ELEMENT,d=new DataView(this.data.buffer,this.data.byteOffset+12,13*c),_=d.getUint32(0,!0),b=_===67305985;if(this.glType=d.getUint32(1*c,b),this.glTypeSize=d.getUint32(2*c,b),this.glFormat=d.getUint32(3*c,b),this.glInternalFormat=d.getUint32(4*c,b),this.glBaseInternalFormat=d.getUint32(5*c,b),this.pixelWidth=d.getUint32(6*c,b),this.pixelHeight=d.getUint32(7*c,b),this.pixelDepth=d.getUint32(8*c,b),this.numberOfArrayElements=d.getUint32(9*c,b),this.numberOfFaces=d.getUint32(10*c,b),this.numberOfMipmapLevels=d.getUint32(11*c,b),this.bytesOfKeyValueData=d.getUint32(12*c,b),this.glType!==0){Logger$2.Error("only compressed formats currently supported");return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){Logger$2.Error("only 2D textures currently supported");return}if(this.numberOfArrayElements!==0){Logger$2.Error("texture arrays not currently supported");return}if(this.numberOfFaces!==e){Logger$2.Error("number of faces expected"+e+", but found "+this.numberOfFaces);return}this.loadType=a.COMPRESSED_2D}return a.prototype.uploadLevels=function(i,e){switch(this.loadType){case a.COMPRESSED_2D:this._upload2DCompressedLevels(i,e);break}},a.prototype._upload2DCompressedLevels=function(i,e){for(var o=a.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,c=this.pixelHeight,d=e?this.numberOfMipmapLevels:1,_=0;_<d;_++){var b=new Int32Array(this.data.buffer,this.data.byteOffset+o,1)[0];o+=4;for(var k=0;k<this.numberOfFaces;k++){var j=new Uint8Array(this.data.buffer,this.data.byteOffset+o,b),$=i.getEngine();$._uploadCompressedDataToTextureDirectly(i,this.glInternalFormat,s,c,j,k,_),o+=b,o+=3-(b+3)%4}s=Math.max(1,s*.5),c=Math.max(1,c*.5)}},a.IsValid=function(i){if(i.byteLength>=12){var e=new Uint8Array(i.buffer,i.byteOffset,12);if(e[0]===171&&e[1]===75&&e[2]===84&&e[3]===88&&e[4]===32&&e[5]===49&&e[6]===49&&e[7]===187&&e[8]===13&&e[9]===10&&e[10]===26&&e[11]===10)return!0}return!1},a.HEADER_LEN=12+13*4,a.COMPRESSED_2D=0,a.COMPRESSED_3D=1,a.TEX_2D=2,a.TEX_3D=3,a}(),KhronosTextureContainer2=function(){function a(i,e){e===void 0&&(e=a.DefaultNumWorkers),this._engine=i,a._Initialized||a._CreateWorkerPool(e)}return a.GetDefaultNumWorkers=function(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)},a._CreateWorkerPool=function(i){this._Initialized=!0,i&&typeof Worker=="function"?a._WorkerPoolPromise=new Promise(function(e){for(var o="("+workerFunc+")()",s=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),c=new Array(i),d=0;d<c.length;d++)c[d]=new Promise(function(_,b){var k=new Worker(s),j=function(_e){k.removeEventListener("error",j),k.removeEventListener("message",$),b(_e)},$=function(_e){_e.data.action==="init"&&(k.removeEventListener("error",j),k.removeEventListener("message",$),_(k))};k.addEventListener("error",j),k.addEventListener("message",$),k.postMessage({action:"init",urls:a.URLConfig})});Promise.all(c).then(function(_){e(new WorkerPool(_))})}):typeof KTX2DECODER=="undefined"?a._NoWorkerPromise=Tools.LoadScriptAsync(a.URLConfig.jsDecoderModule).then(function(){KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0;var e=a.URLConfig;e.wasmUASTCToASTC!==null&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7!==null&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.jsMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder!==null&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0)},a.prototype.uploadAsync=function(i,e,o){var s=this,c=this._engine.getCaps(),d={astc:!!c.astc,bptc:!!c.bptc,s3tc:!!c.s3tc,pvrtc:!!c.pvrtc,etc2:!!c.etc2,etc1:!!c.etc1};return a._WorkerPoolPromise?a._WorkerPoolPromise.then(function(_){return new Promise(function(b,k){_.push(function(j,$){var _e=function(tt){j.removeEventListener("error",_e),j.removeEventListener("message",et),k(tt),$()},et=function(tt){if(tt.data.action==="decoded"){if(j.removeEventListener("error",_e),j.removeEventListener("message",et),!tt.data.success)k({message:tt.data.msg});else try{s._createTexture(tt.data.decodedData,e,o),b()}catch(rt){k({message:rt})}$()}};j.addEventListener("error",_e),j.addEventListener("message",et),j.postMessage({action:"decode",data:i,caps:d,options:o})})})}):a._NoWorkerPromise?a._NoWorkerPromise.then(function(){return new Promise(function(_,b){a._Ktx2Decoder||(a._Ktx2Decoder=new KTX2DECODER.KTX2Decoder),a._Ktx2Decoder.decode(i,c).then(function(k){s._createTexture(k,e),_()}).catch(function(k){b({message:k})})})}):new Promise(function(_,b){a._Ktx2Decoder||(a._Ktx2Decoder=new KTX2DECODER.KTX2Decoder),a._Ktx2Decoder.decode(i,c).then(function(k){s._createTexture(k,e),_()}).catch(function(k){b({message:k})})})},a.prototype.dispose=function(){a._WorkerPoolPromise&&a._WorkerPoolPromise.then(function(i){i.dispose()}),delete a._WorkerPoolPromise,delete a._NoWorkerPromise},a.prototype._createTexture=function(i,e,o){var s=3553;if(this._engine._bindTextureDirectly(s,e),o&&(o.transcodedFormat=i.transcodedFormat,o.isInGammaSpace=i.isInGammaSpace,o.hasAlpha=i.hasAlpha,o.transcoderName=i.transcoderName),i.transcodedFormat===32856?(e.type=0,e.format=5):e.format=i.transcodedFormat,e._gammaSpace=i.isInGammaSpace,e.generateMipMaps=i.mipmaps.length>1,i.errors)throw new Error("KTX2 container - could not transcode the data. "+i.errors);for(var c=0;c<i.mipmaps.length;++c){var d=i.mipmaps[c];if(!d||!d.data)throw new Error("KTX2 container - could not transcode one of the image");i.transcodedFormat===32856?(e.width=d.width,e.height=d.height,this._engine._uploadDataToTextureDirectly(e,d.data,0,c,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(e,i.transcodedFormat,d.width,d.height,d.data,0,c)}e._extension=".ktx2",e.width=i.mipmaps[0].width,e.height=i.mipmaps[0].height,e.isReady=!0,this._engine._bindTextureDirectly(s,null)},a.IsValid=function(i){if(i.byteLength>=12){var e=new Uint8Array(i.buffer,i.byteOffset,12);if(e[0]===171&&e[1]===75&&e[2]===84&&e[3]===88&&e[4]===32&&e[5]===50&&e[6]===48&&e[7]===187&&e[8]===13&&e[9]===10&&e[10]===26&&e[11]===10)return!0}return!1},a.URLConfig={jsDecoderModule:"https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/babylon.ktx2Decoder.js",wasmUASTCToASTC:"https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_astc.wasm",wasmUASTCToBC7:"https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_bc7.wasm",wasmUASTCToRGBA_UNORM:"https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_rgba32_unorm.wasm",wasmUASTCToRGBA_SRGB:"https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_rgba32_srgb.wasm",jsMSCTranscoder:"https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/msc_basis_transcoder.js",wasmMSCTranscoder:"https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/msc_basis_transcoder.wasm",wasmZSTDDecoder:null},a.DefaultNumWorkers=a.GetDefaultNumWorkers(),a}();function workerFunc(){var a;onmessage=function(i){if(!!i.data)switch(i.data.action){case"init":var e=i.data.urls;importScripts(e.jsDecoderModule),e.wasmUASTCToASTC!==null&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7!==null&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.jsMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder!==null&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder),a=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break;case"decode":a.decode(i.data.data,i.data.caps,i.data.options).then(function(o){for(var s=[],c=0;c<o.mipmaps.length;++c){var d=o.mipmaps[c];d&&d.data&&s.push(d.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:o},s)}).catch(function(o){postMessage({action:"decoded",success:!1,msg:o})});break}}}var _KTXTextureLoader=function(){function a(){this.supportCascades=!1}return a.prototype.canLoad=function(i,e){return EndsWith(i,".ktx")||EndsWith(i,".ktx2")||e==="image/ktx"||e==="image/ktx2"},a.prototype.loadCubeData=function(i,e,o,s,c){if(!Array.isArray(i)){e._invertVScale=!e.invertY;var d=e.getEngine(),_=new KhronosTextureContainer(i,6),b=_.numberOfMipmapLevels>1&&e.generateMipMaps;d._unpackFlipY(!0),_.uploadLevels(e,e.generateMipMaps),e.width=_.pixelWidth,e.height=_.pixelHeight,d._setCubeMapTextureParams(e,b),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()}},a.prototype.loadData=function(i,e,o,s){if(KhronosTextureContainer.IsValid(i)){e._invertVScale=!e.invertY;var c=new KhronosTextureContainer(i,1);o(c.pixelWidth,c.pixelHeight,e.generateMipMaps,!0,function(){c.uploadLevels(e,e.generateMipMaps)},c.isInvalid)}else if(KhronosTextureContainer2.IsValid(i)){var d=new KhronosTextureContainer2(e.getEngine());d.uploadAsync(i,e,s).then(function(){o(e.width,e.height,e.generateMipMaps,!0,function(){},!1)},function(_){Logger$2.Warn("Failed to load KTX2 texture data: "+_.message),o(0,0,!1,!1,function(){},!0)})}else Logger$2.Error("texture missing KTX identifier"),o(0,0,!1,!1,function(){},!0)},a}();Engine._TextureLoaders.unshift(new _KTXTextureLoader);var WebXRCamera=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,Vector3.Zero(),o)||this;return c._xrSessionManager=s,c._firstFrame=!1,c._referenceQuaternion=Quaternion.Identity(),c._referencedPosition=new Vector3,c._trackingState=WebXRTrackingState.NOT_TRACKING,c.onBeforeCameraTeleport=new Observable,c.onAfterCameraTeleport=new Observable,c.onTrackingStateChanged=new Observable,c.compensateOnFirstFrame=!0,c._rotate180=new Quaternion(0,1,0,0),c.minZ=.1,c.rotationQuaternion=new Quaternion,c.cameraRigMode=Camera$1.RIG_MODE_CUSTOM,c.updateUpVectorFromRotation=!0,c._updateNumberOfRigCameras(1),c.freezeProjectionMatrix(),c._xrSessionManager.onXRSessionInit.add(function(){c._referencedPosition.copyFromFloats(0,0,0),c._referenceQuaternion.copyFromFloats(0,0,0,1),c._firstFrame=c.compensateOnFirstFrame}),c._xrSessionManager.onXRFrameObservable.add(function(d){c._firstFrame&&c._updateFromXRSession(),c._updateReferenceSpace(),c._updateFromXRSession()},void 0,!0),c}return Object.defineProperty(i.prototype,"trackingState",{get:function(){return this._trackingState},enumerable:!1,configurable:!0}),i.prototype._setTrackingState=function(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))},Object.defineProperty(i.prototype,"realWorldHeight",{get:function(){var e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0},enumerable:!1,configurable:!0}),i.prototype._updateForDualEyeDebugging=function(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Viewport(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Viewport(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null},i.prototype.setTransformationFromNonVRCamera=function(e,o){if(e===void 0&&(e=this.getScene().activeCamera),o===void 0&&(o=!0),!(!e||e===this)){var s=e.computeWorldMatrix();s.decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,Quaternion.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,o&&this._xrSessionManager.resetReferenceSpace()}},i.prototype.getClassName=function(){return"WebXRCamera"},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._lastXRViewerPose=void 0},i.prototype._updateFromXRSession=function(){var e=this,o=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=o||void 0,!o){this._setTrackingState(WebXRTrackingState.NOT_TRACKING);return}var s=o.emulatedPosition?WebXRTrackingState.TRACKING_LOST:WebXRTrackingState.TRACKING;if(this._setTrackingState(s),o.transform){var c=o.transform.orientation;if(o.transform.orientation.x===void 0)return;var d=o.transform.position;this._referencedPosition.set(d.x,d.y,d.z),this._referenceQuaternion.set(c.x,c.y,c.z,c.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==o.views.length&&this._updateNumberOfRigCameras(o.views.length),o.views.forEach(function(_,b){var k=e.rigCameras[b];!k.isLeftCamera&&!k.isRightCamera&&(_.eye==="right"?k._isRightCamera=!0:_.eye==="left"&&(k._isLeftCamera=!0));var j=_.transform.position,$=_.transform.orientation;if(k.parent=e.parent,k.position.set(j.x,j.y,j.z),k.rotationQuaternion.set($.x,$.y,$.z,$.w),e._scene.useRightHandedSystem?k.rotationQuaternion.multiplyInPlace(e._rotate180):(k.position.z*=-1,k.rotationQuaternion.z*=-1,k.rotationQuaternion.w*=-1),Matrix.FromFloat32ArrayToRefScaled(_.projectionMatrix,0,1,k._projectionMatrix),e._scene.useRightHandedSystem||k._projectionMatrix.toggleProjectionMatrixHandInPlace(),b===0&&e._projectionMatrix.copyFrom(k._projectionMatrix),e._xrSessionManager.session.renderState.baseLayer){var _e=e._xrSessionManager.session.renderState.baseLayer.getViewport(_),et=e._xrSessionManager.session.renderState.baseLayer.framebufferWidth,tt=e._xrSessionManager.session.renderState.baseLayer.framebufferHeight;k.viewport.width=_e.width/et,k.viewport.height=_e.height/tt,k.viewport.x=_e.x/et,k.viewport.y=_e.y/tt}k.outputRenderTarget=e._xrSessionManager.getRenderTargetTextureForEye(_.eye)})},i.prototype._updateNumberOfRigCameras=function(e){for(e===void 0&&(e=1);this.rigCameras.length<e;){var o=new TargetCamera("XR-RigCamera: "+this.rigCameras.length,Vector3.Zero(),this.getScene());o.minZ=.1,o.rotationQuaternion=new Quaternion,o.updateUpVectorFromRotation=!0,o.isRigCamera=!0,o.rigParent=this,o.freezeProjectionMatrix(),this.rigCameras.push(o)}for(;this.rigCameras.length>e;){var s=this.rigCameras.pop();s&&s.dispose()}},i.prototype._updateReferenceSpace=function(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){var e=TmpVectors.Matrix[0],o=TmpVectors.Matrix[1],s=TmpVectors.Matrix[2];Matrix.ComposeToRef(i._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),Matrix.ComposeToRef(i._ScaleReadOnly,this.rotationQuaternion,this.position,o),e.invert().multiplyToRef(o,s),s.invert(),this._scene.useRightHandedSystem||s.toggleModelMatrixHandInPlace(),s.decompose(void 0,this._referenceQuaternion,this._referencedPosition);var c=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(c)}},i._ScaleReadOnly=Vector3.One(),i}(FreeCamera),_a,WebXRFeatureName=function(){function a(){}return a.ANCHOR_SYSTEM="xr-anchor-system",a.BACKGROUND_REMOVER="xr-background-remover",a.HIT_TEST="xr-hit-test",a.MESH_DETECTION="xr-mesh-detection",a.PHYSICS_CONTROLLERS="xr-physics-controller",a.PLANE_DETECTION="xr-plane-detection",a.POINTER_SELECTION="xr-controller-pointer-selection",a.TELEPORTATION="xr-controller-teleportation",a.FEATURE_POINTS="xr-feature-points",a.HAND_TRACKING="xr-hand-tracking",a.IMAGE_TRACKING="xr-image-tracking",a.NEAR_INTERACTION="xr-near-interaction",a.DOM_OVERLAY="xr-dom-overlay",a.MOVEMENT="xr-controller-movement",a.LIGHT_ESTIMATION="xr-light-estimation",a.EYE_TRACKING="xr-eye-tracking",a.WALKING_LOCOMOTION="xr-walking-locomotion",a}(),WebXRFeaturesManager=function(){function a(i){var e=this;this._xrSessionManager=i,this._features={},this._xrSessionManager.onXRSessionInit.add(function(){e.getEnabledFeatures().forEach(function(o){var s=e._features[o];s.enabled&&!s.featureImplementation.attached&&!s.featureImplementation.disableAutoAttach&&e.attachFeature(o)})}),this._xrSessionManager.onXRSessionEnded.add(function(){e.getEnabledFeatures().forEach(function(o){var s=e._features[o];s.enabled&&s.featureImplementation.attached&&e.detachFeature(o)})})}return a.AddWebXRFeature=function(i,e,o,s){o===void 0&&(o=1),s===void 0&&(s=!1),this._AvailableFeatures[i]=this._AvailableFeatures[i]||{latest:o},o>this._AvailableFeatures[i].latest&&(this._AvailableFeatures[i].latest=o),s&&(this._AvailableFeatures[i].stable=o),this._AvailableFeatures[i][o]=e},a.ConstructFeature=function(i,e,o,s){e===void 0&&(e=1);var c=this._AvailableFeatures[i][e];if(!c)throw new Error("feature not found");return c(o,s)},a.GetAvailableFeatures=function(){return Object.keys(this._AvailableFeatures)},a.GetAvailableVersions=function(i){return Object.keys(this._AvailableFeatures[i])},a.GetLatestVersionOfFeature=function(i){return this._AvailableFeatures[i]&&this._AvailableFeatures[i].latest||-1},a.GetStableVersionOfFeature=function(i){return this._AvailableFeatures[i]&&this._AvailableFeatures[i].stable||-1},a.prototype.attachFeature=function(i){var e=this._features[i];e&&e.enabled&&!e.featureImplementation.attached&&e.featureImplementation.attach()},a.prototype.detachFeature=function(i){var e=this._features[i];e&&e.featureImplementation.attached&&e.featureImplementation.detach()},a.prototype.disableFeature=function(i){var e=typeof i=="string"?i:i.Name,o=this._features[e];return o&&o.enabled?(o.enabled=!1,this.detachFeature(e),o.featureImplementation.dispose(),delete this._features[e],!0):!1},a.prototype.dispose=function(){var i=this;this.getEnabledFeatures().forEach(function(e){i.disableFeature(e)})},a.prototype.enableFeature=function(i,e,o,s,c){var d=this;e===void 0&&(e="latest"),o===void 0&&(o={}),s===void 0&&(s=!0),c===void 0&&(c=!0);var _=typeof i=="string"?i:i.Name,b=0;if(typeof e=="string"){if(!e)throw new Error("Error in provided version - "+_+" ("+e+")");if(e==="stable"?b=a.GetStableVersionOfFeature(_):e==="latest"?b=a.GetLatestVersionOfFeature(_):b=+e,b===-1||isNaN(b))throw new Error("feature not found - "+_+" ("+e+")")}else b=e;var k=a._ConflictingFeatures[_];if(k!==void 0&&this.getEnabledFeatures().indexOf(k)!==-1)throw new Error("Feature "+_+" cannot be enabled while "+k+" is enabled.");var j=this._features[_],$=a.ConstructFeature(_,b,this._xrSessionManager,o);if(!$)throw new Error("feature not found - "+_);j&&this.disableFeature(_);var _e=$();if(_e.dependsOn){var et=_e.dependsOn.every(function(tt){return!!d._features[tt]});if(!et)throw new Error("Dependant features missing. Make sure the following features are enabled - "+_e.dependsOn.join(", "))}if(_e.isCompatible())return this._features[_]={featureImplementation:_e,enabled:!0,version:b,required:c},s?this._xrSessionManager.session&&!this._features[_].featureImplementation.attached&&this.attachFeature(_):this._features[_].featureImplementation.disableAutoAttach=!0,this._features[_].featureImplementation;if(c)throw new Error("required feature not compatible");return Tools.Warn("Feature "+_+" not compatible with the current environment/browser and was not enabled."),_e},a.prototype.getEnabledFeature=function(i){return this._features[i]&&this._features[i].featureImplementation},a.prototype.getEnabledFeatures=function(){return Object.keys(this._features)},a.prototype._extendXRSessionInitObject=function(i){return __awaiter(this,void 0,void 0,function(){var e,o,s,c,d,_,b;return __generator(this,function(k){switch(k.label){case 0:e=this.getEnabledFeatures(),o=0,s=e,k.label=1;case 1:return o<s.length?(c=s[o],d=this._features[c],_=d.featureImplementation.xrNativeFeatureName,_&&(d.required?(i.requiredFeatures=i.requiredFeatures||[],i.requiredFeatures.indexOf(_)===-1&&i.requiredFeatures.push(_)):(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.indexOf(_)===-1&&i.optionalFeatures.push(_))),d.featureImplementation.getXRSessionInitExtension?[4,d.featureImplementation.getXRSessionInitExtension()]:[3,3]):[3,4];case 2:b=k.sent(),i=__assign(__assign({},i),b),k.label=3;case 3:return o++,[3,1];case 4:return[2,i]}})})},a._AvailableFeatures={},a._ConflictingFeatures=(_a={},_a[WebXRFeatureName.TELEPORTATION]=WebXRFeatureName.MOVEMENT,_a[WebXRFeatureName.MOVEMENT]=WebXRFeatureName.TELEPORTATION,_a),a}();Node$2.AddNodeConstructor("TouchCamera",function(a,i){return function(){return new TouchCamera(a,Vector3.Zero(),i)}});var TouchCamera=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o,s)||this;return c.inputs.addTouch(),c._setupInputs(),c}return Object.defineProperty(i.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var o=this.inputs.attached.touch;o&&(o.touchAngularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var o=this.inputs.attached.touch;o&&(o.touchMoveSensibility=e)},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"TouchCamera"},i.prototype._setupInputs=function(){var e=this.inputs.attached.touch,o=this.inputs.attached.mouse;o?o.touchEnabled=!1:e.allowMouse=!0},i}(FreeCamera);Node$2.AddNodeConstructor("FreeCamera",function(a,i){return function(){return new UniversalCamera(a,Vector3.Zero(),i)}});var UniversalCamera=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,o,s)||this;return c.inputs.addGamepad(),c}return Object.defineProperty(i.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var o=this.inputs.attached.gamepad;o&&(o.gamepadAngularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var o=this.inputs.attached.gamepad;o&&(o.gamepadMoveSensibility=e)},enumerable:!1,configurable:!0}),i.prototype.getClassName=function(){return"UniversalCamera"},i}(TouchCamera);Camera$1._createDefaultParsedCamera=function(a,i){return new UniversalCamera(a,Vector3.Zero(),i)};var WebXRExperienceHelper=function(){function a(i){var e=this;this.scene=i,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this.onInitialXRPoseSetObservable=new Observable,this.onStateChangedObservable=new Observable,this.state=WebXRState.NOT_IN_XR,this.sessionManager=new WebXRSessionManager(i),this.camera=new WebXRCamera("webxr",i,this.sessionManager),this.featuresManager=new WebXRFeaturesManager(this.sessionManager),i.onDisposeObservable.add(function(){e.exitXRAsync()})}return a.CreateAsync=function(i){var e=new a(i);return e.sessionManager.initializeAsync().then(function(){return e._supported=!0,e}).catch(function(o){throw e._setState(WebXRState.NOT_IN_XR),e.dispose(),o})},a.prototype.dispose=function(){var i;this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),(i=this._spectatorCamera)===null||i===void 0||i.dispose(),this._nonVRCamera&&(this.scene.activeCamera=this._nonVRCamera)},a.prototype.enterXRAsync=function(i,e,o,s){var c,d;return o===void 0&&(o=this.sessionManager.getWebXRRenderTarget()),s===void 0&&(s={}),__awaiter(this,void 0,void 0,function(){var _,b=this;return __generator(this,function(k){switch(k.label){case 0:if(!this._supported)throw"WebXR not supported in this browser or environment";return this._setState(WebXRState.ENTERING_XR),e!=="viewer"&&e!=="local"&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(e)),[4,this.featuresManager._extendXRSessionInitObject(s)];case 1:s=k.sent(),i==="immersive-ar"&&e!=="unbounded"&&Logger$2.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode"),k.label=2;case 2:return k.trys.push([2,7,,8]),[4,this.sessionManager.initializeSessionAsync(i,s)];case 3:return k.sent(),[4,this.sessionManager.setReferenceSpaceTypeAsync(e)];case 4:return k.sent(),[4,o.initializeXRLayerAsync(this.sessionManager.session)];case 5:return k.sent(),[4,this.sessionManager.updateRenderStateAsync({depthFar:this.camera.maxZ,depthNear:this.camera.minZ,baseLayer:o.xrLayer})];case 6:return k.sent(),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this.scene.autoClear,this._nonVRCamera=this.scene.activeCamera,this._attachedToElement=!!(!((c=this._nonVRCamera)===null||c===void 0)&&c.inputs.attachedToElement),(d=this._nonVRCamera)===null||d===void 0||d.detachControl(),this.scene.activeCamera=this.camera,i!=="immersive-ar"?this._nonXRToXRCamera():(this.scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1),this.sessionManager.onXRSessionEnded.addOnce(function(){b.camera.rigCameras.forEach(function(j){j.outputRenderTarget=null}),b.scene.autoClear=b._originalSceneAutoClear,b.scene.activeCamera=b._nonVRCamera,b._attachedToElement&&b._nonVRCamera&&b._nonVRCamera.attachControl(!!b._nonVRCamera.inputs.noPreventDefault),i!=="immersive-ar"&&b.camera.compensateOnFirstFrame&&(b._nonVRCamera.setPosition?b._nonVRCamera.setPosition(b.camera.position):b._nonVRCamera.position.copyFrom(b.camera.position)),b._setState(WebXRState.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(function(){b._setState(WebXRState.IN_XR)}),[2,this.sessionManager];case 7:throw _=k.sent(),console.log(_),console.log(_.message),this._setState(WebXRState.NOT_IN_XR),_;case 8:return[2]}})})},a.prototype.exitXRAsync=function(){return this.state!==WebXRState.IN_XR?Promise.resolve():(this._setState(WebXRState.EXITING_XR),this.sessionManager.exitXRAsync())},a.prototype.enableSpectatorMode=function(){var i=this;if(!this._spectatorMode){var e=function(){i._spectatorCamera&&(i._spectatorCamera.position.copyFrom(i.camera.rigCameras[0].globalPosition),i._spectatorCamera.rotationQuaternion.copyFrom(i.camera.rigCameras[0].absoluteRotation))},o=function(){i.state===WebXRState.IN_XR?(i._spectatorCamera=new UniversalCamera("webxr-spectator",Vector3.Zero(),i.scene),i._spectatorCamera.rotationQuaternion=new Quaternion,i.scene.activeCameras=[i.camera,i._spectatorCamera],i.sessionManager.onXRFrameObservable.add(e),i.scene.onAfterRenderCameraObservable.add(function(s){s===i.camera&&(i.scene.getEngine().framebufferDimensionsObject=null)})):i.state===WebXRState.EXITING_XR&&(i.sessionManager.onXRFrameObservable.removeCallback(e),i.scene.activeCameras=null)};this._spectatorMode=!0,this.onStateChangedObservable.add(o),o()}},a.prototype._nonXRToXRCamera=function(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)},a.prototype._setState=function(i){this.state!==i&&(this.state=i,this.onStateChangedObservable.notifyObservers(this.state))},a}(),WebXRControllerComponent=function(){function a(i,e,o,s){o===void 0&&(o=-1),s===void 0&&(s=[]),this.id=i,this.type=e,this._buttonIndex=o,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new Observable,this.onButtonStateChangedObservable=new Observable}return Object.defineProperty(a.prototype,"axes",{get:function(){return this._axes},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"changes",{get:function(){return this._changes},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"hasChanges",{get:function(){return this._hasChanges},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"pressed",{get:function(){return this._pressed},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"touched",{get:function(){return this._touched},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"value",{get:function(){return this._currentValue},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()},a.prototype.isAxes=function(){return this._axesIndices.length!==0},a.prototype.isButton=function(){return this._buttonIndex!==-1},a.prototype.update=function(i){var e=!1,o=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){var s=i.buttons[this._buttonIndex];if(!s)return;this._currentValue!==s.value&&(this.changes.value={current:s.value,previous:this._currentValue},e=!0,this._currentValue=s.value),this._touched!==s.touched&&(this.changes.touched={current:s.touched,previous:this._touched},e=!0,this._touched=s.touched),this._pressed!==s.pressed&&(this.changes.pressed={current:s.pressed,previous:this._pressed},e=!0,this._pressed=s.pressed)}this.isAxes()&&(this._axes.x!==i.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:i.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=i.axes[this._axesIndices[0]],o=!0),this._axes.y!==i.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=i.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:i.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=i.axes[this._axesIndices[1]],o=!0)),e&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),o&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))},a.BUTTON_TYPE="button",a.SQUEEZE_TYPE="squeeze",a.THUMBSTICK_TYPE="thumbstick",a.TOUCHPAD_TYPE="touchpad",a.TRIGGER_TYPE="trigger",a}(),WebXRAbstractMotionController=function(){function a(i,e,o,s,c,d){var _=this;c===void 0&&(c=!1),this.scene=i,this.layout=e,this.gamepadObject=o,this.handedness=s,this._doNotLoadControllerMesh=c,this._controllerCache=d,this._initComponent=function(b){if(!!b){var k=_.layout.components[b],j=k.type,$=k.gamepadIndices.button,_e=[];k.gamepadIndices.xAxis!==void 0&&k.gamepadIndices.yAxis!==void 0&&_e.push(k.gamepadIndices.xAxis,k.gamepadIndices.yAxis),_.components[b]=new WebXRControllerComponent(b,j,$,_e)}},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new Observable,e.components&&Object.keys(e.components).forEach(this._initComponent)}return a.prototype.dispose=function(){var i=this;this.getComponentIds().forEach(function(e){return i.getComponent(e).dispose()}),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(function(e){e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))},a.prototype.getAllComponentsOfType=function(i){var e=this;return this.getComponentIds().map(function(o){return e.components[o]}).filter(function(o){return o.type===i})},a.prototype.getComponent=function(i){return this.components[i]},a.prototype.getComponentIds=function(){return Object.keys(this.components)},a.prototype.getComponentOfType=function(i){return this.getAllComponentsOfType(i)[0]||null},a.prototype.getMainComponent=function(){return this.getComponent(this.layout.selectComponentId)},a.prototype.loadModel=function(){return __awaiter(this,void 0,void 0,function(){var i,e,o=this;return __generator(this,function(s){return i=!this._getModelLoadingConstraints(),e=this._getGenericFilenameAndPath(),i?Logger$2.Warn("Falling back to generic models"):e=this._getFilenameAndPath(),[2,new Promise(function(c,d){var _=function(k){i?o._getGenericParentMesh(k):o._setRootMesh(k),o._processLoadedModel(k),o._modelReady=!0,o.onModelLoadedObservable.notifyObservers(o),c(!0)};if(o._controllerCache){var b=o._controllerCache.filter(function(k){return k.filename===e.filename&&k.path===e.path});if(b[0]){b[0].meshes.forEach(function(k){return k.setEnabled(!0)}),_(b[0].meshes);return}}SceneLoader.ImportMesh("",e.path,e.filename,o.scene,function(k){o._controllerCache&&o._controllerCache.push(__assign(__assign({},e),{meshes:k})),_(k)},null,function(k,j){Logger$2.Log(j),Logger$2.Warn("Failed to retrieve controller model of type "+o.profileId+" from the remote server: "+e.path+e.filename),d(j)})})]})})},a.prototype.updateFromXRFrame=function(i){var e=this;this.getComponentIds().forEach(function(o){return e.getComponent(o).update(e.gamepadObject)}),this.updateModel(i)},Object.defineProperty(a.prototype,"handness",{get:function(){return this.handedness},enumerable:!1,configurable:!0}),a.prototype.pulse=function(i,e,o){return o===void 0&&(o=0),this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[o]?this.gamepadObject.hapticActuators[o].pulse(i,e):Promise.resolve(!1)},a.prototype._getChildByName=function(i,e){return i.getChildren(function(o){return o.name===e},!1)[0]},a.prototype._getImmediateChildByName=function(i,e){return i.getChildren(function(o){return o.name==e},!0)[0]},a.prototype._lerpTransform=function(i,e,o){if(!(!i.minMesh||!i.maxMesh||!i.valueMesh)&&!(!i.minMesh.rotationQuaternion||!i.maxMesh.rotationQuaternion||!i.valueMesh.rotationQuaternion)){var s=o?e*.5+.5:e;Quaternion.SlerpToRef(i.minMesh.rotationQuaternion,i.maxMesh.rotationQuaternion,s,i.valueMesh.rotationQuaternion),Vector3.LerpToRef(i.minMesh.position,i.maxMesh.position,s,i.valueMesh.position)}},a.prototype.updateModel=function(i){!this._modelReady||this._updateModel(i)},a.prototype._getGenericFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},a.prototype._getGenericParentMesh=function(i){var e=this;this.rootMesh=new Mesh(this.profileId+" "+this.handedness,this.scene),i.forEach(function(o){o.parent||(o.isPickable=!1,o.setParent(e.rootMesh))}),this.rootMesh.rotationQuaternion=Quaternion.FromEulerAngles(0,Math.PI,0)},a}(),WebXRGenericTriggerMotionController=function(a){__extends(i,a);function i(e,o,s){var c=a.call(this,e,GenericTriggerLayout[s],o,s)||this;return c.profileId=i.ProfileId,c}return i.prototype._getFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},i.prototype._getModelLoadingConstraints=function(){return!0},i.prototype._processLoadedModel=function(e){},i.prototype._setRootMesh=function(e){var o=this;this.rootMesh=new Mesh(this.profileId+" "+this.handedness,this.scene),e.forEach(function(s){s.isPickable=!1,s.parent||s.setParent(o.rootMesh)}),this.rootMesh.rotationQuaternion=Quaternion.FromEulerAngles(0,Math.PI,0)},i.prototype._updateModel=function(){},i.ProfileId="generic-trigger",i}(WebXRAbstractMotionController),GenericTriggerLayout={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}},WebXRProfiledMotionController=function(a){__extends(i,a);function i(e,o,s,c,d){var _=a.call(this,e,s.layouts[o.handedness||"none"],o.gamepad,o.handedness,void 0,d)||this;return _._repositoryUrl=c,_.controllerCache=d,_._buttonMeshMapping={},_._touchDots={},_.profileId=s.profileId,_}return i.prototype.dispose=function(){var e=this;a.prototype.dispose.call(this),this.controllerCache||Object.keys(this._touchDots).forEach(function(o){e._touchDots[o].dispose()})},i.prototype._getFilenameAndPath=function(){return{filename:this.layout.assetPath,path:this._repositoryUrl+"/profiles/"+this.profileId+"/"}},i.prototype._getModelLoadingConstraints=function(){var e=SceneLoader.IsPluginForExtensionAvailable(".glb");return e||Logger$2.Warn("glTF / glb loader was not registered, using generic controller instead"),e},i.prototype._processLoadedModel=function(e){var o=this;this.getComponentIds().forEach(function(s){var c=o.layout.components[s];o._buttonMeshMapping[s]={mainMesh:o._getChildByName(o.rootMesh,c.rootNodeName),states:{}},Object.keys(c.visualResponses).forEach(function(d){var _=c.visualResponses[d];if(_.valueNodeProperty==="transform")o._buttonMeshMapping[s].states[d]={valueMesh:o._getChildByName(o.rootMesh,_.valueNodeName),minMesh:o._getChildByName(o.rootMesh,_.minNodeName),maxMesh:o._getChildByName(o.rootMesh,_.maxNodeName)};else{var b=c.type===WebXRControllerComponent.TOUCHPAD_TYPE&&c.touchPointNodeName?c.touchPointNodeName:_.valueNodeName;if(o._buttonMeshMapping[s].states[d]={valueMesh:o._getChildByName(o.rootMesh,b)},c.type===WebXRControllerComponent.TOUCHPAD_TYPE&&!o._touchDots[d]){var k=CreateSphere(d+"dot",{diameter:.0015,segments:8},o.scene);k.material=new StandardMaterial(d+"mat",o.scene),k.material.diffuseColor=Color3.Red(),k.parent=o._buttonMeshMapping[s].states[d].valueMesh||null,k.isVisible=!1,o._touchDots[d]=k}}})})},i.prototype._setRootMesh=function(e){this.rootMesh=new Mesh(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(var o,s=0;s<e.length;s++){var c=e[s];c.isPickable=!1,c.parent||(o=c)}o&&o.setParent(this.rootMesh),this.scene.useRightHandedSystem||this.rootMesh.rotate(Axis.Y,Math.PI,Space.WORLD)},i.prototype._updateModel=function(e){var o=this;this.disableAnimation||this.getComponentIds().forEach(function(s){var c=o.getComponent(s);if(!!c.hasChanges){var d=o._buttonMeshMapping[s],_=o.layout.components[s];Object.keys(_.visualResponses).forEach(function(b){var k=_.visualResponses[b],j=c.value;if(k.componentProperty==="xAxis"?j=c.axes.x:k.componentProperty==="yAxis"&&(j=c.axes.y),k.valueNodeProperty==="transform")o._lerpTransform(d.states[b],j,k.componentProperty!=="button");else{var $=d.states[b].valueMesh;$&&($.isVisible=c.touched||c.pressed),o._touchDots[b]&&(o._touchDots[b].isVisible=c.touched||c.pressed)}})}})},i}(WebXRAbstractMotionController),controllerCache=[],WebXRMotionControllerManager=function(){function a(){}return a.ClearProfilesCache=function(){this._ProfilesList=null,this._ProfileLoadingPromises={}},a.DefaultFallbacks=function(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])},a.FindFallbackWithProfileId=function(i){var e=this._Fallbacks[i]||[];return e.unshift(i),e},a.GetMotionControllerWithXRInput=function(i,e,o){var s=this,c=[];if(o&&c.push(o),c.push.apply(c,i.profiles||[]),c.length&&!c[0]&&c.pop(),i.gamepad&&i.gamepad.id)switch(i.gamepad.id){case(i.gamepad.id.match(/oculus touch/gi)?i.gamepad.id:void 0):c.push("oculus-touch-v2");break}var d=c.indexOf("windows-mixed-reality");if(d!==-1&&c.splice(d,0,"microsoft-mixed-reality"),c.length||c.push("generic-trigger"),this.UseOnlineRepository){var _=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,b=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return _.call(this,c,i,e).catch(function(){return b.call(s,c,i,e)})}else return this._LoadProfilesFromAvailableControllers(c,i,e)},a.RegisterController=function(i,e){this._AvailableControllers[i]=e},a.RegisterFallbacksForProfileId=function(i,e){var o;this._Fallbacks[i]?(o=this._Fallbacks[i]).push.apply(o,e):this._Fallbacks[i]=e},a.UpdateProfilesList=function(){return this._ProfilesList=Tools.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(function(i){return JSON.parse(i.toString())}),this._ProfilesList},a.ClearControllerCache=function(){controllerCache.forEach(function(i){i.meshes.forEach(function(e){e.dispose(!1,!0)})}),controllerCache.length=0},a._LoadProfileFromRepository=function(i,e,o){var s=this;return Promise.resolve().then(function(){return s._ProfilesList?s._ProfilesList:s.UpdateProfilesList()}).then(function(c){for(var d=0;d<i.length;++d)if(!!i[d]&&c[i[d]])return i[d];throw new Error("neither controller "+i[0]+" nor all fallbacks were found in the repository,")}).then(function(c){return s._ProfileLoadingPromises[c]||(s._ProfileLoadingPromises[c]=Tools.LoadFileAsync(s.BaseRepositoryUrl+"/profiles/"+c+"/profile.json",!1).then(function(d){return JSON.parse(d)})),s._ProfileLoadingPromises[c]}).then(function(c){return new WebXRProfiledMotionController(o,e,c,s.BaseRepositoryUrl,s.DisableControllerCache?void 0:controllerCache)})},a._LoadProfilesFromAvailableControllers=function(i,e,o){for(var s=0;s<i.length;++s)if(!!i[s])for(var c=this.FindFallbackWithProfileId(i[s]),d=0;d<c.length;++d){var _=this._AvailableControllers[c[d]];if(_)return Promise.resolve(_(e,o))}throw new Error("no controller requested was found in the available controllers list")},a._AvailableControllers={},a._Fallbacks={},a._ProfileLoadingPromises={},a.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",a.PrioritizeOnlineRepository=!0,a.UseOnlineRepository=!0,a.DisableControllerCache=!0,a}();WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId,function(a,i){return new WebXRGenericTriggerMotionController(i,a.gamepad,a.handedness)});WebXRMotionControllerManager.DefaultFallbacks();var idCount=0,WebXRInputSource=function(){function a(i,e,o){var s=this;o===void 0&&(o={}),this._scene=i,this.inputSource=e,this._options=o,this._tmpVector=new Vector3,this._disposed=!1,this.onDisposeObservable=new Observable,this.onMeshLoadedObservable=new Observable,this.onMotionControllerInitObservable=new Observable,this._uniqueId="controller-"+idCount+++"-"+e.targetRayMode+"-"+e.handedness,this.pointer=new AbstractMesh(this._uniqueId+"-pointer",i),this.pointer.rotationQuaternion=new Quaternion,this.inputSource.gripSpace&&(this.grip=new AbstractMesh(this._uniqueId+"-grip",this._scene),this.grip.rotationQuaternion=new Quaternion),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&WebXRMotionControllerManager.GetMotionControllerWithXRInput(e,i,this._options.forceControllerProfile).then(function(c){s.motionController=c,s.onMotionControllerInitObservable.notifyObservers(c),!s._options.doNotLoadControllerMesh&&!s.motionController._doNotLoadControllerMesh&&s.motionController.loadModel().then(function(d){var _;d&&s.motionController&&s.motionController.rootMesh&&(s._options.renderingGroupId&&(s.motionController.rootMesh.renderingGroupId=s._options.renderingGroupId,s.motionController.rootMesh.getChildMeshes(!1).forEach(function(b){return b.renderingGroupId=s._options.renderingGroupId})),s.onMeshLoadedObservable.notifyObservers(s.motionController.rootMesh),s.motionController.rootMesh.parent=s.grip||s.pointer,s.motionController.disableAnimation=!!s._options.disableMotionControllerAnimation),s._disposed&&((_=s.motionController)===null||_===void 0||_.dispose())})},function(){Tools.Warn("Could not find a matching motion controller for the registered input source")})}return Object.defineProperty(a.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0},a.prototype.getWorldPointerRayToRef=function(i,e){e===void 0&&(e=!1);var o=e&&this.grip?this.grip:this.pointer;Vector3.TransformNormalToRef(this._tmpVector,o.getWorldMatrix(),i.direction),i.direction.normalize(),i.origin.copyFrom(o.absolutePosition),i.length=1e3},a.prototype.updateFromXRFrame=function(i,e,o){var s=i.getPose(this.inputSource.targetRaySpace,e);if(this._lastXRPose=s,s){var c=s.transform.position;this.pointer.position.set(c.x,c.y,c.z);var d=s.transform.orientation;this.pointer.rotationQuaternion.set(d.x,d.y,d.z,d.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=o.parent}if(this.inputSource.gripSpace&&this.grip){var _=i.getPose(this.inputSource.gripSpace,e);if(_){var c=_.transform.position,b=_.transform.orientation;this.grip.position.set(c.x,c.y,c.z),this.grip.rotationQuaternion.set(b.x,b.y,b.z,b.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=o.parent}this.motionController&&this.motionController.updateFromXRFrame(i)},a}(),WebXRInput=function(){function a(i,e,o){var s=this;if(o===void 0&&(o={}),this.xrSessionManager=i,this.xrCamera=e,this.options=o,this.controllers=[],this.onControllerAddedObservable=new Observable,this.onControllerRemovedObservable=new Observable,this._onInputSourcesChange=function(c){s._addAndRemoveControllers(c.added,c.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(function(){s._addAndRemoveControllers([],s.controllers.map(function(c){return c.inputSource}))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(function(c){c.addEventListener("inputsourceschange",s._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(function(c){s.controllers.forEach(function(d){d.updateFromXRFrame(c,s.xrSessionManager.referenceSpace,s.xrCamera)})}),this.options.customControllersRepositoryURL&&(WebXRMotionControllerManager.BaseRepositoryUrl=this.options.customControllersRepositoryURL),WebXRMotionControllerManager.UseOnlineRepository=!this.options.disableOnlineControllerRepository,WebXRMotionControllerManager.UseOnlineRepository)try{WebXRMotionControllerManager.UpdateProfilesList().catch(function(){WebXRMotionControllerManager.UseOnlineRepository=!1})}catch{WebXRMotionControllerManager.UseOnlineRepository=!1}}return a.prototype._addAndRemoveControllers=function(i,e){for(var o=this,s=this.controllers.map(function($){return $.inputSource}),c=0,d=i;c<d.length;c++){var _=d[c];if(s.indexOf(_)===-1){var b=new WebXRInputSource(this.xrSessionManager.scene,_,__assign(__assign({},this.options.controllerOptions||{}),{forceControllerProfile:this.options.forceInputProfile,doNotLoadControllerMesh:this.options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this.options.disableControllerAnimation}));this.controllers.push(b),this.onControllerAddedObservable.notifyObservers(b)}}var k=[],j=[];this.controllers.forEach(function($){e.indexOf($.inputSource)===-1?k.push($):j.push($)}),this.controllers=k,j.forEach(function($){o.onControllerRemovedObservable.notifyObservers($),$.dispose()})},a.prototype.dispose=function(){this.controllers.forEach(function(i){i.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),WebXRMotionControllerManager.ClearControllerCache()},a}(),WebXRAbstractFeature=function(){function a(i){this._xrSessionManager=i,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}return Object.defineProperty(a.prototype,"attached",{get:function(){return this._attached},enumerable:!1,configurable:!0}),a.prototype.attach=function(i){var e=this;if(this.isDisposed)return!1;if(i)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,function(o){return e._onXRFrame(o)}),!0},a.prototype.detach=function(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(function(i){i.observable.remove(i.observer)}),!0):(this.disableAutoAttach=!0,!1)},a.prototype.dispose=function(){this.detach(),this.isDisposed=!0},a.prototype.isCompatible=function(){return!0},a.prototype._addNewAttachObserver=function(i,e){this._removeOnDetach.push({observable:i,observer:i.add(e)})},a}(),WebXRControllerPointerSelection=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e)||this;return s._options=o,s._attachController=function(c){if(!s._controllers[c.uniqueId]){var d=s._generateNewMeshPair(c.pointer),_=d.laserPointer,b=d.selectionMesh;switch(s._controllers[c.uniqueId]={xrController:c,laserPointer:_,selectionMesh:b,meshUnderPointer:null,pick:null,tmpRay:new Ray(new Vector3,new Vector3),disabledByNearInteraction:!1,id:i._idCounter++},s._attachedController?!s._options.enablePointerSelectionOnAllControllers&&s._options.preferredHandedness&&c.inputSource.handedness===s._options.preferredHandedness&&(s._attachedController=c.uniqueId):s._options.enablePointerSelectionOnAllControllers||(s._attachedController=c.uniqueId),c.inputSource.targetRayMode){case"tracked-pointer":return s._attachTrackedPointerRayMode(c);case"gaze":return s._attachGazeMode(c);case"screen":return s._attachScreenRayMode(c)}}},s._controllers={},s._tmpVectorForPickCompare=new Vector3,s.disablePointerLighting=!0,s.disableSelectionMeshLighting=!0,s.displayLaserPointer=!0,s.displaySelectionMesh=!0,s.laserPointerPickedColor=new Color3(.9,.9,.9),s.laserPointerDefaultColor=new Color3(.7,.7,.7),s.selectionMeshDefaultColor=new Color3(.8,.8,.8),s.selectionMeshPickedColor=new Color3(.3,.3,1),s._identityMatrix=Matrix.Identity(),s._screenCoordinatesRef=Vector3.Zero(),s._viewportRef=new Viewport(0,0,0,0),s._scene=s._xrSessionManager.scene,s}return i.prototype.attach=function(){var e=this;if(!a.prototype.attach.call(this))return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,function(_){e._detachController(_.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){var o=this._options.gazeCamera,s=this._generateNewMeshPair(o),c=s.laserPointer,d=s.selectionMesh;this._controllers.camera={webXRCamera:o,laserPointer:c,selectionMesh:d,meshUnderPointer:null,pick:null,tmpRay:new Ray(new Vector3,new Vector3),disabledByNearInteraction:!1,id:i._idCounter++},this._attachGazeMode()}return!0},i.prototype.detach=function(){var e=this;return a.prototype.detach.call(this)?(Object.keys(this._controllers).forEach(function(o){e._detachController(o)}),!0):!1},i.prototype.getMeshUnderPointer=function(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null},i.prototype.getXRControllerByPointerId=function(e){for(var o=Object.keys(this._controllers),s=0;s<o.length;++s)if(this._controllers[o[s]].id===e)return this._controllers[o[s]].xrController||null;return null},i.prototype._getPointerSelectionDisabledByPointerId=function(e){for(var o=Object.keys(this._controllers),s=0;s<o.length;++s)if(this._controllers[o[s]].id===e)return this._controllers[o[s]].disabledByNearInteraction;return!0},i.prototype._setPointerSelectionDisabledByPointerId=function(e,o){for(var s=Object.keys(this._controllers),c=0;c<s.length;++c)if(this._controllers[s[c]].id===e){this._controllers[s[c]].disabledByNearInteraction=o;return}},i.prototype._onXRFrame=function(e){var o=this;Object.keys(this._controllers).forEach(function(s){var c=o._controllers[s];if(!o._options.enablePointerSelectionOnAllControllers&&s!==o._attachedController||c.disabledByNearInteraction){c.selectionMesh.isVisible=!1,c.laserPointer.isVisible=!1,c.pick=null;return}c.laserPointer.isVisible=o.displayLaserPointer;var d;if(c.xrController)d=c.xrController.pointer.position,c.xrController.getWorldPointerRayToRef(c.tmpRay);else if(c.webXRCamera)d=c.webXRCamera.position,c.webXRCamera.getForwardRayToRef(c.tmpRay);else return;if(o._options.maxPointerDistance&&(c.tmpRay.length=o._options.maxPointerDistance),!o._options.disableScenePointerVectorUpdate&&d){var _=o._xrSessionManager.scene,b=o._options.xrInput.xrCamera;b&&(b.viewport.toGlobalToRef(_.getEngine().getRenderWidth(),_.getEngine().getRenderHeight(),o._viewportRef),Vector3.ProjectToRef(d,o._identityMatrix,_.getTransformMatrix(),o._viewportRef,o._screenCoordinatesRef),typeof o._screenCoordinatesRef.x=="number"&&typeof o._screenCoordinatesRef.y=="number"&&!isNaN(o._screenCoordinatesRef.x)&&!isNaN(o._screenCoordinatesRef.y)&&(_.pointerX=o._screenCoordinatesRef.x,_.pointerY=o._screenCoordinatesRef.y,c.screenCoordinates={x:o._screenCoordinatesRef.x,y:o._screenCoordinatesRef.y}))}var k=null;o._utilityLayerScene&&(k=o._utilityLayerScene.pickWithRay(c.tmpRay,o._utilityLayerScene.pointerMovePredicate||o.raySelectionPredicate));var j=o._scene.pickWithRay(c.tmpRay,o._scene.pointerMovePredicate||o.raySelectionPredicate);!k||!k.hit?c.pick=j:!j||!j.hit||k.distance<j.distance?c.pick=k:c.pick=j,c.pick&&c.xrController&&(c.pick.aimTransform=c.xrController.pointer,c.pick.gripTransform=c.xrController.grip||null);var $=c.pick;if($&&$.pickedPoint&&$.hit){o._updatePointerDistance(c.laserPointer,$.distance),c.selectionMesh.position.copyFrom($.pickedPoint),c.selectionMesh.scaling.x=Math.sqrt($.distance),c.selectionMesh.scaling.y=Math.sqrt($.distance),c.selectionMesh.scaling.z=Math.sqrt($.distance);var _e=o._convertNormalToDirectionOfRay($.getNormal(!0),c.tmpRay),et=.001;if(c.selectionMesh.position.copyFrom($.pickedPoint),_e){var tt=Vector3.Cross(Axis.Y,_e),rt=Vector3.Cross(_e,tt);Vector3.RotationFromAxisToRef(rt,_e,tt,c.selectionMesh.rotation),c.selectionMesh.position.addInPlace(_e.scale(et))}c.selectionMesh.isVisible=o.displaySelectionMesh,c.meshUnderPointer=$.pickedMesh}else c.selectionMesh.isVisible=!1,o._updatePointerDistance(c.laserPointer,1),c.meshUnderPointer=null})},Object.defineProperty(i.prototype,"_utilityLayerScene",{get:function(){return this._options.customUtilityLayerScene||UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene},enumerable:!1,configurable:!0}),i.prototype._attachGazeMode=function(e){var o=this,s=this._controllers[e&&e.uniqueId||"camera"],c=this._options.timeToSelect||3e3,d=this._options.useUtilityLayer?this._utilityLayerScene:this._scene,_=new PickingInfo,b=CreateTorus("selection",{diameter:.0035*15,thickness:.0025*6,tessellation:20},d);b.isVisible=!1,b.isPickable=!1,b.parent=s.selectionMesh;var k=0,j=!1,$={pointerId:s.id,pointerType:"xr"};s.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){if(!!s.pick){if(o._augmentPointerInit($,s.id,s.screenCoordinates),s.laserPointer.material.alpha=0,b.isVisible=!1,s.pick.hit)if(o._pickingMoved(_,s.pick))j&&(o._options.disablePointerUpOnTouchOut||o._scene.simulatePointerUp(s.pick,$)),j=!1,k=0;else if(k>c/10&&(b.isVisible=!0),k+=o._scene.getEngine().getDeltaTime(),k>=c)o._scene.simulatePointerDown(s.pick,$),j=!0,o._options.disablePointerUpOnTouchOut&&o._scene.simulatePointerUp(s.pick,$),b.isVisible=!1;else{var _e=1-k/c;b.scaling.set(_e,_e,_e)}else j=!1,k=0;o._scene.simulatePointerMove(s.pick,$),_=s.pick}}),this._options.renderingGroupId!==void 0&&(b.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(function(){s.pick&&!o._options.disablePointerUpOnTouchOut&&j&&(o._scene.simulatePointerUp(s.pick,$),s.finalPointerUpTriggered=!0),b.dispose()})},i.prototype._attachScreenRayMode=function(e){var o=this,s=this._controllers[e.uniqueId],c=!1,d={pointerId:s.id,pointerType:"xr"};s.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){o._augmentPointerInit(d,s.id,s.screenCoordinates),!(!s.pick||o._options.disablePointerUpOnTouchOut&&c)&&(c?o._scene.simulatePointerMove(s.pick,d):(o._scene.simulatePointerDown(s.pick,d),c=!0,o._options.disablePointerUpOnTouchOut&&o._scene.simulatePointerUp(s.pick,d)))}),e.onDisposeObservable.addOnce(function(){o._augmentPointerInit(d,s.id,s.screenCoordinates),s.pick&&c&&!o._options.disablePointerUpOnTouchOut&&(o._scene.simulatePointerUp(s.pick,d),s.finalPointerUpTriggered=!0)})},i.prototype._attachTrackedPointerRayMode=function(e){var o=this,s=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);var c={pointerId:s.id,pointerType:"xr"};if(s.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){s.laserPointer.material.disableLighting=o.disablePointerLighting,s.selectionMesh.material.disableLighting=o.disableSelectionMeshLighting,s.pick&&(o._augmentPointerInit(c,s.id,s.screenCoordinates),o._scene.simulatePointerMove(s.pick,c))}),e.inputSource.gamepad){var d=function(k){o._options.overrideButtonId&&(s.selectionComponent=k.getComponent(o._options.overrideButtonId)),s.selectionComponent||(s.selectionComponent=k.getMainComponent()),s.onButtonChangedObserver=s.selectionComponent.onButtonStateChangedObservable.add(function(j){if(j.changes.pressed){var $=j.changes.pressed.current;s.pick?(o._options.enablePointerSelectionOnAllControllers||e.uniqueId===o._attachedController)&&(o._augmentPointerInit(c,s.id,s.screenCoordinates),$?(o._scene.simulatePointerDown(s.pick,c),s.selectionMesh.material.emissiveColor=o.selectionMeshPickedColor,s.laserPointer.material.emissiveColor=o.laserPointerPickedColor):(o._scene.simulatePointerUp(s.pick,c),s.selectionMesh.material.emissiveColor=o.selectionMeshDefaultColor,s.laserPointer.material.emissiveColor=o.laserPointerDefaultColor)):$&&!o._options.enablePointerSelectionOnAllControllers&&!o._options.disableSwitchOnClick&&(o._attachedController=e.uniqueId)}})};e.motionController?d(e.motionController):e.onMotionControllerInitObservable.add(d)}else{var _=function(k){o._augmentPointerInit(c,s.id,s.screenCoordinates),s.xrController&&k.inputSource===s.xrController.inputSource&&s.pick&&(o._scene.simulatePointerDown(s.pick,c),s.selectionMesh.material.emissiveColor=o.selectionMeshPickedColor,s.laserPointer.material.emissiveColor=o.laserPointerPickedColor)},b=function(k){o._augmentPointerInit(c,s.id,s.screenCoordinates),s.xrController&&k.inputSource===s.xrController.inputSource&&s.pick&&(o._scene.simulatePointerUp(s.pick,c),s.selectionMesh.material.emissiveColor=o.selectionMeshDefaultColor,s.laserPointer.material.emissiveColor=o.laserPointerDefaultColor)};s.eventListeners={selectend:b,selectstart:_},this._xrSessionManager.session.addEventListener("selectstart",_),this._xrSessionManager.session.addEventListener("selectend",b)}},i.prototype._convertNormalToDirectionOfRay=function(e,o){if(e){var s=Math.acos(Vector3.Dot(e,o.direction));s<Math.PI/2&&e.scaleInPlace(-1)}return e},i.prototype._detachController=function(e){var o=this,s=this._controllers[e];!s||(s.selectionComponent&&s.onButtonChangedObserver&&s.selectionComponent.onButtonStateChangedObservable.remove(s.onButtonChangedObserver),s.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(s.onFrameObserver),s.eventListeners&&Object.keys(s.eventListeners).forEach(function(c){var d=s.eventListeners&&s.eventListeners[c];d&&o._xrSessionManager.session.removeEventListener(c,d)}),this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(function(){try{if(!s.finalPointerUpTriggered){var c={pointerId:s.id,pointerType:"xr"};o._augmentPointerInit(c,s.id,s.screenCoordinates),o._scene.simulatePointerUp(new PickingInfo,c)}if(s.selectionMesh.dispose(),s.laserPointer.dispose(),delete o._controllers[e],o._attachedController===e){var d=Object.keys(o._controllers);d.length?o._attachedController=d[0]:o._attachedController=""}}catch{Tools.Warn("controller already detached.")}}))},i.prototype._generateNewMeshPair=function(e){var o=this._options.useUtilityLayer?this._options.customUtilityLayerScene||UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,s=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():CreateCylinder("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},o);s.parent=e;var c=new StandardMaterial("laserPointerMat",o);c.emissiveColor=this.laserPointerDefaultColor,c.alpha=.7,s.material=c,s.rotation.x=Math.PI/2,this._updatePointerDistance(s,1),s.isPickable=!1,s.isVisible=!1;var d=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():CreateTorus("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},o);d.bakeCurrentTransformIntoVertices(),d.isPickable=!1,d.isVisible=!1;var _=new StandardMaterial("targetMat",o);return _.specularColor=Color3.Black(),_.emissiveColor=this.selectionMeshDefaultColor,_.backFaceCulling=!1,d.material=_,this._options.renderingGroupId!==void 0&&(s.renderingGroupId=this._options.renderingGroupId,d.renderingGroupId=this._options.renderingGroupId),{laserPointer:s,selectionMesh:d}},i.prototype._pickingMoved=function(e,o){var s;if(!e.hit||!o.hit||!e.pickedMesh||!e.pickedPoint||!o.pickedMesh||!o.pickedPoint||e.pickedMesh!==o.pickedMesh)return!0;(s=e.pickedPoint)===null||s===void 0||s.subtractToRef(o.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));var c=(this._options.gazeModePointerMovedFactor||1)*.01*o.distance,d=this._tmpVectorForPickCompare.length();return d>c},i.prototype._updatePointerDistance=function(e,o){o===void 0&&(o=100),e.scaling.y=o,this._scene.useRightHandedSystem&&(o*=-1),e.position.z=o/2+.05},i.prototype._augmentPointerInit=function(e,o,s){e.pointerId=o,e.pointerType="xr",s&&(e.screenX=s.x,e.screenY=s.y)},Object.defineProperty(i.prototype,"lasterPointerDefaultColor",{get:function(){return this.laserPointerDefaultColor},enumerable:!1,configurable:!0}),i._idCounter=200,i.Name=WebXRFeatureName.POINTER_SELECTION,i.Version=1,i}(WebXRAbstractFeature);WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name,function(a,i){return function(){return new WebXRControllerPointerSelection(a,i)}},WebXRControllerPointerSelection.Version,!0);SubMesh.prototype._projectOnTrianglesToRef=function(a,i,e,o,s,c){for(var d=TmpVectors.Vector3[0],_=TmpVectors.Vector3[1],b=1/0,k=this.indexStart;k<this.indexStart+this.indexCount-(3-o);k+=o){var j=e[k],$=e[k+1],_e=e[k+2];if(s&&_e===4294967295){k+=2;continue}var et=i[j],tt=i[$],rt=i[_e];if(!(!et||!tt||!rt)){var it=Vector3.ProjectOnTriangleToRef(a,et,tt,rt,_);it<b&&(d.copyFrom(_),b=it)}}return c.copyFrom(d),b};SubMesh.prototype._projectOnUnIndexedTrianglesToRef=function(a,i,e,o){for(var s=TmpVectors.Vector3[0],c=TmpVectors.Vector3[1],d=1/0,_=this.verticesStart;_<this.verticesStart+this.verticesCount;_+=3){var b=i[_],k=i[_+1],j=i[_+2],$=Vector3.ProjectOnTriangleToRef(a,b,k,j,c);$<d&&(s.copyFrom(c),d=$)}return o.copyFrom(s),d};SubMesh.prototype.projectToRef=function(a,i,e,o){var s=this.getMaterial();if(!s)return-1;var c=3,d=!1;switch(s.fillMode){case 3:case 4:case 5:case 6:case 8:return-1;case 7:c=1,d=!0;break}return this._mesh.getClassName()==="InstancedLinesMesh"||this._mesh.getClassName()==="LinesMesh"?-1:!e.length&&this._mesh._unIndexed?this._projectOnUnIndexedTrianglesToRef(a,i,e,o):this._projectOnTrianglesToRef(a,i,e,c,d,o)};var WebXRNearInteraction=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e)||this;return s._options=o,s._attachController=function(c){if(!s._controllers[c.uniqueId]){var d=s._generateNewHandTipMesh(),_=s._generateVisualCue();switch(s._controllers[c.uniqueId]={xrController:c,meshUnderPointer:null,nearInteractionMesh:null,pick:null,pickIndexMeshTip:d,grabRay:new Ray(new Vector3,new Vector3),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:i._idCounter++,pickedPointVisualCue:_},s._attachedController?!s._options.enableNearInteractionOnAllControllers&&s._options.preferredHandedness&&c.inputSource.handedness===s._options.preferredHandedness&&(s._attachedController=c.uniqueId):s._options.enableNearInteractionOnAllControllers||(s._attachedController=c.uniqueId),c.inputSource.targetRayMode){case"tracked-pointer":return s._attachNearInteractionMode(c);case"gaze":return null;case"screen":return null}}},s._controllers={},s._farInteractionFeature=null,s.selectionMeshDefaultColor=new Color3(.8,.8,.8),s.selectionMeshPickedColor=new Color3(.3,.3,1),s._hoverRadius=.1,s._pickRadius=.02,s._nearGrabLengthScale=5,s._indexTipQuaternion=new Quaternion,s._indexTipOrientationVector=Vector3.Zero(),s._scene=s._xrSessionManager.scene,s._options.farInteractionFeature&&(s._farInteractionFeature=s._options.farInteractionFeature),s}return i.prototype.attach=function(){var e=this;return a.prototype.attach.call(this)?(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,function(o){e._detachController(o.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0):!1},i.prototype.detach=function(){var e=this;return a.prototype.detach.call(this)?(Object.keys(this._controllers).forEach(function(o){e._detachController(o)}),!0):!1},i.prototype.getMeshUnderPointer=function(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null},i.prototype.getXRControllerByPointerId=function(e){for(var o=Object.keys(this._controllers),s=0;s<o.length;++s)if(this._controllers[o[s]].id===e)return this._controllers[o[s]].xrController||null;return null},i.prototype.setFarInteractionFeature=function(e){this._farInteractionFeature=e},i.prototype._nearPickPredicate=function(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearPickable},i.prototype._nearGrabPredicate=function(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearGrabbable},i.prototype._nearInteractionPredicate=function(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&(e.isNearPickable||e.isNearGrabbable)},i.prototype._controllerAvailablePredicate=function(e,o){for(var s=e;s;){if(s.reservedDataStore&&s.reservedDataStore.nearInteraction&&s.reservedDataStore.nearInteraction.excludedControllerId===o)return!1;s=s.parent}return!0},i.prototype._onXRFrame=function(e){var o=this;Object.keys(this._controllers).forEach(function(s){var c=o._controllers[s];if(!o._options.enableNearInteractionOnAllControllers&&s!==o._attachedController||!c.xrController||!c.xrController.inputSource.hand){c.pick=null;return}if(c.hoverInteraction=!1,c.nearInteraction=!1,c.xrController){var d=c.xrController.inputSource.hand;if(d){var _=d.get("index-finger-tip");if(_){var b=e.getJointPose(_,o._xrSessionManager.referenceSpace);if(b&&b.transform){var k=o._scene.useRightHandedSystem?1:-1,j=b.transform.position,$=b.transform.orientation;o._indexTipQuaternion.set($.x,$.y,$.z*k,$.w*k),c.pickIndexMeshTip&&c.pickIndexMeshTip.position.set(j.x,j.y,j.z*k);var _e=o._nearGrabLengthScale*o._hoverRadius;c.grabRay.origin.set(j.x,j.y,j.z*k),o._indexTipQuaternion.toEulerAnglesToRef(o._indexTipOrientationVector),c.grabRay.direction.set(o._indexTipOrientationVector.x,o._indexTipOrientationVector.y,o._indexTipOrientationVector.z),c.grabRay.length=_e}}}}else return;var et=function(lt,ht){var pt=null;return!ht||!ht.hit?pt=lt:!lt||!lt.hit||ht.distance<lt.distance?pt=ht:pt=lt,pt},tt=function(lt){var ht=new PickingInfo,pt=!1,mt=lt&&lt.pickedPoint&&lt.hit;return lt!=null&&lt.pickedPoint&&(pt=lt.pickedPoint.x===0&&lt.pickedPoint.y===0&&lt.pickedPoint.z===0),mt&&!pt&&(ht=lt),ht};if(!c.grabInteraction){var rt=null,it=null;o._options.useUtilityLayer&&o._utilityLayerScene&&(it=o._pickWithSphere(c,o._hoverRadius,o._utilityLayerScene,function(lt){return o._nearInteractionPredicate(lt)}));var nt=o._pickWithSphere(c,o._hoverRadius,o._scene,function(lt){return o._nearInteractionPredicate(lt)}),ot=et(nt,it);if(ot&&ot.hit&&(rt=tt(ot),rt.hit&&(c.hoverInteraction=!0)),c.pickIndexMeshTip&&c.hoverInteraction){var at=null;o._options.useUtilityLayer&&o._utilityLayerScene&&(at=o._pickWithSphere(c,o._pickRadius,o._utilityLayerScene,function(lt){return o._nearPickPredicate(lt)}));var st=o._pickWithSphere(c,o._pickRadius,o._scene,function(lt){return o._nearPickPredicate(lt)}),ut=et(st,at),ft=tt(ut);ft.hit&&(rt=ft,c.nearInteraction=!0)}c.pick=rt,c.pick&&c.pick.pickedPoint&&c.pick.hit?(c.meshUnderPointer=c.pick.pickedMesh,c.pickedPointVisualCue.position.copyFrom(c.pick.pickedPoint),c.pickedPointVisualCue.isVisible=!0,o._farInteractionFeature&&o._farInteractionFeature.attached&&o._farInteractionFeature._setPointerSelectionDisabledByPointerId(c.id,!0)):(c.meshUnderPointer=null,c.pickedPointVisualCue.isVisible=!1,o._farInteractionFeature&&o._farInteractionFeature.attached&&o._farInteractionFeature._setPointerSelectionDisabledByPointerId(c.id,!1))}})},Object.defineProperty(i.prototype,"_utilityLayerScene",{get:function(){return this._options.customUtilityLayerScene||UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene},enumerable:!1,configurable:!0}),i.prototype._generateVisualCue=function(){var e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,o=CreateSphere("nearInteraction",{diameter:.0035*3},e);o.bakeCurrentTransformIntoVertices(),o.isPickable=!1,o.isVisible=!1,o.rotationQuaternion=Quaternion.Identity();var s=new StandardMaterial("targetMat",e);return s.specularColor=Color3.Black(),s.emissiveColor=this.selectionMeshDefaultColor,s.backFaceCulling=!1,o.material=s,o},i.prototype._isControllerReadyForNearInteraction=function(e){return this._farInteractionFeature?this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e):!0},i.prototype._attachNearInteractionMode=function(e){var o=this,s=this._controllers[e.uniqueId],c={pointerId:s.id,pointerType:"xr"};s.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){!o._options.enableNearInteractionOnAllControllers&&e.uniqueId!==o._attachedController||!s.xrController||!s.xrController.inputSource.hand||(s.pick&&(s.pick.ray=s.grabRay),s.pick&&o._isControllerReadyForNearInteraction(s.id)&&o._scene.simulatePointerMove(s.pick,c),s.nearInteraction&&s.pick&&s.pick.hit?s.nearInteractionMesh||(o._scene.simulatePointerDown(s.pick,c),s.nearInteractionMesh=s.meshUnderPointer):s.nearInteractionMesh&&s.pick&&(o._scene.simulatePointerUp(s.pick,c),s.nearInteractionMesh=null))});var d=function(j){o._options.enableNearInteractionOnAllControllers||e.uniqueId===o._attachedController&&o._isControllerReadyForNearInteraction(s.id)?(s.pick&&(s.pick.ray=s.grabRay),j&&s.pick&&s.meshUnderPointer&&o._nearGrabPredicate(s.meshUnderPointer)?(s.grabInteraction=!0,s.pickedPointVisualCue.isVisible=!1,o._scene.simulatePointerDown(s.pick,c)):!j&&s.pick&&s.grabInteraction&&(o._scene.simulatePointerUp(s.pick,c),s.grabInteraction=!1,s.pickedPointVisualCue.isVisible=!0)):j&&!o._options.enableNearInteractionOnAllControllers&&!o._options.disableSwitchOnClick&&(o._attachedController=e.uniqueId)};if(e.inputSource.gamepad){var _=function(j){s.squeezeComponent=j.getComponent("grasp"),s.squeezeComponent?s.onSqueezeButtonChangedObserver=s.squeezeComponent.onButtonStateChangedObservable.add(function($){if($.changes.pressed){var _e=$.changes.pressed.current;d(_e)}}):(s.selectionComponent=j.getMainComponent(),s.onButtonChangedObserver=s.selectionComponent.onButtonStateChangedObservable.add(function($){if($.changes.pressed){var _e=$.changes.pressed.current;d(_e)}}))};e.motionController?_(e.motionController):e.onMotionControllerInitObservable.add(_)}else{var b=function(j){s.xrController&&j.inputSource===s.xrController.inputSource&&s.pick&&o._isControllerReadyForNearInteraction(s.id)&&s.meshUnderPointer&&o._nearGrabPredicate(s.meshUnderPointer)&&(s.grabInteraction=!0,s.pickedPointVisualCue.isVisible=!1,o._scene.simulatePointerDown(s.pick,c))},k=function(j){s.xrController&&j.inputSource===s.xrController.inputSource&&s.pick&&o._isControllerReadyForNearInteraction(s.id)&&(o._scene.simulatePointerUp(s.pick,c),s.grabInteraction=!1,s.pickedPointVisualCue.isVisible=!0)};s.eventListeners={selectend:k,selectstart:b},this._xrSessionManager.session.addEventListener("selectstart",b),this._xrSessionManager.session.addEventListener("selectend",k)}},i.prototype._detachController=function(e){var o=this,s,c=this._controllers[e];if(!!c){c.squeezeComponent&&c.onSqueezeButtonChangedObserver&&c.squeezeComponent.onButtonStateChangedObservable.remove(c.onSqueezeButtonChangedObserver),c.selectionComponent&&c.onButtonChangedObserver&&c.selectionComponent.onButtonStateChangedObservable.remove(c.onButtonChangedObserver),c.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(c.onFrameObserver),c.eventListeners&&Object.keys(c.eventListeners).forEach(function(b){var k=c.eventListeners&&c.eventListeners[b];k&&o._xrSessionManager.session.removeEventListener(b,k)}),(s=c.pickIndexMeshTip)===null||s===void 0||s.dispose(),c.pickedPointVisualCue.dispose();var d={pointerId:c.id,pointerType:"xr"};if(this._scene.simulatePointerUp(new PickingInfo,d),delete this._controllers[e],this._attachedController===e){var _=Object.keys(this._controllers);_.length?this._attachedController=_[0]:this._attachedController=""}}},i.prototype._generateNewHandTipMesh=function(){var e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,o=null,s=function(c,d,_){var b=null;return b=CreateSphere(c,{diameter:1},_),b.scaling.set(d,d,d),b.isVisible=!1,b};return o=s("IndexPickSphere",this._pickRadius,e),o},i.prototype._pickWithSphere=function(e,o,s,c){var d=new PickingInfo;if(d.distance=1/0,e.pickIndexMeshTip&&e.xrController)for(var _=e.pickIndexMeshTip.position,b=BoundingSphere.CreateFromCenterAndRadius(_,o),k=0;k<s.meshes.length;k++){var j=s.meshes[k];if(!(!c(j)||!this._controllerAvailablePredicate(j,e.xrController.uniqueId))){var $=i.PickMeshWithSphere(j,b);$&&$.hit&&$.distance<d.distance&&(d.hit=$.hit,d.pickedMesh=j,d.pickedPoint=$.pickedPoint,d.aimTransform=e.xrController.pointer,d.gripTransform=e.xrController.grip||null,d.originMesh=e.pickIndexMeshTip,d.distance=$.distance)}}return d},i.PickMeshWithSphere=function(e,o,s){s===void 0&&(s=!1);var c=e.subMeshes,d=new PickingInfo,_=e.getBoundingInfo();if(!e._generatePointsArray()||!e.subMeshes||!_||!s&&!BoundingSphere.Intersects(_.boundingSphere,o))return d;var b=TmpVectors.Vector3[0],k=TmpVectors.Vector3[1],j=1/0,$,_e,et,tt=TmpVectors.Vector3[2],rt=TmpVectors.Matrix[0];rt.copyFrom(e.getWorldMatrix()),rt.invert(),Vector3.TransformCoordinatesToRef(o.center,rt,tt);for(var it=0;it<c.length;it++){var nt=c[it];nt.projectToRef(tt,e._positions,e.getIndices(),k),Vector3.TransformCoordinatesToRef(k,e.getWorldMatrix(),k),$=Vector3.Distance(k,o.center),et=Vector3.Distance(k,e.getAbsolutePosition()),_e=Vector3.Distance(o.center,e.getAbsolutePosition()),_e!==-1&&et!==-1&&et>_e&&($=0,k.copyFrom(o.center)),$!==-1&&$<j&&(j=$,b.copyFrom(k))}return j<o.radius&&(d.hit=!0,d.distance=j,d.pickedMesh=e,d.pickedPoint=b.clone()),d},i._idCounter=200,i.Name=WebXRFeatureName.NEAR_INTERACTION,i.Version=1,i}(WebXRAbstractFeature);WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name,function(a,i){return function(){return new WebXRNearInteraction(a,i)}},WebXRNearInteraction.Version,!0);var WebXREnterExitUIButton=function(){function a(i,e,o){this.element=i,this.sessionMode=e,this.referenceSpaceType=o}return a.prototype.update=function(i){},a}(),WebXREnterExitUI=function(){function a(i,e){var o=this;if(this.scene=i,this.options=e,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new Observable,this._onSessionGranted=function($){o._helper&&o._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;",!e.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),typeof window!="undefined"&&window.location&&window.location.protocol==="http:"&&window.location.hostname!=="localhost")throw Tools.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(e.customButtons)this._buttons=e.customButtons;else{var s=e.sessionMode||"immersive-vr",c=e.referenceSpaceType||"local-floor",d=typeof SVGSVGElement=="undefined"?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A",_=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+d+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";_+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';var b=document.createElement("style");b.appendChild(document.createTextNode(_)),document.getElementsByTagName("head")[0].appendChild(b);var k=document.createElement("button");k.className="babylonVRicon",k.title=s+" - "+c,this._buttons.push(new WebXREnterExitUIButton(k,s,c)),this._buttons[this._buttons.length-1].update=function($){this.element.style.display=$===null||$===this?"":"none",k.className="babylonVRicon"+($===this?" vrdisplaypresenting":"")},this._updateButtons(null)}var j=i.getEngine().getInputElement();j&&j.parentNode&&(j.parentNode.appendChild(this.overlay),i.onDisposeObservable.addOnce(function(){o.dispose()}))}return a.prototype.setHelperAsync=function(i,e){return __awaiter(this,void 0,void 0,function(){var o,s,c=this;return __generator(this,function(d){switch(d.label){case 0:return this._helper=i,this._renderTarget=e,o=this._buttons.map(function(_){return i.sessionManager.isSessionSupportedAsync(_.sessionMode)}),i.onStateChangedObservable.add(function(_){_==WebXRState.NOT_IN_XR&&c._updateButtons(null)}),[4,Promise.all(o)];case 1:return s=d.sent(),s.forEach(function(_,b){_?(c.overlay.appendChild(c._buttons[b].element),c._buttons[b].element.onclick=c._enterXRWithButtonIndex.bind(c,b)):Tools.Warn('Session mode "'+c._buttons[b].sessionMode+'" not supported in browser')}),[2]}})})},a.CreateAsync=function(i,e,o){return __awaiter(this,void 0,void 0,function(){var s;return __generator(this,function(c){switch(c.label){case 0:return s=new a(i,o),[4,s.setHelperAsync(e,o.renderTarget||void 0)];case 1:return c.sent(),[2,s]}})})},a.prototype._enterXRWithButtonIndex=function(i){return i===void 0&&(i=0),__awaiter(this,void 0,void 0,function(){var e,o,s;return __generator(this,function(c){switch(c.label){case 0:return this._helper.state!=WebXRState.IN_XR?[3,2]:[4,this._helper.exitXRAsync()];case 1:return c.sent(),this._updateButtons(null),[3,6];case 2:if(this._helper.state!=WebXRState.NOT_IN_XR)return[3,6];c.label=3;case 3:return c.trys.push([3,5,,6]),[4,this._helper.enterXRAsync(this._buttons[i].sessionMode,this._buttons[i].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures})];case 4:return c.sent(),this._updateButtons(this._buttons[i]),[3,6];case 5:return e=c.sent(),this._updateButtons(null),o=this._buttons[i].element,s=o.title,o.title="Error entering XR session : "+s,o.classList.add("xr-error"),this.options.onError&&this.options.onError(e),[3,6];case 6:return[2]}})})},a.prototype.dispose=function(){var i=this.scene.getEngine().getInputElement();i&&i.parentNode&&i.parentNode.contains(this.overlay)&&i.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)},a.prototype._updateButtons=function(i){var e=this;this._activeButton=i,this._buttons.forEach(function(o){o.update(e._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)},a}(),TimerState;(function(a){a[a.INIT=0]="INIT",a[a.STARTED=1]="STARTED",a[a.ENDED=2]="ENDED"})(TimerState||(TimerState={}));function setAndStartTimer(a){var i,e=0,o=Date.now();a.observableParameters=(i=a.observableParameters)!==null&&i!==void 0?i:{};var s=a.contextObservable.add(function(c){var d=Date.now();e=d-o;var _={startTime:o,currentTime:d,deltaTime:e,completeRate:e/a.timeout,payload:c};a.onTick&&a.onTick(_),a.breakCondition&&a.breakCondition()&&(a.contextObservable.remove(s),a.onAborted&&a.onAborted(_)),e>=a.timeout&&(a.contextObservable.remove(s),a.onEnded&&a.onEnded(_))},a.observableParameters.mask,a.observableParameters.insertFirst,a.observableParameters.scope);return s}(function(){function a(i){var e=this,o,s;this.onEachCountObservable=new Observable,this.onTimerAbortedObservable=new Observable,this.onTimerEndedObservable=new Observable,this.onStateChangedObservable=new Observable,this._observer=null,this._breakOnNextTick=!1,this._tick=function(c){var d=Date.now();e._timer=d-e._startTime;var _={startTime:e._startTime,currentTime:d,deltaTime:e._timer,completeRate:e._timer/e._timeToEnd,payload:c},b=e._breakOnNextTick||e._breakCondition(_);b||e._timer>=e._timeToEnd?e._stop(_,b):e.onEachCountObservable.notifyObservers(_)},this._setState(TimerState.INIT),this._contextObservable=i.contextObservable,this._observableParameters=(o=i.observableParameters)!==null&&o!==void 0?o:{},this._breakCondition=(s=i.breakCondition)!==null&&s!==void 0?s:function(){return!1},i.onEnded&&this.onTimerEndedObservable.add(i.onEnded),i.onTick&&this.onEachCountObservable.add(i.onTick),i.onAborted&&this.onTimerAbortedObservable.add(i.onAborted)}return Object.defineProperty(a.prototype,"breakCondition",{set:function(i){this._breakCondition=i},enumerable:!1,configurable:!0}),a.prototype.clearObservables=function(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()},a.prototype.start=function(i){if(i===void 0&&(i=this._timeToEnd),this._state===TimerState.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=i,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(TimerState.STARTED)},a.prototype.stop=function(){this._state===TimerState.STARTED&&(this._breakOnNextTick=!0)},a.prototype.dispose=function(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()},a.prototype._setState=function(i){this._state=i,this.onStateChangedObservable.notifyObservers(this._state)},a.prototype._stop=function(i,e){e===void 0&&(e=!1),this._contextObservable.remove(this._observer),this._setState(TimerState.ENDED),e?this.onTimerAbortedObservable.notifyObservers(i):this.onTimerEndedObservable.notifyObservers(i)},a})();var WebXRMotionControllerTeleportation=function(a){__extends(i,a);function i(e,o){var s=a.call(this,e)||this;return s._options=o,s._controllers={},s._snappedToPoint=!1,s._tmpRay=new Ray(new Vector3,new Vector3),s._tmpVector=new Vector3,s._tmpQuaternion=new Quaternion,s.skipNextTeleportation=!1,s.backwardsMovementEnabled=!0,s.backwardsTeleportationDistance=.7,s.parabolicCheckRadius=5,s.parabolicRayEnabled=!0,s.straightRayEnabled=!0,s.rotationAngle=Math.PI/8,s.onTargetMeshPositionUpdatedObservable=new Observable,s.teleportationEnabled=!0,s._rotationEnabled=!0,s._attachController=function(c){if(!(s._controllers[c.uniqueId]||s._options.forceHandedness&&c.inputSource.handedness!==s._options.forceHandedness)){s._controllers[c.uniqueId]={xrController:c,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0}};var d=s._controllers[c.uniqueId];if(d.xrController.inputSource.targetRayMode==="tracked-pointer"&&d.xrController.inputSource.gamepad){var _=function(){if(c.motionController){var b=c.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE)||c.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);if(!b||s._options.useMainComponentOnly){var k=c.motionController.getMainComponent();if(!k)return;d.teleportationComponent=k,d.onButtonChangedObserver=k.onButtonStateChangedObservable.add(function(){if(!!s.teleportationEnabled&&k.changes.pressed)if(k.changes.pressed.current){d.teleportationState.forward=!0,s._currentTeleportationControllerId=d.xrController.uniqueId,d.teleportationState.baseRotation=s._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,d.teleportationState.currentRotation=0;var j=s._options.timeToTeleport||3e3;setAndStartTimer({timeout:j,contextObservable:s._xrSessionManager.onXRFrameObservable,breakCondition:function(){return!k.pressed},onEnded:function(){s._currentTeleportationControllerId===d.xrController.uniqueId&&d.teleportationState.forward&&s._teleportForward(c.uniqueId)}})}else d.teleportationState.forward=!1,s._currentTeleportationControllerId=""})}else d.teleportationComponent=b,d.onAxisChangedObserver=b.onAxisValueChangedObservable.add(function(j){if(j.y<=.7&&d.teleportationState.backwards&&(d.teleportationState.backwards=!1),j.y>.7&&!d.teleportationState.forward&&s.backwardsMovementEnabled&&!s.snapPointsOnly&&!d.teleportationState.backwards){d.teleportationState.backwards=!0,s._tmpQuaternion.copyFrom(s._options.xrInput.xrCamera.rotationQuaternion),s._tmpQuaternion.toEulerAnglesToRef(s._tmpVector),s._tmpVector.x=0,s._tmpVector.z=0,Quaternion.FromEulerVectorToRef(s._tmpVector,s._tmpQuaternion),s._tmpVector.set(0,0,s.backwardsTeleportationDistance*(s._xrSessionManager.scene.useRightHandedSystem?1:-1)),s._tmpVector.rotateByQuaternionToRef(s._tmpQuaternion,s._tmpVector),s._tmpVector.addInPlace(s._options.xrInput.xrCamera.position),s._tmpRay.origin.copyFrom(s._tmpVector),s._tmpRay.length=s._options.xrInput.xrCamera.realWorldHeight+.1,s._tmpRay.direction.set(0,-1,0);var $=s._xrSessionManager.scene.pickWithRay(s._tmpRay,function(et){return s._floorMeshes.indexOf(et)!==-1});$&&$.pickedPoint&&(s._options.xrInput.xrCamera.position.x=$.pickedPoint.x,s._options.xrInput.xrCamera.position.z=$.pickedPoint.z)}if(j.y<-.7&&!s._currentTeleportationControllerId&&!d.teleportationState.rotating&&s.teleportationEnabled&&(d.teleportationState.forward=!0,s._currentTeleportationControllerId=d.xrController.uniqueId,d.teleportationState.baseRotation=s._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),j.x){if(d.teleportationState.forward)s._currentTeleportationControllerId===d.xrController.uniqueId&&(s.rotationEnabled?setTimeout(function(){d.teleportationState.currentRotation=Math.atan2(j.x,j.y*(s._xrSessionManager.scene.useRightHandedSystem?1:-1))}):d.teleportationState.currentRotation=0);else if(!d.teleportationState.rotating&&Math.abs(j.x)>.7){d.teleportationState.rotating=!0;var _e=s.rotationAngle*(j.x>0?1:-1)*(s._xrSessionManager.scene.useRightHandedSystem?-1:1);Quaternion.FromEulerAngles(0,_e,0).multiplyToRef(s._options.xrInput.xrCamera.rotationQuaternion,s._options.xrInput.xrCamera.rotationQuaternion)}}else d.teleportationState.rotating=!1;j.x===0&&j.y===0&&d.teleportationState.forward&&s._teleportForward(c.uniqueId)})}};c.motionController?_():c.onMotionControllerInitObservable.addOnce(function(){_()})}else s._xrSessionManager.scene.onPointerObservable.add(function(b){if(b.type===PointerEventTypes.POINTERDOWN){d.teleportationState.forward=!0,s._currentTeleportationControllerId=d.xrController.uniqueId,d.teleportationState.baseRotation=s._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,d.teleportationState.currentRotation=0;var k=s._options.timeToTeleport||3e3;setAndStartTimer({timeout:k,contextObservable:s._xrSessionManager.onXRFrameObservable,onEnded:function(){s._currentTeleportationControllerId===d.xrController.uniqueId&&d.teleportationState.forward&&s._teleportForward(c.uniqueId)}})}else b.type===PointerEventTypes.POINTERUP&&(d.teleportationState.forward=!1,s._currentTeleportationControllerId="")})}},s._options.teleportationTargetMesh||s._createDefaultTargetMesh(),s._floorMeshes=s._options.floorMeshes||[],s._snapToPositions=s._options.snapPositions||[],s._setTargetMeshVisibility(!1),s}return Object.defineProperty(i.prototype,"rotationEnabled",{get:function(){return this._rotationEnabled},set:function(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){var o=this._options.teleportationTargetMesh.getChildMeshes(!1,function(s){return s.name==="rotationCone"});o[0]&&o[0].setEnabled(e)}},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"teleportationTargetMesh",{get:function(){return this._options.teleportationTargetMesh||null},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"snapPointsOnly",{get:function(){return!!this._options.snapPointsOnly},set:function(e){this._options.snapPointsOnly=e},enumerable:!1,configurable:!0}),i.prototype.addFloorMesh=function(e){this._floorMeshes.push(e)},i.prototype.addBlockerMesh=function(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)},i.prototype.addSnapPoint=function(e){this._snapToPositions.push(e)},i.prototype.attach=function(){var e=this;return a.prototype.attach.call(this)?(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,function(o){e._detachController(o.uniqueId)}),!0):!1},i.prototype.detach=function(){var e=this;return a.prototype.detach.call(this)?(Object.keys(this._controllers).forEach(function(o){e._detachController(o)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0):!1},i.prototype.dispose=function(){a.prototype.dispose.call(this),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)},i.prototype.removeFloorMesh=function(e){var o=this._floorMeshes.indexOf(e);o!==-1&&this._floorMeshes.splice(o,1)},i.prototype.removeBlockerMesh=function(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];var o=this._options.pickBlockerMeshes.indexOf(e);o!==-1&&this._options.pickBlockerMeshes.splice(o,1)},i.prototype.removeFloorMeshByName=function(e){var o=this._xrSessionManager.scene.getMeshByName(e);o&&this.removeFloorMesh(o)},i.prototype.removeSnapPoint=function(e){var o=this._snapToPositions.indexOf(e);if(o===-1){for(var s=0;s<this._snapToPositions.length;++s)if(this._snapToPositions[s].equals(e)){o=s;break}}return o!==-1?(this._snapToPositions.splice(o,1),!0):!1},i.prototype.setSelectionFeature=function(e){this._selectionFeature=e},i.prototype._onXRFrame=function(e){var o=this,s=this._xrSessionManager.currentFrame,c=this._xrSessionManager.scene;if(!(!this.attach||!s)){var d=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!d)return;d.rotationQuaternion=d.rotationQuaternion||new Quaternion;var _=this._controllers[this._currentTeleportationControllerId];if(_&&_.teleportationState.forward){Quaternion.RotationYawPitchRollToRef(_.teleportationState.currentRotation+_.teleportationState.baseRotation,0,0,d.rotationQuaternion);var b=!1;if(_.xrController.getWorldPointerRayToRef(this._tmpRay),this.straightRayEnabled){var k=c.pickWithRay(this._tmpRay,function(et){if(o._options.pickBlockerMeshes&&o._options.pickBlockerMeshes.indexOf(et)!==-1)return!0;var tt=o._floorMeshes.indexOf(et);return tt===-1?!1:o._floorMeshes[tt].absolutePosition.y<o._options.xrInput.xrCamera.globalPosition.y});if(k&&k.pickedMesh&&this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(k.pickedMesh)!==-1)return;k&&k.pickedPoint&&(b=!0,this._setTargetMeshPosition(k),this._setTargetMeshVisibility(!0),this._showParabolicPath(k))}if(this.parabolicRayEnabled&&!b){var j=_.xrController.pointer.rotationQuaternion.toEulerAngles().x,$=1+(Math.PI/2-Math.abs(j)),_e=this.parabolicCheckRadius*$;this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(_e*2),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(_e)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize();var k=c.pickWithRay(this._tmpRay,function(tt){return o._options.pickBlockerMeshes&&o._options.pickBlockerMeshes.indexOf(tt)!==-1?!0:o._floorMeshes.indexOf(tt)!==-1});if(k&&k.pickedMesh&&this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(k.pickedMesh)!==-1)return;k&&k.pickedPoint&&(b=!0,this._setTargetMeshPosition(k),this._setTargetMeshVisibility(!0),this._showParabolicPath(k))}this._setTargetMeshVisibility(b)}else this._setTargetMeshVisibility(!1)}else this._setTargetMeshVisibility(!1)}},i.prototype._createDefaultTargetMesh=function(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};var e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,o=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},e);o.isPickable=!1;var s=512,c=new DynamicTexture("teleportationPlaneDynamicTexture",s,e,!0);c.hasAlpha=!0;var d=c.getContext(),_=s/2,b=s/2,k=200;d.beginPath(),d.arc(_,b,k,0,2*Math.PI,!1),d.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",d.fill(),d.lineWidth=10,d.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",d.stroke(),d.closePath(),c.update();var j=new StandardMaterial("teleportationPlaneMaterial",e);j.diffuseTexture=c,o.material=j;var $=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if($.isPickable=!1,$.parent=o,!this._options.defaultTargetMeshOptions.disableAnimation){var _e=new Animation("animationInnerCircle","position.y",30,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE),et=[];et.push({frame:0,value:0}),et.push({frame:30,value:.4}),et.push({frame:60,value:0}),_e.setKeys(et);var tt=new SineEase;tt.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),_e.setEasingFunction(tt),$.animations=[],$.animations.push(_e),e.beginAnimation($,0,60,!0)}var rt=CreateCylinder("rotationCone",{diameterTop:0,tessellation:4},e);if(rt.isPickable=!1,rt.scaling.set(.5,.12,.2),rt.rotate(Axis.X,Math.PI/2),rt.position.z=.6,rt.parent=$,this._options.defaultTargetMeshOptions.torusArrowMaterial)$.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,rt.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{var it=new StandardMaterial("torusConsMat",e);it.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,it.disableLighting?it.emissiveColor=new Color3(.3,.3,1):it.diffuseColor=new Color3(.3,.3,1),it.alpha=.9,$.material=it,rt.material=it,this._teleportationRingMaterial=it}this._options.renderingGroupId!==void 0&&(o.renderingGroupId=this._options.renderingGroupId,$.renderingGroupId=this._options.renderingGroupId,rt.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=o},i.prototype._detachController=function(e){var o=this._controllers[e];!o||(o.teleportationComponent&&(o.onAxisChangedObserver&&o.teleportationComponent.onAxisValueChangedObservable.remove(o.onAxisChangedObserver),o.onButtonChangedObserver&&o.teleportationComponent.onButtonStateChangedObservable.remove(o.onButtonChangedObserver)),delete this._controllers[e])},i.prototype._findClosestSnapPointWithRadius=function(e,o){o===void 0&&(o=this._options.snapToPositionRadius||.8);var s=null,c=Number.MAX_VALUE;if(this._snapToPositions.length){var d=o*o;this._snapToPositions.forEach(function(_){var b=Vector3.DistanceSquared(_,e);b<=d&&b<c&&(c=b,s=_)})}return s},i.prototype._setTargetMeshPosition=function(e){var o=e.pickedPoint;if(!(!this._options.teleportationTargetMesh||!o)){var s=this._findClosestSnapPointWithRadius(o);this._snappedToPoint=!!s,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(s||o),this._options.teleportationTargetMesh.position.y+=.01,this.onTargetMeshPositionUpdatedObservable.notifyObservers(e)}},i.prototype._setTargetMeshVisibility=function(e){!this._options.teleportationTargetMesh||this._options.teleportationTargetMesh.isVisible!==e&&(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach(function(o){o.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))},i.prototype._showParabolicPath=function(e){if(!!e.pickedPoint){var o=this._options.useUtilityLayer?this._options.customUtilityLayerScene||UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,s=this._controllers[this._currentTeleportationControllerId],c=Curve3.CreateQuadraticBezier(s.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(c.getPoints(),e):this._quadraticBezierCurve=CreateLines("teleportation path line",{points:c.getPoints(),instance:this._quadraticBezierCurve,updatable:!0},o),this._quadraticBezierCurve.isPickable=!1,this._options.renderingGroupId!==void 0&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}},i.prototype._teleportForward=function(e){var o=this._controllers[e];if(!(!o||!o.teleportationState.forward||!this.teleportationEnabled)&&(o.teleportationState.forward=!1,this._currentTeleportationControllerId="",!(this.snapPointsOnly&&!this._snappedToPoint))){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){var s=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=s,Quaternion.FromEulerAngles(0,o.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}},i.Name=WebXRFeatureName.TELEPORTATION,i.Version=1,i}(WebXRAbstractFeature);WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name,function(a,i){return function(){return new WebXRMotionControllerTeleportation(a,i)}},WebXRMotionControllerTeleportation.Version,!0);var WebXRDefaultExperience=function(){function a(){}return a.CreateAsync=function(i,e){e===void 0&&(e={});var o=new a;if(!e.disableDefaultUI){var s=__assign({renderTarget:o.renderTarget},e.uiOptions||{});e.optionalFeatures&&(typeof e.optionalFeatures=="boolean"?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=e.optionalFeatures),o.enterExitUI=new WebXREnterExitUI(i,s)}return WebXRExperienceHelper.CreateAsync(i).then(function(c){if(o.baseExperience=c,e.ignoreNativeCameraTransformation&&(o.baseExperience.camera.compensateOnFirstFrame=!1),o.input=new WebXRInput(c.sessionManager,c.camera,__assign({controllerOptions:{renderingGroupId:e.renderingGroupId}},e.inputOptions||{})),!e.disablePointerSelection){var d=__assign(__assign({},e.pointerSelectionOptions),{xrInput:o.input,renderingGroupId:e.renderingGroupId});o.pointerSelection=o.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name,e.useStablePlugins?"stable":"latest",d),e.disableTeleportation||(o.teleportation=o.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name,e.useStablePlugins?"stable":"latest",{floorMeshes:e.floorMeshes,xrInput:o.input,renderingGroupId:e.renderingGroupId}),o.teleportation.setSelectionFeature(o.pointerSelection))}if(e.disableNearInteraction||(o.nearInteraction=o.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name,e.useStablePlugins?"stable":"latest",{xrInput:o.input,farInteractionFeature:o.pointerSelection,renderingGroupId:e.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0})),o.renderTarget=o.baseExperience.sessionManager.getWebXRRenderTarget(e.outputCanvasOptions),!e.disableDefaultUI)return o.enterExitUI.setHelperAsync(o.baseExperience,o.renderTarget)}).then(function(){return o}).catch(function(c){return Logger$2.Error("Error initializing XR"),Logger$2.Error(c),o})},a.prototype.dispose=function(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()},a}();Scene.prototype.createDefaultLight=function(a){if(a===void 0&&(a=!1),a&&this.lights)for(var i=0;i<this.lights.length;i++)this.lights[i].dispose();this.lights.length===0&&new HemisphericLight("default light",Vector3.Up(),this)};Scene.prototype.createDefaultCamera=function(a,i,e){if(a===void 0&&(a=!1),i===void 0&&(i=!1),e===void 0&&(e=!1),i&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){var o=this.getWorldExtends(function(j){return j.isVisible&&j.isEnabled()}),s=o.max.subtract(o.min),c=o.min.add(s.scale(.5)),d,_=s.length()*1.5;if(isFinite(_)||(_=1,c.copyFromFloats(0,0,0)),a){var b=new ArcRotateCamera("default camera",-(Math.PI/2),Math.PI/2,_,c,this);b.lowerRadiusLimit=_*.01,b.wheelPrecision=100/_,d=b}else{var k=new FreeCamera("default camera",new Vector3(c.x,c.y,-_),this);k.setTarget(c),d=k}d.minZ=_*.01,d.maxZ=_*1e3,d.speed=_*.2,this.activeCamera=d,e&&d.attachControl()}};Scene.prototype.createDefaultCameraOrLight=function(a,i,e){a===void 0&&(a=!1),i===void 0&&(i=!1),e===void 0&&(e=!1),this.createDefaultLight(i),this.createDefaultCamera(a,i,e)};Scene.prototype.createDefaultSkybox=function(a,i,e,o,s){if(i===void 0&&(i=!1),e===void 0&&(e=1e3),o===void 0&&(o=0),s===void 0&&(s=!0),!a)return Logger$2.Warn("Can not create default skybox without environment texture."),null;s&&a&&(this.environmentTexture=a);var c=CreateBox("hdrSkyBox",{size:e},this);if(i){var d=new PBRMaterial("skyBox",this);d.backFaceCulling=!1,d.reflectionTexture=a.clone(),d.reflectionTexture&&(d.reflectionTexture.coordinatesMode=Texture.SKYBOX_MODE),d.microSurface=1-o,d.disableLighting=!0,d.twoSidedLighting=!0,c.material=d}else{var _=new StandardMaterial("skyBox",this);_.backFaceCulling=!1,_.reflectionTexture=a.clone(),_.reflectionTexture&&(_.reflectionTexture.coordinatesMode=Texture.SKYBOX_MODE),_.disableLighting=!0,c.material=_}return c.isPickable=!1,c.infiniteDistance=!0,c.ignoreCameraMaxZ=!0,c};Scene.prototype.createDefaultEnvironment=function(a){return EnvironmentHelper?new EnvironmentHelper(a,this):null};Scene.prototype.createDefaultVRExperience=function(a){return a===void 0&&(a={}),new VRExperienceHelper(this,a)};Scene.prototype.createDefaultXRExperienceAsync=function(a){return a===void 0&&(a={}),WebXRDefaultExperience.CreateAsync(this,a).then(function(i){return i})};var EMeshType=(a=>(a.XAvatar="XAvatar",a.XStaticMesh="XStaticMesh",a.XBreathPoint="breathpoint",a.Decal="decal",a.Cgplane="cgplane",a.Tv="tv",a.XSubSequence="XSubSequence",a.XBillboard="XBillboard",a))(EMeshType||{});const checkOS=()=>{const a=navigator.userAgent,i=/(?:Windows Phone)/.test(a),e=/(?:SymbianOS)/.test(a)||i,o=/(?:Android)/.test(a),s=/(?:Firefox)/.test(a);/(?:Chrome|CriOS)/.test(a);const c=/(?:iPad|PlayBook)/.test(a)||o&&!/(?:Mobile)/.test(a)||s&&/(?:Tablet)/.test(a),d=/(?:iPhone|ipad|ipod)/.test(a)&&!c,_=!d&&!o&&!e;return{isTablet:c,isPhone:d,isIOS:/iPhone|iPod|iPad/.test(navigator.userAgent),isAndroid:o,isPc:_}},ue4Rotation2Xverse=a=>isRotationCorrect$1()?(a.pitch>=89.5?a.pitch=89.5:a.pitch<=-89.5&&(a.pitch=-89.5),new Vector3(-1*Math.PI*a.pitch/180,Math.PI*a.yaw/180-Math.PI*27/18,Math.PI*a.roll/180<.001?0:Math.PI*a.roll/180)):null,ue4Rotation2Xverse_mesh=a=>isRotationCorrect$1()?new Vector3(Math.PI*a.pitch/180,Math.PI*a.yaw/180,Math.abs(Math.PI*a.roll)/180<.001?0:-1*(Math.PI*a.roll)/180):null,scaleFromUE4toXverse=100,ue4Scaling2Xverse=a=>isScalingCorrect()?new Vector3(a.x,a.z,-1*a.y):null,ue4Position2Xverse=a=>isPositionCorrect$1()?new Vector3(a.x*.01,a.z*.01,-1*a.y*.01):null,xversePosition2Ue4=a=>isPositionCorrect$1()?{x:a.x*100,y:-1*a.z*100,z:a.y*100}:null,xverseRotation2Ue4=a=>{if(isPositionCorrect$1()){let i=0;return a.z==0?i=0:i=180*a.z/Math.PI,{pitch:180*a.x*-1/Math.PI,yaw:(a.y+Math.PI*27/18)*180/Math.PI,roll:i}}else return null},xverseRotation2Ue4_mesh=a=>{if(isPositionCorrect$1()){let i=0;return a.z==0?i=0:i=-1*(180*a.z)/Math.PI,{pitch:180*a.x/Math.PI,yaw:a.y*180/Math.PI,roll:i}}else return null},calcDistance3D=(a,i)=>Math.sqrt((a.x-i.x)*(a.x-i.x)+(a.y-i.y)*(a.y-i.y)+(a.z-i.z)*(a.z-i.z)),calcDistance3DVector=(a,i)=>Math.sqrt((a.x-i.x)*(a.x-i.x)+(a.y-i.y)*(a.y-i.y)+(a.z-i.z)*(a.z-i.z)),isPositionCorrect$1=a=>!0,isScalingCorrect=a=>!0,calcDistance3DAngle=(a,i)=>Math.sqrt((a.roll-i.roll)*(a.roll-i.roll)+(a.pitch-i.pitch)*(a.pitch-i.pitch)+(a.yaw-i.yaw)*(a.yaw-i.yaw)),isRotationCorrect$1=a=>!0,computeWordLength=(a,i=new Map)=>{let e=0;for(let o=0;o<a.length;o++){const s=a.codePointAt(o),c=i.get(s);if(c)e+=c;else if(s<975||s>1024&&s<1920)e++;else if(s>4499&&s<4600||s>8207&&s<8232||s>8238&&s<8287||s>8238&&s<8287||s>8304&&s<8384||s>8447&&s<9211||s>11263&&s<11624||s>11646&&s<11671||s>11679&&s<11845||s>11903&&s<12020||s>12031&&s<12246||s>12287&&s<12544||s>12548&&s<12728||s>12735&&s<12772||s>12783&&s<19894||s>19967&&s<40918||s>42191&&s<42240||s>44031&&s<55204||s>59276&&s<59287||s>59412&&s<59493||s>63743&&s<64207||s>65039&&s<65050||s>65071&&s<65510)e+=2;else if(s>9311&&s<11158||s>126979&&s<129783){e+=2;const d=a.codePointAt(o+1);d>65023&&d<65040&&o++}else console.log("String has non-supported character!",s,a[o])}return e},getStringBoundaries=(a,i,e=new Map)=>{let o=0,s="",c=-1,d=0;const _=[0];for(let b=0;b<a.length;b++){const k=a.codePointAt(b);let j=e.get(k);if(j)o+=j,s+=a[b],k>64&&k<91||k>96&&k<123?(c==-1&&(c=b),d+=j):(c=-1,d=0);else if(k<975||k>1024&&k<1920)j=1,o++,s+=a[b],k>64&&k<91||k>96&&k<123?(c==-1&&(c=b),d+=j):(c=-1,d=0);else if(k>4499&&k<4600||k>8207&&k<8232||k>8238&&k<8287||k>8238&&k<8287||k>8304&&k<8384||k>8447&&k<9211||k>11263&&k<11624||k>11646&&k<11671||k>11679&&k<11845||k>11903&&k<12020||k>12031&&k<12246||k>12287&&k<12544||k>12548&&k<12728||k>12735&&k<12772||k>12783&&k<19894||k>19967&&k<40918||k>42191&&k<42240||k>44031&&k<55204||k>59276&&k<59287||k>59412&&k<59493||k>63743&&k<64207||k>65039&&k<65050||k>65071&&k<65510)j=2,o+=2,c=-1,d=0,s+=a[b];else if(k>9311&&k<11158){j=2,o+=2,c=-1,d=0,s+=a[b];const $=a.codePointAt(b+1);$>65023&&$<65040&&(s+=a[b+1],b++)}else k>126979&&k<129783&&(j=2,o+=2,c=-1,d=0,b++,s+=String.fromCodePoint(k));if(b==_[_.length-1]+1&&c>0?(_[_.length-1]=c,o=0+d):o>i&&(_.push(b),d>=o&&(d=0+j,c=0),o=0+j),b>=a.length-1)break}return _[_.length-1]!=a.length&&_.push(a.length),[s,_]},getAlphaWidthMap=(a,i)=>{const e=new DynamicTexture("test",3,i),o=new Map;for(let s=32;s<127;s++){const c=String.fromCodePoint(s),d=2+"px "+a;e.drawText(c,null,null,d,"#000000","#ffffff",!0);const _=e.getContext();_.font=d;const b=_.measureText(c).width;o.set(s,b)}return e.dispose(),o},_RegisteredClass={};function RegisterXObjectClass(a,i){_RegisteredClass[a]=i}function GetXObjectClass(a){return _RegisteredClass[a]}const DEFAULT_LOGGER={debug:console.log,info:console.log,warn:console.warn,error:console.error},fr=class{constructor(i){ct(this,"module");this.module=i}static setLogger(i){fr.instance=i}debug(...i){return fr.instance.debug(...i)}info(...i){return fr.instance.info(...i)}warn(...i){return fr.instance.warn(...i)}error(...i){return fr.instance.error(...i)}};let Logger$1=fr;ct(Logger$1,"instance",DEFAULT_LOGGER);new Logger$1("Serialization");const __decoratorInitialStore={},__mergedStore={},deepCopy=function(a,i,e){let o;if(i||(i=""),e||(e=!1),a==null||typeof a!="object")return a;if(a instanceof Date)return o=new Date,o.setTime(a.getTime()),o;if(a instanceof Array){o=[];for(let s=0,c=a.length;s<c;s++)o[s]=deepCopy(a[s],i,e);return o}if(a instanceof Object){if(a instanceof XObject)return o=_copySource(a,i,e),o;if(a instanceof AssetContainer)return e?o=a.clone(i,!1,{doNotInstantiate:!0},!1):o=a.clone(i),o;for(const s in a)Object.prototype.hasOwnProperty.call(a,s)&&(o[s]=deepCopy(a[s]));return o}throw new Error("Unable to copy obj! Its type isn't supported.")},_copySource=function(a,i,e){const o=GetXObjectClass(a.getClassName()),s=new o,c=getPropertiesMarkAsSerializable(s);i||(i=""),e||(e=!1);for(const d in c){const _=a[d];if(_!=null){const b=s;_ instanceof XObject?b[d]=_copySource(_,i,e):b[d]=deepCopy(_,i,e)}}return s.name=i,s};function getDirectStore(a){const i=a.getClassName();return __decoratorInitialStore[i]||(__decoratorInitialStore[i]={}),__decoratorInitialStore[i]}function generateSerializableMember(a,i){return(e,o)=>{const s=getDirectStore(e);s[o]||(s[o]={type:a,sourceName:i})}}function xProperty(a){return generateSerializableMember(0,a)}function getPropertiesMarkAsSerializable(a){const i=a.getClassName();if(__mergedStore[i])return __mergedStore[i];__mergedStore[i]={};const e=__mergedStore[i];let o=a,s=i;for(;s;){const c=__decoratorInitialStore[s];for(const b in c)e[b]=c[b];let d,_=!1;do{if(d=Object.getPrototypeOf(o),!d.getClassName){_=!0;break}if(d.getClassName()!==s)break;o=d}while(d);if(_)break;s=d.getClassName(),o=d}return e}class XArchive{constructor(){ct(this,"loadingPromises");this.loadingPromises=new Array}static serialize(i){if(!i.outer)return{className:"",uuid:0,xobjectInfo:{},sceneInfo:""};const o=i.outer.uuid,s={className:"",uuid:0,xobjectInfo:{},sceneInfo:""};s.className=i.getClassName(),s.uuid=o;const c=getPropertiesMarkAsSerializable(i);for(const d in c){const b=c[d].sourceName||d,k=i[d];s.xobjectInfo[b]=k}return s}async deserializeObject(i,e=""){if(i==null||typeof i!="object"||i instanceof Date)return i;if(i instanceof Array){for(let o=0,s=i.length;o<s;o++)i[o]=this.deserializeObject(i[o],e);return i}if(i instanceof Object){if(i.className)GetXObjectClass(i.className)&&this.deserialize(i,e);else return i;return i}throw new Error("Unable to copy obj! Its type isn't supported.")}async deserialize(i,e=""){const o=GetXObjectClass(i.className);if(!o)throw new Error("Unable to deserialize obj! Its type isn't XObject.");const s=new o,c=getPropertiesMarkAsSerializable(s);for(const d in c){const _=c[d],b=i.xobjectInfo[_.sourceName||d];if(b!=null)if(s[d]instanceof AssetContainer){const k=await SceneLoader.LoadAssetContainerAsync(e,b.sceneInfo,EngineStore.LastCreatedScene);s[d]=k,k.addAllToScene()}else s[d]instanceof XObject?s[d]=await this.deserialize(b,e):s[d]=await this.deserializeObject(b,e)}return s.postLoad(),s}static clone(i,e,o){return deepCopy(i,e,o)}}var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=(a,i,e,o)=>{for(var s=o>1?void 0:o?__getOwnPropDesc$3(i,e):i,c=a.length-1,d;c>=0;c--)(d=a[c])&&(s=(o?d(i,e,s):d(s))||s);return o&&s&&__defProp$3(i,e,s),s};class XObject{constructor(){ct(this,"_outer");ct(this,"_name","");this._outer=null}set outer(i){this._outer=i}get outer(){return this._outer}get name(){return this._name}set name(i){this._name=i}getClassName(){return"XObject"}toJSON(){return XArchive.serialize(this)}dispose(){}postLoad(){}clone(i){return XArchive.clone(this,i)}}__decorateClass$3([xProperty("name")],XObject.prototype,"_name",2);RegisterXObjectClass("XObject",XObject);var Codes$1=(a=>(a[a.Success=0]="Success",a[a.Timeout=1003]="Timeout",a))(Codes$1||{});const COMPONENT_LIST_PREFIX="/component_list.json";class XverseError$1 extends Error{constructor(e,o){super(o);ct(this,"code");this.code=e}toJSON(){return{code:this.code,message:this.message}}toString(){if(Object(this)!==this)throw new TypeError;let o=this.name;o=o===void 0?"Error":String(o);let s=this.message;s=s===void 0?"":String(s);const c=this.code;return s=c===void 0?s:c+","+s,o===""?s:s===""?o:o+": "+s}}class AvatarAssetLoadingError extends XverseError$1{constructor(i){super(5100,i||"[Engine] \u89D2\u8272\u8D44\u4EA7\u52A0\u8F7D\u5931\u8D25")}}class AvatarAnimationError extends XverseError$1{constructor(i){super(5101,i||"[Engine] \u89D2\u8272\u52A8\u753B\u64AD\u653E\u5931\u8D25")}}class TimeoutError$1 extends XverseError$1{constructor(i){super(Codes$1.Timeout,i||"[Engine] \u8D85\u65F6\u9519\u8BEF")}}class DuplicateAvatarIDError extends XverseError$1{constructor(i){super(5103,i||"[Engine] \u89D2\u8272id\u91CD\u590D")}}class ContainerLoadingFailedError extends XverseError$1{constructor(i){super(5104,i||"[Engine] \u89D2\u8272\u8D44\u4EA7\u62C9\u53D6\u9519\u8BEF")}}class XTvMediaUrlError extends XverseError$1{constructor(i){super(5201,i||"[Engine] \u4F20\u5165Url\u9519\u8BEF")}}class XTvVideoElementError extends XverseError$1{constructor(i){super(5202,i||"[Engine] \u4F20\u5165video DOM\u9519\u8BEF")}}class XTvModelError extends XverseError$1{constructor(i){super(5203,i||"[Engine] \u4F20\u5165TV\u6A21\u578Burl\u9519\u8BEF")}}class XLowpolyModelError extends XverseError$1{constructor(i){super(5204,i||"[Engine] \u4F20\u5165\u6A21\u578Burl\u9519\u8BEF")}}class XLowpolyJsonError extends XverseError$1{constructor(i){super(5205,i||"[Engine] \u4F20\u5165\u6A21\u578Bjson\u9519\u8BEF")}}class XDecalError extends XverseError$1{constructor(i){super(5206,i||"[Engine] Decal\u6A21\u578B\u9519\u8BEF")}}class XDecalTextureError extends XverseError$1{constructor(i){super(5207,i||"[Engine] decal\u7EB9\u7406\u9519\u8BEF")}}class XBreathPointError extends XverseError$1{constructor(i){super(5208,i||"[Engine] \u547C\u5438\u70B9\u9519\u8BEF")}}class XMaterialError extends XverseError$1{constructor(i){super(5210,i||"[Engine] Material\u9519\u8BEF")}}class ExceedMaxAvatarNumError extends XverseError$1{constructor(i){super(5211,i||"[Engine] \u89D2\u8272\u4E2A\u6570\u8D85\u51FA\u4E0A\u9650")}}const avatarSetting={fileType:".glb",lodType:"_lod",lod:[{level:"lod0",fileName:".glb",quota:5,dist:1e3},{level:"lod1",fileName:"_lod2.glb",quota:5,dist:2e3},{level:"lod2",fileName:"_lod4.glb",quota:0,dist:7500}],isRayCastEnable:!0,maxAvatarNum:40,maxBillBoardDist:7500,body:"body",head:"head",hair:"hair",suit:"suit",pants:"pants",shoes:"shoes",clothes:"clothes",animations:"animations",defaultIdle:"Idle",cullingDistance:200,defaultMove:"Walking"},avatarResources={ygb:{name:"ygb",mat:"NM_ygb",mesh:"ygb"}},action={GiftClap:{animName:"GiftClap",keyTime:1760},Cheering:{animName:"Cheering",attachPair:[{bone:"mixamorig_MiddleFinger2_R",obj:"ygb",offset:{x:0,y:0,z:0},rotate:{x:0,y:3.84,z:0},scale:{x:1,y:1,z:1}},{bone:"mixamorig_MiddleFinger2_L",obj:"ygb",offset:{x:0,y:0,z:0},rotate:{x:0,y:3.49,z:0},scale:{x:1,y:1,z:1}}]}},getAnimationKey=(a,i)=>i+"_"+a;var _GLTFUtilities=function(){function a(){}return a._CreateBufferView=function(i,e,o,s,c){var d={buffer:i,byteLength:o};return e&&(d.byteOffset=e),c&&(d.name=c),s&&(d.byteStride=s),d},a._CreateAccessor=function(i,e,o,s,c,d,_,b){var k={name:e,bufferView:i,componentType:s,count:c,type:o};return _!=null&&(k.min=_),b!=null&&(k.max=b),d!=null&&(k.byteOffset=d),k},a._CalculateMinMaxPositions=function(i,e,o,s){var c=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0],_=3,b,k,j;if(o)for(var $=e,_e=e+o;$<_e;++$){b=_*$,k=Vector3.FromArray(i,b),s&&a._GetRightHandedPositionVector3FromRef(k),j=k.asArray();for(var et=0;et<_;++et){var tt=j[et];tt<c[et]&&(c[et]=tt),tt>d[et]&&(d[et]=tt),++b}}return{min:c,max:d}},a._GetRightHandedPositionVector3=function(i){return new Vector3(i.x,i.y,-i.z)},a._GetRightHandedPositionVector3FromRef=function(i){i.z*=-1},a._GetRightHandedPositionArray3FromRef=function(i){i[2]*=-1},a._GetRightHandedNormalVector3=function(i){return new Vector3(i.x,i.y,-i.z)},a._GetRightHandedNormalVector3FromRef=function(i){i.z*=-1},a._GetRightHandedNormalArray3FromRef=function(i){i[2]*=-1},a._GetRightHandedVector4FromRef=function(i){i.z*=-1,i.w*=-1},a._GetRightHandedArray4FromRef=function(i){i[2]*=-1,i[3]*=-1},a._GetRightHandedQuaternionFromRef=function(i){i.x*=-1,i.y*=-1},a._GetRightHandedQuaternionArrayFromRef=function(i){i[0]*=-1,i[1]*=-1},a._NormalizeTangentFromRef=function(i){var e=Math.sqrt(i.x*i.x+i.y*i.y+i.z*i.z);e>0&&(i.x/=e,i.y/=e,i.z/=e)},a._GetDataAccessorElementCount=function(i){switch(i){case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4}},a}(),_TangentType;(function(a){a[a.INTANGENT=0]="INTANGENT",a[a.OUTTANGENT=1]="OUTTANGENT"})(_TangentType||(_TangentType={}));var _GLTFAnimation=function(){function a(){}return a._CreateNodeAnimation=function(i,e,o,s,c,d){var _=[],b=[],k=e.getKeys(),j=a.calculateMinMaxKeyFrames(k),$=a._DeduceInterpolation(k,o,c),_e=j.max-j.min,et=$.interpolationType,tt=$.shouldBakeAnimation;if(tt?a._CreateBakedAnimation(i,e,o,j.min,j.max,e.framePerSecond,d,_,b,j,s,c):et==="LINEAR"||et==="STEP"?a._CreateLinearOrStepAnimation(i,e,o,_e,_,b,s,c):et==="CUBICSPLINE"?a._CreateCubicSplineAnimation(i,e,o,_e,_,b,s,c):a._CreateBakedAnimation(i,e,o,j.min,j.max,e.framePerSecond,d,_,b,j,s,c),_.length&&b.length){var rt={inputs:_,outputs:b,samplerInterpolation:et,inputsMin:tt?j.min:Tools.FloatRound(j.min/e.framePerSecond),inputsMax:tt?j.max:Tools.FloatRound(j.max/e.framePerSecond)};return rt}return null},a._DeduceAnimationInfo=function(i){var e=null,o="VEC3",s=!1,c=i.targetProperty.split(".");switch(c[0]){case"scaling":{e="scale";break}case"position":{e="translation";break}case"rotation":{o="VEC4",e="rotation";break}case"rotationQuaternion":{o="VEC4",s=!0,e="rotation";break}case"influence":{o="SCALAR",e="weights";break}default:Tools.Error("Unsupported animatable property "+c[0])}return e?{animationChannelTargetPath:e,dataAccessorType:o,useQuaternion:s}:(Tools.Error("animation channel target path and data accessor type could be deduced"),null)},a._CreateNodeAnimationFromNodeAnimations=function(i,e,o,s,c,d,_,b,k,j){var $;if(i instanceof TransformNode&&i.animations)for(var _e=0,et=i.animations;_e<et.length;_e++){var tt=et[_e],rt=a._DeduceAnimationInfo(tt);rt&&($={name:tt.name,samplers:[],channels:[]},a.AddAnimation(""+tt.name,tt.hasRunningRuntimeAnimations?e:$,i,tt,rt.dataAccessorType,rt.animationChannelTargetPath,s,d,_,b,k,rt.useQuaternion,j),$.samplers.length&&$.channels.length&&o.push($))}},a._CreateMorphTargetAnimationFromMorphTargetAnimations=function(i,e,o,s,c,d,_,b,k,j){var $;if(i instanceof Mesh){var _e=i.morphTargetManager;if(_e)for(var et=0;et<_e.numTargets;++et)for(var tt=_e.getTarget(et),rt=0,it=tt.animations;rt<it.length;rt++){for(var nt=it[rt],ot=new Animation(""+nt.name,"influence",nt.framePerSecond,nt.dataType,nt.loopMode,nt.enableBlending),at=[],st=nt.getKeys(),ut=0;ut<st.length;++ut)for(var ft=st[ut],lt=0;lt<_e.numTargets;++lt)lt==et?at.push(ft):at.push({frame:ft.frame,value:0});ot.setKeys(at);var ht=a._DeduceAnimationInfo(ot);ht&&($={name:ot.name,samplers:[],channels:[]},a.AddAnimation(nt.name,nt.hasRunningRuntimeAnimations?e:$,i,ot,ht.dataAccessorType,ht.animationChannelTargetPath,s,d,_,b,k,ht.useQuaternion,j,_e.numTargets),$.samplers.length&&$.channels.length&&o.push($))}}},a._CreateNodeAndMorphAnimationFromAnimationGroups=function(i,e,o,s,c,d,_,b,k){var j,$;if(i.animationGroups)for(var _e=i.animationGroups,et=function(nt){var ot=new Map,at=new Map,st=new Set,ut=nt.to-nt.from;$={name:nt.name,channels:[],samplers:[]};for(var ft=function(ht){var pt=nt.targetedAnimations[ht],mt=pt.target,dt=pt.animation;if(mt instanceof TransformNode||mt.length===1&&mt[0]instanceof TransformNode){var gt=a._DeduceAnimationInfo(pt.animation);if(gt){var _t=mt instanceof TransformNode?mt:mt[0],yt=b[_t.uniqueId];a.AddAnimation(""+dt.name,$,_t,dt,gt.dataAccessorType,gt.animationChannelTargetPath,o,c,d,_,yt,gt.useQuaternion,k)}}else if(mt instanceof MorphTarget||mt.length===1&&mt[0]instanceof MorphTarget){var gt=a._DeduceAnimationInfo(pt.animation);if(gt){var Tt=mt instanceof MorphTarget?mt:mt[0];if(Tt){var St=i.morphTargetManagers.find(function(Et){for(var xt=0;xt<Et.numTargets;++xt)if(Et.getTarget(xt)===Tt)return!0;return!1});if(St){var At=i.meshes.find(function(Et){return Et.morphTargetManager===St});At&&(ot.has(At)||ot.set(At,new Map),(j=ot.get(At))===null||j===void 0||j.set(Tt,dt),st.add(At),at.set(At,dt))}}}}},lt=0;lt<nt.targetedAnimations.length;++lt)ft(lt);st.forEach(function(ht){for(var pt=ht.morphTargetManager,mt=null,dt=[],gt=at.get(ht),_t=gt.getKeys(),yt=_t.length,Tt=0;Tt<yt;++Tt)for(var St=0;St<pt.numTargets;++St){var At=pt.getTarget(St),vt=ot.get(ht);if(vt){var Et=vt.get(At);Et?(mt||(mt=new Animation(nt.name+"_"+ht.name+"_MorphWeightAnimation","influence",Et.framePerSecond,Animation.ANIMATIONTYPE_FLOAT,Et.loopMode,Et.enableBlending)),dt.push(Et.getKeys()[Tt])):dt.push({frame:nt.from+ut/yt*Tt,value:At.influence,inTangent:_t[0].inTangent?0:void 0,outTangent:_t[0].outTangent?0:void 0})}}mt.setKeys(dt);var xt=a._DeduceAnimationInfo(mt);xt&&a.AddAnimation(nt.name+"_"+ht.name+"_MorphWeightAnimation",$,ht,mt,xt.dataAccessorType,xt.animationChannelTargetPath,o,c,d,_,!1,xt.useQuaternion,k,pt==null?void 0:pt.numTargets)}),$.channels.length&&$.samplers.length&&e.push($)},tt=0,rt=_e;tt<rt.length;tt++){var it=rt[tt];et(it)}},a.AddAnimation=function(i,e,o,s,c,d,_,b,k,j,$,_e,et,tt){var rt=a._CreateNodeAnimation(o,s,d,$,_e,et),it,nt,ot,at,st,ut,ft;if(rt){if(tt){for(var lt=0,ht=0,pt=[];rt.inputs.length>0;)ht=rt.inputs.shift(),lt%tt==0&&pt.push(ht),lt++;rt.inputs=pt}var mt=_[o.uniqueId],dt=rt.inputs.length*4;it=_GLTFUtilities._CreateBufferView(0,b.getByteOffset(),dt,void 0,i+" keyframe data view"),k.push(it),rt.inputs.forEach(function(gt){b.setFloat32(gt)}),nt=_GLTFUtilities._CreateAccessor(k.length-1,i+" keyframes","SCALAR",5126,rt.inputs.length,null,[rt.inputsMin],[rt.inputsMax]),j.push(nt),ot=j.length-1,st=rt.outputs.length,dt=_GLTFUtilities._GetDataAccessorElementCount(c)*4*rt.outputs.length,it=_GLTFUtilities._CreateBufferView(0,b.getByteOffset(),dt,void 0,i+" data view"),k.push(it),rt.outputs.forEach(function(gt){gt.forEach(function(_t){b.setFloat32(_t)})}),nt=_GLTFUtilities._CreateAccessor(k.length-1,i+" data",c,5126,st,null,null,null),j.push(nt),at=j.length-1,ut={interpolation:rt.samplerInterpolation,input:ot,output:at},e.samplers.push(ut),ft={sampler:e.samplers.length-1,target:{node:mt,path:d}},e.channels.push(ft)}},a._CreateBakedAnimation=function(i,e,o,s,c,d,_,b,k,j,$,_e){var et,tt=Quaternion.Identity(),rt=null,it,nt=null,ot=null,at=null,st=null,ut=null;j.min=Tools.FloatRound(s/d);for(var ft=e.getKeys(),lt=0,ht=ft.length;lt<ht;++lt){if(ut=null,ot=ft[lt],lt+1<ht)if(at=ft[lt+1],ot.value.equals&&ot.value.equals(at.value)||ot.value===at.value)if(lt===0)ut=ot.frame;else continue;else ut=at.frame;else{if(st=ft[lt-1],ot.value.equals&&ot.value.equals(st.value)||ot.value===st.value)continue;ut=c}if(ut){for(var pt=ot.frame;pt<=ut;pt+=_)if(it=Tools.FloatRound(pt/d),it!==rt){rt=it,nt=it;var mt={key:0,repeatCount:0,loopMode:e.loopMode};et=e._interpolate(pt,mt),a._SetInterpolatedValue(i,et,it,e,o,tt,b,k,$,_e)}}}nt&&(j.max=nt)},a._ConvertFactorToVector3OrQuaternion=function(i,e,o,s,c,d,_){var b,k,j=null,$=a._GetBasePositionRotationOrScale(e,c,d,_);if(s===Animation.ANIMATIONTYPE_FLOAT)switch(b=o.targetProperty.split("."),k=b?b[1]:"",j=_?Quaternion.FromArray($).normalize():Vector3.FromArray($),k){case"x":{j[k]=d&&_&&c!=="scale"?-i:i;break}case"y":{j[k]=d&&_&&c!=="scale"?-i:i;break}case"z":{j[k]=d&&!_&&c!=="scale"?-i:i;break}case"w":{j.w=i;break}default:Tools.Error('glTFAnimation: Unsupported component type "'+k+'" for scale animation!')}return j},a._SetInterpolatedValue=function(i,e,o,s,c,d,_,b,k,j){var $=s.dataType,_e;_.push(o),typeof e=="number"&&i instanceof TransformNode&&(e=this._ConvertFactorToVector3OrQuaternion(e,i,s,$,c,k,j)),e&&(c==="rotation"?(j?d=e:(_e=e,Quaternion.RotationYawPitchRollToRef(_e.y,_e.x,_e.z,d)),k&&(_GLTFUtilities._GetRightHandedQuaternionFromRef(d),i.parent||(d=Quaternion.FromArray([0,1,0,0]).multiply(d))),b.push(d.asArray())):c==="weights"?b.push([e]):(_e=e,k&&c!=="scale"&&(_GLTFUtilities._GetRightHandedPositionVector3FromRef(_e),i.parent||(_e.x*=-1,_e.z*=-1)),b.push(_e.asArray())))},a._CreateLinearOrStepAnimation=function(i,e,o,s,c,d,_,b){for(var k=0,j=e.getKeys();k<j.length;k++){var $=j[k];c.push($.frame/e.framePerSecond),a._AddKeyframeValue($,e,d,o,i,_,b)}},a._CreateCubicSplineAnimation=function(i,e,o,s,c,d,_,b){e.getKeys().forEach(function(k){c.push(k.frame/e.framePerSecond),a.AddSplineTangent(i,_TangentType.INTANGENT,d,o,"CUBICSPLINE",k,s,b,_),a._AddKeyframeValue(k,e,d,o,i,_,b),a.AddSplineTangent(i,_TangentType.OUTTANGENT,d,o,"CUBICSPLINE",k,s,b,_)})},a._GetBasePositionRotationOrScale=function(i,e,o,s){var c;return e==="rotation"?s?i.rotationQuaternion?(c=i.rotationQuaternion.asArray(),o&&(_GLTFUtilities._GetRightHandedQuaternionArrayFromRef(c),i.parent||(c=Quaternion.FromArray([0,1,0,0]).multiply(Quaternion.FromArray(c)).asArray()))):c=Quaternion.Identity().asArray():(c=i.rotation.asArray(),_GLTFUtilities._GetRightHandedNormalArray3FromRef(c)):e==="translation"?(c=i.position.asArray(),o&&_GLTFUtilities._GetRightHandedPositionArray3FromRef(c)):c=i.scaling.asArray(),c},a._AddKeyframeValue=function(i,e,o,s,c,d,_){var b,k,j=e.dataType;if(j===Animation.ANIMATIONTYPE_VECTOR3){if(b=i.value.asArray(),s==="rotation"){var $=Vector3.FromArray(b),_e=Quaternion.RotationYawPitchRoll($.y,$.x,$.z);d&&(_GLTFUtilities._GetRightHandedQuaternionFromRef(_e),c.parent||(_e=Quaternion.FromArray([0,1,0,0]).multiply(_e))),b=_e.asArray()}else s==="translation"&&d&&(_GLTFUtilities._GetRightHandedNormalArray3FromRef(b),c.parent||(b[0]*=-1,b[2]*=-1));o.push(b)}else if(j===Animation.ANIMATIONTYPE_FLOAT){if(s==="weights")o.push([i.value]);else if(k=this._ConvertFactorToVector3OrQuaternion(i.value,c,e,j,s,d,_),k){if(s==="rotation"){var et=_?k:Quaternion.RotationYawPitchRoll(k.y,k.x,k.z).normalize();d&&(_GLTFUtilities._GetRightHandedQuaternionFromRef(et),c.parent||(et=Quaternion.FromArray([0,1,0,0]).multiply(et))),o.push(et.asArray())}else s==="translation"&&d&&(_GLTFUtilities._GetRightHandedNormalVector3FromRef(k),c.parent||(k.x*=-1,k.z*=-1));o.push(k.asArray())}}else j===Animation.ANIMATIONTYPE_QUATERNION?(b=i.value.normalize().asArray(),d&&(_GLTFUtilities._GetRightHandedQuaternionArrayFromRef(b),c.parent||(b=Quaternion.FromArray([0,1,0,0]).multiply(Quaternion.FromArray(b)).asArray())),o.push(b)):Tools.Error("glTFAnimation: Unsupported key frame values for animation!")},a._DeduceInterpolation=function(i,e,o){var s,c=!1,d;if(e==="rotation"&&!o)return{interpolationType:"LINEAR",shouldBakeAnimation:!0};for(var _=0,b=i.length;_<b;++_)if(d=i[_],d.inTangent||d.outTangent)if(s){if(s!=="CUBICSPLINE"){s="LINEAR",c=!0;break}}else s="CUBICSPLINE";else if(s){if(s==="CUBICSPLINE"||d.interpolation&&d.interpolation===AnimationKeyInterpolation.STEP&&s!=="STEP"){s="LINEAR",c=!0;break}}else d.interpolation&&d.interpolation===AnimationKeyInterpolation.STEP?s="STEP":s="LINEAR";return s||(s="LINEAR"),{interpolationType:s,shouldBakeAnimation:c}},a.AddSplineTangent=function(i,e,o,s,c,d,_,b,k){var j,$=e===_TangentType.INTANGENT?d.inTangent:d.outTangent;if(c==="CUBICSPLINE"){if(s==="rotation")if($){if(b)j=$.asArray();else{var _e=$;j=Quaternion.RotationYawPitchRoll(_e.y,_e.x,_e.z).asArray()}k&&(_GLTFUtilities._GetRightHandedQuaternionArrayFromRef(j),i.parent||(j=Quaternion.FromArray([0,1,0,0]).multiply(Quaternion.FromArray(j)).asArray()))}else j=[0,0,0,0];else s==="weights"?$?j=[$]:j=[0]:$?(j=$.asArray(),k&&s==="translation"&&(_GLTFUtilities._GetRightHandedPositionArray3FromRef(j),i.parent||(j[0]*=-1,j[2]*=-1))):j=[0,0,0];o.push(j)}},a.calculateMinMaxKeyFrames=function(i){var e=1/0,o=-1/0;return i.forEach(function(s){e=Math.min(e,s.frame),o=Math.max(o,s.frame)}),{min:e,max:o}},a}(),GLTFData=function(){function a(){this.glTFFiles={}}return a.prototype.downloadFiles=function(){function i(d,_){return d.indexOf(_,d.length-_.length)!==-1}for(var e in this.glTFFiles){var o=document.createElement("a");document.body.appendChild(o),o.setAttribute("type","hidden"),o.download=e;var s=this.glTFFiles[e],c=void 0;i(e,".glb")?c={type:"model/gltf-binary"}:i(e,".bin")?c={type:"application/octet-stream"}:i(e,".gltf")?c={type:"model/gltf+json"}:i(e,".jpeg")||i(e,".jpg")?c={type:"image/jpeg"}:i(e,".png")&&(c={type:"image/png"}),o.href=window.URL.createObjectURL(new Blob([s],c)),o.click()}},a}(),_GLTFMaterialExporter=function(){function a(i){this._textureMap={},this._textureMap={},this._exporter=i}return a.FuzzyEquals=function(i,e,o){return Scalar.WithinEpsilon(i.r,e.r,o)&&Scalar.WithinEpsilon(i.g,e.g,o)&&Scalar.WithinEpsilon(i.b,e.b,o)},a.prototype._convertMaterialsToGLTFAsync=function(i,e,o){for(var s=[],c=0,d=i;c<d.length;c++){var _=d[c];_.getClassName()==="StandardMaterial"?s.push(this._convertStandardMaterialAsync(_,e,o)):_.getClassName().indexOf("PBR")!==-1?s.push(this._convertPBRMaterialAsync(_,e,o)):Tools.Warn("Unsupported material type: "+_.name)}return Promise.all(s).then(function(){})},a.prototype._stripTexturesFromMaterial=function(i){var e={};if(i){e.name=i.name,e.doubleSided=i.doubleSided,e.alphaMode=i.alphaMode,e.alphaCutoff=i.alphaCutoff,e.emissiveFactor=i.emissiveFactor;var o=i.pbrMetallicRoughness;o&&(e.pbrMetallicRoughness={},e.pbrMetallicRoughness.baseColorFactor=o.baseColorFactor,e.pbrMetallicRoughness.metallicFactor=o.metallicFactor,e.pbrMetallicRoughness.roughnessFactor=o.roughnessFactor)}return e},a.prototype._hasTexturesPresent=function(i){var e;if(i.emissiveTexture||i.normalTexture||i.occlusionTexture)return!0;var o=i.pbrMetallicRoughness;if(o&&(o.baseColorTexture||o.metallicRoughnessTexture))return!0;if(i.extensions)for(var s in i.extensions){var c=i.extensions[s];if(c)return(e=c.hasTextures)===null||e===void 0?void 0:e.call(c)}return!1},a.prototype._getTextureInfo=function(i){if(i){var e=i.uid;if(e in this._textureMap)return this._textureMap[e]}return null},a.prototype._convertToGLTFPBRMetallicRoughness=function(i){var e=new Vector2(0,1),o=new Vector2(0,.1),s=new Vector2(0,.1),c=new Vector2(1300,.1);function d(et,tt,rt,it,nt){return(1-et)*(1-et)*(1-et)*tt+3*(1-et)*(1-et)*et*rt+3*(1-et)*et*et*it+et*et*et*nt}function _(et){var tt=Math.pow(et/c.x,.333333);return d(tt,e.y,o.y,s.y,c.y)}var b=i.diffuseColor.toLinearSpace().scale(.5),k=i.alpha,j=Scalar.Clamp(i.specularPower,0,a._MaxSpecularPower),$=_(j),_e={baseColorFactor:[b.r,b.g,b.b,k],metallicFactor:0,roughnessFactor:$};return _e},a._SolveMetallic=function(i,e,o){if(e<this._DielectricSpecular.r)return this._DielectricSpecular,0;var s=this._DielectricSpecular.r,c=i*o/(1-this._DielectricSpecular.r)+e-2*this._DielectricSpecular.r,d=this._DielectricSpecular.r-e,_=c*c-4*s*d;return Scalar.Clamp((-c+Math.sqrt(_))/(2*s),0,1)},a._SetAlphaMode=function(i,e){e.needAlphaBlending()?i.alphaMode="BLEND":e.needAlphaTesting()&&(i.alphaMode="MASK",i.alphaCutoff=e.alphaCutOff)},a.prototype._convertStandardMaterialAsync=function(i,e,o){var s=this._exporter._materialMap,c=this._exporter._materials,d=[],_=this._convertToGLTFPBRMetallicRoughness(i),b={name:i.name};return i.backFaceCulling!=null&&!i.backFaceCulling&&(i.twoSidedLighting||Tools.Warn(i.name+": Back-face culling enabled and two-sided lighting disabled is not supported in glTF."),b.doubleSided=!0),o&&(i.diffuseTexture&&d.push(this._exportTextureAsync(i.diffuseTexture,e).then(function(k){k&&(_.baseColorTexture=k)})),i.bumpTexture&&d.push(this._exportTextureAsync(i.bumpTexture,e).then(function(k){k&&(b.normalTexture=k,i.bumpTexture!=null&&i.bumpTexture.level!==1&&(b.normalTexture.scale=i.bumpTexture.level))})),i.emissiveTexture&&(b.emissiveFactor=[1,1,1],d.push(this._exportTextureAsync(i.emissiveTexture,e).then(function(k){k&&(b.emissiveTexture=k)}))),i.ambientTexture&&d.push(this._exportTextureAsync(i.ambientTexture,e).then(function(k){if(k){var j={index:k.index};b.occlusionTexture=j,j.strength=1}}))),(i.alpha<1||i.opacityTexture)&&(i.alphaMode===Constants.ALPHA_COMBINE?b.alphaMode="BLEND":Tools.Warn(i.name+": glTF 2.0 does not support alpha mode: "+i.alphaMode.toString())),i.emissiveColor&&!a.FuzzyEquals(i.emissiveColor,Color3.Black(),a._Epsilon)&&(b.emissiveFactor=i.emissiveColor.asArray()),b.pbrMetallicRoughness=_,a._SetAlphaMode(b,i),c.push(b),s[i.uniqueId]=c.length-1,this._finishMaterial(d,b,i,e)},a.prototype._finishMaterial=function(i,e,o,s){var c=this;return Promise.all(i).then(function(){for(var d=c._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial",e,o),_=null,b=0,k=d;b<k.length;b++){var j=k[b];_||(_=[]),_.push(c._exportTextureAsync(j,s))}return _||(_=[Promise.resolve(null)]),Promise.all(_).then(function(){var $=c._exporter._extensionsPostExportMaterialAsync("exportMaterial",e,o);return $?$.then(function(){return e}):e})})},a.prototype._convertPBRMetallicRoughnessMaterialAsync=function(i,e,o){var s=this._exporter._materialMap,c=this._exporter._materials,d=[],_={};i.baseColor&&(_.baseColorFactor=[i.baseColor.r,i.baseColor.g,i.baseColor.b,i.alpha]),i.metallic!=null&&i.metallic!==1&&(_.metallicFactor=i.metallic),i.roughness!=null&&i.roughness!==1&&(_.roughnessFactor=i.roughness);var b={name:i.name};return i.doubleSided&&(b.doubleSided=i.doubleSided),a._SetAlphaMode(b,i),o&&(i.baseTexture!=null&&d.push(this._exportTextureAsync(i.baseTexture,e).then(function(k){k&&(_.baseColorTexture=k)})),i.normalTexture&&d.push(this._exportTextureAsync(i.normalTexture,e).then(function(k){k&&(b.normalTexture=k,i.normalTexture.level!==1&&(b.normalTexture.scale=i.normalTexture.level))})),i.occlusionTexture&&d.push(this._exportTextureAsync(i.occlusionTexture,e).then(function(k){k&&(b.occlusionTexture=k,i.occlusionStrength!=null&&(b.occlusionTexture.strength=i.occlusionStrength))})),i.emissiveTexture&&d.push(this._exportTextureAsync(i.emissiveTexture,e).then(function(k){k&&(b.emissiveTexture=k)}))),a.FuzzyEquals(i.emissiveColor,Color3.Black(),a._Epsilon)&&(b.emissiveFactor=i.emissiveColor.asArray()),b.pbrMetallicRoughness=_,c.push(b),s[i.uniqueId]=c.length-1,this._finishMaterial(d,b,i,e)},a.prototype._createBase64FromCanvasAsync=function(i,e,o,s){var c=this;return new Promise(function(d,_){return __awaiter(c,void 0,void 0,function(){var b,k,j,$,_e,et;return __generator(this,function(tt){switch(tt.label){case 0:return b=Constants.TEXTURETYPE_UNSIGNED_INT,k=this._exporter._babylonScene,j=k.getEngine(),$=j.createRawTexture(i,e,o,Constants.TEXTUREFORMAT_RGBA,!1,!0,Texture.NEAREST_SAMPLINGMODE,null,b),[4,TextureTools.ApplyPostProcess("pass",$,k,b,Constants.TEXTURE_NEAREST_SAMPLINGMODE,Constants.TEXTUREFORMAT_RGBA)];case 1:return tt.sent(),[4,j._readTexturePixels($,e,o)];case 2:return _e=tt.sent(),[4,Tools.DumpDataAsync(e,o,_e,s,void 0,!0,!1)];case 3:return et=tt.sent(),d(et),[2]}})})})},a.prototype._createWhiteTexture=function(i,e,o){for(var s=new Uint8Array(i*e*4),c=0;c<s.length;c=c+4)s[c]=s[c+1]=s[c+2]=s[c+3]=255;var d=RawTexture.CreateRGBATexture(s,i,e,o);return d},a.prototype._resizeTexturesToSameDimensions=function(i,e,o){var s=i?i.getSize():{width:0,height:0},c=e?e.getSize():{width:0,height:0},d,_;return s.width<c.width?(i&&i instanceof Texture?d=TextureTools.CreateResizedCopy(i,c.width,c.height,!0):d=this._createWhiteTexture(c.width,c.height,o),_=e):s.width>c.width?(e&&e instanceof Texture?_=TextureTools.CreateResizedCopy(e,s.width,s.height,!0):_=this._createWhiteTexture(s.width,s.height,o),d=i):(d=i,_=e),{texture1:d,texture2:_}},a.prototype._convertPixelArrayToFloat32=function(i){if(i instanceof Uint8Array){for(var e=i.length,o=new Float32Array(i.length),s=0;s<e;++s)o[s]=i[s]/255;return o}else{if(i instanceof Float32Array)return i;throw new Error("Unsupported pixel format!")}},a.prototype._convertSpecularGlossinessTexturesToMetallicRoughnessAsync=function(i,e,o,s){var c;return __awaiter(this,void 0,void 0,function(){var d,_,b,k,j,$,_e,et,tt,rt,it,nt,ot,at,st,ut,ft,St,At,lt,ht,pt,mt,dt,gt,_t,yt,Tt,St,At,vt,Et,xt,bt,Mt,Mt;return __generator(this,function(Rt){switch(Rt.label){case 0:return d=[],i||e?(_=i?i.getScene():e?e.getScene():null,_?(b=this._resizeTexturesToSameDimensions(i,e,_),k=(c=b.texture1)===null||c===void 0?void 0:c.getSize(),j=void 0,$=void 0,_e=k.width,et=k.height,[4,b.texture1.readPixels()]):[3,3]):[2,Promise.reject("_ConvertSpecularGlosinessTexturesToMetallicRoughness: diffuse and specular glossiness textures are not defined!")];case 1:return tt=Rt.sent(),[4,b.texture2.readPixels()];case 2:if(rt=Rt.sent(),tt)j=this._convertPixelArrayToFloat32(tt);else return[2,Promise.reject("Failed to retrieve pixels from diffuse texture!")];if(rt)$=this._convertPixelArrayToFloat32(rt);else return[2,Promise.reject("Failed to retrieve pixels from specular glossiness texture!")];for(it=$.byteLength,nt=new Uint8Array(it),ot=new Uint8Array(it),at=4,st=Color3.Black(),ut=0,ft=0,St=0;St<et;++St)for(At=0;At<_e;++At)lt=(_e*St+At)*at,ht=new Color3(j[lt],j[lt+1],j[lt+2]).toLinearSpace().multiply(o.diffuseColor),pt=new Color3($[lt],$[lt+1],$[lt+2]).toLinearSpace().multiply(o.specularColor),mt=$[lt+3]*o.glossiness,dt={diffuseColor:ht,specularColor:pt,glossiness:mt},gt=this._convertSpecularGlossinessToMetallicRoughness(dt),st.r=Math.max(st.r,gt.baseColor.r),st.g=Math.max(st.g,gt.baseColor.g),st.b=Math.max(st.b,gt.baseColor.b),ut=Math.max(ut,gt.metallic),ft=Math.max(ft,gt.roughness),ot[lt]=gt.baseColor.r*255,ot[lt+1]=gt.baseColor.g*255,ot[lt+2]=gt.baseColor.b*255,ot[lt+3]=b.texture1.hasAlpha?j[lt+3]*255:255,nt[lt]=0,nt[lt+1]=gt.roughness*255,nt[lt+2]=gt.metallic*255,nt[lt+3]=255;for(_t={baseColor:st,metallic:ut,roughness:ft},yt=!1,Tt=!1,St=0;St<et;++St)for(At=0;At<_e;++At)vt=(_e*St+At)*at,ot[vt]/=_t.baseColor.r>a._Epsilon?_t.baseColor.r:1,ot[vt+1]/=_t.baseColor.g>a._Epsilon?_t.baseColor.g:1,ot[vt+2]/=_t.baseColor.b>a._Epsilon?_t.baseColor.b:1,Et=Color3.FromInts(ot[vt],ot[vt+1],ot[vt+2]),xt=Et.toGammaSpace(),ot[vt]=xt.r*255,ot[vt+1]=xt.g*255,ot[vt+2]=xt.b*255,a.FuzzyEquals(xt,Color3.White(),a._Epsilon)||(Tt=!0),nt[vt+1]/=_t.roughness>a._Epsilon?_t.roughness:1,nt[vt+2]/=_t.metallic>a._Epsilon?_t.metallic:1,bt=Color3.FromInts(255,nt[vt+1],nt[vt+2]),a.FuzzyEquals(bt,Color3.White(),a._Epsilon)||(yt=!0);return yt&&(Mt=this._createBase64FromCanvasAsync(nt,_e,et,s).then(function(Pt){_t.metallicRoughnessTextureBase64=Pt}),d.push(Mt)),Tt&&(Mt=this._createBase64FromCanvasAsync(ot,_e,et,s).then(function(Pt){_t.baseColorTextureBase64=Pt}),d.push(Mt)),[2,Promise.all(d).then(function(){return _t})];case 3:return[2,Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")]}})})},a.prototype._convertSpecularGlossinessToMetallicRoughness=function(i){var e=this._getPerceivedBrightness(i.diffuseColor),o=this._getPerceivedBrightness(i.specularColor),s=1-this._getMaxComponent(i.specularColor),c=a._SolveMetallic(e,o,s),d=i.diffuseColor.scale(s/(1-a._DielectricSpecular.r)/Math.max(1-c,a._Epsilon)),_=i.specularColor.subtract(a._DielectricSpecular.scale(1-c)).scale(1/Math.max(c,a._Epsilon)),b=Color3.Lerp(d,_,c*c);b=b.clampToRef(0,1,b);var k={baseColor:b,metallic:c,roughness:1-i.glossiness};return k},a.prototype._getPerceivedBrightness=function(i){return i?Math.sqrt(.299*i.r*i.r+.587*i.g*i.g+.114*i.b*i.b):0},a.prototype._getMaxComponent=function(i){return i?Math.max(i.r,Math.max(i.g,i.b)):0},a.prototype._convertMetalRoughFactorsToMetallicRoughnessAsync=function(i,e,o,s){var c=[],d=i._albedoColor,_=i._metallic,b=i._roughness,k={baseColor:d,metallic:_,roughness:b};if(s){var j=i._albedoTexture;j&&c.push(this._exportTextureAsync(i._albedoTexture,e).then(function(_e){_e&&(o.baseColorTexture=_e)}));var $=i._metallicTexture;$&&c.push(this._exportTextureAsync($,e).then(function(_e){_e&&(o.metallicRoughnessTexture=_e)}))}return Promise.all(c).then(function(){return k})},a.prototype._getGLTFTextureSampler=function(i){var e=this._getGLTFTextureWrapModesSampler(i),o=i instanceof Texture?i.samplingMode:null;if(o!=null)switch(o){case Texture.LINEAR_LINEAR:{e.magFilter=9729,e.minFilter=9729;break}case Texture.LINEAR_NEAREST:{e.magFilter=9729,e.minFilter=9728;break}case Texture.NEAREST_LINEAR:{e.magFilter=9728,e.minFilter=9729;break}case Texture.NEAREST_LINEAR_MIPLINEAR:{e.magFilter=9728,e.minFilter=9987;break}case Texture.NEAREST_NEAREST:{e.magFilter=9728,e.minFilter=9728;break}case Texture.NEAREST_LINEAR_MIPNEAREST:{e.magFilter=9728,e.minFilter=9985;break}case Texture.LINEAR_NEAREST_MIPNEAREST:{e.magFilter=9729,e.minFilter=9984;break}case Texture.LINEAR_NEAREST_MIPLINEAR:{e.magFilter=9729,e.minFilter=9986;break}case Texture.NEAREST_NEAREST_MIPLINEAR:{e.magFilter=9728,e.minFilter=9986;break}case Texture.LINEAR_LINEAR_MIPLINEAR:{e.magFilter=9729,e.minFilter=9987;break}case Texture.LINEAR_LINEAR_MIPNEAREST:{e.magFilter=9729,e.minFilter=9985;break}case Texture.NEAREST_NEAREST_MIPNEAREST:{e.magFilter=9728,e.minFilter=9984;break}}return e},a.prototype._getGLTFTextureWrapMode=function(i){switch(i){case Texture.WRAP_ADDRESSMODE:return 10497;case Texture.CLAMP_ADDRESSMODE:return 33071;case Texture.MIRROR_ADDRESSMODE:return 33648;default:return Tools.Error("Unsupported Texture Wrap Mode "+i+"!"),10497}},a.prototype._getGLTFTextureWrapModesSampler=function(i){var e=this._getGLTFTextureWrapMode(i instanceof Texture?i.wrapU:Texture.WRAP_ADDRESSMODE),o=this._getGLTFTextureWrapMode(i instanceof Texture?i.wrapV:Texture.WRAP_ADDRESSMODE);return e===10497&&o===10497?{}:{wrapS:e,wrapT:o}},a.prototype._convertSpecGlossFactorsToMetallicRoughnessAsync=function(i,e,o,s){var c=this;return Promise.resolve().then(function(){var d=c._exporter._samplers,_=c._exporter._textures,b=i._albedoColor,k=i._reflectivityColor,j=i._microSurface,$={diffuseColor:b,specularColor:k,glossiness:j},_e=null,et=i._albedoTexture,tt=i._reflectivityTexture;if(et){var rt=c._getGLTFTextureSampler(et);rt.magFilter!=null&&rt.minFilter!=null&&rt.wrapS!=null&&rt.wrapT!=null&&(d.push(rt),_e=d.length-1)}var it=i._useMicroSurfaceFromReflectivityMapAlpha;return tt&&!it?Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported"):(et||tt)&&s?c._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(et,tt,$,e).then(function(nt){if(nt.baseColorTextureBase64){var ot=c._getTextureInfoFromBase64(nt.baseColorTextureBase64,"bjsBaseColorTexture_"+_.length+".png",e,et?et.coordinatesIndex:null,_e);ot&&(o.baseColorTexture=ot)}if(nt.metallicRoughnessTextureBase64){var at=c._getTextureInfoFromBase64(nt.metallicRoughnessTextureBase64,"bjsMetallicRoughnessTexture_"+_.length+".png",e,tt?tt.coordinatesIndex:null,_e);at&&(o.metallicRoughnessTexture=at)}return nt}):c._convertSpecularGlossinessToMetallicRoughness($)})},a.prototype._convertPBRMaterialAsync=function(i,e,o){var s=this,c={},d={name:i.name},_=i.isMetallicWorkflow();if(_){var b=i._albedoColor,k=i.alpha;return b&&(c.baseColorFactor=[b.r,b.g,b.b,k]),this._convertMetalRoughFactorsToMetallicRoughnessAsync(i,e,c,o).then(function(j){return s.setMetallicRoughnessPbrMaterial(j,i,d,c,e,o)})}else return this._convertSpecGlossFactorsToMetallicRoughnessAsync(i,e,c,o).then(function(j){return s.setMetallicRoughnessPbrMaterial(j,i,d,c,e,o)})},a.prototype.setMetallicRoughnessPbrMaterial=function(i,e,o,s,c,d){var _=this._exporter._materialMap,b=this._exporter._materials,k=[];if(i){if(a._SetAlphaMode(o,e),a.FuzzyEquals(i.baseColor,Color3.White(),a._Epsilon)&&e.alpha>=a._Epsilon||(s.baseColorFactor=[i.baseColor.r,i.baseColor.g,i.baseColor.b,e.alpha]),i.metallic!=null&&i.metallic!==1&&(s.metallicFactor=i.metallic),i.roughness!=null&&i.roughness!==1&&(s.roughnessFactor=i.roughness),e.backFaceCulling!=null&&!e.backFaceCulling&&(e._twoSidedLighting||Tools.Warn(e.name+": Back-face culling enabled and two-sided lighting disabled is not supported in glTF."),o.doubleSided=!0),d){var j=e._bumpTexture;if(j){var $=this._exportTextureAsync(j,c).then(function(rt){rt&&(o.normalTexture=rt,j.level!==1&&(o.normalTexture.scale=j.level))});k.push($)}var _e=e._ambientTexture;if(_e){var $=this._exportTextureAsync(_e,c).then(function(it){if(it){var nt={index:it.index,texCoord:it.texCoord};o.occlusionTexture=nt;var ot=e._ambientTextureStrength;ot&&(nt.strength=ot)}});k.push($)}var et=e._emissiveTexture;if(et){var $=this._exportTextureAsync(et,c).then(function(it){it&&(o.emissiveTexture=it)});k.push($)}}var tt=e._emissiveColor;a.FuzzyEquals(tt,Color3.Black(),a._Epsilon)||(o.emissiveFactor=tt.asArray()),o.pbrMetallicRoughness=s,b.push(o),_[e.uniqueId]=b.length-1}return this._finishMaterial(k,o,e,c)},a.prototype.getPixelsFromTexture=function(i){var e=(i.textureType===Constants.TEXTURETYPE_UNSIGNED_INT,i.readPixels());return e},a.prototype._exportTextureAsync=function(i,e){var o=this,s=this._exporter._extensionsPreExportTextureAsync("exporter",i,e);return s?s.then(function(c){return c?o._exportTextureInfoAsync(c,e):o._exportTextureInfoAsync(i,e)}):this._exportTextureInfoAsync(i,e)},a.prototype._exportTextureInfoAsync=function(i,e){var o=this;return Promise.resolve().then(function(){return __awaiter(o,void 0,void 0,function(){var s,c,d,_,b,k,j,$,_e,et=this;return __generator(this,function(tt){switch(tt.label){case 0:return s=i.uid,s in this._textureMap?[2,this._textureMap[s]]:[3,1];case 1:return[4,this.getPixelsFromTexture(i)];case 2:if(c=tt.sent(),!c)return[2,null];for(d=this._exporter._samplers,_=this._getGLTFTextureSampler(i),b=null,k=null,j=0;j<d.length;++j)if($=d[j],$.minFilter===_.minFilter&&$.magFilter===_.magFilter&&$.wrapS===_.wrapS&&$.wrapT===_.wrapT){k=j;break}if(k==null?(d.push(_),b=d.length-1):b=k,_e=i.getSize(),i.mimeType)switch(i.mimeType){case"image/jpeg":e="image/jpeg";break;case"image/png":e="image/png";break}return[2,this._createBase64FromCanvasAsync(c,_e.width,_e.height,e).then(function(rt){var it=et._getTextureInfoFromBase64(rt,i.name.replace(/\.\/|\/|\.\\|\\/g,"_"),e,i.coordinatesIndex,b);return it&&(et._textureMap[s]=it,et._exporter._extensionsPostExportTextures("linkTextureInfo",it,i)),it})]}})})})},a.prototype._getTextureInfoFromBase64=function(i,e,o,s,c){var d=this._exporter._textures,_=this._exporter._images,b=this._exporter._imageData,k=null,j={source:_.length,name:e};c!=null&&(j.sampler=c);for(var $=atob(i.split(",")[1]),_e=new ArrayBuffer($.length),et=new Uint8Array(_e),tt=0,rt=$.length;tt<rt;++tt)et[tt]=$.charCodeAt(tt);var it={data:et,mimeType:o},nt=o==="image/jpeg"?".jpeg":".png",ot=e+nt,at=ot;if(ot in b&&(ot=e+"_"+Tools.RandomId()+nt),b[ot]=it,o==="image/jpeg"||o==="image/png"){for(var st={name:e,uri:ot},ut=null,tt=0;tt<_.length;++tt)if(_[tt].uri===at){ut=tt;break}ut==null?(_.push(st),j.source=_.length-1):j.source=ut,d.push(j),k={index:d.length-1},s!=null&&(k.texCoord=s)}else Tools.Error("Unsupported texture mime type "+o);return k},a._DielectricSpecular=new Color3(.04,.04,.04),a._MaxSpecularPower=1024,a._Epsilon=1e-6,a}(),_Exporter=function(){function a(i,e){this._includeCoordinateSystemConversionNodes=!1,this._extensions={},this._glTF={asset:{generator:"BabylonJS",version:"2.0"}},this._babylonScene=i,this._bufferViews=[],this._accessors=[],this._meshes=[],this._scenes=[],this._nodes=[],this._images=[],this._materials=[],this._materialMap=[],this._textures=[],this._samplers=[],this._skins=[],this._animations=[],this._imageData={},this._orderedImageData=[],this._options=e||{},this._animationSampleRate=e&&e.animationSampleRate?e.animationSampleRate:1/60,this._includeCoordinateSystemConversionNodes=!!(e&&e.includeCoordinateSystemConversionNodes),this._glTFMaterialExporter=new _GLTFMaterialExporter(this),this._loadExtensions()}return a.prototype._applyExtension=function(i,e,o,s){var c=this;if(o>=e.length)return Promise.resolve(i);var d=s(e[o],i);return d?d.then(function(_){return c._applyExtension(_,e,o+1,s)}):this._applyExtension(i,e,o+1,s)},a.prototype._applyExtensions=function(i,e){for(var o=[],s=0,c=a._ExtensionNames;s<c.length;s++){var d=c[s];o.push(this._extensions[d])}return this._applyExtension(i,o,0,e)},a.prototype._extensionsPreExportTextureAsync=function(i,e,o){return this._applyExtensions(e,function(s,c){return s.preExportTextureAsync&&s.preExportTextureAsync(i,c,o)})},a.prototype._extensionsPostExportMeshPrimitiveAsync=function(i,e,o,s){return this._applyExtensions(e,function(c,d){return c.postExportMeshPrimitiveAsync&&c.postExportMeshPrimitiveAsync(i,d,o,s)})},a.prototype._extensionsPostExportNodeAsync=function(i,e,o,s){return this._applyExtensions(e,function(c,d){return c.postExportNodeAsync&&c.postExportNodeAsync(i,d,o,s)})},a.prototype._extensionsPostExportMaterialAsync=function(i,e,o){return this._applyExtensions(e,function(s,c){return s.postExportMaterialAsync&&s.postExportMaterialAsync(i,c,o)})},a.prototype._extensionsPostExportMaterialAdditionalTextures=function(i,e,o){for(var s=[],c=0,d=a._ExtensionNames;c<d.length;c++){var _=d[c],b=this._extensions[_];b.postExportMaterialAdditionalTextures&&s.push.apply(s,b.postExportMaterialAdditionalTextures(i,e,o))}return s},a.prototype._extensionsPostExportTextures=function(i,e,o){for(var s=0,c=a._ExtensionNames;s<c.length;s++){var d=c[s],_=this._extensions[d];_.postExportTexture&&_.postExportTexture(i,e,o)}},a.prototype._forEachExtensions=function(i){for(var e=0,o=a._ExtensionNames;e<o.length;e++){var s=o[e],c=this._extensions[s];c.enabled&&i(c)}},a.prototype._extensionsOnExporting=function(){var i=this;this._forEachExtensions(function(e){e.wasUsed&&(i._glTF.extensionsUsed==null&&(i._glTF.extensionsUsed=[]),i._glTF.extensionsUsed.indexOf(e.name)===-1&&i._glTF.extensionsUsed.push(e.name),e.required&&(i._glTF.extensionsRequired==null&&(i._glTF.extensionsRequired=[]),i._glTF.extensionsRequired.indexOf(e.name)===-1&&i._glTF.extensionsRequired.push(e.name)),i._glTF.extensions==null&&(i._glTF.extensions={}),e.onExporting&&e.onExporting())})},a.prototype._loadExtensions=function(){for(var i=0,e=a._ExtensionNames;i<e.length;i++){var o=e[i],s=a._ExtensionFactories[o](this);this._extensions[o]=s}},a.prototype.dispose=function(){for(var i in this._extensions){var e=this._extensions[i];e.dispose()}},a.RegisterExtension=function(i,e){a.UnregisterExtension(i)&&Tools.Warn("Extension with the name "+i+" already exists"),a._ExtensionFactories[i]=e,a._ExtensionNames.push(i)},a.UnregisterExtension=function(i){if(!a._ExtensionFactories[i])return!1;delete a._ExtensionFactories[i];var e=a._ExtensionNames.indexOf(i);return e!==-1&&a._ExtensionNames.splice(e,1),!0},a.prototype.reorderIndicesBasedOnPrimitiveMode=function(i,e,o,s,c){switch(e){case Material.TriangleFillMode:{s||(s=0);for(var d=i.indexStart,_=i.indexStart+i.indexCount;d<_;d=d+3){var b=s+d*4,k=c.getUInt32(b+4),j=c.getUInt32(b+8);c.setUInt32(j,b+4),c.setUInt32(k,b+8)}break}case Material.TriangleFanDrawMode:{for(var d=i.indexStart+i.indexCount-1,$=i.indexStart;d>=$;--d)c.setUInt32(o[d],s),s+=4;break}case Material.TriangleStripDrawMode:{i.indexCount>=3&&(c.setUInt32(o[i.indexStart+2],s+4),c.setUInt32(o[i.indexStart+1],s+8));break}}},a.prototype.reorderVertexAttributeDataBasedOnPrimitiveMode=function(i,e,o,s,c,d,_,b){if(b&&o===Material.ClockWiseSideOrientation)switch(e){case Material.TriangleFillMode:{this.reorderTriangleFillMode(i,e,o,s,c,d,_,b);break}case Material.TriangleStripDrawMode:{this.reorderTriangleStripDrawMode(i,e,o,s,c,d,_,b);break}case Material.TriangleFanDrawMode:{this.reorderTriangleFanMode(i,e,o,s,c,d,_,b);break}}},a.prototype.reorderTriangleFillMode=function(i,e,o,s,c,d,_,b){var k=this.getVertexBufferFromMesh(s,i.getMesh());if(k){var j=k.byteStride/VertexBuffer.GetTypeByteLength(k.type);if(i.verticesCount%3!==0)Tools.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");else{var $=[],_e=0;switch(s){case VertexBuffer.PositionKind:case VertexBuffer.NormalKind:{for(var et=i.verticesStart;et<i.verticesStart+i.verticesCount;et=et+3)_e=et*j,$.push(Vector3.FromArray(c,_e)),$.push(Vector3.FromArray(c,_e+2*j)),$.push(Vector3.FromArray(c,_e+j));break}case VertexBuffer.TangentKind:{for(var et=i.verticesStart;et<i.verticesStart+i.verticesCount;et=et+3)_e=et*j,$.push(Vector4.FromArray(c,_e)),$.push(Vector4.FromArray(c,_e+2*j)),$.push(Vector4.FromArray(c,_e+j));break}case VertexBuffer.ColorKind:{for(var tt=k.getSize(),et=i.verticesStart;et<i.verticesStart+i.verticesCount;et=et+tt)_e=et*j,tt===4?($.push(Vector4.FromArray(c,_e)),$.push(Vector4.FromArray(c,_e+2*j)),$.push(Vector4.FromArray(c,_e+j))):($.push(Vector3.FromArray(c,_e)),$.push(Vector3.FromArray(c,_e+2*j)),$.push(Vector3.FromArray(c,_e+j)));break}case VertexBuffer.UVKind:case VertexBuffer.UV2Kind:{for(var et=i.verticesStart;et<i.verticesStart+i.verticesCount;et=et+3)_e=et*j,$.push(Vector2.FromArray(c,_e)),$.push(Vector2.FromArray(c,_e+2*j)),$.push(Vector2.FromArray(c,_e+j));break}default:Tools.Error("Unsupported Vertex Buffer type: "+s)}this.writeVertexAttributeData($,d,s,c,_,b)}}else Tools.Warn("reorderTriangleFillMode: Vertex Buffer Kind "+s+" not present!")},a.prototype.reorderTriangleStripDrawMode=function(i,e,o,s,c,d,_,b){var k=this.getVertexBufferFromMesh(s,i.getMesh());if(k){var j=k.byteStride/VertexBuffer.GetTypeByteLength(k.type),$=[],_e=0;switch(s){case VertexBuffer.PositionKind:case VertexBuffer.NormalKind:{_e=i.verticesStart,$.push(Vector3.FromArray(c,_e+2*j)),$.push(Vector3.FromArray(c,_e+j));break}case VertexBuffer.TangentKind:{for(var et=i.verticesStart+i.verticesCount-1;et>=i.verticesStart;--et)_e=et*j,$.push(Vector4.FromArray(c,_e));break}case VertexBuffer.ColorKind:{for(var et=i.verticesStart+i.verticesCount-1;et>=i.verticesStart;--et)_e=et*j,k.getSize()===4?$.push(Vector4.FromArray(c,_e)):$.push(Vector3.FromArray(c,_e));break}case VertexBuffer.UVKind:case VertexBuffer.UV2Kind:{for(var et=i.verticesStart+i.verticesCount-1;et>=i.verticesStart;--et)_e=et*j,$.push(Vector2.FromArray(c,_e));break}default:Tools.Error("Unsupported Vertex Buffer type: "+s)}this.writeVertexAttributeData($,d+12,s,c,_,b)}else Tools.Warn("reorderTriangleStripDrawMode: Vertex buffer kind "+s+" not present!")},a.prototype.reorderTriangleFanMode=function(i,e,o,s,c,d,_,b){var k=this.getVertexBufferFromMesh(s,i.getMesh());if(k){var j=k.byteStride/VertexBuffer.GetTypeByteLength(k.type),$=[],_e=0;switch(s){case VertexBuffer.PositionKind:case VertexBuffer.NormalKind:{for(var et=i.verticesStart+i.verticesCount-1;et>=i.verticesStart;--et)_e=et*j,$.push(Vector3.FromArray(c,_e));break}case VertexBuffer.TangentKind:{for(var et=i.verticesStart+i.verticesCount-1;et>=i.verticesStart;--et)_e=et*j,$.push(Vector4.FromArray(c,_e));break}case VertexBuffer.ColorKind:{for(var et=i.verticesStart+i.verticesCount-1;et>=i.verticesStart;--et)_e=et*j,$.push(Vector4.FromArray(c,_e)),k.getSize()===4?$.push(Vector4.FromArray(c,_e)):$.push(Vector3.FromArray(c,_e));break}case VertexBuffer.UVKind:case VertexBuffer.UV2Kind:{for(var et=i.verticesStart+i.verticesCount-1;et>=i.verticesStart;--et)_e=et*j,$.push(Vector2.FromArray(c,_e));break}default:Tools.Error("Unsupported Vertex Buffer type: "+s)}this.writeVertexAttributeData($,d,s,c,_,b)}else Tools.Warn("reorderTriangleFanMode: Vertex buffer kind "+s+" not present!")},a.prototype.writeVertexAttributeData=function(i,e,o,s,c,d){for(var _=0,b=i;_<b.length;_++){var k=b[_];d&&o!==VertexBuffer.ColorKind&&!(k instanceof Vector2)&&(k instanceof Vector3?o===VertexBuffer.NormalKind?_GLTFUtilities._GetRightHandedNormalVector3FromRef(k):o===VertexBuffer.PositionKind?_GLTFUtilities._GetRightHandedPositionVector3FromRef(k):Tools.Error("Unsupported vertex attribute kind!"):_GLTFUtilities._GetRightHandedVector4FromRef(k)),o===VertexBuffer.NormalKind?k.normalize():o===VertexBuffer.TangentKind&&k instanceof Vector4&&_GLTFUtilities._NormalizeTangentFromRef(k);for(var j=0,$=k.asArray();j<$.length;j++){var _e=$[j];c.setFloat32(_e,e),e+=4}}},a.prototype.writeAttributeData=function(i,e,o,s,c,d,_){var b=[],k;switch(i){case VertexBuffer.PositionKind:{for(var j=0,$=o.length/s;j<$;++j){k=j*s;var _e=Vector3.FromArray(o,k);d&&_GLTFUtilities._GetRightHandedPositionVector3FromRef(_e),b.push(_e.asArray())}break}case VertexBuffer.NormalKind:{for(var j=0,et=o.length/s;j<et;++j){k=j*s;var _e=Vector3.FromArray(o,k);d&&_GLTFUtilities._GetRightHandedNormalVector3FromRef(_e),_e.normalize(),b.push(_e.asArray())}break}case VertexBuffer.TangentKind:{for(var j=0,tt=o.length/s;j<tt;++j){k=j*s;var _e=Vector4.FromArray(o,k);d&&_GLTFUtilities._GetRightHandedVector4FromRef(_e),_GLTFUtilities._NormalizeTangentFromRef(_e),b.push(_e.asArray())}break}case VertexBuffer.ColorKind:{for(var rt=_.material,it=rt?rt.getClassName()==="StandardMaterial":!0,_e=s===3?new Color3:new Color4,j=0,nt=o.length/s;j<nt;++j)k=j*s,s===3?(Color3.FromArrayToRef(o,k,_e),it&&_e.toLinearSpaceToRef(_e)):(Color4.FromArrayToRef(o,k,_e),it&&_e.toLinearSpaceToRef(_e)),b.push(_e.asArray());break}case VertexBuffer.UVKind:case VertexBuffer.UV2Kind:{for(var j=0,ot=o.length/s;j<ot;++j)k=j*s,b.push(d?[o[k],o[k+1]]:[o[k],o[k+1]]);break}case VertexBuffer.MatricesIndicesKind:case VertexBuffer.MatricesIndicesExtraKind:{for(var j=0,at=o.length/s;j<at;++j){k=j*s;var _e=Vector4.FromArray(o,k);b.push(_e.asArray())}break}case VertexBuffer.MatricesWeightsKind:case VertexBuffer.MatricesWeightsExtraKind:{for(var j=0,st=o.length/s;j<st;++j){k=j*s;var _e=Vector4.FromArray(o,k);b.push(_e.asArray())}break}default:Tools.Warn("Unsupported Vertex Buffer Type: "+i),b=[]}var ut;switch(e){case 5121:{ut=c.setUInt8.bind(c);break}case 5123:{ut=c.setUInt16.bind(c);break}case 5125:ut=c.setUInt32.bind(c);case 5126:{ut=c.setFloat32.bind(c);break}default:{Tools.Warn("Unsupported Attribute Component kind: "+e);return}}for(var ft=0,lt=b;ft<lt.length;ft++)for(var ht=lt[ft],pt=0,mt=ht;pt<mt.length;pt++){var dt=mt[pt];ut(dt)}},a.prototype.writeMorphTargetAttributeData=function(i,e,o,s,c,d,_,b,k,j){var $=[],_e,et=new Vector3,tt=new Vector4(0,0,0,0);switch(i){case VertexBuffer.PositionKind:{for(var rt=o.verticesStart;rt<o.verticesCount;++rt){_e=o.indexStart+rt*_;var it=Vector3.FromArray(c,_e),nt=Vector3.FromArray(d,_e);et=nt.subtractToRef(it,et),k&&_GLTFUtilities._GetRightHandedPositionVector3FromRef(et),j&&(j.min.copyFromFloats(Math.min(et.x,j.min.x),Math.min(et.y,j.min.y),Math.min(et.z,j.min.z)),j.max.copyFromFloats(Math.max(et.x,j.max.x),Math.max(et.y,j.max.y),Math.max(et.z,j.max.z))),$.push(et.asArray())}break}case VertexBuffer.NormalKind:{for(var rt=o.verticesStart;rt<o.verticesCount;++rt){_e=o.indexStart+rt*_;var it=Vector3.FromArray(c,_e);it.normalize();var nt=Vector3.FromArray(d,_e);nt.normalize(),et=nt.subtractToRef(it,et),k&&_GLTFUtilities._GetRightHandedNormalVector3FromRef(et),$.push(et.asArray())}break}case VertexBuffer.TangentKind:{for(var rt=o.verticesStart;rt<o.verticesCount;++rt){_e=o.indexStart+rt*(_+1);var it=Vector4.FromArray(c,_e);_GLTFUtilities._NormalizeTangentFromRef(it);var nt=Vector4.FromArray(d,_e);_GLTFUtilities._NormalizeTangentFromRef(nt),tt=nt.subtractToRef(it,tt),k&&_GLTFUtilities._GetRightHandedVector4FromRef(tt),$.push([tt.x,tt.y,tt.z])}break}default:Tools.Warn("Unsupported Vertex Buffer Type: "+i),$=[]}var ot;switch(e){case 5121:{ot=b.setUInt8.bind(b);break}case 5123:{ot=b.setUInt16.bind(b);break}case 5125:ot=b.setUInt32.bind(b);case 5126:{ot=b.setFloat32.bind(b);break}default:{Tools.Warn("Unsupported Attribute Component kind: "+e);return}}for(var at=0,st=$;at<st.length;at++)for(var ut=st[at],ft=0,lt=ut;ft<lt.length;ft++){var ht=lt[ft];ot(ht)}},a.prototype.generateJSON=function(i,e,o){var s=this,c={byteLength:this._totalByteLength},d,_,b,k=this._totalByteLength;c.byteLength&&(this._glTF.buffers=[c]),this._nodes&&this._nodes.length&&(this._glTF.nodes=this._nodes),this._meshes&&this._meshes.length&&(this._glTF.meshes=this._meshes),this._scenes&&this._scenes.length&&(this._glTF.scenes=this._scenes,this._glTF.scene=0),this._bufferViews&&this._bufferViews.length&&(this._glTF.bufferViews=this._bufferViews),this._accessors&&this._accessors.length&&(this._glTF.accessors=this._accessors),this._animations&&this._animations.length&&(this._glTF.animations=this._animations),this._materials&&this._materials.length&&(this._glTF.materials=this._materials),this._textures&&this._textures.length&&(this._glTF.textures=this._textures),this._samplers&&this._samplers.length&&(this._glTF.samplers=this._samplers),this._skins&&this._skins.length&&(this._glTF.skins=this._skins),this._images&&this._images.length&&(i?(this._glTF.images=[],this._images.forEach(function($){$.uri&&(_=s._imageData[$.uri],s._orderedImageData.push(_),d=$.uri.split(".")[0]+" image",b=_GLTFUtilities._CreateBufferView(0,k,_.data.length,void 0,d),k+=_.data.buffer.byteLength,s._bufferViews.push(b),$.bufferView=s._bufferViews.length-1,$.name=d,$.mimeType=_.mimeType,$.uri=void 0,s._glTF.images||(s._glTF.images=[]),s._glTF.images.push($))}),c.byteLength=k):this._glTF.images=this._images),i||(c.uri=e+".bin");var j=o?JSON.stringify(this._glTF,null,2):JSON.stringify(this._glTF);return j},a.prototype._generateGLTFAsync=function(i,e){var o=this;return e===void 0&&(e=!0),this._generateBinaryAsync().then(function(s){o._extensionsOnExporting();var c=o.generateJSON(!1,i,!0),d=new Blob([s],{type:"application/octet-stream"}),_=i+".gltf",b=i+".bin",k=new GLTFData;if(k.glTFFiles[_]=c,k.glTFFiles[b]=d,o._imageData)for(var j in o._imageData)k.glTFFiles[j]=new Blob([o._imageData[j].data],{type:o._imageData[j].mimeType});return e&&o.dispose(),k})},a.prototype._generateBinaryAsync=function(){var i=this,e=new _BinaryWriter(4);return this.createSceneAsync(this._babylonScene,e).then(function(){return i._localEngine&&i._localEngine.dispose(),e.getArrayBuffer()})},a.prototype._getPadding=function(i){var e=i%4,o=e===0?e:4-e;return o},a.prototype._generateGLBAsync=function(i,e){var o=this;return e===void 0&&(e=!0),this._generateBinaryAsync().then(function(s){o._extensionsOnExporting();var c=o.generateJSON(!0),d=i+".glb",_=12,b=8,k=c.length,j,$=0;if(typeof TextEncoder!="undefined"){var _e=new TextEncoder;j=_e.encode(c),k=j.length}for(var et=0;et<o._orderedImageData.length;++et)$+=o._orderedImageData[et].data.byteLength;var tt=o._getPadding(k),rt=o._getPadding(s.byteLength),it=o._getPadding($),nt=_+2*b+k+tt+s.byteLength+rt+$+it,ot=new ArrayBuffer(_),at=new DataView(ot);at.setUint32(0,1179937895,!0),at.setUint32(4,2,!0),at.setUint32(8,nt,!0);var st=new ArrayBuffer(b+k+tt),ut=new DataView(st);ut.setUint32(0,k+tt,!0),ut.setUint32(4,1313821514,!0);var ft=new Uint8Array(st,b);if(j)ft.set(j);else for(var lt="_".charCodeAt(0),et=0;et<k;++et){var ht=c.charCodeAt(et);ht!=c.codePointAt(et)?ft[et]=lt:ft[et]=ht}for(var pt=new Uint8Array(st,b+k),et=0;et<tt;++et)pt[et]=32;var mt=new ArrayBuffer(b),dt=new DataView(mt);dt.setUint32(0,s.byteLength+$+it,!0),dt.setUint32(4,5130562,!0);for(var gt=new ArrayBuffer(rt),_t=new Uint8Array(gt),et=0;et<rt;++et)_t[et]=0;for(var yt=new ArrayBuffer(it),Tt=new Uint8Array(yt),et=0;et<it;++et)Tt[et]=0;for(var St=[ot,st,mt,s],et=0;et<o._orderedImageData.length;++et)St.push(o._orderedImageData[et].data.buffer);St.push(gt),St.push(yt);var At=new Blob(St,{type:"application/octet-stream"}),vt=new GLTFData;return vt.glTFFiles[d]=At,o._localEngine!=null&&o._localEngine.dispose(),e&&o.dispose(),vt})},a.prototype.setNodeTransformation=function(i,e,o){e.getPivotPoint().equalsToFloats(0,0,0)||Tools.Warn("Pivot points are not supported in the glTF serializer"),e.position.equalsToFloats(0,0,0)||(i.translation=o?_GLTFUtilities._GetRightHandedPositionVector3(e.position).asArray():e.position.asArray()),e.scaling.equalsToFloats(1,1,1)||(i.scale=e.scaling.asArray());var s=Quaternion.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z);e.rotationQuaternion&&s.multiplyInPlace(e.rotationQuaternion),s.x===0&&s.y===0&&s.z===0&&s.w===1||(o&&_GLTFUtilities._GetRightHandedQuaternionFromRef(s),i.rotation=s.normalize().asArray())},a.prototype.getVertexBufferFromMesh=function(i,e){if(e.isVerticesDataPresent(i)){var o=e.getVertexBuffer(i);if(o)return o}return null},a.prototype.createBufferViewKind=function(i,e,o,s,c,d){var _=o instanceof Mesh?o:o instanceof InstancedMesh?o.sourceMesh:null;if(_){var b=_.getVertexBuffer(i),k=_.getVerticesData(i);if(b&&k){var j=VertexBuffer.GetTypeByteLength(e),$=k.length*j,_e=_GLTFUtilities._CreateBufferView(0,s.getByteOffset(),$,c,i+" - "+_.name);this._bufferViews.push(_e),this.writeAttributeData(i,e,k,c/j,s,d,o)}}},a.prototype.setMorphTargetAttributes=function(i,e,o,s,c){if(o){e.targets||(e.targets=[]);var d={};if(o.hasNormals){var _=i.getMesh().getVerticesData(VertexBuffer.NormalKind),b=o.getNormals(),k=i.verticesCount,j=12,$=k*j,_e=_GLTFUtilities._CreateBufferView(0,s.getByteOffset(),$,j,o.name+"_NORMAL");this._bufferViews.push(_e);var et=this._bufferViews.length-1,tt=_GLTFUtilities._CreateAccessor(et,o.name+" - NORMAL","VEC3",5126,k,0,null,null);this._accessors.push(tt),d.NORMAL=this._accessors.length-1,this.writeMorphTargetAttributeData(VertexBuffer.NormalKind,5126,i,o,_,b,j/4,s,c)}if(o.hasPositions){var rt=i.getMesh().getVerticesData(VertexBuffer.PositionKind),it=o.getPositions(),k=i.verticesCount,j=12,$=k*j,_e=_GLTFUtilities._CreateBufferView(0,s.getByteOffset(),$,j,o.name+"_POSITION");this._bufferViews.push(_e);var et=this._bufferViews.length-1,nt={min:new Vector3(1/0,1/0,1/0),max:new Vector3(-1/0,-1/0,-1/0)},tt=_GLTFUtilities._CreateAccessor(et,o.name+" - POSITION","VEC3",5126,k,0,null,null);this._accessors.push(tt),d.POSITION=this._accessors.length-1,this.writeMorphTargetAttributeData(VertexBuffer.PositionKind,5126,i,o,rt,it,j/4,s,c,nt),tt.min=nt.min.asArray(),tt.max=nt.max.asArray()}if(o.hasTangents){var ot=i.getMesh().getVerticesData(VertexBuffer.TangentKind),at=o.getTangents(),k=i.verticesCount,j=12,$=k*j,_e=_GLTFUtilities._CreateBufferView(0,s.getByteOffset(),$,j,o.name+"_NORMAL");this._bufferViews.push(_e);var et=this._bufferViews.length-1,tt=_GLTFUtilities._CreateAccessor(et,o.name+" - TANGENT","VEC3",5126,k,0,null,null);this._accessors.push(tt),d.TANGENT=this._accessors.length-1,this.writeMorphTargetAttributeData(VertexBuffer.TangentKind,5126,i,o,ot,at,j/4,s,c)}e.targets.push(d)}},a.prototype.getMeshPrimitiveMode=function(i){return i instanceof LinesMesh?Material.LineListDrawMode:i.material?i.material.fillMode:Material.TriangleFillMode},a.prototype.setPrimitiveMode=function(i,e){switch(e){case Material.TriangleFillMode:break;case Material.TriangleStripDrawMode:{i.mode=5;break}case Material.TriangleFanDrawMode:{i.mode=6;break}case Material.PointListDrawMode:i.mode=0;case Material.PointFillMode:{i.mode=0;break}case Material.LineLoopDrawMode:{i.mode=2;break}case Material.LineListDrawMode:{i.mode=1;break}case Material.LineStripDrawMode:{i.mode=3;break}}},a.prototype.setAttributeKind=function(i,e){switch(e){case VertexBuffer.PositionKind:{i.attributes.POSITION=this._accessors.length-1;break}case VertexBuffer.NormalKind:{i.attributes.NORMAL=this._accessors.length-1;break}case VertexBuffer.ColorKind:{i.attributes.COLOR_0=this._accessors.length-1;break}case VertexBuffer.TangentKind:{i.attributes.TANGENT=this._accessors.length-1;break}case VertexBuffer.UVKind:{i.attributes.TEXCOORD_0=this._accessors.length-1;break}case VertexBuffer.UV2Kind:{i.attributes.TEXCOORD_1=this._accessors.length-1;break}case VertexBuffer.MatricesIndicesKind:{i.attributes.JOINTS_0=this._accessors.length-1;break}case VertexBuffer.MatricesIndicesExtraKind:{i.attributes.JOINTS_1=this._accessors.length-1;break}case VertexBuffer.MatricesWeightsKind:{i.attributes.WEIGHTS_0=this._accessors.length-1;break}case VertexBuffer.MatricesWeightsExtraKind:{i.attributes.WEIGHTS_1=this._accessors.length-1;break}default:Tools.Warn("Unsupported Vertex Buffer Type: "+e)}},a.prototype.setPrimitiveAttributesAsync=function(i,e,o,s){var c,d=[],_=null,b,k;e instanceof Mesh?_=e:e instanceof InstancedMesh&&(_=e.sourceMesh);var j=[{kind:VertexBuffer.PositionKind,accessorType:"VEC3",accessorComponentType:5126,byteStride:12},{kind:VertexBuffer.NormalKind,accessorType:"VEC3",accessorComponentType:5126,byteStride:12},{kind:VertexBuffer.ColorKind,accessorType:"VEC4",accessorComponentType:5126,byteStride:16},{kind:VertexBuffer.TangentKind,accessorType:"VEC4",accessorComponentType:5126,byteStride:16},{kind:VertexBuffer.UVKind,accessorType:"VEC2",accessorComponentType:5126,byteStride:8},{kind:VertexBuffer.UV2Kind,accessorType:"VEC2",accessorComponentType:5126,byteStride:8},{kind:VertexBuffer.MatricesIndicesKind,accessorType:"VEC4",accessorComponentType:5123,byteStride:8},{kind:VertexBuffer.MatricesIndicesExtraKind,accessorType:"VEC4",accessorComponentType:5123,byteStride:8},{kind:VertexBuffer.MatricesWeightsKind,accessorType:"VEC4",accessorComponentType:5126,byteStride:16},{kind:VertexBuffer.MatricesWeightsExtraKind,accessorType:"VEC4",accessorComponentType:5126,byteStride:16}];if(_){for(var $=null,_e=this.getMeshPrimitiveMode(_),et={},tt=_.morphTargetManager,rt=0,it=j;rt<it.length;rt++){var nt=it[rt],ot=nt.kind,at=nt.accessorComponentType;if(_.isVerticesDataPresent(ot)){var st=this.getVertexBufferFromMesh(ot,_);nt.byteStride=st?st.getSize()*VertexBuffer.GetTypeByteLength(nt.accessorComponentType):VertexBuffer.DeduceStride(ot)*4,nt.byteStride===12&&(nt.accessorType="VEC3"),this.createBufferViewKind(ot,at,e,o,nt.byteStride,s),nt.bufferViewIndex=this._bufferViews.length-1,et[ot]=nt.bufferViewIndex}}if(_.getTotalIndices()){var ut=_.getIndices();if(ut){var ft=ut.length*4;b=_GLTFUtilities._CreateBufferView(0,o.getByteOffset(),ft,void 0,"Indices - "+_.name),this._bufferViews.push(b),$=this._bufferViews.length-1;for(var lt=0,ht=ut.length;lt<ht;++lt)o.setUInt32(ut[lt])}}if(_.subMeshes)for(var pt=0,mt=_.subMeshes;pt<mt.length;pt++){var dt=mt[pt],gt=dt.getMaterial()||_.getScene().defaultMaterial,_t=null;if(gt)if(_ instanceof LinesMesh){var yt={name:_.name+" material"};(!_.color.equals(Color3.White())||_.alpha<1)&&(yt.pbrMetallicRoughness={baseColorFactor:_.color.asArray().concat([_.alpha])}),this._materials.push(yt),_t=this._materials.length-1}else if(gt.getClassName()==="MultiMaterial"){var Tt=gt.subMaterials[dt.materialIndex];Tt&&(gt=Tt,_t=this._materialMap[gt.uniqueId])}else _t=this._materialMap[gt.uniqueId];var St=_t!=null?this._materials[_t]:null,At={attributes:{}};this.setPrimitiveMode(At,_e);for(var vt=0,Et=j;vt<Et.length;vt++){var nt=Et[vt],ot=nt.kind;if(!((ot===VertexBuffer.UVKind||ot===VertexBuffer.UV2Kind)&&!this._options.exportUnusedUVs&&St&&!this._glTFMaterialExporter._hasTexturesPresent(St))){var xt=_.getVerticesData(ot);if(xt){var st=this.getVertexBufferFromMesh(ot,_);if(st){var bt=st.getSize(),Mt=nt.bufferViewIndex;if(Mt!=null){k={min:null,max:null},ot==VertexBuffer.PositionKind&&(k=_GLTFUtilities._CalculateMinMaxPositions(xt,0,xt.length/bt,s));var Rt=_GLTFUtilities._CreateAccessor(Mt,ot+" - "+e.name,nt.accessorType,nt.accessorComponentType,xt.length/bt,0,k.min,k.max);this._accessors.push(Rt),this.setAttributeKind(At,ot)}}}}}if($){var Rt=_GLTFUtilities._CreateAccessor($,"indices - "+e.name,"SCALAR",5125,dt.indexCount,dt.indexStart*4,null,null);this._accessors.push(Rt),At.indices=this._accessors.length-1}if(_t!=null&&Object.keys(At.attributes).length>0){var Pt=_.overrideMaterialSideOrientation!==null?_.overrideMaterialSideOrientation:gt.sideOrientation;if(Pt==Material.ClockWiseSideOrientation&&this._babylonScene.useRightHandedSystem||Pt==Material.ClockWiseSideOrientation&&s&&_.overrideMaterialSideOrientation!==((c=_.material)===null||c===void 0?void 0:c.sideOrientation)){var It=$!=null?this._bufferViews[$].byteOffset:null;It==null&&(It=0);var Dt=null;if($!=null&&(Dt=_.getIndices()),Dt)this.reorderIndicesBasedOnPrimitiveMode(dt,_e,Dt,It,o);else for(var Ct=0,Ot=j;Ct<Ot.length;Ct++){var nt=Ot[Ct],xt=_.getVerticesData(nt.kind);if(xt){var Ft=this._bufferViews[et[nt.kind]].byteOffset;Ft||(Ft=0),this.reorderVertexAttributeDataBasedOnPrimitiveMode(dt,_e,Pt,nt.kind,xt,Ft,o,s)}}}At.material=_t}if(tt)for(var wt=void 0,Bt=0;Bt<tt.numTargets;++Bt)wt=tt.getTarget(Bt),this.setMorphTargetAttributes(dt,At,wt,o,s);i.primitives.push(At),this._extensionsPostExportMeshPrimitiveAsync("postExport",At,dt,o),d.push()}}return Promise.all(d).then(function(){})},a.prototype.isBabylonCoordinateSystemConvertingNode=function(i){if(i instanceof TransformNode){if(i.name!=="__root__")return!1;for(var e=i.getWorldMatrix(),o=Matrix.Compose(this._convertToRightHandedSystem?new Vector3(-1,1,1):Vector3.One(),Quaternion.Identity(),Vector3.Zero()),s=e.multiply(o),c=Matrix.IdentityReadOnly,d=0;d<16;d++)if(Math.abs(s.m[d]-c.m[d])>Epsilon)return!1;return!(i instanceof Mesh&&i.geometry!==null||i instanceof InstancedMesh&&i.sourceMesh.geometry!==null||this._includeCoordinateSystemConversionNodes)}return!1},a.prototype.createSceneAsync=function(i,e){var o=this,s={nodes:[]},c,d,_,b=__spreadArray(__spreadArray(__spreadArray([],i.transformNodes,!0),i.meshes,!0),i.lights,!0),k=[];return this._convertToRightHandedSystem=!i.useRightHandedSystem,this._convertToRightHandedSystemMap={},i.rootNodes.forEach(function(j){o._convertToRightHandedSystemMap[j.uniqueId]=o._convertToRightHandedSystem,j.getDescendants(!1).forEach(function($){o._convertToRightHandedSystemMap[$.uniqueId]=o._convertToRightHandedSystem})}),i.rootNodes.forEach(function(j){if(o.isBabylonCoordinateSystemConvertingNode(j)){k.push(j);var $=b.indexOf(j);$!==-1&&b.splice($,1),j.getDescendants(!1).forEach(function(_e){o._convertToRightHandedSystemMap[_e.uniqueId]=!1})}}),this._glTFMaterialExporter._convertMaterialsToGLTFAsync(i.materials,"image/png",!0).then(function(){return o.createNodeMapAndAnimationsAsync(i,b,e).then(function(j){return o.createSkinsAsync(i,j,e).then(function($){if(o._nodeMap=j,o._totalByteLength=e.getByteOffset(),o._totalByteLength==null)throw new Error("undefined byte length!");for(var _e=0,et=b;_e<et.length;_e++){var tt=et[_e];if(c=o._nodeMap[tt.uniqueId],c!==void 0){if(d=o._nodes[c],tt.metadata&&(o._options.metadataSelector?d.extras=o._options.metadataSelector(tt.metadata):tt.metadata.gltf&&(d.extras=tt.metadata.gltf.extras)),!tt.parent||k.indexOf(tt.parent)!==-1)if(o._options.shouldExportNode&&!o._options.shouldExportNode(tt))Tools.Log("Omitting "+tt.name+" from scene.");else{var rt=o._convertToRightHandedSystemMap[tt.uniqueId];rt&&(d.translation&&(d.translation[2]*=-1,d.translation[0]*=-1),d.rotation=d.rotation?Quaternion.FromArray([0,1,0,0]).multiply(Quaternion.FromArray(d.rotation)).asArray():Quaternion.FromArray([0,1,0,0]).asArray()),s.nodes.push(c)}if(tt instanceof Mesh){var it=tt;it.skeleton&&(d.skin=$[it.skeleton.uniqueId])}if(_=tt.getDescendants(!0),!d.children&&_&&_.length){for(var nt=[],ot=0,at=_;ot<at.length;ot++){var st=at[ot];o._nodeMap[st.uniqueId]!=null&&nt.push(o._nodeMap[st.uniqueId])}nt.length&&(d.children=nt)}}}s.nodes.length&&o._scenes.push(s)})})})},a.prototype.createNodeMapAndAnimationsAsync=function(i,e,o){for(var s=this,c=Promise.resolve(),d={},_,b={name:"runtime animations",channels:[],samplers:[]},k=[],j=function(rt){!$._options.shouldExportNode||$._options.shouldExportNode(rt)?c=c.then(function(){var it=s._convertToRightHandedSystemMap[rt.uniqueId];return s.createNodeAsync(rt,o,it,d).then(function(nt){var ot=s._extensionsPostExportNodeAsync("createNodeAsync",nt,rt,d);return ot==null?(Tools.Warn("Not exporting node "+rt.name),Promise.resolve()):ot.then(function(at){!at||(s._nodes.push(at),_=s._nodes.length-1,d[rt.uniqueId]=_,i.animationGroups.length||(_GLTFAnimation._CreateMorphTargetAnimationFromMorphTargetAnimations(rt,b,k,d,s._nodes,o,s._bufferViews,s._accessors,it,s._animationSampleRate),rt.animations.length&&_GLTFAnimation._CreateNodeAnimationFromNodeAnimations(rt,b,k,d,s._nodes,o,s._bufferViews,s._accessors,it,s._animationSampleRate)))})})}):""+rt.name},$=this,_e=0,et=e;_e<et.length;_e++){var tt=et[_e];j(tt)}return c.then(function(){return b.channels.length&&b.samplers.length&&s._animations.push(b),k.forEach(function(rt){rt.channels.length&&rt.samplers.length&&s._animations.push(rt)}),i.animationGroups.length&&_GLTFAnimation._CreateNodeAndMorphAnimationFromAnimationGroups(i,s._animations,d,s._nodes,o,s._bufferViews,s._accessors,s._convertToRightHandedSystemMap,s._animationSampleRate),d})},a.prototype.createNodeAsync=function(i,e,o,s){var c=this;return Promise.resolve().then(function(){var d={},_={primitives:[]};if(i.name&&(d.name=i.name),i instanceof TransformNode){if(c.setNodeTransformation(d,i,o),i instanceof Mesh){var b=i.morphTargetManager;if(b&&b.numTargets>0){_.weights=[];for(var k=0;k<b.numTargets;++k)_.weights.push(b.getTarget(k).influence)}}return c.setPrimitiveAttributesAsync(_,i,e,o).then(function(){return _.primitives.length&&(c._meshes.push(_),d.mesh=c._meshes.length-1),d})}else return d})},a.prototype.createSkinsAsync=function(i,e,o){for(var s,c=Promise.resolve(),d={},_=0,b=i.skeletons;_<b.length;_++){for(var k=b[_],j={joints:[]},$=[],_e={},et=-1,tt=0;tt<k.bones.length;++tt){var rt=k.bones[tt],it=(s=rt.getIndex())!==null&&s!==void 0?s:tt;it!==-1&&(_e[it]=rt,it>et&&(et=it))}for(var it=0;it<=et;++it){var rt=_e[it];$.push(rt.getInvertedAbsoluteTransform());var nt=rt.getTransformNode();nt?j.joints.push(e[nt.uniqueId]):Tools.Warn("Exporting a bone without a linked transform node is currently unsupported")}var ot=64,at=$.length*ot,st=o.getByteOffset(),ut=_GLTFUtilities._CreateBufferView(0,st,at,void 0,"InverseBindMatrices - "+k.name);this._bufferViews.push(ut);var ft=this._bufferViews.length-1,lt=_GLTFUtilities._CreateAccessor(ft,"InverseBindMatrices - "+k.name,"MAT4",5126,$.length,null,null,null),ht=this._accessors.push(lt)-1;j.inverseBindMatrices=ht,this._skins.push(j),d[k.uniqueId]=this._skins.length-1,$.forEach(function(pt){pt.m.forEach(function(mt){o.setFloat32(mt)})})}return c.then(function(){return d})},a._ExtensionNames=new Array,a._ExtensionFactories={},a}(),_BinaryWriter=function(){function a(i){this._arrayBuffer=new ArrayBuffer(i),this._dataView=new DataView(this._arrayBuffer),this._byteOffset=0}return a.prototype.resizeBuffer=function(i){for(var e=new ArrayBuffer(i),o=new Uint8Array(this._arrayBuffer),s=new Uint8Array(e),c=0,d=s.byteLength;c<d;++c)s[c]=o[c];return this._arrayBuffer=e,this._dataView=new DataView(this._arrayBuffer),e},a.prototype.getArrayBuffer=function(){return this.resizeBuffer(this.getByteOffset())},a.prototype.getByteOffset=function(){if(this._byteOffset==null)throw new Error("Byte offset is undefined!");return this._byteOffset},a.prototype.setUInt8=function(i,e){e!=null?e<this._byteOffset?this._dataView.setUint8(e,i):Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._byteOffset+1>this._arrayBuffer.byteLength&&this.resizeBuffer(this._arrayBuffer.byteLength*2),this._dataView.setUint8(this._byteOffset,i),this._byteOffset+=1)},a.prototype.setUInt16=function(i,e){e!=null?e<this._byteOffset?this._dataView.setUint16(e,i,!0):Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._byteOffset+2>this._arrayBuffer.byteLength&&this.resizeBuffer(this._arrayBuffer.byteLength*2),this._dataView.setUint16(this._byteOffset,i,!0),this._byteOffset+=2)},a.prototype.getUInt32=function(i){if(i<this._byteOffset)return this._dataView.getUint32(i,!0);throw Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"),new Error("BinaryWriter: byteoffset is greater than the current binary buffer length!")},a.prototype.getVector3Float32FromRef=function(i,e){e+8>this._byteOffset?Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(i.x=this._dataView.getFloat32(e,!0),i.y=this._dataView.getFloat32(e+4,!0),i.z=this._dataView.getFloat32(e+8,!0))},a.prototype.setVector3Float32FromRef=function(i,e){e+8>this._byteOffset?Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(e,i.x,!0),this._dataView.setFloat32(e+4,i.y,!0),this._dataView.setFloat32(e+8,i.z,!0))},a.prototype.getVector4Float32FromRef=function(i,e){e+12>this._byteOffset?Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(i.x=this._dataView.getFloat32(e,!0),i.y=this._dataView.getFloat32(e+4,!0),i.z=this._dataView.getFloat32(e+8,!0),i.w=this._dataView.getFloat32(e+12,!0))},a.prototype.setVector4Float32FromRef=function(i,e){e+12>this._byteOffset?Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(e,i.x,!0),this._dataView.setFloat32(e+4,i.y,!0),this._dataView.setFloat32(e+8,i.z,!0),this._dataView.setFloat32(e+12,i.w,!0))},a.prototype.setFloat32=function(i,e){isNaN(i)&&Tools.Error("Invalid data being written!"),e!=null&&(e<this._byteOffset?this._dataView.setFloat32(e,i,!0):Tools.Error("BinaryWriter: byteoffset is greater than the current binary length!")),this._byteOffset+4>this._arrayBuffer.byteLength&&this.resizeBuffer(this._arrayBuffer.byteLength*2),this._dataView.setFloat32(this._byteOffset,i,!0),this._byteOffset+=4},a.prototype.setUInt32=function(i,e){e!=null?e<this._byteOffset?this._dataView.setUint32(e,i,!0):Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._byteOffset+4>this._arrayBuffer.byteLength&&this.resizeBuffer(this._arrayBuffer.byteLength*2),this._dataView.setUint32(this._byteOffset,i,!0),this._byteOffset+=4)},a}(),name="textureTransformPixelShader",shader=`precision highp float;
  10866. varying vec2 vUV;
  10867. uniform sampler2D textureSampler;
  10868. uniform mat4 textureTransformMat;
  10869. void main(void) {
  10870. vec2 uvTransformed=(textureTransformMat*vec4(vUV.xy,1,1)).xy;
  10871. gl_FragColor=texture2D(textureSampler,uvTransformed);
  10872. }`;ShaderStore.ShadersStore[name]=shader;var NAME$4="KHR_texture_transform",KHR_texture_transform=function(){function a(i){this._recordedTextures=[],this.name=NAME$4,this.enabled=!0,this.required=!1,this._wasUsed=!1}return a.prototype.dispose=function(){for(var i=0,e=this._recordedTextures;i<e.length;i++){var o=e[i];o.dispose()}},Object.defineProperty(a.prototype,"wasUsed",{get:function(){return this._wasUsed},enumerable:!1,configurable:!0}),a.prototype.postExportTexture=function(i,e,o){var s=o&&(o.uAng===0&&o.wAng===0&&o.vAng===0||o.uRotationCenter===0&&o.vRotationCenter===0);if(s){var c={},d=!1;if((o.uOffset!==0||o.vOffset!==0)&&(c.offset=[o.uOffset,o.vOffset],d=!0),(o.uScale!==1||o.vScale!==1)&&(c.scale=[o.uScale,o.vScale],d=!0),o.wAng!==0&&(c.rotation=o.wAng,d=!0),o.coordinatesIndex!==0&&(c.texCoord=o.coordinatesIndex,d=!0),!d)return;this._wasUsed=!0,e.extensions||(e.extensions={}),e.extensions[NAME$4]=c}},a.prototype.preExportTextureAsync=function(i,e,o){var s=this;return new Promise(function(c,d){var _=e.getScene();if(!_){d(i+': "scene" is not defined for Babylon texture '+e.name+"!");return}var b=!1;if((e.uAng!==0||e.wAng!==0||e.vAng!==0)&&(e.uRotationCenter!==0||e.vRotationCenter!==0)&&(b=!0),!b){c(e);return}return s._textureTransformTextureAsync(e,_).then(function(k){c(k)}).catch(function(k){d(k)})})},a.prototype._textureTransformTextureAsync=function(i,e){var o=this;return new Promise(function(s){var c=new ProceduralTexture(""+i.name,i.getSize(),"textureTransform",e);c||(Tools.Log("Cannot create procedural texture for "+i.name+"!"),s(i)),c.reservedDataStore={hidden:!0,source:i},o._recordedTextures.push(c),c.coordinatesIndex=i.coordinatesIndex,c.setTexture("textureSampler",i),c.setMatrix("textureTransformMat",i.getTextureMatrix()),c.isReady()?(c.render(),s(c)):c.getEffect().executeWhenCompiled(function(){c.render(),s(c)})})},a}();_Exporter.RegisterExtension(NAME$4,function(a){return new KHR_texture_transform(a)});var NAME$3="KHR_lights_punctual",KHR_lights_punctual=function(){function a(i){this.name=NAME$3,this.enabled=!0,this.required=!1,this._exporter=i}return a.prototype.dispose=function(){this._lights=null},Object.defineProperty(a.prototype,"wasUsed",{get:function(){return!!this._lights},enumerable:!1,configurable:!0}),a.prototype.onExporting=function(){this._exporter._glTF.extensions[NAME$3]=this._lights},a.prototype.postExportNodeAsync=function(i,e,o,s){var c=this;return new Promise(function(d,_){if(e&&o instanceof ShadowLight){var b=o,k=void 0,j=b.getTypeID()==Light.LIGHTTYPEID_POINTLIGHT?"point":b.getTypeID()==Light.LIGHTTYPEID_DIRECTIONALLIGHT?"directional":b.getTypeID()==Light.LIGHTTYPEID_SPOTLIGHT?"spot":null;if(j==null)Logger$2.Warn(i+": Light "+b.name+" is not supported in "+NAME$3);else{var $=b.position.clone(),_e=c._exporter._convertToRightHandedSystemMap[o.uniqueId];if($.equals(Vector3.Zero())||(_e&&_GLTFUtilities._GetRightHandedPositionVector3FromRef($),e.translation=$.asArray()),j!=="point"){var et=b.direction,tt=-Math.atan2(et.z*(c._exporter._babylonScene.useRightHandedSystem?-1:1),et.x)+Math.PI/2,rt=Math.sqrt(et.x*et.x+et.z*et.z),it=-Math.atan2(et.y,rt),nt=Quaternion.RotationYawPitchRoll(tt,it,0);_e&&_GLTFUtilities._GetRightHandedQuaternionFromRef(nt),nt.equals(Quaternion.Identity())||(e.rotation=nt.asArray())}if(b.falloffType!==Light.FALLOFF_GLTF&&Logger$2.Warn(i+": Light falloff for "+b.name+" does not match the "+NAME$3+" specification!"),k={type:j},b.diffuse.equals(Color3.White())||(k.color=b.diffuse.asArray()),b.intensity!==1&&(k.intensity=b.intensity),b.range!==Number.MAX_VALUE&&(k.range=b.range),j==="spot"){var ot=b;ot.angle!==Math.PI/2&&(k.spot==null&&(k.spot={}),k.spot.outerConeAngle=ot.angle/2),ot.innerAngle!==0&&(k.spot==null&&(k.spot={}),k.spot.innerConeAngle=ot.innerAngle/2)}c._lights==null&&(c._lights={lights:[]}),c._lights.lights.push(k);var at={light:c._lights.lights.length-1},st=o.parent;if(st&&st.getChildren().length==1){var ut=c._exporter._nodes[s[st.uniqueId]];if(ut){var ft=TmpVectors.Matrix[0],lt=TmpVectors.Matrix[1],ht=ut.translation?new Vector3(ut.translation[0],ut.translation[1],ut.translation[2]):Vector3.Zero(),pt=ut.rotation?new Quaternion(ut.rotation[0],ut.rotation[1],ut.rotation[2],ut.rotation[3]):Quaternion.Identity(),mt=ut.scale?new Vector3(ut.scale[0],ut.scale[1],ut.scale[2]):Vector3.One();Matrix.ComposeToRef(mt,pt,ht,ft),ft.invertToRef(lt);var dt=TmpVectors.Matrix[2],gt=e.translation?new Vector3(e.translation[0],e.translation[1],e.translation[2]):Vector3.Zero();b instanceof DirectionalLight&&gt.subtractInPlace(c._exporter._babylonScene.useRightHandedSystem?b.direction:_GLTFUtilities._GetRightHandedPositionVector3(b.direction));var _t=c._exporter._babylonScene.useRightHandedSystem?Quaternion.Identity():new Quaternion(0,1,0,0);e.rotation&&_t.multiplyInPlace(new Quaternion(e.rotation[0],e.rotation[1],e.rotation[2],e.rotation[3]));var yt=e.scale?new Vector3(e.scale[0],e.scale[1],e.scale[2]):Vector3.One();Matrix.ComposeToRef(yt,_t,gt,dt),dt.multiplyToRef(lt,dt);var Tt=TmpVectors.Vector3[0],St=TmpVectors.Quaternion[0],At=TmpVectors.Vector3[1];dt.decompose(Tt,St,At),ut.scale=Tt.asArray(),ut.rotation=St.asArray(),ut.translation=At.asArray(),ut.extensions==null&&(ut.extensions={}),ut.extensions[NAME$3]=at,d(null);return}}e.extensions==null&&(e.extensions={}),e.extensions[NAME$3]=at}}d(e)})},a}();_Exporter.RegisterExtension(NAME$3,function(a){return new KHR_lights_punctual(a)});var NAME$2="KHR_materials_clearcoat",KHR_materials_clearcoat=function(){function a(i){this.name=NAME$2,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=i}return a.prototype.dispose=function(){},Object.defineProperty(a.prototype,"wasUsed",{get:function(){return this._wasUsed},enumerable:!1,configurable:!0}),a.prototype.postExportMaterialAdditionalTextures=function(i,e,o){var s=[];return o instanceof PBRBaseMaterial&&o.clearCoat.isEnabled?(o.clearCoat.texture&&s.push(o.clearCoat.texture),!o.clearCoat.useRoughnessFromMainTexture&&o.clearCoat.textureRoughness&&s.push(o.clearCoat.textureRoughness),o.clearCoat.bumpTexture&&s.push(o.clearCoat.bumpTexture),s):[]},a.prototype.postExportMaterialAsync=function(i,e,o){var s=this;return new Promise(function(c,d){if(o instanceof PBRBaseMaterial){if(!o.clearCoat.isEnabled){c(e);return}s._wasUsed=!0,e.extensions=e.extensions||{};var _=s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.texture),b=void 0;o.clearCoat.useRoughnessFromMainTexture?b=s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.texture):b=s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.textureRoughness),o.clearCoat.isTintEnabled&&Tools.Warn("Clear Color tint is not supported for glTF export. Ignoring for: "+o.name),o.clearCoat.remapF0OnInterfaceChange&&Tools.Warn("Clear Color F0 remapping is not supported for glTF export. Ignoring for: "+o.name);var k=s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.bumpTexture),j={clearcoatFactor:o.clearCoat.intensity,clearcoatTexture:_!=null?_:void 0,clearcoatRoughnessFactor:o.clearCoat.roughness,clearcoatRoughnessTexture:b!=null?b:void 0,clearcoatNormalTexture:k!=null?k:void 0,hasTextures:function(){return j.clearcoatTexture!==null||j.clearcoatRoughnessTexture!==null||j.clearcoatRoughnessTexture!==null}};e.extensions[NAME$2]=j}c(e)})},a}();_Exporter.RegisterExtension(NAME$2,function(a){return new KHR_materials_clearcoat(a)});var NAME$1="KHR_materials_sheen",KHR_materials_sheen=function(){function a(i){this.name=NAME$1,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=i}return a.prototype.dispose=function(){},Object.defineProperty(a.prototype,"wasUsed",{get:function(){return this._wasUsed},enumerable:!1,configurable:!0}),a.prototype.postExportMaterialAdditionalTextures=function(i,e,o){return o instanceof PBRMaterial&&o.sheen.isEnabled&&o.sheen.texture?[o.sheen.texture]:[]},a.prototype.postExportMaterialAsync=function(i,e,o){var s=this;return new Promise(function(c,d){var _,b,k,j;if(o instanceof PBRMaterial){if(!o.sheen.isEnabled){c(e);return}s._wasUsed=!0,e.extensions==null&&(e.extensions={});var $={sheenColorFactor:o.sheen.color.asArray(),sheenRoughnessFactor:(_=o.sheen.roughness)!==null&&_!==void 0?_:0,hasTextures:function(){return $.sheenColorTexture!==null||$.sheenRoughnessTexture!==null}};o.sheen.texture&&($.sheenColorTexture=(b=s._exporter._glTFMaterialExporter._getTextureInfo(o.sheen.texture))!==null&&b!==void 0?b:void 0),o.sheen.textureRoughness&&!o.sheen.useRoughnessFromMainTexture?$.sheenRoughnessTexture=(k=s._exporter._glTFMaterialExporter._getTextureInfo(o.sheen.textureRoughness))!==null&&k!==void 0?k:void 0:o.sheen.texture&&o.sheen.useRoughnessFromMainTexture&&($.sheenRoughnessTexture=(j=s._exporter._glTFMaterialExporter._getTextureInfo(o.sheen.texture))!==null&&j!==void 0?j:void 0),e.extensions[NAME$1]=$}c(e)})},a}();_Exporter.RegisterExtension(NAME$1,function(a){return new KHR_materials_sheen(a)});var NAME="KHR_materials_unlit",KHR_materials_unlit=function(){function a(i){this.name=NAME,this.enabled=!0,this.required=!1,this._wasUsed=!1}return Object.defineProperty(a.prototype,"wasUsed",{get:function(){return this._wasUsed},enumerable:!1,configurable:!0}),a.prototype.dispose=function(){},a.prototype.postExportMaterialAsync=function(i,e,o){var s=this;return new Promise(function(c,d){var _=!1;o instanceof PBRMaterial?_=o.unlit:o instanceof StandardMaterial&&(_=o.disableLighting),_&&(s._wasUsed=!0,e.extensions==null&&(e.extensions={}),e.extensions[NAME]={}),c(e)})},a}();_Exporter.RegisterExtension(NAME,function(a){return new KHR_materials_unlit(a)});new Logger$1("XPackage");function LoadXObject(a,i){return new Promise((e,o)=>{const s=JSON.parse(i);new XArchive().deserialize(s,a).then(d=>{e(d)}).catch(d=>{o(d)})})}const log$14=new Logger$1("AvatarManager");class XAvatarLoader{constructor(){ct(this,"containers",new Map);ct(this,"meshes",new Map);ct(this,"animations",new Map);ct(this,"aniPath",new Map);ct(this,"binPath",new Map);ct(this,"texPath",new Map);ct(this,"matPath",new Map);ct(this,"mshPath",new Map);ct(this,"rootPath",new Map);ct(this,"meshTexList",new Map);ct(this,"_enableIdb",!0);ct(this,"_mappings",new Map);ct(this,"_sharedTex",new Map);ct(this,"avaliableAnimation",new Map);ct(this,"enableShareTexture",!0);ct(this,"enableShareAnimation",!0);ct(this,"fillEmptyLod",!0);ct(this,"pendantMap",new Map);const i=new GLTFFileLoader;SceneLoader.RegisterPlugin(i),i.preprocessUrlAsync=function(e){const o=avatarLoader._mappings.get(e);return o?Promise.resolve(o):Promise.resolve(e)}}_parsePendant(i,e){if(!i||!e){log$14.error("[Engine] invalid id or url when loading pendant");return}const o=".zip",s=e.replace(o,"/");this.pendantMap.set(i,s)}pullAndLoadXObject(i,e){const o=avatarLoader.pendantMap.get(e);return Tools.LoadFileAsync(o+`${e}.json`,!1).then(s=>{if(!(s instanceof ArrayBuffer))return LoadXObject(o,s).then(c=>c)})}getParsedUrl(i,e,o,s=""){return new Promise((c,d)=>{if(!o||o.indexOf(".zip")===-1)return c(o);const _=this.rootPath.get(o);if(_)return c(_);{const b=".zip",k=o.replace(b,"")+COMPONENT_LIST_PREFIX;i.urlTransformer(k,!0).then(j=>{if(!j)return d("Loading Failed");new Response(j).json().then($=>{var tt,rt,it,nt,ot,at,st;const _e=o.replace(b,""),et=_e+((tt=$==null?void 0:$.components)==null?void 0:tt.url.replace("./",""));if(this.rootPath.set(o,et),$.components?($.components.url&&this.mshPath.set(e,_e+"/"+((rt=$==null?void 0:$.components)==null?void 0:rt.url.replace("./",""))),$.components.url_lod2&&this.mshPath.set(e+"_"+avatarSetting.lod[1].level,_e+"/"+((it=$==null?void 0:$.components)==null?void 0:it.url_lod2.replace("./",""))),$.components.url_lod4&&this.mshPath.set(e+"_"+avatarSetting.lod[2].level,_e+"/"+((nt=$==null?void 0:$.components)==null?void 0:nt.url_lod4.replace("./","")))):($.meshes.url&&this.mshPath.set(e,_e+"/"+((ot=$==null?void 0:$.meshes)==null?void 0:ot.url.replace("./",""))),$.meshes.url_lod2&&this.mshPath.set(e+"_"+avatarSetting.lod[1].level,_e+"/"+((at=$==null?void 0:$.meshes)==null?void 0:at.url_lod2.replace("./",""))),$.meshes.url_lod4&&this.mshPath.set(e+"_"+avatarSetting.lod[2].level,_e+"/"+((st=$==null?void 0:$.meshes)==null?void 0:st.url_lod4.replace("./","")))),$.materials&&$.materials.forEach(ut=>{const ft=_e+"/"+ut.url;this.matPath.set(ut.name,ft)}),$.bin){const ut=_e+"/"+$.bin.url;this.binPath.set(e,ut);const ft=_e+"/"+$.bin.url_lod2;this.binPath.set(e+"_"+avatarSetting.lod[1].level,ft);const lt=_e+"/"+$.bin.url_lod4;this.binPath.set(e+"_"+avatarSetting.lod[2].level,lt)}return $.textures&&$.textures.forEach(ut=>{const ft=_e+"/"+ut.url;this.texPath.set(ut.url,ft);const lt=this.meshTexList.get($.components.url);ut.type==="png"&&(lt?lt.find(ht=>ht===ut.name)||lt.push(ut.url):this.meshTexList.set(e,[ut.name]))}),c(et)}).catch($=>{d(`[Engine] parse json file error,${$}`)})}).catch(j=>{d(`[Engine] ulrtransform error, cannot find resource in db,${j}`)})}})}async parse(i,e){const o=[];e.forEach(s=>{this._setAnimationList(s.id,s.animations),o.push(this.getParsedUrl(i,s.id,s.url)),s.components.forEach(c=>{c.name==="pendant"?c.units.forEach(d=>{this._parsePendant(d.id,d.url)}):c.units.forEach(d=>{o.push(this.getParsedUrl(i,d.name,d.url))})})}),await Promise.all(o)}_setAnimationList(i,e){e?e.forEach(o=>{this.aniPath.set(i+"_"+o.name,o.url)}):log$14.error("[Engine] no animation list exist, please check config for details")}disposeContainer(){const i=[];this.containers.forEach((e,o)=>{if(e.xReferenceCount<1){if(this.enableShareTexture&&e.textures.length>0){for(let s=0;s<e.textures.length;++s)e.textures[s].xReferenceCount!=null?e.textures[s].xReferenceCount--:e.textures[s].xReferenceCount=0,e.textures[s]._parentContainer=null;e.textures=[]}i.push(o)}}),i.forEach(e=>{var o,s;(o=this.containers.get(e))==null||o.removeAllFromScene(),(s=this.containers.get(e))==null||s.dispose(),this.containers.delete(e)}),this._sharedTex.forEach((e,o)=>{e.xReferenceCount==0&&(e.dispose(),this._sharedTex.delete(o))})}set enableIdb(i){this._enableIdb=i}getGlbPath(i){return this.aniPath.get(i+".glb")}getGltfPath(i){return this.mshPath.get(i+".gltf")}getPngUrl(i){return this.texPath.get(i+".png")}getMeshUrl(i){return this.mshPath.get(i)}_getSourceKey(i,e){return e&&avatarSetting.lod[e]?i+avatarSetting.lod[e].fileName.split(".")[0]:i}_getAnimPath(i,e){let o=this.aniPath.get(e+"_animations_"+e.split("_")[1]);return o||(o=this.aniPath.get(e+"_"+i)),o}load(i,e,o,s){return this.loadGlb(i,e,o).then(c=>c||Promise.reject("[Engine] container load failed")).catch(()=>Promise.reject("[Engine] container load failed"))}_searchAnimation(i,e){let o;return this.containers.forEach((s,c)=>{const d=e.split("_")[0];c.indexOf(d)!=-1&&c.indexOf(i)!=-1&&(o=s)}),o}loadAnimRes(i,e,o){const s=this._getAnimPath(e,o),c=getAnimationKey(e,o);return s&&this.containers.get(s)?Promise.resolve(this.containers.get(s)):s?this._loadGlbFromBlob(i,c,s).then(d=>d.animationGroups.length==0?(this.containers.delete(c),d.dispose(),Promise.reject("container does not contains animation data")):d):Promise.reject("no such url")}loadGlb(i,e,o){let s=this.getMeshUrl(this._getSourceKey(e,o));return!s&&this.fillEmptyLod&&(o=0,s=this.getMeshUrl(this._getSourceKey(e,o))),s&&this.containers.get(s)?Promise.resolve(this.containers.get(s)):s?this._enableIdb?this._loadGlbFromBlob(i,this._getSourceKey(e,o),s):this._loadGlbFromUrl(i,this._getSourceKey(e,o),s):Promise.reject("no such url")}loadGltf(i,e,o,s){const c=this._getSourceKey(e,o||0);let d=this.getGltfPath(c);return!d&&this.fillEmptyLod&&(d=this.getGltfPath(e)),d&&this.containers.get(d)?Promise.resolve(this.containers.get(d)):this._enableIdb?this._loadGltfFromBlob(i,e,o,s):d?this._loadGltfFromUrl(i,e,d.replace(e+".gltf","")):Promise.reject()}loadSubsequence(){}loadVAT(){}getResourceName(i){return this.meshTexList.get(i)}_loadGltfFromUrl(i,e,o){return SceneLoader.LoadAssetContainerAsync(o,e+".gltf",i.Scene,null,".gltf")}_loadGlbFromBlob(i,e,o){return i.urlTransformer(o).then(s=>SceneLoader.LoadAssetContainerAsync("",s,i.Scene,null,".glb").then(c=>{if(c){if(this.containers.get(o))return c.dispose(),this.containers.get(o);if(c.addAllToScene(),this.enableShareTexture&&c.textures.length>0){const d=[];let _=!1;c.meshes.forEach(b=>{if(b.material){const k=b.material._albedoTexture;if(k){let j=k.name;j=j.replace(" (Base Color)","").split(".")[0];const $=this._sharedTex.get(j);$?(_=!0,b.material._albedoTexture=$,d.push($),$._parentContainer=c,$.xReferenceCount++):(this._sharedTex.set(j,k),c.textures[0].xReferenceCount=1)}}}),_&&(c.textures.forEach(b=>{i.Scene.removeTexture(b),b.dispose()}),c.textures=d)}return c.xReferenceCount=0,c.meshes.forEach(d=>{d.setEnabled(!1)}),this.containers.set(o,c),Promise.resolve(c)}else return Promise.reject("glb file load failed")}))}_loadGlbFromUrl(i,e,o){return SceneLoader.LoadAssetContainerAsync("",o,i.Scene,null,".glb").then(s=>s?(s.addAllToScene(),s.meshes.forEach(c=>{c.setEnabled(!1)}),this.enableShareTexture&&s.textures.length>0?(s.meshes.forEach(c=>{if(c.material){const d=c.material._albedoTexture;if(d){let _=d.name;_=_.replace(" (Base Color)","").split(".")[0];const b=this._sharedTex.get(_);b?(c.material._albedoTexture=b,b.xReferenceCount++):(this._sharedTex.set(_,d),s.textures[0].xReferenceCount=1)}}}),s.xReferenceCount=0,this.containers.set(o,s),Promise.resolve(s)):Promise.reject("glb file load failed"),s.xReferenceCount=0,this.containers.set(o,s),Promise.resolve(s)):Promise.reject("glb file load failed"))}_loadGltfFromBlob(i,e,o,s){return new Promise((c,d)=>{const _=[];let b=this._getSourceKey(e,o),k=this.getGltfPath(b);if(!k&&this.fillEmptyLod&&(o=0,b=this._getSourceKey(e,o),k=this.getGltfPath(b)),!k)return d(`[Engine] gltf path incorrect ${b},cancel.`);const j=this.mshPath.get(b+".gltf");if(!j)return d("cannot find asset mshPath");const $=this.binPath.get(b+".bin");if(!$)return d("cannot find asset binPath");if(!s){const tt=this.meshTexList.get(e);if(!tt||tt.length==0)return d("cannot find texture");s=tt[0]}const _e=this.texPath.get(s+".png");if(!_e)return d();const et=this.texPath.get(s+"-astc.ktx");if(!et)return d();_.push(this._blobMapping(i,j)),_.push(this._blobMapping(i,$)),_.push(this._blobMapping(i,_e)),_.push(this._blobMapping(i,et)),Promise.all(_).then(()=>{const tt=k.replace(b+".gltf","");SceneLoader.LoadAssetContainerAsync(tt,b+".gltf",i.Scene,null,".gltf").then(rt=>{var nt;this.containers.set(k,rt),rt.addAllToScene(),rt.meshes.forEach(ot=>{ot.setEnabled(!1)});const it=this._sharedTex.get(e);it?((nt=rt.meshes[1].material._albedoTexture)==null||nt.dispose(),rt.meshes[1].material._albedoTexture=it):this._sharedTex.set(e,rt.meshes[1].material._albedoTexture),c(rt)})})})}_blobMapping(i,e){return new Promise((o,s)=>{i.urlTransformer(e).then(c=>c?(this._mappings.set(e,c),o(e)):s(`[Engine] url urlTransformer parse error ${e}`))})}}const avatarLoader=new XAvatarLoader,log$13=new Logger$1("AnimationController");class XAnimationController{constructor(i){ct(this,"iBodyAnim");ct(this,"animations",[]);ct(this,"defaultAnimation","Idle");ct(this,"onPlay","Idle");ct(this,"loop",!0);ct(this,"animationExtras",[]);ct(this,"enableBlend",!1);ct(this,"enableSkLod",!1);ct(this,"_boneMap",new Map);ct(this,"_lodMask",new Map);ct(this,"activeFaceAnimation");ct(this,"iFaceAnim");ct(this,"_scene");ct(this,"_avatar");ct(this,"onPlayObservable",new Observable);ct(this,"postObserver");ct(this,"playAnimation",(i,e,o=0,s,c,d)=>new Promise((_,b)=>{if(this._isPlaying(i,o)||(this._registerAnimInfo(i,e,o,s,c,d),!this._isAnimate()))return _(null);this._prerocess(i,e),this._avatar.avatarManager.loadAnimation(this._avatar.avatarType,i).then(k=>{if(!k)return b(new AvatarAnimationError("animation group does not exist"));const j=this._mappingSkeleton(k);if(!j)return b(new AvatarAnimationError("mapping animation failed"));if(j&&this._isAnimationValid(j))return j.dispose(),b(new AvatarAnimationError("mapping animation failed"));if(this.enableSkLod&&this.skeletonMask(j,o),this.detachAnimation(o),o==0?this.iBodyAnim.animGroup=j:o==1&&(this.iFaceAnim.animGroup=j),!this._playAnimation(o))return b(new AvatarAnimationError("[Engine] play animation failed, animtion resource does not match current character"));this._playEffect(),this.postObserver=j.onAnimationEndObservable.addOnce(()=>(this._postprocess(o),_(null)))})}));ct(this,"stopAnimation",(i=0)=>{var e,o,s,c;switch(i){case 0:this.iBodyAnim&&this.iBodyAnim.animGroup&&((e=this.iBodyAnim)==null||e.animGroup.stop());break;case 1:this.iFaceAnim&&this.iFaceAnim.animGroup&&((o=this.iFaceAnim)==null||o.animGroup.stop());break;case 2:this.iBodyAnim&&this.iBodyAnim.animGroup&&((s=this.iBodyAnim)==null||s.animGroup.stop()),this.iFaceAnim&&this.iFaceAnim.animGroup&&((c=this.iFaceAnim)==null||c.animGroup.stop());break}});ct(this,"pauseAnimation",(i=0)=>{var e,o,s,c;switch(i){case 0:this.iBodyAnim&&this.iBodyAnim.animGroup&&((e=this.iBodyAnim)==null||e.animGroup.pause());break;case 1:this.iFaceAnim&&this.iFaceAnim.animGroup&&((o=this.iFaceAnim)==null||o.animGroup.pause());break;case 2:this.iBodyAnim&&this.iBodyAnim.animGroup&&((s=this.iBodyAnim)==null||s.animGroup.pause()),this.iFaceAnim&&this.iFaceAnim.animGroup&&((c=this.iFaceAnim)==null||c.animGroup.pause());break}});ct(this,"resetAnimation",(i=0)=>{var e,o,s,c;switch(i){case 0:this.iBodyAnim&&this.iBodyAnim.animGroup&&((e=this.iBodyAnim)==null||e.animGroup.reset());break;case 1:this.iFaceAnim&&this.iFaceAnim.animGroup&&((o=this.iFaceAnim)==null||o.animGroup.reset());break;case 2:this.iBodyAnim&&this.iBodyAnim.animGroup&&((s=this.iBodyAnim)==null||s.animGroup.reset()),this.iFaceAnim&&this.iFaceAnim.animGroup&&((c=this.iFaceAnim)==null||c.animGroup.reset());break}});this._avatar=i,this._scene=i.avatarManager.scene,this.animationExtras.push(action.Cheering.animName),this._boneMap=new Map}_isPlaying(i,e){return e==0&&this.iBodyAnim!=null&&this.iBodyAnim.animGroup&&i==this.iBodyAnim.name?!0:!!(e==1&&this.iFaceAnim!=null&&this.iFaceAnim.animGroup&&i==this.iFaceAnim.name)}activeAnimation(i=0){var e,o;switch(i){case 0:return(e=this.iBodyAnim)==null?void 0:e.animGroup;case 1:return(o=this.iFaceAnim)==null?void 0:o.animGroup;default:return}}enableAnimationBlend(i=.1,e=0){var o,s,c,d;if(e==0&&((o=this.iBodyAnim)==null?void 0:o.animGroup))for(const _ of(s=this.iBodyAnim)==null?void 0:s.animGroup.targetedAnimations)_.animation.enableBlending=!0,_.animation.blendingSpeed=i;else if(e==0&&((c=this.iFaceAnim)==null?void 0:c.animGroup))for(const _ of(d=this.iFaceAnim)==null?void 0:d.animGroup.targetedAnimations)_.animation.enableBlending=!0,_.animation.blendingSpeed=i}disableAnimationBlend(i=0){var e,o,s,c;if(i==0&&((e=this.iBodyAnim)==null?void 0:e.animGroup))for(const d of(o=this.iBodyAnim)==null?void 0:o.animGroup.targetedAnimations)d.animation.enableBlending=!1;else if(i==0&&((s=this.iFaceAnim)==null?void 0:s.animGroup))for(const d of(c=this.iFaceAnim)==null?void 0:c.animGroup.targetedAnimations)d.animation.enableBlending=!1}skeletonMask(i,e=0){if(e==0){const o=this._lodMask.get(this._avatar.distLevel);if(o)for(let s=0;s<i.targetedAnimations.length;++s)o.includes(i.targetedAnimations[s].target.name)||(i.targetedAnimations.splice(s,1),s--);return!0}return!1}detachAnimation(i=2){var e,o;switch(i){case 0:this.iBodyAnim&&this.iBodyAnim.animGroup&&(this.iBodyAnim.animGroup._parentContainer.xReferenceCount&&this.iBodyAnim.animGroup._parentContainer.xReferenceCount--,this.iBodyAnim.animGroup.stop(),this.iBodyAnim.animGroup.dispose(),this.iBodyAnim.animGroup=void 0);break;case 1:this.iFaceAnim&&this.iFaceAnim.animGroup&&(this.iFaceAnim.animGroup._parentContainer.xReferenceCount&&this.iFaceAnim.animGroup._parentContainer.xReferenceCount--,this.iFaceAnim.animGroup.stop(),this.iFaceAnim.animGroup.dispose(),this.iFaceAnim.animGroup=void 0);break;case 2:this.iBodyAnim&&this.iBodyAnim.animGroup&&(this.iBodyAnim.animGroup._parentContainer.xReferenceCount&&this.iBodyAnim.animGroup._parentContainer.xReferenceCount--,(e=this.iBodyAnim)==null||e.animGroup.stop(),(o=this.iBodyAnim)==null||o.animGroup.dispose(),this.iBodyAnim.animGroup=void 0),this.iFaceAnim&&this.iFaceAnim.animGroup&&(this.iFaceAnim.animGroup._parentContainer.xReferenceCount&&this.iFaceAnim.animGroup._parentContainer.xReferenceCount--,this.iFaceAnim.animGroup.stop(),this.iFaceAnim.animGroup.dispose(),this.iFaceAnim.animGroup=void 0);break}}blendAnimation(){}getAnimation(i,e){return avatarLoader.animations.get(getAnimationKey(e,i))}_mappingSkeleton(i){if(i){const e=i.clone(i.name,o=>{var c,d,_;const s=o.name.split(" ").length>2?o.name.split(" ")[2]:o.name;if(this._boneMap.size===((c=this._avatar.skeleton)==null?void 0:c.bones.length))return this._boneMap.get(s);{const b=(_=(d=this._avatar.skeleton)==null?void 0:d.bones.find(k=>k.name===o.name||k.name===o.name.split(" ")[2]))==null?void 0:_.getTransformNode();return b&&(b.name=s,this._boneMap.set(s,b)),b}});return e._parentContainer=i._parentContainer,e}else return}removeAnimation(i){const e=avatarLoader.containers.get(i.name);e&&(e.dispose(),avatarLoader.containers.delete(i.name),avatarLoader.animations.delete(getAnimationKey(i.name,i.skType)))}_setPosition(i,e){this._avatar.priority===0&&this._avatar.isRender&&i===this.defaultAnimation&&i!=this.onPlay&&!this._avatar.isSelected&&this._avatar.setPosition(this._avatar.position,!0)}_registerAnimInfo(i,e,o=0,s,c,d){const _={name:i,skType:this._avatar.avatarType,loop:e,playSpeed:s,currentFrame:0,startFrame:c,endFrame:d};o==0?this.iBodyAnim==null?this.iBodyAnim=_:(this.iBodyAnim.name=i,this.iBodyAnim.skType=this._avatar.avatarType,this.iBodyAnim.loop=e,this.iBodyAnim.playSpeed=s,this.iBodyAnim.currentFrame=0,this.iBodyAnim.startFrame=c,this.iBodyAnim.endFrame=d):o==1&&(this.iFaceAnim==null?this.iFaceAnim=_:(this.iFaceAnim.name=i,this.iFaceAnim.skType=this._avatar.avatarType,this.iFaceAnim.loop=e,this.iFaceAnim.playSpeed=s,this.iFaceAnim.currentFrame=0,this.iFaceAnim.startFrame=c,this.iFaceAnim.endFrame=d)),this.onPlay=i,this.loop=e}_isAnimate(){var i;return!(!this._avatar.isRender||!this._avatar.skeleton||((i=this._avatar.rootNode)==null?void 0:i.getChildMeshes().length)==0)}_prerocess(i,e){this._avatar.isRayCastEnable&&this._setPosition(i,e),this._avatar.priority===0&&log$13.info(`start play animation: ${i} on avatar ${this._avatar.id}`)}_playEffect(){this.animationExtras.indexOf(this.iBodyAnim.name)!=-1&&action.Cheering.attachPair.forEach(e=>{this._avatar.attachExtraProp(e.obj,e.bone,new Vector3(e.offset.x,e.offset.y,e.offset.z),new Vector3(e.rotate.x,e.rotate.y,e.rotate.z)),this._avatar.showExtra(e.obj)})}_playAnimation(i=0){var e,o;return i==0&&this.iBodyAnim&&((e=this.iBodyAnim)==null?void 0:e.animGroup)?(this.onPlayObservable.notifyObservers(this._scene),this.iBodyAnim.animGroup.start(this.loop,this.iBodyAnim.playSpeed,this.iBodyAnim.startFrame,this.iBodyAnim.endFrame,!1),!0):i==1&&this.iFaceAnim&&((o=this.iFaceAnim)==null?void 0:o.animGroup)?(this.iFaceAnim.animGroup.start(this.loop,this.iFaceAnim.playSpeed,this.iFaceAnim.startFrame,this.iFaceAnim.endFrame,!1),!0):!1}_postprocess(i){var o,s;let e;i==0?e=(o=this.iBodyAnim)==null?void 0:o.name:i==1&&(e=(s=this.iFaceAnim)==null?void 0:s.name),e===action.Cheering.animName&&this._avatar.disposeExtra()}_isAnimationValid(i){for(let e=0;e<i.targetedAnimations.length;++e)if(i.targetedAnimations[e].target)return!1;return!0}}const log$12=new Logger$1("XAvatarComopnent");class XAvatarComopnent{constructor(){ct(this,"resourceIdList",[]);ct(this,"skeleton");ct(this,"extraProp");ct(this,"extras",[]);ct(this,"body");ct(this,"accessories");this.accessories=new Map}addBodyComp(i,e){return!i.rootNode||e.root.getChildMeshes().length===0?(e.isRender=!1,!1):(this.body=e,this.body.root.parent=i.rootNode,e.isRender=!0,this.body.root.getChildMeshes()[0]&&(this.body.root.getChildMeshes()[0].xtype=EMeshType.XAvatar,this.body.root.getChildMeshes()[0].xid=i.id),this.skeleton=e.skeleton,!0)}addClothesComp(i,e){return!i.rootNode||!this.skeleton||!e.root?(e.isRender=!1,!1):(e.root.xtype=EMeshType.XAvatar,e.root.xid=i.id,e.isRender=!0,e.root.parent=i.rootNode.getChildMeshes()[0],this.resourceIdList.push(e),e.root.skeleton=this.skeleton,e.root.getChildMeshes().forEach(o=>{o.skeleton=this.skeleton}),!0)}clearClothesComp(i){i.root.getChildMeshes().forEach(e=>{e.skeleton=null,e.dispose(),e.xid=void 0}),i.root.dispose(),this.resourceIdList=this.resourceIdList.filter(e=>e.uId!=i.uId)}clearAllClothesComps(){this.resourceIdList.forEach(i=>{var e;i.root.parent=null,i.root._parentContainer.xReferenceCount&&(i.root._parentContainer.xReferenceCount--,i.root._parentContainer=null),i.isRender=!1,i.isSelected=!1,i.root.getChildMeshes().forEach(o=>{o.skeleton=null,o.dispose()}),(e=i.root.skeleton)==null||e.dispose(),i.root.dispose()}),this.resourceIdList=[]}dispose(i){this.body?(this.body.root._parentContainer.xReferenceCount&&(this.body.root._parentContainer.xReferenceCount--,this.body.root._parentContainer=null),this.clearAllClothesComps(),this.body.isRender=!1,this.body.skeleton.dispose(),this.body.skeleton=null,this.body.root.dispose(),this.body=void 0,this.skeleton&&(this.skeleton.dispose(),this.skeleton=void 0)):log$12.warn("[Engine] no body to dispose")}async attachPendant(i,e){return Promise.resolve(avatarLoader.pullAndLoadXObject(i.avatarManager.sceneManager,e).then(o=>{const s=o,c=this.accessories.get(s.pointId);return c?(c.dispose(),this.accessories.set(s.pointId,s),log$12.warn("[Engine] \u8BE5\u6302\u70B9\u5F53\u524D\u88AB\u5360\u7528\uFF0C\u5DF2\u66FF\u6362\u8BE5\u6302\u70B9")):this.accessories.set(s.pointId,s),s.attachTo(i),s}))}detachPendant(i,e=!0){const o=this.accessories.get(i);o&&(o.dispose(),this.accessories.delete(i))}changeClothesComp(i,e,o,s,c){return new Promise(d=>{if(this.resourceIdList.some(_=>_.name===e))return d();if(i.isHide||!i.isRender)c.concat(o).forEach(b=>{i.clothesList=i.clothesList.filter(j=>j.type!=b);const k={type:o,id:e,url:s,lod:0};i.clothesList.push(k)}),d();else{const _=c.concat(o);i.avatarManager.loadDecoration(o,e,0).then(b=>{if(b){i.attachDecoration(b);const k={type:o,id:e,url:s};i.clothesList.push(k),b.root.setEnabled(!0),_.forEach(j=>{const $=this.resourceIdList.filter(_e=>_e.type===j);if($.length>1){const _e=$.filter(et=>et.name===e);if(_e.length>1)for(let et=1;et<_e.length;++et){i.detachDecoration(_e[et]),i.clothesList=i.clothesList.filter(rt=>rt.id!=_e[et].name);const tt={type:o,id:e,url:s};i.clothesList.push(tt)}}$[0]&&$[0].name!=e&&this._readyToDetach(i,o)&&(i.detachDecoration($[0]),i.clothesList=i.clothesList.filter(_e=>_e.id!=$[0].name))})}return d()})}})}_readyToDetach(i,e){return!((e=="clothes"||e=="pants")&&i.clothesList.filter(s=>s.type==="suit").length==1&&(!i.clothesList.some(s=>s.type==="pants")||!i.clothesList.some(s=>s.type==="clothes")))}addDecoComp(i,e,o,s,c){if(i.isRender){const d=i.avatarManager.extraComps.get(e),_=d==null?void 0:d.clone(e,void 0);if(!d){log$12.error("\u6CA1\u6709\u5BF9\u5E94\u7684\u7EC4\u4EF6");return}this.extras.push(_);const b=this.skeleton.bones.find(k=>k.name===o);_.position=s,_.rotation=c,_.attachToBone(b,i.rootNode.getChildMeshes()[0])}}showExtra(i){this.extras.forEach(e=>{e.name.indexOf(i)>0&&e.setEnabled(!0)})}hideExtra(i){this.extras.forEach(e=>{e.name.indexOf(i)>0&&e.setEnabled(!1)})}disposeExtra(){this.extras.forEach(i=>{i.dispose()}),this.extras=[]}}function LinearBezierCurves(a,i,e){return Vector3.Lerp(i,e,1-a)}function QuadraticBezierCurves(a,i,e,o){const s=LinearBezierCurves(a,i,e),c=LinearBezierCurves(a,e,o);return LinearBezierCurves(a,s,c)}function CubicBezierCurves(a,i,e,o,s){const c=QuadraticBezierCurves(a,i,e,o),d=QuadraticBezierCurves(a,e,o,s);return LinearBezierCurves(a,c,d)}function CardinalMultiply(a,i,e,o,s,c){let d,_,b,k;return d=a[0]*i+a[1]*e+a[2]*o+a[3]*s,_=a[4]*i+a[5]*e+a[6]*o+a[7]*s,b=a[8]*i+a[9]*e+a[10]*o+a[11]*s,k=a[12]*i+a[13]*e+a[14]*o+a[15]*s,k+c*(b+c*(_+c*d))}function CardinalCurves(a,i,e,o,s,c){const d=new Array(16),_=c;return d[0]=-_,d[1]=2-_,d[2]=_-2,d[3]=_,d[4]=2*_,d[5]=_-3,d[8]=-_,d[9]=0,d[12]=0,d[13]=1,d[6]=3-2*_,d[7]=-_,d[10]=_,d[11]=0,d[14]=0,d[15]=0,new Vector3(CardinalMultiply(d,i.x,e.x,o.x,s.x,a),CardinalMultiply(d,i.y,e.y,o.y,s.x,a),CardinalMultiply(d,i.z,e.z,o.z,s.x,a))}function HermiteCurves(a,i,e,o,s){const c=Math.pow(a,3),d=Math.pow(a,2),_=2*c-3*d+1,b=-2*c+3*d,k=c-2*d+a,j=c-d,$=i.multiplyByFloats(_,_,_),_e=e.multiplyByFloats(b,b,b),et=o.multiplyByFloats(k,k,k),tt=s.multiplyByFloats(j,j,j);return $.add(_e.add(et).add(tt))}const log$11=new Logger$1("XStateMachine");class XStateMachine{constructor(i){ct(this,"state");ct(this,"isMoving");ct(this,"isRotating");ct(this,"_observer");ct(this,"_movingObserver");ct(this,"_scene");this._scene=i}rotateTo(i,e,o,s){return new Promise((c,d)=>{var $;const _=i.avatarManager.scene;if(o&&i.setRotation(o),e==o)return c();i.priority===0&&log$11.info(`avatar ${i.id} starts to rotate from ${o} to ${e}`);let b=0;const k=1e3/25,j=calcDistance3DAngle(e,i.rotation)/k;this._movingObserver&&_.onBeforeRenderObservable.remove(this._movingObserver),($=i.controller)==null||$.playAnimation(s||"Walking",!0),this._movingObserver=_==null?void 0:_.onBeforeRenderObservable.add(()=>{var _e;if(b<1){if(!i.rootNode)return i.setRotation(e),c();const et=Vector3.Lerp(i.rootNode.rotation,ue4Rotation2Xverse(e),b);i.setRotation(xverseRotation2Ue4(et)),b+=k/(j*1e3)}else return _.onBeforeRenderObservable.remove(this._movingObserver),(_e=i.controller)==null||_e.playAnimation("Idle",!0),c()})})}_filterPathPoint(i){let e=0;const o=1e-4;if(i.length<=1)return i;for(;e<i.length-1;)calcDistance3D(i[e],i[e+1])<o?i.splice(e,1):e++;return i}moveToHermite(i,e,o,s,c,d,_){return new Promise((b,k)=>{var ot;const j=i.avatarManager.scene;i.priority===0&&log$11.info(`avatar ${i.id} starts to move from ${e} to ${o}`);let $=0,_e=ue4Position2Xverse(e),et;const tt=i.rootNode.rotation.y,rt=new Vector3(-Math.sin(tt)*c,0,-Math.cos(tt)*c),it=rt.clone();it.x=-it.x,it.z=-it.z;const nt=1e3/25;this._movingObserver&&j.onBeforeRenderObservable.remove(this._movingObserver),(ot=i.controller)==null||ot.playAnimation(d,!0),this._movingObserver=j==null?void 0:j.onBeforeRenderObservable.add(()=>{var st;et=HermiteCurves($,ue4Position2Xverse(e),ue4Position2Xverse(o),rt,it),i.rootNode.lookAt(et);const at=xverseRotation2Ue4({x:i.rootNode.rotation.x,y:i.rootNode.rotation.y,z:i.rootNode.rotation.z});if(at&&(at.roll=0,at.pitch=0,i.setRotation(at)),$<=1){if(i.setPosition(xversePosition2Ue4(_e),_),!i.rootNode)return i.setPosition(o,_),b();$+=nt/s,_e=et.clone()}else return i.setPosition(o,_),j.onBeforeRenderObservable.remove(this._movingObserver),(st=i.controller)==null||st.playAnimation("Idle",!0),b()})})}moveToCardinal(i,e,o,s,c,d,_,b){return new Promise((k,j)=>{var ot;const $=i.avatarManager.scene;i.priority===0&&log$11.info(`avatar ${i.id} starts to move from ${e} to ${o}`);let _e=0;const et=ue4Position2Xverse(d[0]),tt=ue4Position2Xverse(d[1]);let rt=ue4Position2Xverse(e),it;const nt=1e3/25;this._movingObserver&&$.onBeforeRenderObservable.remove(this._movingObserver),(ot=i.controller)==null||ot.playAnimation(c,!0),this._movingObserver=$==null?void 0:$.onBeforeRenderObservable.add(()=>{var st;it=CardinalCurves(_e,ue4Position2Xverse(e),et,tt,ue4Position2Xverse(o),_),i.rootNode.lookAt(it);const at=xverseRotation2Ue4({x:i.rootNode.rotation.x,y:i.rootNode.rotation.y,z:i.rootNode.rotation.z});if(at&&(at.roll=0,at.pitch=0,i.setRotation(at)),_e<=1){if(i.setPosition(xversePosition2Ue4(rt),b),!i.rootNode)return i.setPosition(o,b),k();_e+=nt/s,rt=it.clone()}else return i.setPosition(o,b),$.onBeforeRenderObservable.remove(this._movingObserver),(st=i.controller)==null||st.playAnimation("Idle",!0),k()})})}moveToBezier(i,e,o,s,c){return new Promise((d,_)=>{var tt;e.length<2&&_("[Engine input Bezier control points error]");const b=i.avatarManager.scene;i.priority===0&&log$11.info(`avatar ${i.id} starts to move in Bezier Curve, from ${e[0]} to ${e[e.length-1]}`);let k=0;const j=new Array;e.forEach(rt=>{j.push(ue4Position2Xverse(rt))});let $=j[0],_e;const et=1e3/25;this._movingObserver&&b.onBeforeRenderObservable.remove(this._movingObserver),(tt=i.controller)==null||tt.playAnimation(s,!0),this._movingObserver=b==null?void 0:b.onBeforeRenderObservable.add(()=>{var rt;switch(e.length){case 2:_e=LinearBezierCurves(k,j[0],j[1]);break;case 3:_e=QuadraticBezierCurves(k,j[0],j[1],j[2]);break;case 4:_e=CubicBezierCurves(k,j[0],j[1],j[2],j[3]);break}if(k!=0){i.rootNode.lookAt(_e);const it=xverseRotation2Ue4({x:i.rootNode.rotation.x,y:i.rootNode.rotation.y,z:i.rootNode.rotation.z});it&&(it.roll=0,it.pitch=0,i.setRotation(it))}if(k<1){if(i.setPosition(xversePosition2Ue4($),c),!i.rootNode)return i.setPosition(j[j.length-1],c),d();k+=et/o,$=_e.clone()}else return b.onBeforeRenderObservable.remove(this._movingObserver),(rt=i.controller)==null||rt.playAnimation("Idle",!0),d()})})}moveTo(i,e,o,s,c,d,_){return new Promise((b,k)=>{var nt;const j=i.avatarManager.scene;i.priority===0&&log$11.info(`avatar ${i.id} starts to move from ${e} to ${o}`);let $=0;d?d=d.concat(o):d=[o],d=this._filterPathPoint(d);let _e=e,et=d.shift();if(!et)return k("[Engine input path error]");let tt=calcDistance3D(_e,et)/s;const rt=1e3/25;i.rootNode.lookAt(ue4Position2Xverse(et));const it=xverseRotation2Ue4({x:i.rootNode.rotation.x,y:i.rootNode.rotation.y,z:i.rootNode.rotation.z});it&&(it.roll=0,it.pitch=0,i.setRotation(it)),this._movingObserver&&j.onBeforeRenderObservable.remove(this._movingObserver),(nt=i.controller)==null||nt.playAnimation(c,!0),this._movingObserver=j==null?void 0:j.onBeforeRenderObservable.add(()=>{var ot;if($<1){const at=Vector3.Lerp(ue4Position2Xverse(_e),ue4Position2Xverse(et),$);if(i.setPosition(xversePosition2Ue4(at),_),!i.rootNode)return i.setPosition(o,_),b();$+=rt/(tt*1e3)}else if(_e=et,et=d.shift(),et){tt=calcDistance3D(_e,et)/s,i.rootNode.lookAt(ue4Position2Xverse(et));const at=xverseRotation2Ue4({x:i.rootNode.rotation.x,y:i.rootNode.rotation.y,z:i.rootNode.rotation.z});at&&(at.roll=0,at.pitch=0,i.setRotation(at)),$=0}else return j.onBeforeRenderObservable.remove(this._movingObserver),(ot=i.controller)==null||ot.playAnimation("Idle",!0),b()})})}lookAt(i,e,o){return new Promise(s=>{var et,tt;const c=ue4Position2Xverse(e),d=1e-4;if(calcDistance3D(i.position,e)<=d)return s();const _=new Vector3(i.rootNode.rotation.x%(Math.PI*2),i.rootNode.rotation.y%(Math.PI*2),i.rootNode.rotation.z%(Math.PI*2));(et=i.rootNode)==null||et.lookAt(c);const b=new Vector3(i.rootNode.rotation.x%(Math.PI*2),(i.rootNode.rotation.y+Math.PI)%(Math.PI*2),i.rootNode.rotation.z%(Math.PI*2));if(i.rootNode.rotation=_,b.y-_.y>Math.PI&&(b.y-=2*Math.PI),b.y-_.y<-Math.PI&&(b.y+=2*Math.PI),i.rootNode&&Math.abs(_.x/_.z-b.x/b.z)<=d)return s();let k=0;const j=o||1/100,$=(tt=i.rootNode)==null?void 0:tt.getScene(),_e=$==null?void 0:$.onBeforeRenderObservable.add(()=>{var nt;const rt=(nt=i.controller)==null?void 0:nt.animations.find(ot=>ot.name=="Idle");(rt==null?void 0:rt.isPlaying)!=!0&&(rt==null||rt.play());const it=Vector3.Lerp(_,b,k);if(k<1){const ot=xverseRotation2Ue4({x:it.x,y:it.y-Math.PI,z:it.z});ot&&(ot.roll=0,ot.pitch=0,i.setRotation(ot)),k+=j}else _e&&$.onBeforeRenderObservable.remove(_e),s()})})}sendObjectTo(i,e,o,s=2,c=10,d={x:0,y:0,z:150}){return new Promise((_,b)=>{var k;if(!o.loaded)b("Gift has not inited!");else{const j=(k=i.rootNode)==null?void 0:k.getScene();let $=0;const _e=1/(s*25),et=_e,tt=c/100,rt=8*tt*_e*_e;let it=.5*rt/_e,nt=ue4Position2Xverse(i.position);const ot=ue4Position2Xverse(d),at=ue4Position2Xverse(i.position),st=j==null?void 0:j.onBeforeRenderObservable.add(()=>{(!e||!i.position)&&(st&&j.onBeforeRenderObservable.remove(st),b("Invalid receiver when shoot gift!")),o.loaded||(st&&j.onBeforeRenderObservable.remove(st),_());var ut;e instanceof XAvatar?ut=ue4Position2Xverse(e.position):ut=ue4Position2Xverse(e);const ft=new Vector3((ut.x-at.x)*_e,it,(ut.z-at.z)*_e);it=it-rt,$<1?(nt=nt.add(ft),o.setPositionVector(nt.add(ot)),$+=et):(_(),st&&j.onBeforeRenderObservable.remove(st))})}})}roll(i,e,o,s){var c,d;this._observer&&((c=this._scene)==null||c.onBeforeRenderObservable.remove(this._observer)),e&&(o=o!=null?o:1,s=s!=null?s:1,this._observer=(d=this._scene)==null?void 0:d.onBeforeRenderObservable.add(()=>{i.rootNode.rotation.y+=o*.1*s,i.rootNode.rotation.y%=Math.PI*2}))}disposeObsever(){this._movingObserver&&this._scene.onBeforeRenderObservable.remove(this._movingObserver)}}class PoolObject{constructor(i,e,o,s=!0){ct(this,"data");ct(this,"nextFree");ct(this,"previousFree");ct(this,"free");this.data=i,this.nextFree=e,this.previousFree=o,this.free=s}dispose(){this.data&&this.data instanceof Mesh&&this.data.dispose(!0,!0),this.previousFree=null,this.nextFree=null,this.data=null}}class Pool{constructor(i,e,o,s,...c){ct(this,"objCreator");ct(this,"objReseter");ct(this,"_pool");ct(this,"lastFree");ct(this,"nextFree");ct(this,"capacity");this._pool=[],this.objCreator=i,this.objReseter=e;for(let d=0;d<s;d++)this.addNewObject(this.newPoolObject(...c));this.capacity=o}addNewObject(i){return this._pool.push(i),this.release(i),i}release(i){i.free=!0,i.nextFree=null,i.previousFree=this.lastFree,this.lastFree?this.lastFree.nextFree=i:this.nextFree=i,this.lastFree=i,this.objReseter(i)}getFree(...i){const e=this.nextFree?this.nextFree:this.addNewObject(this.newPoolObject(...i));return e.free=!1,this.nextFree=e.nextFree,this.nextFree||(this.lastFree=null),e}newPoolObject(...i){const e=this.objCreator(...i);return new PoolObject(e,this.nextFree,this.lastFree)}releaseAll(){this._pool.forEach(i=>this.release(i))}clean(i=0,...e){let o=this.nextFree;if(!o)return;let s=0;for(;o;)s+=1,o=o.nextFree;let c=!1;if(s>i&&this._pool.length>this.capacity&&(c=!0),c)for(o=this.nextFree;o;){o.free=!1,this.nextFree=o.nextFree;const d=this._pool.indexOf(o);this._pool.splice(d,1),this.nextFree||(this.lastFree=null),o==null||o.dispose(),o=this.nextFree}}}const texRootDir="https://app-asset-1258211750.file.myqcloud.com/1/textures/",pr=class{constructor(i){ct(this,"billboardMap",new Map);ct(this,"sceneManager");ct(this,"billboardPool");ct(this,"userBackGroundBlob",new Array);ct(this,"npcBackGroundBlob",new Array);ct(this,"tickObserver");ct(this,"tickInterval");ct(this,"_updateLoopObserver");this.sceneManager=i,this.billboardPool=new Pool(this.createBillboardAsset,this.resetBillboardAsset,0,60,this.sceneManager.Scene,!1),this.tickInterval=250;let e=0;this.tickObserver=this.sceneManager.Scene.onAfterRenderObservable.add(()=>{e+=1,e==this.tickInterval&&(this.tick(),e=0)}),this.launchBillboardStatusLoop()}tick(){this.billboardPool.clean(0,this.sceneManager.Scene,!1)}createBillboardAsset(i,e=!1){const o=MeshBuilder.CreatePlane("billboard-",{height:.001,width:.001,sideOrientation:Mesh.DOUBLESIDE},i);o.isPickable=!0,o.setEnabled(!1);const s=new DynamicTexture("billboard-tex-",{width:.001+1,height:.001+1},i,e,Texture.BILINEAR_SAMPLINGMODE);s.hasAlpha=!0;const c=new StandardMaterial("billboard-mat-",i);return c.diffuseTexture=s,c.emissiveColor=new Color3(.95,.95,.95),c.useAlphaFromDiffuseTexture=!0,o.material=c,o.billboardMode=Mesh.BILLBOARDMODE_Y,o.position.y=0,o}resetBillboardAsset(i){const e=i.data;return e.setEnabled(!1),e.isPickable=!1,i}async loadBackGroundTexToIDB(){pr.userBubbleUrls.forEach(o=>{this.sceneManager.urlTransformer(o).then(s=>{this.userBackGroundBlob.push(s)})}),pr.npcBubbleUrls.forEach(o=>{this.sceneManager.urlTransformer(o).then(s=>{this.npcBackGroundBlob.push(s)})})}addBillboardToMap(i,e){this.billboardMap.set(i,e)}addBillboard(i,e,o){let s=this.getBillboard(i);return s||(s=new XBillboard(this,e,o),this.addBillboardToMap(i,s)),s}generateStaticBillboard(i,{id:e="billboard",isUser:o,background:s,font:c="Arial",fontsize:d=40,fontcolor:_="#ffffff",fontstyle:b="600",linesize:k=16,linelimit:j,scale:$=1,width:_e=.01,height:et=.01,position:tt={x:0,y:0,z:0}}){const rt=this.addBillboard(e,!1,!0);rt.getMesh()==null&&rt.init(e,_e,et);let it;o!=null&&(it=o?pr.userBubbleUrls:pr.npcBubbleUrls),rt&&rt.getMesh()&&(rt.DEFAULT_CONFIGS={id:e,isUser:o,background:s,font:c,fontsize:d,fontcolor:_,fontstyle:b,linesize:k,linelimit:j,scale:$,width:_e,height:et,position:tt},rt.drawBillboard({imageList:s||it},{texts:i,font:c,fontsize:d,fontcolor:_,fontstyle:b,linesize:k,linelimit:j},{position:tt,scale:$}),e&&rt.setId(e),rt.setStatus(BillboardStatus.SHOW))}getBillboard(i){return this.billboardMap.get(i)}toggle(i,e){var o;(o=this.getBillboard(i))==null||o.setStatus(e?BillboardStatus.SHOW:BillboardStatus.HIDE)}removeBillboard(i){const e=this.getBillboard(i);e&&(e.setStatus(BillboardStatus.DISPOSE),this.billboardMap.delete(i))}launchBillboardStatusLoop(){this._updateLoopObserver=this.sceneManager.Scene.onBeforeRenderObservable.add(()=>{this.billboardMap.size<=0||this.billboardMap.forEach(i=>{i.stageChanged&&(i.status==BillboardStatus.SHOW?i.show():i.status==BillboardStatus.HIDE?i.hide():(i.hide(),i.dispose()),i.stageChanged=!1)})})}};let XBillboardManager=pr;ct(XBillboardManager,"alphaWidthMap",new Map),ct(XBillboardManager,"userBubbleUrls",[texRootDir+"bubble01.png",texRootDir+"bubble02.png",texRootDir+"bubble03.png"]),ct(XBillboardManager,"npcBubbleUrls",[texRootDir+"bubble01_npc.png",texRootDir+"bubble02_npc.png",texRootDir+"bubble03_npc.png"]);const log$10=new Logger$1("XAvatarBillboardComponent");class XAvatarBillboardComponent{constructor(i){ct(this,"_nickName","");ct(this,"_words","");ct(this,"_isNameVisible",!0);ct(this,"_isBubbleVisible",!0);ct(this,"_isGiftButtonsVisible",!1);ct(this,"withinVisualRange",!1);ct(this,"_bubble");ct(this,"_nameBoard");ct(this,"_giftButtons",new Map);ct(this,"_buttonTex",new Map);ct(this,"_nameLinesLimit",2);ct(this,"_nameLengthPerLine",16);ct(this,"_scene");ct(this,"_pickBbox",null);ct(this,"bbox");ct(this,"_height",.26);ct(this,"_attachmentObservers",new Map);ct(this,"attachToAvatar",(i,e,o=!1,s={x:0,y:0,z:0},c=!1,d)=>{const _=i.rootNode;if(this.bbox||i.getBbox(),e&&_){let b=this._attachmentObservers.get(e);if(b)if(c)this._scene.onBeforeRenderObservable.remove(b),this._attachmentObservers.delete(e);else return;const k=ue4Position2Xverse(s);o?(e.setParent(_),e.position=k):(b=this._scene.onBeforeRenderObservable.add(()=>{let j=0;d?(j=i.rootNode.rotation.y/Math.PI*180+90,i.rootNode.rotation.y&&(e.rotation.y=i.rootNode.rotation.y)):j=i.avatarManager.sceneManager.cameraComponent.getCameraPose().rotation.yaw,j||(j=0);const $=new Vector3(0,this._height,0);i.controller&&i.controller.activeAnimation()&&i.controller.activeAnimation().animatables[0]&&(this._height=$.y=(i.controller.activeAnimation().animatables[0].target.position.y*.01-.66)*i.scale),$.y<.07*i.scale&&($.y=0),e.position.x=_.position.x+k.x*Math.sin(j*Math.PI/180)+k.z*Math.cos(j*Math.PI/180),e.position.z=_.position.z+k.x*Math.cos(j*Math.PI/180)-k.z*Math.sin(j*Math.PI/180),e.position.y=_.position.y+this.bbox.maximum.y+k.y+$.y}),this._attachmentObservers.set(e,b))}else log$10.error("avatar or attachment not found!")});ct(this,"detachFromAvatar",(i,e,o=!1)=>{const s=this._attachmentObservers.get(e);s&&this._scene.onBeforeRenderObservable.remove(s),i.rootNode?(e.setEnabled(!1),e.parent=null,o&&e.dispose()):log$10.error("avatar not found!")});ct(this,"getBbox",(i,e={})=>{const{isConst:o=!1,changeWithAvatar:s=!1}=e;let{localCenter:c={x:0,y:0,z:75},width:d=1.32,height:_=1.5,depth:b=.44}=e;if(s){const k=i.scale;c={x:c.x*k,y:c.y*k,z:c.z*k},d*=k,_*=k,b*=k}if(i.rootNode){let k=new Vector3(0,0,0),j=new Vector3(0,0,0);if(o){const _e=ue4Position2Xverse(c);k=k.add(_e.add(new Vector3(-d/2,-_/2,-b/2))),j=j.add(_e.add(new Vector3(d/2,_/2,b/2)))}else if(k=k.add(new Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)),j=j.add(new Vector3(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY)),i.isRender){i.rootNode.getChildMeshes().forEach(tt=>{const rt=tt.getBoundingInfo().boundingBox.minimum,it=tt.getBoundingInfo().boundingBox.maximum;k.x=Math.min(k.x,rt.x),j.x=Math.max(j.x,it.x),k.y=Math.min(k.y,rt.y),j.y=Math.max(j.y,it.y),k.z=Math.min(k.z,rt.z),j.z=Math.max(j.z,it.z)});const _e=j.x-k.x,et=j.z-k.z;k.x-=i.scale*_e/2,j.x+=i.scale*_e/2,j.y*=i.scale,k.z-=i.scale*et/2,j.z+=i.scale*et/2}else{const _e=i.avatarManager.getMainAvatar();_e&&_e.bbComponent.bbox&&(k.x=_e.bbComponent.bbox.minimum.x,j.x=_e.bbComponent.bbox.maximum.x,k.y=_e.bbComponent.bbox.minimum.y,j.y=_e.bbComponent.bbox.maximum.y,k.z=_e.bbComponent.bbox.minimum.z,j.z=_e.bbComponent.bbox.maximum.z)}const $=i.rootNode.computeWorldMatrix(!0);this.bbox?this.bbox.reConstruct(k,j,$):this.bbox=new BoundingBox(k,j,$),this._pickBbox==null}else log$10.error("avatar not found!")});this._scene=i}get isNameVisible(){return this._isNameVisible}get isBubbleVisible(){return this._isBubbleVisible}get isGiftButtonsVisible(){return this._isGiftButtonsVisible}get words(){return this._words}get nickName(){return this._nickName}get giftButtons(){return this._giftButtons}get bubble(){return this._bubble}get nameBoard(){return this._nameBoard}setNicknameStatus(i){var e;if(this.nameBoard&&this.nameBoard.setStatus(i),i==BillboardStatus.DISPOSE){const o=(e=this.nameBoard)==null?void 0:e.getMesh();if(o){const s=this._attachmentObservers.get(o);s&&(this._scene.onBeforeRenderObservable.remove(s),this._attachmentObservers.delete(o))}}}setBubbleStatus(i){var e;if(this.bubble&&this.bubble.setStatus(i),i==BillboardStatus.DISPOSE){const o=(e=this.bubble)==null?void 0:e.getMesh();if(o){const s=this._attachmentObservers.get(o);s&&(this._scene.onBeforeRenderObservable.remove(s),this._attachmentObservers.delete(o))}}}setButtonsStatus(i){this.giftButtons&&this.giftButtons.size!=0&&this.giftButtons.forEach(e=>{if(e.setStatus(i),i==BillboardStatus.DISPOSE&&e.getMesh()){const o=e.getMesh();if(o){const s=this._attachmentObservers.get(o);s&&(this._scene.onBeforeRenderObservable.remove(s),this._attachmentObservers.delete(o))}}})}setGiftButtonsVisible(i){this.setButtonsStatus(i?BillboardStatus.SHOW:BillboardStatus.DISPOSE)}dispose(i){this._attachmentObservers.forEach(e=>{this._scene.onBeforeRenderObservable.remove(e)}),this._attachmentObservers.clear(),this.updateBillboardStatus(i,BillboardStatus.DISPOSE),this._buttonTex.clear(),this._pickBbox&&(i.avatarManager.bboxMeshPool.release(this._pickBbox),this._pickBbox=null)}updateBillboardStatus(i,e){this.bbox||i.getBbox(),i.isRender?(i.setBubbleStatus(e),i.setButtonsStatus(e),i.setNicknameStatus(e)):(i.setBubbleStatus(BillboardStatus.DISPOSE),i.setButtonsStatus(BillboardStatus.DISPOSE),i.enableNickname?i.setNicknameStatus(e):i.setNicknameStatus(BillboardStatus.DISPOSE))}disposeBillBoard(i){this._attachmentObservers.forEach(e=>{this._scene.onBeforeRenderObservable.remove(e)}),this._attachmentObservers.clear(),this.updateBillboardStatus(i,BillboardStatus.DISPOSE),this._buttonTex.clear(),this._pickBbox&&(i.avatarManager.bboxMeshPool.release(this._pickBbox),this._pickBbox=null)}setPickBoxScale(i){this._pickBbox&&this._pickBbox.data&&(this._pickBbox.data.scaling=new Vector3(i,i,i))}setIsPickable(i,e){i.rootNode&&i.rootNode.getChildMeshes().forEach(o=>{o.isPickable=e}),this._pickBbox&&this._pickBbox.data&&(this._pickBbox.data.isPickable=e)}initNameboard(i,e=1){this._nameBoard==null&&(this._nameBoard=i.avatarManager.sceneManager.billboardComponent.addBillboard("name-"+i.id,!1,!0)),this._nameBoard.init("nickname",e/300,e/300)}initBubble(i,e=1){this._bubble==null&&(this._bubble=i.avatarManager.sceneManager.billboardComponent.addBillboard("bubble-"+i.id,!1,!0)),i.isRender&&this._bubble.init("bubble",e/250,e/250)}say(i,e=this._words,{id:o,isUser:s,background:c,font:d="Arial",fontsize:_=38,fontcolor:b="#ffffff",fontstyle:k="bold",linesize:j=22,linelimit:$,offsets:_e={x:0,y:0,z:40},scale:et,compensationZ:tt=11.2,reregistAnyway:rt=!0}){(!this.bubble||this.bubble.getMesh()==null)&&i.initBubble(),this._words=e;let it;s!=null&&(it=s?XBillboardManager.userBubbleUrls:XBillboardManager.npcBubbleUrls),this._bubble&&(this._bubble.DEFAULT_CONFIGS={id:o,isUser:s,background:c||it,font:d,fontsize:_,fontcolor:b,fontstyle:k,linesize:j,linelimit:$,offsets:_e,scale:et,compensationZ:tt,reregistAnyway:rt},this._bubble.getMesh()&&(i.avatarManager.enableBubble?(this._bubble.drawBillboard({imageList:c||it},{texts:this._words,font:d,fontsize:_,fontcolor:b,fontstyle:k,linesize:j},{offsets:_e,scale:et,compensationZ:tt}),this.attachToAvatar(i,this._bubble.getMesh(),!1,this._bubble.offsets,rt)):this.setBubbleStatus(BillboardStatus.DISPOSE),o&&this._bubble.setId(o))),this.setButtonsStatus(BillboardStatus.DISPOSE)}silent(){this.setBubbleStatus(BillboardStatus.DISPOSE),this._words=""}setNickName(i,e,{id:o,isUser:s,background:c,font:d="Arial",fontsize:_=40,fontcolor:b="#ffffff",fontstyle:k="bold",linesize:j=22,linelimit:$,offsets:_e={x:0,y:0,z:15},scale:et,compensationZ:tt=0,reregistAnyway:rt=!1}){this._nickName=e,(!this.nameBoard||this.nameBoard.getMesh()==null)&&this.initNameboard(i),this._nameBoard&&this._nameBoard.getMesh()&&(this._nameBoard.DEFAULT_CONFIGS={id:o,isUser:s,background:c,font:d,fontsize:_,fontcolor:b,fontstyle:k,linesize:j,linelimit:$,offsets:_e,scale:et,compensationZ:tt,reregistAnyway:rt},i.avatarManager.enableNickname?(this._nameBoard.drawBillboard({},{texts:this._nickName,font:d,fontsize:_,fontcolor:b,fontstyle:k,linesize:j,linelimit:$},{offsets:_e,scale:et,compensationZ:0}),this.attachToAvatar(i,this._nameBoard.getMesh(),!1,this._nameBoard.offsets,rt)):this.setNicknameStatus(BillboardStatus.DISPOSE),o&&this._nameBoard.setId(o))}generateButtons(i,e=null,o,s=85){if(e&&(this._buttonTex=e,this.clearButtons()),this._buttonTex.size==0)return;let c=(this._buttonTex.size-1)/2;this._buttonTex.forEach((d,_)=>{let b=this._giftButtons.get(_);b||(b=i.avatarManager.sceneManager.billboardComponent.addBillboard("button-"+_+i.id,!0,!1),b.init(_,o/240,o/240));const k={x:o*c*70,y:0,z:o*(s-20*(c*c))};b.drawBillboard({imageList:[d]},{},{offsets:k,scale:o}),this.attachToAvatar(i,b.getMesh(),!1,b.offsets,!0),this._giftButtons.set(_,b),c-=1}),this.setBubbleStatus(BillboardStatus.DISPOSE)}clearButtons(){this._giftButtons.forEach(i=>{i.dispose()}),this._giftButtons.clear()}createPickBoundingbox(i,e){const o=e.extendSize.x*2,s=e.extendSize.y*2,c=e.extendSize.z*2,d=this._scene,_=Math.max(o,c),b=i.avatarManager.bboxMeshPool.getFree(d,_,s,_),k=b.data;return k&&(k.position=e.centerWorld,k.setEnabled(!1),k.isPickable=!0,k.xtype=EMeshType.XAvatar,k.xid=i.id),b}}const log$$=new Logger$1("Avatar"),castRayOffsetY=.01,castRayTeleportationOffset=10;var EDressType=(a=>(a.BODY="body",a.CLOTHES="clothes",a.HEAD="head",a.HAIR="hair",a.PANTS="pants",a.SUIT="suit",a.SHOES="shoes",a.PENDANT="pendant",a))(EDressType||{});class XAvatar{constructor({id:i,avatarType:e,priority:o,avatarManager:s,assets:c,status:d}){ct(this,"id","-1");ct(this,"priority",0);ct(this,"isRender",!1);ct(this,"distLevel",0);ct(this,"isInLoadingList",!1);ct(this,"isHide",!1);ct(this,"component");ct(this,"controller");ct(this,"stateMachine");ct(this,"bbComponent");ct(this,"_avatarType");ct(this,"clothesList",[]);ct(this,"isSelected",!1);ct(this,"pendingLod",!1);ct(this,"_previousReceivedPosition",new Vector3(0,1e4,0));ct(this,"_avatarPosition");ct(this,"_avatarRotation");ct(this,"_avatarScale");ct(this,"rootNode");ct(this,"distToCam",1e11);ct(this,"enableNickname",!0);ct(this,"distance",1e11);ct(this,"isCulling",!1);ct(this,"reslevel",0);ct(this,"isInLoadingQueue",!1);ct(this,"_isRayCastEnable");ct(this,"_scene");ct(this,"_avatarManager");ct(this,"_transparent",0);ct(this,"hide",()=>(this.isHide=!0,this._hide(),!this.isRender));ct(this,"_show",()=>{var i;this.isHide||(this.setIsPickable(!0),this.bbComponent._attachmentObservers.forEach((e,o)=>{o.setEnabled(!0)}),this.priority==0&&(this.rootNode.setEnabled(!0),this.isRender=!0,this.avatarManager._updateBillboardStatus(this,BillboardStatus.SHOW),this.component.accessories.forEach(e=>{e.rootComponent.setEnabled(!0)}),(i=this.controller)==null||i.playAnimation(this.controller.onPlay,this.controller.loop)),this.component.accessories.forEach(e=>{e.rootComponent.setEnabled(!0)}))});ct(this,"show",()=>(this.isHide=!1,this._show(),!!this.isRender));ct(this,"setAnimations",i=>{this.controller.animations=i});ct(this,"attachToAvatar",(i,e=!1,o={x:0,y:0,z:0},s=!1,c,d)=>this.bbComponent.attachToAvatar(this,i,e,o,s,d));ct(this,"detachFromAvatar",(i,e=!1)=>this.bbComponent.detachFromAvatar(this,i,e));ct(this,"getBbox",(i={})=>this.bbComponent.getBbox(this,i));this.id=i,this._avatarManager=s,this._scene=this.avatarManager.scene,this.clothesList=c,this._avatarType=e,this.priority=o||0,this.controller=new XAnimationController(this),this.component=new XAvatarComopnent,this.stateMachine=new XStateMachine(this._scene),this.bbComponent=new XAvatarBillboardComponent(this._scene),this.rootNode=new TransformNode(i,this._avatarManager.scene),this._avatarScale=d.avatarScale==null?1:d.avatarScale,this._avatarRotation=d.avatarRotation==null?{pitch:0,yaw:0,roll:0}:d.avatarRotation,this._avatarPosition=d.avatarPosition==null?{x:0,y:0,z:0}:d.avatarPosition,this._isRayCastEnable=avatarSetting.isRayCastEnable,this.setPosition(this._avatarPosition,!0),this.setRotation(this._avatarRotation),this.setScale(this.scale),this._isRayCastEnable=avatarSetting.isRayCastEnable,this._scene.registerBeforeRender(()=>{this.tick()})}tick(){this.cullingTick()}cullingTick(){var i;this.isCulling&&((i=this.rootNode)==null||i.getChildMeshes().forEach(e=>{this.distToCam<50?e.visibility=0:e.visibility=this._transparent}))}setTransParentThresh(i){this._transparent=i}get isNameVisible(){return this.bbComponent.isNameVisible}get isBubbleVisible(){return this.bbComponent.isBubbleVisible}get isGiftButtonsVisible(){return this.bbComponent.isGiftButtonsVisible}get words(){return this.bbComponent.words}get nickName(){return this.bbComponent.nickName}get giftButtons(){return this.bbComponent.giftButtons}get bubble(){return this.bbComponent.bubble}get nameBoard(){return this.bbComponent.nameBoard}get avatarManager(){return this._avatarManager}set withinVisibleRange(i){this.bbComponent.withinVisualRange=i}setNicknameStatus(i){return this.bbComponent.setNicknameStatus(i)}setBubbleStatus(i){return this.bbComponent.setBubbleStatus(i)}setButtonsStatus(i){return this.bbComponent.setBubbleStatus(i)}setGiftButtonsVisible(i){return this.bbComponent.setGiftButtonsVisible(i)}get avatarType(){return this._avatarType}attachBody(i){return this.component.addBodyComp(this,i)}attachDecoration(i){return this.component.addClothesComp(this,i)}detachDecoration(i){return this.component.clearClothesComp(i)}detachDecorationAll(){return this.component.clearAllClothesComps()}get skeleton(){return this.component.skeleton}get position(){return this._avatarPosition}get rotation(){return this._avatarRotation}get scale(){return this._avatarScale}_hide_culling(){this.bbComponent.updateBillboardStatus(this,BillboardStatus.HIDE),this.isCulling=!0}_show_culling(){this.isCulling&&(this.rootNode&&this.rootNode.getChildMeshes().forEach(i=>{i.visibility=1}),this.bbComponent.updateBillboardStatus(this,BillboardStatus.SHOW),this.isCulling=!1)}_hide(){!this.isHide||(this.setIsPickable(!1),this.bbComponent._attachmentObservers.forEach((i,e)=>{e.setEnabled(!1)}),this.priority==0?(this.rootNode.setEnabled(!1),this.isRender=!1,this.bbComponent.updateBillboardStatus(this,BillboardStatus.HIDE),this.component.accessories.forEach(i=>{i.rootComponent.setEnabled(!1)})):this.isRender&&(this.avatarManager.currentLODUsers[this.distLevel]--,this.removeAvatarFromScene()),this.component.accessories.forEach(i=>{i.rootComponent.setEnabled(!1)}))}rotate(i,e,o){return this.stateMachine.roll(this,i,e,o)}set isRayCastEnable(i){this._isRayCastEnable=i}get isRayCastEnable(){return this._isRayCastEnable}getAvatarId(){return this.id}getAvaliableAnimations(){const i=avatarLoader.avaliableAnimation.get(this.avatarType);return i||[]}setPosition(i,e=!1){if(this._avatarPosition=i,this.rootNode){const o=ue4Position2Xverse(this._avatarPosition);let s=!1;this.avatarManager.getMainAvatar()&&(this.id!=this.avatarManager.getMainAvatar().id||(Math.abs(o.y-this._previousReceivedPosition.y)>castRayOffsetY&&(s=!0),o.subtract(this._previousReceivedPosition).length()>castRayTeleportationOffset&&(s=!0))),this._isRayCastEnable?s||e?this._castRay(i).then(c=>{this.rootNode.position=o,this.rootNode.position.y-=c}).catch(c=>{Promise.reject(c)}):(this.rootNode.position.x=o.x,this.rootNode.position.z=o.z):this.rootNode.position=o,this._previousReceivedPosition=o.clone()}return Promise.resolve(i)}setRotation(i){if(this._avatarRotation=i,this.rootNode){const e={pitch:i.pitch,yaw:i.yaw+180,roll:i.roll},o=ue4Rotation2Xverse(e);this.rootNode.rotation=o}}setAvatarVisible(i){this.rootNode&&(this.rootNode.setEnabled(i),this.rootNode.getChildMeshes().forEach(e=>{e.setEnabled(i)}))}setScale(i){this._avatarScale=i,this.rootNode&&(this.rootNode.scaling=new Vector3(i,i,i)),this.bbComponent.bbox&&this.getBbox()}_removeAvatarFromScene(){var i,e;this.isRender=!1,(i=this.controller)==null||i.detachAnimation(),this.component.dispose(this),(e=this.avatarManager.sceneManager)==null||e.lightComponent.removeShadow(this),this.component.accessories.forEach(o=>{o.rootComponent.setEnabled(!1)})}removeAvatarFromScene(){this._removeAvatarFromScene(),this._disposeBillBoard()}_disposeBillBoard(){this.bbComponent.disposeBillBoard(this)}addComponent(i,e,o,s){return e==="pendant"?this.component.attachPendant(this,i):this.component.changeClothesComp(this,i,e,o,s)}removeComponent(i,e){if(i==="pendant")e?this.component.detachPendant(e):this.component.accessories.forEach((o,s)=>{this.component.detachPendant(s)});else{const o=this.component.resourceIdList.find(s=>s.type==i);o&&(this.detachDecoration(o),this.clothesList=this.clothesList.filter(s=>s.type!=i))}}getComponentByType(i,e){if(i==="pendant")if(e){const o=this.component.accessories.get(e);return o||[]}else return Array.from(this.component.accessories).map(o=>o[1]);else return this.component.resourceIdList.find(o=>o.type==i)}_castRay(i){return new Promise((e,o)=>{var et;const s=ue4Position2Xverse(i),c=new Vector3(0,-1,0),d=1.5*this.scale,_=100*d,b=d,k=new Vector3(s.x,s.y+b,+s.z),j=new Ray(k,c,_),$=(et=this.avatarManager.sceneManager)==null?void 0:et.getGround(i);if(!$||$.length<=0)return log$$.warn(`\u89D2\u8272 id= ${this.id} \u627E\u4E0D\u5230\u5730\u9762\uFF0C\u5F53\u524D\u9AD8\u5EA6\u4E3A\u4E0B\u53D1\u9AD8\u5EA6`),e(0);let _e=j.intersectsMeshes($);if(_e.length>0)return e(_e[0].distance-b);if(c.y=1,_e=j.intersectsMeshes($),_e.length>0)return e(-(_e[0].distance-b))})}setPickBoxScale(i){return this.bbComponent.setPickBoxScale(i)}setIsPickable(i){return this.bbComponent.setIsPickable(this,i)}createPickBoundingbox(i){return this.bbComponent.createPickBoundingbox(this,i)}scaleBbox(i){this.bbComponent.bbox&&this.bbComponent.bbox.scale(i)}rotateTo(i,e,o){return this.stateMachine.rotateTo(this,i,e,o)}faceTo(i,e){return this.stateMachine.lookAt(this,i,e)}removeObserver(){this.stateMachine.disposeObsever()}moveHermite(i,e,o,s,c,d){return this.stateMachine.moveToHermite(this,i,e,o,s,c,d)}moveCardinal(i,e,o,s,c,d,_=!1){return this.stateMachine.moveToCardinal(this,i,e,o,s,c,d,_)}move(i,e,o,s,c,d=!1){return this.stateMachine.moveTo(this,i,e,o,s,c,d)}initNameboard(i=1){return this.bbComponent.initNameboard(this,i)}initBubble(i=1){return this.bbComponent.initBubble(this,i)}say(i,{id:e,isUser:o,background:s,font:c="Arial",fontsize:d=38,fontcolor:_="#ffffff",fontstyle:b="bold",linesize:k=22,linelimit:j,offsets:$={x:0,y:0,z:40},scale:_e=this._avatarScale,compensationZ:et=11.2,reregistAnyway:tt=!0}){return this.bbComponent.say(this,i,{id:e,isUser:o,background:s,font:c,fontsize:d,fontcolor:_,fontstyle:b,linesize:k,linelimit:j,offsets:$,scale:_e,compensationZ:et,reregistAnyway:tt})}silent(){return this.bbComponent.silent()}setNickName(i,{id:e,isUser:o,background:s,font:c="Arial",fontsize:d=40,fontcolor:_="#ffffff",fontstyle:b="bold",linesize:k=22,linelimit:j,offsets:$={x:0,y:0,z:15},scale:_e=this._avatarScale,compensationZ:et=0,reregistAnyway:tt=!1}){return this.bbComponent.setNickName(this,i,{id:e,isUser:o,background:s,font:c,fontsize:d,fontcolor:_,fontstyle:b,linesize:k,linelimit:j,offsets:$,scale:_e,compensationZ:et,reregistAnyway:tt})}generateButtons(i=null,e=this._avatarScale,o=85){return this.bbComponent.generateButtons(this,i,e,o)}clearButtons(){return this.bbComponent.clearButtons()}attachExtraProp(i,e,o,s){return this.component.addDecoComp(this,i,e,o,s)}showExtra(i){return this.component.showExtra(i)}hideExtra(i){return this.component.hideExtra(i)}disposeExtra(){return this.component.disposeExtra()}getSkeletonPositionByName(i){var e;if(this.skeleton){const o=this.skeleton.bones.find(s=>s.name.replace("Clone of ","")==i);if(o&&o.getTransformNode()&&((e=o.getTransformNode())==null?void 0:e.position)){const s=o.getTransformNode().position;return xversePosition2Ue4({x:s.x,y:s.y,z:s.z})}}}shootTo(i,e,o=2,s=10,c={x:0,y:0,z:150}){return this.stateMachine.sendObjectTo(this,i,e,o,s,c)}}const log$_=new Logger$1("AvatarManager");var EAvatarRelationRank=(a=>(a[a.Self=0]="Self",a[a.Npc=1]="Npc",a[a.Friend=2]="Friend",a[a.Stranger=3]="Stranger",a[a.Robot=4]="Robot",a[a.Unknown=5]="Unknown",a))(EAvatarRelationRank||{});class XAvatarManager{constructor(i){ct(this,"characterMap",new Map);ct(this,"curAnimList",[]);ct(this,"extraComps",new Map);ct(this,"_mainUser");ct(this,"_scene");ct(this,"_sceneManager");ct(this,"_lodSettings");ct(this,"maxBillBoardDist",0);ct(this,"maxAvatarNum",0);ct(this,"currentLODUsers",[]);ct(this,"bboxMeshPool");ct(this,"_distLevels",[]);ct(this,"_maxLODUsers",[]);ct(this,"_cullingDistance",0);ct(this,"_maxDistRange");ct(this,"_delayTime",100);ct(this,"_queueLength",-1);ct(this,"_queue",[]);ct(this,"_processList",[]);ct(this,"_process");ct(this,"_updateLoopObserver");ct(this,"_enableNickname",!0);ct(this,"_enableBubble",!0);ct(this,"_tickObserver");ct(this,"_tickInterval");ct(this,"_defaultAnims");ct(this,"_tickDispose",0);ct(this,"_disposeTime",10);ct(this,"avatarLoader",avatarLoader);ct(this,"onThingsLoading",!1);ct(this,"compMap",new Map);this._scene=i.mainScene,this._sceneManager=i,this.initAvatarMap(),this._initSettings(),this._maxDistRange=this._distLevels[this._distLevels.length-1],this.bboxMeshPool=new Pool(this.createBboxAsset,this.resetBboxAsset,0,0,this._sceneManager.Scene,0,0,0),this._tickInterval=250;let e=0;this._tickObserver=this._scene.onAfterRenderObservable.add(()=>{e+=1,e==this._tickInterval&&(this.tick(),e=0)})}tick(){this.bboxMeshPool.clean(0)}createBboxAsset(i,e,o,s){return MeshBuilder.CreateBox("avatarBbox",{width:e,height:o,depth:s},i)}resetBboxAsset(i){const e=i.data;return e.setEnabled(!1),e.isPickable=!1,i}_initSettings(){this._defaultAnims=avatarSetting.defaultIdle,this._lodSettings=avatarSetting.lod,this._distLevels=avatarSetting.lod.map(i=>i.dist),this._maxLODUsers=avatarSetting.lod.map(i=>i.quota),this.currentLODUsers=new Array(this._distLevels.length).fill(0),this.maxAvatarNum=avatarSetting.maxAvatarNum,this.maxBillBoardDist=avatarSetting.maxBillBoardDist,this._cullingDistance=avatarSetting.cullingDistance}maxRenderNum(){let i=0;return this._maxLODUsers.forEach(e=>{i+=e}),i}curRenderNum(){let i=0;return this.currentLODUsers.forEach(e=>{i+=e}),i}setLoDLevels(i){this._distLevels=i}set cullingDistance(i){this._cullingDistance=i}get cullingDistance(){return this._cullingDistance}getLoDLevels(){return this._distLevels}setLodUserLimits(i,e){this._maxLODUsers.length>i&&(this._maxLODUsers[i]=e)}setLodDist(i,e){this._distLevels[i]=e}setMaxDistRange(i){this._maxDistRange=i,this._distLevels[this._distLevels.length-1]=i}get scene(){return this._scene}setMainAvatar(i){var e;this._mainUser=(e=this.characterMap.get(0))==null?void 0:e.get(i)}getMainAvatar(){return this._mainUser}get enableNickname(){return this._enableNickname}get enableBubble(){return this._enableBubble}enableAllNickname(i){this._enableNickname=i,this.characterMap.forEach(e=>{e.forEach(o=>{i?o.nameBoard&&o.nickName.length>0&&o.isRender&&o.setNickName(o.nickName,o.nameBoard.DEFAULT_CONFIGS):o.setNicknameStatus(BillboardStatus.DISPOSE)})})}enableAllBubbles(i){this._enableBubble=i,this.characterMap.forEach(e=>{e.forEach(o=>{i?o.bubble&&o.words.length>0&&o.isRender&&o.say(o.words,o.bubble.DEFAULT_CONFIGS):o.setBubbleStatus(BillboardStatus.DISPOSE)})})}getAvatarById(i){let e;return this.characterMap.forEach((o,s)=>{o.get(i)&&(e=o.get(i))}),e}getAvatarNums(){let i=0;return this.characterMap.forEach((e,o)=>{i+=e.size}),i}registerAvatar(i){this.characterMap.get(i.priority).set(i.id,i)}unregisterAvatar(i){this.characterMap.get(i.priority).delete(i.id)}initAvatarMap(){this.characterMap.set(0,new Map),this.characterMap.set(1,new Map),this.characterMap.set(2,new Map),this.characterMap.set(3,new Map),this.characterMap.set(4,new Map),this.characterMap.set(5,new Map)}loadAvatar({id:i,avatarType:e,priority:o,avatarManager:s,assets:c,status:d}){return new Promise((_,b)=>{if(this.getAvatarById(i))return b(new DuplicateAvatarIDError(`[Engine] cannot init avatar with the same id = ${i}`));if(this.getAvatarNums()>this.maxAvatarNum)return b(new ExceedMaxAvatarNumError(`[Engine] \u8D85\u51FA\u6700\u5927\u89D2\u8272\u9650\u5236 ${this.maxAvatarNum}`));const k=new XAvatar({id:i,avatarType:e,priority:o,avatarManager:s,assets:c,status:d});if(this.registerAvatar(k),o==0)this.setMainAvatar(k.id),this.addAvatarToScene(k,0).then(j=>(log$_.debug(`[Engine] avatar ${k.id} has been added to scene`),j?(this._updateBillboardStatus(j,BillboardStatus.SHOW),setTimeout(()=>{this.launchProcessLoadingLoop()},this._delayTime),_(j)):(k.removeAvatarFromScene(),b(new AvatarAssetLoadingError)))).catch(j=>(k.removeAvatarFromScene(),b(new AvatarAssetLoadingError(j))));else return _(k)})}deleteAvatar(i){return i.isRender?(i.removeAvatarFromScene(),this.currentLODUsers[i.distLevel]--):i.bbComponent.disposeBillBoard(i),this._processList=this._processList.filter(e=>e.id!==i.id),this.unregisterAvatar(i),i.rootNode&&(i.rootNode.dispose(),i.rootNode=void 0),i.bbComponent.bbox&&i.bbComponent.bbox.dispose(),i.removeObserver(),i}_checkLODLevel(i){if(i<this._distLevels[0])return 0;for(let e=1;e<this._distLevels.length;++e)if(i>=this._distLevels[e-1]&&i<this._distLevels[e])return e;return this._distLevels.length-1}get sceneManager(){return this._sceneManager}launchProcessLoadingLoop(){this._updateAvatarStatus()}stopProcessLoadingLoop(){var i;this._updateLoopObserver&&((i=this._scene)==null||i.onBeforeRenderObservable.remove(this._updateLoopObserver)),this._queueLength=0,this._clear(this.compMap),this._process&&(this._process.isInLoadingList=!1,this._process.removeAvatarFromScene(),this._process=void 0),this._processList.forEach(e=>{e.isInLoadingList=!1}),this._processList=[]}_distToMain(i){var c;const e=(c=this._mainUser)==null?void 0:c.position,o=i.position,s=this.sceneManager.cameraComponent.MainCamera.position;if(o&&s){const d=this.sceneManager.cameraComponent.MainCamera.getFrontPosition(1).subtract(s),_=i.rootNode.position.subtract(s),b=new Vector3(d.x,0,d.z).normalize(),k=new Vector3(_.x,0,_.z).normalize();let j=1;if(b&&k){const $=b.multiply(k);j=Math.acos($.x+$.y+$.z)<this.sceneManager.cameraComponent.getCameraHorizonFov()*.6?1:1e11}return calcDistance3D(e||s,o)*j}else return log$_.warn("user position or camera position is not correct!"),1e11}_distToCamera(i){var s;const e=(s=this._sceneManager)==null?void 0:s.cameraComponent.getCameraPose().position,o=i.position;return o&&e?calcDistance3D(e,o):(log$_.warn("user position or camera position is not correct!"),1e11)}showAll(i){this.characterMap.forEach((e,o)=>{i&&o==0&&e.forEach((s,c)=>{s.show()}),o!=0&&e.forEach((s,c)=>{s.show()})})}hideAll(i){this.characterMap.forEach((e,o)=>{i&&o==0&&e.forEach((s,c)=>{s.hide()}),o!=0&&e.forEach((s,c)=>{s.hide()})})}_assemblyAvatar(i,e){var s,c;const o=i.get(avatarSetting.body);if(o&&!e.attachBody(o)){e.isInLoadingList=!1,this._clear(i);return}for(const d of i)if(d[0]!=avatarSetting.body&&d[0]!=avatarSetting.animations&&!e.attachDecoration(d[1])){e.isInLoadingList=!1,e.removeAvatarFromScene(),this._clear(i);return}e.isRender=!0,(s=e.controller)==null||s.playAnimation(e.controller.onPlay,e.controller.loop),(c=e.controller)==null||c.onPlayObservable.addOnce(()=>{var d,_;if(!this.getAvatarById(e.id)){e.isInLoadingList=!1,e.removeAvatarFromScene(),this.currentLODUsers[e.distLevel]--;return}if(this.getAvatarById(e.id).rootNode.getChildMeshes().length<i.size){log$_.error(`this avatar does not have complete components, render failed. current list ${(d=this.getAvatarById(e.id))==null?void 0:d.clothesList},avatar: ${e.id},${e.nickName}`),e.isInLoadingList=!1,e.removeAvatarFromScene(),this.currentLODUsers[e.distLevel]--;return}e.setIsPickable(!0),e.isInLoadingList=!1,e.setAvatarVisible(!0),(_=this._sceneManager)==null||_.lightComponent.setShadow(e),e.getBbox(),e.nameBoard&&e.nickName.length>0&&this._enableNickname&&e.setNickName(e.nickName,e.nameBoard.DEFAULT_CONFIGS),e.component.accessories.forEach(b=>{b.attachTo(e),b.rootComponent.setEnabled(!0)}),e.bubble&&e.words.length>0&&e.say(e.words,e.bubble.DEFAULT_CONFIGS),log$_.debug(`[Engine] avatar ${e.id} has been added to scene, current number of users : ${this.currentLODUsers}`)})}_disposeUnusedAssets(){this._tickDispose++,(this._tickDispose>this._disposeTime||avatarLoader.containers.size>100)&&(avatarLoader.disposeContainer(),this._tickDispose=0)}_addResourcesToList(i,e){return i.clothesList.forEach(o=>{o.lod=e,this._queue.push(o)}),this._queue.push({type:avatarSetting.animations,id:this._defaultAnims}),this._queue.push({type:avatarSetting.body,id:i.avatarType,lod:e}),!0}_updateBillboardStatus(i,e){i.bbComponent.updateBillboardStatus(i,e)}_processLayer(i){const e=this.characterMap.get(i),o=[];for(e==null||e.forEach(s=>{s.distToCam=this._distToCamera(s);const c=s.distToCam<this._cullingDistance;if(s.isRender&&(!s.isHide&&c?s._hide_culling():s._show_culling()),s.priority!=0){s.distance=this._distToMain(s);let d=BillboardStatus.SHOW;s.distance<this._maxDistRange&&(c?d=BillboardStatus.HIDE:s._show_culling(),this._updateBillboardStatus(s,d)),s.isHide||(s.isInLoadingList?this.currentLODUsers[s.distLevel]++:o.push(s))}}),o.sort((s,c)=>c.distance-s.distance);o.length>0&&this.curRenderNum()<this.maxRenderNum();){const s=o.pop();let c=this._checkLODLevel(s.distance),d=!1;for(let _=0;_<this._maxLODUsers.length;++_)if(this.currentLODUsers[_]<this._maxLODUsers[_]){c=_,d=!0;break}if(!d||s.distance>this._maxDistRange){if(s.isRender){s._removeAvatarFromScene();let _=BillboardStatus.HIDE;s.distance<this._maxDistRange&&(_=BillboardStatus.SHOW),this._updateBillboardStatus(s,_)}break}c!=s.distLevel?(s.isRender&&(s.pendingLod=!0),s.distLevel=c,this._processList.push(s),s.isInLoadingList=!0):s.isRender||(this._processList.push(s),s.isInLoadingList=!0),this.currentLODUsers[c]++}return this.curRenderNum()>=this.maxRenderNum()&&o.forEach(s=>{if(s.isRender){s._removeAvatarFromScene();let c=BillboardStatus.HIDE;s.distance<this._maxDistRange&&(c=BillboardStatus.SHOW),this._updateBillboardStatus(s,c)}}),this.curRenderNum()<this.maxRenderNum()}_updateAvatar(){this.currentLODUsers=[0,0,0];const i=[5,4,3,2,1,0];for(;i.length>0;){const e=i.pop();if(!this._processLayer(e)){i.forEach(s=>{var c;(c=this.characterMap.get(s))==null||c.forEach(d=>{d.distance=this._distToMain(d);let _=BillboardStatus.HIDE;d.distToCam<this._maxDistRange&&(_=BillboardStatus.SHOW,d.isRender&&d._removeAvatarFromScene()),this._updateBillboardStatus(d,_)})});break}}}_updateAvatarStatus(){this._updateLoopObserver=this.scene.onBeforeRenderObservable.add(()=>{var i;if(!(this.getAvatarNums()<=0)){if(!this._process&&this._processList.length==0&&this._updateAvatar(),!this._process&&this._processList.length>0){const e=this._processList.shift();e!=this._process&&!e.isCulling?this._addResourcesToList(e,e.distLevel)?(this._process=e,this._queueLength=this._queue.length):(this._process=void 0,this._queue=[],e.isInLoadingList=!1):e.isInLoadingList=!1}if(this.compMap.size===this._queueLength&&this._process){this._process.pendingLod&&(this._process.pendingLod=!1,this._process._removeAvatarFromScene());const e=Date.now();this._assemblyAvatar(this.compMap,this._process),(i=this._sceneManager)==null||i.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now()-e),this._updateBillboardStatus(this._process,BillboardStatus.SHOW),this.compMap.clear(),this._queue=[],this._process.isInLoadingList=!1,this._process=void 0}this._disposeUnusedAssets(),this._loadResByList(this.compMap)}})}_clear(i){i.forEach((e,o)=>{o==avatarSetting.body&&(e.root._parentContainer?e.root._parentContainer.xReferenceCount--:e.root.getChildMeshes().forEach(s=>{s.dispose()})),(o==avatarSetting.clothes||o==avatarSetting.hair||o==avatarSetting.head||o==avatarSetting.pants||o==avatarSetting.head||o==avatarSetting.suit)&&(e.root._parentContainer?e.root._parentContainer.xReferenceCount--:e.root.dispose())})}_loadResByList(i){let e=0;const o=5;if(!this._process){i.clear();return}for(;!this.onThingsLoading&&e<o&&this._queue.length>0;){const s=Date.now(),c=this._queue.pop();setTimeout(()=>{c?c.type===avatarSetting.body?(this.onThingsLoading=!0,this.loadBody(c.type,c.id,c.lod).then(d=>{d&&i.set(avatarSetting.body,d),e+=Date.now()-s,this.onThingsLoading=!1}).catch(d=>{this._process&&(this._process.isHide=!0,this.currentLODUsers[this._process.distLevel]--,this._clear(i),this._queue=[],this._process.isInLoadingList=!1,this._process=void 0,e+=100,this.onThingsLoading=!1),log$_.warn(`[Engine] body ${c.id} uri error, type ${c.type}, avatar has been hided`+d)})):c.type===avatarSetting.animations?this.loadAnimation(this._process.avatarType,c.id).then(d=>{d&&i.set(avatarSetting.animations,d),e+=Date.now()-s,this.onThingsLoading=!1}).catch(d=>{this._process&&(this._process.isHide=!0,this.currentLODUsers[this._process.distLevel]--,this._clear(i),this._queue=[],this._process.isInLoadingList=!1,this._process=void 0,e+=100,this.onThingsLoading=!1),log$_.warn(`animation ${c.id} uri error, type ${c.type}, avatar has been hided`+d)}):this.loadDecoration(c.type,c.id,c.lod).then(d=>{d&&i.set(d.type,d),e+=Date.now()-s,this.onThingsLoading=!1}).catch(d=>{this._process&&(this._process.isHide=!0,this.currentLODUsers[this._process.distLevel]--,this._clear(i),this._queue=[],this._process.isInLoadingList=!1,this._process=void 0,e+=100,this.onThingsLoading=!1),log$_.warn(`component ${c.id} uri error, type ${c.type}, avatar has been hided`+d)}):e+=100},0)}}_validateContainer(i){return!i.meshes||i.meshes.length<=1?(log$_.warn("import container has no valid meshes"),!1):!i.skeletons||i.skeletons.length==0?(log$_.warn("import container has no valid skeletons"),!1):!0}_getAssetContainer(i,e){return new Promise((o,s)=>{const c=this._getSourceKey(i,e||0),d=avatarLoader.containers.get(c);if(d)return o(d);avatarLoader.load(this.sceneManager,i,e).then(_=>_?this._validateContainer(_)?(avatarLoader.containers.set(c,_),o(_)):s(new ContainerLoadingFailedError(`[Engine] :: cannot load body type ${i}.`)):s(new ContainerLoadingFailedError(`[Engine] container load failed cannot load body type ${i}.`))).catch(_=>s(new ContainerLoadingFailedError(`[Engine] ${_} :: cannot load body type ${i}.`)))})}_clipContainerRes(i){i.transformNodes=[],i.skeletons.forEach(e=>{e.dispose()}),i.skeletons=[]}loadBody(i,e,o){return avatarLoader.load(this.sceneManager,e,o).then(s=>{if(s){const c=s.instantiateModelsToScene();s.xReferenceCount++;const d={isRender:!1,uId:Math.random(),root:c.rootNodes[0],skeletonType:i,name:e,animations:c.animationGroups,skeleton:c.skeletons[0],lod:o};return c.rootNodes[0]._parentContainer=s,c.rootNodes[0].setEnabled(!1),d}else return Promise.reject(new ContainerLoadingFailedError("[Engine] container failed instanciates failed"))}).catch(()=>Promise.reject(new ContainerLoadingFailedError(`[Engine] body type ${i} instanciates failed`)))}updateAnimationLists(i,e){return new Promise((o,s)=>(avatarLoader.avaliableAnimation.set(e,i),o()))}loadAnimation(i,e){return avatarLoader.loadAnimRes(this.sceneManager,e,i).then(o=>{if(o){let s;const c=this.avatarLoader.animations;return o.animationGroups.forEach(d=>{d.stop(),d.name===e&&(s=d,s.pContainer=o),c.set(getAnimationKey(d.name,i),d)}),this._clipContainerRes(o),o.xReferenceCount++,s}else return Promise.reject(new ContainerLoadingFailedError("[Engine] container failed instanciates failed"))})}loadDecoration(i,e,o){return avatarLoader.load(this.sceneManager,e,o).then(s=>{if(s){if(s.meshes.length<=1)return console.error("\u3010\u5F02\u5E38\uFF0Ccontainer\u4E0D\u542Bmesh\u3011"),Promise.reject(`\u3010\u5F02\u5E38\uFF0Ccontainer\u4E0D\u542Bmesh\u3011 ${e}`);const c=s.meshes[1].clone(s.meshes[1].name,null);if(!c)return log$_.warn("[Engine] decoration does not exist!"),null;const d={isRender:!1,uId:Math.random(),root:c,type:i,name:e,isSelected:!1,lod:o};if(s.xReferenceCount++,c._parentContainer=s,s.meshes.length>1)for(let _=2;_<s.meshes.length;_++)c.addChild(s.meshes[_].clone(s.meshes[_].name,null));return c.setEnabled(!1),d.isSelected=!0,d}else return Promise.reject(new ContainerLoadingFailedError("[Engine] container failed, instanciates failed."))})}_getSourceKey(i,e){return e&&avatarSetting.lod[e]?i+avatarSetting.lod[e].fileName.split(".")[0]:i}addAvatarToScene(i,e){const o=Date.now();return this.loadBody(i.avatarType,i.avatarType,e).then(s=>{var c;return s?(i.attachBody(s),s.animations.length>0?(s.animations.forEach(d=>{d.stop()}),i.setAnimations(s.animations),(c=i.controller)==null||c.playAnimation(i.controller.onPlay,!0),i.isRender=!0,i.isInLoadingList=!1,i.setAvatarVisible(!0),i):this.loadAnimation(i.avatarType,this._defaultAnims).then(d=>{if(!d)return i.removeAvatarFromScene(),i.isInLoadingList=!1,Promise.reject(new AvatarAnimationError);const _=[];return i.clothesList.length>0&&i.clothesList.forEach(b=>{_.push(this.loadDecoration(b.type,b.id,e))}),Promise.all(_).then(b=>{var $,_e,et,tt;b.forEach(rt=>{if(rt&&!rt.isRender)i.attachDecoration(rt);else{i.isInLoadingList=!1,i.removeAvatarFromScene(),Promise.reject(new AvatarAssetLoadingError);return}}),i.isRender=!0,($=i.controller)==null||$.playAnimation(i.controller.onPlay,i.controller.loop),i.setAvatarVisible(!0),(_e=this._sceneManager)==null||_e.lightComponent.setShadow(i);const k=avatarLoader.mshPath.get("meshes/ygb.glb"),j=avatarLoader.matPath.get(avatarResources.ygb.mesh);if(k&&j)this.loadExtra(j,k).then(rt=>{var it;return i.isRender=!0,i.isInLoadingList=!1,i.distLevel=e,(it=this._sceneManager)==null||it.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now()-o),i});else return i.isRender=!0,i.isInLoadingList=!1,i.distLevel=e,(et=this._sceneManager)==null||et.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now()-o),i;return i.isInLoadingList=!1,i.distLevel=e,(tt=this._sceneManager)==null||tt.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now()-o),i}).catch(()=>Promise.reject(new AvatarAssetLoadingError(`[Engine] avatar ${i.id} instanciates failed.`)))}).catch(()=>Promise.reject(new AvatarAssetLoadingError(`[Engine] avatar ${i.id} instanciates failed.`)))):(i.isInLoadingList=!1,Promise.reject(new ContainerLoadingFailedError(`[Engine] avatar ${i.id} instanciates failed`)))}).catch(()=>Promise.reject(new AvatarAssetLoadingError(`[Engine] avatar ${i.id} instanciates failed.`)))}loadExtra(i,e){const o=avatarResources.ygb.name;return new Promise((s,c)=>{var d;(d=this.sceneManager)==null||d.urlTransformer(i).then(_=>{SceneLoader.LoadAssetContainerAsync("",_,this.scene,null,avatarSetting.fileType).then(b=>{var j;this.extraComps.set(o,b.meshes[0]);const k=new NodeMaterial(`material_${o}`,this._scene,{emitComments:!1});(j=this.sceneManager)==null||j.urlTransformer(e).then($=>{k.loadAsync($).then(()=>{b.meshes[2].material.dispose(!0,!0),k.build(!1),b.meshes[2].material=k,s(b.meshes[2])})})})})})}getAvatarList(){const i=[];return this.characterMap.forEach((e,o)=>{e.forEach((s,c)=>{i.push(s)})}),i}_debug_avatar(){var e,o;console.error("===>currentLODUsers",this.currentLODUsers),console.error("===>maxLODUsers",this._maxLODUsers),console.error("===>Loddist",this.getLoDLevels()),console.error("===> main character loc",(o=(e=this._mainUser)==null?void 0:e.rootNode)==null?void 0:o.position);let i=0;this.getAvatarList().forEach(s=>{s.isRender&&(console.error(`avatar id : ${s.id},lod ${s.distLevel},is Hide ${s.isHide}, distance ${s.distance}, is pending ${s.isInLoadingList}`),i++)}),console.error("========= avatar num",i),console.error("loop:",this._updateLoopObserver?"on":"false","=> process",this._process,"===> comp",this._processList),console.error("===>maxLODUsers",this._maxLODUsers)}}const log$Z=new Logger$1("XLightManager");class XLightManager{constructor(i){ct(this,"_scene");ct(this,"_envTexture");ct(this,"_shadowLight");ct(this,"_shadowGenerator");ct(this,"_avatarShadowMeshMap");ct(this,"_cullingShadowObservers");ct(this,"sceneManager");this.sceneManager=i,this._scene=this.sceneManager.Scene,this._envTexture=null,this.shadowLean=.1;const e=new Vector3(this.shadowLean,-1,0),o=1024;this._shadowLight=new DirectionalLight("AvatarLight",e,this._scene),this._shadowLight.shadowMaxZ=5e3,this._shadowLight.intensity=0,this.attachLightToCamera(this._shadowLight),this._shadowGenerator=new ShadowGenerator(o,this._shadowLight,!0),this._avatarShadowMeshMap=new Map,this._cullingShadowObservers=new Map}set shadowLean(i){i=Math.min(i,1),i=Math.max(i,-1),this._shadowLight&&(this._shadowLight.direction=new Vector3(i,-1,0))}setIBL(i){return new Promise((e,o)=>{this.sceneManager.urlTransformer(i).then(s=>{var c;if(s==((c=this._envTexture)==null?void 0:c.url))return e("env set success");this._envTexture!=null&&this.disposeIBL(),this._envTexture=CubeTexture.CreateFromPrefilteredData(s,this._scene,".env"),this._scene.environmentTexture=this._envTexture,this._envTexture.onLoadObservable.addOnce(()=>{e("env set success"),log$Z.info("env set success")})}).catch(()=>{o("env set fail")})})}disposeIBL(){this._envTexture==null?log$Z.info("env not exist"):(this._envTexture.dispose(),this._envTexture=null,this._scene.environmentTexture=null,log$Z.info("env dispose success"))}removeShadow(i){var e;if(this._avatarShadowMeshMap.has(i)){this._avatarShadowMeshMap.delete(i),this._cullingShadowObservers.get(i)&&(this._scene.onBeforeRenderObservable.remove(this._cullingShadowObservers.get(i)),this._cullingShadowObservers.delete(i));const o=i.rootNode;o&&((e=this._shadowGenerator)==null||e.removeShadowCaster(o))}else return}enableShadow(i){this._shadowLight&&(this._shadowLight.shadowEnabled=i)}setShadow(i){if(this._avatarShadowMeshMap.has(i))return;i.rootNode&&this._avatarShadowMeshMap.set(i,i.rootNode.getChildMeshes());const e=20,o=10,s=this.cullingShadow(e,o,i);this._cullingShadowObservers.set(i,s)}cullingShadow(i,e,o){let s=0;const c=()=>{var _;if(s==e){const b=this._avatarShadowMeshMap.get(o),k=(_=o.rootNode)==null?void 0:_.getChildMeshes(),j=this._scene.activeCamera;b==null||b.forEach($=>{var _e;(_e=this._shadowGenerator)==null||_e.removeShadowCaster($,!1)}),k==null||k.forEach($=>{var _e;(_e=this._shadowGenerator)==null||_e.addShadowCaster($,!1)}),j&&o.rootNode.position.subtract(j.position).length()>i&&(k==null||k.forEach($=>{var _e;(_e=this._shadowGenerator)==null||_e.removeShadowCaster($,!1)})),k&&this._avatarShadowMeshMap.set(o,k),s=0}else s+=1};return this._scene.onBeforeRenderObservable.add(c)}attachLightToCamera(i){const e=i,o=15,s=()=>{const c=this._scene.activeCamera;if(c){const d=e.direction,_=new Vector3(o*d.x,o*d.y,o*d.z),b=c.position;e.position=b.subtract(_)}};return e&&this._scene.registerBeforeRender(s),s}}ParticleSystemSet.prototype.systems=new Array;const ar=class{constructor(i){ct(this,"_scene");ct(this,"_particles");ct(this,"_light");ct(this,"load",(i,e,o)=>new Promise(s=>{ParticleSystemSet.BaseAssetsUrl=i;const c=new XMLHttpRequest;c.open("get",i+"/"+e),c.send(null),c.onload=()=>{if(c.status==200){const d=JSON.parse(c.responseText);let _=null;if(Object.keys(d).find(b=>b=="systems")==null){const b=ParticleSystem.Parse(d,this._scene,i);_=new ParticleSystemSet,_.systems.push(b)}else _=ParticleSystemSet.Parse(d,this._scene,!1);s(_)}}}));ct(this,"get",i=>this._particles.get(i));ct(this,"start",i=>{const e=this._particles.get(i);e&&e.start()});ct(this,"stop",i=>{var o;const e=((o=this._particles.get(i))==null?void 0:o.systems)||[];for(let s=0;s<e.length;s++)e[s].stop()});ct(this,"remove",i=>{const e=this._particles.get(i);e&&e.dispose()});ct(this,"setParticlePosition",(i,e)=>{const o=this._particles.get(i);o&&(o.emitterNode=e)});ct(this,"setParticleScalingInPlace",(i,e)=>{const o=this._particles.get(i);o==null||o.systems.forEach(s=>{ar.scalingInPlace(s,e)})});if(this._scene=i,this._particles=new Map,this._light=null,this._scene.getLightByName("fireworkLight"))this._light=this._scene.getLightByName("fireworkLight");else{const e=new PointLight("fireworkLight",new Vector3(0,0,0),i);e.intensity=0,this._light=e}}_flashBang(i=200){const e=this._scene.getLightByName("fireworkLight");e.intensity=1,setTimeout(()=>{e.intensity=0},i)}};let XParticleManager=ar;ct(XParticleManager,"disposeParticleSysSet",i=>{!i.systems||(i.systems.forEach(e=>{ar.disposeParticleSystem(e)}),i.dispose())}),ct(XParticleManager,"disposeParticleSystem",i=>{i.particleSystem&&(i=i.particleSystem),i.subEmitters&&i.subEmitters.forEach(e=>{e instanceof Array?e.forEach(o=>{ar.disposeParticleSystem(o)}):ar.disposeParticleSystem(e)}),i.dispose()}),ct(XParticleManager,"scalingInPlace",(i,e)=>{i.getClassName()==="ParticleSystem"&&(i.minSize*=e,i.maxSize*=e,i.subEmitters!=null&&i.subEmitters.forEach(o=>{o instanceof SubEmitter&&ar.scalingInPlace(o.particleSystem,e),o instanceof ParticleSystem&&ar.scalingInPlace(o,e),o instanceof Array&&o.forEach(s=>{ar.scalingInPlace(s.particleSystem,e)})}))});const DefaultUrlTransformer$1=async a=>a,log$Y=new Logger$1("subSequence"),DEFAULT_FRAME_RATE=30,ROOT_MESH_ANIM_PROPERTY=["scaling","position","rotation"],MESH_TAG="XSubSequence";class XSpriteManager extends SpriteManager{constructor(e,o,s,c,d){super(e,o,s,c,d);ct(this,"originalPositions");this.originalPositions=new Array,this.sprites.forEach(_=>{this.originalPositions.push(_.position)})}static Parse(e,o,s){const c=new XSpriteManager(e.name,"",e.capacity,{width:e.cellWidth,height:e.cellHeight},o);e.texture?c.texture=Texture.Parse(e.texture,o,s):e.textureName&&(c.texture=new Texture(s+e.textureUrl,o,!0,e.invertY!==void 0?e.invertY:!0));for(const d of e.sprites){const _=Sprite.Parse(d,c);c.originalPositions.push(_.position)}return c}}class XSubSequence{constructor(i,e,o=DefaultUrlTransformer$1){ct(this,"_scene");ct(this,"_meshGroups");ct(this,"_animGroup");ct(this,"_particleGroups");ct(this,"_materialGroups");ct(this,"_spriteGroups");ct(this,"_glowGroups");ct(this,"_highLightGroups");ct(this,"_endFrame");ct(this,"_centerNode");ct(this,"_rootDir");ct(this,"_abosoluteUrl");ct(this,"_name");ct(this,"_pickable",!1);ct(this,"urlTransformer");ct(this,"onLoadedObserverable",new Observable);ct(this,"onSubSequenceTransformationChangeObservable",new Observable);ct(this,"onIntersectionObservable",new Observable);ct(this,"_loaded");ct(this,"_isStarted");ct(this,"_isPaused");ct(this,"_isDisposing",!1);ct(this,"init",()=>new Promise((i,e)=>{this.urlTransformer(this._abosoluteUrl).then(o=>{const s=new XMLHttpRequest;s.open("get",o),s.send(null),s.onload=()=>{if(s.status==200){const c=JSON.parse(s.responseText);this.load(c).then(()=>{this.onLoadedObserverable.notifyObservers(this),this._loaded=!0,i()},()=>{e(),log$Y.error("subSequence: Load ${jsonBlob} json fail")})}},s.onerror=()=>{log$Y.error("http: Get ${jsonBlob} json fail"),e()}})}));ct(this,"play",async(i=!0)=>new Promise(e=>{if(this._animGroup.isPlaying&&this._animGroup.stop(),this._particleGroups.forEach(o=>{var s;((s=o.emitterNode)==null?void 0:s.getClassName())=="Mesh"&&o.emitterNode instanceof Mesh?o.emitterNode.isEnabled()&&o.start():o.start()}),this._animGroup.targetedAnimations.length==0){this.show();let o=0;this._spriteGroups.forEach(s=>{s.sprites.forEach(c=>{c.toIndex>o&&(o=c.toIndex)})}),this._spriteGroups.forEach(s=>{s.sprites.forEach(c=>{c.playAnimation(c.fromIndex,c.toIndex,i,c.delay,()=>{c.toIndex==o&&(this._isPaused=!0,this.hide(),e())})})})}else this._animGroup.play(i),this._spriteGroups.forEach(o=>{o.sprites.forEach(s=>{s.playAnimation(s.fromIndex,s.toIndex,i,s.delay)})}),i?this._animGroup.onAnimationGroupLoopObservable.addOnce(()=>{e()}):this._animGroup.onAnimationGroupEndObservable.addOnce(()=>{this._spriteGroups.forEach(o=>{o.sprites.forEach(s=>{s.isVisible=!1,s.isPickable=!1,s.stopAnimation()})}),e()});this._isStarted=!0,this._isPaused=!1}));ct(this,"stop",()=>{this._animGroup.stop(),this._particleGroups.forEach(i=>{i.systems.forEach(e=>{e.stop()})}),this._spriteGroups.forEach(i=>{i.sprites.forEach(e=>{e.stopAnimation()})}),this._isStarted=!1});ct(this,"clone",(i="Clone")=>{const e=new XSubSequence(this._scene,this._abosoluteUrl);return e._centerNode.name=i+"_"+this._centerNode.name,e._animGroup.name=i+"_"+this._animGroup.name,this._meshGroups.forEach(o=>{const s=o.clone(i+"_",e._centerNode),c=s.getChildren(void 0,!1);if(c.forEach(d=>{d.setEnabled(!0)}),c.push(s),s){const d=o.getChildren(void 0,!1);d.push(o),this.animGroup.targetedAnimations.forEach(_=>{if(_.target instanceof Node$2){const b=d.indexOf(_.target);b!=-1&&e._animGroup.addTargetedAnimation(_.animation,c[b])}})}}),e._loaded=!0,e});ct(this,"goToFrame",i=>{this._animGroup.start(!0,1,i,i)});ct(this,"pause",()=>{this._isPaused=!0,this._animGroup.pause()});ct(this,"reset",()=>{this._animGroup.reset()});ct(this,"loadTrackToAnim",i=>{const e=Array();let o=!0;i.keyFrame.forEach(c=>{if(c.frame>this._endFrame&&(this._endFrame=c.frame),c.value instanceof Array)if("blockName"in i){if(c.value.length==1){const d={frame:c.frame,value:c.value[0]},_=c.value[0];d.value=_,e.push(d),o=!1}else if(c.value.length==3){const d={frame:c.frame,value:new Color3(0,0,0)},_=new Color3(c.value[0],c.value[1],c.value[2]);d.value=_,e.push(d)}}else{const d={frame:c.frame,value:new Vector3(0,0,0)},_=new Vector3(c.value[0],c.value[1],c.value[2]);d.value=_,e.push(d)}else e.push(c),o=!1}),i.loop==null&&(i.loop=!1),i.index==null&&(i.index=0);let s=null;if("blockName"in i){const c={keyFrame:e,blockName:i.blockName,property:i.property,targetName:i.targetName,index:i.index,loop:i.loop};s=this.transferTrackToAnim(c,o)}else{const c={keyFrame:e,property:i.property,targetName:i.targetName,index:i.index,loop:i.loop};s=this.transferTrackToAnim(c,o)}return s});ct(this,"transferTrackToAnim",(i,e)=>{let o=null;e?("blockName"in i?o=new Animation(i.targetName+"_"+i.property,i.property,DEFAULT_FRAME_RATE,Animation.ANIMATIONTYPE_COLOR3,Animation.ANIMATIONLOOPMODE_CYCLE):o=new Animation(i.targetName+"_"+i.property,i.property,DEFAULT_FRAME_RATE,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CYCLE),o.setKeys(i.keyFrame)):(o=new Animation(i.targetName+"_"+i.property,i.property,DEFAULT_FRAME_RATE,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE),o.setKeys(i.keyFrame));let s=null;return"blockName"in i?s={animation:o,blockName:i.blockName,targetName:i.targetName,nodeIndex:i.index,loop:i.loop}:s={animation:o,targetName:i.targetName,nodeIndex:i.index,loop:i.loop},s});e.indexOf("./")==0&&(e=e.slice(2)),this._abosoluteUrl=e,this._name=e.split("/").slice(-1)[0].split(".")[0].split("_")[1],this._rootDir=e.split("/").slice(0,-1).join("/")+"/",this._scene=i,this._meshGroups=new Map,this._animGroup=new AnimationGroup("SubSeqAnim_",this._scene),this._particleGroups=new Map,this._materialGroups=new Map,this._glowGroups=new Map,this._highLightGroups=new Map,this._spriteGroups=new Map,this._endFrame=0,this._centerNode=new TransformNode("__rootSubSeq__",i),this._loaded=!1,this._isPaused=!0,this._isStarted=!1,this._centerNode.setEnabled(!1),this.urlTransformer=o,this._centerNode.onAfterWorldMatrixUpdateObservable.add(()=>{this.onSubSequenceTransformationChangeObservable.notifyObservers(this)}),this._animGroup.onAnimationGroupPlayObservable.add(()=>{this._particleGroups.forEach(s=>{s.systems.forEach(c=>{c.isStarted()||c.start()})}),this.show()}),this._animGroup.onAnimationGroupLoopObservable.add(()=>{this._particleGroups.forEach(s=>{s.systems.forEach(c=>{c.isStarted()||c.start()})})}),this._animGroup.onAnimationGroupEndObservable.add(()=>{this.beforeAnimationGroupEndHook(),this.hide()})}beforeAnimationGroupEndHook(){}dispose(){this._isDisposing=!0,this._spriteGroups.forEach(i=>{i.dispose()}),this._glowGroups.forEach(i=>{i.dispose()}),this._highLightGroups.forEach(i=>{i.dispose()}),this._particleGroups.forEach(i=>{XParticleManager.disposeParticleSysSet(i)}),this._animGroup.stop(),this._animGroup.dispose(),this._meshGroups.forEach(i=>{i.getChildren(void 0,!1).forEach(e=>{var o,s;(e.getClassName()==="AbstractMesh"||e.getClassName()==="Mesh")&&((o=e.skeleton)==null||o.dispose(),(s=e.material)==null||s.dispose(!0,!0)),e.dispose(!0,!0)}),i.dispose(!1,!0)}),this._centerNode.dispose(!1,!0),this._materialGroups.forEach(i=>{}),this._materialGroups.clear(),this._spriteGroups.clear(),this._glowGroups.clear(),this._highLightGroups.clear(),this._meshGroups.clear(),this._particleGroups.clear(),this._loaded=!1}get animGroup(){return this._animGroup}get name(){return this._name}get path(){return this._abosoluteUrl}get position(){return xversePosition2Ue4(this.pos)}get rotation(){return xverseRotation2Ue4(this.rot)}get scaling(){return this.scal}get pos(){return this._centerNode.position}get rot(){return this._centerNode.rotation}get scal(){return this._centerNode.scaling}get root(){return this._centerNode}get loaded(){return this._loaded}get isPlaying(){return this._animGroup?this._animGroup.isPlaying:this._isStarted&&!this._isPaused}get isStarted(){return this._animGroup?this._animGroup.isStarted:this._isStarted}get isPickable(){return this._pickable}set isPickable(i){this._meshGroups.forEach(e=>{e.getChildMeshes().forEach(o=>{o.isPickable=i})}),this._spriteGroups.forEach(e=>{e.isPickable=i,e.sprites.forEach(o=>{o.isPickable=i})}),this._pickable=i}addAnimation(i){this._animGroup.addTargetedAnimation(i,this._centerNode),this._spriteGroups.forEach(e=>{e.sprites.forEach(o=>{this._animGroup.addTargetedAnimation(i,o)})})}setStartFrame(i){this._animGroup.stop(),this._animGroup.targetedAnimations.forEach(e=>{const o=e.animation.getKeys();o.forEach(s=>{i+o[0].frame>0?s.frame+=i:s.frame-=o[0].frame})})}lookAt(i){ue4Position2Xverse(i)&&this.root.lookAt(ue4Position2Xverse(i))}setPosition(i){this.setPositionVector(ue4Position2Xverse(i))}setPositionVector(i){this._centerNode.position=i,this._particleGroups.forEach(e=>{e.emitterNode==null||e.emitterNode instanceof Vector3?e.emitterNode=i:this._scene.getMeshByName(e.emitterNode.name)||(e.emitterNode=i)}),this._spriteGroups.forEach(e=>{e.sprites.forEach((o,s)=>{o.position=i})})}setScaling(i){this.setScalingVector(ue4Scaling2Xverse(i))}setScalingVector(i){var e;this._centerNode.scaling=i,(e=this._particleGroups)==null||e.forEach(o=>{o.systems.forEach(s=>{XParticleManager.scalingInPlace(s,i.x)})}),this._spriteGroups.forEach(o=>{o.sprites.forEach(s=>{s.size*=i.x})})}setRotation(i){this.setRotationVector(ue4Rotation2Xverse(i))}setRotationVector(i){this._centerNode.rotation=i}hide(){this._centerNode.setEnabled(!1),this._particleGroups.forEach(i=>{i.systems.forEach(e=>{e.isStarted()&&e.stop()})}),this._spriteGroups.forEach(i=>{i.sprites.forEach(e=>{e.isVisible=!1})})}show(){this._centerNode.setEnabled(!0),this._centerNode.getChildren().forEach(i=>{i.setEnabled(!0),i.getChildMeshes().forEach(e=>{e.setEnabled(!0)})}),this._particleGroups.forEach(i=>{i.systems.forEach(e=>{e.start()})}),this._spriteGroups.forEach(i=>{i.sprites.forEach(e=>{e.isVisible=!0})})}get totalFrame(){return this._endFrame}load(i){return new Promise((e,o)=>{const s=i.Mesh,c=i.Sprite,d=i.Material,_=i.Glow,b=i.HighLight,k=i.Particle,j=i.MeshTrack,$=i.ParticleTrack,_e=i.MaterialTrack;this._animGroup.name+=i.Type;const et=Date.now();this._centerNode.name+=i.Type;const tt=new Array,rt=new Array;s!=null&&s.forEach(it=>{tt.push(this.loadMesh(it))}),c!=null&&c.forEach(it=>{rt.push(this.loadSprite(it))}),Promise.all(tt).then(()=>{d!=null&&d.forEach(it=>{rt.push(this.loadMaterial(it))}),k!=null&&k.forEach(it=>{rt.push(this.loadParticle(it))}),Promise.all(rt).then(()=>{if(this._isDisposing){const nt=Date.now()-et;log$Y.info(`subSequence: Load ${i.Type} takes ${nt} ms`),e(this);return}if(_!=null)for(const nt of _)this.loadGlow(nt);if(b!=null)for(const nt of b)this.loadHighLight(nt);j!=null&&j.forEach(nt=>{const ot=this._meshGroups.get(nt.targetName);if(ot!=null){const at=this.loadTrackToAnim(nt);ROOT_MESH_ANIM_PROPERTY.indexOf(at.animation.targetProperty)==-1?ot.getChildMeshes().forEach(st=>{at.animation.targetProperty in st&&this._animGroup.addTargetedAnimation(at.animation,st)}):this._animGroup.addTargetedAnimation(at.animation,ot)}}),$!=null&&$.forEach(nt=>{var ut;const ot=nt.index,at=nt.targetName,st=(ut=this._particleGroups.get(at))==null?void 0:ut.systems[ot];if(st!=null){const ft=this.loadTrackToAnim(nt);this._animGroup.addTargetedAnimation(ft.animation,st)}}),_e!=null&&_e.forEach(nt=>{const ot=this._materialGroups.get(nt.targetName);if(ot){const at=ot[0];if(at!=null)if(at.getBlockByName(nt.blockName)!=null){const st=this.loadTrackToAnim(nt);ot==null||ot.forEach(ut=>{this._animGroup.addTargetedAnimation(st.animation,ut.getBlockByName(nt.blockName))})}else console.error("property "+nt.property+"is not in "+at.name)}});const it=Date.now()-et;log$Y.info(`subSequence: Load ${i.Type} takes ${it} ms`),e(this)},()=>{log$Y.error(`subSequence: Load ${i.Type} fail`),o()})},()=>{o()})})}loadMesh(i){return new Promise((e,o)=>{const s=this._rootDir+i.uri;this.urlTransformer(s).then(c=>{if(this._isDisposing){e();return}SceneLoader.LoadAssetContainer("",c,this._scene,d=>{if(this._isDisposing){d.removeAllFromScene(),e();return}d.animationGroups.forEach(b=>{b.stop()}),d.animationGroups.length!=0&&(d.animationGroups.forEach(b=>{b.targetedAnimations.forEach(k=>{this._animGroup.addTargetedAnimation(k.animation,k.target)}),b.dispose()}),d.animationGroups=[],d.animations=[],d.materials=[]);const _=new TransformNode("__root__"+i.name,this._scene);if(i.uri.split(".")[1]=="glb")d.meshes[0].parent=_;else if(i.uri.split(".")[1]=="obj"){const b=new TransformNode("__root__",this._scene);d.meshes.forEach(k=>{k.parent=b,k.Type=MESH_TAG}),b.parent=_}_.getChildMeshes().forEach(b=>{i.isPickable!=null?b.isPickable=i.isPickable:b.isPickable=!1,b.xtype="XSubSequence"}),this._meshGroups.set(i.name,_),_.parent=this._centerNode,d.addAllToScene(),e()},()=>{},()=>{log$Y.error("subSequence:Load effect mesh fail"),log$Y.error(`Effect Mesh ${i.name} load error`),o()},".glb")},()=>{log$Y.error("http:Get effect mesh fail"),log$Y.error(`Effect Mesh ${i.name} load error`),o()})})}loadSprite(i){return new Promise((e,o)=>{if(this._isDisposing){e();return}const s=this._rootDir+i.uri;if(i.uri!==""){i.name;const c=new XMLHttpRequest;c.open("get",s),c.send(null),c.onload=()=>{if(c.status==200){const d=JSON.parse(c.responseText),_=XSpriteManager.Parse(d,this._scene,this._rootDir);_.sprites.forEach(b=>{b.stopAnimation()}),this._spriteGroups.set(i.name,_),e()}else log$Y.error("subSequence:Load effect sprite fail"),log$Y.error(`Effect Sprite ${i.name} load error`),o()}}})}loadMaterial(i){return new Promise((e,o)=>{if(this._isDisposing){e();return}const s=this._rootDir+i.uri;if(i.uri!==""){const c=i.name,d=new NodeMaterial(`material_${c}`,this._scene,{emitComments:!1});d.backFaceCulling=!1,this.urlTransformer(s).then(_=>{if(this._isDisposing){d.dispose(!1,!0,!1),e();return}d.loadAsync(_).then(()=>{if(this._isDisposing){d.dispose(!0,!0,!1),e();return}d.build(!1);const b=new Array;let k=!1;for(let j=0;j<i.meshName.length;j++)this._meshGroups.forEach($=>{$.getChildMeshes().forEach(_e=>{var et;if(_e.name===i.meshName[j]){k=!0,(et=_e.material)==null||et.dispose(!0,!0);const tt=_e;if(tt.skeleton==null){const rt=d;tt.material=rt,b.push(rt)}else if(tt.numBoneInfluencers=4,tt.computeBonesUsingShaders=!0,j==0){const rt=d;tt.material=rt,b.push(rt)}else{const rt=d.clone(`material_${c}`+String(j),!1);tt.material=rt,b.push(rt)}}})});k?this._materialGroups.set(i.name,b):d.dispose(!0,!0),e()},()=>{log$Y.error("http:Get effect Material fail"),log$Y.error(`Effect NodeMaterial ${c} load error`),o()})})}})}async loadGlow(i){const e=new GlowLayer(i.name,this._scene,{blurKernelSize:i.blurKernelSize});e.intensity=i.intensity,i.meshName.forEach(o=>{const s=this._scene.getMeshByName(o);s!=null&&e.addIncludedOnlyMesh(s)}),this._glowGroups.set(i.name,e)}loadHighLight(i){const e=new HighlightLayer(i.name,this._scene);i.meshName.forEach(o=>{const s=this._scene.getMeshByName(o);if(s!=null){const c=new Color3(i.color[0],i.color[1],i.color[2]);e.addMesh(s,c)}}),this._highLightGroups.set(i.name,e)}loadParticle(i){return new Promise((e,o)=>{const s=this._rootDir+i.rootDir,c=new XParticleManager(this._scene);this.urlTransformer(s+i.uri).then(d=>{if(this._isDisposing){e();return}c.load(s,i.uri,i.name).then(_=>{if(this._isDisposing){o();return}this._particleGroups.set(i.name,_),e()},()=>{log$Y.error(`SubSequence: ${i.name} particle load fail`),o()})},()=>{log$Y.error(`http: ${s+i.uri} load fail`),o()})})}}const DefaultUrlTransformer=async a=>a;class XSequence{constructor(i,e,o="test",s=DefaultUrlTransformer){ct(this,"_scene");ct(this,"_name");ct(this,"_subSeqs");ct(this,"_animGroup");ct(this,"_targetSubSeqs");ct(this,"_abosoluteUrl");ct(this,"_rootDir");ct(this,"urlTransformer");ct(this,"init",async()=>new Promise(i=>{this.urlTransformer(this._abosoluteUrl).then(e=>{const o=new XMLHttpRequest;o.open("get",e),o.send(null),o.onload=()=>{if(o.status==200){const s=JSON.parse(o.responseText);this.load(s).then(()=>{i()})}}})}));ct(this,"getRootOfSubSeqs",()=>{const i=new Array;return this._subSeqs.forEach(e=>{i.push(e.root)}),i});ct(this,"play",async(i=!0)=>new Promise(e=>{this._animGroup.play(i),i?this._animGroup.onAnimationGroupLoopObservable.addOnce(()=>{e()}):this._animGroup.onAnimationGroupEndObservable.addOnce(()=>{e()})}));ct(this,"goToFrame",i=>{this._animGroup.goToFrame(i)});ct(this,"hide",()=>{this._subSeqs.forEach(i=>{i.hide()})});ct(this,"show",()=>{this._subSeqs.forEach(i=>{i.show()})});ct(this,"pause",()=>{this._animGroup.pause()});ct(this,"reset",()=>{this._animGroup.reset()});this._scene=i,this._abosoluteUrl=e,this._rootDir=e.split("/").slice(0,-1).join("/")+"/",this._name=o,this._subSeqs=new Map,this._animGroup=new AnimationGroup("Seq_"+o,i),this._targetSubSeqs=new Map,this._animGroup.onAnimationGroupPlayObservable.add(()=>{this._subSeqs.forEach(c=>{c.show()})}),this._animGroup.onAnimationGroupEndObservable.add(()=>{this._subSeqs.forEach(c=>{c.hide()})}),this.urlTransformer=s}get animGroup(){return this._animGroup}serialize(){const i={};return i.SubSequence=new Array,i.TimeLine=new Array,this._subSeqs.forEach(e=>{const o={name:e.name,uri:e.path};i.SubSequence.push(o);const s=this._targetSubSeqs.get(e);s&&i.TimeLine.push({frame:s==null?void 0:s.frame,position:s.position,rotation:s.rotation,scaling:s.scaling,name:e.name})}),i}get isPlaying(){return this._animGroup.isPlaying}get isStarted(){return this._animGroup.isStarted}get loaded(){let i=!0;return this._subSeqs.forEach(e=>{i=i&&e.loaded}),i}dispose(){this._subSeqs.forEach(i=>{i.dispose()}),this.animGroup.dispose()}setFrame(i,e){const o=this._subSeqs.get(i);if(o){const s=this._targetSubSeqs.get(o);s&&(s.frame=e),s&&this.update(o,s)}}get name(){return this._name}update(i,e){if(e){const o={frame:e.frame,scaling:new Vector3(e.scaling[0],e.scaling[1],e.scaling[2]),position:new Vector3(e.position[0],e.position[1],e.position[2]),rotation:new Vector3(e.rotation[0]/180*Math.PI,e.rotation[1]/180*Math.PI,e.rotation[2]/180*Math.PI),name:e.name},s=this._subSeqs.get(o.name);s&&(s.setPositionVector(o.position),s.setRotationVector(o.rotation),s.setScalingVector(o.scaling),s.setStartFrame(o.frame),this._targetSubSeqs.set(s,e),s.onSubSequenceTransformationChangeObservable.add(()=>{const c=this._targetSubSeqs.get(s);c&&(c.position=[s.pos.x,s.pos.y,s.pos.z]),c&&(c.rotation=[s.rot.x,s.rot.y,s.rot.z]),c&&(c.scaling=[s.scal.x,s.scal.y,s.scal.z])}))}}load(i){return new Promise((e,o)=>{const s=new Array,c=i.SubSequence,d=i.TimeLine;for(const _ of c){_.uri.indexOf("./")==0&&(_.uri=_.uri.slice(2));const b=new XSubSequence(this._scene,this._rootDir+_.uri,this.urlTransformer);this._subSeqs.set(_.name,b),s.push(b.init())}Promise.all(s).then(()=>{d.forEach(_=>{const b=this._subSeqs.get(_.name);b&&this.update(b,_)}),this._subSeqs.forEach(_=>{_.animGroup.targetedAnimations.forEach(b=>{this._animGroup.addTargetedAnimation(b.animation,b.target)})}),e()},()=>{o()})})}}const log$X=new Logger$1("XStaticMesh");class XStaticMesh{constructor({id:i,mesh:e,group:o="default",lod:s=0,xtype:c=EMeshType.XStaticMesh,skinInfo:d="default",url:_=""}){ct(this,"_mesh");ct(this,"_id","-1");ct(this,"_group");ct(this,"_lod");ct(this,"_isMoving",!1);ct(this,"_isRotating",!1);ct(this,"_isVisible",!0);ct(this,"_skinInfo");ct(this,"setVisibility",(i,e)=>{Array.isArray(i)?i.forEach(o=>{this.setVisibility(o,e)}):i.isAnInstance||(i.visibility=e)});ct(this,"setPickable",(i,e)=>{Array.isArray(i)?i.forEach(o=>{this.setPickable(o,e)}):("isPickable"in i&&(i.isPickable=e),i.setEnabled(e))});ct(this,"hide",()=>{var i;this._isVisible=!1,this.mesh&&this.setVisibility(this.mesh,0),this.mesh&&this.setPickable(this.mesh,!1),(i=this.mesh)==null||i.getChildMeshes().forEach(e=>{this.setVisibility(e,0),this.setPickable(e,!1)})});ct(this,"show",()=>{var i;this._isVisible=!0,this.mesh&&this.setVisibility(this.mesh,1),this.mesh&&this.setPickable(this.mesh,!0),(i=this.mesh)==null||i.getChildMeshes().forEach(e=>{this.setVisibility(e,1),this.setPickable(e,!0)})});ct(this,"attachToAvatar",(i,e={x:0,y:.5,z:0},o={yaw:0,pitch:0,roll:0},s={x:.35,y:.35,z:.35})=>{const c=ue4Scaling2Xverse(s),d=ue4Rotation2Xverse(o),_=ue4Position2Xverse(e),b=this._mesh;i&&b?(i.setParent(b),i.position=_,i.rotation=d,i.scaling=c):log$X.error("[Engine] avatar or attachment not found!")});ct(this,"detachFromAvatar",(i,e=!1)=>{this._mesh&&i?this._mesh.removeChild(i):log$X.error("[Engine] avatar not found!")});this._id=i,this._mesh=e,this._group=o,this._lod=s,this._skinInfo=d,this.unallowMove(),this._mesh.xtype=c,this._mesh.xid=i,this._mesh.xgroup=this._group,this._mesh.xlod=this._lod,this._mesh.xskinInfo=this._skinInfo,this._mesh.xurl=_}get mesh(){return this._mesh}get position(){var c;if(!this._mesh)return null;const{x:i,y:e,z:o}=(c=this._mesh)==null?void 0:c.position;return xversePosition2Ue4({x:i,y:e,z:o})}get id(){return this._id}get group(){return this._group}get isMoving(){return this._isMoving}get isVisible(){return this._isVisible}get isRotating(){return this._isRotating}get skinInfo(){return this._skinInfo}allowMove(){this._mesh!=null&&(this._mesh.getChildMeshes().forEach(i=>{i.unfreezeWorldMatrix()}),this._mesh.unfreezeWorldMatrix())}unallowMove(){this._mesh!=null&&(this._mesh.getChildMeshes().forEach(i=>{i.freezeWorldMatrix()}),this._mesh.freezeWorldMatrix())}getID(){return this._id}setPosition(i){if(this._mesh){const e=ue4Position2Xverse(i);this._mesh.position=e}else log$X.error("[Engine] no root for positioning")}setRotation(i){const e=ue4Rotation2Xverse_mesh(i);this._mesh?this._mesh.rotation=e:log$X.error("[Engine] no root for rotating")}setScale(i){this._mesh?this._mesh.scaling=new Vector3(i,i,-i):log$X.error("[Engine] no root for scaling")}disableAvatar(){var i;(i=this._mesh)==null||i.setEnabled(!1)}enableAvatar(){var i;(i=this._mesh)==null||i.setEnabled(!0)}togglePickable(i){var e;(e=this.mesh)==null||e.getChildMeshes().forEach(o=>{"instances"in o&&"isPickable"in o&&(o.isPickable=i)}),this.mesh!=null&&"isPickable"in this.mesh&&(this.mesh.isPickable=i)}setMaterial(i){var e;(e=this.mesh)==null||e.getChildMeshes().forEach(o=>{"instances"in o&&"material"in o&&(o.material=i)}),this.mesh!=null&&"material"in this.mesh&&(this.mesh.material=i)}dispose(i=!1,e=!1){!this.mesh.isDisposed()&&this.mesh.dispose(i,e)}}class Timeout$1{constructor(i,e,o=!0){ct(this,"_fn");ct(this,"_delay");ct(this,"_timeout");this._fn=i,this._delay=e,o&&this.start()}get delay(){return this._delay}get isSet(){return!!this._timeout}setDelay(i){this._delay=i}start(){this.isSet||(this._timeout=window.setTimeout(()=>{const i=this._fn;this.clear(),i()},this._delay))}clear(){window.clearTimeout(this._timeout),this._timeout=void 0}reset(){this.clear(),this.start()}}class Stream$1{constructor(i){ct(this,"el");ct(this,"_streamPlayTimer",null);ct(this,"play",()=>new Promise((i,e)=>{this._streamPlayTimer=new Timeout$1(()=>{e("Stream play timeout")},5e3),this.el&&this.el.play().then(()=>{var o;i(),(o=this._streamPlayTimer)==null||o.clear()}).catch(o=>{var s;e("Media Failed to autoplay"),(s=this._streamPlayTimer)==null||s.clear()})}));if(!i){this.el=this.createVideoElement();return}this.el=i}createVideoElement(){const i=document.createElement("video");return i.muted=!0,i.autoplay=!1,i.playsInline=!0,i.width=360,i.height=640,i.setAttribute("autostart","false"),i.setAttribute("controls","controls"),i.setAttribute("muted","true"),i.setAttribute("preload","auto"),i.setAttribute("hidden","hidden"),document.body.appendChild(i),i}}var tvFragment=`precision highp float;
  10873. varying vec2 vUV;
  10874. uniform float tvWidthHeightScale;
  10875. uniform float mvWidthHeightScale;
  10876. uniform float bforceforceKeepContent;
  10877. uniform sampler2D texture_video;
  10878. // \u7B49\u6BD4\u4F8B\u7F29\u653E\u753B\u9762\u5360\u6EE1\u5C4F\u5E55\uFF0C\u5B58\u5728\u5185\u5BB9\u7684\u4E22\u5931
  10879. vec2 equalScalingFitTvSize(vec2 uv, float tvWidthHeightScale, float mvWidthHeightScale)
  10880. {
  10881. if( tvWidthHeightScale > mvWidthHeightScale )
  10882. {
  10883. float scale = mvWidthHeightScale/tvWidthHeightScale;
  10884. uv.y = (uv.y - 0.5) * scale + 0.5;
  10885. }else if( tvWidthHeightScale < mvWidthHeightScale )
  10886. {
  10887. float scale = tvWidthHeightScale/mvWidthHeightScale;
  10888. uv.x = (uv.x - 0.5) * scale + 0.5;
  10889. }
  10890. return vec2( uv.x , uv.y);
  10891. }
  10892. // \u5F3A\u5236\u4FDD\u7559\u753B\u9762\u5185\u5BB9\uFF08\u5E26\u6709\u9ED1\u8FB9\uFF09
  10893. vec2 forceKeepContent(vec2 uv, float tvWidthHeightScale, float mvWidthHeightScale)
  10894. {
  10895. if( tvWidthHeightScale > mvWidthHeightScale )
  10896. {
  10897. float scale = mvWidthHeightScale/tvWidthHeightScale;
  10898. uv.x = (uv.x - 0.5) / scale + 0.5;
  10899. }else if( tvWidthHeightScale < mvWidthHeightScale )
  10900. {
  10901. float scale = tvWidthHeightScale/mvWidthHeightScale;
  10902. uv.y = (uv.y - 0.5) / scale + 0.5;
  10903. }
  10904. return vec2( uv.x , uv.y);
  10905. }
  10906. void main()
  10907. {
  10908. vec2 uv = vUV;
  10909. vec3 rgb;
  10910. vec3 color = vec3(0,0,0);
  10911. // \u4E00\u65E6\u8BBE\u7F6E\u4E86mvWidthHeightScale\uFF0C\u5C31\u4F1A\u89E6\u53D1\u7B49\u6BD4\u4F8B\u7F29\u653Eor\u5F3A\u5236\u4FDD\u5185\u5BB9
  10912. if(tvWidthHeightScale > 0.0 && mvWidthHeightScale > 0.0)
  10913. {
  10914. if(bforceforceKeepContent > 0.0){
  10915. uv = forceKeepContent(uv, tvWidthHeightScale, mvWidthHeightScale);
  10916. }else{
  10917. uv = equalScalingFitTvSize(uv, tvWidthHeightScale, mvWidthHeightScale);
  10918. }
  10919. }
  10920. color = texture2D(texture_video, uv).rgb;
  10921. if( uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 )
  10922. {
  10923. color = vec3(0,0,0);
  10924. }
  10925. gl_FragColor = vec4(color, 1.0);
  10926. }
  10927. `,tvVertex=`precision highp float;
  10928. varying vec2 vUV;
  10929. attribute vec2 uv;
  10930. attribute vec3 position;
  10931. uniform mat4 view;
  10932. uniform mat4 projection;
  10933. uniform mat4 world;
  10934. void main()
  10935. {
  10936. vUV = uv;
  10937. gl_Position = projection * view * world * vec4(position , 1.0);
  10938. }
  10939. `;const log$W=new Logger$1("XTelevision");var EFitMode=(a=>(a.fill="fill",a.contain="contain",a.cover="cover",a))(EFitMode||{});class XTelevision{constructor(i,e,o,s){ct(this,"videoElement");ct(this,"meshPath");ct(this,"scene");ct(this,"tvMeshs",[]);ct(this,"vAng");ct(this,"videoMat");ct(this,"videoTexture");ct(this,"widthHeightScale");ct(this,"fitMode");ct(this,"_scenemanager");if(this.scene=i,this.meshPath=e,this._scenemanager=o,s!=null){const{vAng:c=0,widthHeightScale:d=-1,fitMode:_="fill"}=s;this.vAng=c,this.widthHeightScale=d,this.fitMode=_}}set tvWidthHeightscale(i){this.widthHeightScale=i}get tvWidthHeightscale(){return this.widthHeightScale}get tvFitMode(){return this.fitMode}set tvFitMode(i){this.fitMode=i}setPlaySpeed(i){this.videoElement!=null&&(this.videoElement.playbackRate=i)}getMesh(){return this.tvMeshs}createElement(i,e=!1){const s=new Stream$1().el;return s.loop=e,s.autoplay=!0,s.src=i,s}async setUrl(i){const{url:e,isLive:o=!1,poster:s=null,bLoop:c=!1,bMuted:d=!0}=i||{};if(typeof e!="string")return log$W.error("[Engine] Tv setUrl Error, url must be string: ",e),Promise.reject(new XTvMediaUrlError("[Engine] url must be string"));if(this.videoElement){this.videoElement.src=e,s!=null&&s.length>0&&(this.videoElement.poster=s);const b=this.play();return"bMuted"in i&&b!==void 0&&b.then(()=>{this.videoElement.muted=d}),this.videoElement.addEventListener("loadedmetadata",k=>{this.videoElement.videoWidth>0?this.videoMat.setFloat("mvWidthHeightScale",this.videoElement.videoWidth/this.videoElement.videoHeight):this.videoMat.setFloat("mvWidthHeightScale",16/9)}),Promise.resolve(this)}const _=this.createElement(e,c);return s!=null&&s.length>0&&(_.poster=s),this.setVideo(_,o).then(()=>{var k;const b=(k=this.videoElement)==null?void 0:k.play();"bMuted"in i&&b!==void 0&&b.then(()=>{this.videoElement.muted=d})}).catch(b=>{const k=new XTvMediaUrlError("[Engine] setUrl error! "+b);return log$W.error(k),Promise.reject(k)})}setCurrentTime(i){if(!this.videoElement){log$W.warn("[Engine] The television is not been initialize succesfully");return}const{currentTime:e}=i;if(typeof e!="number"){log$W.warn("[Engine] video currentTime must be number");return}this.videoElement.currentTime=e/1e3}getCurrentTime(){return this.videoElement?this.videoElement.currentTime*1e3:-1}play(){return log$W.info("[Engine] Play television"),this.toggle(!0),this.videoElement?this.videoElement.play():Promise.resolve()}pause(){var i;return log$W.info("[Engine] Pause television"),(i=this.videoElement)==null?void 0:i.pause()}stop(){log$W.info("[Engine] Stop television"),this.pause(),setTimeout(()=>{this.setCurrentTime({currentTime:0})}),this.toggle(!1)}toggle(i){log$W.info(`[Engine] Set Tv visibility = ${i}`);for(let e=0;e<this.tvMeshs.length;++e)i==!0?this.tvMeshs[e].show():this.tvMeshs[e].hide()}getVideoMat(){return this.videoMat}changeTvFitMode(){this.fitMode=="contain"?(this.widthHeightScale<0&&(this.widthHeightScale=2.4),this.videoMat.setFloat("tvWidthHeightScale",this.widthHeightScale),this.videoMat.setFloat("bforceforceKeepContent",1)):this.fitMode=="cover"?(this.widthHeightScale<0&&(this.widthHeightScale=this.calWidthHeightScale()),this.videoMat.setFloat("tvWidthHeightScale",this.widthHeightScale),this.videoMat.setFloat("bforceforceKeepContent",-1)):this.videoMat.setFloat("tvWidthHeightScale",-1)}async setVideo(i,e=!1,o=!0){return this.tvMeshs.length!=0?(log$W.warn(`[Engine] Set Video. length!=0, mesh: ${this.meshPath}, src: ${i.src}`),new Promise((s,c)=>{if(!(i instanceof HTMLVideoElement))return log$W.error("[Engine] Error, param of setVideo must be a HTMLVideoElement"),c(new XTvVideoElementError("[Engine] param of setVideo must be a HTMLVideoElement"));this.videoElement=i,o==!1&&(e==!1||checkOS().isIOS)&&i.crossOrigin!=="anonymous"&&(i.crossOrigin="anonymous",i.load()),this.videoElement.addEventListener("loadedmetadata",d=>{this.videoElement.videoWidth>0?this.videoMat.setFloat("mvWidthHeightScale",this.videoElement.videoWidth/this.videoElement.videoHeight):this.videoMat.setFloat("mvWidthHeightScale",16/9)}),this.videoTexture.updateURL(this.videoElement.src),s(this)})):(log$W.warn(`[Engine] Set Video. length==0, mesh: ${this.meshPath}, src: ${i.src}`),this.meshPath==""?(log$W.error("[Engine] Error, television meshPath is empty."),Promise.reject(new XTvVideoElementError("[Engine] Error, television meshPath is empty."))):this._scenemanager.urlTransformer(this.meshPath).then(s=>new Promise((c,d)=>i instanceof HTMLVideoElement?(this.videoElement=i,o==!1&&(e==!1||checkOS().isIOS)&&i.crossOrigin!=="anonymous"&&(i.crossOrigin="anonymous",i.load()),SceneLoader.LoadAssetContainerAsync("",s,this.scene,null,".glb").then(_=>{for(let k=_.materials.length-1;k>=0;--k)_.materials[k].dispose();const b=[];this.videoTexture=new VideoTexture("videoTex_"+Date.now(),i,this.scene,!1,!0,void 0,{autoPlay:!0,autoUpdateTexture:!0,muted:!0}),this.videoTexture.vAng=this.vAng,this.videoMat=new ShaderMaterial("videoMat_"+Date.now(),this.scene,{vertexSource:tvVertex,fragmentSource:tvFragment},{attributes:["uv","position"],uniforms:["view","projection","worldViewProjection","world"]}),this.videoMat.setTexture("texture_video",this.videoTexture),this.videoMat.setFloat("tvWidthHeightScale",-1),this.videoMat.setFloat("mvWidthHeightScale",16/9),this.videoMat.setFloat("bforceforceKeepContent",-1),this.videoMat.backFaceCulling=!1,this.videoMat.sideOrientation=Mesh.FRONTSIDE,this.videoElement.addEventListener("loadedmetadata",k=>{this.videoElement.videoWidth>0?this.videoMat.setFloat("mvWidthHeightScale",this.videoElement.videoWidth/this.videoElement.videoHeight):this.videoMat.setFloat("mvWidthHeightScale",16/9)});for(let k=0;k<_.meshes.length;++k)_.meshes[k].visibility=1,_.meshes[k].isPickable=!0,_.meshes[k].checkCollisions=!1,_.meshes[k].material=this.videoMat,"hasVertexAlpha"in _.meshes[k]&&(_.meshes[k].hasVertexAlpha=!1),this.scene.addMesh(_.meshes[k]),b.push(new XStaticMesh({id:_.meshes[k].id,mesh:_.meshes[k],xtype:EMeshType.Tv}));this.changeTvFitMode(),this.tvMeshs=b,this.toggle(!0),c(this)}).catch(_=>{log$W.error("[Engine] setVideo: create Tv by input mesh error! "+_),d(new XTvModelError("[Engine] setVideo: create Tv by input mesh error! "+_))})):d(new XTvVideoElementError("[Engine] param of setVideo must be a HTMLVideoElement")))))}async setSameVideo(i,e=""){return i==null||i==null?(log$W.error("[Engine] setSameVideo: input material is null or undefined "),Promise.reject(new XTvModelError("[Engine] setSameVideo input material is null or undefined !"))):this.tvMeshs.length!=0&&e==""?(log$W.warn(`[Engine] Set mirror video. length!=0, mesh: ${this.meshPath}`),new Promise((o,s)=>{try{this.videoMat=i,this.tvMeshs.forEach(c=>{c.setMaterial(i)}),this.changeTvFitMode(),o(this)}catch(c){log$W.error("[Engine] setSameVideo: create Tv by input mesh error! "+c),s(new XTvModelError("[Engine] create Tv by input mesh error! "+c))}})):(e!=""&&(this.meshPath=e,this.widthHeightScale=-1),this.meshPath==""?(log$W.error("[Engine] Error, setSameVideo television meshPath is empty."),Promise.reject(new XTvVideoElementError("[Engine] Error, setSameVideo television meshPath is empty."))):(log$W.warn(`[Engine] Set mirror video. length==0, mesh: ${this.meshPath}`),this._scenemanager.urlTransformer(this.meshPath).then(o=>new Promise((s,c)=>(this.videoMat=i,i!=null&&i.getActiveTextures()[0]&&(this.videoElement=i==null?void 0:i.getActiveTextures()[0].video),SceneLoader.LoadAssetContainerAsync("",o,this.scene,null,".glb").then(d=>{for(let b=d.materials.length-1;b>=0;--b)d.materials[b].dispose();const _=[];for(let b=0;b<d.meshes.length;++b)d.meshes[b].visibility=0,d.meshes[b].isPickable=!0,d.meshes[b].checkCollisions=!1,d.meshes[b].material=this.videoMat,"hasVertexAlpha"in d.meshes[b]&&(d.meshes[b].hasVertexAlpha=!1),this.scene.addMesh(d.meshes[b]),_.push(new XStaticMesh({id:d.meshes[b].id,mesh:d.meshes[b],xtype:EMeshType.Tv}));e!=""&&this.cleanTv(!1,!1),this.tvMeshs=_,this.changeTvFitMode(),s(this)}).catch(d=>{log$W.error("[Engine] setSameVideo: create Tv by input mesh error! "+d),c(new XTvModelError("[Engine] create Tv by input mesh error! "+d))}))))))}async changeTvModel(i=""){return i!=""&&(this.meshPath=i,this.widthHeightScale=-1),this.meshPath==""?(log$W.error("[Engine] Error,changeTvModel television meshPath is empty."),Promise.reject(new XTvVideoElementError("[Engine] Error, changeTvModel television meshPath is empty."))):this.videoMat==null||this.videoMat==null?(log$W.error("[Engine] changeTvModel: videoMat is null or undefined! "),Promise.reject(new XTvModelError("[Engine] changeTvModel: videoMat is null or undefined!"))):this._scenemanager.urlTransformer(this.meshPath).then(e=>new Promise((o,s)=>SceneLoader.LoadAssetContainerAsync("",e,this.scene,null,".glb").then(c=>{for(let _=c.materials.length-1;_>=0;--_)c.materials[_].dispose();const d=[];for(let _=0;_<c.meshes.length;++_)c.meshes[_].visibility=0,c.meshes[_].isPickable=!0,c.meshes[_].checkCollisions=!1,c.meshes[_].material=this.videoMat,"hasVertexAlpha"in c.meshes[_]&&(c.meshes[_].hasVertexAlpha=!1),this.scene.addMesh(c.meshes[_]),d.push(new XStaticMesh({id:c.meshes[_].id,mesh:c.meshes[_],xtype:EMeshType.Tv}));i!=""&&this.cleanTv(!1,!1),this.tvMeshs=d,this.changeTvFitMode(),o(this)}).catch(c=>{log$W.error("[Engine] changeTvModel: create Tv by input mesh error! "+c),s(new XTvModelError("[Engine] changeTvModel: create Tv by input mesh error! "+c))})))}calWidthHeightScale(){const i=[1e5,1e5,1e5],e=[-1e5,-1e5,-1e5];for(let d=0;d<this.tvMeshs.length;++d)if(this.tvMeshs[d].mesh.name!="__root__"){const _=this.tvMeshs[d].mesh.getBoundingInfo().boundingBox.vectorsWorld;for(let b=0;b<_.length;++b)i[0]>_[b].x&&(i[0]=_[b].x),i[1]>_[b].y&&(i[1]=_[b].y),i[2]>_[b].z&&(i[2]=_[b].z),e[0]<_[b].x&&(e[0]=_[b].x),e[1]<_[b].y&&(e[1]=_[b].y),e[2]<_[b].z&&(e[2]=_[b].z);break}const o=e[0]-i[0],s=e[1]-i[1],c=e[2]-i[2];return Math.sqrt(o*o+c*c)/Math.abs(s)}cleanTv(i=!1,e=!0){log$W.warn("[Engine] cleanTV");for(let o=0;o<this.tvMeshs.length;++o)this.tvMeshs[o].dispose(i,e);this.tvMeshs=[],this.meshPath=""}}class XStats{constructor(i){ct(this,"scene");ct(this,"sceneInstrumentation");ct(this,"engineInstrumentation");ct(this,"caps");ct(this,"engine");ct(this,"_canvas");ct(this,"_osversion");ct(this,"_scenemanager");this._scenemanager=i,this.scene=i.Scene,this._canvas=i.canvas,this.initSceneInstrument()}initSceneInstrument(){this.sceneInstrumentation=new SceneInstrumentation(this.scene),this.sceneInstrumentation.captureCameraRenderTime=!0,this.sceneInstrumentation.captureActiveMeshesEvaluationTime=!0,this.sceneInstrumentation.captureRenderTargetsRenderTime=!0,this.sceneInstrumentation.captureFrameTime=!0,this.sceneInstrumentation.captureRenderTime=!0,this.sceneInstrumentation.captureInterFrameTime=!0,this.sceneInstrumentation.captureParticlesRenderTime=!0,this.sceneInstrumentation.captureSpritesRenderTime=!0,this.sceneInstrumentation.capturePhysicsTime=!0,this.sceneInstrumentation.captureAnimationsTime=!0,this.engineInstrumentation=new EngineInstrumentation(this.scene.getEngine()),this.caps=this.scene.getEngine().getCaps(),this.engine=this.scene.getEngine(),this._osversion=this.osVersion()}getFrameTimeCounter(){return this.sceneInstrumentation.frameTimeCounter.current}getInterFrameTimeCounter(){return this.sceneInstrumentation.interFrameTimeCounter.current}getActiveMeshEvaluationTime(){return this.sceneInstrumentation.activeMeshesEvaluationTimeCounter.current}getDrawCall(){return this.sceneInstrumentation.drawCallsCounter.current}getDrawCallTime(){return this.sceneInstrumentation.renderTimeCounter.current}getAnimationTime(){return this.sceneInstrumentation.animationsTimeCounter.current}getActiveMesh(){return this.scene.getActiveMeshes().length}getActiveFaces(){return Math.round(this.scene.getActiveIndices()/3)}getActiveBones(){return this.scene.getActiveBones()}getActiveAnimation(){return this.scene._activeAnimatables.length}getActiveParticles(){return this.scene.getActiveParticles()}getTotalMaterials(){return this.scene.materials.length}getTotalTextures(){return this.scene.textures.length}getTotalGeometries(){return this.scene.geometries.length}getTotalMeshes(){return this.scene.meshes.length}getCameraRenderTime(){return this.sceneInstrumentation.cameraRenderTimeCounter.current}getTotalRootNodes(){return this.scene.rootNodes.length}getRenderTargetRenderTime(){const i=this.getDrawCallTime(),e=this.getActiveMeshEvaluationTime(),o=this.getCameraRenderTime()-(e+i);return this.getRTT1Time()+o}getRegisterBeforeRenderTime(){return this.sceneInstrumentation.registerBeforeTimeCounter.current}getRegisterAfterRenderTime(){return this.sceneInstrumentation.registerAfterTimeCounter.current}getRTT1Time(){return this.sceneInstrumentation.getRTT1TimeCounter.current}getRegisterBeforeRenderObserverLength(){return this.scene.onBeforeRenderObservable.observers.length}getRegisterAfterRenderObserverLength(){return this.scene.onAfterRenderObservable.observers.length}getTotalMeshByType(){const i=new Map;return this.scene.meshes.forEach(e=>{i.has(e.xtype)?i.set(e.xtype,i.get(e.xtype)+1):i.set(e.xtype,1)}),i}getHardwareRenderInfo(){return{maxTexturesUnits:this.caps.maxTexturesImageUnits,maxVertexTextureImageUnits:this.caps.maxVertexTextureImageUnits,maxCombinedTexturesImageUnits:this.caps.maxCombinedTexturesImageUnits,maxTextureSize:this.caps.maxTextureSize,maxSamples:this.caps.maxSamples,maxCubemapTextureSize:this.caps.maxCubemapTextureSize,maxRenderTextureSize:this.caps.maxRenderTextureSize,maxVertexAttribs:this.caps.maxVertexAttribs,maxVaryingVectors:this.caps.maxVaryingVectors,maxVertexUniformVectors:this.caps.maxVertexUniformVectors,maxFragmentUniformVectors:this.caps.maxFragmentUniformVectors,standardDerivatives:this.caps.standardDerivatives,supportTextureCompress:{s3tc:this.caps.s3tc!==void 0,s3tc_srgb:this.caps.s3tc_srgb!==void 0,pvrtc:this.caps.pvrtc!==void 0,etc1:this.caps.etc1!==void 0,etc2:this.caps.etc2!==void 0,astc:this.caps.astc!==void 0,bptc:this.caps.bptc!==void 0},textureFloat:this.caps.textureFloat,vertexArrayObject:this.caps.vertexArrayObject,textureAnisotropicFilterExtension:this.caps.textureAnisotropicFilterExtension!==void 0,maxAnisotropy:this.caps.maxAnisotropy,instancedArrays:this.caps.instancedArrays,uintIndices:this.caps.uintIndices,highPrecisionShaders:this.caps.highPrecisionShaderSupported,fragmentDepth:this.caps.fragmentDepthSupported,textureFloatLinearFiltering:this.caps.textureFloatLinearFiltering,renderToTextureFloat:this.caps.textureFloatRender,textureHalfFloat:this.caps.textureHalfFloat,textureHalfFloatLinearFiltering:this.caps.textureHalfFloatLinearFiltering,textureHalfFloatRender:this.caps.textureHalfFloatRender,textureLOD:this.caps.textureLOD,drawBuffersExtension:this.caps.drawBuffersExtension,depthTextureExtension:this.caps.depthTextureExtension,colorBufferFloat:this.caps.colorBufferFloat,supportTimerQuery:this.caps.timerQuery!==void 0,canUseTimestampForTimerQuery:this.caps.canUseTimestampForTimerQuery,supportOcclusionQuery:this.caps.supportOcclusionQuery,multiview:this.caps.multiview,oculusMultiview:this.caps.oculusMultiview,maxMSAASamples:this.caps.maxMSAASamples,blendMinMax:this.caps.blendMinMax,canUseGLInstanceID:this.caps.canUseGLInstanceID,canUseGLVertexID:this.caps.canUseGLVertexID,supportComputeShaders:this.caps.supportComputeShaders,supportSRGBBuffers:this.caps.supportSRGBBuffers,supportStencil:this.engine.isStencilEnable}}getSystemInfo(){return{resolution:"real: "+this.engine.getRenderWidth()+"x"+this.engine.getRenderHeight()+" cavs: "+this._canvas.clientWidth+"x"+this._canvas.clientHeight,hardwareScalingLevel:this.engine.getHardwareScalingLevel().toFixed(2).toString()+"_"+this._scenemanager.initEngineScaleNumber.toFixed(2).toString(),driver:this.engine.getGlInfo().renderer,vender:this.engine.getGlInfo().vendor,version:this.engine.getGlInfo().version,os:this._osversion}}getFps(){const i=this.sceneInstrumentation.frameTimeCounter.lastSecAverage,e=this.sceneInstrumentation.interFrameTimeCounter.lastSecAverage;return 1e3/(i+e)}osVersion(){const i=window.navigator.userAgent;let e;return/iphone|ipad|ipod/gi.test(i)?e=i.match(/OS (\d+)_(\d+)_?(\d+)?/):/android/gi.test(i)&&(e=i.match(/Android (\d+)/)),e!=null&&e.length>0?e[0]:null}}class RunTimeArray{constructor(){ct(this,"circularData");this.circularData=[]}add(i){this.circularData.length>1e3&&this.circularData.shift(),this.circularData.push(i)}getAvg(){let i=0;for(let e=0;e<this.circularData.length;e++)i+=this.circularData[e];return{sum:i,avg:i/this.circularData.length||0}}getMax(){let i=0;for(let e=0;e<this.circularData.length;e++)i<this.circularData[e]&&(i=this.circularData[e]);return i||0}clear(){this.circularData=[]}getStat(){const i=this.getAvg(),e={sum:i.sum,avg:i.avg,max:this.getMax()};return this.clear(),e}}class XEngineRunTimeStats{constructor(){ct(this,"timeArray_loadStaticMesh",new RunTimeArray);ct(this,"timeArray_updateStaticMesh",new RunTimeArray);ct(this,"timeArray_addAvatarToScene",new RunTimeArray)}}const log$V=new Logger$1("XDecalManager");class XDecalManager{constructor(i){ct(this,"scene");ct(this,"_decal");ct(this,"_mat");ct(this,"_sharedMat");ct(this,"_scenemanager");this._decal=new Map,this._mat=new Map,this._sharedMat=new Map,this._scenemanager=i,this.scene=i.Scene}get decals(){return Array.from(this._decal.values())}getMesh(){return this._decal}async addDecal(i){const{id:e,meshPath:o,skinInfo:s="default"}=i;return this._decal.get(e)?(log$V.warn(`[Engine] Cannot add decal with an existing id: [${e}], meshPath: ${o}, skinInfo:${s}`),Promise.resolve(!0)):(log$V.info(`[Engine] addDecal wiht id:[${e}], meshPath: ${o}, skinInfo:${s}`),new Promise((c,d)=>this._scenemanager.urlTransformer(o).then(_=>new Promise((b,k)=>{if(this._decal.get(e))b(!0);else{const j=new XDecal({id:e,scene:this.scene,meshPath:_,skinInfo:s});this._decal.set(e,j),j.loadModel().then(()=>{b(!0)}).catch($=>{log$V.error(`[Engine] addDecal Error! id: [${e}], meshpath:${o}, skin: ${s}. ${$}`),k(new XDecalError(`[Engine] addDecal Error! id: [${e}], meshpath:${o}, skin: ${s}. ${$}`))})}})).then(_=>{_==!0?c(!0):d(!1)}).catch(_=>{log$V.error(`[Engine] Add Decal error! id: [${e}], meshpath:${o}, skin:${s}. ${_}`),d(new XDecalError(`[Engine] addDecal error! id: [${e}], meshpath:${o}, skin:${s}. ${_}`))})))}setDecalTexture(i){const{id:e,buffer:o,isDynamic:s=!1,width:c=1100,height:d=25,slots:_=1,visibleSlots:b=1}=i,k=!0;return log$V.info(`[Engine] setDecalTexture wiht id:[${e}]`),new Promise((j,$)=>{const _e=this._decal.get(e);if(_e!=null)if(this._mat.get(e)!=null)this.changeDecalTexture({id:e,buffer:o,isUrl:k,isDynamic:s,width:c,height:d,slots:_,visibleSlots:b}),j(!0);else{const et=new XDecalMaterial(e,this.scene);et.setTexture(o,k,s,c,d,_,b).then(()=>{_e.setMat(et.getMat()),this._decal.set(e,_e),this._mat.set(e,et),j(!0)}).catch(tt=>{log$V.error("[Engine] setDecalTexture Error! "+tt),$(new XDecalTextureError(`[Engine] decal set texture error! ${tt}`))})}else log$V.error("[Engine] Error! decal id: ["+e+"] is not find!"),$(new XDecalTextureError(`[Engine] decal id: [${e}] is not find!`))})}async shareDecal(i){const{idTar:e,meshPath:o,idSrc:s,skinInfo:c="default"}=i;return this._decal.has(s)&&!this._decal.has(e)&&this._mat.has(s)&&!this._mat.has(e)?(log$V.info(`[Engine] shareDecal wiht idTar:[${e}], idSrc:[${s}], skinInfo: ${c}, meshPath: ${o}`),new Promise((d,_)=>this._scenemanager.urlTransformer(o).then(b=>{const k=new XDecal({id:e,scene:this.scene,meshPath:b,skinInfo:c}),j=this._mat.get(s);j!=null&&(k.setMat(j.getMat()),k.sourceMatId=s,this._decal.set(e,k),this.addSharedMatCount(s)),d(!0)}).catch(b=>{_(new XDecalError(`[Engine] decal shareDecal error! ${b}`))}))):(log$V.error(`[Engine] shareDecal Error. idSrc: [${s}] not exist! or idTar: [${e}] exists!`),Promise.reject(`[Engine] shareDecal Error. idSrc: [${s}] not exist! or idTar: [${e}] exists!`))}changeDecalModel(i){const{id:e,meshPath:o}=i,s=this._decal.get(e);return new Promise((c,d)=>s!=null?(log$V.info(`[Engine] changeDecalModel id:${e}`),s.changeModel(o).then(()=>{this._decal.set(e,s),c(!0)})):(log$V.warn(`[Engine] changeDecalModel id:${e} is not exist`),d(`[Engine] changeDecalModel id:${e} is not exist`)))}changeDecalTexture(i){const{id:e,buffer:o,isUrl:s=!1,isDynamic:c=!1,width:d=1110,height:_=25,slots:b=1,visibleSlots:k=1}=i,j=this._mat.get(e);j!=null&&this._decal.has(e)?(j.changeTexture(o,s,c,d,_,b,k),this._mat.set(e,j)):log$V.error(`[Engine] changeDecalTexture Error. id:${e} is not exist`)}deleteDecal(i){var e,o;if(this._decal.has(i)){const s=this._decal.get(i);s!=null&&s.cleanMesh(),this._sharedMat.get(i)!=null?this.minusSharedMatCount(i):this._mat.get(i)!=null?((e=this._mat.get(i))==null||e.cleanTexture(),this._mat.delete(i)):((o=s.sourceMatId)==null?void 0:o.length)>0&&this.minusSharedMatCount(s.sourceMatId),this._decal.delete(i)}}deleteDecalBySkinInfo(i){for(const[e,o]of this._decal.entries())o.skinInfo==i&&this.deleteDecal(e)}addSharedMatCount(i){const e=this._sharedMat.get(i);e!=null?this._sharedMat.set(i,e+1):this._sharedMat.set(i,1)}minusSharedMatCount(i){var o;const e=this._sharedMat.get(i);e!=null&&(this._sharedMat.set(i,e-1),e==0&&(this._sharedMat.delete(i),(o=this._mat.get(i))==null||o.cleanTexture(),this._mat.delete(i)))}toggle(i,e){const o=this._decal.get(i);o==null||o.toggle(e)}toggleDecalBySkinInfo(i,e){for(const[o,s]of this._decal.entries())s.skinInfo==i&&s.toggle(e)}updateTexAsWords(i,e,o={}){const{clearArea:s=!0,w:c=480,h:d=480,y:_=d/2,fontsize:b=70,slots:k=1,visibleSlots:j=1,font:$="black-body",color:_e="white",fontweight:et=100}=o;let{x:tt=c/2}=o;const rt=this._mat.get(i);if(rt){tt==-1&&(tt=(rt.getUOffset()+j/k)%1*c*k);const nt=rt.getMat().diffuseTexture,ot=nt.getContext();s&&ot.clearRect(tt-c/2,_-d/2,c,d),ot.textAlign="center",ot.textBaseline="middle",nt.drawText(e,tt,_,et+" "+b+"px "+$,_e,"transparent",!0),nt.hasAlpha=!0,nt.update()}}async updateTexAsImg(i,e,o={}){const{clearArea:s=!0,w:c=480,h:d=480,x:_=c/2,y:b=d/2,clearW:k=c,clearH:j=d}=o;return e==null||e==null||e==""?(log$V.error(`[Engine] updateTexAsImg Error. id: [${i}], newBuffer is Null or ""!`),Promise.reject(new XDecalError(`[Engine] updateTexAsImg Error. id: [${i}], newBuffer is Null or ""!`))):new Promise(($,_e)=>this._scenemanager.urlTransformer(e).then(et=>new Promise((tt,rt)=>{const it=this._mat.get(i);if(it){const ot=it.getMat().diffuseTexture;if(typeof e=="string"){const at=new Image;at.crossOrigin="anonymous",at.src=et,at.onload=()=>{const st=ot.getContext();s&&st.clearRect(_-k/2,b-j/2,k,j),st.drawImage(at,_-c/2,b-d/2,c,d),ot.update(),tt(!0)},at.onerror=()=>{log$V.error(`[Engine] updateTexAsImg Error.newImg load error. id: [${i}], decalMat is Null or undefined!`),rt(new XDecalError(`[Engine] updateTexAsImg Error. id: [${i}], decalMat is Null or undefined!`))}}else log$V.error(`[Engine] updateTexAsImg Error. id: [${i}], Buffer is not string!`),rt(new XDecalError(`[Engine] updateTexAsImg Error. id: [${i}], Buffer is not string!`))}else log$V.error(`[Engine] updateTexAsImg Error. id: [${i}], decalMat is Null or undefined!`),rt(new XDecalError(`[Engine] updateTexAsImg Error. id: [${i}], decalMat is Null or undefined!`))}).then(tt=>{tt==!0?$(!0):(log$V.error(`[Engine] updateTexAsImg Error. id: [${i}] !`),_e(new XDecalError(`[Engine] updateTexAsImg error! id: [${i}]`)))}).catch(tt=>{log$V.error(`[Engine] updateTexAsImg Error. id: [${i}]. ${tt}`)})))}startAnime(i,e){log$V.info(`[Engine] Decal Start Anime. [${i}]`);const{speed:o=.001,callback:s}=e,c=this._mat.get(i);c?(c.do_animation(o),s&&c.uOffsetObserverable.add(s)):(log$V.error(`[Engine] startAnime Error. id: [${i}] is not exist!`),new XDecalError(`[Engine] startAnime Error. id: [${i}] is not exist!`))}}class XDecalMaterial{constructor(i,e){ct(this,"_id");ct(this,"_tex");ct(this,"scene");ct(this,"_mat");ct(this,"_speed",.001);ct(this,"_slots",1);ct(this,"_visibleSlots",1);ct(this,"_isRegisterAnimation");ct(this,"_animeObserver",null);ct(this,"_uOffsetObserverable");ct(this,"reg_mat_update",()=>{const i=this._mat.diffuseTexture;i!=null&&(i.uOffset=i.uOffset+this._speed,i.uOffset>1&&(i.uOffset-=1),Math.round(i.uOffset%(1/this._slots)/this._speed)==0&&this._uOffsetObserverable.notifyObservers(this))});ct(this,"setTexture",async(i,e=!0,o=!1,s=1,c=1,d=1,_=1)=>new Promise((b,k)=>{this._slots=d,this._visibleSlots=_;const j=this._tex;o?(this._tex=new DynamicTexture("dyTex",{width:s,height:c},this.scene,!0,Texture.BILINEAR_SAMPLINGMODE),this._tex.name="decal_dy_"+this._id,this._tex.uScale=_/d,this._tex.vScale=-1,this._tex.vOffset=1,this._tex.wrapU=1,this._mat.emissiveColor=new Color3(.95,.95,.95),this._mat.diffuseTexture=this._tex,this._mat.diffuseTexture.hasAlpha=!0,this._mat.useAlphaFromDiffuseTexture=!0,this._mat.backFaceCulling=!1,this._mat.transparencyMode=Material.MATERIAL_ALPHATEST,j!=null&&j.dispose(),b(!0)):!o&&e&&typeof i=="string"?this._tex=new Texture(i,this.scene,!0,!1,Texture.BILINEAR_SAMPLINGMODE,()=>{this._tex.name="decal_"+this._id,this._mat.emissiveTexture=this._tex,this._mat.diffuseTexture=this._tex,this._mat.diffuseTexture.hasAlpha=!0,this._mat.useAlphaFromDiffuseTexture=!0,this._mat.transparencyMode=Material.MATERIAL_ALPHATEST,j!=null&&j.dispose(),b(!0)},()=>{log$V.error("[Engine] decal create texture error!"),k(new XDecalTextureError("[Engine] decal create texture error!"))},null,!0):this._tex=new Texture("data:decal_"+this._id,this.scene,!0,!1,Texture.BILINEAR_SAMPLINGMODE,()=>{this._tex.name="decal_"+this._id,this._mat.emissiveTexture=this._tex,this._mat.diffuseTexture=this._tex,this._mat.diffuseTexture.hasAlpha=!0,this._mat.useAlphaFromDiffuseTexture=!0,this._mat.transparencyMode=Material.MATERIAL_ALPHATEST,j!=null&&j.dispose(),b(!0)},()=>{log$V.error("[Engine] decal create texture error!"),k(new XDecalTextureError("[Engine] decal create texture error!"))},i,!0)}));this._id=i,this.scene=e,this._mat=new StandardMaterial("decalMat_"+this._id,this.scene),this._isRegisterAnimation=!1,this._uOffsetObserverable=new Observable}get uOffsetObserverable(){return this._uOffsetObserverable}getMat(){return this._mat}set speed(i){this._speed=i}getUOffset(){return this._tex.uOffset}do_animation(i){this._speed=i,this._isRegisterAnimation==!1&&(this._isRegisterAnimation=!0,this._animeObserver=this.scene.onBeforeRenderObservable.add(()=>{this.reg_mat_update()}))}changeTexture(i,e=!1,o=!1,s=1,c=1,d=1,_=1){return this._mat==null||this._tex==null?(log$V.error("[Engine] Decal Mat is null or tex is null"),Promise.reject(new XDecalTextureError("[Engine] Decal Mat is null or tex is null"))):this.setTexture(i,e,o,s,c,d,_)}cleanTexture(){log$V.info("[Engine] Decal clean Texture"),this.scene.onBeforeRenderObservable.remove(this._animeObserver),this._uOffsetObserverable.clear(),this._tex.dispose(),this._mat.dispose()}}class XDecal{constructor(i){ct(this,"_id");ct(this,"meshPath");ct(this,"_low_model",[]);ct(this,"_mat",null);ct(this,"scene");ct(this,"_skinInfo");ct(this,"sourceMatId","");ct(this,"loadModel",async()=>new Promise((i,e)=>{typeof this.meshPath=="string"?SceneLoader.LoadAssetContainerAsync("",this.meshPath,this.scene,null,".glb").then(o=>{for(let s=o.materials.length-1;s>=0;--s)o.materials[s].dispose();for(let s=0;s<o.meshes.length;++s)o.meshes[s].visibility=1,o.meshes[s].isPickable=!0,o.meshes[s].checkCollisions=!1,"hasVertexAlpha"in o.meshes[s]&&(o.meshes[s].hasVertexAlpha=!1),this.scene.addMesh(o.meshes[s]),this._low_model.push(new XStaticMesh({id:this._id,mesh:o.meshes[s],xtype:EMeshType.Decal,skinInfo:this._skinInfo})),this.toggle(!1);i(!0)}).catch(o=>{e(new XDecalError(`[Engine] decal load model error! ${o}`))}):e(new XDecalError("[Engine] decal inport mesh is not string!"))}).catch(i=>{new XDecalError(`[Engine] decal loadModel ${i}`)}));const{id:e,scene:o,meshPath:s,skinInfo:c="default"}=i;this._id=e,this.scene=o,this.meshPath=s,this._skinInfo=c}get skinInfo(){return this._skinInfo}getMesh(){return this._low_model}getMat(){return this._mat}get id(){return this._id}toggle(i){for(let e=0;e<this._low_model.length;++e)i==!0?this._low_model[e].show():this._low_model[e].hide()}setMat(i){this._mat=i;for(let e=0;e<this._low_model.length;++e)this._low_model[e].mesh.material=this._mat;this.toggle(!0)}changeModel(i=""){return i!=""&&(this.meshPath=i),this.meshPath==""?(log$V.error("[Engine] changeModel Error! meshPath is empty"),Promise.reject(new XDecalTextureError("[Engine] changeModel Error! meshPath is empty"))):new Promise((e,o)=>SceneLoader.LoadAssetContainerAsync("",this.meshPath,this.scene,null,".glb").then(s=>{for(let d=s.materials.length-1;d>=0;--d)s.materials[d].dispose();const c=[];for(let d=0;d<s.meshes.length;++d)s.meshes[d].visibility=0,s.meshes[d].isPickable=!0,s.meshes[d].checkCollisions=!1,"hasVertexAlpha"in s.meshes[d]&&(s.meshes[d].hasVertexAlpha=!1),this._mat!=null&&(s.meshes[d].material=this._mat),this.scene.addMesh(s.meshes[d]),c.push(new XStaticMesh({id:this._id,mesh:s.meshes[d],xtype:EMeshType.Decal,skinInfo:this._skinInfo}));i!=""&&this.cleanMesh(),this._low_model=c,this._mat!=null&&this.toggle(!0),e(this)}).catch(s=>{log$V.error("[Engine] Create decal error! "+s),o(new XDecalError("[Engine] Create decal error! "+s))}))}cleanMesh(i=!1,e=!1){log$V.info("[Engine] Decal Model clean mesh");for(let o=0;o<this._low_model.length;++o)this._low_model[o].dispose(i,e)}}const log$U=new Logger$1("XBreathPointManager");class XBreathPointManager{constructor(i){ct(this,"_scene");ct(this,"materialMap",new Map);ct(this,"breathPoints",new Map);ct(this,"_sceneManager");ct(this,"_allIds",new Set);ct(this,"_loopBPKeys",[]);ct(this,"addBreathPoint",async i=>{const e=[{url:"https://static.xverse.cn/qqktv/texture.png"}];if(e.length<=0){log$U.warn("[Engine] BreathPoint get texture list error: textureList.length <= 0"),new XBreathPointError("[Engine] BreathPoint get texture list error!");return}const o=e[0],{id:s,spriteSheet:c=o.url,spriteWidthNumber:d=20,spriteHeightNumber:_=1,position:b,rotation:k={pitch:-90,yaw:270,roll:0},size:j=.6,width:$=-1,height:_e=-1,fps:et=30,billboardMode:tt=!1,forceLeaveGround:rt=!1,type:it="default",lifeTime:nt=-1,backfaceculling:ot=!0,maxVisibleRegion:at=-1,skinInfo:st="default"}=i;if(this.breathPoints.get(s)){log$U.warn("[Engine] Cannot add breathPoint with an existing id: ["+s+"]"),new XBreathPointError("[Engine] Cannot add breathPoint with an existing id: ["+s+"]");return}if(rt){const gt=this.castRay(new Vector3(b.x,b.y,b.z))*scaleFromUE4toXverse;gt!=0?b.z=b.z-gt+1:b.z=b.z+1}let ut;if(this.materialMap.get(it)){const gt=this.materialMap.get(it);gt.count=gt.count+1,ut=gt.mat}else{const gt=new Texture(c,this._scene,!0,!0,Texture.BILINEAR_SAMPLINGMODE,null,()=>{log$U.error("[Engine] Breathpoint create texture error."),new XBreathPointError("[Engine] Breathpoint create texture error.")},null,!0);gt.name="TexBreathPoint_"+s,ut=new StandardMaterial(`MaterialBreathPoint_${s}`,this._scene),ut.alpha=1,ut.emissiveTexture=gt,ut.backFaceCulling=ot,ut.diffuseTexture=gt,ut.diffuseTexture.hasAlpha=!0,ut.useAlphaFromDiffuseTexture=!0,this.materialMap.set(it,{mat:ut,count:1,lastRenderTime:Date.now(),fps:et,spriteWidthNumber:d,spriteHeightNumber:_,spriteSheet:c,texture:gt})}const ft=new Array(6);for(let gt=0;gt<6;gt++)ft[gt]=new Vector4(0,0,0,0);ft[0]=new Vector4(0,0,1/d,1/_),ft[1]=new Vector4(0,0,1/d,1/_);let lt={};$>0&&_e>0?lt={width:$,height:_e,depth:.01,faceUV:ft}:lt={size:j,depth:.01,faceUV:ft};const ht=MeshBuilder.CreateBox(s,lt,this._scene);ht.material=ut;const pt=new XStaticMesh({id:s,mesh:ht,xtype:EMeshType.XBreathPoint,skinInfo:st});let mt=k;tt&&(ht.billboardMode=Mesh.BILLBOARDMODE_ALL,pt.allowMove(),mt={pitch:0,yaw:270,roll:0});const dt=new BreathPoint$1({type:it,mesh:pt,id:s,position:b,rotation:mt,mat:ut,maxVisibleRegion:at,scene:this._scene,skinInfo:st});this.breathPoints.set(s,dt),this._allIds.add(s),nt>0&&setTimeout(()=>{this.clearBreathPoints(s)},nt*1e3)});ct(this,"reg_breathpoint_update",()=>{const i=new Date().getTime();if(this.materialMap!=null)for(const[e,o]of this.materialMap)i-o.lastRenderTime>1e3/o.fps&&(o.lastRenderTime=i,Math.abs(o.mat.diffuseTexture.uOffset-(1-1/o.spriteWidthNumber))<1e-6?(o.mat.diffuseTexture.uOffset=0,Math.abs(o.mat.diffuseTexture.vOffset-(1-1/o.spriteHeightNumber))<1e-6?o.mat.diffuseTexture.vOffset=0:o.mat.diffuseTexture.vOffset+=1/o.spriteHeightNumber):o.mat.diffuseTexture.uOffset+=1/o.spriteWidthNumber)});ct(this,"reg_breathpoint_autovisible",()=>{if(this._scene.getFrameId()%2==0)if(this._loopBPKeys.length==0)this._loopBPKeys=Array.from(this._allIds);else{const i=this._getMainPlayerPosition();for(let e=0;e<5&&this._loopBPKeys.length>0;++e){const o=this._loopBPKeys.pop();if(o!=null){const s=this.getBreathPoint(o);if(s!=null&&s.maxvisibleregion>=0&&s.mesh.visibility==1){const c=s.mesh.position;calcDistance3DVector(i,c)>=s.maxvisibleregion?s==null||s.removeFromScene():s==null||s.addToScene()}}}}});this._sceneManager=i,this._scene=i.Scene,this._scene.registerBeforeRender(this.reg_breathpoint_update),this._scene.registerBeforeRender(this.reg_breathpoint_autovisible)}setAllBreathPointVisibility(i){for(const[e,o]of this.breathPoints.entries())o.toggleVisibility(i)}toggleBPVisibilityBySkinInfo(i,e){for(const[o,s]of this.breathPoints.entries())s.skinInfo==i&&s.toggleVisibility(e)}toggleBPVisibilityById(i,e){const o=this.getBreathPoint(i);o!=null&&o.toggleVisibility(e)}getBreathPointBySkinInfo(i){const e=[];for(const[o,s]of this.breathPoints.entries())s.skinInfo==i&&e.push(s);return e}getAllBreathPoint(){return this.breathPoints}getBreathPoint(i){return this.breathPoints.get(i)}delete(i){const e=this.breathPoints.get(i);if(e!=null){e.dispose(),this._allIds.delete(i);const o=this.materialMap.get(e._type);o!=null&&(o.count=o.count-1,o.count<=0&&(o.count=0,o.texture.dispose(),o.mat.dispose(!0,!0),this.materialMap.delete(e._type))),this.breathPoints.delete(i)}}castRay(i){var _;i=ue4Position2Xverse({x:i.x,y:i.y,z:i.z});const e=new Vector3(0,-1,0),o=new Ray(i,e,length),s=[],c=(_=this._sceneManager)==null?void 0:_.getGround({x:i.x,y:i.y,z:i.z});let d=o.intersectsMeshes(c);if(d.length>0){const b=d[0];if(b&&b.pickedMesh){const k=b.distance;e.y=1;const j=o.intersectsMeshes(s);let $=1e8;if(j.length>0){const _e=j[0];return _e&&_e.pickedMesh&&($=-_e.distance),$==1e8?k:Math.abs($)<Math.abs(k)?$:k}}}else if(e.y=1,d=o.intersectsMeshes(s),d.length>0){const b=d[0];if(b&&b.pickedMesh)return b.distance}return 0}changePickable(i){for(const[e,o]of this.breathPoints.entries())o.changePickable(i)}clearBreathPoints(i){log$U.info(`[Engine] clearBreathPoints: ${i}`);for(const[e,o]of this.breathPoints.entries())(o._type==i||o._id==i)&&this.delete(o._id)}clearBreathPointsBySkinInfo(i){log$U.info(`[Engine] clearBreathPointsBySkinInfo: ${i}`);for(const[e,o]of this.breathPoints.entries())o.skinInfo==i&&this.delete(o._id)}clearAllBreathPoints(){log$U.info("[Engine] ClearAllBreathPoints");for(const[i,e]of this.breathPoints.entries())this.delete(e._id)}_getMainPlayerPosition(){var o;const i=this._sceneManager.cameraComponent.MainCamera.position,e=this._sceneManager.avatarComponent.getMainAvatar();if(e!=null&&e!=null){const s=(o=e==null?void 0:e.rootNode)==null?void 0:o.position;if(s!=null)return s}return i}changeBreathPointPose(i,e,o){const s=new Vector3(i.position.x,i.position.y,i.position.z);if(this.breathPoints.get(o)!=null){log$U.info(`[Engine] changeBreathPointPose, id:${o}`);const c=this.breathPoints.get(o),d=c.mesh.position;let _=d.subtract(s);_=Vector3.Normalize(_);const b=Vector3.Distance(d,s),k=new Ray(s,_,b),j=this._scene.multiPickWithRay(k);if(j){for(let $=0;$<j.length;$++)if(j[$].pickedMesh!=null&&e.mesh.name.indexOf(j[$].pickedMesh.name)>=0){const _e=j[$].pickedPoint;c.mesh.position=s.add(_e.subtract(s).scale(.99)),this.breathPoints.set(o,c)}}}else log$U.warn(`[Engine] changeBreathPointPose, id:${o} is not existing!`)}}class BreathPoint$1{constructor(i){ct(this,"_staticmesh");ct(this,"_id");ct(this,"_mat");ct(this,"_type");ct(this,"_maxVisibleRegion");ct(this,"_skinInfo");ct(this,"_scene");ct(this,"_isInScene");const{mesh:e,id:o,position:s,rotation:c,mat:d,type:_="default",maxVisibleRegion:b=-1,scene:k,skinInfo:j="default"}=i;this._id=o,e.mesh.position=ue4Position2Xverse(s),e.mesh.rotation=ue4Rotation2Xverse(c),this._staticmesh=e,this._mat=d,this._type=_,this._maxVisibleRegion=b,this._scene=k,this._skinInfo=j,this._isInScene=!0}get isInScene(){return this._isInScene}get skinInfo(){return this._skinInfo}get maxvisibleregion(){return this._maxVisibleRegion}getMesh(){return this._staticmesh}get mesh(){return this._staticmesh.mesh}toggleVisibility(i){i==!0?this._staticmesh.show():this._staticmesh.hide()}changePickable(i){this._staticmesh.mesh.isPickable=i}removeFromScene(){this._isInScene&&(this._staticmesh.mesh!=null&&this._scene.removeMesh(this._staticmesh.mesh),this._isInScene=!1)}addToScene(){this._isInScene==!1&&(this._staticmesh.mesh!=null&&this._scene.addMesh(this._staticmesh.mesh),this._isInScene=!0)}dispose(){var i;(i=this._staticmesh.mesh)==null||i.dispose(!1,!1)}set position(i){this._staticmesh.mesh.position=ue4Position2Xverse(i)}get position(){return xversePosition2Ue4(this._staticmesh.mesh.position)}set rotation(i){this._staticmesh.mesh.rotation=ue4Rotation2Xverse(i)}get rotation(){return xverseRotation2Ue4(this._staticmesh.mesh.rotation)}}var pureVideoFragment=`precision highp float;
  10940. varying vec3 ModelPos;
  10941. uniform float isYUV; // false: 0, true: 1.0
  10942. uniform sampler2D texture_video;
  10943. // uniform sampler2D chrominanceYTexture;
  10944. // uniform sampler2D chrominanceUTexture;
  10945. // uniform sampler2D chrominanceVTexture;
  10946. uniform float haveShadowLight;
  10947. varying vec4 vPositionFromLight;
  10948. uniform float fireworkLight;
  10949. varying float fireworkDistance;
  10950. varying float fireworkCosTheta;
  10951. uniform sampler2D shadowSampler;
  10952. // uniform float focal;
  10953. // uniform float captureWidth;
  10954. // uniform float captureHeight;
  10955. uniform vec3 focal_width_height;
  10956. const float inv_2_PI = 0.1591549; // 1 / (2 * pi)
  10957. const float inv_PI = 0.3183099; // 1 / ( pi)
  10958. const vec2 invAtan = vec2(0.1591549, 0.3183099);
  10959. float unpack(vec4 color)
  10960. {
  10961. const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  10962. return dot(color, bit_shift);
  10963. }
  10964. float ShadowCalculation(vec4 vPositionFromLight, sampler2D ShadowMap)
  10965. {
  10966. vec3 projCoords = vPositionFromLight.xyz / vPositionFromLight.w;
  10967. vec3 depth = 0.5 * projCoords + vec3(0.5);
  10968. vec2 uv = depth.xy;
  10969. if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0)
  10970. {
  10971. return 1.0;
  10972. }
  10973. #ifndef SHADOWFULLFLOAT
  10974. float shadow = unpack(texture2D(ShadowMap, uv));
  10975. #else
  10976. float shadow = texture2D(ShadowMap, uv).x;
  10977. #endif
  10978. if (depth.z > shadow - 1e-4)
  10979. {
  10980. return 0.7;
  10981. }
  10982. else
  10983. {
  10984. return 1.0;
  10985. }
  10986. }
  10987. // const float f = 514.133282; //937.83246;
  10988. // const float w = 720.0;
  10989. // const float h = 1280.0;
  10990. // vec2 SampleTex(vec3 pt3d, vec2 widthHeight)
  10991. vec2 SampleTex(vec3 pt3d)
  10992. {
  10993. // // vec2 uv = vec2( f/w*pt3d.x/pt3d.z, f/h*pt3d.y/pt3d.z ); // \u6A21\u578B\u53D8\u6362\u5230\u76F8\u673A\u5750\u6807\u7CFB\u4E0B
  10994. // vec2 uv = vec2( focal/captureWidth*pt3d.x/pt3d.z, focal/captureHeight*pt3d.y/pt3d.z ); // \u6A21\u578B\u53D8\u6362\u5230\u76F8\u673A\u5750\u6807\u7CFB\u4E0B
  10995. // uv.x = uv.x + 0.5;
  10996. // uv.y = uv.y + 0.5;
  10997. // return uv;
  10998. return focal_width_height.x / focal_width_height.yz *pt3d.xy/pt3d.z + 0.5;
  10999. }
  11000. void main()
  11001. {
  11002. vec3 yuv;
  11003. vec3 rgb;
  11004. vec2 uv;
  11005. vec3 color = vec3(0,0,0);
  11006. vec3 flash_color = fireworkLight * 1000.0 / fireworkDistance * fireworkCosTheta * vec3(1,0,0);
  11007. float shadow = 1.0;
  11008. if (haveShadowLight > 0.5)
  11009. {
  11010. shadow = ShadowCalculation(vPositionFromLight, shadowSampler);
  11011. }
  11012. // uv = SampleTex( normalize(ModelPos), vec2(captureWidth, captureHeight));
  11013. uv = SampleTex( normalize(ModelPos) );
  11014. if( isYUV < 0.5 )
  11015. {
  11016. color = texture2D(texture_video, uv).rgb;
  11017. }else{
  11018. const mat4 YUV2RGB = mat4
  11019. (
  11020. 1.1643828125, 0, 1.59602734375, -.87078515625,
  11021. 1.1643828125, -.39176171875, -.81296875, .52959375,
  11022. 1.1643828125, 2.017234375, 0, -1.081390625,
  11023. 0, 0, 0, 1
  11024. );
  11025. vec4 result = vec4(
  11026. texture2D(texture_video, vec2(uv.x, uv.y*0.666666 + 0.333333 ) ).x,
  11027. texture2D(texture_video, vec2(uv.x * 0.5, uv.y*0.333333 ) ).x,
  11028. texture2D(texture_video, vec2(0.5 + uv.x * 0.5, uv.y*0.333333 ) ).x,
  11029. 1) * YUV2RGB;
  11030. color = clamp(result.rgb, 0.0, 1.0);
  11031. }
  11032. if( uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 )
  11033. {
  11034. color = vec3(0,0,0);
  11035. }
  11036. // gl_FragColor = vec4(shadow, shadow, shadow, 1.0);
  11037. gl_FragColor = vec4(shadow * (color + flash_color) * 1.0, 1.0);
  11038. }
  11039. `,pureVideoVertex=`precision highp float;
  11040. varying vec3 ModelPos;
  11041. varying vec4 vPositionFromLight;
  11042. varying float fireworkDistance;
  11043. varying float fireworkCosTheta;
  11044. attribute vec2 uv;
  11045. attribute vec3 position;
  11046. attribute vec4 world0;
  11047. attribute vec4 world1;
  11048. attribute vec4 world2;
  11049. attribute vec4 world3;
  11050. #ifdef NORMAL
  11051. attribute vec3 normal;
  11052. #endif
  11053. uniform vec3 fireworkLightPosition;
  11054. uniform mat4 view;
  11055. uniform mat4 projection;
  11056. uniform mat4 lightSpaceMatrix;
  11057. uniform mat4 world;
  11058. uniform mat4 worldViewProjection;
  11059. float DistanceCalculation(vec3 Q, vec3 P)
  11060. {
  11061. return (Q.x - P.x) * (Q.x - P.x) + (Q.y - P.y) * (Q.y - P.y) + (Q.z - P.z) * (Q.z - P.z);
  11062. }
  11063. float CosThetaCalculation(vec3 Q, vec3 P)
  11064. {
  11065. return max(0.,dot(Q, P));
  11066. }
  11067. void main()
  11068. {
  11069. #include<instancesVertex>
  11070. vPositionFromLight = lightSpaceMatrix * finalWorld * vec4(position, 1.0);
  11071. // fireworkDistance = DistanceCalculation(vec3(finalWorld * vec4(position, 1.0)), fireworkLightPosition);
  11072. fireworkDistance = distance(vec3(finalWorld * vec4(position, 1.0)), fireworkLightPosition);
  11073. fireworkCosTheta = 1.0;
  11074. #ifdef NORMAL
  11075. vec3 directionFirework = fireworkLightPosition.xyz - vec3(finalWorld * vec4(position, 1.0));
  11076. directionFirework = normalize(directionFirework);
  11077. // directionFirework = directionFirework / (directionFirework.x * directionFirework.x + directionFirework.y * directionFirework.y + directionFirework.z * directionFirework.z);
  11078. fireworkCosTheta = CosThetaCalculation(directionFirework, normal);
  11079. #endif
  11080. ModelPos = vec3( view * finalWorld * vec4(position , 1.0));
  11081. gl_Position = projection * view * finalWorld * vec4(position , 1.0);
  11082. }
  11083. `,panoFragment=`precision highp float;
  11084. uniform float isYUV; // false: 0, true: 1.0
  11085. varying vec2 TexCoords;
  11086. varying vec3 WorldPos;
  11087. varying vec3 vNormal;
  11088. uniform float haveShadowLight;
  11089. varying vec4 vPositionFromLight;
  11090. uniform float fireworkLight;
  11091. varying float fireworkDistance;
  11092. varying float fireworkCosTheta;
  11093. uniform sampler2D shadowSampler;
  11094. uniform vec3 centre_pose;
  11095. uniform sampler2D texture_pano;
  11096. const float inv_2_PI = 0.1591549; // 1 / (2 * pi)
  11097. const float inv_PI = 0.3183099; // 1 / ( pi)
  11098. const vec2 invAtan = vec2(0.1591549, 0.3183099);
  11099. float unpack(vec4 color)
  11100. {
  11101. const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  11102. return dot(color, bit_shift);
  11103. }
  11104. float ShadowCalculation(vec4 vPositionFromLight, sampler2D ShadowMap)
  11105. {
  11106. vec3 projCoords = vPositionFromLight.xyz / vPositionFromLight.w;
  11107. vec3 depth = 0.5 * projCoords + vec3(0.5);
  11108. vec2 uv = depth.xy;
  11109. if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0)
  11110. {
  11111. return 1.0;
  11112. }
  11113. #ifndef SHADOWFULLFLOAT
  11114. float shadow = unpack(texture2D(ShadowMap, uv));
  11115. #else
  11116. float shadow = texture2D(ShadowMap, uv).x;
  11117. #endif
  11118. if (depth.z > shadow)
  11119. {
  11120. return 0.7;
  11121. }
  11122. else
  11123. {
  11124. return 1.0;
  11125. }
  11126. }
  11127. vec2 SampleSphericalMap(vec3 pt3d)
  11128. {
  11129. vec2 uv = vec2( atan(-pt3d.z,pt3d.x), atan( pt3d.y, sqrt(pt3d.x*pt3d.x + pt3d.z * pt3d.z)));
  11130. uv.x = 0.5 + uv.x * inv_2_PI ; // yaw: \u6C34\u5E73\u65B9\u5411 \uFF0C0 \u5230 360 \uFF0C \u5BF9\u5E948k\u7684\u5BBD
  11131. uv.y = 0.5 + uv.y * inv_PI ; // pitch: \u7AD6\u76F4\u65B9\u5411\uFF0C -64 \u5230 64 \uFF0C\u5BF9\u5E944k\u7684\u957F
  11132. return vec2(uv.x,uv.y);
  11133. }
  11134. vec3 fitUint8Range(vec3 color)
  11135. {
  11136. if( color.x < 0.0 ){color.x = 0.0;}
  11137. if( color.x > 1.0 ){color.x = 1.0;}
  11138. if( color.y < 0.0 ){color.y = 0.0;}
  11139. if( color.y > 1.0 ){color.y = 1.0;}
  11140. if( color.z < 0.0 ){color.z = 0.0;}
  11141. if( color.z > 1.0 ){color.z = 1.0;}
  11142. return color;
  11143. }
  11144. void main()
  11145. {
  11146. // // Debug
  11147. // vec3 vLightPosition = vec3(0,10,100);
  11148. // // World values
  11149. // vec3 vPositionW = vec3( WorldPos.x, WorldPos.y, WorldPos.z );
  11150. // vec3 vNormalW = normalize( vNormal) ;
  11151. // vec3 viewDirectionW = normalize(vPositionW);
  11152. // // Light
  11153. // vec3 lightVectorW = normalize(vLightPosition - vPositionW);
  11154. // // diffuse
  11155. // float ndl = max(0., dot(vNormalW, lightVectorW));
  11156. // gl_FragColor = vec4( ndl, ndl, ndl, 1.);
  11157. vec2 uv;
  11158. vec3 color = vec3(0,0,0);
  11159. vec3 flash_color = fireworkLight * 1000.0 / fireworkDistance * fireworkCosTheta * vec3(1,0,0);
  11160. float shadow = 1.0;
  11161. if (haveShadowLight > 0.5)
  11162. {
  11163. shadow = ShadowCalculation(vPositionFromLight, shadowSampler);
  11164. }
  11165. uv = SampleSphericalMap(normalize( WorldPos - centre_pose ));
  11166. if( isYUV < 0.5 )
  11167. {
  11168. color = texture2D(texture_pano, uv).rgb;
  11169. }else{
  11170. const mat4 YUV2RGB = mat4
  11171. (
  11172. 1.1643828125, 0, 1.59602734375, -.87078515625,
  11173. 1.1643828125, -.39176171875, -.81296875, .52959375,
  11174. 1.1643828125, 2.017234375, 0, -1.081390625,
  11175. 0, 0, 0, 1
  11176. );
  11177. vec4 result = vec4(
  11178. texture2D(texture_pano, vec2(uv.x, uv.y*0.666666 + 0.333333 ) ).x,
  11179. texture2D(texture_pano, vec2(uv.x * 0.5, uv.y*0.333333 ) ).x,
  11180. texture2D(texture_pano, vec2(0.5 + uv.x * 0.5, uv.y*0.333333 ) ).x,
  11181. 1) * YUV2RGB;
  11182. color = fitUint8Range(result.rgb);
  11183. }
  11184. if( uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 )
  11185. {
  11186. color = vec3(0,0,0);
  11187. }
  11188. gl_FragColor = vec4( shadow * (color + flash_color), 1.0);
  11189. }`,panoVertex=`precision highp float;
  11190. varying vec2 TexCoords;
  11191. varying vec3 vNormal;
  11192. varying vec3 WorldPos;
  11193. varying vec4 vPositionFromLight;
  11194. varying float fireworkDistance;
  11195. varying float fireworkCosTheta;
  11196. uniform vec3 fireworkLightPosition;
  11197. uniform mat4 lightSpaceMatrix;
  11198. attribute vec3 normal;
  11199. attribute vec2 uv;
  11200. attribute vec3 position;
  11201. uniform mat4 view;
  11202. uniform mat4 projection;
  11203. uniform mat4 world;
  11204. uniform mat4 worldViewProjection;
  11205. attribute vec4 world0;
  11206. attribute vec4 world1;
  11207. attribute vec4 world2;
  11208. attribute vec4 world3;
  11209. float DistanceCalculation(vec3 Q, vec3 P)
  11210. {
  11211. return (Q.x - P.x) * (Q.x - P.x) + (Q.y - P.y) * (Q.y - P.y) + (Q.z - P.z) * (Q.z - P.z);
  11212. }
  11213. float CosThetaCalculation(vec3 Q, vec3 P)
  11214. {
  11215. return max(0.,dot(Q, P));
  11216. }
  11217. void main()
  11218. {
  11219. #include<instancesVertex>
  11220. vPositionFromLight = lightSpaceMatrix * world * vec4(position, 1.0);
  11221. fireworkDistance = DistanceCalculation(vec3(finalWorld * vec4(position, 1.0)), fireworkLightPosition);
  11222. fireworkCosTheta = 1.0;
  11223. vec3 newP = vec3( finalWorld * vec4(position, 1.0) );
  11224. WorldPos = newP;
  11225. TexCoords = uv;
  11226. vNormal = normal;
  11227. gl_Position = projection * view * vec4(newP , 1.0);
  11228. }
  11229. `;class XVideoRawYUV{constructor(i,e){ct(this,"scene");ct(this,"_videoRawYUVTexture");ct(this,"videosResOriArray");ct(this,"_currentVideoId");this.scene=i,this._videoRawYUVTexture=[],this.videosResOriArray=e,this._currentVideoId=-1;for(let o=0;o<e.length;++o)(s=>{const c=RawTexture.CreateLuminanceTexture(null,e[s].width,e[s].height*1.5,this.scene,!1,!0);c.name="videoTex_"+e[s].width+"_"+e[s].height,this._videoRawYUVTexture.push(c)})(o)}inRange(i){return i>=0&&i<this._videoRawYUVTexture.length}getVideoYUVTex(i){return this.inRange(i)?this._videoRawYUVTexture[i]:null}findId(i,e){let o=0;for(let s=0;s<this.videosResOriArray.length;++s)if(this.videosResOriArray[s].width==i&&this.videosResOriArray[s].height==e){o=s;break}return o}getCurrentVideoTexId(){return this._currentVideoId}setCurrentVideoTexId(i){this._currentVideoId=i}}const log$T=new Logger$1("XMaterial");var EShaderMode=(a=>(a[a.default=0]="default",a[a.video=1]="video",a[a.videoAndPano=2]="videoAndPano",a))(EShaderMode||{});class XMaterialComponent{constructor(i,e){ct(this,"scene");ct(this,"engine");ct(this,"yuvInfo");ct(this,"shaderMode");ct(this,"_panoInfo");ct(this,"_dynamic_size");ct(this,"_dynamic_babylonpose");ct(this,"_dynamic_textures");ct(this,"_dynamic_shaders");ct(this,"_scenemanager");ct(this,"_videoTexture");ct(this,"_videoElement");ct(this,"_lowModelShader");ct(this,"_defaultShader");ct(this,"_inputYUV420",!0);ct(this,"_inputPanoYUV420",!0);ct(this,"_videoRawYUVTexArray");ct(this,"_isUpdateYUV",!0);ct(this,"initMaterial",async()=>new Promise((i,e)=>{this._initDefaultShader(),this.shaderMode==2?this.initDynamicData(this._panoInfo.dynamicRange,this._panoInfo.width,this._panoInfo.height).then(()=>{this._initPureVideoShader(),this._prepareRender(this.yuvInfo)}):this.shaderMode==1?(this._initPureVideoShader(),this._prepareRender(this.yuvInfo)):this.shaderMode==0,i(!0)}));ct(this,"_initPureVideoContent",i=>{this._inputYUV420?this._videoRawYUVTexArray.getVideoYUVTex(0)!=null&&(this._lowModelShader.setTexture("texture_video",this._videoRawYUVTexArray.getVideoYUVTex(0)),this._lowModelShader.setFloat("isYUV",1),Texture.WhenAllReady([this._videoRawYUVTexArray.getVideoYUVTex(0)],()=>{this._changePureVideoLowModelShaderCanvasSize(i)})):(this._videoElement=i.videoElement,this._videoTexture||(this._videoTexture=new VideoTexture("InterVideoTexture",this._videoElement,this.scene,!0,!1)),Texture.WhenAllReady([this._videoTexture],()=>{this._changePureVideoLowModelShaderCanvasSize({width:this._videoElement.height,height:this._videoElement.width,fov:i.fov})}),this._lowModelShader.setTexture("texture_video",this._videoTexture),this._lowModelShader.setFloat("isYUV",0))});ct(this,"_changePureVideoLowModelShaderCanvasSize",i=>{var d;const e=i.fov||50,o=i.width||720,s=i.height||1280,c=o/(2*Math.tan(Math.PI*e/360));(d=this._lowModelShader)==null||d.setVector3("focal_width_height",new Vector3(c,o,s))});ct(this,"updateRawYUVData",(i,e,o,s=-1)=>{var c,d;if(s==-1&&(s=this.yuvInfo.fov),this._isUpdateYUV==!0){const _={width:e,height:o,fov:s},b=this._videoRawYUVTexArray.findId(e,o),k=this._videoRawYUVTexArray.getCurrentVideoTexId();(k<0||b!=k||s!=this.yuvInfo.fov)&&(this.yuvInfo.width=e,this.yuvInfo.height=o,this.yuvInfo.fov=s,this._videoRawYUVTexArray.setCurrentVideoTexId(b),this._changeVideoRes(b),this.changeCameraFovWithShaderUpdate(_),this._scenemanager.yuvInfo=_),(c=this._videoRawYUVTexArray.getVideoYUVTex(b))==null||c.update(i),(d=this._videoRawYUVTexArray.getVideoYUVTex(b))==null||d.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE)}});ct(this,"_changeVideoRes",i=>{this._lowModelShader.setTexture("texture_video",this._videoRawYUVTexArray.getVideoYUVTex(i))});ct(this,"initDynamicData",(i,e,o)=>new Promise((s,c)=>{this.setDynamicSize(i).then(d=>{if(d){for(let _=0;_<i;++_)(b=>{this.initDynamicTexture(b,e,o),this.initDynamicShaders(b).then(()=>{this._updatePanoShaderInput(b)})})(_);s(!0)}else c(new XMaterialError(`[Engine] DynamicRoomSize (${i}) is too small`))})}).catch(s=>log$T.error(`[Engine] ${s}`)));ct(this,"_initDefaultShader",()=>{this._defaultShader==null&&(this._defaultShader=new GridMaterial("GridShader",this.scene),this._defaultShader.gridRatio=50,this._defaultShader.lineColor=new Color3(0,0,.5),this._defaultShader.majorUnitFrequency=1,this._defaultShader.mainColor=new Color3(.6,.6,.6),this._defaultShader.backFaceCulling=!1)});ct(this,"_initPureVideoShader",()=>{if(this._lowModelShader==null){const i=new ShaderMaterial("PureVideoShader",this.scene,{vertexSource:pureVideoVertex,fragmentSource:pureVideoFragment},{attributes:["uv","position","world0","world1","world2","world3"],uniforms:["view","projection","worldViewProjection","world"],defines:["#define SHADOWFULLFLOAT"]});i.setTexture("shadowSampler",null),i.setMatrix("lightSpaceMatrix",null),i.setFloat("haveShadowLight",0),i.setTexture("texture_video",null),i.setFloat("isYUV",this._inputYUV420?1:0),i.setFloat("fireworkLight",0),i.setVector3("fireworkLightPosition",new Vector3(0,0,0)),i.setVector3("focal_width_height",new Vector3(772.022491,720,1280)),i.backFaceCulling=!1,this._lowModelShader=i}});ct(this,"setDynamicSize",i=>new Promise((e,o)=>{i>=1&&i<=100?(this._dynamic_size=i,e(!0)):(this._dynamic_size=1,e(!1))}));ct(this,"_isInDynamicRange",i=>i<this._dynamic_size&&i>=0);ct(this,"initDynamicTexture",(i,e,o)=>{this._isInDynamicRange(i)&&(this._dynamic_textures[i]!=null&&(this._dynamic_textures[i].dispose(),this._dynamic_textures[i]=null),this._dynamic_textures[i]=new RawTexture(null,e,o*1.5,Engine.TEXTUREFORMAT_LUMINANCE,this.scene,!1,!0,Texture.NEAREST_SAMPLINGMODE,Engine.TEXTURETYPE_UNSIGNED_BYTE),this._dynamic_textures[i].name="Pano_Dynamic_"+i+"_"+Date.now())});ct(this,"initDynamicShaders",i=>(log$T.info("[Engine] Material init dynamic shader."),new Promise((e,o)=>{this._dynamic_shaders[i]!=null&&this._dynamic_shaders[i].dispose();const s=new ShaderMaterial("Pano_Shader_"+i,this.scene,{vertexSource:panoVertex,fragmentSource:panoFragment},{attributes:["uv","position","world0","world1","world2","world3"],uniforms:["view","projection","worldViewProjection","world"],defines:["#define SHADOWFULLFLOAT"]});s.setTexture("texture_pano",null),s.setVector3("centre_pose",new Vector3(0,0,0)),s.setFloat("isYUV",this._inputPanoYUV420?1:0),s.setTexture("shadowSampler",null),s.setMatrix("lightSpaceMatrix",null),s.setFloat("haveShadowLight",0),s.setFloat("fireworkLight",0),s.setVector3("fireworkLightPosition",new Vector3(0,0,0)),s.backFaceCulling=!1,this._dynamic_shaders[i]=s,e(!0)})));this._scenemanager=i,this.scene=i.Scene,this.engine=this.scene.getEngine(),this.shaderMode=1,this._dynamic_textures=[],this._dynamic_shaders=[],this._dynamic_babylonpose=[],this._videoRawYUVTexArray=new XVideoRawYUV(this.scene,e.videoResOriArray),this.shaderMode=e.shaderMode,e.yuvInfo!=null&&(this.yuvInfo=e.yuvInfo),e.panoInfo!=null&&this.setPanoInfo(e.panoInfo)}stopYUVUpdate(){this._isUpdateYUV=!1}allowYUVUpdate(){this._isUpdateYUV=!0}setPanoInfo(i){this._panoInfo=i}_prepareRender(i){i&&(this._initPureVideoContent(i),this._updatePureVideoShaderInput())}changeCameraFovWithShaderUpdate(i){this._changePureVideoLowModelShaderCanvasSize(i),this._scenemanager.cameraComponent.cameraFovChange(i)}getPureVideoShader(){return this._lowModelShader}getDefaultShader(){return this._defaultShader}updatePanoPartYUV(i,e,o){const s=e.subarray(0,o.width*o.height),c=e.subarray(o.width*o.height,o.width*o.height*1.25),d=e.subarray(o.width*o.height*1.25),_=this._panoInfo.width,b=this._panoInfo.height;if(this._dynamic_textures[i]!=null){const k=this._dynamic_textures[i].getInternalTexture();if(k!=null&&k!=null){const j=this.engine._getTextureTarget(k);this.engine._bindTextureDirectly(j,k,!0),this.engine.updateTextureData(k,s,o.startX,b*1.5-o.startY-o.height,o.width,o.height),this.engine.updateTextureData(k,c,o.startX*.5,(b-o.startY-o.height)*.5,o.width*.5-1,o.height*.5-1),this.engine.updateTextureData(k,d,o.startX*.5+_*.5,(b-o.startY-o.height)*.5,o.width*.5,o.height*.5),this.engine._bindTextureDirectly(j,null)}}}changePanoImg(i,e){if(log$T.info(`[Engine] changePanoImg, id=${i}, pose=${e.pose.position.x},${e.pose.position.y},${e.pose.position.z}`),!this._isInDynamicRange(i))return log$T.error(`[Engine] ${i} is bigger than dynamic size set in PanoInfo`),Promise.reject(new XMaterialError(`[Engine] ${i} is bigger than dynamic size set in PanoInfo`));const o=ue4Position2Xverse(e.pose.position);return o&&(this._dynamic_babylonpose[i]={position:o}),new Promise((s,c)=>{try{typeof e.data=="string"?(this.setPanoYUV420(!1),this._dynamic_textures[i].updateURL(e.data,null,()=>{this._dynamic_textures[i].updateSamplingMode(Texture.NEAREST_SAMPLINGMODE)})):(this.isPanoYUV420()==!1&&this.initDynamicTexture(i,this._panoInfo.width,this._panoInfo.height),this.setPanoYUV420(!0),this._dynamic_textures[i].update(e.data),this._dynamic_textures[i].updateSamplingMode(Texture.NEAREST_SAMPLINGMODE)),s(this)}catch(d){c(new XMaterialError(`[Engine] ChangePanoImg Error! ${d}`))}}).then(s=>(e.fov!=null&&this._scenemanager.cameraComponent.changeCameraFov(e.fov*Math.PI/180),this._dynamic_shaders[i].setFloat("isYUV",this._inputPanoYUV420?1:0),this._dynamic_shaders[i].setTexture("texture_pano",this._dynamic_textures[i]),this._dynamic_shaders[i].setVector3("centre_pose",this._dynamic_babylonpose[i].position),!0))}setYUV420(i){this._inputYUV420=i}isYUV420(){return this._inputYUV420}setPanoYUV420(i){this._inputPanoYUV420=i}isPanoYUV420(){return this._inputPanoYUV420}getDynamicShader(i){return this._dynamic_shaders[i]}_updatePureVideoShaderInput(){var i,e,o,s,c,d,_,b,k,j,$,_e;if(this.scene.getLightByName("AvatarLight")?((i=this.scene.getLightByName("AvatarLight"))!=null&&i.shadowEnabled?(e=this._lowModelShader)==null||e.setFloat("haveShadowLight",1):(o=this._lowModelShader)==null||o.setFloat("haveShadowLight",0),(d=this._lowModelShader)==null||d.setTexture("shadowSampler",(c=(s=this.scene.getLightByName("AvatarLight"))==null?void 0:s.getShadowGenerator())==null?void 0:c.getShadowMapForRendering()),(k=this._lowModelShader)==null||k.setMatrix("lightSpaceMatrix",(b=(_=this.scene.getLightByName("AvatarLight"))==null?void 0:_.getShadowGenerator())==null?void 0:b.getTransformMatrix())):((j=this._lowModelShader)==null||j.setTexture("shadowSampler",this._videoRawYUVTexArray.getVideoYUVTex(0)),($=this._lowModelShader)==null||$.setMatrix("lightSpaceMatrix",new Matrix),(_e=this._lowModelShader)==null||_e.setFloat("haveShadowLight",0)),this.scene.getLightByName("fireworkLight"))this.scene.registerBeforeRender(()=>{var et;this._lowModelShader.setFloat("fireworkLight",this.scene.getLightByName("fireworkLight").getScaledIntensity()),this._lowModelShader.setVector3("fireworkLightPosition",(et=this.scene.getLightByName("fireworkLight"))==null?void 0:et.position)});else{const et=new PointLight("fireworkLight",new Vector3(0,0,0),this.scene);et.intensity=0}}_updatePanoShaderInput(i){var e,o,s,c,d,_,b,k,j,$,_e,et;if(this._isInDynamicRange(i))if(this.scene.getLightByName("AvatarLight")?((e=this.scene.getLightByName("AvatarLight"))!=null&&e.shadowEnabled?(o=this._dynamic_shaders[i])==null||o.setFloat("haveShadowLight",1):(s=this._dynamic_shaders[i])==null||s.setFloat("haveShadowLight",0),(_=this._dynamic_shaders[i])==null||_.setTexture("shadowSampler",(d=(c=this.scene.getLightByName("AvatarLight"))==null?void 0:c.getShadowGenerator())==null?void 0:d.getShadowMapForRendering()),(j=this._dynamic_shaders[i])==null||j.setMatrix("lightSpaceMatrix",(k=(b=this.scene.getLightByName("AvatarLight"))==null?void 0:b.getShadowGenerator())==null?void 0:k.getTransformMatrix())):(($=this._lowModelShader)==null||$.setTexture("shadowSampler",this._videoRawYUVTexArray.getVideoYUVTex(0)),(_e=this._lowModelShader)==null||_e.setMatrix("lightSpaceMatrix",new Matrix),(et=this._lowModelShader)==null||et.setFloat("haveShadowLight",0)),this.scene.getLightByName("fireworkLight"))this.scene.registerBeforeRender(()=>{var tt;this._dynamic_shaders[i].setFloat("fireworkLight",this.scene.getLightByName("fireworkLight").getScaledIntensity()),this._dynamic_shaders[i].setVector3("fireworkLightPosition",(tt=this.scene.getLightByName("fireworkLight"))==null?void 0:tt.position)});else{const tt=new PointLight("fireworkLight",new Vector3(0,0,0),this.scene);tt.intensity=0}}}class XCameraComponent{constructor(i,e,o){ct(this,"maincameraRotLimitObserver",null);ct(this,"mainCamera");ct(this,"cgCamera");ct(this,"saveCameraPose");ct(this,"_cameraPose");ct(this,"scene");ct(this,"canvas");ct(this,"yuvInfo");ct(this,"forceKeepVertical",!1);ct(this,"initCamera",i=>{const{maxZ:e=1e4,minZ:o=.1,angularSensibility:s=2e3}=i;this.mainCamera=new FreeCamera("camera_main",new Vector3(0,1e3,0),this.scene),this.mainCamera.mode=Camera$1.PERSPECTIVE_CAMERA,this.mainCamera.speed=.1,this.mainCamera.angularSensibility=s,this.mainCamera.setTarget(new Vector3(0,1010,0)),this.mainCamera.minZ=o,this.mainCamera.fov=Math.PI*this.yuvInfo.fov/180,this.mainCamera.maxZ=e,this.mainCamera.fovMode=Camera$1.FOVMODE_HORIZONTAL_FIXED,this.cgCamera=new FreeCamera("camera_temp",new Vector3(0,1e3,0),this.scene),this.cgCamera.mode=Camera$1.PERSPECTIVE_CAMERA,this.cgCamera.speed=.1,this.cgCamera.setTarget(new Vector3(0,1010,0)),this.cgCamera.maxZ=e,this.cgCamera.minZ=o,this.cgCamera.fovMode=Camera$1.FOVMODE_HORIZONTAL_FIXED,this.cameraFovChange(this.yuvInfo)});ct(this,"cameraFovChange",i=>{this.yuvInfo=i;const e=i.width,o=i.height,s=this.canvas.width,c=this.canvas.height,d=i.fov;if(this.forceKeepVertical==!0){const _=e/(2*Math.tan(Math.PI*d/360)),b=2*Math.atan(o/(2*_));this.mainCamera.fov=b,this.cgCamera.fov=b,this.mainCamera.fovMode=Camera$1.FOVMODE_VERTICAL_FIXED,this.cgCamera.fovMode=Camera$1.FOVMODE_VERTICAL_FIXED}else if(this.mainCamera.fovMode=Camera$1.FOVMODE_HORIZONTAL_FIXED,this.cgCamera.fovMode=Camera$1.FOVMODE_HORIZONTAL_FIXED,s/c<e/o&&this.mainCamera.fov){const _=c,b=s,k=_*e/o/(2*Math.tan(d*Math.PI/360)),j=2*Math.atan(b/(2*k));this.mainCamera.fov=j,this.cgCamera.fov=j}else this.mainCamera.fov=Math.PI*d/180,this.cgCamera.fov=Math.PI*d/180});ct(this,"setCameraPose",i=>{var s;const e=ue4Position2Xverse(i.position);let o=null;i.rotation!=null&&(o=ue4Rotation2Xverse(i.rotation)),this._cameraPose={position:e},o!=null&&(this._cameraPose.rotation=o),this.scene.activeCamera===this.mainCamera&&!((s=this.mainCamera)!=null&&s.isDisposed())&&this._setCamPositionRotation(this.mainCamera,this._cameraPose)});ct(this,"_setCamPositionRotation",(i,e)=>{var o,s;e.position&&(i.position=(o=e.position)==null?void 0:o.clone()),e.rotation&&(i.rotation=(s=e.rotation)==null?void 0:s.clone())});ct(this,"switchCamera",i=>{var e;(e=this.scene.activeCamera)==null||e.detachControl(this.canvas),this.scene.activeCamera=i});ct(this,"reCalXYZRot",(i,e)=>(i=i%(2*Math.PI),Math.abs(e-i)>=Math.PI&&(i=i-2*Math.PI),i));ct(this,"_moveCam",(i,e,o,s,c,d,_,b)=>{const k=(nt,ot,at)=>(nt.x=this.reCalXYZRot(nt.x,ot.x),nt.y=this.reCalXYZRot(nt.y,ot.y),nt.z=this.reCalXYZRot(nt.z,ot.z),new Vector3((ot.x-nt.x)*at+nt.x,(ot.y-nt.y)*at+nt.y,(ot.z-nt.z)*at+nt.z)),j=function(nt,ot,at){return new Vector3((ot.x-nt.x)*at+nt.x,(ot.y-nt.y)*at+nt.y,(ot.z-nt.z)*at+nt.z)},$=new Animation("myAnimation1","position",_,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT);let _e=[],et=e,tt=o;for(let nt=0;nt<d;++nt)_e.push({frame:nt,value:j(et,tt,nt/d)});_e.push({frame:_e.length,value:j(et,tt,1)}),$.setKeys(_e);const rt=new Animation("myAnimation2","rotation",_,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT);_e=[],et=s,tt=c;for(let nt=0;nt<d;++nt)_e.push({frame:nt,value:k(et,tt,nt/d)});_e.push({frame:_e.length,value:k(et,tt,1)}),rt.setKeys(_e),i.animations.push(rt),i.animations.push($);const it=this.scene.beginAnimation(i,0,d,!1);it.onAnimationEnd=()=>{b(),it.stop(),it.animationStarted=!1}});this.scene=e,this.canvas=i,this.yuvInfo=o.yuvInfo,o.forceKeepVertical!=null&&(this.forceKeepVertical=o.forceKeepVertical),this.initCamera(o.cameraParam)}get MainCamera(){return this.mainCamera}get CgCamera(){return this.cgCamera}getCameraHorizonFov(){return this.mainCamera.fovMode==Camera$1.FOVMODE_HORIZONTAL_FIXED?this.mainCamera.fov:Math.PI*this.yuvInfo.fov/180}changeMainCameraRotationDamping(i=2e3){this.mainCamera.angularSensibility=i}removeMainCameraRotationLimit(){this.maincameraRotLimitObserver!=null&&this.mainCamera.onAfterCheckInputsObservable.remove(this.maincameraRotLimitObserver)}setMainCameraInfo(i){const{maxZ:e=1e4,minZ:o=.1,angularSensibility:s=2e3}=i;this.mainCamera.maxZ=e,this.mainCamera.minZ=o,this.mainCamera.angularSensibility=s}getMainCameraInfo(){return{maxZ:this.mainCamera.maxZ,minZ:this.mainCamera.minZ,angularSensibility:this.mainCamera.angularSensibility}}_limitAngle(i,e){return Math.abs(Math.abs(e[0]-e[1])-360)<1e-6||(i=(i%360+360)%360,e[0]=(e[0]%360+360)%360,e[1]=(e[1]%360+360)%360,e[0]>e[1]?i>e[1]&&i<e[0]&&(Math.abs(i-e[0])<Math.abs(i-e[1])?i=e[0]:i=e[1]):i<e[0]?i=e[0]:i>e[1]&&(i=e[1])),i}setMainCameraRotationLimit(i,e){this.maincameraRotLimitObserver!=null&&this.removeMainCameraRotationLimit();const o=this.mainCamera,{yaw:s,pitch:c,roll:d}=i,{yaw:_,pitch:b,roll:k}=e;if(_<0||b<0||k<0)throw new Error("\u76F8\u673A\u65CB\u8F6C\u9650\u5236\u53EA\u80FD\u8BBE\u7F6E\u4E3A\u5927\u4E8E0");const j=[c-b,c+b],$=[s-_,s+_],_e=[d-k,d+k];this.maincameraRotLimitObserver=o.onAfterCheckInputsObservable.add(()=>{let{pitch:et,yaw:tt,roll:rt}=xverseRotation2Ue4(o.rotation);et=this._limitAngle(et,j),tt=this._limitAngle(tt,$),rt=this._limitAngle(rt,_e),o.rotation=ue4Rotation2Xverse({pitch:et,yaw:tt,roll:rt})})}setMainCameraRotationLimitByAnchor(i,e,o){this.maincameraRotLimitObserver!=null&&this.removeMainCameraRotationLimit();const s=this.mainCamera,c=ue4Rotation2Xverse_mesh(e),d=ue4Rotation2Xverse_mesh(o);d!=null&&c!=null&&i.mesh!=null&&(this.maincameraRotLimitObserver=s.onAfterCheckInputsObservable.add(()=>{const _=i.mesh.rotation;o.yaw>0&&(s.rotation.y<=_.y-d.y+c.y?s.rotation.y=_.y-d.y+c.y:s.rotation.y>=_.y+d.y+c.y&&(s.rotation.y=_.y+d.y+c.y)),o.pitch>0&&(s.rotation.x<=_.x-d.x+c.x?s.rotation.x=_.x-d.x+c.x:s.rotation.x>=_.x+d.x+c.x&&(s.rotation.x=_.x+d.x+c.x)),o.roll>0&&(s.rotation.z<=_.z-d.z+c.z?s.rotation.z=_.z-d.z+c.z:s.rotation.z>=_.z+d.z+c.z&&(s.rotation.z=_.z+d.z+c.z))}))}getCameraPose(){const i=xversePosition2Ue4({x:this.mainCamera.position.x,y:this.mainCamera.position.y,z:this.mainCamera.position.z}),e=xverseRotation2Ue4({x:this.mainCamera.rotation.x,y:this.mainCamera.rotation.y,z:this.mainCamera.rotation.z});return{position:i,rotation:e}}changeCameraFov(i,e){this.mainCamera.fov=i,e!=null&&(this.mainCamera.fovMode=e==0?Camera$1.FOVMODE_HORIZONTAL_FIXED:Camera$1.FOVMODE_VERTICAL_FIXED)}controlCameraRotation(i,e,o=.5,s=.5){const c={pitch:s*e*180,yaw:o*i*180,roll:0};this.addRot(c)}addRot(i){const e=this.mainCamera,o=ue4Rotation2Xverse_mesh(i);o!=null&&e.rotation.addInPlace(o)}getCameraFov(){return this.mainCamera.fov}allowMainCameraController(){this.mainCamera.attachControl(this.canvas,!0)}detachMainCameraController(){this.mainCamera.detachControl(this.canvas)}forceChangeSavedCameraPose(i){this.saveCameraPose!=null&&(i.position!=null&&(this.saveCameraPose.position=ue4Position2Xverse(i.position)),i.rotation!=null&&(this.saveCameraPose.rotation=ue4Rotation2Xverse(i.rotation)))}changeToFirstPersonView(i){this.saveCameraPose={position:this.mainCamera.position.clone(),rotation:this.mainCamera.rotation.clone()},this.mainCamera.attachControl(this.canvas,!0),i.position!=null&&(this.mainCamera.position=ue4Position2Xverse(i.position)),i.rotation!=null&&(this.mainCamera.rotation=ue4Rotation2Xverse(i.rotation))}changeToThirdPersonView(){this.saveCameraPose!=null&&this.mainCamera!=null&&(this.mainCamera.position=this.saveCameraPose.position.clone(),this.mainCamera.rotation=this.saveCameraPose.rotation.clone(),this.mainCamera.detachControl(this.canvas))}switchToMainCamera(){this.switchCamera(this.mainCamera)}switchToCgCamera(){this.switchCamera(this.cgCamera)}moveMainCamera(i,e,o,s,c){this._moveCam(this.mainCamera,this.mainCamera.position,i,this.mainCamera.rotation,e,o,s,c)}}function uuid$2(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=Math.random()*16|0;return(a==="x"?i:i&3|8).toString(16)})}function hashCode(a){let i=0,e,o;if(a==null||a.length===0)return i;for(e=0;e<a.length;e++)o=a.charCodeAt(e),i=(i<<5)-i+o,i|=0;return i}const log$S=new Logger$1("XStaticMeshComponent"),yr=class{constructor(i){ct(this,"scene");ct(this,"_staticmeshes");ct(this,"_lowModel_group");ct(this,"_CgPlane");ct(this,"_rootDir");ct(this,"_abosoluteUrl");ct(this,"_partMeshSkinInfo");ct(this,"_meshInfoJson");ct(this,"_orijson");ct(this,"_notUsedRegionLists");ct(this,"_meshInfoKeys");ct(this,"_currentUpdateRegionCount");ct(this,"_currentMeshUsedLod");ct(this,"_currentPartGroup");ct(this,"_allowRegionUpdate");ct(this,"_allowRegionForceLod");ct(this,"_forceLod");ct(this,"_scenemanager");ct(this,"regionIdInCamera");ct(this,"regionIdInCameraConst");ct(this,"_cameraInRegionId");ct(this,"_meshVis");ct(this,"_doMeshVisChangeNumber");ct(this,"_meshVisTypeName");ct(this,"_visCheckDurationFrameNumber");ct(this,"_regionLodRule");ct(this,"reg_staticmesh_partupdate",()=>{if(this._allowRegionUpdate&&(this.scene.getFrameId(),this._meshUpdateFrame()),this._allowRegionForceLod){this.scene.getFrameId()%2==0&&this.setOneRegionLod(this._meshInfoKeys[this._currentUpdateRegionCount%this._meshInfoKeys.length].toString(),this._forceLod);let e=!0;const o=Array.from(this._currentMeshUsedLod.keys());if(o.length>0){for(let s=0;s<o.length;++s)this._currentMeshUsedLod.get(o[s])!=this._forceLod&&(e=!1);e&&(this._allowRegionForceLod=!1)}}});ct(this,"setMeshInfo",(i,e="")=>{this._abosoluteUrl!=i&&(this._abosoluteUrl.length>0&&this.deleteLastRegionMesh(),this._partMeshSkinInfo=e,this._abosoluteUrl=i,this._rootDir=this._abosoluteUrl.slice(0,-4)+"/",this.parseJson(this._rootDir+"meshInfo.json").then(()=>{this.startMeshUpdate()}))});ct(this,"_meshUpdateFrame",()=>{{let i=this._meshInfoKeys[this._currentUpdateRegionCount%this._meshInfoKeys.length];const e=!0;let o=3;if(this._scenemanager!=null&&this._scenemanager.cameraComponent!=null){const s=this._getMainPlayerPosition();if(s!=null){if(this._cameraInRegionId>=0){const d=this.getRegionIdWhichIncludeCamera(s);(this._cameraInRegionId!=d||this.regionIdInCamera.length==0)&&(this._cameraInRegionId=d,this.regionIdInCamera=this._getNeighborId(this._cameraInRegionId.toString()),this.regionIdInCameraConst=this.regionIdInCamera.slice());let _=this.regionIdInCamera.pop();for(;_!=null;)if(this._notUsedRegionLists.indexOf(_)>=0)_=this.regionIdInCamera.pop();else break;_!=null&&(i=_.toString())}else this._cameraInRegionId=this.getRegionIdWhichIncludeCamera(s);if(this._currentMeshUsedLod.size==0||this._notUsedRegionLists.indexOf(parseInt(i))>=0){i=this._cameraInRegionId.toString();const d=this._getNeighborId(i);for(;d.length==0&&(i=this.getNearestRegionIdWithCamera(s).toString()),this._notUsedRegionLists.indexOf(parseInt(i))>=0;)i=d.pop().toString()}const c=this._meshInfoJson[this._cameraInRegionId.toString()].lod;o=3,this._cameraInRegionId.toString()==i?o=this._regionLodRule[0]:c[0].indexOf(parseInt(i))>=0?o=this._regionLodRule[1]:c[1].indexOf(parseInt(i))>=0?o=this._regionLodRule[2]:c[2].indexOf(parseInt(i))>=0?o=this._regionLodRule[3]:o=this._regionLodRule[4]}}this.setOneRegionLod(i,o,e),this.updateRegionNotInLocalNeighbor(),this.cleanRootNodes()}});ct(this,"updateRegionNotInLocalNeighbor",()=>{Array.from(this._currentMeshUsedLod.keys()).forEach(e=>{this.regionIdInCameraConst.indexOf(parseInt(e))<0&&this.setOneRegionLod(e,-1)})});ct(this,"cleanRootNodes",()=>{if(this.scene.getFrameId()%3==0){const i=[];this.scene.rootNodes.forEach(e=>{(e.getClassName()=="TransformNode"&&e.getChildren().length==0||e.getClassName()=="Mesh"&&e.name=="__root__"&&e.getChildren().length==0)&&i.push(e)}),i.forEach(e=>{e.dispose()})}});ct(this,"setOneRegionLod",(i,e,o=!0)=>{this._currentUpdateRegionCount++;const s=this._calHashCode(this._rootDir),c="region_"+s+"_"+i;if(e<0){this._currentMeshUsedLod.has(i)&&(this._currentMeshUsedLod.delete(i),this._currentPartGroup.delete(c),this.deleteMeshesByCustomProperty("group","region_"+s+"_"+i));return}const d=this._rootDir+i+"_lod"+e+"_xverse.glb",_=this._currentMeshUsedLod.get(i);this._currentPartGroup.add(c),_!=null?_!=e&&(this._currentMeshUsedLod.set(i,e),this._scenemanager.addNewLowPolyMesh({url:d,group:"region_"+s+"_"+i,pick:!0,lod:e,skinInfo:this._partMeshSkinInfo},[{group:"region_"+s+"_"+i,mode:0}])):(this._currentMeshUsedLod.set(i,e),this._scenemanager.addNewLowPolyMesh({url:d,group:"region_"+s+"_"+i,pick:!0,lod:e,skinInfo:this._partMeshSkinInfo}))});ct(this,"checkPointInView",({x:i,y:e,z:o})=>{const s=ue4Position2Xverse({x:i,y:e,z:o});if(!s)return!1;for(let c=0;c<6;c++)if(this.scene.frustumPlanes[c].dotCoordinate(s)<0)return!1;return!0});ct(this,"addNewLowPolyMesh",(i,e,o)=>{if(!i.url.endsWith("glb")&&!i.url.startsWith("blob:"))return i.url.endsWith("zip")?(this.setMeshInfo(i.url,i.skinInfo),Promise.resolve(!0)):(log$S.error("[Engine] input model path is error! ",i.url),Promise.reject(new XLowpolyModelError("[Engine] input model path is error! "+i.url)));{const s=i.url;return new Promise((c,d)=>this._scenemanager.urlTransformer(i.url).then(_=>{i.url=_;const b=new XStaticMeshFromOneGltf(this.scene,i),k=Date.now();return new Promise((j,$)=>{b.loadMesh(o,!0).then(_e=>{const et=Date.now();if(this._scenemanager.engineRunTimeStats.timeArray_loadStaticMesh.add(et-k),_e==!0){const tt=this.getLowModelType(i);let rt=0;if(this._lowModel_group.has(tt)&&(rt=this._lowModel_group.get(tt).length),o!=null&&this._scenemanager.currentShader!=null&&this._scenemanager.currentShader.name!=o.name&&b.setMaterial(this._scenemanager.currentShader),this._allowRegionUpdate==!1&&tt.startsWith("region_"))b.dispose();else if(this._staticmeshes.push(b),this.lowmodelGroupMapAddValue(tt,b),e!=null&&e.length>0){const it=[];for(let nt=0;nt<e.length;++nt)it.push(e[nt].group),this.updateLowModelGroup(e[nt],tt,rt)}this._scenemanager.engineRunTimeStats.timeArray_updateStaticMesh.add(Date.now()-et),j(!0)}else $(new XLowpolyModelError("[Engine] after lowmodel error!"))}).catch(_e=>{log$S.error("[Engine] load Mesh ["+s+"] error! "+_e),$(new XLowpolyModelError(`[Engine] load Mesh [${s}] error! ${_e}`))})})}).then(_=>{_==!0?(log$S.info(`[Engine] load Mesh [${s}] successfully.`),c(!0)):d(!1)}).catch(_=>{log$S.error("[Engine] addNewLowPolyMesh ["+s+"] error! "+_),d(new XLowpolyModelError(`[Engine] addNewLowPolyMesh [${s}] error! ${_}`))}))}});ct(this,"toggleLowModelVisibility",i=>{const{vis:e,groupName:o="",skinInfo:s=""}=i;this._meshVis=e,this._meshVisTypeName={groupName:o,skinInfo:s},this._doMeshVisChangeNumber=0,o==yr.ALL_MESHES||this._currentPartGroup.has(o)==!0||this._partMeshSkinInfo==s?e==!1?(this._visCheckDurationFrameNumber=100,this.stopMeshUpdate()):(this._visCheckDurationFrameNumber=1,this.startMeshUpdate()):this._visCheckDurationFrameNumber=1});ct(this,"reg_staticmesh_visibility",()=>{if(this._doMeshVisChangeNumber>=0)if(this._doMeshVisChangeNumber<this._visCheckDurationFrameNumber)if(this._doMeshVisChangeNumber=this._doMeshVisChangeNumber+1,this._meshVisTypeName.groupName==yr.ALL_MESHES)this._lowModel_group.forEach((i,e)=>{for(let o=0,s=i.length;o<s;++o)i[o].toggleVisibility(this._meshVis)});else{if(this._lowModel_group.has(this._meshVisTypeName.groupName))for(let i=0;i<this._lowModel_group.get(this._meshVisTypeName.groupName).length;++i)this._lowModel_group.get(this._meshVisTypeName.groupName)[i].toggleVisibility(this._meshVis);if(this._meshVisTypeName.skinInfo!="")for(let i=0;i<this._staticmeshes.length;++i)this._staticmeshes[i].skinInfo==this._meshVisTypeName.skinInfo&&this._staticmeshes[i].toggleVisibility(this._meshVis)}else this._meshVis=!0,this._meshVisTypeName={groupName:"",skinInfo:""},this._doMeshVisChangeNumber=-1});ct(this,"_getMeshesByCustomProperty",(i,e)=>{let o=[];return this._staticmeshes.forEach(s=>{s[i]!=null&&s[i]==e&&(o=o.concat(s.meshes))}),o});this._lowModel_group=new Map,this._staticmeshes=[],this._meshInfoJson=null,this._meshInfoKeys=[],this._currentUpdateRegionCount=0,this._abosoluteUrl="",this._partMeshSkinInfo="",this._forceLod=3,this._allowRegionUpdate=!1,this._allowRegionForceLod=!1,this._currentMeshUsedLod=new Map,this._currentPartGroup=new Set,this._scenemanager=i,this.scene=i.Scene,this.regionIdInCamera=[],this.regionIdInCameraConst=[],this._cameraInRegionId=-1,this._rootDir="",this._meshVis=!0,this._meshVisTypeName={groupName:"",skinInfo:""},this._doMeshVisChangeNumber=-1,this._visCheckDurationFrameNumber=-1,this._regionLodRule=[0,1,3,3,-1],this.initCgLowModel(),this._regionPartLoop()}get cameraInRegionId(){return this._cameraInRegionId}setRegionLodRule(i){return i.length!=5?!1:(i.forEach(e=>{}),this._regionLodRule=i,!0)}get lowModel_group(){return this._lowModel_group}_regionPartLoop(){this.scene.registerBeforeRender(this.reg_staticmesh_partupdate),this.scene.registerAfterRender(this.reg_staticmesh_visibility)}_globalSearchCameraInWhichRegion(i,e){let o=-1;for(let s=0;s<e.length;++s){const c=this._meshInfoJson[e[s].toString()].boundingbox,d=c[0],_=c[1];if(i.x>=d[0]&&i.x<=_[0]&&i.y>=d[1]&&i.y<=_[1]&&i.z>=d[2]&&i.z<=_[2]||i.x>=_[0]&&i.x<=d[0]&&i.y>=_[1]&&i.y<=d[1]&&i.z>=_[2]&&i.z<=d[2]){o=parseInt(e[s].toString());break}}return o}getRegionIdByPosition(i){return this.getRegionIdWhichIncludeCamera(i)}getRegionIdWhichIncludeCamera(i){let e=-1;if(this._allowRegionUpdate==!1)return e;if(this._cameraInRegionId==-1?e=this._globalSearchCameraInWhichRegion(i,this._meshInfoKeys):(e=this._globalSearchCameraInWhichRegion(i,this.regionIdInCameraConst),e==-1&&(e=this._globalSearchCameraInWhichRegion(i,this._meshInfoKeys))),e==-1){let o=1e7;for(let s=0;s<this._meshInfoKeys.length;++s){const c=this._meshInfoJson[this._meshInfoKeys[s]].center,d=Math.abs(i.x-c[0])+Math.abs(i.y-c[1]);o>d&&(o=d,e=parseInt(this._meshInfoKeys[s]))}}return e}getNearestRegionIdWithCamera(i){let e=1,o=1e7;for(let s=0;s<this._meshInfoKeys.length;++s){if(this._notUsedRegionLists.indexOf(parseInt(this._meshInfoKeys[s]))>=0)continue;const c=this._meshInfoJson[this._meshInfoKeys[s]].center,d=Math.abs(i.x-c[0])+Math.abs(i.y-c[1]);o>d&&(o=d,e=parseInt(this._meshInfoKeys[s]))}return e}_getNeighborId(i){const e=this._meshInfoJson[i].lod;let o=[];const s=Object.keys(e);for(let c=s.length-1;c>=0;--c)o=o.concat(e[s[c]]);return o.push(parseInt(i)),o}_getMainPlayerPosition(){const i=this._scenemanager.cameraComponent.getCameraPose().position,e=this._scenemanager.avatarComponent.getMainAvatar();if(e!=null&&e!=null){const o=e.position;if(o!=null)return o}return i}_calHashCode(i){return hashCode(i)+"_"+this._partMeshSkinInfo}forceAllRegionLod(i=3){i<0&&(i=0),i>3&&(i=3),this.stopMeshUpdate(),this._allowRegionForceLod=!0,this._forceLod=i}deleteLastRegionMesh(){if(this._rootDir!=""){const i=this._calHashCode(this._rootDir);this._currentMeshUsedLod.clear(),this._currentPartGroup.clear(),this._meshInfoJson=null,this._meshInfoKeys=[],this._currentUpdateRegionCount=0,this._orijson=null,this._notUsedRegionLists=[],this._partMeshSkinInfo="",this._abosoluteUrl="",this.stopMeshUpdate(),this.deleteMeshesByCustomProperty("group","region_"+i,!0)}}startMeshUpdate(){this._allowRegionUpdate==!1&&this._meshInfoJson!=null&&this._abosoluteUrl!=""&&this._meshInfoKeys.length>0&&(this._allowRegionUpdate=!0)}stopMeshUpdate(){this._allowRegionUpdate=!1}parseJson(i){return new Promise((e,o)=>this._scenemanager.urlTransformer(i).then(s=>{const c=new XMLHttpRequest;c.open("get",s),c.send(null),c.onload=()=>{if(c.status==200){const d=JSON.parse(c.responseText);this._orijson=d,this._meshInfoJson=this._orijson.usedRegion,this._notUsedRegionLists=this._orijson.notUsedRegion,this._meshInfoKeys=Object.keys(this._meshInfoJson),log$S.info("[Engine] parse zip mesh info successful"),e()}},c.onerror=()=>{log$S.error(`[Engine] load zip mesh info json error, (provided by blob): ${s}`),o(new XLowpolyJsonError(`[Engine] load zip mesh info json error, (provided by blob): ${s}`))}}).catch(s=>{log$S.error(`[Engine] load zip mesh info json error: ${s}, link:${i}`),o(new XLowpolyJsonError(`[Engine] load zip mesh info json error: ${s}, link: ${i}`))}))}initCgLowModel(){const i=MeshBuilder.CreatePlane("CgPlane",{size:400});i.position=new Vector3(0,1010,0),i.rotation=new Vector3(3*Math.PI/2,0,0),this._CgPlane=new XStaticMesh({id:"CgPlane",mesh:i,xtype:EMeshType.Cgplane}),this._CgPlane.hide()}getLowModelType(i){let e="";return i.group!=null?e=i.group:e="default",e}lowmodelGroupMapAddValue(i,e){const o=this._lowModel_group.get(i);o!=null?(o.push(e),this._lowModel_group.set(i,o)):this._lowModel_group.set(i,[e])}updateLowModelGroup(i,e,o){let s=o;i.group==e||(s=-1),i.mode==0?this.deleteLowModelGroup(i.group,s):i.mode==1?this.toggleVisibleLowModelGroup(!1,i.group,s):i.mode==2&&this.toggleVisibleLowModelGroup(!0,i.group,s)}toggleVisibleLowModelGroup(i,e,o=-1){if(this._lowModel_group.has(e)){const s=this._lowModel_group.get(e);let c=s.length;o>=0&&c>=o&&(c=o);for(let d=0;d<c;++d)s[d].toggleVisibility(i)}}deleteLowModelGroup(i,e=-1){if(this._lowModel_group.has(i)){const c=this._lowModel_group.get(i);let d=c.length;e>=0&&d>=e&&(d=e);for(let _=0;_<d;++_)c[_].dispose();e>=0?this._lowModel_group.set(i,this._lowModel_group.get(i).slice(d)):this._lowModel_group.delete(i)}const o=this._lowModel_group.get(i),s=[];o!=null&&o.length>0?this._staticmeshes.forEach(c=>{if(c.group!=i)s.push(c);else for(let d=0;d<o.length;++d)c.groupUuid==o[d].groupUuid&&s.push(c)}):this._staticmeshes.forEach(c=>{c.group!=i&&s.push(c)}),this._staticmeshes=s}deleteMeshesByGroup(i){this.deleteLowModelGroup(i)}deleteMeshesById(i){this.deleteMeshesByCustomProperty("id",i)}deleteMeshesByLoD(i){this.deleteMeshesByCustomProperty("lod",i)}deleteMeshesBySkinInfo(i){this.deleteMeshesByCustomProperty("skinInfo",i)}removeMeshesFromSceneByGroup(i){this.removeMeshesFromSceneByCustomProperty("group",i)}removeMeshesFromSceneById(i){this.removeMeshesFromSceneByCustomProperty("id",i)}addMeshesToSceneByGroup(i){this.addMeshesToSceneByCustomProperty("group",i)}addMeshesToSceneById(i){this.addMeshesToSceneByCustomProperty("id",i)}removeMeshesFromSceneByCustomProperty(i,e,o=!1){this._staticmeshes.forEach(s=>{s.isinscene&&s[i]!=null&&(o?s[i].indexOf(e)<0||s.removeFromScene():s[i]!=e||s.removeFromScene())})}addMeshesToSceneByCustomProperty(i,e,o=!1){this._staticmeshes.forEach(s=>{s.isinscene==!1&&s[i]!=null&&(o?s[i].indexOf(e)<0||s.addToScene():s[i]!=e||s.addToScene())})}deleteMeshesByCustomProperty(i,e,o=!1){const s=[];this._staticmeshes.forEach(d=>{d[i]!=null&&(o?d[i].indexOf(e)<0?s.push(d):d.dispose():d[i]!=e?s.push(d):d.dispose())}),this._staticmeshes=s;const c=Array.from(this._lowModel_group.keys());for(let d=0;d<c.length;++d){const _=c[d],b=this._lowModel_group.get(_);if(b!=null){const k=[];for(let j=0;j<b.length;++j)b[j][i]!=null&&(o?b[j][i].indexOf(e)<0&&k.push(b[j]):b[j][i]!=e&&k.push(b[j]));k.length>0?this._lowModel_group.set(_,k):this._lowModel_group.delete(_)}}}getMeshes(){let i=[];for(let e=0;e<this._staticmeshes.length;++e)i=i.concat(this._staticmeshes[e].meshes);return i}getCgMesh(){return this._CgPlane}getMeshesByGroup(i="default"){const e=this._lowModel_group.get(i);if(e!=null){let o=[];for(let s=0;s<e.length;++s)o=o.concat(e[s].meshes);return o}else return null}getMeshesByGroup2(i="default"){return this._getMeshesByCustomProperty("group",i)}};let XStaticMeshComponent=yr;ct(XStaticMeshComponent,"ALL_MESHES","ALL_MESHES");class XStaticMeshFromOneGltf{constructor(i,e){ct(this,"_scene");ct(this,"_url");ct(this,"_group");ct(this,"_pickable");ct(this,"_meshes");ct(this,"_id");ct(this,"_lod");ct(this,"_groupUuid");ct(this,"_isInScene");ct(this,"_skinInfo");ct(this,"loadMesh",(i,e)=>{const o=this._meshes.length,s=e?1:0,c=this._url;return SceneLoader.LoadAssetContainerAsync("",c,this._scene,()=>{this._scene.blockMaterialDirtyMechanism=!0},".glb").then(d=>{for(let _=d.materials.length-1;_>=0;--_)d.materials[_].dispose();this._scene.blockMaterialDirtyMechanism=!0;for(let _=0;_<d.meshes.length;++_){const b=d.meshes[_];if("instances"in b){"visibility"in b&&(b.visibility=0),"isPickable"in b&&(b.isPickable=this._pickable),i!=null&&(b.material=i),"hasVertexAlpha"in b&&(b.hasVertexAlpha=!1);const k=new XStaticMesh({id:this._groupUuid+"-"+Math.random().toString(36).substr(2,5),mesh:b,lod:this._lod,group:this._group,url:this._url,xtype:EMeshType.XStaticMesh,skinInfo:this._skinInfo});this._meshes.push(k)}this._scene.addMesh(b)}return!0}).then(()=>{this._isInScene=!0;for(let d=o;d<this._meshes.length;++d)this._meshes[d].mesh.visibility=s;return Promise.resolve(!0)}).catch(d=>{log$S.error("[Engine] input gltf mesh uri error! "+d),Promise.reject(new XLowpolyModelError("[Engine] input gltf mesh uri error! "+d))})});this._meshes=[],this._scene=i,this._url=e.url,e.group!=null?this._group=e.group:this._group="default",e.pick!=null?this._pickable=e.pick:this._pickable=!1,e.id!=null?this._id=e.id:this._id="default",e.lod!=null?this._lod=e.lod:this._lod=-1,e.skinInfo!=null?this._skinInfo=e.skinInfo:this._skinInfo="default",this._groupUuid=uuid$2(),this._isInScene=!1}get isinscene(){return this._isInScene}get groupUuid(){return this._groupUuid}get skinInfo(){return this._skinInfo}get group(){return this._group}get meshes(){return this._meshes}get url(){return this._url}get id(){return this._id}get lod(){return this._lod}removeFromScene(){if(this._isInScene){this._isInScene=!1;for(let i=0,e=this._meshes.length;i<e;++i)this._meshes[i].mesh!=null&&this._scene.removeMesh(this._meshes[i].mesh)}}addToScene(){if(this._isInScene==!1){this._isInScene=!0;for(let i=0,e=this._meshes.length;i<e;++i)this._meshes[i].mesh!=null&&this._scene.addMesh(this._meshes[i].mesh)}}toggleVisibility(i){const e=i?1:0;for(let o=0,s=this._meshes.length;o<s;++o)"visibility"in this._meshes[o].mesh&&(this._meshes[o].mesh.visibility=e)}togglePickable(i){for(let e=0,o=this._meshes.length;e<o;++e)"isPickable"in this._meshes[e].mesh&&(this._meshes[e].mesh.isPickable=i)}setMaterial(i){for(let e=0,o=this._meshes.length;e<o;++e)"material"in this._meshes[e].mesh&&(this._meshes[e].mesh.material=i)}dispose(){for(let i=0,e=this._meshes.length;i<e;++i)this._meshes[i].mesh.dispose(!1,!1)}}const log$R=new Logger$1("XSceneManager");var ECurrentShaderMode=(a=>(a[a.default=0]="default",a[a.video=1]="video",a[a.pano=2]="pano",a))(ECurrentShaderMode||{}),EImageQuality=(a=>(a[a.low=0]="low",a[a.mid=1]="mid",a[a.high=2]="high",a))(EImageQuality||{});class XSceneManager{constructor(i,e,o,s,c){ct(this,"scene");ct(this,"engine");ct(this,"canvas");ct(this,"gl");ct(this,"_yuvInfo");ct(this,"cameraParam");ct(this,"shaderMode");ct(this,"panoInfo");ct(this,"_initEngineScaleNumber");ct(this,"_forceKeepVertical",!1);ct(this,"_currentShader");ct(this,"_currentPanoId");ct(this,"_renderStatusCheckCount",0);ct(this,"_renderStatusNotChecktCount",0);ct(this,"_nonlinearCanvasResize",!1);ct(this,"_bChangeEngineSize",!0);ct(this,"_cameraManager");ct(this,"_lowpolyManager");ct(this,"_materialManager");ct(this,"_statisticManager");ct(this,"_breathPointManager");ct(this,"_skytv");ct(this,"_mv",[]);ct(this,"_decalManager");ct(this,"_lightManager");ct(this,"_avatarManager");ct(this,"urlTransformer");ct(this,"_billboardManager");ct(this,"_backgroundImg");ct(this,"engineRunTimeStats");ct(this,"_pipeLine");ct(this,"uploadHardwareSystemInfo",()=>{const i=this.statisticComponent.getHardwareRenderInfo(),e=this.statisticComponent.getSystemInfo(),o={driver:e.driver,vender:e.vender,webgl:e.version,os:e.os};log$R.warn(JSON.stringify(i)),log$R.warn(JSON.stringify(o))});ct(this,"addNewLowPolyMesh",async(i,e)=>(this._currentShader==null&&await this.initSceneManager(),this._lowpolyManager.addNewLowPolyMesh(i,e,this._currentShader)));ct(this,"initSceneManager",async()=>(await this._materialManager.initMaterial(),this.applyShader()));ct(this,"registerAfterRender",()=>{var i;if(this._forceKeepVertical){const e=this.canvas.width,o=this.canvas.height;let s=0,c=[[0,0,0,0],[0,0,0,0]];if(((i=this._cameraManager.MainCamera)==null?void 0:i.fovMode)===Camera$1.FOVMODE_HORIZONTAL_FIXED?(s=Math.ceil((o-this._yuvInfo.height*e/this._yuvInfo.width)/2),c=[[0,0,e,s],[0,o-s,e,s]]):(s=Math.ceil((e-this._yuvInfo.width*o/this._yuvInfo.height)/2),c=[[0,0,s,o],[e-s,0,s,o]]),s>0){this.gl.enable(this.gl.SCISSOR_TEST);for(let d=0;d<c.length;++d)this.gl.scissor(c[d][0],c[d][1],c[d][2],c[d][3]),this.gl.clearColor(0,0,0,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT);this.gl.disable(this.gl.SCISSOR_TEST)}}});ct(this,"resetRender",()=>{this.scene.environmentTexture&&(this.scene.environmentTexture._texture?this.lightComponent.setIBL(this.scene.environmentTexture._texture.url):this.scene.environmentTexture.url&&this.lightComponent.setIBL(this.scene.environmentTexture.url))});const d=/iphone|ipad/gi.test(window.navigator.userAgent)||e.disableWebGL2;o||(o=new Engine(i,!0,{preserveDrawingBuffer:!0,stencil:!0,disableWebGL2Support:d},!0)),s||(s=new Scene(o)),this.scene=s,this.engine=o,this.canvas=i,this.scene.clearColor=new Color4(.7,.7,.7,1),this.engine.getCaps().parallelShaderCompile=void 0,this._initEngineScaleNumber=this.engine.getHardwareScalingLevel(),this.engine.enableOfflineSupport=!1,this.engine.doNotHandleContextLost=!0,this.scene.clearCachedVertexData(),this.scene.cleanCachedTextureBuffer(),this.urlTransformer=e.urlTransformer||(j=>Promise.resolve(j)),e.logger&&Logger$1.setLogger(e.logger),this.gl=i.getContext("webgl2",{preserveDrawingBuffer:!0})||i.getContext("webgl",{preserveDrawingBuffer:!0})||i.getContext("experimental-webgl",{preserveDrawingBuffer:!0}),this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,1),this._currentPanoId=0,e.forceKeepVertical!=null&&(this._forceKeepVertical=e.forceKeepVertical),e.panoInfo!=null&&(this.panoInfo=e.panoInfo),e.shaderMode!=null&&(this.shaderMode=e.shaderMode),e.yuvInfo!=null?this._yuvInfo=e.yuvInfo:this._yuvInfo={width:e.videoResOriArray[0].width,height:e.videoResOriArray[0].height,fov:50},e.cameraParam!=null&&(this.cameraParam=e.cameraParam),e.nonlinearCanvasResize!=null&&(this._nonlinearCanvasResize=e.nonlinearCanvasResize),this._cameraManager=new XCameraComponent(this.canvas,this.scene,{cameraParam:this.cameraParam,yuvInfo:this._yuvInfo,forceKeepVertical:this._forceKeepVertical}),this._lowpolyManager=new XStaticMeshComponent(this),this._materialManager=new XMaterialComponent(this,{videoResOriArray:e.videoResOriArray,yuvInfo:this._yuvInfo,panoInfo:this.panoInfo,shaderMode:this.shaderMode}),this._statisticManager=new XStats(this),this._breathPointManager=new XBreathPointManager(this),this._decalManager=new XDecalManager(this),this._avatarManager=new XAvatarManager(this),this._billboardManager=new XBillboardManager(this),this.billboardComponent.loadBackGroundTexToIDB();let _=!1,b=!1;e.disableLight!=null&&(_=e.disableLight),e.disablePostprocess!=null&&(b=e.disablePostprocess),_||(this._lightManager=new XLightManager(this)),b||this.postprocessing(),this.initSceneManager(),this.engineRunTimeStats=new XEngineRunTimeStats,/iphone/gi.test(window.navigator.userAgent)&&window.devicePixelRatio&&window.devicePixelRatio===3&&window.screen.width===375&&window.screen.height===812?this.engine.setHardwareScalingLevel(this._initEngineScaleNumber*2):this.engine.setHardwareScalingLevel(this._initEngineScaleNumber*(c||1.8)),this.scene.registerBeforeRender(()=>{this._nonlinearCanvasResize&&this._bChangeEngineSize&&(this.setEngineSize(this._yuvInfo),this._bChangeEngineSize=!1)}),this.scene.registerAfterRender(()=>{this._nonlinearCanvasResize||this.registerAfterRender()}),window.addEventListener("resize",()=>{this._nonlinearCanvasResize?this._bChangeEngineSize=!0:this.engine.resize()}),XBillboardManager.alphaWidthMap=getAlphaWidthMap("Arial",this.scene),this.uploadHardwareSystemInfo()}get yuvInfo(){return this.getCurrentShaderMode()==1?this._yuvInfo:{width:-1,height:-1,fov:-1}}set yuvInfo(i){this.getCurrentShaderMode()==1&&(this._yuvInfo=i,this._cameraManager.cameraFovChange(i))}get mainScene(){return this.scene}get cameraComponent(){return this._cameraManager}get staticmeshComponent(){return this._lowpolyManager}get materialComponent(){return this._materialManager}get statisticComponent(){return this._statisticManager}get avatarComponent(){return this._avatarManager}get lightComponent(){return this._lightManager}get Engine(){return this.engine}get Scene(){return this.scene}get billboardComponent(){return this._billboardManager}get breathPointComponent(){return this._breathPointManager}get skytvComponent(){return this._skytv}get mvComponent(){return this._mv}get decalComponent(){return this._decalManager}get currentShader(){return this._currentShader}get initEngineScaleNumber(){return this._initEngineScaleNumber}setImageQuality(i){i==0?(this.engine.setHardwareScalingLevel(this.adaptRatio(0)),this.enablePostProcessing(!1),this._lightManager.enableShadow(!1),this._materialManager._updatePureVideoShaderInput(),log$R.info("[Engine] change image quality to low")):i==1?(this.engine.setHardwareScalingLevel(this.adaptRatio(1)),this.enablePostProcessing(!0),this._lightManager.enableShadow(!0),this._materialManager._updatePureVideoShaderInput(),log$R.info("[Engine] change image quality to mid")):i==2&&(this.engine.setHardwareScalingLevel(this.adaptRatio(2)),this.enablePostProcessing(!0),this._lightManager.enableShadow(!0),this._materialManager._updatePureVideoShaderInput(),log$R.info("[Engine] change image quality to high"))}adaptRatio(i){const e=Math.max(this.canvas.clientWidth,this.canvas.clientHeight);return i==0?e/853:i==1?e/1280:e/1920}setNonlinearCanvasResize(i){this._nonlinearCanvasResize=i,this._bChangeEngineSize=i,i||this.engine.resize()}changeCameraFovWithShaderUpdate(i){this.materialComponent.changeCameraFovWithShaderUpdate(i)}setBackgroundColor(i){this.scene.clearColor=new Color4(i.r,i.g,i.b,i.a)}setBackgroundImg(i){return this._backgroundImg!=null&&this._backgroundImg.url==i?Promise.resolve(!0):new Promise((e,o)=>{this.urlTransformer(i).then(s=>{this._backgroundImg==null?this._backgroundImg={layer:new Layer("tex_background_"+Date.now(),s,this.Scene,!0),url:i}:this._backgroundImg.url!=i&&this._backgroundImg.layer!=null&&this._backgroundImg.layer.texture!=null&&(this._backgroundImg.layer.texture.updateURL(s),this._backgroundImg.layer.name="tex_background_"+Date.now(),this._backgroundImg.url=i),e(!0)}).catch(s=>{log$R.error(`[Engine] set background image Error: ${s}`),o(`[Engine] set background image Error: ${s}`)})})}cleanTheWholeScene(){const i=this.scene.getFrameId();this.scene.onBeforeRenderObservable.clear(),this.scene.onAfterRenderObservable.clear(),this.scene.clearCachedVertexData(),this.scene.cleanCachedTextureBuffer(),this.scene.registerBeforeRender(()=>{this.scene.getFrameId()-i>5&&this.scene.dispose()})}getAreaAvatar(i,e){const o=[];return this._avatarManager.getAvatarList().forEach(s=>{const c=i,d=s.position;d&&c&&calcDistance3D(c,d)<e&&o.push(s.id)}),o}setEngineSize(i){const e=i.width,o=i.height,s=this.canvas.width;this.canvas.height,this.engine.setSize(Math.round(s),Math.round(s*(o/e)))}getCurrentShaderMode(){return this._currentShader===this._materialManager.getDefaultShader()?0:this._currentShader===this._materialManager.getPureVideoShader()?1:2}addSkyTV(i,e){return this._skytv=new XTelevision(this.scene,i,this,e),this._skytv}addMv(i,e){this._mv.push(new XTelevision(this.scene,i,this,e))}addMeshInfo(i){this._lowpolyManager.setMeshInfo(i)}applyShader(){return new Promise((i,e)=>{this.shaderMode==EShaderMode.videoAndPano||this.shaderMode==EShaderMode.video?this.changeVideoShaderForLowModel():this.shaderMode==EShaderMode.default&&this.changeDefaultShaderForLowModel(),i(!0)})}changeHardwareScaling(i){i<1?i=1:i>2.5&&(i=2.5),this._bChangeEngineSize=!0,this.engine.setHardwareScalingLevel(this._initEngineScaleNumber*i)}getCurrentUsedPanoId(){return this._currentPanoId}render(){try{this.scene.render()}catch(i){throw log$R.error(`[Engine] Render Error: ${i}`),i}}isReadyToRender(i){const{checkMesh:e=!0,checkEffect:o=!1,checkPostProgress:s=!1,checkParticle:c=!1,checkAnimation:d=!1,materialNameWhiteLists:_=[]}=i;if(this.scene._isDisposed)return log$R.error("[Engine] this.scene._isDisposed== false "),!1;let b;const k=this.scene.getEngine();if(o&&!k.areAllEffectsReady())return log$R.error("[Engine] engine.areAllEffectsReady == false"),!1;if(d&&this.scene._pendingData.length>0)return log$R.error("[Engine] scene._pendingData.length > 0 && animation error"),!1;if(e){for(b=0;b<this.scene.meshes.length;b++){const j=this.scene.meshes[b];if(!j.isEnabled()||!j.subMeshes||j.subMeshes.length===0||j!=null&&j.material!=null&&!(j.material.name.startsWith("Pure")||j.material.name.startsWith("Pano")))continue;if(!j.isReady(!0))return log$R.error(`[Engine] scene. mesh isReady == false, mesh name:${j.name}, mesh xtype: ${j==null?void 0:j.xtype}, mesh xgroup: ${j==null?void 0:j.xgroup}, mesh xskinInfo: ${j==null?void 0:j.xskinInfo}`),!1;const $=j.hasThinInstances||j.getClassName()==="InstancedMesh"||j.getClassName()==="InstancedLinesMesh"||k.getCaps().instancedArrays&&j.instances.length>0;for(const _e of this.scene._isReadyForMeshStage)if(!_e.action(j,$))return log$R.error(`[Engine] scene._isReadyForMeshStage == false, mesh name:${j.name}, mesh xtype: ${j==null?void 0:j.xtype}, mesh xgroup: ${j==null?void 0:j.xgroup}, mesh xskinInfo: ${j==null?void 0:j.xskinInfo}`),!1}for(b=0;b<this.scene.geometries.length;b++)if(this.scene.geometries[b].delayLoadState===2)return log$R.error("[Engine] geometry.delayLoadState === 2"),!1}if(s){if(this.scene.activeCameras&&this.scene.activeCameras.length>0){for(const j of this.scene.activeCameras)if(!j.isReady(!0))return log$R.error("[Engine] camera not ready === false, ",j.name),!1}else if(this.scene.activeCamera&&!this.scene.activeCamera.isReady(!0))return log$R.error("[Engine] activeCamera ready === false, ",this.scene.activeCamera.name),!1}if(c){for(const j of this.scene.particleSystems)if(!j.isReady())return log$R.error("[Engine] particleSystem ready === false, ",j.name),!1}return!0}changePanoShaderForLowModel(i){return log$R.info(`[Engine] changePanoShaderForLowModel: ${i}`),this._materialManager.allowYUVUpdate(),new Promise((e,o)=>{this._materialManager._isInDynamicRange(i)==!1&&o(!1),this._currentPanoId=i,this._currentShader=this._materialManager.getDynamicShader(i),this.changeShaderForLowModel().then(()=>{e(!0)})})}changeVideoShaderForLowModel(){return log$R.info("[Engine] changeVideoShaderForLowModel"),this._currentShader=this._materialManager.getPureVideoShader(),this._materialManager.allowYUVUpdate(),this.changeShaderForLowModel()}changeDefaultShaderForLowModel(){return log$R.info("[Engine] changeDefaultShaderForLowModel"),this._currentShader=this._materialManager.getDefaultShader(),this._materialManager.stopYUVUpdate(),this.changeShaderForLowModel()}changeShaderForLowModel(){return new Promise((i,e)=>{this._lowpolyManager.getMeshes().forEach(o=>{o.setMaterial(this._currentShader)}),this._lowpolyManager.getCgMesh().mesh.material=this._currentShader,i(!0)})}setIBL(i){this._lightManager.setIBL(i)}enablePostProcessing(i){this._pipeLine&&(this._pipeLine.bloomEnabled=i)}postprocessing(){const i=new DefaultRenderingPipeline("default",!0,this.scene);i.imageProcessingEnabled=!1,i.bloomEnabled=!0,i.bloomThreshold=1,i.bloomWeight=1,i.bloomKernel=64,i.bloomScale=.1,this._pipeLine=i}getGround(i){const e=this._lowpolyManager.getMeshes(),o=[];return e.forEach(s=>{s.mesh.name.indexOf("SM_Stage")>=0&&o.push(s.mesh)}),this.Scene.meshes.forEach(s=>{s.name.split("_")[0]==="ground"&&o.push(s)}),o}}new Logger$1("XVolume");class WorldStore{static get DefaultWorld(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}}ct(WorldStore,"Instances",new Array);class XLevel extends XObject{constructor(){var e;super();ct(this,"_OwningWorld");ct(this,"Actors");ct(this,"Components");this._OwningWorld=null,(e=XWorld.GetDefaultWorld())==null||e.Levels.push(this),this.Actors=new Array,this.Components=new Array}get OwningWorld(){return this._OwningWorld}set OWningWorld(e){this._OwningWorld=e}dispose(){var o;const e=XWorld.GetDefaultWorld().Levels.indexOf(this);(o=XWorld.GetDefaultWorld())==null||o.Levels.splice(e,1)}}class XWorld extends XObject{constructor(){super();ct(this,"_persistentLevel");ct(this,"Levels");ct(this,"Components");XWorld.Instances.push(this),this._persistentLevel=null,this.Levels=new Array,this.Components=new Array}static GetDefaultWorld(){return WorldStore.DefaultWorld}static get Instances(){return WorldStore.Instances}get persistentLevel(){return this._persistentLevel==null&&(this._persistentLevel=new XLevel),this._persistentLevel}set persistentLevel(e){this._persistentLevel=e}dispose(){const e=XWorld.Instances.indexOf(this);XWorld.Instances.splice(e,1),this.Levels=[],this.Components=[],this._persistentLevel=null}}class XActorComponent extends XObject{constructor(){super();ct(this,"_ownerPrivate");ct(this,"_worldPrivate");ct(this,"_tickEnabled");this._ownerPrivate=null,this._worldPrivate=XWorld.GetDefaultWorld(),this._tickEnabled=!0}Tick(){}ReceiveTick(){this.tickEnabled&&this.Tick()}get tickEnabled(){return this._tickEnabled}set tickEnabled(e){this._tickEnabled=e}get owner(){return this._ownerPrivate}set owner(e){e&&(this._ownerPrivate=e,this._outer=e==null?void 0:e.outer)}set outer(e){this._outer=e}get outer(){return this.owner&&(this._outer=this.owner.outer),this._outer}RegisterComponentWithWorld(e){}}var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=(a,i,e,o)=>{for(var s=o>1?void 0:o?__getOwnPropDesc$2(i,e):i,c=a.length-1,d;c>=0;c--)(d=a[c])&&(s=(o?d(i,e,s):d(s))||s);return o&&s&&__defProp$2(i,e,s),s};AssetContainer.prototype.clone=function(a,i=!0,e,o=!0){const s=new AssetContainer(this.scene);a||(a="");const c=$=>a+"_CloneOf_"+$,d={},_={},b=[],k=[];e||(e={doNotInstantiate:!0});const j=($,_e)=>{if(d[$.uniqueId]=_e.uniqueId,_[_e.uniqueId]=_e,c&&(_e.name=c($.name)),_e instanceof Mesh){const et=_e;if(s.meshes.push(_e),_e.geometry&&s.geometries.push(_e.geometry),et.morphTargetManager){const tt=$.morphTargetManager;et.morphTargetManager=tt.clone(),s.morphTargetManagers.push(et.morphTargetManager);for(let rt=0;rt<tt.numTargets;rt++){const it=tt.getTarget(rt),nt=et.morphTargetManager.getTarget(rt);d[it.uniqueId]=nt.uniqueId,_[nt.uniqueId]=nt}}}else _e instanceof TransformNode&&s.transformNodes.push(_e)};return this.transformNodes.forEach($=>{if(!$.parent){const _e=$.instantiateHierarchy(null,e,(et,tt)=>{j(et,tt)});_e&&s.rootNodes.push(_e)}}),this.meshes.forEach($=>{if(!$.parent){const _e=$.instantiateHierarchy(null,e,(et,tt)=>{if(j(et,tt),tt.material){const rt=tt;if(rt.material)if(i){const it=et.material;if(k.indexOf(it)===-1){let nt=it.clone(c?c(it.name):"Clone of "+it.name);if(s.materials.push(nt),k.push(it),d[it.uniqueId]=nt.uniqueId,_[nt.uniqueId]=nt,it.getClassName()==="MultiMaterial"){const ot=it;for(const at of ot.subMaterials)!at||(nt=at.clone(c?c(at.name):"Clone of "+at.name),k.push(at),d[at.uniqueId]=nt.uniqueId,_[nt.uniqueId]=nt);ot.subMaterials=ot.subMaterials.map(at=>at&&_[d[at.uniqueId]]),s.multiMaterials.push(ot)}}rt.getClassName()!=="InstancedMesh"&&(rt.material=_[d[it.uniqueId]])}else rt.material.getClassName()==="MultiMaterial"?(this.scene.multiMaterials.indexOf(rt.material)===-1&&this.scene.addMultiMaterial(rt.material),s.multiMaterials.indexOf(rt.material)===-1&&s.multiMaterials.push(rt.material)):(this.scene.materials.indexOf(rt.material)===-1&&this.scene.addMaterial(rt.material),s.materials.indexOf(rt.material)===-1&&s.materials.push(rt.material))}});_e&&s.rootNodes.push(_e)}}),this.skeletons.forEach($=>{const _e=$.clone(c?c($.name):"Clone of "+$.name);$.overrideMesh&&(_e.overrideMesh=_[d[$.overrideMesh.uniqueId]]);for(const et of this.meshes)if(et.skeleton===$&&!et.isAnInstance){const tt=_[d[et.uniqueId]];if(tt.isAnInstance||(tt.skeleton=_e,b.indexOf(_e)!==-1))continue;b.push(_e);for(const rt of _e.bones)rt._linkedTransformNode&&(rt._linkedTransformNode=_[d[rt._linkedTransformNode.uniqueId]])}s.skeletons.push(_e)}),this.animationGroups.forEach($=>{const _e=$.clone($.name,et=>_[d[et.uniqueId]]||et,o);s.animationGroups.push(_e)}),this.textures.forEach($=>{const _e=$.clone();_e&&s.textures.push(_e)}),this.cameras.forEach($=>{s.cameras.push($.clone(c($.name)))}),this.lights.forEach($=>{const _e=$.clone(c($.name));_e&&s.lights.push(_e)}),s};AssetContainer.prototype.GetName=function(){return this._name||(this._name=""),this._name};AssetContainer.prototype.SetName=function(a){this._name=a};AssetContainer.prototype.GetRootNode=function(){return this._rootNode||(this._rootNode=this.meshes[0]),this._rootNode};AssetContainer.prototype.CreateRootNodeByName=function(a){const i=new Mesh("assetContainerRootMesh_"+a,this.scene);return this.meshes.forEach(e=>{e.parent||i.addChild(e)}),this.meshes.unshift(i),i};AssetContainer.prototype.GetMeshesWithoutParent=function(){const a=new Array;return this.meshes.forEach(i=>{i.parent||a.push(i)}),a};AssetContainer.prototype.GetOwner=function(){return this._owner};AssetContainer.prototype.SetOwner=function(a){this._owner||(this._owner=new XObject),this._owner=a};AssetContainer.prototype.toJSON=function(){const a=this.GetOwner(),i=a==null?void 0:a.outer;return i?i.SaveAsset(this):""};AssetContainer.prototype.getClassName=function(){return"AssetContainer"};new Logger$1("XSceneComponent");class XSceneComponent extends XActorComponent{constructor(){super();ct(this,"_attachParent");ct(this,"_attachChildren");ct(this,"_rootNode");ct(this,"_billboardMode",0);ct(this,"_castShadow",!0);ct(this,"_asset");ct(this,"_bbox");ct(this,"getBbox",(e={})=>{const{isConst:o=!1,changeWithAvatar:s=!1}=e;let{localCenter:c={x:0,y:0,z:75},width:d=1.32,height:_=1.5,depth:b=.44}=e;if(s){const k=this.scaling;c={x:c.x*k.x,y:c.y*k.y,z:c.z*k.z},d*=k.x,_*=k.y,b*=k.z}if(this.rootNode){let k=new Vector3(0,0,0),j=new Vector3(0,0,0);if(o){const _e=ue4Position2Xverse(c);k=k.add(_e.add(new Vector3(-d/2,-_/2,-b/2))),j=j.add(_e.add(new Vector3(d/2,_/2,b/2)))}else{k=k.add(new Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)),j=j.add(new Vector3(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY)),this.rootNode.getChildMeshes().forEach(tt=>{const rt=tt.getBoundingInfo().boundingBox.minimum,it=tt.getBoundingInfo().boundingBox.maximum;k.x=Math.min(k.x,rt.x),j.x=Math.max(j.x,it.x),k.y=Math.min(k.y,rt.y),j.y=Math.max(j.y,it.y),k.z=Math.min(k.z,rt.z),j.z=Math.max(j.z,it.z)});const _e=j.x-k.x,et=j.z-k.z;k.x-=this.scaling.x*_e/2,j.x+=this.scaling.x*_e/2,j.y*=this.scaling.y,k.z-=this.scaling.z*et/2,j.z+=this.scaling.z*et/2}const $=this.rootNode.computeWorldMatrix(!0);this.bbox?this.bbox.reConstruct(k,j,$):this.bbox=new BoundingBox(k,j,$)}});const e=EngineStore.LastCreatedScene;this._bbox=null,this._attachChildren=new Array,this._attachParent=null,this._asset=new AssetContainer(e),this._rootNode=this._asset.GetRootNode()}getClassName(){return"XSceneComponent"}set asset(e){!e||(this._asset=e,this._asset.SetOwner(this),this._rootNode=this._asset.GetRootNode())}get asset(){return this._asset}set castShadow(e){!this._rootNode||(this._rootNode.getChildMeshes().forEach(o=>{}),this._castShadow=e)}get castShadow(){return this._castShadow}set position(e){if(!this.rootNode||!e)return;const o=ue4Position2Xverse(e);o&&(this.rootNode.position=o)}get position(){return this.rootNode?xversePosition2Ue4(this.rootNode.position):{x:0,y:0,z:0}}set rotation(e){if(!this.rootNode||!e)return;const o=ue4Rotation2Xverse(e);o&&(this.rootNode.rotation=o)}get rotation(){return this.rootNode?xverseRotation2Ue4(this.rootNode.rotation):{pitch:0,yaw:0,roll:0}}set scaling(e){if(!this.rootNode||!e)return;const o=ue4Scaling2Xverse(e);o&&(this.rootNode.scaling=o)}get scaling(){if(!this.rootNode)return{x:0,y:0,z:0};const e=this.rootNode.scaling;return{x:e.x,y:-e.z,z:e.y}}setEnabled(e){!this.rootNode||(this.rootNode.setEnabled(e),this._attachChildren.forEach(o=>{o.setEnabled(e)}))}isEnabled(){return this.rootNode?this.rootNode.isEnabled:null}get billboardMode(){return this._billboardMode}set bllboardMode(e){this._billboardMode!==e&&(!this.rootNode||this._rootNode.getChildMeshes().forEach(o=>{o.billboardMode=e}))}set name(e){!this.rootNode||(this.rootNode.name=e)}get name(){return this.rootNode?this.rootNode.name:""}get bbox(){return this._bbox}set bbox(e){this._bbox=e}get rootNode(){return this._rootNode}postLoad(){var e;this._asset&&(this.asset=this._asset,this._rootNode=(e=this._asset)==null?void 0:e.GetRootNode())}dispose(){var e,o;(e=this._asset)==null||e.dispose(),(o=this._bbox)==null||o.dispose(),this._attachChildren=[],this._attachParent=null}DetachFromComponent(e){!this.rootNode||(this.rootNode.parent=null,e._attachChildren.splice(e._attachChildren.indexOf(this),1),this._attachParent=null)}AttachToComponent(e,o={x:0,y:0,z:0}){if(!this.asset||!this.rootNode)return;const s=this.rootNode;this.asset.scene;const c=ue4Position2Xverse(o);s.setParent(e.rootNode),s.position=c,e._attachChildren.push(this),this._attachParent=e}}__decorateClass$2([xProperty("xAsset")],XSceneComponent.prototype,"_asset",2);RegisterXObjectClass("XSceneComponent",XSceneComponent);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=(a,i,e,o)=>{for(var s=o>1?void 0:o?__getOwnPropDesc$1(i,e):i,c=a.length-1,d;c>=0;c--)(d=a[c])&&(s=(o?d(i,e,s):d(s))||s);return o&&s&&__defProp$1(i,e,s),s};new Logger$1("XActor");class XActor extends XObject{constructor(){super();ct(this,"_children");ct(this,"_ownedComponent");ct(this,"_rootComponent");ct(this,"_tickObserver");ct(this,"_tickInterval");const e=EngineStore.LastCreatedScene;this._children=new Array,this._ownedComponent=new Set,this._rootComponent=new XSceneComponent,this._rootComponent.owner=this,this._tickInterval=1;let o=0;this._tickObserver=e.onAfterRenderObservable.add(()=>{o+=1,o==this._tickInterval&&(this._tick(),o=0)})}set outer(e){this._outer=e,this._ownedComponent.forEach(o=>{o.outer=e})}get outer(){return this._outer}get rootComponent(){return this._rootComponent}getClassName(){return"XActor"}_tick(){this._ownedComponent.forEach(e=>{e.ReceiveTick()})}get tickInterval(){return this._tickInterval}set tickInterval(e){this._tickInterval=e}AttachToActor(e){e._children.push(this),this._rootComponent.AttachToComponent(e.rootComponent)}postLoad(){this._ownedComponent.add(this._rootComponent)}dispose(){this._children=[],this._ownedComponent.clear(),this._rootComponent.dispose(),this._tickObserver.unregisterOnNextCall=!0}}__decorateClass$1([xProperty("rootComponent")],XActor.prototype,"_rootComponent",2);RegisterXObjectClass("XActor",XActor);var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(a,i,e,o)=>{for(var s=o>1?void 0:o?__getOwnPropDesc(i,e):i,c=a.length-1,d;c>=0;c--)(d=a[c])&&(s=(o?d(i,e,s):d(s))||s);return o&&s&&__defProp(i,e,s),s};class XAccessory extends XActor{constructor(){super();ct(this,"_pointId");ct(this,"_attachBoneId");ct(this,"_attachType");ct(this,"_attachPointOffset");ct(this,"_attachPointRotation");ct(this,"_attachPointScale")}getClassName(){return"XAccessory"}set attachType(e){this._attachType=e}get attachType(){return this._attachType}set attachBoneId(e){this._attachBoneId=e}get attachBoneId(){return this._attachBoneId}set attachPointOffset(e){this._attachPointOffset=e}get attachPointOffset(){return this._attachPointOffset}set attachPointRotation(e){this._attachPointRotation=e}get attachPointScale(){return this._attachPointScale}set pointId(e){this._pointId=e}get pointId(){return this._pointId}set attachPointOffsetVector3(e){this._attachPointOffset=xversePosition2Ue4(e)}set attachPointScaleVector3(e){this._attachPointScale={x:e.x,y:-e.z,z:e.y}}set attachPointRotationVector3(e){this._attachPointRotation=xverseRotation2Ue4_mesh(e)}setLocalRTS(e){if(e){const o=ue4Scaling2Xverse(this._attachPointScale);o&&(e.scaling=o);const s=ue4Position2Xverse(this._attachPointOffset);s&&(e.position=s);const c=ue4Rotation2Xverse_mesh(this._attachPointRotation);c&&(e.rotation=c)}}setParentTo(e){this.rootComponent&&this.rootComponent.rootNode&&(this.rootComponent.rootNode.parent=e,this.setLocalRTS(this.rootComponent.rootNode))}detachFrom(e=!0){e?this.dispose():this.rootComponent&&this.rootComponent.rootNode&&(this.rootComponent.rootNode.parent=null,this.rootComponent.rootNode.detachFromBone(!1))}attachTo(e){var o;if(!e.skeleton){(o=this.rootComponent.rootNode)==null||o.setEnabled(!1);return}switch(this._attachType){case 0:this.rootComponent&&this.rootComponent.rootNode&&e.component.body&&(this.rootComponent.rootNode.parent=e.component.body.root,this.setLocalRTS(this.rootComponent.rootNode));break;case 1:{const s=e.skeleton.bones.find(c=>c.name===this._attachBoneId);s&&this.rootComponent&&this.rootComponent.rootNode&&e.component.body&&(this.rootComponent.rootNode.attachToBone(s,e.component.body.root),this.setLocalRTS(this.rootComponent.rootNode));break}}}async play(){this.rootComponent.asset&&this.rootComponent.asset.animationGroups&&this.rootComponent.asset.animationGroups.length>0&&(this.rootComponent.asset.animationGroups[0].play(),this.rootComponent.asset.animationGroups[0].onAnimationGroupEndObservable.addOnce(()=>Promise.resolve(null)))}stop(){this.rootComponent.asset&&this.rootComponent.asset.animationGroups&&this.rootComponent.asset.animationGroups.length>0&&this.rootComponent.asset.animationGroups[0].stop()}}__decorateClass([xProperty("_pointId")],XAccessory.prototype,"_pointId",2);__decorateClass([xProperty("_attachBoneId")],XAccessory.prototype,"_attachBoneId",2);__decorateClass([xProperty("_attachType")],XAccessory.prototype,"_attachType",2);__decorateClass([xProperty("_attachPointOffset")],XAccessory.prototype,"_attachPointOffset",2);__decorateClass([xProperty("_attachPointRotation")],XAccessory.prototype,"_attachPointRotation",2);__decorateClass([xProperty("_attachPointScale")],XAccessory.prototype,"_attachPointScale",2);RegisterXObjectClass("XAccessory",XAccessory);function getPointerWorldPos(a,i){const e=a.pick(a.pointerX,a.pointerY,()=>!1),o=new Vector3(0,0,0);return(e==null?void 0:e.ray)!=null&&(o.x=e.ray.origin.x+e.ray.direction.x*i,o.y=e.ray.origin.y+e.ray.direction.y*i,o.z=e.ray.origin.z+e.ray.direction.z*i),(e==null?void 0:e.hit)&&(e==null?void 0:e.pickedMesh)?{position:xversePosition2Ue4(o),meshName:e.pickedMesh.name}:{position:xversePosition2Ue4(o),meshName:""}}const log$Q=new Logger$1("ScreenShot");function CreateScreenshot(a,i,e,o,s="image/png",c=!1){const{height:d,width:_}=_getScreenshotSize(a,i,e);if(log$Q.info("[Engine]CreateScreenshot!"),!(d&&_)){log$Q.error("[Engine]CreateScreenshot Invalid 'size' parameter !");return}Tools._ScreenshotCanvas||(Tools._ScreenshotCanvas=document.createElement("canvas")),Tools._ScreenshotCanvas.width=_,Tools._ScreenshotCanvas.height=d;const b=Tools._ScreenshotCanvas.getContext("2d"),k=a.getRenderWidth()/a.getRenderHeight();let j=_,$=j/k;$>d&&($=d,j=$*k);const _e=Math.max(0,_-j)/2,et=Math.max(0,d-$)/2;i.getScene().onAfterRenderObservable.addOnce(function(){const rt=a.getRenderingCanvas();b&&rt?b.drawImage(rt,_e,et,j,$):log$Q.error("[Engine]CreateScreenshot Invalid renderContext and renderingCanvas!"),c?(Tools.EncodeScreenshotCanvasData(void 0,s),o&&o("")):Tools.EncodeScreenshotCanvasData(o,s)})}function CreateScreenshotAsync(a,i,e,o="image/png"){return new Promise((s,c)=>{CreateScreenshot(a,i,e,d=>{typeof d!="undefined"?s(d):c(new Error("Data is undefined"))},o)})}function CreateScreenshotUsingRenderTarget(a,i,e,o,s="image/png",c=1,d=!1,_,b=!1,k=!1){const{height:j,width:$}=_getScreenshotSize(a,i,e),_e={width:$,height:j};if(!(j&&$)){log$Q.error("Invalid 'size' parameter !");return}const et=i.getScene();let tt=null;const rt=et.activeCameras;et.activeCameras=null,et.activeCamera!==i&&(tt=et.activeCamera,et.activeCamera=i),et.render();const it=new RenderTargetTexture("screenShot",_e,et,!1,!1,Constants.TEXTURETYPE_UNSIGNED_INT,!1,Texture.NEAREST_SAMPLINGMODE,void 0,k,void 0,void 0,void 0,c);it.renderList=null,it.samples=c,it.renderSprites=b,et.onAfterRenderTargetsRenderObservable.addOnce(function(){it.readPixels(void 0,void 0,void 0,!1).then(ot=>{Tools.DumpData($,j,ot,o,s,_,!0),it.dispose()})});const nt=()=>{et.incrementRenderId(),et.resetCachedMaterial(),it.render(!0),et.incrementRenderId(),et.resetCachedMaterial(),tt&&(et.activeCamera=tt),et.activeCameras=rt,i.getProjectionMatrix(!0),et.render()};if(d){const ot=new FxaaPostProcess("antialiasing",1,et.activeCamera);it.addPostProcess(ot),ot.getEffect().isReady()?nt():ot.getEffect().onCompiled=()=>{nt()}}else nt()}function CreateScreenshotUsingRenderTargetAsync(a,i,e,o="image/png",s=1,c=!1,d,_=!1){return new Promise((b,k)=>{CreateScreenshotUsingRenderTarget(a,i,e,j=>{typeof j!="undefined"?b(j):k(new Error("Data is undefined"))},o,s,c,d,_)})}function _getScreenshotSize(a,i,e){let o=0,s=0;if(typeof e=="object"){const c=e.precision?Math.abs(e.precision):1;e.width&&e.height?(o=e.height*c,s=e.width*c):e.width&&!e.height?(s=e.width*c,o=Math.round(s/a.getAspectRatio(i))):e.height&&!e.width?(o=e.height*c,s=Math.round(o*a.getAspectRatio(i))):(s=Math.round(a.getRenderWidth()*c),o=Math.round(s/a.getAspectRatio(i)))}else isNaN(e)||(o=e,s=e);return s&&(s=Math.floor(s)),o&&(o=Math.floor(o)),{height:o|0,width:s|0}}const initSideEffects=()=>{Tools.CreateScreenshot=CreateScreenshot,Tools.CreateScreenshotAsync=CreateScreenshotAsync,Tools.CreateScreenshotUsingRenderTarget=CreateScreenshotUsingRenderTarget,Tools.CreateScreenshotUsingRenderTargetAsync=CreateScreenshotUsingRenderTargetAsync};initSideEffects();const VERSION$2="1.0.97";ParticleSystem.prototype.isReady=function(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;if(this.blendMode!==ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return!0};const animationMap=new Map;animationMap.set("Falling",new AnimationRange("Falling1",0,15));animationMap.set("Click",new AnimationRange("Click",16,39));animationMap.set("Disappear",new AnimationRange("Disappear",40,47));class SpriteRain{constructor(i,e,o,s,c=1,d=1,_=36,b=15,k){ct(this,"_scene");ct(this,"_subSequence");ct(this,"_rainParticles");ct(this,"_sky");ct(this,"_pickNumber");ct(this,"_radius");ct(this,"_rainNumber");ct(this,"_rainSize");ct(this,"_rainSpeed");ct(this,"_ground");ct(this,"_keepOnGroundDuration");ct(this,"_animationMap",new Map);ct(this,"clickAction",i=>{const e="Click",o=this._animationMap.get(e);!o||(i.isPickable=!1,this._pickNumber+=1,i.playAnimation(o.from,o.to,!1,20,()=>{i.isVisible=!1}))});ct(this,"onPointerDownCallback",()=>{const i=this._scene.pickSprite(this._scene.pointerX,this._scene.pointerY);i.hit&&i.pickedSprite&&this.clickAction(i.pickedSprite)});ct(this,"hitGroundAction",i=>{const e="Disappear",o=this._animationMap.get(e);!o||i.playAnimation(o.from,o.to,!1,this._keepOnGroundDuration*(25/60)/(o.to-o.from),()=>{i.isVisible=!1})});this._scene=i,this._subSequence=new XSubSequence(i,e,k),this._sky=ue4Position2Xverse(o),this._pickNumber=0,this._ground=ue4Position2Xverse(s),this._radius=b,this._rainNumber=_,this._rainParticles=new Array,this._rainSize=d,this._rainSpeed=c,this._keepOnGroundDuration=2*1e3,this._animationMap=animationMap}init(){return new Promise((i,e)=>{this._subSequence.init().then(()=>{this.initSpirteRain(),this._subSequence.isPickable=!0,this._scene.onPointerDown=this.onPointerDownCallback,this._subSequence._spriteGroups.forEach(o=>{o.sprites.forEach(s=>{const c=this._scene.onBeforeRenderObservable.add(()=>{s.position.y<=this._ground.y&&(c&&this._scene.onBeforeRenderObservable.remove(c),this.hitGroundAction(s))})})}),i()},()=>{e()})})}play(i){return new Promise((e,o)=>{var d;const s="Falling",c=this._animationMap.get(s);!c||((d=this._rainParticles)==null||d.forEach(_=>{_.start()}),this._subSequence.show(),this._subSequence._spriteGroups.forEach(_=>{_.sprites.forEach((b,k)=>{const j=k/this._rainNumber*b.delay,$=1-k%2*2;b.playAnimation(c.from,c.to,!0,b.delay+$*j,()=>{e()})})}))})}stop(){var i;this._pickNumber=0,this._subSequence.hide(),this._subSequence.animGroup.stop(),(i=this._rainParticles)==null||i.forEach(e=>{e.stop()})}dispose(){var i;this._subSequence.dispose(),(i=this._rainParticles)==null||i.forEach(e=>{e.dispose(!0)}),this._scene.onPointerDown===this.onPointerDownCallback&&(this._scene.onPointerDown=()=>{})}get pickNumber(){return this._pickNumber}initSpirteRain(){var e;const i=this._rainNumber;(e=this._subSequence._spriteGroups)==null||e.forEach(o=>{var d;const s=o.sprites[0];s.size*=this._rainSize,s.position=this._sky;for(let _=0;_<i-1;_++){const b=new Sprite("money"+_.toString(),o);b.size=s.size,b.fromIndex=s.fromIndex,b.toIndex=s.toIndex,b.delay=s.delay,b.cellIndex=s.cellIndex,b.position=s.position}const c=this.initRainParticle(o.sprites,this._radius);(d=this._rainParticles)==null||d.push(c)})}initRainParticle(i,e){const o=i.length,s=this._sky,c=new ParticleSystem("spawnParticles",o,this._scene);c.emitter=s,c.emitRate=this._rainNumber*100,c.gravity=new Vector3(0,-9.81*this._rainSpeed,0),c.minAngularSpeed=10,c.maxAngularSpeed=100,c.minEmitPower=-25,c.maxEmitPower=-250,c.startPositionFunction=function(_,b){const k=2*Math.random()*Math.PI,j=Math.random()*e*Math.sin(k),$=this.minEmitBox.y,_e=Math.random()*e*Math.cos(k);Vector3.TransformCoordinatesFromFloatsToRef(j,$,_e,_,b)};const d=this._ground;return c.updateFunction=function(_){for(let b=0;b<_.length;b++){const k=_[b];if(k.age+=this._scaledUpdateSpeed,k.age>=k.lifeTime){this.recycleParticle(k),b--;continue}else k.colorStep.scaleToRef(this._scaledUpdateSpeed,this._scaledColorStep),k.color.addInPlace(this._scaledColorStep),k.color.a<0&&(k.color.a=0),k.angle+=k.angularSpeed*this._scaledUpdateSpeed,k.direction.scaleToRef(this._scaledUpdateSpeed,this._scaledDirection),k.position.addInPlace(this._scaledDirection),this.gravity.scaleToRef(this._scaledUpdateSpeed,this._scaledGravity),k.direction.addInPlace(this._scaledGravity);i[b].position.y>d.y&&(i[b].position=k.position.clone(),i[b].angle=k.angle)}},c}}class XRain extends XSubSequence{constructor(i,e,o){super(i,e,o),this.onLoadedObserverable.addOnce(()=>{this._particleGroups.forEach(s=>{const c=s.systems[0];c.getClassName()=="ParticleSystem"&&(c.startPositionFunction=function(d,_){const k=2*Math.random()*Math.PI,j=Math.random()*15*Math.sin(k),$=this.minEmitBox.y,_e=Math.random()*15*Math.cos(k);Vector3.TransformCoordinatesFromFloatsToRef(j,$,_e,d,_)})})})}}const log$P=new Logger$1("Billboard");var BillboardStatus=(a=>(a[a.SHOW=1]="SHOW",a[a.HIDE=0]="HIDE",a[a.DISPOSE=-1]="DISPOSE",a))(BillboardStatus||{});class XBillboard{constructor(i,e=!1,o=!1){ct(this,"_mesh",null);ct(this,"_texture",null);ct(this,"_scalingFactor",1);ct(this,"offsets",null);ct(this,"_pickable");ct(this,"_background",null);ct(this,"_billboardManager");ct(this,"poolobj",null);ct(this,"_usePool");ct(this,"_initMeshScale",new Vector3(1,1,1));ct(this,"_status",-1);ct(this,"_stageChanged",!1);ct(this,"DEFAULT_CONFIGS",{});this._billboardManager=i,this._pickable=e,this._usePool=o}set scalingFactor(i){this._scalingFactor=i}set background(i){this._background=i}get size(){return-1}setStatus(i){i!=this._status&&(this._stageChanged=!0,this._status=i)}get status(){return this._status}get stageChanged(){return this._stageChanged}set stageChanged(i){this._stageChanged=i}init(i="",e=.001,o=.001,s=!1){const c=this._billboardManager.sceneManager.Scene;if(this._usePool){const d=this._billboardManager.billboardPool.getFree(c,e,o,s);this._mesh=d.data,this._mesh.isPickable=this._pickable,this._mesh.xid=i,this._mesh.xtype=EMeshType.XBillboard,this._texture=this._mesh.material.diffuseTexture,this.poolobj=d}else this._mesh=this._billboardManager.createBillboardAsset(c,s);this._mesh.isPickable=this._pickable,this._initMeshScale.x=e*1e3,this._initMeshScale.y=o*1e3,this._mesh.xid=i,this._mesh.xtype=EMeshType.XBillboard,this._texture=this._mesh.material.diffuseTexture,this.setStatus(1),this._stageChanged=!0}dispose(){this._usePool?this.poolobj&&(this._billboardManager.billboardPool.release(this.poolobj),this._mesh=null,this._texture=null,this.poolobj=null):this._mesh&&(this._mesh.dispose(!0,!0),this._mesh=null,this._texture=null),this._background=null}getMesh(){return this._mesh}updateImage(i){return new Promise(e=>{if(this._texture==null){log$P.error("[Engine]Billboard texture not found");return}const o=this._mesh,s=this._texture,c=this._scalingFactor,d=this._initMeshScale.x,_=this._initMeshScale.y,b=this._texture.getContext(),k=this._texture.getSize();b.clearRect(0,0,k.width,k.height);const j=new Image;j.crossOrigin="anonymous",j.src=i,j.onload=()=>{const $=j.width*c,_e=j.height*c;o.scaling.x=$*d,o.scaling.y=_e*_,s.scaleTo($,_e),b.drawImage(j,0,0,$,_e),s.hasAlpha=!0,s.update(),e()}})}show(){this._mesh&&(this._mesh.setEnabled(!0),this._mesh.isPickable=this._pickable)}hide(){this._mesh&&(this._mesh.setEnabled(!1),this._mesh.isPickable=!1)}setId(i){this._mesh&&(this._mesh.xid=i)}setPosition(i){if(i&&this._mesh){const e=ue4Position2Xverse(i);this._mesh.position=e}}updateText(i,e,o=!0,s=[],c=30,d="monospace",_="black",b="bold",k){if(this._texture==null){log$P.error("[Engine]Billboard texture not found");return}const j=this._texture,$=this._mesh,_e=this._scalingFactor,et=this._initMeshScale.x,tt=this._initMeshScale.y;if(i!=""){const rt=this._texture.getContext(),it=this._texture.getSize();rt.clearRect(0,0,it.width,it.height);const nt=new Image;if(o){e!=null?e?this._background=this._billboardManager.userBackGroundBlob:this._background=this._billboardManager.npcBackGroundBlob:this._background||(this._background=this._billboardManager.userBackGroundBlob);let ot=i,at=k&&k<s.length-1?k:s.length-1;if(this._background){if(at>this._background.length){for(let st=0;st<at-this._background.length;st++)s.pop();at=s.length-1,ot=i.slice(0,s[at]-1)+String.fromCharCode(8230)}nt.crossOrigin="anonymous",nt.src=this._background[at-1],nt.onload=function(){const st=nt.width*_e,ut=nt.height*_e;$.scaling.x=st*et,$.scaling.y=ut*tt,j.scaleTo(st,ut),rt.textAlign="center",rt.textBaseline="middle",rt.drawImage(nt,0,0,st,ut);for(let ft=0;ft<at;ft++)j.drawText(ot.slice(s[0+ft],s[1+ft]),st/2,ut*(ft+1)/(at+1)+(ft-(at-1)/2)*_e*10,b+" "+c*_e+"px "+d,_,"transparent",!0);j.hasAlpha=!0}}}else{const ot=k&&k<s.length-1?k:s.length-1,at=480*_e,st=60*_e*ot;this._mesh.scaling=new Vector3(at*et,st*tt,1),j.scaleTo(at,st);const ut=j.getContext();ut.textAlign="center",ut.textBaseline="middle";for(let ft=0;ft<ot;ft++)setTimeout(()=>{j.drawText(i.slice(s[0+ft],s[1+ft]),at/2+2*_e,st*(ft+1)/(ot+1)+(ft-(ot-1)/2)*_e*10+2*_e,b+" "+c*_e+"px "+d,"#333333","transparent",!0),j.drawText(i.slice(s[0+ft],s[1+ft]),at/2,st*(ft+1)/(ot+1)+(ft-(ot-1)/2)*_e*10,b+" "+c*_e+"px "+d,_,"transparent",!0)},0);j.hasAlpha=!0}}else this.clearText()}drawBillboard(i,e,o){var it;const{imageList:s}=i,{texts:c,font:d="monospace",fontsize:_=40,fontcolor:b="#ffffff",fontstyle:k="",linesize:j=20,linelimit:$}=e,{position:_e,offsets:et,scale:tt,compensationZ:rt=0}=o;if(this.scalingFactor=tt||1,et&&(this.offsets={x:et.x*this._scalingFactor,y:et.y*this._scalingFactor,z:et.z*this._scalingFactor}),this.offsets||(this.offsets={x:0,y:0,z:0}),this.setPosition(_e),s&&!c)(it=this._billboardManager.sceneManager)==null||it.urlTransformer(s[0]).then(nt=>{this.updateImage(nt)});else if(c&&!s){const[nt,ot]=getStringBoundaries(c,j,XBillboardManager.alphaWidthMap);this.offsets.z+=this._scalingFactor*rt*(ot.length-1),this.updateText(nt,void 0,!1,ot,_,d,b,k,$)}else if(c&&s){this.background=s;const[nt,ot]=getStringBoundaries(c,j,XBillboardManager.alphaWidthMap);this.offsets.z+=this._scalingFactor*rt*(ot.length-1),this.updateText(nt,void 0,!0,ot,_,d,b,k,$)}this.setStatus(1)}clearText(){if(this._texture!=null){const i=this._texture.getContext(),e=this._texture.getSize();i.clearRect(0,0,e.width,e.height),this._texture.update()}}}var AvatarGroup=(a=>(a.Npc="npc",a.User="user",a))(AvatarGroup||{}),ChangeComponentsMode=(a=>(a[a.Preview=0]="Preview",a[a.Confirm=1]="Confirm",a[a.Cancel=2]="Cancel",a))(ChangeComponentsMode||{}),MotionType=(a=>(a.Walk="walk",a.Run="run",a.Fly="fly",a))(MotionType||{}),MotionAnimtion=(a=>(a.walk="Walking",a.run="Running",a.swim="Swim02",a.idle="Idle",a.swimIdle="Swim01",a))(MotionAnimtion||{});class XverseError extends Error{constructor(e,o){super(o);ct(this,"code");this.code=e}toJSON(){return{code:this.code,message:this.message}}toString(){if(Object(this)!==this)throw new TypeError;let o=this.name;o=o===void 0?"Error":String(o);let s=this.message;s=s===void 0?"":String(s);const c=this.code;return s=c===void 0?s:c+","+s,o===""?s:s===""?o:o+": "+s}}class ParamError extends XverseError{constructor(i){super(1001,i||"\u53C2\u6570\u9519\u8BEF")}}class InternalError extends XverseError{constructor(i){super(1002,i||"\u5185\u90E8\u9519\u8BEF")}}class TimeoutError extends XverseError{constructor(i){super(1003,i||"\u8D85\u65F6")}}class AuthenticationError extends XverseError{constructor(i){super(1004,i||"\u9274\u6743\u5931\u8D25")}}class TokenExpiredError extends XverseError{constructor(i){super(1005,i||"Token \u5DF2\u8FC7\u671F")}}class UnsupportedError extends XverseError{constructor(i){super(1006,i||"\u624B\u673A\u7CFB\u7EDF\u4E0D\u652F\u6301XVerse")}}class InitNetworkTimeoutError extends XverseError{constructor(i){super(1007,i||"\u7F51\u7EDC\u521D\u59CB\u5316\u8D85\u65F6")}}class InitDecoderTimeoutError extends XverseError{constructor(i){super(1008,i||"Decoder \u521D\u59CB\u5316\u8D85\u65F6")}}class InitConfigTimeoutError extends XverseError{constructor(i){super(1009,i||"\u914D\u7F6E\u521D\u59CB\u5316\u8D85\u65F6")}}class InitEngineTimeoutError extends XverseError{constructor(i){super(1010,i||"\u5F15\u64CE\u521D\u59CB\u5316\u8D85\u65F6")}}class InitEngineError extends XverseError{constructor(i){super(1011,i||"\u5F15\u64CE\u521D\u59CB\u5316\u9519\u8BEF")}}class ActionBlockedError extends XverseError{constructor(i){super(1012,i||"\u52A8\u4F5C\u88AB\u5C4F\u853D")}}class PreloadCanceledError extends XverseError{constructor(i){super(1013,i||"\u9884\u52A0\u8F7D\u88AB\u53D6\u6D88")}}class FrequencyLimitError extends XverseError{constructor(i){super(1014,i||"\u9891\u7387\u9650\u5236")}}class UsersUpperLimitError extends XverseError{constructor(i){super(2e3,i||"\u76F4\u64AD\u95F4\u4EBA\u6570\u5DF2\u6EE1")}}class RoomsUpperLimitError extends XverseError{constructor(i){super(2001,i||"\u623F\u95F4\u5230\u8FBE\u4E0A\u9650")}}class ServerParamError extends XverseError{constructor(i){super(2002,i||"\u670D\u52A1\u5668\u53C2\u6570\u9519\u8BEF")}}class LackOfTokenError extends XverseError{constructor(i){super(2003,i||"\u7F3A\u5C11 Token")}}class LoginFailedError extends XverseError{constructor(i){super(2004,i||"\u8FDB\u5165\u623F\u95F4\u5931\u8D25")}}class VerifyServiceDownError extends XverseError{constructor(i){super(2005,i||"\u9274\u6743\u670D\u52A1\u5F02\u5E38")}}class CreateSessionFailedError extends XverseError{constructor(i){super(2006,i||"\u521B\u5EFA session \u5931\u8D25")}}class RtcConnectionError extends XverseError{constructor(i){super(2008,i||"RTC\u5EFA\u8054\u5931\u8D25")}}class DoActionFailedError extends XverseError{constructor(i){super(2009,i||"\u52A8\u4F5C\u6267\u884C\u5931\u8D25")}}class StateSyncFailedError extends XverseError{constructor(i){super(2010,i||"\u72B6\u6001\u540C\u6B65\u5931\u8D25")}}class BroadcastFailedError extends XverseError{constructor(i){super(2011,i||"\u5E7F\u64AD\u63A5\u53E3\u63A5\u53E3\u5F02\u5E38")}}class DataAbnormalError extends XverseError{constructor(i){super(2012,i||"\u6570\u636E\u5F02\u5E38")}}class GetOnVehicleError extends XverseError{constructor(i){super(2015,i||"\u4E0A\u8F7D\u5177\u5931\u8D25\u9700\u8981\u9884\u7EA6")}}class RepeatLoginError extends XverseError{constructor(i){super(2017,i||"\u5F02\u5730\u767B\u5F55")}}class RoomDoseNotExistError extends XverseError{constructor(i){super(2018,i||"\u6307\u5B9A\u623F\u95F4\u4E0D\u5B58\u5728")}}class TicketExpireError extends XverseError{constructor(i){super(2019,i||"\u7968\u636E\u8FC7\u671F")}}class ServerRateLimitError extends XverseError{constructor(i){super(2020,i||"\u670D\u52A1\u7AEF\u9891\u7387\u9650\u5236")}}class DoActionBlockedError extends XverseError{constructor(i){super(2333,i||"\u52A8\u4F5C\u88AB\u5C4F\u853D")}}class UnReachableError extends XverseError{constructor(i){super(2335,i||"\u533A\u57DF\u4E0D\u53EF\u5230\u8FBE")}}class ActionMaybeDelayError extends XverseError{constructor(i){super(2334,i||"\u52A8\u4F5C\u53EF\u80FD\u5EF6\u8FDF\u6267\u884C")}}class ActionResponseTimeoutError extends XverseError{constructor(i){super(2999,i||"action\u56DE\u5305\u8D85\u65F6")}}var Codes=(a=>(a[a.Success=0]="Success",a[a.Param=1001]="Param",a[a.Internal=1002]="Internal",a[a.Timeout=1003]="Timeout",a[a.Authentication=1004]="Authentication",a[a.TokenExpired=1005]="TokenExpired",a[a.Unsupported=1006]="Unsupported",a[a.InitNetworkTimeout=1007]="InitNetworkTimeout",a[a.InitDecoderTimeout=1008]="InitDecoderTimeout",a[a.InitConfigTimeout=1009]="InitConfigTimeout",a[a.InitEngineTimeout=1010]="InitEngineTimeout",a[a.InitEngine=1011]="InitEngine",a[a.ActionBlocked=1012]="ActionBlocked",a[a.PreloadCanceled=1013]="PreloadCanceled",a[a.FrequencyLimit=1014]="FrequencyLimit",a[a.UsersUpperLimit=2e3]="UsersUpperLimit",a[a.RoomsUpperLimit=2001]="RoomsUpperLimit",a[a.ServerParam=2002]="ServerParam",a[a.LackOfToken=2003]="LackOfToken",a[a.LoginFailed=2004]="LoginFailed",a[a.VerifyServiceDown=2005]="VerifyServiceDown",a[a.CreateSessionFailed=2006]="CreateSessionFailed",a[a.RtcConnection=2008]="RtcConnection",a[a.DoActionFailed=2009]="DoActionFailed",a[a.StateSyncFailed=2010]="StateSyncFailed",a[a.BroadcastFailed=2011]="BroadcastFailed",a[a.DataAbnormal=2012]="DataAbnormal",a[a.GetOnVehicle=2015]="GetOnVehicle",a[a.RepeatLogin=2017]="RepeatLogin",a[a.RoomDoseNotExist=2018]="RoomDoseNotExist",a[a.TicketExpire=2019]="TicketExpire",a[a.ServerRateLimit=2020]="ServerRateLimit",a[a.DoActionBlocked=2333]="DoActionBlocked",a[a.UnReachable=2335]="UnReachable",a[a.ActionMaybeDelay=2334]="ActionMaybeDelay",a[a.ActionResponseTimeout=2999]="ActionResponseTimeout",a))(Codes||{});const CodeErrorMap={1001:ParamError,1002:InternalError,1003:TimeoutError,1004:AuthenticationError,1005:TokenExpiredError,1006:UnsupportedError,1007:InitNetworkTimeoutError,1008:InitDecoderTimeoutError,1009:InitConfigTimeoutError,1010:InitEngineTimeoutError,1011:InitEngineError,1012:ActionBlockedError,1013:PreloadCanceledError,1014:FrequencyLimitError,2e3:UsersUpperLimitError,2001:RoomsUpperLimitError,2002:ServerParamError,2003:LackOfTokenError,2004:LoginFailedError,2005:VerifyServiceDownError,2006:CreateSessionFailedError,2008:RtcConnectionError,2009:DoActionFailedError,2010:StateSyncFailedError,2011:BroadcastFailedError,2012:DataAbnormalError,2015:GetOnVehicleError,2017:RepeatLoginError,2018:RoomDoseNotExistError,2019:TicketExpireError,2020:ServerRateLimitError,2333:DoActionBlockedError,2335:UnReachableError,2334:ActionMaybeDelayError,2999:ActionResponseTimeoutError};class EventEmitter{constructor(){ct(this,"topics",{});ct(this,"on",(i,e,o)=>this.register(!1,i,e,o));ct(this,"once",(i,e,o)=>this.register(!0,i,e,o));ct(this,"register",(i,e,o,s)=>{this.topics[e]||(this.topics[e]={once:i,listeners:[],excuted:!1});const c={order:s||0,listener:o,once:i};return this.topics[e].listeners.push(c),this.topics[e].listeners.sort((d,_)=>d.order-_.order),{unsub:()=>{this.off(e,o)}}});ct(this,"off",(i,e)=>{const o=this.topics[i];if(!o)return;const s=o.listeners.findIndex(c=>c.listener===e);this.topics[i].listeners.splice(s,1),this.topics[i].listeners.length===0&&delete this.topics[i]});ct(this,"removeAllListener",()=>{this.topics={}});ct(this,"emit",(i,e)=>{!this.topics[i]||!this.topics[i].listeners||this.topics[i].listeners.length<1||this.topics[i].excuted||(this.topics[i].listeners.forEach(o=>{try{o.listener(e!==void 0?e:{})}catch(s){console.error(s)}}),this.topics[i]&&this.topics[i].once&&(this.topics[i].excuted=!0))})}}const debounce=(a,i)=>{let e=!1;return function(...o){e||(a.call(this,...o),e=!0,setTimeout(()=>e=!1,i))}},debounceDelay=(a,i)=>{let e=!1;return function(...o){if(e)return;e=!0;const s=this;setTimeout(()=>{a.call(s,...o),e=!1},i)}},safeDecodeURIComponent=a=>{let i="";try{i=decodeURIComponent(a)}catch{i=a}return i},safelyJsonParse=a=>{let i={};try{i=JSON.parse(a)}catch{}return i},getRandomItem=a=>a.length===0?null:a[Math.floor(Math.random()*a.length)],ENV="production";function getFormattedDate(a){const i=a.getMonth()+1,e=a.getDate(),o=a.getHours(),s=a.getMinutes(),c=a.getSeconds(),d=a.getMilliseconds(),_=(i<10?"0":"")+i,b=(e<10?"0":"")+e,k=(o<10?"0":"")+o,j=(s<10?"0":"")+s,$=(c<10?"0":"")+c;return a.getFullYear()+"-"+_+"-"+b+" "+k+":"+j+":"+$+"."+d}const SERVER_URLS={DEV:"wss://sit-eks.xverse.cn/ws",PROD:"wss://eks.xverse.cn/ws"},ENV_URL={DEV:"https://beta-lang-api.xverse.cn/",PROD:"https://lang-api.xverse.cn/"},REPORT_URL={DEV:"https://xa.xverse.cn:6680/collect",PROD:"https://xa.xverse.cn/collect"},MAX_RECONNECT_COUNT=3,DEFAULT_JOINROOM_TIMEOUT=15e3,DEFAULT_MAIN_CAMERA_FOV=50,DEFAULT_AVATAR_SCALE$1=1,REPORT_NUM_PER_REQUEST=20,DEFAULT_OPEN_TIMEOUT_MS=6e3,WS_CLOSE_NORMAL=1e3,WS_CLOSE_RECONNECT=3008,PING_INTERVAL_MS=1e3,TEXTURE_URL="https://static.xverse.cn/qqktv/texture.png",REPORT_MODULE_TYPE="xverse-js",authenticationErrorCodes=[3001,3002,3003,3005],RTT_MAX_VALUE=200,HB_MAX_VALUE=500,DURATION=5,Cr=class extends EventEmitter{constructor(){super();ct(this,"_header",{});ct(this,"_body",{});ct(this,"_queue",[]);ct(this,"_disabled",!1);ct(this,"_interval",null);ct(this,"_reportUrl");ct(this,"isDocumentLoaded",()=>document.readyState==="complete");this._header.logModuleId=REPORT_MODULE_TYPE,this._header.url=location.href,this._header.enviroment=ENV,this._header.networkType=window.navigator.connection?window.navigator.connection.type:"unknown",this._interval=window.setInterval(()=>{this._flushReport()},10*1e3)}static appendExtraMetrics(e){this.VALID_METRICS.push(...e)}disable(){this._disabled=!0,this._interval&&window.clearInterval(this._interval)}updateHeader(e){Object.assign(this._header,e)}updateBody(e){Object.assign(this._body,e)}updateReportUrl(e){this._reportUrl=e}report(e,o,s){if(e==="measurement"&&(Array.isArray(o)||(o=[o]),o.forEach(b=>{var k;(k=b.metric)!=null&&k.endsWith("Action")||Cr.VALID_METRICS.includes(b.metric)||console.warn("invalid upload metric",b.metric)})),this._disabled)return;s||(s={});const{immediate:c,sampleRate:d}=s;if(d&&d>Math.random())return;this.updateBody({logTime:getFormattedDate(new Date),logTimestamp:Date.now()});const _=b=>{const k=Kt(qt(Kt({},this._body),{type:e}),b);this._queue.push(k),e==="measurement"&&this.emit("report",b)};Array.isArray(o)?o.forEach(b=>_(b)):_(o),(c||this._queue.length>=REPORT_NUM_PER_REQUEST)&&this._flushReport()}_flushReport(){if(this._disabled||!this._queue.length||!this.isDocumentLoaded())return;const e={header:this._header,body:this._queue.splice(0,REPORT_NUM_PER_REQUEST)};this._post(e)}_post(e){const o=this._reportUrl||REPORT_URL.DEV;return new Promise((s,c)=>{const d=new XMLHttpRequest;d.open("POST",o),d.setRequestHeader("Content-Type","application/json");try{d.send(JSON.stringify(e))}catch(_){console.error(_)}d.addEventListener("readystatechange",()=>{if(d.readyState==4)return d.status==200?s(d):c("Unable to send log")})})}};let Reporter=Cr;ct(Reporter,"VALID_METRICS",["assetsPreload","joinRoom","changeSkin","getOnVehicle","getOffVehicle","getOnWatchTower","getOffWatchTower","setPerson","sendGift","photobooth","photoboothExit","reconnect","observer","telescope","telescopeExit","avatarLoadDuration","avatarLoadAt","changeComponents","playEffect","startJoinRoomAt","initRoomDuration","webglInitCost","webglInitAt","configInitAt","configInitCost","networkInitAt","networkInitCost","wasmInitAt","wasmInitCost","wsOpenedCost","datachannelOpenedAt","datachannelOpenedCost","wsOpenedAt","baiduRtt","workerRtt","loadAssets","playAnimationStart","playAnimationEnd","userAvatarStopMoving","userAvatarStartMoving","userAvatarStopRotating","userAvatarStartRotating","liveEntranceClick","sdkInit","networkQualityChange","pageShow","pageHide","http","renderError","firstMediaArravalAt","firstRenderAt","firstUpdateStreamLength","firstYUVDecodedAt","startGame","wasmDownloadCost","getUserWithAvatar"]);const reporter=new Reporter;var LoggerLevels=(a=>(a[a.Debug=1]="Debug",a[a.Info=2]="Info",a[a.Warn=3]="Warn",a[a.Error=4]="Error",a[a.Off=5]="Off",a))(LoggerLevels||{});const Er=class{constructor(i){ct(this,"module","log");ct(this,"level",1);this.module=i}static setLevel(i){this.level=i}setLevel(i){this.level=i}atleast(i){return i>=this.level&&i>=Er.level}print(i,e,...o){if(this.atleast(e)){const s=i=="debug"?"info":i,c=this.prefix(i);console[s].call(null,c,...o)}if(i!=="debug"&&i!=="info"){const s=o.map(c=>{if(c instanceof Object)try{return JSON.stringify(c)}catch{return c}else return c}).join(",");reporter.report("log",{message:s,level:i,module:this.module})}}debug(...i){return this.print("debug",1,...i)}info(...i){return this.print("info",2,...i)}infoAndReportLog(i,...e){const{reportOptions:o}=i;delete i.reportOptions,reporter.report("log",i,o),e.length||(e=[i.message]),this.debug(...e)}infoAndReportMeasurement(i,...e){var s;const{reportOptions:o}=i;if(i.startTime){const c=Date.now();i.value===void 0&&(i.endTime=c),i.value===void 0&&(i.value=c-i.startTime)}if(i.error?i.code=((s=i.error)==null?void 0:s.code)||Codes.Internal:i.code=Codes.Success,reporter.report("measurement",i,o),e.length||(e=[i]),i.level===4||i.error){this.error(...e);return}this.warn(...e)}warn(...i){return this.print("warn",3,...i)}error(...i){return this.print("error",4,...i)}prefix(i){return`[${this.module}][${i}] ${getFormattedDate(new Date)}:`}};let Logger=Er;ct(Logger,"level",4);function getDistance(a,i){const{x:e,y:o,z:s}=a,{x:c,y:d,z:_}=i;return Math.sqrt(Math.abs(e-c)**2+Math.abs(o-d)**2+Math.abs(s-_)**2)}function uuid$1(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=Math.random()*16|0;return(a==="x"?i:i&3|8).toString(16)})}function getErrorByCode(a){if(a===Codes.Success)return InternalError;const i=CodeErrorMap[a];return i||console.warn("unkown code",a),i||InternalError}const log$O=new Logger("events");class EventsManager extends EventEmitter{constructor(){super(...arguments);ct(this,"events",new Map);ct(this,"specialEvents",new Map)}remove(e,o,s,c){if(this.specialEvents.has(e)&&!c&&o===Codes.Success)return;this.events.get(e)&&(this.emit(e,{code:o,data:s}),this.events.delete(e),this.specialEvents.delete(e))}async track(e,o){const s=e.traceId,{sampleRate:c=1,noReport:d=!1,special:_}=o||{},b=Actions[e.event]+"Action",k=e.tag;this.events.set(s,!0),_&&this.specialEvents.set(s,!0);const j=Date.now();let $=null;return new Promise((_e,et)=>{if(d)return this.off(s),this.events.delete(s),_e(void 0);this.on(s,({code:rt,data:it,msg:nt})=>{if(rt===Codes.Success)_e(it),this.off(s),Math.random()<c&&log$O.infoAndReportMeasurement({metric:b,tag:k,extra:e.extra,startTime:j,traceId:s});else{if(rt===Codes.ActionMaybeDelay)return;if(rt===Codes.DoActionBlocked&&e.event===Actions.Rotation){log$O.debug(b+" response code: "+rt);return}const ot=getErrorByCode(rt),at=new ot(nt);this.off(s),et(at),this.emit("actionResponseError",{error:at,event:e,tag:k}),log$O.infoAndReportMeasurement({metric:b,tag:k,extra:e.extra,error:at,startTime:j,traceId:s})}});const tt=e.timeout||2e3;$=window.setTimeout(()=>{if($&&clearTimeout($),!this.events.get(s))return;const rt=new ActionResponseTimeoutError(`${b} timeout in ${tt}ms`);this.emit("actionResponseTimeout",{error:rt,event:e,tag:k}),et(rt),this.events.delete(s),this.off(s),log$O.infoAndReportMeasurement({metric:b,tag:k,extra:e.extra,error:rt,startTime:j,traceId:s})},tt)})}emitTraceIdToDecoder(e,o){if(e===Actions.Rotation||e===Actions.Clicking||e===Actions.GetOnVehicle||e===Actions.GetOffVehicle||e===Actions.Joystick){const s={[Actions.Rotation]:"Rotation",[Actions.GetOnVehicle]:"GetOnVehicle",[Actions.GetOffVehicle]:"GetOffVehicle",[Actions.Clicking]:"MoveTo",[Actions.Joystick]:"Joystick"};this.emit("traceId",{traceId:o,timestamp:Date.now(),event:s[e]})}}}const eventsManager=new EventsManager;var VehicleType=(a=>(a.HotAirBalloon="hotAirBalloon",a.Airship="airship",a))(VehicleType||{}),Actions=(a=>(a[a.Clicking=1]="Clicking",a[a.PlayCG=6]="PlayCG",a[a.Back=7]="Back",a[a.ChangeRoom=8]="ChangeRoom",a[a.ChangeSkin=13]="ChangeSkin",a[a.Joystick=15]="Joystick",a[a.Transfer=18]="Transfer",a[a.GetOnVehicle=22]="GetOnVehicle",a[a.GetOffVehicle=23]="GetOffVehicle",a[a.StopMoving=34]="StopMoving",a[a.UnaryActionLine=1e3]="UnaryActionLine",a[a.Init=1001]="Init",a[a.Exit=1002]="Exit",a[a.SetIFrameInfo=1003]="SetIFrameInfo",a[a.GetNeighborPoints=1004]="GetNeighborPoints",a[a.ReserveSeat=1005]="ReserveSeat",a[a.GetReserveStatus=1006]="GetReserveStatus",a[a.ChangeNickname=1007]="ChangeNickname",a[a.ChangeBitRateInfo=1008]="ChangeBitRateInfo",a[a.Echo=1009]="Echo",a[a.SetPlayerState=1010]="SetPlayerState",a[a.TurnTo=1011]="TurnTo",a[a.TurnToFace=1012]="TurnToFace",a[a.RotateTo=1013]="RotateTo",a[a.Rotation=1014]="Rotation",a[a.CameraTurnTo=1015]="CameraTurnTo",a[a.ConfirmEvent=1016]="ConfirmEvent",a[a.Broadcast=1017]="Broadcast",a[a.NotifyActionLine=2e4]="NotifyActionLine",a[a.AudienceChangeToVisitor=1020]="AudienceChangeToVisitor",a[a.VisitorChangeToAudience=1021]="VisitorChangeToAudience",a[a.RemoveVisitor=1022]="RemoveVisitor",a[a.GetUserWithAvatar=1023]="GetUserWithAvatar",a[a.GetNewUserState=1024]="GetNewUserState",a[a.SetSyncPolicy=1025]="SetSyncPolicy",a[a.StartLive=1026]="StartLive",a))(Actions||{}),RemoveVisitorType=(a=>(a[a.RVT_ChangeToObserver=1]="RVT_ChangeToObserver",a[a.RVT_MoveOutOfTheRoom=2]="RVT_MoveOutOfTheRoom",a))(RemoveVisitorType||{}),NewUserStateType=(a=>(a[a.NUST_Undefined=0]="NUST_Undefined",a[a.NUST_Myself=1]="NUST_Myself",a[a.NUST_FollowingList=2]="NUST_FollowingList",a))(NewUserStateType||{}),SyncPolicy=(a=>(a[a.SP_Default=0]="SP_Default",a[a.SP_PauseUpdateStatus=1]="SP_PauseUpdateStatus",a))(SyncPolicy||{}),CoreBroadcastType=(a=>(a.PlayAnimation="PlayAnimation",a))(CoreBroadcastType||{}),MessageHandleType=(a=>(a[a.MHT_Undefined=0]="MHT_Undefined",a[a.MHT_RoomMulticast=1]="MHT_RoomMulticast",a[a.MHT_FollowListMulticast=2]="MHT_FollowListMulticast",a[a.MHT_CustomTargetSync=3]="MHT_CustomTargetSync",a))(MessageHandleType||{});new Logger("xverse-broadcast");const Sr=class{constructor(i,e){this.room=i,Sr.handlers.push(e)}broadcast(i){const{data:e,msgType:o=MessageHandleType.MHT_FollowListMulticast,targetUserIds:s,sampleRate:c=1}=i;return this.room.actionsHandler.broadcast({data:e,msgType:o,targetUserIds:s,sampleRate:c})}};let Broadcast=Sr;ct(Broadcast,"handlers",[]);const log$N=new Logger("actions-handler"),QueueActions=[Actions.Transfer,Actions.ChangeSkin,Actions.GetOnVehicle,Actions.GetOffVehicle];class ActionsHandler{constructor(i){ct(this,"room");ct(this,"currentActiveAction");ct(this,"blockedActions",[]);ct(this,"avatarComponentsSync",i=>{const e={action_type:Actions.SetPlayerState,set_player_state_action:{player_state:{avatar_components:JSON.stringify(i)}}};this.sendData({data:e})});this.room=i}addBlockedActions(i){this.blockedActions.push(...i)}removeBlockedActions(i){if(!i){this.blockedActions=[];return}const e=this.blockedActions.indexOf(i);this.blockedActions.splice(e,1)}async sendData(i){await this.beforeSend(i);const e=uuid$1();if(this.room.networkController.sendRtcData(qt(Kt({},i.data),{trace_id:e,user_id:this.room.options.userId})),eventsManager.emitTraceIdToDecoder(i.data.action_type,e),this.blockedActions.includes(i.data.action_type))return new Promise(()=>{});if(i.track===!1)return Promise.resolve(null);const{sampleRate:o=1,timeout:s=2e3,tag:c,data:d,special:_}=i;return eventsManager.track({timeout:s,traceId:e,event:d.action_type,tag:c,extra:d},{special:_,sampleRate:o,noReport:this.room.viewMode==="serverless"||this.room.options.viewMode==="serverless"}).finally(()=>{QueueActions.includes(i.data.action_type)&&(this.currentActiveAction=void 0)})}async beforeSend(i){var c;const e=(c=this.room._userAvatar)==null?void 0:c.isMoving,o=i.data.action_type;if(QueueActions.includes(o)){if(this.currentActiveAction)return log$N.error(`${Actions[this.currentActiveAction]} still pending, reject ${Actions[o]}`),Promise.reject(new FrequencyLimitError(`${Actions[o]} action request frequency limit`));this.currentActiveAction=o}if(e&&QueueActions.includes(i.data.action_type))try{await this.stopMoving()}catch(d){this.currentActiveAction=void 0,log$N.error("before action stopMoving failed",d)}}async moveTo(i){const{point:e,extra:o="",motionType:s}=i,c={action_type:Actions.Clicking,clicking_action:{clicking_point:e,clicking_type:ClickType.IgnoreView,extra:encodeURIComponent(o),attitude:s},clicking_state:this.room._currentClickingState};return this.sendData({data:c})}transfer(i){const{renderType:e,player:o,camera:s,areaName:c,attitude:d,pathName:_,person:b,noMedia:k,timeout:j,tag:$,special:_e}=i,et={data:{action_type:Actions.Transfer,transfer_action:{render_type:e,player:o,camera:s,areaName:c,attitude:d,pathName:_,person:{type:b},noMedia:k,tiles:[0,1,2,4]}},special:_e,timeout:j||4e3,tag:$};return this.sendData(et).then(tt=>(typeof b!="undefined"&&this.room.updateCurrentNetworkOptions({person:b,rotationRenderType:e}),tt))}changeRotationRenderType(i){const{renderType:e,player:o,camera:s,areaName:c,attitude:d,pathName:_}=i;return this.transfer({renderType:e,player:o,camera:s,areaName:c,attitude:d,pathName:_,tag:"changeToRotationVideo"})}requestPanorama(i,e,o){const{camera:s,player:c,areaName:d,attitude:_,pathName:b,tag:k}=i;return this.transfer({renderType:RenderType.ClientRotationPano,player:c,camera:s,person:Person.First,areaName:d,attitude:_,pathName:b,noMedia:e,timeout:o,tag:k||"requestPanorama",special:!e})}setMotionType(i){return this.transfer({attitude:i,tag:"setMotionType"})}setNickName(i){const e={action_type:Actions.ChangeNickname,change_nickname_action:{nickname:i}};return this.sendData({data:e})}getReserveSeat({routeId:i,name:e}){const o={action_type:Actions.ReserveSeat,reserve_seat_action:{route_id:i,name:e}};return this.sendData({data:o})}getReserveStatus({routeId:i,name:e,need_detail:o}){const s={action_type:Actions.GetReserveStatus,get_reserve_status_action:{route_id:i,name:e,need_detail:o}};return this.sendData({data:s,timeout:2e3}).then(c=>c.reserveDetail)}stopMoving(){const i={action_type:Actions.StopMoving,stop_move_action:{}};return this.sendData({data:i})}getOnVehicle({routeId:i,name:e,camera:o}){const s={action_type:Actions.GetOnVehicle,get_on_vehicle_action:{route_id:i,name:e,camera:o}};return this.sendData({data:s})}getOffVehicle({renderType:i,player:e,camera:o}){const s={action_type:Actions.GetOffVehicle,get_off_vehicle_action:{render_type:i,player:e,camera:o}};return this.sendData({data:s})}confirmEvent(i){const e={action_type:Actions.ConfirmEvent,confirm_event_action:{id:i}};return this.sendData({data:e,track:!1})}echo(i){const e={action_type:Actions.Echo,echo_msg:{echoMsg:i}};return this.sendData({data:e,track:!1})}async changeSkin(i){const e=i.special===void 0?i.renderType===RenderType.ClientRotationPano:i.special,{skinId:o,mode:s,landingType:c=LandingType.Stay,landingPoint:d,landingCamera:_,renderType:b,areaName:k,attitude:j,pathName:$,person:_e,noMedia:et,timeout:tt,roomTypeId:rt=""}=i,it=this.room.skinList.filter(ot=>ot.id===o)[0];if(!it){const ot=`skin ${o} is invalid`;return log$N.error(ot),Promise.reject(new ParamError(ot))}const nt={action_type:Actions.ChangeSkin,change_skin_action:{skinID:o,mode:s===ChangeMode.Preview?ChangeMode.Preview:ChangeMode.Confirm,skin_data_version:o+it.versionId,landing_type:c,landing_point:d,landing_camera:_,render_wrapper:{render_type:b},areaName:k,attitude:j,noMedia:et,person:_e,pathName:$,roomTypeId:rt}};return this.sendData({data:nt,timeout:tt||6e3,special:e}).then(async ot=>(b===RenderType.ClientRotationPano&&ot&&await this.room.panorama.handleReceivePanorama(ot),this.handleChangeSkin(i))).catch(ot=>et?this.handleChangeSkin(i):Promise.reject(ot))}handleChangeSkin(i){const{skinId:e,mode:o,renderType:s,areaName:c,attitude:d,pathName:_}=i;return this.room.sceneManager.staticmeshComponent.getCgMesh().show(),this.room.sceneManager.cameraComponent.switchToCgCamera(),this.room.engineProxy._updateSkinAssets(e).then(()=>{this.room.sceneManager.staticmeshComponent.getCgMesh().hide(),this.room.sceneManager.cameraComponent.switchToMainCamera(),this.room.pathManager.currentArea=c,log$N.info("changeSkin _updateSkinAssets susccss"),this.room.updateCurrentNetworkOptions({pathName:_,attitude:d,areaName:c}),this.room.skinChangedHook(),this.room.emit("skinChanged",{skin:{id:e},mode:o}),s===RenderType.ClientRotationPano&&this.room.sceneManager.cameraComponent.allowMainCameraController()})}rotate({pitch:i,yaw:e}){var s;if(this.room.isPano||((s=this.room._userAvatar)==null?void 0:s._isChangingComponentsMode))return;const o={action_type:Actions.Rotation,rotation_action:{vertical_move:i,horizontal_move:-e}};this.sendData({data:o,track:!1})}turnTo(i){const{point:e,timeout:o=2e3,offset:s=8}=i||{},c={action_type:Actions.TurnTo,turn_to_action:{turn_to_point:e,offset:s}};return this.sendData({data:c,timeout:o})}rotateTo(i){const{point:e,offset:o=0,speed:s=3}=i||{},c={action_type:Actions.RotateTo,rotate_to_action:{rotate_to_point:e,offset:o,speed:s}};return this.sendData({data:c})}broadcast(i){const{data:e,msgType:o=MessageHandleType.MHT_FollowListMulticast,targetUserIds:s,sampleRate:c=1}=i;if(o===MessageHandleType.MHT_CustomTargetSync&&!Array.isArray(s))return Promise.reject(new ParamError(`param targetUserIds is required when msgType is ${MessageHandleType[o]}`));const d={action_type:Actions.Broadcast,broadcast_action:{data:JSON.stringify(e),user_id:this.room.options.userId,msgType:o}};return Array.isArray(s)&&o===MessageHandleType.MHT_CustomTargetSync&&(d.broadcast_action.target_user_ids=s),this.room.actionsHandler.sendData({data:d,tag:e.broadcastType,sampleRate:c})}getNeighborPoints(i){const{point:e,containSelf:o=!1,searchRange:s=500}=i,c={action_type:Actions.GetNeighborPoints,get_neighbor_points_action:{point:e,level:1,containSelf:o,searchRange:s}};return this.sendData({data:c,sampleRate:0}).then(d=>d.nps)}playCG(i){const e={action_type:Actions.PlayCG,play_cg_action:{cg_name:i}};return this.sendData({data:e})}audienceToVisitor(i){const{avatarId:e,avatarComponents:o,player:s,camera:c}=i,d={action_type:Actions.AudienceChangeToVisitor,audienceChangeToVisitorAction:{avatarID:e,avatarComponents:o,player:s,camera:c}};return log$N.debug("send data: audience to visitor"),this.sendData({data:d})}visitorToAudience(i){const{renderType:e,player:o,camera:s,areaName:c,attitude:d,pathName:_,person:b,noMedia:k}=i,j={action_type:Actions.VisitorChangeToAudience,visitorChangeToAudienceAction:{transferAction:{render_type:e,player:o,camera:s,areaName:c,attitude:d,pathName:_,person:{type:b},noMedia:k,tiles:[0,1,2,4]}}};return log$N.debug("send data: visitor to audience"),this.sendData({data:j})}removeVisitor(i){const{removeType:e,userIDList:o,extraInfo:s=""}=i,c={action_type:Actions.RemoveVisitor,removeVisitorAction:{removeVisitorEvent:e,userIDList:o.map(d=>String(d)),extraInfo:encodeURIComponent(s)}};return log$N.debug("send data: remove visitor"),this.sendData({data:c})}getUserWithAvatar(i,e){const o={action_type:Actions.GetUserWithAvatar,getUserWithAvatarAction:{userType:i,roomID:e}};return log$N.debug("send data: get user with avatar"),this.sendData({data:o,sampleRate:0}).then(s=>(Math.random()<.1&&log$N.infoAndReportMeasurement({metric:"getUserWithAvatar",startTime:Date.now(),extra:{visitors:s.userWithAvatarList,avatars:this.room.avatars.filter(c=>c.withModel).map(c=>({isHost:c.isHost,userID:c.userId}))}}),s.userWithAvatarList))}getNewUserState(i){const e={action_type:Actions.GetNewUserState,getNewUserStateAction:{userType:i}};return this.sendData({data:e,sampleRate:0}).then(o=>o)}setSyncPolicy({syncPolicy:i}){const e={action_type:Actions.SetSyncPolicy,setSyncPolicyAction:{syncPolicy:i}};return this.sendData({data:e})}joystick(i){const{degree:e,level:o=1}=i,s=uuid$1();let c=-e+90+360;c>=360&&(c-=360);const d={action_type:Actions.Joystick,dir_action:{move_angle:c,speed_level:o},trace_id:s,user_id:this.room.options.userId,packet_id:s};return this.sendData({data:d,track:!1})}startLive(i){const{roomId:e,rtmpAddress:o,timeout:s=2e4}=i,c={action_type:Actions.StartLive,startLiveAction:{roomId:e,rtmpAddress:o}};return this.sendData({data:c,timeout:s})}}const log$M=new Logger("db");class BaseTable{constructor(i,e){ct(this,"db");ct(this,"isCreatingTable",!1);ct(this,"hasCleared",!1);this.dbName=i,this.dbVersion=e}async clearDataBase(i){return this.hasCleared||(i&&(this.hasCleared=!0),!window.indexedDB.databases)?Promise.resolve():new Promise((e,o)=>{const s=window.indexedDB.deleteDatabase(this.dbName);s.onsuccess=()=>{e()},s.onerror=o})}tableName(){throw new Error("Derived class have to override 'tableName', and set a proper table name!")}keyPath(){throw new Error("Derived class have to override 'keyPath', and set a proper index name!")}index(){throw new Error("Derived class have to override 'index', and set a proper index name!")}async checkAndOpenDatabase(){return this.db?Promise.resolve(this.db):new Promise((i,e)=>{const s=setTimeout(()=>{log$M.warn("wait db to open for",200),this.db?i(this.db):i(this.checkAndOpenDatabase()),clearTimeout(s)},200);this.openDatabase(this.dbName,this.dbVersion||1,()=>{this.db&&!this.isCreatingTable&&i(this.db),log$M.warn(`successCallback called, this.db: ${!!this.db}, this.isCreatingStore: ${this.isCreatingTable}`),clearTimeout(s)},()=>{e(new Error("Failed to open database!")),clearTimeout(s)},()=>{this.db&&i(this.db),clearTimeout(s),log$M.warn(`successCallback called, this.db: ${!!this.db}, this.isCreatingStore: ${this.isCreatingTable}`)})})}openDatabase(i,e,o,s,c){if(this.isCreatingTable)return;this.isCreatingTable=!0,log$M.warn({database:i,version:e});const d=window.indexedDB.open(i,e),_=this.tableName();d.onsuccess=b=>{this.db=d.result,log$M.warn(`IndexedDb ${i} is opened.`),this.db.objectStoreNames.contains(_)&&(this.isCreatingTable=!1),o&&o(b)},d.onerror=b=>{var k;log$M.error("Failed to open database",(k=b==null?void 0:b.srcElement)==null?void 0:k.error),this.isCreatingTable=!1,s&&s(b),this.clearDataBase(!0)},d.onupgradeneeded=b=>{const k=b.target.result,j=this.index();log$M.warn(`Creating table ${_}.`);let $=k.objectStoreNames.contains(_);if($)$=k.transaction([_],"readwrite").objectStore(_);else{const _e=this.keyPath();$=k.createObjectStore(_,{keyPath:_e})}j.map(_e=>{$.createIndex(_e,_e,{unique:!1})}),this.isCreatingTable=!1,log$M.warn(`Table ${_} opened`),c&&c(b)}}async add(i){const e=this.tableName(),c=(await this.checkAndOpenDatabase()).transaction([e],"readwrite").objectStore(e).add(i);return new Promise(function(d,_){c.onsuccess=b=>{d(b)},c.onerror=b=>{var k;log$M.error((k=b.srcElement)==null?void 0:k.error),_(b)}})}async put(i){const e=this.tableName(),c=(await this.checkAndOpenDatabase()).transaction([e],"readwrite").objectStore(e).put(i);return new Promise(function(d,_){c.onsuccess=b=>{d(b)},c.onerror=b=>{var k;log$M.error("db put error",(k=b.srcElement)==null?void 0:k.error),_(b)}})}delete(i,e,o){const s=this.tableName();this.checkAndOpenDatabase().then(c=>{const _=c.transaction([s],"readwrite").objectStore(s).delete(i);_.onsuccess=e,_.onerror=o})}update(){this.checkAndOpenDatabase().then(i=>{})}async getAllKeys(){const i=this.tableName(),e=await this.checkAndOpenDatabase();return new Promise((o,s)=>{const d=e.transaction([i],"readonly").objectStore(i).getAllKeys();d.onsuccess=_=>{o(_.target.result)},d.onerror=_=>{log$M.error("db getAllKeys error",_),s(_)}})}async query(i,e){const o=this.tableName(),s=await this.checkAndOpenDatabase();return new Promise((c,d)=>{const k=s.transaction([o],"readonly").objectStore(o).index(i).get(e);k.onsuccess=function(j){var _e;const $=(_e=j==null?void 0:j.target)==null?void 0:_e.result;c&&c($)},k.onerror=j=>{log$M.error("db query error",j),d(j)}})}async sleep(i){return new Promise(e=>{setTimeout(()=>{e("")},i)})}}class ModelTable extends BaseTable{constructor(){super("XverseDatabase",1)}tableName(){return"models"}index(){return["url"]}keyPath(){return"url"}}const modelTable=new ModelTable;var axios$2={exports:{}},bind$2=function(i,e){return function(){for(var s=new Array(arguments.length),c=0;c<s.length;c++)s[c]=arguments[c];return i.apply(e,s)}},bind$1=bind$2,toString=Object.prototype.toString;function isArray$1(a){return toString.call(a)==="[object Array]"}function isUndefined(a){return typeof a=="undefined"}function isBuffer(a){return a!==null&&!isUndefined(a)&&a.constructor!==null&&!isUndefined(a.constructor)&&typeof a.constructor.isBuffer=="function"&&a.constructor.isBuffer(a)}function isArrayBuffer(a){return toString.call(a)==="[object ArrayBuffer]"}function isFormData(a){return typeof FormData!="undefined"&&a instanceof FormData}function isArrayBufferView(a){var i;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?i=ArrayBuffer.isView(a):i=a&&a.buffer&&a.buffer instanceof ArrayBuffer,i}function isString(a){return typeof a=="string"}function isNumber$1(a){return typeof a=="number"}function isObject$1(a){return a!==null&&typeof a=="object"}function isPlainObject(a){if(toString.call(a)!=="[object Object]")return!1;var i=Object.getPrototypeOf(a);return i===null||i===Object.prototype}function isDate(a){return toString.call(a)==="[object Date]"}function isFile(a){return toString.call(a)==="[object File]"}function isBlob(a){return toString.call(a)==="[object Blob]"}function isFunction$1(a){return toString.call(a)==="[object Function]"}function isStream(a){return isObject$1(a)&&isFunction$1(a.pipe)}function isURLSearchParams(a){return typeof URLSearchParams!="undefined"&&a instanceof URLSearchParams}function trim(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")}function isStandardBrowserEnv(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function forEach(a,i){if(!(a===null||typeof a=="undefined"))if(typeof a!="object"&&(a=[a]),isArray$1(a))for(var e=0,o=a.length;e<o;e++)i.call(null,a[e],e,a);else for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&i.call(null,a[s],s,a)}function merge(){var a={};function i(s,c){isPlainObject(a[c])&&isPlainObject(s)?a[c]=merge(a[c],s):isPlainObject(s)?a[c]=merge({},s):isArray$1(s)?a[c]=s.slice():a[c]=s}for(var e=0,o=arguments.length;e<o;e++)forEach(arguments[e],i);return a}function extend$2(a,i,e){return forEach(i,function(s,c){e&&typeof s=="function"?a[c]=bind$1(s,e):a[c]=s}),a}function stripBOM(a){return a.charCodeAt(0)===65279&&(a=a.slice(1)),a}var utils$d={isArray:isArray$1,isArrayBuffer,isBuffer,isFormData,isArrayBufferView,isString,isNumber:isNumber$1,isObject:isObject$1,isPlainObject,isUndefined,isDate,isFile,isBlob,isFunction:isFunction$1,isStream,isURLSearchParams,isStandardBrowserEnv,forEach,merge,extend:extend$2,trim,stripBOM},utils$c=utils$d;function encode(a){return encodeURIComponent(a).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var buildURL$2=function(i,e,o){if(!e)return i;var s;if(o)s=o(e);else if(utils$c.isURLSearchParams(e))s=e.toString();else{var c=[];utils$c.forEach(e,function(b,k){b===null||typeof b=="undefined"||(utils$c.isArray(b)?k=k+"[]":b=[b],utils$c.forEach(b,function($){utils$c.isDate($)?$=$.toISOString():utils$c.isObject($)&&($=JSON.stringify($)),c.push(encode(k)+"="+encode($))}))}),s=c.join("&")}if(s){var d=i.indexOf("#");d!==-1&&(i=i.slice(0,d)),i+=(i.indexOf("?")===-1?"?":"&")+s}return i},utils$b=utils$d;function InterceptorManager$1(){this.handlers=[]}InterceptorManager$1.prototype.use=function(i,e,o){return this.handlers.push({fulfilled:i,rejected:e,synchronous:o?o.synchronous:!1,runWhen:o?o.runWhen:null}),this.handlers.length-1};InterceptorManager$1.prototype.eject=function(i){this.handlers[i]&&(this.handlers[i]=null)};InterceptorManager$1.prototype.forEach=function(i){utils$b.forEach(this.handlers,function(o){o!==null&&i(o)})};var InterceptorManager_1=InterceptorManager$1,utils$a=utils$d,normalizeHeaderName$1=function(i,e){utils$a.forEach(i,function(s,c){c!==e&&c.toUpperCase()===e.toUpperCase()&&(i[e]=s,delete i[c])})},enhanceError$2=function(i,e,o,s,c){return i.config=e,o&&(i.code=o),i.request=s,i.response=c,i.isAxiosError=!0,i.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}},i},enhanceError$1=enhanceError$2,createError$2=function(i,e,o,s,c){var d=new Error(i);return enhanceError$1(d,e,o,s,c)},createError$1=createError$2,settle$1=function(i,e,o){var s=o.config.validateStatus;!o.status||!s||s(o.status)?i(o):e(createError$1("Request failed with status code "+o.status,o.config,null,o.request,o))},utils$9=utils$d,cookies$1=utils$9.isStandardBrowserEnv()?function(){return{write:function(e,o,s,c,d,_){var b=[];b.push(e+"="+encodeURIComponent(o)),utils$9.isNumber(s)&&b.push("expires="+new Date(s).toGMTString()),utils$9.isString(c)&&b.push("path="+c),utils$9.isString(d)&&b.push("domain="+d),_===!0&&b.push("secure"),document.cookie=b.join("; ")},read:function(e){var o=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return o?decodeURIComponent(o[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),isAbsoluteURL$1=function(i){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(i)},combineURLs$1=function(i,e){return e?i.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):i},isAbsoluteURL=isAbsoluteURL$1,combineURLs=combineURLs$1,buildFullPath$1=function(i,e){return i&&!isAbsoluteURL(e)?combineURLs(i,e):e},utils$8=utils$d,ignoreDuplicateOf=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],parseHeaders$1=function(i){var e={},o,s,c;return i&&utils$8.forEach(i.split(`
  11230. `),function(_){if(c=_.indexOf(":"),o=utils$8.trim(_.substr(0,c)).toLowerCase(),s=utils$8.trim(_.substr(c+1)),o){if(e[o]&&ignoreDuplicateOf.indexOf(o)>=0)return;o==="set-cookie"?e[o]=(e[o]?e[o]:[]).concat([s]):e[o]=e[o]?e[o]+", "+s:s}}),e},utils$7=utils$d,isURLSameOrigin$1=utils$7.isStandardBrowserEnv()?function(){var i=/(msie|trident)/i.test(navigator.userAgent),e=document.createElement("a"),o;function s(c){var d=c;return i&&(e.setAttribute("href",d),d=e.href),e.setAttribute("href",d),{href:e.href,protocol:e.protocol?e.protocol.replace(/:$/,""):"",host:e.host,search:e.search?e.search.replace(/^\?/,""):"",hash:e.hash?e.hash.replace(/^#/,""):"",hostname:e.hostname,port:e.port,pathname:e.pathname.charAt(0)==="/"?e.pathname:"/"+e.pathname}}return o=s(window.location.href),function(d){var _=utils$7.isString(d)?s(d):d;return _.protocol===o.protocol&&_.host===o.host}}():function(){return function(){return!0}}();function Cancel$3(a){this.message=a}Cancel$3.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")};Cancel$3.prototype.__CANCEL__=!0;var Cancel_1=Cancel$3,utils$6=utils$d,settle=settle$1,cookies=cookies$1,buildURL$1=buildURL$2,buildFullPath=buildFullPath$1,parseHeaders=parseHeaders$1,isURLSameOrigin=isURLSameOrigin$1,createError=createError$2,defaults$4=defaults_1,Cancel$2=Cancel_1,xhr=function(i){return new Promise(function(o,s){var c=i.data,d=i.headers,_=i.responseType,b;function k(){i.cancelToken&&i.cancelToken.unsubscribe(b),i.signal&&i.signal.removeEventListener("abort",b)}utils$6.isFormData(c)&&delete d["Content-Type"];var j=new XMLHttpRequest;if(i.auth){var $=i.auth.username||"",_e=i.auth.password?unescape(encodeURIComponent(i.auth.password)):"";d.Authorization="Basic "+btoa($+":"+_e)}var et=buildFullPath(i.baseURL,i.url);j.open(i.method.toUpperCase(),buildURL$1(et,i.params,i.paramsSerializer),!0),j.timeout=i.timeout;function tt(){if(!!j){var it="getAllResponseHeaders"in j?parseHeaders(j.getAllResponseHeaders()):null,nt=!_||_==="text"||_==="json"?j.responseText:j.response,ot={data:nt,status:j.status,statusText:j.statusText,headers:it,config:i,request:j};settle(function(st){o(st),k()},function(st){s(st),k()},ot),j=null}}if("onloadend"in j?j.onloadend=tt:j.onreadystatechange=function(){!j||j.readyState!==4||j.status===0&&!(j.responseURL&&j.responseURL.indexOf("file:")===0)||setTimeout(tt)},j.onabort=function(){!j||(s(createError("Request aborted",i,"ECONNABORTED",j)),j=null)},j.onerror=function(){s(createError("Network Error",i,null,j)),j=null},j.ontimeout=function(){var nt=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",ot=i.transitional||defaults$4.transitional;i.timeoutErrorMessage&&(nt=i.timeoutErrorMessage),s(createError(nt,i,ot.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",j)),j=null},utils$6.isStandardBrowserEnv()){var rt=(i.withCredentials||isURLSameOrigin(et))&&i.xsrfCookieName?cookies.read(i.xsrfCookieName):void 0;rt&&(d[i.xsrfHeaderName]=rt)}"setRequestHeader"in j&&utils$6.forEach(d,function(nt,ot){typeof c=="undefined"&&ot.toLowerCase()==="content-type"?delete d[ot]:j.setRequestHeader(ot,nt)}),utils$6.isUndefined(i.withCredentials)||(j.withCredentials=!!i.withCredentials),_&&_!=="json"&&(j.responseType=i.responseType),typeof i.onDownloadProgress=="function"&&j.addEventListener("progress",i.onDownloadProgress),typeof i.onUploadProgress=="function"&&j.upload&&j.upload.addEventListener("progress",i.onUploadProgress),(i.cancelToken||i.signal)&&(b=function(it){!j||(s(!it||it&&it.type?new Cancel$2("canceled"):it),j.abort(),j=null)},i.cancelToken&&i.cancelToken.subscribe(b),i.signal&&(i.signal.aborted?b():i.signal.addEventListener("abort",b))),c||(c=null),j.send(c)})},utils$5=utils$d,normalizeHeaderName=normalizeHeaderName$1,enhanceError=enhanceError$2,DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(a,i){!utils$5.isUndefined(a)&&utils$5.isUndefined(a["Content-Type"])&&(a["Content-Type"]=i)}function getDefaultAdapter(){var a;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(a=xhr),a}function stringifySafely(a,i,e){if(utils$5.isString(a))try{return(i||JSON.parse)(a),utils$5.trim(a)}catch(o){if(o.name!=="SyntaxError")throw o}return(e||JSON.stringify)(a)}var defaults$3={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:getDefaultAdapter(),transformRequest:[function(i,e){return normalizeHeaderName(e,"Accept"),normalizeHeaderName(e,"Content-Type"),utils$5.isFormData(i)||utils$5.isArrayBuffer(i)||utils$5.isBuffer(i)||utils$5.isStream(i)||utils$5.isFile(i)||utils$5.isBlob(i)?i:utils$5.isArrayBufferView(i)?i.buffer:utils$5.isURLSearchParams(i)?(setContentTypeIfUnset(e,"application/x-www-form-urlencoded;charset=utf-8"),i.toString()):utils$5.isObject(i)||e&&e["Content-Type"]==="application/json"?(setContentTypeIfUnset(e,"application/json"),stringifySafely(i)):i}],transformResponse:[function(i){var e=this.transitional||defaults$3.transitional,o=e&&e.silentJSONParsing,s=e&&e.forcedJSONParsing,c=!o&&this.responseType==="json";if(c||s&&utils$5.isString(i)&&i.length)try{return JSON.parse(i)}catch(d){if(c)throw d.name==="SyntaxError"?enhanceError(d,this,"E_JSON_PARSE"):d}return i}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(i){return i>=200&&i<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils$5.forEach(["delete","get","head"],function(i){defaults$3.headers[i]={}});utils$5.forEach(["post","put","patch"],function(i){defaults$3.headers[i]=utils$5.merge(DEFAULT_CONTENT_TYPE)});var defaults_1=defaults$3,utils$4=utils$d,defaults$2=defaults_1,transformData$1=function(i,e,o){var s=this||defaults$2;return utils$4.forEach(o,function(d){i=d.call(s,i,e)}),i},isCancel$1=function(i){return!!(i&&i.__CANCEL__)},utils$3=utils$d,transformData=transformData$1,isCancel=isCancel$1,defaults$1=defaults_1,Cancel$1=Cancel_1;function throwIfCancellationRequested(a){if(a.cancelToken&&a.cancelToken.throwIfRequested(),a.signal&&a.signal.aborted)throw new Cancel$1("canceled")}var dispatchRequest$1=function(i){throwIfCancellationRequested(i),i.headers=i.headers||{},i.data=transformData.call(i,i.data,i.headers,i.transformRequest),i.headers=utils$3.merge(i.headers.common||{},i.headers[i.method]||{},i.headers),utils$3.forEach(["delete","get","head","post","put","patch","common"],function(s){delete i.headers[s]});var e=i.adapter||defaults$1.adapter;return e(i).then(function(s){return throwIfCancellationRequested(i),s.data=transformData.call(i,s.data,s.headers,i.transformResponse),s},function(s){return isCancel(s)||(throwIfCancellationRequested(i),s&&s.response&&(s.response.data=transformData.call(i,s.response.data,s.response.headers,i.transformResponse))),Promise.reject(s)})},utils$2=utils$d,mergeConfig$2=function(i,e){e=e||{};var o={};function s(j,$){return utils$2.isPlainObject(j)&&utils$2.isPlainObject($)?utils$2.merge(j,$):utils$2.isPlainObject($)?utils$2.merge({},$):utils$2.isArray($)?$.slice():$}function c(j){if(utils$2.isUndefined(e[j])){if(!utils$2.isUndefined(i[j]))return s(void 0,i[j])}else return s(i[j],e[j])}function d(j){if(!utils$2.isUndefined(e[j]))return s(void 0,e[j])}function _(j){if(utils$2.isUndefined(e[j])){if(!utils$2.isUndefined(i[j]))return s(void 0,i[j])}else return s(void 0,e[j])}function b(j){if(j in e)return s(i[j],e[j]);if(j in i)return s(void 0,i[j])}var k={url:d,method:d,data:d,baseURL:_,transformRequest:_,transformResponse:_,paramsSerializer:_,timeout:_,timeoutMessage:_,withCredentials:_,adapter:_,responseType:_,xsrfCookieName:_,xsrfHeaderName:_,onUploadProgress:_,onDownloadProgress:_,decompress:_,maxContentLength:_,maxBodyLength:_,transport:_,httpAgent:_,httpsAgent:_,cancelToken:_,socketPath:_,responseEncoding:_,validateStatus:b};return utils$2.forEach(Object.keys(i).concat(Object.keys(e)),function($){var _e=k[$]||c,et=_e($);utils$2.isUndefined(et)&&_e!==b||(o[$]=et)}),o},data={version:"0.24.0"},VERSION$1=data.version,validators$1={};["object","boolean","number","function","string","symbol"].forEach(function(a,i){validators$1[a]=function(o){return typeof o===a||"a"+(i<1?"n ":" ")+a}});var deprecatedWarnings={};validators$1.transitional=function(i,e,o){function s(c,d){return"[Axios v"+VERSION$1+"] Transitional option '"+c+"'"+d+(o?". "+o:"")}return function(c,d,_){if(i===!1)throw new Error(s(d," has been removed"+(e?" in "+e:"")));return e&&!deprecatedWarnings[d]&&(deprecatedWarnings[d]=!0,console.warn(s(d," has been deprecated since v"+e+" and will be removed in the near future"))),i?i(c,d,_):!0}};function assertOptions(a,i,e){if(typeof a!="object")throw new TypeError("options must be an object");for(var o=Object.keys(a),s=o.length;s-- >0;){var c=o[s],d=i[c];if(d){var _=a[c],b=_===void 0||d(_,c,a);if(b!==!0)throw new TypeError("option "+c+" must be "+b);continue}if(e!==!0)throw Error("Unknown option "+c)}}var validator$1={assertOptions,validators:validators$1},utils$1=utils$d,buildURL=buildURL$2,InterceptorManager=InterceptorManager_1,dispatchRequest=dispatchRequest$1,mergeConfig$1=mergeConfig$2,validator=validator$1,validators=validator.validators;function Axios$1(a){this.defaults=a,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios$1.prototype.request=function(i){typeof i=="string"?(i=arguments[1]||{},i.url=arguments[0]):i=i||{},i=mergeConfig$1(this.defaults,i),i.method?i.method=i.method.toLowerCase():this.defaults.method?i.method=this.defaults.method.toLowerCase():i.method="get";var e=i.transitional;e!==void 0&&validator.assertOptions(e,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1);var o=[],s=!0;this.interceptors.request.forEach(function(_e){typeof _e.runWhen=="function"&&_e.runWhen(i)===!1||(s=s&&_e.synchronous,o.unshift(_e.fulfilled,_e.rejected))});var c=[];this.interceptors.response.forEach(function(_e){c.push(_e.fulfilled,_e.rejected)});var d;if(!s){var _=[dispatchRequest,void 0];for(Array.prototype.unshift.apply(_,o),_=_.concat(c),d=Promise.resolve(i);_.length;)d=d.then(_.shift(),_.shift());return d}for(var b=i;o.length;){var k=o.shift(),j=o.shift();try{b=k(b)}catch($){j($);break}}try{d=dispatchRequest(b)}catch($){return Promise.reject($)}for(;c.length;)d=d.then(c.shift(),c.shift());return d};Axios$1.prototype.getUri=function(i){return i=mergeConfig$1(this.defaults,i),buildURL(i.url,i.params,i.paramsSerializer).replace(/^\?/,"")};utils$1.forEach(["delete","get","head","options"],function(i){Axios$1.prototype[i]=function(e,o){return this.request(mergeConfig$1(o||{},{method:i,url:e,data:(o||{}).data}))}});utils$1.forEach(["post","put","patch"],function(i){Axios$1.prototype[i]=function(e,o,s){return this.request(mergeConfig$1(s||{},{method:i,url:e,data:o}))}});var Axios_1=Axios$1,Cancel=Cancel_1;function CancelToken(a){if(typeof a!="function")throw new TypeError("executor must be a function.");var i;this.promise=new Promise(function(s){i=s});var e=this;this.promise.then(function(o){if(!!e._listeners){var s,c=e._listeners.length;for(s=0;s<c;s++)e._listeners[s](o);e._listeners=null}}),this.promise.then=function(o){var s,c=new Promise(function(d){e.subscribe(d),s=d}).then(o);return c.cancel=function(){e.unsubscribe(s)},c},a(function(s){e.reason||(e.reason=new Cancel(s),i(e.reason))})}CancelToken.prototype.throwIfRequested=function(){if(this.reason)throw this.reason};CancelToken.prototype.subscribe=function(i){if(this.reason){i(this.reason);return}this._listeners?this._listeners.push(i):this._listeners=[i]};CancelToken.prototype.unsubscribe=function(i){if(!!this._listeners){var e=this._listeners.indexOf(i);e!==-1&&this._listeners.splice(e,1)}};CancelToken.source=function(){var i,e=new CancelToken(function(s){i=s});return{token:e,cancel:i}};var CancelToken_1=CancelToken,spread=function(i){return function(o){return i.apply(null,o)}},isAxiosError=function(i){return typeof i=="object"&&i.isAxiosError===!0},utils=utils$d,bind=bind$2,Axios=Axios_1,mergeConfig=mergeConfig$2,defaults=defaults_1;function createInstance(a){var i=new Axios(a),e=bind(Axios.prototype.request,i);return utils.extend(e,Axios.prototype,i),utils.extend(e,i),e.create=function(s){return createInstance(mergeConfig(a,s))},e}var axios$1=createInstance(defaults);axios$1.Axios=Axios;axios$1.Cancel=Cancel_1;axios$1.CancelToken=CancelToken_1;axios$1.isCancel=isCancel$1;axios$1.VERSION=data.version;axios$1.all=function(i){return Promise.all(i)};axios$1.spread=spread;axios$1.isAxiosError=isAxiosError;axios$2.exports=axios$1;axios$2.exports.default=axios$1;var axios=axios$2.exports;const isFunction=a=>typeof a=="function";class AxiosCanceler{constructor(){ct(this,"pendingMap",new Map)}addPending(i){return new axios.CancelToken(e=>{this.pendingMap.has(i)||this.pendingMap.set(i,e)})}removeAllPending(){this.pendingMap.forEach(i=>{i&&isFunction(i)&&i()}),this.pendingMap.clear()}removePending(i){if(this.pendingMap.has(i)){const e=this.pendingMap.get(i);e&&e(i),this.pendingMap.delete(i)}}removeCancelToken(i){this.pendingMap.has(i)&&this.pendingMap.delete(i)}reset(){this.pendingMap=new Map}}const log$L=new Logger("http");class Http$1{constructor(){ct(this,"instatnce");ct(this,"canceler");ct(this,"requestParams",i=>Kt({},i.params));ct(this,"requestConstant",()=>({x_nounce:this.randomString(),x_timestamp:new Date().getTime(),x_os:"web"}));this.instatnce=axios.create(),this.canceler=new AxiosCanceler}get(i){return this.request(qt(Kt({},i),{method:"GET"}))}post(i){return this.request(qt(Kt({},i),{method:"POST"}))}request(i){const{url:e,timeout:o=1e4,method:s,key:c,beforeRequest:d,responseType:_,data:b}=i;let{retry:k=0}=i;const j=this.transformUrlHook(e),$=this.canceler.addPending(e);d&&isFunction(d)&&d(i);const _e=this.requestParams(i);let et={url:j,method:s,timeout:o,cancelToken:$,responseType:_,params:_e};s==="POST"&&(et=Kt({data:b},et));const tt=Date.now(),rt=()=>this.instatnce.request(et).then(it=>(c&&log$L.infoAndReportMeasurement({metric:"http",startTime:tt,extra:e,group:"http",tag:c}),this.canceler.removeCancelToken(e),it)).catch(it=>{const nt=axios.isCancel(it);return k>0&&!nt?(k--,log$L.warn(`request ${e} retry, left retry count`,k),rt()):(log$L.infoAndReportMeasurement({metric:"http",startTime:tt,error:it,extra:{url:e,isCanceled:nt},tag:c,group:"http"}),this.canceler.removeCancelToken(e),Promise.reject(it))});return rt()}transformUrlHook(i){return i}randomString(){let i="";const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o=e.length;for(let s=0;s<8;s++)i+=e.charAt(Math.floor(Math.random()*o));return i}}const http$1=new Http$1,log$K=new Logger("AssetsStorage");class AssetsStorage{static async readOrRequest(i,e){let o=null;try{o=await modelTable.query("url",i)}catch(c){return log$K.debug(c),log$K.warn("cache query error",i),Promise.resolve(i)}let s=o&&o.model;return s||(s=await this.requestAndPut({url:i,responseType:"blob",retry:2})),typeof s=="string"&&(s=this.dataURItoBlob(s)),e&&e.returnBlob?s:URL.createObjectURL(s)}static async requestAndPut(i){try{const e=await http$1.get(i);return await modelTable.put({url:i.url,model:e.data}),e.data}catch{return Promise.reject(new InternalError("request and put error"))}}}ct(AssetsStorage,"dataURItoBlob",i=>{let e;i.split(",")[0].indexOf("base64")>=0?e=atob(i.split(",")[1]):e=unescape(i.split(",")[1]);const o=i.split(",")[0].split(":")[1].split(";")[0],s=new Uint8Array(e.length);for(let d=0;d<e.length;d++)s[d]=e.charCodeAt(d);return new Blob([s],{type:o})});const Ar=class{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const i={};return{getItem:e=>{const o=i[e];return o===void 0?null:o},setItem:(e,o)=>{i[e]=o}}}}static ReadString(i,e){const o=this._Storage.getItem(i);return o!==null?o:e}static WriteString(i,e){this._Storage.setItem(i,e)}static ReadBoolean(i,e){const o=this._Storage.getItem(i);return o!==null?o==="true":e}static WriteBoolean(i,e){this._Storage.setItem(i,e?"true":"false")}static ReadNumber(i,e){const o=this._Storage.getItem(i);return o!==null?parseFloat(o):e}static WriteNumber(i,e){this._Storage.setItem(i,e.toString())}};let DataStorage=Ar;ct(DataStorage,"_Storage",Ar._GetStorage());const urlMap=new Map,urlTransformer=async(a,i=!1)=>typeof a!="string"?(console.warn("url transformer error",a),a):a.startsWith("blob:")?a:i?AssetsStorage.readOrRequest(a,{returnBlob:!0}):urlMap.has(a)?urlMap.get(a):AssetsStorage.readOrRequest(a).then(e=>(urlMap.set(a,e),e));var workerSourceCode=`onmessage = function (event) {
  11231. const data = event.data
  11232. if (!data) return
  11233. if (data.type === 'start') {
  11234. const startTime = Date.now()
  11235. const request = new XMLHttpRequest()
  11236. request.open('GET', data.url)
  11237. try {
  11238. request.send()
  11239. } catch (error) {
  11240. console.error(error)
  11241. }
  11242. request.addEventListener('readystatechange', () => {
  11243. if (request.readyState == 4) {
  11244. if (request.status == 200) {
  11245. postMessage(Date.now() - startTime)
  11246. }
  11247. }
  11248. })
  11249. }
  11250. }
  11251. `;const log$J=new Logger("detect");let worker=null;function checkNetworkQuality(a){if(!a)return;const i=Date.now();if(pingOthers("https://www.baidu.com",function(e,o){log$J.infoAndReportMeasurement({metric:"baiduRtt",group:"http",value:o,startTime:i})}),!worker){const e=new Blob([workerSourceCode],{type:"application/javascript"});worker=new Worker(URL.createObjectURL(e)),worker.onmessage=function(o){log$J.infoAndReportMeasurement({metric:"workerRtt",group:"http",startTime:i,value:o.data})}}}function pingOthers(a,i){let e=!1;const o=new Image;o.onload=c,o.onerror=d;const s=Date.now();function c(b){e=!0,_()}function d(b){}function _(){const b=Date.now()-s;if(typeof i=="function")return e?i(null,b):(console.error("error loading resource"),i("error",b))}o.src=a+"/favicon.ico?"+ +new Date}const log$I=new Logger("heartbeat");class Heartbeat{constructor(i){ct(this,"_interval",null);ct(this,"ping",()=>{const i=Date.now().toString();this.handler.ping(i)});this.handler=i}start(){this.stop(),log$I.debug(`Setting ping interval to ${PING_INTERVAL_MS}ms`),this._interval=window.setInterval(this.ping,PING_INTERVAL_MS)}stop(){log$I.debug("stop heartbeat"),this._interval&&window.clearInterval(this._interval)}pong(i,e){!i||typeof i=="string"&&this.handler.pong(Date.now()-Number(i),e)}}class NetworkMonitor{constructor(i){ct(this,"_listener");this._listener=i}get isOnline(){const i=window.navigator;return typeof i.onLine=="boolean"?i.onLine:!0}start(){window.addEventListener("online",this._listener),window.addEventListener("offline",this._listener)}stop(){window.removeEventListener("online",this._listener),window.removeEventListener("offline",this._listener)}}function VisibilityChangeHandler(){this.subscribers=[],this.bindFunc=void 0,this.id=1,this.addListener()}VisibilityChangeHandler.prototype={subscribe(a){if(!a)return;const i=++this.id,e={id:i,handler:a};return this.subscribers.push(e),()=>{this.subscribers=this.subscribers.filter(s=>s.id==i)}},destroy(){!this.bindFunc||(document.hidden!==void 0?document.removeEventListener("visibilitychange",this.bindFunc,!1):document.webkitHidden&&document.removeEventListener("webkitvisibilitychange",this.bindFunc,!1))},broadcast(a){this.subscribers.forEach(i=>i.handler(a))},addListener(){document.hidden!==void 0?(this.bindFunc=()=>this.broadcast(document.hidden),document.addEventListener("visibilitychange",this.bindFunc,!1)):document.webkitHidden&&(this.bindFunc=()=>this.broadcast(document.webkitHidden),document.addEventListener("webkitvisibilitychange",this.bindFunc,!1))}};const WASM_Version="h264",DECODER_VERSION="v0.9.3",WASM_URLS={h264:"https://static.xverse.cn/wasm/v17/lib_ff264dec.js",xv265:"https://static.xverse.cn/wasm/codec-release/h265-dec-sw-wasm/v-0-9-1/libxv265dec.js",h265:""},STUCK_STAGE_GOOD=45,STUCK_STAGE_WELL=85,STUCK_STAGE_FAIR=125,STUCK_STAGE_BAD=165,DECODER_PASSIVE_JITTER=0;function add(a,i){return i==-1&&(i=0),a+i}function count_valid(a,i){let e=0;return i!=-1&&(e=1),a+e}function count_less(a,i){function e(o,s){let c=0;return s!=-1&&s<i&&(c=1),o+c}return a.reduce(e,0)}function count_sd(a,i){function e(o,s){let c=0;return s==-1?c=0:c=(s-i)*(s-i),o+c}return Math.sqrt(a.reduce(e,0)/a.reduce(count_valid,0))||0}function max(a,i){return Math.max(a,i)}class CircularArray{constructor(i,e,o){this.sum=0,this.incomingSum=0,this.count=0,this.incomingCount=0,this.max=0,this.incomingMax=0,this.goodLess=0,this.wellLess=0,this.fairLess=0,this.badLess=0,this.countLess=!1,this.lessThreshes=[],this.incomingData=[],this.circularData=Array(i).fill(-1),this.circularPtr=0,this.circularLength=i,e&&(this.countLess=!0,this.lessThreshes=o)}add(i){i<0||(this.circularData[this.circularPtr]!=-1?(this.sum-=this.circularData[this.circularPtr],Math.abs(this.circularData[this.circularPtr]-this.max)<.01&&(this.circularData[this.circularPtr]=-1,this.max=this.computeMax(this.circularData))):this.count+=1,this.sum+=i,this.incomingSum+=i,this.incomingCount+=1,this.max<i&&(this.max=i),this.incomingMax<i&&(this.incomingMax=i),this.circularData[this.circularPtr]=i,this.circularPtr=(this.circularPtr+1)%this.circularLength,this.incomingData.push(i),this.incomingData.length>this.circularLength&&(this.clearIncoming(),this.incomingCount=0,this.incomingSum=0))}computeAvg(i){return i.reduce(add,0)/i.reduce(count_valid,0)||0}computeMax(i){return i.reduce(max,0)||0}computeThreshPercent(i){if(this.countLess){const e=count_less(i,this.lessThreshes[0])||0,o=count_less(i,this.lessThreshes[1])||0,s=count_less(i,this.lessThreshes[2])||0,c=count_less(i,this.lessThreshes[3])||0,d=i.reduce(count_valid,0);return[e,o,s,c,d]}else return[0,0,0,0,0]}getAvg(){return this.sum/this.count||0||0}getMax(i=!0){return this.max||0}getStandardDeviation(){return count_sd(this.circularData,this.getAvg())}getThreshPercent(){return this.computeThreshPercent(this.circularData)}getIncomingMax(){return this.computeMax(this.incomingData)||0}getIncomingAvg(){return this.computeAvg(this.incomingData)||0}getIncomingStandardDeviation(){return count_sd(this.incomingData,this.getIncomingAvg())}getIncomingThreshPercent(){return this.computeThreshPercent(this.incomingData)}clearFastComputeItem(){this.sum=0,this.incomingSum=0,this.count=0,this.incomingCount=0,this.max=0,this.incomingMax=0,this.goodLess=0,this.wellLess=0,this.fairLess=0,this.badLess=0}clearIncoming(){for(;this.incomingData.length>0;)this.incomingData.pop()}clear(){this.circularData.fill(-1),this.circularPtr=0,this.clearFastComputeItem(),this.clearIncoming()}}class SecondArray{constructor(){this.circularData=[]}add(i){this.circularData.push(i)}getAvg(){let i=0;for(let e=0;e<this.circularData.length;e++)i+=this.circularData[e];return{sum:i,avg:i/this.circularData.length||0}}getMax(){let i=0;for(let e=0;e<this.circularData.length;e++)i<this.circularData[e]&&(i=this.circularData[e]);return i||0}clear(){this.circularData=[]}getStat(){const i=this.getAvg(),e={sum:i.sum,avg:i.avg,max:this.getMax()};return this.clear(),e}}var decoder=`/* eslint-disable no-inner-declarations */
  11252. /* eslint-disable default-case */
  11253. /* eslint-disable no-restricted-globals */
  11254. // import { arrayBuffer } from "stream/consumers"
  11255. // import { addSyntheticLeadingComment, textChangeRangeIsUnchanged } from "typescript"
  11256. /* eslint-disable no-undef */
  11257. const CACHE_BUF_LENGTH = 16
  11258. const YUV_BUF_LENGTH = 16
  11259. if ('function' === typeof importScripts) {
  11260. const startTime = Date.now()
  11261. // self.importScripts('https://static.xverse.cn/wasm/zx_test_exclusive/v2/libxv265dec.js')
  11262. // printConsole.log('Decoder update time is 2021/10/14 12:13 ')
  11263. const YUVArray = []
  11264. const mediaArray = []
  11265. let IframesReceived = 0
  11266. let IframesDecoded = 0
  11267. let lastReceivePts = 0
  11268. let lastProcessPts = 0
  11269. let framesReturned = 0
  11270. let send_out_buffer = 0
  11271. let lastPoc = 0
  11272. let cachedFirstFrame = undefined
  11273. let cachedPanoramaFirstFrame = undefined
  11274. const printConsole = {
  11275. log: (msg) => self.postMessage({ t: MessageEvent.ConsoleLog, printMsg: msg }),
  11276. error: (msg, code) => self.postMessage({ t: MessageEvent.ConsoleError, printMsg: msg, code: code }),
  11277. }
  11278. const MessageEvent = {
  11279. DecodeMessage: 0,
  11280. UpdateStats: 1,
  11281. WASMReady: 2,
  11282. CacheFrame: 3,
  11283. RecordVideo: 4,
  11284. OnlyEmitSignal: 5,
  11285. WASMReadyCost: 6,
  11286. PanoramaMessage: 7,
  11287. RequestIFrame: 8,
  11288. ConsoleLog: 9,
  11289. ConsoleError: 10,
  11290. }
  11291. let lastReceiveContentPts = 0
  11292. let saveMediaBytes = 0 // Just for test use
  11293. const IFrameCacheBuffer = {}
  11294. for (var i = 0; i < CACHE_BUF_LENGTH; ++i) {
  11295. mediaArray.push({
  11296. pts: -1,
  11297. receive_ts: 0,
  11298. decode_ts: 0,
  11299. yuv_ts: 0,
  11300. render_ts: 0,
  11301. media: null,
  11302. meta: null,
  11303. isIDR: false,
  11304. })
  11305. }
  11306. let downloadBlob = (data, fileName, mimeType) => {
  11307. const blob = new Blob([data], {
  11308. type: mimeType,
  11309. })
  11310. const url = URL.createObjectURL(blob)
  11311. self.postMessage({ t: MessageEvent.RecordVideo, fileObj: blob, link: url })
  11312. //downloadURL(url, fileName)
  11313. setTimeout(function () {
  11314. return URL.revokeObjectURL(url)
  11315. }, 3000)
  11316. }
  11317. function Decoder() {
  11318. this.expected_frameCnt = 1
  11319. this.inited = false
  11320. this.wasminited = false
  11321. this.cacheMap = new Map()
  11322. this.receivedMedia = 0
  11323. this.receivedFrame = 0
  11324. this.receivedYUV = 0
  11325. this.receivedEmit = 0
  11326. this.lastReceivedEmit = 0
  11327. this.mediaBytesReceived = 0
  11328. this.metaBytesReceived = 0
  11329. this.prevSeq = 0
  11330. this.packetsLost = 0
  11331. this.packetsDrop = 0
  11332. this.dtpf = 0
  11333. this.dtmf = 0
  11334. this.getFrameInterval = 10
  11335. this.jumpI = false
  11336. this.startEmit = false
  11337. this.JankTimes = 0
  11338. this.bigJankTimes = 0
  11339. this.mediaCacheBuffer = new Uint8Array(1024 * 1024 * 10) // 10MB for video recording
  11340. this.errorCacheBuffer = new Uint8Array(1024 * 1024 * 10) // 10MB for error stream recording
  11341. this.mediaCacheSize = 0
  11342. this.errorCacheSize = 0
  11343. this.startRecord = false
  11344. this.saveRecord = false
  11345. this.requestingIFrame = false
  11346. this.decoderId = 0 // 0 for 720p, 1 for 480p.
  11347. this.DecodablePts = 0
  11348. this.BlockedFrames = []
  11349. this.decodeTimeCircular = Array(120).fill(-1)
  11350. this.dtcPtr = 0
  11351. this.readPtr = 1
  11352. this.writePtr = 1
  11353. this.cntBufInc = 0
  11354. this.prevBufNum = 0
  11355. this.MAX_TRY_TO_DEC_BUFNUM = 3
  11356. this.skipFrameUntilI = true
  11357. this.enable_logging = false
  11358. this.framesReceivedBetweenTimerInterval = 0
  11359. this.maxFramesReceivedBetweenTimerInterval = 0
  11360. this.isFirstFrame = 1
  11361. this.consumerPrevPts = -1
  11362. this.consumerCurrPts = -1
  11363. this.consumerWaitingIDR = false
  11364. this.lastObj = null
  11365. this.bufferIFrame = 0
  11366. this.passiveJitterLength = 0
  11367. }
  11368. //refactor:
  11369. Decoder.prototype.isBufEmpty = function () {
  11370. return this.readPtr == this.writePtr
  11371. }
  11372. Decoder.prototype.isBufFull = function () {
  11373. return (this.writePtr + 1) % CACHE_BUF_LENGTH == this.readPtr
  11374. }
  11375. Decoder.prototype.getNumOfPktToBeDec = function () {
  11376. return (this.writePtr + CACHE_BUF_LENGTH - this.readPtr) % CACHE_BUF_LENGTH
  11377. }
  11378. Decoder.prototype.getNumOfEmptySlot = function () {
  11379. return CACHE_BUF_LENGTH - this.getNumOfPktToBeDec() - 1
  11380. }
  11381. Decoder.prototype.aheadof = function (a, b) {
  11382. return (a - b + 65536) % 65536 > 65536 / 2
  11383. }
  11384. Decoder.prototype.distance = function (a, b) {
  11385. var res
  11386. if (this.aheadof(a, b)) {
  11387. res = this.seqDiff(b, a, 65536)
  11388. } else {
  11389. res = this.seqDiff(a, b, 65536)
  11390. }
  11391. return res
  11392. }
  11393. Decoder.prototype.isSeqJump = function (a, b) {
  11394. return this.distance(a, b) >= CACHE_BUF_LENGTH - 1
  11395. }
  11396. Decoder.prototype.seqDiff = function (a, b, mod) {
  11397. return (a + mod - b) % mod
  11398. }
  11399. //notice: n could be nagative
  11400. Decoder.prototype.seqAdd = function (seq, n, mod) {
  11401. return (seq + mod + n) % mod
  11402. }
  11403. //end refactor
  11404. Decoder.prototype.resetDecoder = function () {
  11405. this.isFirstFrame = 1
  11406. this.expected_frameCnt = 1
  11407. this.receivedMedia = 0
  11408. this.receivedYUV = 0
  11409. this.receivedEmit = 0
  11410. this.lastReceivedEmit = 0
  11411. this.mediaBytesReceived = 0
  11412. this.metaBytesReceived = 0
  11413. this.prevSeq = 0
  11414. this.packetsLost = 0
  11415. this.packetsDrop = 0
  11416. this.dtpf = 0
  11417. this.dtmf = 0
  11418. this.JankTimes = 0
  11419. this.bigJankTimes = 0
  11420. this.getFrameInterval = 10
  11421. this.jumpI = false
  11422. IframesReceived = 0
  11423. IframesDecoded = 0
  11424. lastReceivePts = 0
  11425. lastProcessPts = 0
  11426. lastReceiveContentPts = 0
  11427. this.requestingIFrame = false
  11428. this.DecodablePts = 0
  11429. this.BlockedFrames = []
  11430. this.decodeTimeCircular.fill(-1)
  11431. this.dtcPtr = 0
  11432. for (var i = 0; i < CACHE_BUF_LENGTH; ++i) {
  11433. mediaArray[i].media = null
  11434. mediaArray[i].meta = null
  11435. mediaArray[i] = {
  11436. pts: -1,
  11437. receive_ts: 0,
  11438. decode_ts: 0,
  11439. yuv_ts: 0,
  11440. render_ts: 0,
  11441. media: null,
  11442. meta: null,
  11443. isIDR: false,
  11444. }
  11445. }
  11446. //refactor:
  11447. this.readPtr = this.writePtr = 1
  11448. this.cntBufInc = 0
  11449. this.prevBufNum = 0
  11450. this.MAX_TRY_TO_DEC_BUFNUM = 3
  11451. this.skipFrameUntilI = true
  11452. this.consumerPrevPts = -1
  11453. this.consumerCurrPts = -1
  11454. this.consumerWaitingIDR = false
  11455. this.lastObj = null
  11456. this.bufferIFrame = 0
  11457. //end refactor
  11458. }
  11459. //refactor:
  11460. Decoder.prototype.changeLogSwitch = function (status) {
  11461. this.enable_logging = status
  11462. }
  11463. const MAX_LOG_NUM = 128
  11464. logBufQueue = []
  11465. Decoder.prototype.dumpLogBuf = function () {
  11466. while (logBufQueue.length > 0) {
  11467. console.log(logBufQueue.shift())
  11468. }
  11469. }
  11470. Decoder.prototype.dumpJitterBufInfo = function (label, pts = -1) {
  11471. // if (!this.enable_logging) {
  11472. // return
  11473. // }
  11474. logInfo =
  11475. 'WritePtr: ' +
  11476. this.writePtr +
  11477. ', ReadPtr: ' +
  11478. this.readPtr +
  11479. '\\n' +
  11480. ', Producer Prev/Curr: ' +
  11481. this.prevSeq +
  11482. '/' +
  11483. pts +
  11484. '\\n' +
  11485. ', Consumer Prev/Curr: ' +
  11486. this.consumerPrevPts +
  11487. '/' +
  11488. this.consumerCurrPts +
  11489. '\\n' +
  11490. 'awaitingBuf: ' +
  11491. this.getNumOfPktToBeDec() +
  11492. ', emptySlotNum: ' +
  11493. this.getNumOfEmptySlot() +
  11494. ', skipFrameUntilI: ' +
  11495. this.skipFrameUntilI +
  11496. '\\n' +
  11497. ' framesReceivedBetweenTimerInterval: ' +
  11498. this.framesReceivedBetweenTimerInterval +
  11499. ', maxFramesReceivedBetweenTimerInterval: ' +
  11500. this.maxFramesReceivedBetweenTimerInterval +
  11501. '\\n' +
  11502. ' label: ' +
  11503. label +
  11504. '\\n'
  11505. if (pts != -1) {
  11506. logInfo += ' this.notEnoughSlots(' + pts + '): ' + this.notEnoughSlots(pts) + '\\n'
  11507. }
  11508. if (this.enable_logging) {
  11509. console.log(logInfo)
  11510. } else {
  11511. logBufQueue.push(logInfo)
  11512. if (logBufQueue.length > MAX_LOG_NUM) {
  11513. logBufQueue.shift()
  11514. }
  11515. }
  11516. }
  11517. Decoder.prototype.resetBufItem = function (index) {
  11518. mediaArray[index].media = null
  11519. mediaArray[index].meta = null
  11520. if (mediaArray[index].isIDR == true) {
  11521. this.bufferIFrame -= 1
  11522. }
  11523. mediaArray[index] = {
  11524. pts: -1,
  11525. receive_ts: 0,
  11526. decode_ts: 0,
  11527. yuv_ts: 0,
  11528. render_ts: 0,
  11529. media: null,
  11530. meta: null,
  11531. isIDR: false,
  11532. }
  11533. this.readPtr = this.seqAdd(this.readPtr, 1, CACHE_BUF_LENGTH)
  11534. }
  11535. Decoder.prototype.checkPktOrderInConsumer = function (index) {
  11536. if (this.consumerPrevPts == -1) {
  11537. if (!this.isSlotEmpty(index)) {
  11538. this.consumerPrevPts = mediaArray[index].pts
  11539. }
  11540. return true
  11541. }
  11542. if (this.isSlotEmpty(index)) {
  11543. //lost
  11544. // debugger
  11545. // console.log("[xmedia] return on SLOT EMPTY, prev: %s", prev)
  11546. this.consumerWaitingIDR = true
  11547. this.consumerPrevPts = this.seqAdd(this.consumerPrevPts, 1, 65536)
  11548. return true
  11549. }
  11550. if (!this.slotHasMedia(index)) {
  11551. // pure meta
  11552. // debugger
  11553. // console.log("[xmedia] return on meta, prev: %s, cur: %s", this., mediaArray[index].pts)
  11554. this.consumerPrevPts = mediaArray[index].pts
  11555. return true
  11556. }
  11557. this.consumerCurrPts = mediaArray[index].pts
  11558. if (this.consumerWaitingIDR || this.seqDiff(this.consumerCurrPts, this.consumerPrevPts, 65536) != 1) {
  11559. // if (!mediaArray[index].isIDR && mediaArray[index].media.byteLength!=0) {
  11560. if (this.isPFrame(mediaArray[index].isIDR, mediaArray[index].media.byteLength)) {
  11561. console.error('[INFO][XMEDIA] optimize to further reduce clutter chance. copy console log to developer')
  11562. this.dumpLogBuf()
  11563. this.dumpJitterBufInfo('go away.')
  11564. // debugger
  11565. this.consumerPrevPts = -1
  11566. // this.resetDecoder()
  11567. return false
  11568. }
  11569. }
  11570. // console.log("[xmedia] return finally, prev: %s, cur: %s", prev, cur)
  11571. this.consumerPrevPts = this.consumerCurrPts
  11572. this.consumerWaitingIDR = false
  11573. return true
  11574. }
  11575. Decoder.prototype.slotHasMedia = function (index) {
  11576. return mediaArray[index].media != null && mediaArray[index].media.byteLength != 0
  11577. }
  11578. Decoder.prototype.slotHasContent = function (index) {
  11579. return mediaArray[index].media != null && mediaArray[index].meta != null && mediaArray[index].pts != -1
  11580. }
  11581. Decoder.prototype.procBufItem = function (index) {
  11582. this.dumpJitterBufInfo('Entering Decoder.prototype.procBufItem')
  11583. // console.log('[][Core][WASM], pts: %s, isIDR: %s, length: %s', mediaArray[index].pts, mediaArray[index].isIDR, mediaArray[index].media.length)
  11584. // var loginfo = 'pts: %s, isIDR: %s, length: %s', mediaArray[index].pts, mediaArray[index].isIDR, mediaArray[index].media.length
  11585. needToSkip = this.skipFrameUntilI && !mediaArray[index].isIDR
  11586. var loginfo =
  11587. 'pts: ' +
  11588. mediaArray[index].pts +
  11589. ', isidr: ' +
  11590. mediaArray[index].isIDR +
  11591. ', slotHasMedia: ' +
  11592. this.slotHasMedia(index) +
  11593. ', slotHasMeta: ' +
  11594. (mediaArray[index].meta != null) +
  11595. ', needToSkip: ' +
  11596. needToSkip
  11597. if (this.slotHasContent(index) && !needToSkip) {
  11598. // console.log("[xmedia] %s ------------ 001", mediaArray[index].pts)
  11599. let objData = {
  11600. media: mediaArray[index].media,
  11601. frameCnt: mediaArray[index].pts,
  11602. meta: mediaArray[index].meta,
  11603. metadata: mediaArray[index].metadata,
  11604. isIDR: mediaArray[index].isIDR,
  11605. }
  11606. // -------------------
  11607. if (this.checkPktOrderInConsumer(index)) {
  11608. // console.log("[xmedia] %s ------------ 002", mediaArray[index].pts)
  11609. this.decodeFrame(objData)
  11610. }
  11611. if (mediaArray[index].isIDR) {
  11612. // console.log("[xmedia] %s ------------ 003", mediaArray[index].pts)
  11613. // console.log("mediaArray[index].isIDR: this.skipFrameUntilI = false")
  11614. this.skipFrameUntilI = false
  11615. }
  11616. } else {
  11617. // console.log("[xmedia] %s ------------ 004", mediaArray[index].pts)
  11618. if (this.slotHasMedia(index)) {
  11619. // console.log("[xmedia] %s ------------ 005", mediaArray[index].pts)
  11620. //need to skip, waiting I Frame
  11621. //dropCache++
  11622. this.dropPkt += 1
  11623. // MARKER META1META2
  11624. // self.postMessage({ t: MessageEvent.OnlyEmitSignal, meta_only: true, meta: mediaArray[index].meta, metadata: mediaArray[index].metadata })
  11625. } else {
  11626. // console.log("[xmedia] %s ------------ 006", mediaArray[index].pts)
  11627. // no media
  11628. if (mediaArray[index].meta != null) {
  11629. this.checkPktOrderInConsumer(index)
  11630. // console.log("[xmedia] %s ------------ 007", mediaArray[index].pts)
  11631. // Still frame
  11632. // console.log('[send signal]', mediaArray[index].pts)
  11633. self.postMessage({
  11634. t: MessageEvent.OnlyEmitSignal,
  11635. meta_only: true,
  11636. meta: mediaArray[index].meta,
  11637. metadata: mediaArray[index].metadata,
  11638. })
  11639. } else {
  11640. // console.log("[xmedia] %s ------------ 008", mediaArray[index].pts)
  11641. // Lost_rcv++
  11642. // console.log("lost_rcv++: this.skipFrameUntilI = true")
  11643. // console.info('[xmedia] FFFFF This code should not be executed!!!!')
  11644. console.info('[xmedia] null pkt sneaked into profBufItem without harm')
  11645. this.skipFrameUntilI = true
  11646. }
  11647. }
  11648. }
  11649. this.dumpJitterBufInfo('Leaving Decoder.prototype.procBufItem, ' + loginfo)
  11650. this.lastObj = mediaArray[index]
  11651. this.resetBufItem(index)
  11652. }
  11653. Decoder.prototype.flushBuffer = function (untilIDR) {
  11654. this.dumpJitterBufInfo('Entering Decoder.prototype.flushBuffer')
  11655. this.skipFrameUntilI = true
  11656. var breakWhenIDR = false
  11657. while (this.getNumOfPktToBeDec() > 0) {
  11658. index = this.readPtr
  11659. if (this.slotHasMedia(index)) {
  11660. // dropMedia until IDR // \u6765\u4E0D\u53CA\u89E3\u7801\u4E22\u5E27
  11661. this.packetsDrop += 1
  11662. if (untilIDR) {
  11663. if (mediaArray[index].isIDR == true) {
  11664. breakWhenIDR = true
  11665. break
  11666. }
  11667. }
  11668. } else if (mediaArray[index].meta != null) {
  11669. self.postMessage({
  11670. t: MessageEvent.OnlyEmitSignal,
  11671. meta_only: true,
  11672. meta: mediaArray[index].meta,
  11673. metadata: mediaArray[index].metadata,
  11674. })
  11675. }
  11676. this.resetBufItem(index)
  11677. }
  11678. if (!breakWhenIDR) {
  11679. this.isFirstFrame = true
  11680. }
  11681. this.dumpJitterBufInfo('Leaving Decoder.prototype.flushBuffer')
  11682. return this.isFirstFrame
  11683. }
  11684. // var cnt = 0
  11685. Decoder.prototype.getFrameToDecode = function () {
  11686. this.dumpJitterBufInfo('Entering Decoder.prototype.getFrameToDecode')
  11687. if (this.getNumOfPktToBeDec() == 0) {
  11688. return false
  11689. }
  11690. //bufNum awaiting increase counter
  11691. // while (this.getNumOfPktToBeDec() > CACHE_BUF_LENGTH / 2) {
  11692. // needToCheck = true
  11693. // if (this.cntBufInc > this.MAX_TRY_TO_DEC_BUFNUM) {
  11694. // console.log('ringbuffer is deteriorating, flush until IDR')
  11695. // var untilIDR = true
  11696. // this.flushBuffer(untilIDR)
  11697. // this.cntBufInc = 0
  11698. // break
  11699. // }
  11700. // this.procBufItem(this.readPtr)
  11701. // }
  11702. // if (this.getNumOfPktToBeDec() == 0) {
  11703. // return false
  11704. // }
  11705. let IFrmInBuffer = 0
  11706. let frmInBuffer = 0
  11707. for (var i = 0; i < CACHE_BUF_LENGTH; ++i) {
  11708. if (mediaArray[i].isIDR) {
  11709. IFrmInBuffer += 1
  11710. }
  11711. if (this.slotHasMedia(i)) {
  11712. frmInBuffer += 1
  11713. }
  11714. }
  11715. if (!this.slotHasContent(this.readPtr) && IFrmInBuffer == 0) {
  11716. if (frmInBuffer > 0) {
  11717. // There is P frame in buffer but cannot be decoded.
  11718. // Due to ordered data channel, this is packet loss.
  11719. // So request for I frame here.
  11720. printConsole.log('detect packet lost. Request for I frame.')
  11721. self.postMessage({ t: MessageEvent.RequestIFrame })
  11722. }
  11723. return false
  11724. }
  11725. this.procBufItem(this.readPtr)
  11726. // if (this.getNumOfPktToBeDec() > this.prevBufNum) {
  11727. // this.cntBufInc++
  11728. // } else {
  11729. // if (this.cntBufInc > 2) {
  11730. // // aimd
  11731. // this.cntBufInc / 2
  11732. // }
  11733. // }
  11734. // this.prevBufNum = this.getNumOfPktToBeDec()
  11735. this.dumpJitterBufInfo('Leaving Decoder.prototype.getFrameToDecode')
  11736. return true
  11737. }
  11738. //refactor end:
  11739. var cacheBuffer
  11740. var resultBuffer
  11741. Decoder.prototype.startDecoding = function () {
  11742. function iterative_getFrameToDecode() {
  11743. self.decoder.framesReceivedBetweenTimerInterval = 0
  11744. self.decoder.dumpJitterBufInfo('Entering Decoder.prototype.iterative_getFrameToDecode')
  11745. var start_ts = Date.now()
  11746. let hasDecodeFrame = self.decoder.getFrameToDecode()
  11747. var end_ts = Date.now()
  11748. // refactor
  11749. let expect_interval =
  11750. 1000 / (30 + Math.max(self.decoder.getNumOfPktToBeDec() - self.decoder.passiveJitterLength, 0))
  11751. //let expect_interval = 1000 / (Decoder.prototype.getNumOfPktToBeDec() + 30)
  11752. if (hasDecodeFrame) {
  11753. let usedTime = end_ts - start_ts
  11754. self.decoder.getFrameInterval = expect_interval - Math.max(usedTime, self.decoder.dtpf)
  11755. if (self.decoder.getFrameInterval < 1) {
  11756. self.decoder.getFrameInterval = 0
  11757. }
  11758. } else {
  11759. self.decoder.getFrameInterval = 5
  11760. }
  11761. // let usedTime = end_ts - start_ts
  11762. // FPS = 30
  11763. // if (usedTime * FPS < 1000) {
  11764. // self.decoder.getFrameInterval = 1000 / (FPS + Decoder.prototype.getNumOfPktToBeDec())
  11765. // } else {
  11766. // self.decoder.getFrameInterval = 1 //ms
  11767. // }
  11768. // if (Decoder.prototype.getNumOfPktToBeDec() == 0) {
  11769. // //Hinse: have to get buf to send asap.
  11770. // self.decoder.getFrameInterval = 5 //ms
  11771. // }
  11772. setTimeout(iterative_getFrameToDecode, self.decoder.getFrameInterval)
  11773. self.decoder.dumpJitterBufInfo('Leaving Decoder.prototype.iterative_getFrameToDecode')
  11774. // refactor end
  11775. }
  11776. function postStats() {
  11777. function add(accumulator, a) {
  11778. if (a == -1) {
  11779. a = 0
  11780. }
  11781. return accumulator + a
  11782. }
  11783. function count_valid(accumulator, a) {
  11784. let non_zero = 0
  11785. if (a != -1) {
  11786. non_zero = 1
  11787. }
  11788. return accumulator + non_zero
  11789. }
  11790. function max(maxer, a) {
  11791. return Math.max(maxer, a)
  11792. }
  11793. const dtpf =
  11794. self.decoder.decodeTimeCircular.reduce(add, 0) / self.decoder.decodeTimeCircular.reduce(count_valid, 0) || 0
  11795. const dtmf = self.decoder.decodeTimeCircular.reduce(max, 0)
  11796. let objData = {
  11797. t: MessageEvent.UpdateStats,
  11798. mediaBytesReceived: self.decoder.mediaBytesReceived,
  11799. metaBytesReceived: self.decoder.metaBytesReceived,
  11800. packetsLost: self.decoder.packetsLost, // \u7F51\u7EDC\u4E22\u5E27
  11801. packetsDrop: self.decoder.packetsDrop, // \u6765\u4E0D\u53CA\u89E3\u7801\u4E22\u5E27
  11802. framesReceived: self.decoder.receivedMedia,
  11803. framesDecoded: self.decoder.receivedYUV,
  11804. framesRendered: self.decoder.receivedEmit,
  11805. framesReturned: framesReturned,
  11806. // framesAwait: leastReceivePts - lastProcessPts,
  11807. framesAwait: self.decoder.getNumOfPktToBeDec(), // \u7B49\u5F85\u89E3\u7801\u7684\u5E27
  11808. decodeTimePerFrame: dtpf,
  11809. decodeTimeMaxFrame: dtmf,
  11810. sendOutBuffer: send_out_buffer,
  11811. JankTimes: self.decoder.JankTimes,
  11812. bigJankTimes: self.decoder.bigJankTimes,
  11813. receivedIframe: self.decoder.IframesReceived,
  11814. decodedIframe: self.decoder.IframesDecoded,
  11815. }
  11816. self.postMessage(objData)
  11817. self.decoder.dtmf = 0
  11818. }
  11819. setTimeout(iterative_getFrameToDecode, this.getFrameInterval)
  11820. setInterval(postStats, 1000)
  11821. }
  11822. Decoder.prototype.initAll = function (config) {
  11823. if (typeof wasmSource != 'undefined') {
  11824. if (wasmSource == 0) {
  11825. // Load from indexedDB
  11826. // console.log('Load WASM from indexedDB')
  11827. printConsole.log('Load WASM from indexedDB')
  11828. wasmSource = undefined
  11829. } else if (wasmSource == 1) {
  11830. // Load by fetch
  11831. // console.log('Load WASM by fetch')
  11832. printConsole.log('Load WASM by fetch')
  11833. wasmSource = undefined
  11834. } else {
  11835. printConsole.log('WASM not ready now, wait for 200 ms.')
  11836. }
  11837. } else {
  11838. printConsole.log('wasm variable is not defined. Probably libffmpeg.js file is not loaded properly.')
  11839. }
  11840. if (typeof wasmTable === 'undefined') {
  11841. setTimeout(self.decoder.initAll, 200, config)
  11842. return 0
  11843. }
  11844. cacheBuffer = Module._malloc(1024 * 1024)
  11845. resultBuffer = Module._malloc(64)
  11846. self.postMessage({
  11847. t: MessageEvent.WASMReadyCost,
  11848. type: 'report',
  11849. data: {
  11850. metric: 'wasmDownloadCost',
  11851. value: Date.now() - startTime,
  11852. group: 'costs',
  11853. },
  11854. })
  11855. // WASM already initialized. Now we open decoder.
  11856. const LOG_LEVEL_WASM = 2
  11857. const DECODER_H264 = 0
  11858. const decoder_type = DECODER_H264
  11859. for (var j = 0; j < YUV_BUF_LENGTH; ++j) {
  11860. YUVArray.push({ status: 0, buffer: new Uint8Array((config.width * config.height * 3) / 2) })
  11861. }
  11862. printConsole.log('Going to open decoder ' + String(Date.now()))
  11863. var ret0 = Module._openDecoder(0, decoder_type, LOG_LEVEL_WASM)
  11864. if (ret0 == 0) {
  11865. self.decoder.startDecoding()
  11866. self.postMessage({ t: MessageEvent.WASMReady, wasm_ready: true, updateStats: false })
  11867. } else {
  11868. printConsole.error('openDecoder failed with error ' + String(ret0), '5001')
  11869. return 1
  11870. }
  11871. return 0
  11872. }
  11873. Decoder.prototype.cacheFrame = function (data) {
  11874. if (data.position != undefined) {
  11875. var media = data.data.subarray(data.metaLen, data.metaLen + data.mediaLen)
  11876. if (IFrameCacheBuffer[JSON.stringify(data.position)] == undefined) {
  11877. for (var key in IFrameCacheBuffer) delete IFrameCacheBuffer[key] // Clear Frame Cache
  11878. IFrameCacheBuffer[JSON.stringify(data.position)] = {}
  11879. }
  11880. IFrameCacheBuffer[JSON.stringify(data.position)][data.cachedKey] = media
  11881. self.postMessage({
  11882. t: MessageEvent.CacheFrame,
  11883. cacheFrame: true,
  11884. cachedKey: data.cachedKey,
  11885. metadata: data.metadata,
  11886. })
  11887. }
  11888. }
  11889. Decoder.prototype.updateMediaMetaStats = function (data) {
  11890. this.metaBytesReceived += data.metaLen
  11891. this.mediaBytesReceived += data.mediaLen
  11892. if (data.mediaLen != 0) {
  11893. this.receivedMedia++
  11894. }
  11895. }
  11896. Decoder.prototype.isIFrame = function (isIDR, mediaLen) {
  11897. // return data.isIDR && media.byteLength !=0
  11898. return isIDR && mediaLen != 0
  11899. }
  11900. Decoder.prototype.isPFrame = function (isIDR, mediaLen) {
  11901. // return !data.isIDR && media.byteLength !=0
  11902. return !isIDR && mediaLen != 0
  11903. }
  11904. Decoder.prototype.isPureMeta = function (metaLen, mediaLen) {
  11905. // return media.byteLength == 0 && meta.byteLength !=0
  11906. return mediaLen == 0 && metaLen != 0
  11907. }
  11908. Decoder.prototype.isInvalidPkt = function (isIDR, mediaLen, metaLen) {
  11909. return !this.isIFrame(isIDR, mediaLen) && !this.isPFrame(isIDR, mediaLen) && !this.isPureMeta(metaLen, mediaLen)
  11910. }
  11911. Decoder.prototype.isSlotEmpty = function (index) {
  11912. return !this.slotHasMedia(index) && mediaArray[index].meta == null
  11913. }
  11914. Decoder.prototype.handleNewPktOnFlush = function (isIDR, mediaLen) {
  11915. var dropPkt = false
  11916. // console.log("[xmedia] 000-1 isFirstFrame %s", this.isFirstFrame)
  11917. if (this.isFirstFrame) {
  11918. // let IDR/meta pass
  11919. // console.log("[xmedia] 000-2 isIDR: %s, mediaLen: %s", isIDR, mediaLen)
  11920. // console.log("[xmedia] 000-3 this.isPFrame(isIDR, mediaLen): %s", this.isPFrame(isIDR, mediaLen))
  11921. if (this.isPFrame(isIDR, mediaLen)) {
  11922. // console.log("[xmedia] 001: isPFrame TRUE")
  11923. this.packetsDrop += 1
  11924. // MARKER META1META2
  11925. dropPkt = true
  11926. }
  11927. if (this.isIFrame(isIDR, mediaLen)) {
  11928. // console.log("[xmedia] 002: isIFrame TRUE")
  11929. this.isFirstFrame = false
  11930. }
  11931. }
  11932. // console.log("[xmedia] 003: dropPkt: %s", dropPkt)
  11933. return dropPkt
  11934. }
  11935. Decoder.prototype.notEnoughSlots = function (pts) {
  11936. return this.isBufFull() || this.seqDiff(pts, this.prevSeq, CACHE_BUF_LENGTH) > this.getNumOfEmptySlot()
  11937. }
  11938. Decoder.prototype.receiveFrame = function (data) {
  11939. var key = data.cachedKey
  11940. var pts = data.frameCnt
  11941. var meta = data.data.subarray(0, data.metaLen)
  11942. var media
  11943. if (data.cached) {
  11944. media = IFrameCacheBuffer[JSON.stringify(data.position)][key]
  11945. } else if (data.cacheRequest) {
  11946. media = data.data.subarray(data.metaLen, data.metaLen + data.mediaLen)
  11947. self.decoder.cacheFrame(data)
  11948. } else {
  11949. media = data.data.subarray(data.metaLen, data.metaLen + data.mediaLen)
  11950. }
  11951. this.updateMediaMetaStats(data)
  11952. if (this.isFirstFrame) {
  11953. // console.log('[xmedia] isFirstFrame = true. pts:%s', pts)
  11954. if (this.isPFrame(data.isIDR, media.byteLength)) {
  11955. // MARKER META1META2
  11956. this.packetsDrop += 1
  11957. return
  11958. }
  11959. this.prevSeq = this.seqDiff(pts, 1, 65536)
  11960. this.readPtr = this.writePtr = pts % CACHE_BUF_LENGTH
  11961. if (data.isIDR) {
  11962. this.isFirstFrame = false
  11963. }
  11964. }
  11965. if (pts !== this.seqAdd(this.prevSeq, 1, 65536) && pts !== this.prevSeq) {
  11966. this.packetsLost += 1
  11967. }
  11968. const index = pts % CACHE_BUF_LENGTH
  11969. if (this.startRecord) {
  11970. this.mediaCacheBuffer.set(media, this.mediaCacheSize)
  11971. this.mediaCacheSize += media.byteLength
  11972. }
  11973. if (this.saveRecord) {
  11974. downloadBlob(this.mediaCacheBuffer.subarray(0, this.mediaCacheSize), 'test.264', 'application/octet-stream')
  11975. this.mediaCacheSize = 0
  11976. this.saveRecord = false
  11977. this.startRecord = false
  11978. }
  11979. //refactor:
  11980. // Step 1, big jump detected. we cannot handle it, flush all.
  11981. var untilIDR, pktDrop
  11982. if (this.isSeqJump(this.prevSeq, pts)) {
  11983. // console.log('[resetdecoder] Fatal: decoder seq jump from ' + this.prevSeq + ' to ' + pts)
  11984. untilIDR = false
  11985. this.flushBuffer(untilIDR)
  11986. pktDrop = this.handleNewPktOnFlush(data.isIDR, media.byteLength)
  11987. if (pktDrop) return
  11988. }
  11989. this.dumpJitterBufInfo('Entering Decoder.prototype.receiveFrame', pts)
  11990. // console.log("--->> this.notEnoughSlots(pts): %s", this.notEnoughSlots(pts))
  11991. // Step 2,
  11992. if (this.aheadof(pts, this.prevSeq)) {
  11993. // pts before prevSeq
  11994. // pkts in wrong order
  11995. if (this.packetsLost > 0) {
  11996. this.packetsLost -= 1
  11997. // this.packetdisorder +=1
  11998. }
  11999. // console.log("[xmedia] disorder frame received. preSeq: %s, pts: %s", this.prevSeq, pts)
  12000. if (this.seqDiff(this.prevSeq, pts, 65536) < this.getNumOfPktToBeDec()) {
  12001. // slot for pts is not handled yet. just put it back:
  12002. // console.log('put disorder frame to enc_queue, pkt:%s, prevPts: %s, numOfPktToBeDec: %s', pts, this.prevSeq, this.getNumOfPktToBeDec())
  12003. } else {
  12004. //dropDisorder++
  12005. console.error(
  12006. 'drop disorder pkt:%s, prevPts: %s, numOfPktToBeDec: %s',
  12007. pts,
  12008. this.prevSeq,
  12009. this.getNumOfPktToBeDec(),
  12010. )
  12011. this.packetsDrop += 1
  12012. // ---------------------
  12013. // Note:
  12014. //
  12015. // Three principles for meta data:
  12016. // step 1 step 2
  12017. // 1. backend -----> frontend (decoder.js) -----> frontend (worker.js), meta pkts must be kept in order in the whole pipeline
  12018. // 2. if media presents and needs to be dropped, the meta companion needs to be dropped together.
  12019. // 3. if media is absent (media.bytelength == 0), send meta anyway
  12020. // ---------------------
  12021. // According to rule 1, drop meta at this point is reasonable.
  12022. return
  12023. }
  12024. } else {
  12025. // pts after prevSeq
  12026. // make sure the ringbuffer has empty slot for new pkt
  12027. if (this.notEnoughSlots(pts)) {
  12028. this.dumpJitterBufInfo('Fatal: decoder buf is full', pts)
  12029. //dropIncoming
  12030. untilIDR = true
  12031. this.flushBuffer(untilIDR)
  12032. if (this.notEnoughSlots(pts)) {
  12033. untilIDR = false
  12034. this.flushBuffer(untilIDR)
  12035. }
  12036. pktDrop = this.handleNewPktOnFlush(data.isIDR, media.byteLength)
  12037. if (pktDrop) return
  12038. }
  12039. }
  12040. mediaArray[index] = {
  12041. pts: pts,
  12042. receive_ts: Date.now(),
  12043. decode_ts: 0,
  12044. yuv_ts: 0,
  12045. render_ts: 0,
  12046. media: media,
  12047. meta: meta,
  12048. metadata: data.metadata,
  12049. isIDR: data.isIDR,
  12050. }
  12051. if (data.isIDR == true) {
  12052. this.bufferIFrame += 1
  12053. }
  12054. this.framesReceivedBetweenTimerInterval += 1
  12055. if (this.framesReceivedBetweenTimerInterval > this.maxFramesReceivedBetweenTimerInterval) {
  12056. this.maxFramesReceivedBetweenTimerInterval = this.framesReceivedBetweenTimerInterval
  12057. }
  12058. if (!this.aheadof(pts, this.prevSeq)) {
  12059. // writePtr += (cur - prev)
  12060. this.writePtr = this.seqAdd(this.writePtr, this.seqDiff(pts, this.prevSeq, CACHE_BUF_LENGTH), CACHE_BUF_LENGTH)
  12061. if (this.seqAdd(index, 1, CACHE_BUF_LENGTH) != this.writePtr) {
  12062. this.dumpJitterBufInfo('dec worker internal info: index (' + index + ') != write_ptr (' + this.writePtr + ')')
  12063. // debugger
  12064. }
  12065. this.prevSeq = pts
  12066. }
  12067. this.dumpJitterBufInfo('Leaving Decoder.prototype.receiveFrame')
  12068. //refactor end
  12069. }
  12070. Decoder.prototype.startEmiter = function () {
  12071. self.decoder.startEmit = true
  12072. if (cachedFirstFrame != undefined) {
  12073. self.postMessage(cachedFirstFrame, [cachedFirstFrame.data.buffer])
  12074. send_out_buffer += 1
  12075. this.receivedEmit++
  12076. cachedFirstFrame = undefined
  12077. }
  12078. if (cachedPanoramaFirstFrame != undefined) {
  12079. self.postMessage(cachedPanoramaFirstFrame)
  12080. send_out_buffer += 1
  12081. this.receivedEmit++
  12082. cachedPanoramaFirstFrame = undefined
  12083. }
  12084. }
  12085. Decoder.prototype.decodePanorama = function (data) {
  12086. console.log('upload pano data')
  12087. var content = data.data.data
  12088. var content_size = data.data.mediaLen
  12089. // var cacheBuffer = Module._malloc(content_size)
  12090. // var resultBuffer = Module._malloc(64)
  12091. Module.HEAPU8.set(content, cacheBuffer)
  12092. let ret = 0
  12093. try {
  12094. ret = Module._decodeData(0, 0, cacheBuffer, content_size, resultBuffer)
  12095. // currently only need to use flushDecoder for pano mode.
  12096. ret = Module._flushDecoder(0, 0, resultBuffer)
  12097. // // console.log('[][Core][WASM] return value %s',ret)
  12098. // if(ret!=0){
  12099. // // console.log('[][Core][WASM],-abcdefg-----> ', ret)
  12100. // var ret_close = Module._closeDecoder(0)
  12101. // // eslint-disable-next-line no-empty
  12102. // if (ret_close === 0) {
  12103. // // console.log('[][Core][WASM] decoder closed for restart')
  12104. // } else {
  12105. // printConsole.error('close decoder failed after decode pano.')
  12106. // return 1
  12107. // }
  12108. // var ret0 = Module._openDecoder(0, 0, 2)
  12109. // // console.log('[][Core][WASM] decoder restart success')
  12110. // // var ret1 = Module._openDecoder(1, decoder_type, LOG_LEVEL_WASM)
  12111. // if (ret0 === 0) {
  12112. // ret = Module._decodeData(0, 0, cacheBuffer, content_size, resultBuffer)
  12113. // } else {
  12114. // printConsole.error('openDecoder failed with error ' + String(ret0) , '5001')
  12115. // return 1
  12116. // }
  12117. // }
  12118. } catch (e) {
  12119. console.log('catch error ', e)
  12120. printConsole.error(e.message, '5002')
  12121. }
  12122. // let ret = Module._decodeData(0, 0, cacheBuffer, content_size, resultBuffer)
  12123. var width = Module.getValue(resultBuffer, 'i32')
  12124. var height = Module.getValue(resultBuffer + 4, 'i32')
  12125. var stride_y = Module.getValue(resultBuffer + 20, 'i32')
  12126. var stride_u = Module.getValue(resultBuffer + 24, 'i32')
  12127. var stride_v = Module.getValue(resultBuffer + 28, 'i32')
  12128. var addr_y = Module.getValue(resultBuffer + 8, 'i32')
  12129. var addr_u = Module.getValue(resultBuffer + 12, 'i32')
  12130. var addr_v = Module.getValue(resultBuffer + 16, 'i32')
  12131. var poc = Module.getValue(resultBuffer + 32, 'i32')
  12132. if (ret != 0) {
  12133. printConsole.log(
  12134. 'Decode Data error for panorama, ret value is ' + String(ret) + ', frame content size: ' + String(content_size),
  12135. )
  12136. return
  12137. }
  12138. var yuv_data = new Uint8Array((width * height * 3) / 2)
  12139. let pos = 0
  12140. for (let i = 0; i < height; i++) {
  12141. let src = addr_y + i * stride_y
  12142. let tmp = HEAPU8.subarray(src, src + width)
  12143. tmp = new Uint8Array(tmp)
  12144. yuv_data.set(tmp, pos)
  12145. pos += tmp.length
  12146. }
  12147. for (let i = 0; i < height / 2; i++) {
  12148. let src = addr_u + i * stride_u
  12149. let tmp = HEAPU8.subarray(src, src + width / 2)
  12150. tmp = new Uint8Array(tmp)
  12151. yuv_data.set(tmp, pos)
  12152. pos += tmp.length
  12153. let src2 = addr_v + i * stride_v
  12154. let tmp2 = HEAPU8.subarray(src2, src2 + width / 2)
  12155. tmp2 = new Uint8Array(tmp2)
  12156. yuv_data.set(tmp2, pos)
  12157. pos += tmp2.length
  12158. }
  12159. const objData = {
  12160. t: MessageEvent.PanoramaMessage,
  12161. tileId: data.data.tileId,
  12162. // uuid: data.data.uuid,
  12163. data: yuv_data,
  12164. metadata: data.data.metadata,
  12165. // x: data.data.x,
  12166. // y: data.data.y,
  12167. // z: data.data.z,
  12168. }
  12169. //TODO: remove debug
  12170. if (this.startEmit) {
  12171. self.postMessage(objData)
  12172. } else {
  12173. cachedPanoramaFirstFrame = objData
  12174. }
  12175. // console.log('upload pano data with dataLength:', len(yuv_data))
  12176. var ret_close = Module._closeDecoder(0)
  12177. // eslint-disable-next-line no-empty
  12178. if (ret_close === 0) {
  12179. // console.log('[][Core][WASM] decoder closed for restart')
  12180. } else {
  12181. printConsole.error('close decoder failed after decode pano.')
  12182. return 1
  12183. }
  12184. var ret0 = Module._openDecoder(0, 0, 2)
  12185. // var ret1 = Module._openDecoder(1, decoder_type, LOG_LEVEL_WASM)
  12186. if (ret0 === 0) {
  12187. // console.log('[][Core][WASM] decoder restart success')
  12188. self.decoder.startDecoding()
  12189. self.postMessage({ t: MessageEvent.WASMReady, wasm_ready: true, updateStats: false })
  12190. } else {
  12191. printConsole.error('openDecoder failed with error ' + String(ret0), '5001')
  12192. return 1
  12193. }
  12194. }
  12195. Decoder.prototype.decodeFrame = function (data) {
  12196. var content = data.media
  12197. if (typeof content == 'undefined') {
  12198. printConsole.error('null content in decoder', '5999')
  12199. return
  12200. }
  12201. var content_size = content.byteLength
  12202. // var cacheBuffer = Module._malloc(content_size)
  12203. // var resultBuffer = Module._malloc(64)
  12204. Module.HEAPU8.set(content, cacheBuffer)
  12205. const index = data.frameCnt % CACHE_BUF_LENGTH
  12206. mediaArray[index].decode_ts = Date.now()
  12207. var objData
  12208. if (content_size != 0) {
  12209. // var date = Date.now()
  12210. // var curDate = Date.now()
  12211. // while (curDate - date < 100) {
  12212. // curDate = Date.now()
  12213. // }
  12214. // TODO: Enable/Disable it by config
  12215. if (data.isIDR) {
  12216. this.errorCacheSize = 0
  12217. }
  12218. // Guarantee that stream start from I frame
  12219. if (this.errorCacheSize != 0 || data.isIDR) {
  12220. this.errorCacheBuffer.set(content, this.mediaCacheSize)
  12221. this.errorCacheSize += content.byteLength
  12222. }
  12223. let start_ts = Date.now()
  12224. let ret = 0
  12225. try {
  12226. ret = Module._decodeData(0, data.frameCnt, cacheBuffer, content_size, resultBuffer)
  12227. // if(ret==8){
  12228. // // console.log('[][Core][WASM],-abcdefg-----> ', ret)
  12229. // var ret_close = Module._closeDecoder(0)
  12230. // // eslint-disable-next-line no-empty
  12231. // if (ret_close === 0) {
  12232. // // console.log('[][Core][WASM] decoder closed for restart')
  12233. // } else {
  12234. // printConsole.error('close decoder failed after decode pano.')
  12235. // return 1
  12236. // }
  12237. // var ret0 = Module._openDecoder(0, 0, 2)
  12238. // // console.log('[][Core][WASM] decoder restart success')
  12239. // // var ret1 = Module._openDecoder(1, decoder_type, LOG_LEVEL_WASM)
  12240. // if (ret0 === 0) {
  12241. // ret = Module._decodeData(0, data.frameCnt, cacheBuffer, content_size, resultBuffer)
  12242. // } else {
  12243. // printConsole.error('openDecoder failed with error ' + String(ret0) , '5001')
  12244. // return 1
  12245. // }
  12246. // }
  12247. } catch (e) {
  12248. console.log('catch error ', e)
  12249. if (this.errorCacheSize > 0) {
  12250. downloadBlob(this.errorCacheBuffer.subarray(0, this.errorCacheSize), 'error.264', 'application/octet-stream')
  12251. this.errorCacheSize = 0
  12252. }
  12253. printConsole.error(e.message, '5002')
  12254. }
  12255. var width = Module.getValue(resultBuffer, 'i32')
  12256. var height = Module.getValue(resultBuffer + 4, 'i32')
  12257. var stride_y = Module.getValue(resultBuffer + 20, 'i32')
  12258. var stride_u = Module.getValue(resultBuffer + 24, 'i32')
  12259. var stride_v = Module.getValue(resultBuffer + 28, 'i32')
  12260. var addr_y = Module.getValue(resultBuffer + 8, 'i32')
  12261. var addr_u = Module.getValue(resultBuffer + 12, 'i32')
  12262. var addr_v = Module.getValue(resultBuffer + 16, 'i32')
  12263. var poc = Module.getValue(resultBuffer + 32, 'i32')
  12264. var pts = data.frameCnt
  12265. if (ret != 0) {
  12266. printConsole.log(
  12267. 'Decode Data error for video stream, ret value is ' +
  12268. String(ret) +
  12269. ', frame content size: ' +
  12270. String(content_size),
  12271. )
  12272. if (this.errorCacheSize > 0) {
  12273. downloadBlob(this.errorCacheBuffer.subarray(0, this.errorCacheSize), 'error.264', 'application/octet-stream')
  12274. this.errorCacheSize = 0
  12275. }
  12276. printConsole.log('current poc is ' + String(poc) + ', last poc is ' + String(lastPoc))
  12277. return
  12278. }
  12279. lastPoc = poc
  12280. this.receivedYUV++
  12281. let end_ts = Date.now()
  12282. fdt = end_ts - start_ts
  12283. if (fdt + self.decoder.getFrameInterval > 84) {
  12284. this.JankTimes++
  12285. }
  12286. if (fdt + self.decoder.getFrameInterval > 125) {
  12287. this.bigJankTimes++
  12288. }
  12289. self.decoder.dtpf = self.decoder.dtpf * 0.9 + fdt * 0.1
  12290. // if (fdt > self.decoder.dtmf) {
  12291. // self.decoder.dtmf = fdt
  12292. // }
  12293. self.decoder.decodeTimeCircular[self.decoder.dtcPtr] = fdt
  12294. self.decoder.dtcPtr = (self.decoder.dtcPtr + 1) % self.decoder.decodeTimeCircular.length
  12295. if (YUVArray.length <= 0) {
  12296. // printConsole.error('No buffer to save YUV after decoding, pts is ' + String(pts), '5002')
  12297. return
  12298. }
  12299. var first_available_buffer = YUVArray.shift()
  12300. var yuv_data = first_available_buffer.buffer
  12301. let pos = 0
  12302. for (let i = 0; i < height; i++) {
  12303. let src = addr_y + i * stride_y
  12304. let tmp = HEAPU8.subarray(src, src + width)
  12305. tmp = new Uint8Array(tmp)
  12306. yuv_data.set(tmp, pos)
  12307. pos += tmp.length
  12308. }
  12309. for (let i = 0; i < height / 2; i++) {
  12310. let src = addr_u + i * stride_u
  12311. let tmp = HEAPU8.subarray(src, src + width / 2)
  12312. tmp = new Uint8Array(tmp)
  12313. yuv_data.set(tmp, pos)
  12314. pos += tmp.length
  12315. let src2 = addr_v + i * stride_v
  12316. let tmp2 = HEAPU8.subarray(src2, src2 + width / 2)
  12317. tmp2 = new Uint8Array(tmp2)
  12318. yuv_data.set(tmp2, pos)
  12319. pos += tmp2.length
  12320. }
  12321. objData = {
  12322. t: MessageEvent.DecodeMessage,
  12323. data: yuv_data,
  12324. width: width,
  12325. height: height,
  12326. pts: data.frameCnt,
  12327. yuv_ts: Date.now(),
  12328. meta: data.meta,
  12329. metadata: data.metadata,
  12330. }
  12331. } else {
  12332. objData = {
  12333. t: MessageEvent.DecodeMessage,
  12334. data: null,
  12335. width: 0,
  12336. height: 0,
  12337. pts: data.frameCnt,
  12338. yuv_ts: Date.now(),
  12339. meta: data.meta,
  12340. metadata: data.metadata,
  12341. }
  12342. }
  12343. if (this.startEmit) {
  12344. if (objData.data != null) {
  12345. objData.postTs = Date.now()
  12346. self.postMessage(objData, [objData.data.buffer])
  12347. send_out_buffer += 1
  12348. this.receivedEmit++
  12349. } else {
  12350. objData.postTs = Date.now()
  12351. self.postMessage(objData)
  12352. this.receivedEmit++
  12353. }
  12354. } else {
  12355. if (objData.data != null) {
  12356. cachedFirstFrame = objData
  12357. }
  12358. }
  12359. // if (cacheBuffer != null) {
  12360. // Module._free(cacheBuffer)
  12361. // cacheBuffer = null
  12362. // }
  12363. // if (resultBuffer != null) {
  12364. // Module._free(resultBuffer)
  12365. // resultBuffer = null
  12366. // }
  12367. return
  12368. }
  12369. Decoder.prototype.receiveBuffer = function (data) {
  12370. framesReturned++
  12371. send_out_buffer -= 1
  12372. YUVArray.push({ status: 0, buffer: data.buffer })
  12373. }
  12374. Decoder.prototype.setPassiveJitter = function (len) {
  12375. this.passiveJitterLength = len
  12376. }
  12377. Decoder.prototype.uninitDecoder = function () {
  12378. printConsole.log('Going to uninit decoder.')
  12379. }
  12380. Decoder.prototype.StartRecord = function () {
  12381. printConsole.log('Start Record')
  12382. this.startRecord = true
  12383. }
  12384. Decoder.prototype.SaveRecord = function () {
  12385. printConsole.log('Save Record')
  12386. this.saveRecord = true
  12387. }
  12388. Decoder.prototype.ReceivePanorama = function (data) {
  12389. self.decoder.resetDecoder()
  12390. self.decoder.decodePanorama(data)
  12391. }
  12392. Decoder.prototype.LoadWASM = function (url) {
  12393. printConsole.log('Load WASM from ' + String(url))
  12394. try {
  12395. self.importScripts(url)
  12396. } catch (e) {
  12397. console.log('catch error ', e)
  12398. printConsole.error(e.message, '5003')
  12399. }
  12400. }
  12401. // self.incoming_pkt_queue = new array()
  12402. function getRandomInt(max) {
  12403. return Math.floor(Math.random() * max)
  12404. }
  12405. // console.log(getRandomInt(30));
  12406. self.decoder = new Decoder()
  12407. netArray = []
  12408. var gTmpIdx = 0
  12409. var gLossCnt = 0
  12410. self.onmessage = function (evt) {
  12411. switch (evt.data.t) {
  12412. case 1: // Init Message
  12413. self.decoder.initAll(evt.data.config)
  12414. break
  12415. case 0: // Decode Message
  12416. // console.log('[][Core][WASM],------> ', evt.data)
  12417. gTmpIdx += 1
  12418. randLen = 16
  12419. // randLen = getRandomInt(30)
  12420. // eslint-disable-next-line no-constant-condition
  12421. if (gTmpIdx > 100 && false) {
  12422. var test_jitter_buffer = true
  12423. if (test_jitter_buffer == true) {
  12424. if (netArray.length % 5 == 4) {
  12425. // netArray.insert(netArray.length -1, evt.data)
  12426. netArray.splice(netArray.length - 1, 0, evt.data)
  12427. } else {
  12428. netArray.push(evt.data)
  12429. }
  12430. if (netArray.length > randLen) {
  12431. // 1. jitter
  12432. while (netArray.length > 0) {
  12433. // console.log("[xmedia] array len: %s", netArray.length)
  12434. gLossCnt += 1
  12435. var pkt = netArray.shift()
  12436. // lose pkt
  12437. var dropInterval = 50
  12438. var dropContinousPkts = 3
  12439. if (gLossCnt % dropInterval < dropContinousPkts) {
  12440. if (gLossCnt == dropInterval + dropContinousPkts - 1) {
  12441. gLossCnt = 0
  12442. }
  12443. } else {
  12444. self.decoder.receiveFrame(pkt)
  12445. }
  12446. }
  12447. // // 2. disorder
  12448. // if (incoming_pkt_queue.length % 3) {
  12449. // in[0]
  12450. // in[2]
  12451. // in[1]
  12452. // }
  12453. }
  12454. } else {
  12455. self.decoder.receiveFrame(evt.data)
  12456. }
  12457. } else {
  12458. self.decoder.receiveFrame(evt.data)
  12459. }
  12460. break
  12461. case 2: // Receive used buffer
  12462. self.decoder.receiveBuffer(evt.data)
  12463. break
  12464. case 3: // Unint Message
  12465. self.decoder.uninitDecoder()
  12466. break
  12467. case 4: // Reset status
  12468. self.decoder.resetDecoder()
  12469. break
  12470. case 5: // Start emit
  12471. self.decoder.startEmiter()
  12472. break
  12473. case 6: // Start Record
  12474. self.decoder.StartRecord()
  12475. break
  12476. case 7: // Save Record
  12477. self.decoder.SaveRecord()
  12478. break
  12479. case 8: // Panorama Decode Message
  12480. self.decoder.ReceivePanorama(evt.data)
  12481. break
  12482. case 9: // Select WASM Version
  12483. self.decoder.setPassiveJitter(evt.data.jitterLength)
  12484. self.decoder.LoadWASM(evt.data.url)
  12485. break
  12486. case 100: // change decoder worker status
  12487. self.decoder.changeLogSwitch(evt.data.status)
  12488. break
  12489. }
  12490. }
  12491. }
  12492. `;const panorama_width=4096,panorama_height=2048,tile_width=512,tile_height=256;function ToRadius(a){return a/180*Math.PI}function ToAngle(a){return a/Math.PI*180}function getAngleInView(a,i){const e={},o=i.x-a.width*.5,s=a.height*.5-i.y,c=-1*ToRadius(a.angle.pitch),d=ToRadius(a.angle.yaw),_=a.width/2/Math.tan(ToRadius(a.horz_fov/2)),b=Math.sin(c),k=Math.cos(c);for(e.yaw=Math.atan2(o,_*k+s*b),e.pitch=Math.atan2((s-_*Math.tan(c))*Math.cos(e.yaw),_+s*Math.tan(c)),e.pitch=ToAngle(e.pitch),e.yaw=ToAngle(d+e.yaw);e.yaw>359.9;)e.yaw-=360;for(;e.yaw<0;)e.yaw+=360;return e}function getRectangleInView(a){const i={},e=Array(9),o=a.height,s=a.width;for(let d=0,_=0;_<=o;_+=o/2)for(let b=0;b<=s;b+=s/2,d++){const k={};k.x=b,k.y=_;let j={};j=a,j.angle.pitch>=90&&(j.angle.pitch=89.999),j.angle.pitch<=-90&&(j.angle.pitch=-89.999),j.angle.yaw=0,e[d]=getAngleInView(a,k),e[d].pitch<-90?e[d].pitch=90:e[d].pitch>90&&(e[d].pitch=-90)}let c=e[0].yaw>e[3].yaw?3:0;return e[c].yaw>e[6].yaw&&(c=6),e[c].yaw>e[c+2].yaw&&(e[c+2].yaw+=360),e[c+2].yaw>e[c].yaw+180?(i.x=0,i.width=panorama_width):(i.x=(e[c].yaw/360-.5)*panorama_width,i.width=(e[c+2].yaw/360-.5)*panorama_width-i.x),i.y=(.5-e[e[0].pitch>e[1].pitch?0:1].pitch/180)*panorama_height,i.height=(.5-e[e[6].pitch>e[7].pitch?7:6].pitch/180)*panorama_height-i.y,i}function MaskSetToOne(a,i){const e=a/8,o=a%8;i.setUint8(e,i.getUint8(e)|1<<7-o)}function IsAll0(a){return a.getUint32(0)==0&&a.getUint32(4)==0}function getMaskFromTiles(a,i){const e=new DataView(i);a.forEach(function(o,s){MaskSetToOne(o,e)})}function operateForDataView(a,i,e,o){e.setUint32(0,o(a.getUint32(0),i.getUint32(0))),e.setUint32(4,o(a.getUint32(4),i.getUint32(4)))}function getTilesInView(a,i){const e=getRectangleInView(a),o=Math.floor(e.x/tile_width),s=Math.floor((e.x+e.width-1)/tile_width),c=Math.floor(e.y/tile_height),d=Math.floor((e.y+e.height-1)/tile_height);console.log({left:o,right:s,top:c,bottom:d});const b=[],k=panorama_height/tile_height;for(let j=o;j<=s;j++)for(let $=c;$<=d;$++)b.push(j*k+$);return console.log(b),getMaskFromTiles(b,i),b}var md5$1={exports:{}};(function(module){(function(){var ERROR="input is invalid type",WINDOW=typeof window=="object",root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&typeof self=="object",NODE_JS=!root.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;NODE_JS?root=commonjsGlobal:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&!0&&module.exports,ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer!="undefined",HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}(root.JS_MD5_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(a){return Object.prototype.toString.call(a)==="[object Array]"}),ARRAY_BUFFER&&(root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(a){return typeof a=="object"&&a.buffer&&a.buffer.constructor===ArrayBuffer});var createOutputMethod=function(a){return function(i,e){return new Md5(!0).update(i,e)[a]()}},createMethod=function(){var a=createOutputMethod("hex");NODE_JS&&(a=nodeWrap(a)),a.getCtx=a.create=function(){return new Md5},a.update=function(o){return a.create().update(o)};for(var i=0;i<OUTPUT_TYPES.length;++i){var e=OUTPUT_TYPES[i];a[e]=createOutputMethod(e)}return a},nodeWrap=function(method){var crypto=eval("require('crypto')"),Buffer=eval("require('buffer').Buffer"),nodeMethod=function(a){if(typeof a=="string")return crypto.createHash("md5").update(a,"utf8").digest("hex");if(a==null)throw ERROR;return a.constructor===ArrayBuffer&&(a=new Uint8Array(a)),Array.isArray(a)||ArrayBuffer.isView(a)||a.constructor===Buffer?crypto.createHash("md5").update(new Buffer(a)).digest("hex"):method(a)};return nodeMethod};function Md5(a){if(a)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var i=new ArrayBuffer(68);this.buffer8=new Uint8Array(i),this.blocks=new Uint32Array(i)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Md5.prototype.update=function(a,i){if(!this.finalized){for(var e,o=0,s,c=a.length,d=this.blocks,_=this.buffer8;o<c;){if(this.hashed&&(this.hashed=!1,d[0]=d[16],d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0),ARRAY_BUFFER)for(s=this.start;o<c&&s<64;++o)e=a.charCodeAt(o),i||e<128?_[s++]=e:e<2048?(_[s++]=192|e>>6,_[s++]=128|e&63):e<55296||e>=57344?(_[s++]=224|e>>12,_[s++]=128|e>>6&63,_[s++]=128|e&63):(e=65536+((e&1023)<<10|a.charCodeAt(++o)&1023),_[s++]=240|e>>18,_[s++]=128|e>>12&63,_[s++]=128|e>>6&63,_[s++]=128|e&63);else for(s=this.start;o<c&&s<64;++o)e=a.charCodeAt(o),i||e<128?d[s>>2]|=e<<SHIFT[s++&3]:e<2048?(d[s>>2]|=(192|e>>6)<<SHIFT[s++&3],d[s>>2]|=(128|e&63)<<SHIFT[s++&3]):e<55296||e>=57344?(d[s>>2]|=(224|e>>12)<<SHIFT[s++&3],d[s>>2]|=(128|e>>6&63)<<SHIFT[s++&3],d[s>>2]|=(128|e&63)<<SHIFT[s++&3]):(e=65536+((e&1023)<<10|a.charCodeAt(++o)&1023),d[s>>2]|=(240|e>>18)<<SHIFT[s++&3],d[s>>2]|=(128|e>>12&63)<<SHIFT[s++&3],d[s>>2]|=(128|e>>6&63)<<SHIFT[s++&3],d[s>>2]|=(128|e&63)<<SHIFT[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var a=this.blocks,i=this.lastByteIndex;a[i>>2]|=EXTRA[i&3],i>=56&&(this.hashed||this.hash(),a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),a[14]=this.bytes<<3,a[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var a,i,e,o,s,c,d=this.blocks;this.first?(a=d[0]-680876937,a=(a<<7|a>>>25)-271733879<<0,o=(-1732584194^a&2004318071)+d[1]-117830708,o=(o<<12|o>>>20)+a<<0,e=(-271733879^o&(a^-271733879))+d[2]-1126478375,e=(e<<17|e>>>15)+o<<0,i=(a^e&(o^a))+d[3]-1316259209,i=(i<<22|i>>>10)+e<<0):(a=this.h0,i=this.h1,e=this.h2,o=this.h3,a+=(o^i&(e^o))+d[0]-680876936,a=(a<<7|a>>>25)+i<<0,o+=(e^a&(i^e))+d[1]-389564586,o=(o<<12|o>>>20)+a<<0,e+=(i^o&(a^i))+d[2]+606105819,e=(e<<17|e>>>15)+o<<0,i+=(a^e&(o^a))+d[3]-1044525330,i=(i<<22|i>>>10)+e<<0),a+=(o^i&(e^o))+d[4]-176418897,a=(a<<7|a>>>25)+i<<0,o+=(e^a&(i^e))+d[5]+1200080426,o=(o<<12|o>>>20)+a<<0,e+=(i^o&(a^i))+d[6]-1473231341,e=(e<<17|e>>>15)+o<<0,i+=(a^e&(o^a))+d[7]-45705983,i=(i<<22|i>>>10)+e<<0,a+=(o^i&(e^o))+d[8]+1770035416,a=(a<<7|a>>>25)+i<<0,o+=(e^a&(i^e))+d[9]-1958414417,o=(o<<12|o>>>20)+a<<0,e+=(i^o&(a^i))+d[10]-42063,e=(e<<17|e>>>15)+o<<0,i+=(a^e&(o^a))+d[11]-1990404162,i=(i<<22|i>>>10)+e<<0,a+=(o^i&(e^o))+d[12]+1804603682,a=(a<<7|a>>>25)+i<<0,o+=(e^a&(i^e))+d[13]-40341101,o=(o<<12|o>>>20)+a<<0,e+=(i^o&(a^i))+d[14]-1502002290,e=(e<<17|e>>>15)+o<<0,i+=(a^e&(o^a))+d[15]+1236535329,i=(i<<22|i>>>10)+e<<0,a+=(e^o&(i^e))+d[1]-165796510,a=(a<<5|a>>>27)+i<<0,o+=(i^e&(a^i))+d[6]-1069501632,o=(o<<9|o>>>23)+a<<0,e+=(a^i&(o^a))+d[11]+643717713,e=(e<<14|e>>>18)+o<<0,i+=(o^a&(e^o))+d[0]-373897302,i=(i<<20|i>>>12)+e<<0,a+=(e^o&(i^e))+d[5]-701558691,a=(a<<5|a>>>27)+i<<0,o+=(i^e&(a^i))+d[10]+38016083,o=(o<<9|o>>>23)+a<<0,e+=(a^i&(o^a))+d[15]-660478335,e=(e<<14|e>>>18)+o<<0,i+=(o^a&(e^o))+d[4]-405537848,i=(i<<20|i>>>12)+e<<0,a+=(e^o&(i^e))+d[9]+568446438,a=(a<<5|a>>>27)+i<<0,o+=(i^e&(a^i))+d[14]-1019803690,o=(o<<9|o>>>23)+a<<0,e+=(a^i&(o^a))+d[3]-187363961,e=(e<<14|e>>>18)+o<<0,i+=(o^a&(e^o))+d[8]+1163531501,i=(i<<20|i>>>12)+e<<0,a+=(e^o&(i^e))+d[13]-1444681467,a=(a<<5|a>>>27)+i<<0,o+=(i^e&(a^i))+d[2]-51403784,o=(o<<9|o>>>23)+a<<0,e+=(a^i&(o^a))+d[7]+1735328473,e=(e<<14|e>>>18)+o<<0,i+=(o^a&(e^o))+d[12]-1926607734,i=(i<<20|i>>>12)+e<<0,s=i^e,a+=(s^o)+d[5]-378558,a=(a<<4|a>>>28)+i<<0,o+=(s^a)+d[8]-2022574463,o=(o<<11|o>>>21)+a<<0,c=o^a,e+=(c^i)+d[11]+1839030562,e=(e<<16|e>>>16)+o<<0,i+=(c^e)+d[14]-35309556,i=(i<<23|i>>>9)+e<<0,s=i^e,a+=(s^o)+d[1]-1530992060,a=(a<<4|a>>>28)+i<<0,o+=(s^a)+d[4]+1272893353,o=(o<<11|o>>>21)+a<<0,c=o^a,e+=(c^i)+d[7]-155497632,e=(e<<16|e>>>16)+o<<0,i+=(c^e)+d[10]-1094730640,i=(i<<23|i>>>9)+e<<0,s=i^e,a+=(s^o)+d[13]+681279174,a=(a<<4|a>>>28)+i<<0,o+=(s^a)+d[0]-358537222,o=(o<<11|o>>>21)+a<<0,c=o^a,e+=(c^i)+d[3]-722521979,e=(e<<16|e>>>16)+o<<0,i+=(c^e)+d[6]+76029189,i=(i<<23|i>>>9)+e<<0,s=i^e,a+=(s^o)+d[9]-640364487,a=(a<<4|a>>>28)+i<<0,o+=(s^a)+d[12]-421815835,o=(o<<11|o>>>21)+a<<0,c=o^a,e+=(c^i)+d[15]+530742520,e=(e<<16|e>>>16)+o<<0,i+=(c^e)+d[2]-995338651,i=(i<<23|i>>>9)+e<<0,a+=(e^(i|~o))+d[0]-198630844,a=(a<<6|a>>>26)+i<<0,o+=(i^(a|~e))+d[7]+1126891415,o=(o<<10|o>>>22)+a<<0,e+=(a^(o|~i))+d[14]-1416354905,e=(e<<15|e>>>17)+o<<0,i+=(o^(e|~a))+d[5]-57434055,i=(i<<21|i>>>11)+e<<0,a+=(e^(i|~o))+d[12]+1700485571,a=(a<<6|a>>>26)+i<<0,o+=(i^(a|~e))+d[3]-1894986606,o=(o<<10|o>>>22)+a<<0,e+=(a^(o|~i))+d[10]-1051523,e=(e<<15|e>>>17)+o<<0,i+=(o^(e|~a))+d[1]-2054922799,i=(i<<21|i>>>11)+e<<0,a+=(e^(i|~o))+d[8]+1873313359,a=(a<<6|a>>>26)+i<<0,o+=(i^(a|~e))+d[15]-30611744,o=(o<<10|o>>>22)+a<<0,e+=(a^(o|~i))+d[6]-1560198380,e=(e<<15|e>>>17)+o<<0,i+=(o^(e|~a))+d[13]+1309151649,i=(i<<21|i>>>11)+e<<0,a+=(e^(i|~o))+d[4]-145523070,a=(a<<6|a>>>26)+i<<0,o+=(i^(a|~e))+d[11]-1120210379,o=(o<<10|o>>>22)+a<<0,e+=(a^(o|~i))+d[2]+718787259,e=(e<<15|e>>>17)+o<<0,i+=(o^(e|~a))+d[9]-343485551,i=(i<<21|i>>>11)+e<<0,this.first?(this.h0=a+1732584193<<0,this.h1=i-271733879<<0,this.h2=e-1732584194<<0,this.h3=o+271733878<<0,this.first=!1):(this.h0=this.h0+a<<0,this.h1=this.h1+i<<0,this.h2=this.h2+e<<0,this.h3=this.h3+o<<0)},Md5.prototype.hex=function(){this.finalize();var a=this.h0,i=this.h1,e=this.h2,o=this.h3;return HEX_CHARS[a>>4&15]+HEX_CHARS[a&15]+HEX_CHARS[a>>12&15]+HEX_CHARS[a>>8&15]+HEX_CHARS[a>>20&15]+HEX_CHARS[a>>16&15]+HEX_CHARS[a>>28&15]+HEX_CHARS[a>>24&15]+HEX_CHARS[i>>4&15]+HEX_CHARS[i&15]+HEX_CHARS[i>>12&15]+HEX_CHARS[i>>8&15]+HEX_CHARS[i>>20&15]+HEX_CHARS[i>>16&15]+HEX_CHARS[i>>28&15]+HEX_CHARS[i>>24&15]+HEX_CHARS[e>>4&15]+HEX_CHARS[e&15]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[o>>4&15]+HEX_CHARS[o&15]+HEX_CHARS[o>>12&15]+HEX_CHARS[o>>8&15]+HEX_CHARS[o>>20&15]+HEX_CHARS[o>>16&15]+HEX_CHARS[o>>28&15]+HEX_CHARS[o>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(a){if(a==="hex")return this.hex();this.finalize();var i=this.h0,e=this.h1,o=this.h2,s=this.h3,c=[i&255,i>>8&255,i>>16&255,i>>24&255,e&255,e>>8&255,e>>16&255,e>>24&255,o&255,o>>8&255,o>>16&255,o>>24&255,s&255,s>>8&255,s>>16&255,s>>24&255];return c},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var a=new ArrayBuffer(16),i=new Uint32Array(a);return i[0]=this.h0,i[1]=this.h1,i[2]=this.h2,i[3]=this.h3,a},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var a,i,e,o="",s=this.array(),c=0;c<15;)a=s[c++],i=s[c++],e=s[c++],o+=BASE64_ENCODE_CHAR[a>>>2]+BASE64_ENCODE_CHAR[(a<<4|i>>>4)&63]+BASE64_ENCODE_CHAR[(i<<2|e>>>6)&63]+BASE64_ENCODE_CHAR[e&63];return a=s[c],o+=BASE64_ENCODE_CHAR[a>>>2]+BASE64_ENCODE_CHAR[a<<4&63]+"==",o};var exports=createMethod();COMMON_JS?module.exports=exports:root.md5=exports})()})(md5$1);var crypto={exports:{}};(function(a){var i=i||function(e,o){var s={},c=s.lib={},d=function(){},_=c.Base={extend:function(rt){d.prototype=this;var it=new d;return rt&&it.mixIn(rt),it.hasOwnProperty("init")||(it.init=function(){it.$super.init.apply(this,arguments)}),it.init.prototype=it,it.$super=this,it},create:function(){var rt=this.extend();return rt.init.apply(rt,arguments),rt},init:function(){},mixIn:function(rt){for(var it in rt)rt.hasOwnProperty(it)&&(this[it]=rt[it]);rt.hasOwnProperty("toString")&&(this.toString=rt.toString)},clone:function(){return this.init.prototype.extend(this)}},b=c.WordArray=_.extend({init:function(rt,it){rt=this.words=rt||[],this.sigBytes=it!=o?it:4*rt.length},toString:function(rt){return(rt||j).stringify(this)},concat:function(rt){var it=this.words,nt=rt.words,ot=this.sigBytes;if(rt=rt.sigBytes,this.clamp(),ot%4)for(var at=0;at<rt;at++)it[ot+at>>>2]|=(nt[at>>>2]>>>24-8*(at%4)&255)<<24-8*((ot+at)%4);else if(65535<nt.length)for(at=0;at<rt;at+=4)it[ot+at>>>2]=nt[at>>>2];else it.push.apply(it,nt);return this.sigBytes+=rt,this},clamp:function(){var rt=this.words,it=this.sigBytes;rt[it>>>2]&=4294967295<<32-8*(it%4),rt.length=e.ceil(it/4)},clone:function(){var rt=_.clone.call(this);return rt.words=this.words.slice(0),rt},random:function(rt){for(var it=[],nt=0;nt<rt;nt+=4)it.push(4294967296*e.random()|0);return new b.init(it,rt)}}),k=s.enc={},j=k.Hex={stringify:function(rt){var it=rt.words;rt=rt.sigBytes;for(var nt=[],ot=0;ot<rt;ot++){var at=it[ot>>>2]>>>24-8*(ot%4)&255;nt.push((at>>>4).toString(16)),nt.push((at&15).toString(16))}return nt.join("")},parse:function(rt){for(var it=rt.length,nt=[],ot=0;ot<it;ot+=2)nt[ot>>>3]|=parseInt(rt.substr(ot,2),16)<<24-4*(ot%8);return new b.init(nt,it/2)}},$=k.Latin1={stringify:function(rt){var it=rt.words;rt=rt.sigBytes;for(var nt=[],ot=0;ot<rt;ot++)nt.push(String.fromCharCode(it[ot>>>2]>>>24-8*(ot%4)&255));return nt.join("")},parse:function(rt){for(var it=rt.length,nt=[],ot=0;ot<it;ot++)nt[ot>>>2]|=(rt.charCodeAt(ot)&255)<<24-8*(ot%4);return new b.init(nt,it)}},_e=k.Utf8={stringify:function(rt){try{return decodeURIComponent(escape($.stringify(rt)))}catch{throw Error("Malformed UTF-8 data")}},parse:function(rt){return $.parse(unescape(encodeURIComponent(rt)))}},et=c.BufferedBlockAlgorithm=_.extend({reset:function(){this._data=new b.init,this._nDataBytes=0},_append:function(rt){typeof rt=="string"&&(rt=_e.parse(rt)),this._data.concat(rt),this._nDataBytes+=rt.sigBytes},_process:function(rt){var it=this._data,nt=it.words,ot=it.sigBytes,at=this.blockSize,st=ot/(4*at),st=rt?e.ceil(st):e.max((st|0)-this._minBufferSize,0);if(rt=st*at,ot=e.min(4*rt,ot),rt){for(var ut=0;ut<rt;ut+=at)this._doProcessBlock(nt,ut);ut=nt.splice(0,rt),it.sigBytes-=ot}return new b.init(ut,ot)},clone:function(){var rt=_.clone.call(this);return rt._data=this._data.clone(),rt},_minBufferSize:0});c.Hasher=et.extend({cfg:_.extend(),init:function(rt){this.cfg=this.cfg.extend(rt),this.reset()},reset:function(){et.reset.call(this),this._doReset()},update:function(rt){return this._append(rt),this._process(),this},finalize:function(rt){return rt&&this._append(rt),this._doFinalize()},blockSize:16,_createHelper:function(rt){return function(it,nt){return new rt.init(nt).finalize(it)}},_createHmacHelper:function(rt){return function(it,nt){return new tt.HMAC.init(rt,nt).finalize(it)}}});var tt=s.algo={};return s}(Math);(function(){var e=i,d=e.lib,o=d.WordArray,s=d.Hasher,c=[],d=e.algo.SHA1=s.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(_,b){for(var k=this._hash.words,j=k[0],$=k[1],_e=k[2],et=k[3],tt=k[4],rt=0;80>rt;rt++){if(16>rt)c[rt]=_[b+rt]|0;else{var it=c[rt-3]^c[rt-8]^c[rt-14]^c[rt-16];c[rt]=it<<1|it>>>31}it=(j<<5|j>>>27)+tt+c[rt],it=20>rt?it+(($&_e|~$&et)+1518500249):40>rt?it+(($^_e^et)+1859775393):60>rt?it+(($&_e|$&et|_e&et)-1894007588):it+(($^_e^et)-899497514),tt=et,et=_e,_e=$<<30|$>>>2,$=j,j=it}k[0]=k[0]+j|0,k[1]=k[1]+$|0,k[2]=k[2]+_e|0,k[3]=k[3]+et|0,k[4]=k[4]+tt|0},_doFinalize:function(){var _=this._data,b=_.words,k=8*this._nDataBytes,j=8*_.sigBytes;return b[j>>>5]|=128<<24-j%32,b[(j+64>>>9<<4)+14]=Math.floor(k/4294967296),b[(j+64>>>9<<4)+15]=k,_.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var _=s.clone.call(this);return _._hash=this._hash.clone(),_}});e.SHA1=s._createHelper(d),e.HmacSHA1=s._createHmacHelper(d)})(),function(){var e=i,o=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(s,c){s=this._hasher=new s.init,typeof c=="string"&&(c=o.parse(c));var d=s.blockSize,_=4*d;c.sigBytes>_&&(c=s.finalize(c)),c.clamp();for(var b=this._oKey=c.clone(),k=this._iKey=c.clone(),j=b.words,$=k.words,_e=0;_e<d;_e++)j[_e]^=1549556828,$[_e]^=909522486;b.sigBytes=k.sigBytes=_,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var c=this._hasher;return s=c.finalize(s),c.reset(),c.finalize(this._oKey.clone().concat(s))}})}(),function(){var e=i,o=e.lib,s=o.WordArray,c=e.enc;c.Base64={stringify:function(d){var _=d.words,b=d.sigBytes,k=this._map;d.clamp();for(var j=[],$=0;$<b;$+=3)for(var _e=_[$>>>2]>>>24-$%4*8&255,et=_[$+1>>>2]>>>24-($+1)%4*8&255,tt=_[$+2>>>2]>>>24-($+2)%4*8&255,rt=_e<<16|et<<8|tt,it=0;it<4&&$+it*.75<b;it++)j.push(k.charAt(rt>>>6*(3-it)&63));var nt=k.charAt(64);if(nt)for(;j.length%4;)j.push(nt);return j.join("")},parse:function(d){var _=d.length,b=this._map,k=b.charAt(64);if(k){var j=d.indexOf(k);j!=-1&&(_=j)}for(var $=[],_e=0,et=0;et<_;et++)if(et%4){var tt=b.indexOf(d.charAt(et-1))<<et%4*2,rt=b.indexOf(d.charAt(et))>>>6-et%4*2;$[_e>>>2]|=(tt|rt)<<24-_e%4*8,_e++}return s.create($,_e)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.exports=i})(crypto);var domParser={},sax={},nameStartChar=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,nameChar=new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),tagNamePattern=new RegExp("^"+nameStartChar.source+nameChar.source+"*(?::"+nameStartChar.source+nameChar.source+"*)?$"),S_TAG=0,S_ATTR=1,S_ATTR_SPACE=2,S_EQ=3,S_ATTR_NOQUOT_VALUE=4,S_ATTR_END=5,S_TAG_SPACE=6,S_TAG_CLOSE=7;function XMLReader$1(){}XMLReader$1.prototype={parse:function(a,i,e){var o=this.domBuilder;o.startDocument(),_copy(i,i={}),parse(a,i,e,o,this.errorHandler),o.endDocument()}};function parse(a,i,e,o,s){function c(St){if(St>65535){St-=65536;var At=55296+(St>>10),vt=56320+(St&1023);return String.fromCharCode(At,vt)}else return String.fromCharCode(St)}function d(St){var At=St.slice(1,-1);return At in e?e[At]:At.charAt(0)==="#"?c(parseInt(At.substr(1).replace("x","0x"))):(s.error("entity not found:"+St),St)}function _(St){if(St>rt){var At=a.substring(rt,St).replace(/&#?\w+;/g,d);_e&&b(rt),o.characters(At,0,St-rt),rt=St}}function b(St,At){for(;St>=j&&(At=$.exec(a));)k=At.index,j=k+At[0].length,_e.lineNumber++;_e.columnNumber=St-k+1}for(var k=0,j=0,$=/.*(?:\r\n?|\n)|.*$/g,_e=o.locator,et=[{currentNSMap:i}],tt={},rt=0;;){try{var it=a.indexOf("<",rt);if(it<0){if(!a.substr(rt).match(/^\s*$/)){var nt=o.doc,ot=nt.createTextNode(a.substr(rt));nt.appendChild(ot),o.currentElement=ot}return}switch(it>rt&&_(it),a.charAt(it+1)){case"/":var dt=a.indexOf(">",it+3),at=a.substring(it+2,dt),st=et.pop();dt<0?(at=a.substring(it+2).replace(/[\s<].*/,""),s.error("end tag name: "+at+" is not complete:"+st.tagName),dt=it+1+at.length):at.match(/\s</)&&(at=at.replace(/[\s<].*/,""),s.error("end tag name: "+at+" maybe not complete"),dt=it+1+at.length);var ut=st.localNSMap,ft=st.tagName==at,lt=ft||st.tagName&&st.tagName.toLowerCase()==at.toLowerCase();if(lt){if(o.endElement(st.uri,st.localName,at),ut)for(var ht in ut)o.endPrefixMapping(ht);ft||s.fatalError("end tag name: "+at+" is not match the current start tagName:"+st.tagName)}else et.push(st);dt++;break;case"?":_e&&b(it),dt=parseInstruction(a,it,o);break;case"!":_e&&b(it),dt=parseDCC(a,it,o,s);break;default:_e&&b(it);var pt=new ElementAttributes,mt=et[et.length-1].currentNSMap,dt=parseElementStartPart(a,it,pt,mt,d,s),gt=pt.length;if(!pt.closed&&fixSelfClosed(a,dt,pt.tagName,tt)&&(pt.closed=!0,e.nbsp||s.warning("unclosed xml attribute")),_e&&gt){for(var _t=copyLocator(_e,{}),yt=0;yt<gt;yt++){var Tt=pt[yt];b(Tt.offset),Tt.locator=copyLocator(_e,{})}o.locator=_t,appendElement$1(pt,o,mt)&&et.push(pt),o.locator=_e}else appendElement$1(pt,o,mt)&&et.push(pt);pt.uri==="http://www.w3.org/1999/xhtml"&&!pt.closed?dt=parseHtmlSpecialContent(a,dt,pt.tagName,d,o):dt++}}catch(St){s.error("element parse error: "+St),dt=-1}dt>rt?rt=dt:_(Math.max(it,rt)+1)}}function copyLocator(a,i){return i.lineNumber=a.lineNumber,i.columnNumber=a.columnNumber,i}function parseElementStartPart(a,i,e,o,s,c){for(var d,_,b=++i,k=S_TAG;;){var j=a.charAt(b);switch(j){case"=":if(k===S_ATTR)d=a.slice(i,b),k=S_EQ;else if(k===S_ATTR_SPACE)k=S_EQ;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(k===S_EQ||k===S_ATTR)if(k===S_ATTR&&(c.warning('attribute value must after "="'),d=a.slice(i,b)),i=b+1,b=a.indexOf(j,i),b>0)_=a.slice(i,b).replace(/&#?\w+;/g,s),e.add(d,_,i-1),k=S_ATTR_END;else throw new Error("attribute value no end '"+j+"' match");else if(k==S_ATTR_NOQUOT_VALUE)_=a.slice(i,b).replace(/&#?\w+;/g,s),e.add(d,_,i),c.warning('attribute "'+d+'" missed start quot('+j+")!!"),i=b+1,k=S_ATTR_END;else throw new Error('attribute value must after "="');break;case"/":switch(k){case S_TAG:e.setTagName(a.slice(i,b));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:k=S_TAG_CLOSE,e.closed=!0;case S_ATTR_NOQUOT_VALUE:case S_ATTR:case S_ATTR_SPACE:break;default:throw new Error("attribute invalid close char('/')")}break;case"":return c.error("unexpected end of input"),k==S_TAG&&e.setTagName(a.slice(i,b)),b;case">":switch(k){case S_TAG:e.setTagName(a.slice(i,b));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:break;case S_ATTR_NOQUOT_VALUE:case S_ATTR:_=a.slice(i,b),_.slice(-1)==="/"&&(e.closed=!0,_=_.slice(0,-1));case S_ATTR_SPACE:k===S_ATTR_SPACE&&(_=d),k==S_ATTR_NOQUOT_VALUE?(c.warning('attribute "'+_+'" missed quot(")!!'),e.add(d,_.replace(/&#?\w+;/g,s),i)):((o[""]!=="http://www.w3.org/1999/xhtml"||!_.match(/^(?:disabled|checked|selected)$/i))&&c.warning('attribute "'+_+'" missed value!! "'+_+'" instead!!'),e.add(_,_,i));break;case S_EQ:throw new Error("attribute value missed!!")}return b;case"\x80":j=" ";default:if(j<=" ")switch(k){case S_TAG:e.setTagName(a.slice(i,b)),k=S_TAG_SPACE;break;case S_ATTR:d=a.slice(i,b),k=S_ATTR_SPACE;break;case S_ATTR_NOQUOT_VALUE:var _=a.slice(i,b).replace(/&#?\w+;/g,s);c.warning('attribute "'+_+'" missed quot(")!!'),e.add(d,_,i);case S_ATTR_END:k=S_TAG_SPACE;break}else switch(k){case S_ATTR_SPACE:e.tagName,(o[""]!=="http://www.w3.org/1999/xhtml"||!d.match(/^(?:disabled|checked|selected)$/i))&&c.warning('attribute "'+d+'" missed value!! "'+d+'" instead2!!'),e.add(d,d,i),i=b,k=S_ATTR;break;case S_ATTR_END:c.warning('attribute space is required"'+d+'"!!');case S_TAG_SPACE:k=S_ATTR,i=b;break;case S_EQ:k=S_ATTR_NOQUOT_VALUE,i=b;break;case S_TAG_CLOSE:throw new Error("elements closed character '/' and '>' must be connected to")}}b++}}function appendElement$1(a,i,e){for(var o=a.tagName,s=null,$=a.length;$--;){var c=a[$],d=c.qName,_=c.value,_e=d.indexOf(":");if(_e>0)var b=c.prefix=d.slice(0,_e),k=d.slice(_e+1),j=b==="xmlns"&&k;else k=d,b=null,j=d==="xmlns"&&"";c.localName=k,j!==!1&&(s==null&&(s={},_copy(e,e={})),e[j]=s[j]=_,c.uri="http://www.w3.org/2000/xmlns/",i.startPrefixMapping(j,_))}for(var $=a.length;$--;){c=a[$];var b=c.prefix;b&&(b==="xml"&&(c.uri="http://www.w3.org/XML/1998/namespace"),b!=="xmlns"&&(c.uri=e[b||""]))}var _e=o.indexOf(":");_e>0?(b=a.prefix=o.slice(0,_e),k=a.localName=o.slice(_e+1)):(b=null,k=a.localName=o);var et=a.uri=e[b||""];if(i.startElement(et,k,o,a),a.closed){if(i.endElement(et,k,o),s)for(b in s)i.endPrefixMapping(b)}else return a.currentNSMap=e,a.localNSMap=s,!0}function parseHtmlSpecialContent(a,i,e,o,s){if(/^(?:script|textarea)$/i.test(e)){var c=a.indexOf("</"+e+">",i),d=a.substring(i+1,c);if(/[&<]/.test(d))return/^script$/i.test(e)?(s.characters(d,0,d.length),c):(d=d.replace(/&#?\w+;/g,o),s.characters(d,0,d.length),c)}return i+1}function fixSelfClosed(a,i,e,o){var s=o[e];return s==null&&(s=a.lastIndexOf("</"+e+">"),s<i&&(s=a.lastIndexOf("</"+e)),o[e]=s),s<i}function _copy(a,i){for(var e in a)i[e]=a[e]}function parseDCC(a,i,e,o){var s=a.charAt(i+2);switch(s){case"-":if(a.charAt(i+3)==="-"){var c=a.indexOf("-->",i+4);return c>i?(e.comment(a,i+4,c-i-4),c+3):(o.error("Unclosed comment"),-1)}else return-1;default:if(a.substr(i+3,6)=="CDATA["){var c=a.indexOf("]]>",i+9);return e.startCDATA(),e.characters(a,i+9,c-i-9),e.endCDATA(),c+3}var d=split(a,i),_=d.length;if(_>1&&/!doctype/i.test(d[0][0])){var b=d[1][0],k=_>3&&/^public$/i.test(d[2][0])&&d[3][0],j=_>4&&d[4][0],$=d[_-1];return e.startDTD(b,k&&k.replace(/^(['"])(.*?)\1$/,"$2"),j&&j.replace(/^(['"])(.*?)\1$/,"$2")),e.endDTD(),$.index+$[0].length}}return-1}function parseInstruction(a,i,e){var o=a.indexOf("?>",i);if(o){var s=a.substring(i,o).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return s?(s[0].length,e.processingInstruction(s[1],s[2]),o+2):-1}return-1}function ElementAttributes(a){}ElementAttributes.prototype={setTagName:function(a){if(!tagNamePattern.test(a))throw new Error("invalid tagName:"+a);this.tagName=a},add:function(a,i,e){if(!tagNamePattern.test(a))throw new Error("invalid attribute:"+a);this[this.length++]={qName:a,value:i,offset:e}},length:0,getLocalName:function(a){return this[a].localName},getLocator:function(a){return this[a].locator},getQName:function(a){return this[a].qName},getURI:function(a){return this[a].uri},getValue:function(a){return this[a].value}};function _set_proto_(a,i){return a.__proto__=i,a}_set_proto_({},_set_proto_.prototype)instanceof _set_proto_||(_set_proto_=function(a,i){function e(){}e.prototype=i,e=new e;for(i in a)e[i]=a[i];return e});function split(a,i){var e,o=[],s=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(s.lastIndex=i,s.exec(a);e=s.exec(a);)if(o.push(e),e[1])return o}sax.XMLReader=XMLReader$1;var dom={};function copy(a,i){for(var e in a)i[e]=a[e]}function _extends(a,i){var e=a.prototype;if(Object.create){var o=Object.create(i.prototype);e.__proto__=o}if(!(e instanceof i)){let c=function(){};var s=c;c.prototype=i.prototype,c=new c,copy(e,c),a.prototype=e=c}e.constructor!=a&&(typeof a!="function"&&console.error("unknow Class:"+a),e.constructor=a)}var htmlns="http://www.w3.org/1999/xhtml",NodeType={},ELEMENT_NODE=NodeType.ELEMENT_NODE=1,ATTRIBUTE_NODE=NodeType.ATTRIBUTE_NODE=2,TEXT_NODE=NodeType.TEXT_NODE=3,CDATA_SECTION_NODE=NodeType.CDATA_SECTION_NODE=4,ENTITY_REFERENCE_NODE=NodeType.ENTITY_REFERENCE_NODE=5,ENTITY_NODE=NodeType.ENTITY_NODE=6,PROCESSING_INSTRUCTION_NODE=NodeType.PROCESSING_INSTRUCTION_NODE=7,COMMENT_NODE=NodeType.COMMENT_NODE=8,DOCUMENT_NODE=NodeType.DOCUMENT_NODE=9,DOCUMENT_TYPE_NODE=NodeType.DOCUMENT_TYPE_NODE=10,DOCUMENT_FRAGMENT_NODE=NodeType.DOCUMENT_FRAGMENT_NODE=11,NOTATION_NODE=NodeType.NOTATION_NODE=12,ExceptionCode={},ExceptionMessage={};ExceptionCode.INDEX_SIZE_ERR=(ExceptionMessage[1]="Index size error",1);ExceptionCode.DOMSTRING_SIZE_ERR=(ExceptionMessage[2]="DOMString size error",2);var HIERARCHY_REQUEST_ERR=ExceptionCode.HIERARCHY_REQUEST_ERR=(ExceptionMessage[3]="Hierarchy request error",3);ExceptionCode.WRONG_DOCUMENT_ERR=(ExceptionMessage[4]="Wrong document",4);ExceptionCode.INVALID_CHARACTER_ERR=(ExceptionMessage[5]="Invalid character",5);ExceptionCode.NO_DATA_ALLOWED_ERR=(ExceptionMessage[6]="No data allowed",6);ExceptionCode.NO_MODIFICATION_ALLOWED_ERR=(ExceptionMessage[7]="No modification allowed",7);var NOT_FOUND_ERR=ExceptionCode.NOT_FOUND_ERR=(ExceptionMessage[8]="Not found",8);ExceptionCode.NOT_SUPPORTED_ERR=(ExceptionMessage[9]="Not supported",9);var INUSE_ATTRIBUTE_ERR=ExceptionCode.INUSE_ATTRIBUTE_ERR=(ExceptionMessage[10]="Attribute in use",10);ExceptionCode.INVALID_STATE_ERR=(ExceptionMessage[11]="Invalid state",11);ExceptionCode.SYNTAX_ERR=(ExceptionMessage[12]="Syntax error",12);ExceptionCode.INVALID_MODIFICATION_ERR=(ExceptionMessage[13]="Invalid modification",13);ExceptionCode.NAMESPACE_ERR=(ExceptionMessage[14]="Invalid namespace",14);ExceptionCode.INVALID_ACCESS_ERR=(ExceptionMessage[15]="Invalid access",15);function DOMException$1(a,i){if(i instanceof Error)var e=i;else e=this,Error.call(this,ExceptionMessage[a]),this.message=ExceptionMessage[a],Error.captureStackTrace&&Error.captureStackTrace(this,DOMException$1);return e.code=a,i&&(this.message=this.message+": "+i),e}DOMException$1.prototype=Error.prototype;copy(ExceptionCode,DOMException$1);function NodeList(){}NodeList.prototype={length:0,item:function(a){return this[a]||null},toString:function(a,i){for(var e=[],o=0;o<this.length;o++)serializeToString(this[o],e,a,i);return e.join("")}};function LiveNodeList(a,i){this._node=a,this._refresh=i,_updateLiveList(this)}function _updateLiveList(a){var i=a._node._inc||a._node.ownerDocument._inc;if(a._inc!=i){var e=a._refresh(a._node);__set__(a,"length",e.length),copy(e,a),a._inc=i}}LiveNodeList.prototype.item=function(a){return _updateLiveList(this),this[a]};_extends(LiveNodeList,NodeList);function NamedNodeMap(){}function _findNodeIndex(a,i){for(var e=a.length;e--;)if(a[e]===i)return e}function _addNamedNode(a,i,e,o){if(o?i[_findNodeIndex(i,o)]=e:i[i.length++]=e,a){e.ownerElement=a;var s=a.ownerDocument;s&&(o&&_onRemoveAttribute(s,a,o),_onAddAttribute(s,a,e))}}function _removeNamedNode(a,i,e){var o=_findNodeIndex(i,e);if(o>=0){for(var s=i.length-1;o<s;)i[o]=i[++o];if(i.length=s,a){var c=a.ownerDocument;c&&(_onRemoveAttribute(c,a,e),e.ownerElement=null)}}else throw DOMException$1(NOT_FOUND_ERR,new Error(a.tagName+"@"+e))}NamedNodeMap.prototype={length:0,item:NodeList.prototype.item,getNamedItem:function(a){for(var i=this.length;i--;){var e=this[i];if(e.nodeName==a)return e}},setNamedItem:function(a){var i=a.ownerElement;if(i&&i!=this._ownerElement)throw new DOMException$1(INUSE_ATTRIBUTE_ERR);var e=this.getNamedItem(a.nodeName);return _addNamedNode(this._ownerElement,this,a,e),e},setNamedItemNS:function(a){var i=a.ownerElement,e;if(i&&i!=this._ownerElement)throw new DOMException$1(INUSE_ATTRIBUTE_ERR);return e=this.getNamedItemNS(a.namespaceURI,a.localName),_addNamedNode(this._ownerElement,this,a,e),e},removeNamedItem:function(a){var i=this.getNamedItem(a);return _removeNamedNode(this._ownerElement,this,i),i},removeNamedItemNS:function(a,i){var e=this.getNamedItemNS(a,i);return _removeNamedNode(this._ownerElement,this,e),e},getNamedItemNS:function(a,i){for(var e=this.length;e--;){var o=this[e];if(o.localName==i&&o.namespaceURI==a)return o}return null}};function DOMImplementation$1(a){if(this._features={},a)for(var i in a)this._features=a[i]}DOMImplementation$1.prototype={hasFeature:function(a,i){var e=this._features[a.toLowerCase()];return!!(e&&(!i||i in e))},createDocument:function(a,i,e){var o=new Document;if(o.implementation=this,o.childNodes=new NodeList,o.doctype=e,e&&o.appendChild(e),i){var s=o.createElementNS(a,i);o.appendChild(s)}return o},createDocumentType:function(a,i,e){var o=new DocumentType;return o.name=a,o.nodeName=a,o.publicId=i,o.systemId=e,o}};function Node$1(){}Node$1.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(a,i){return _insertBefore(this,a,i)},replaceChild:function(a,i){this.insertBefore(a,i),i&&this.removeChild(i)},removeChild:function(a){return _removeChild(this,a)},appendChild:function(a){return this.insertBefore(a,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(a){return cloneNode(this.ownerDocument||this,this,a)},normalize:function(){for(var a=this.firstChild;a;){var i=a.nextSibling;i&&i.nodeType==TEXT_NODE&&a.nodeType==TEXT_NODE?(this.removeChild(i),a.appendData(i.data)):(a.normalize(),a=i)}},isSupported:function(a,i){return this.ownerDocument.implementation.hasFeature(a,i)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(a){for(var i=this;i;){var e=i._nsMap;if(e){for(var o in e)if(e[o]==a)return o}i=i.nodeType==ATTRIBUTE_NODE?i.ownerDocument:i.parentNode}return null},lookupNamespaceURI:function(a){for(var i=this;i;){var e=i._nsMap;if(e&&a in e)return e[a];i=i.nodeType==ATTRIBUTE_NODE?i.ownerDocument:i.parentNode}return null},isDefaultNamespace:function(a){var i=this.lookupPrefix(a);return i==null}};function _xmlEncoder(a){return a=="<"&&"&lt;"||a==">"&&"&gt;"||a=="&"&&"&amp;"||a=='"'&&"&quot;"||"&#"+a.charCodeAt()+";"}copy(NodeType,Node$1);copy(NodeType,Node$1.prototype);function _visitNode(a,i){if(i(a))return!0;if(a=a.firstChild)do if(_visitNode(a,i))return!0;while(a=a.nextSibling)}function Document(){}function _onAddAttribute(a,i,e){a&&a._inc++;var o=e.namespaceURI;o=="http://www.w3.org/2000/xmlns/"&&(i._nsMap[e.prefix?e.localName:""]=e.value)}function _onRemoveAttribute(a,i,e,o){a&&a._inc++;var s=e.namespaceURI;s=="http://www.w3.org/2000/xmlns/"&&delete i._nsMap[e.prefix?e.localName:""]}function _onUpdateChild(a,i,e){if(a&&a._inc){a._inc++;var o=i.childNodes;if(e)o[o.length++]=e;else{for(var s=i.firstChild,c=0;s;)o[c++]=s,s=s.nextSibling;o.length=c}}}function _removeChild(a,i){var e=i.previousSibling,o=i.nextSibling;return e?e.nextSibling=o:a.firstChild=o,o?o.previousSibling=e:a.lastChild=e,_onUpdateChild(a.ownerDocument,a),i}function _insertBefore(a,i,e){var o=i.parentNode;if(o&&o.removeChild(i),i.nodeType===DOCUMENT_FRAGMENT_NODE){var s=i.firstChild;if(s==null)return i;var c=i.lastChild}else s=c=i;var d=e?e.previousSibling:a.lastChild;s.previousSibling=d,c.nextSibling=e,d?d.nextSibling=s:a.firstChild=s,e==null?a.lastChild=c:e.previousSibling=c;do s.parentNode=a;while(s!==c&&(s=s.nextSibling));return _onUpdateChild(a.ownerDocument||a,a),i.nodeType==DOCUMENT_FRAGMENT_NODE&&(i.firstChild=i.lastChild=null),i}function _appendSingleChild(a,i){var e=i.parentNode;if(e){var o=a.lastChild;e.removeChild(i);var o=a.lastChild}var o=a.lastChild;return i.parentNode=a,i.previousSibling=o,i.nextSibling=null,o?o.nextSibling=i:a.firstChild=i,a.lastChild=i,_onUpdateChild(a.ownerDocument,a,i),i}Document.prototype={nodeName:"#document",nodeType:DOCUMENT_NODE,doctype:null,documentElement:null,_inc:1,insertBefore:function(a,i){if(a.nodeType==DOCUMENT_FRAGMENT_NODE){for(var e=a.firstChild;e;){var o=e.nextSibling;this.insertBefore(e,i),e=o}return a}return this.documentElement==null&&a.nodeType==ELEMENT_NODE&&(this.documentElement=a),_insertBefore(this,a,i),a.ownerDocument=this,a},removeChild:function(a){return this.documentElement==a&&(this.documentElement=null),_removeChild(this,a)},importNode:function(a,i){return importNode(this,a,i)},getElementById:function(a){var i=null;return _visitNode(this.documentElement,function(e){if(e.nodeType==ELEMENT_NODE&&e.getAttribute("id")==a)return i=e,!0}),i},createElement:function(a){var i=new Element;i.ownerDocument=this,i.nodeName=a,i.tagName=a,i.childNodes=new NodeList;var e=i.attributes=new NamedNodeMap;return e._ownerElement=i,i},createDocumentFragment:function(){var a=new DocumentFragment;return a.ownerDocument=this,a.childNodes=new NodeList,a},createTextNode:function(a){var i=new Text;return i.ownerDocument=this,i.appendData(a),i},createComment:function(a){var i=new Comment;return i.ownerDocument=this,i.appendData(a),i},createCDATASection:function(a){var i=new CDATASection;return i.ownerDocument=this,i.appendData(a),i},createProcessingInstruction:function(a,i){var e=new ProcessingInstruction;return e.ownerDocument=this,e.tagName=e.target=a,e.nodeValue=e.data=i,e},createAttribute:function(a){var i=new Attr;return i.ownerDocument=this,i.name=a,i.nodeName=a,i.localName=a,i.specified=!0,i},createEntityReference:function(a){var i=new EntityReference;return i.ownerDocument=this,i.nodeName=a,i},createElementNS:function(a,i){var e=new Element,o=i.split(":"),s=e.attributes=new NamedNodeMap;return e.childNodes=new NodeList,e.ownerDocument=this,e.nodeName=i,e.tagName=i,e.namespaceURI=a,o.length==2?(e.prefix=o[0],e.localName=o[1]):e.localName=i,s._ownerElement=e,e},createAttributeNS:function(a,i){var e=new Attr,o=i.split(":");return e.ownerDocument=this,e.nodeName=i,e.name=i,e.namespaceURI=a,e.specified=!0,o.length==2?(e.prefix=o[0],e.localName=o[1]):e.localName=i,e}};_extends(Document,Node$1);function Element(){this._nsMap={}}Element.prototype={nodeType:ELEMENT_NODE,hasAttribute:function(a){return this.getAttributeNode(a)!=null},getAttribute:function(a){var i=this.getAttributeNode(a);return i&&i.value||""},getAttributeNode:function(a){return this.attributes.getNamedItem(a)},setAttribute:function(a,i){var e=this.ownerDocument.createAttribute(a);e.value=e.nodeValue=""+i,this.setAttributeNode(e)},removeAttribute:function(a){var i=this.getAttributeNode(a);i&&this.removeAttributeNode(i)},appendChild:function(a){return a.nodeType===DOCUMENT_FRAGMENT_NODE?this.insertBefore(a,null):_appendSingleChild(this,a)},setAttributeNode:function(a){return this.attributes.setNamedItem(a)},setAttributeNodeNS:function(a){return this.attributes.setNamedItemNS(a)},removeAttributeNode:function(a){return this.attributes.removeNamedItem(a.nodeName)},removeAttributeNS:function(a,i){var e=this.getAttributeNodeNS(a,i);e&&this.removeAttributeNode(e)},hasAttributeNS:function(a,i){return this.getAttributeNodeNS(a,i)!=null},getAttributeNS:function(a,i){var e=this.getAttributeNodeNS(a,i);return e&&e.value||""},setAttributeNS:function(a,i,e){var o=this.ownerDocument.createAttributeNS(a,i);o.value=o.nodeValue=""+e,this.setAttributeNode(o)},getAttributeNodeNS:function(a,i){return this.attributes.getNamedItemNS(a,i)},getElementsByTagName:function(a){return new LiveNodeList(this,function(i){var e=[];return _visitNode(i,function(o){o!==i&&o.nodeType==ELEMENT_NODE&&(a==="*"||o.tagName==a)&&e.push(o)}),e})},getElementsByTagNameNS:function(a,i){return new LiveNodeList(this,function(e){var o=[];return _visitNode(e,function(s){s!==e&&s.nodeType===ELEMENT_NODE&&(a==="*"||s.namespaceURI===a)&&(i==="*"||s.localName==i)&&o.push(s)}),o})}};Document.prototype.getElementsByTagName=Element.prototype.getElementsByTagName;Document.prototype.getElementsByTagNameNS=Element.prototype.getElementsByTagNameNS;_extends(Element,Node$1);function Attr(){}Attr.prototype.nodeType=ATTRIBUTE_NODE;_extends(Attr,Node$1);function CharacterData(){}CharacterData.prototype={data:"",substringData:function(a,i){return this.data.substring(a,a+i)},appendData:function(a){a=this.data+a,this.nodeValue=this.data=a,this.length=a.length},insertData:function(a,i){this.replaceData(a,0,i)},appendChild:function(a){throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])},deleteData:function(a,i){this.replaceData(a,i,"")},replaceData:function(a,i,e){var o=this.data.substring(0,a),s=this.data.substring(a+i);e=o+e+s,this.nodeValue=this.data=e,this.length=e.length}};_extends(CharacterData,Node$1);function Text(){}Text.prototype={nodeName:"#text",nodeType:TEXT_NODE,splitText:function(a){var i=this.data,e=i.substring(a);i=i.substring(0,a),this.data=this.nodeValue=i,this.length=i.length;var o=this.ownerDocument.createTextNode(e);return this.parentNode&&this.parentNode.insertBefore(o,this.nextSibling),o}};_extends(Text,CharacterData);function Comment(){}Comment.prototype={nodeName:"#comment",nodeType:COMMENT_NODE};_extends(Comment,CharacterData);function CDATASection(){}CDATASection.prototype={nodeName:"#cdata-section",nodeType:CDATA_SECTION_NODE};_extends(CDATASection,CharacterData);function DocumentType(){}DocumentType.prototype.nodeType=DOCUMENT_TYPE_NODE;_extends(DocumentType,Node$1);function Notation(){}Notation.prototype.nodeType=NOTATION_NODE;_extends(Notation,Node$1);function Entity(){}Entity.prototype.nodeType=ENTITY_NODE;_extends(Entity,Node$1);function EntityReference(){}EntityReference.prototype.nodeType=ENTITY_REFERENCE_NODE;_extends(EntityReference,Node$1);function DocumentFragment(){}DocumentFragment.prototype.nodeName="#document-fragment";DocumentFragment.prototype.nodeType=DOCUMENT_FRAGMENT_NODE;_extends(DocumentFragment,Node$1);function ProcessingInstruction(){}ProcessingInstruction.prototype.nodeType=PROCESSING_INSTRUCTION_NODE;_extends(ProcessingInstruction,Node$1);function XMLSerializer$1(){}XMLSerializer$1.prototype.serializeToString=function(a,i,e){return nodeSerializeToString.call(a,i,e)};Node$1.prototype.toString=nodeSerializeToString;function nodeSerializeToString(a,i){var e=[],o=this.nodeType==9?this.documentElement:this,s=o.prefix,c=o.namespaceURI;if(c&&s==null){var s=o.lookupPrefix(c);if(s==null)var d=[{namespace:c,prefix:null}]}return serializeToString(this,e,a,i,d),e.join("")}function needNamespaceDefine(a,i,e){var o=a.prefix||"",s=a.namespaceURI;if(!o&&!s||o==="xml"&&s==="http://www.w3.org/XML/1998/namespace"||s=="http://www.w3.org/2000/xmlns/")return!1;for(var c=e.length;c--;){var d=e[c];if(d.prefix==o)return d.namespace!=s}return!0}function serializeToString(a,i,e,o,s){if(o)if(a=o(a),a){if(typeof a=="string"){i.push(a);return}}else return;switch(a.nodeType){case ELEMENT_NODE:s||(s=[]),s.length;var c=a.attributes,d=c.length,et=a.firstChild,_=a.tagName;e=htmlns===a.namespaceURI||e,i.push("<",_);for(var b=0;b<d;b++){var k=c.item(b);k.prefix=="xmlns"?s.push({prefix:k.localName,namespace:k.value}):k.nodeName=="xmlns"&&s.push({prefix:"",namespace:k.value})}for(var b=0;b<d;b++){var k=c.item(b);if(needNamespaceDefine(k,e,s)){var j=k.prefix||"",$=k.namespaceURI,_e=j?" xmlns:"+j:" xmlns";i.push(_e,'="',$,'"'),s.push({prefix:j,namespace:$})}serializeToString(k,i,e,o,s)}if(needNamespaceDefine(a,e,s)){var j=a.prefix||"",$=a.namespaceURI,_e=j?" xmlns:"+j:" xmlns";i.push(_e,'="',$,'"'),s.push({prefix:j,namespace:$})}if(et||e&&!/^(?:meta|link|img|br|hr|input)$/i.test(_)){if(i.push(">"),e&&/^script$/i.test(_))for(;et;)et.data?i.push(et.data):serializeToString(et,i,e,o,s),et=et.nextSibling;else for(;et;)serializeToString(et,i,e,o,s),et=et.nextSibling;i.push("</",_,">")}else i.push("/>");return;case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(var et=a.firstChild;et;)serializeToString(et,i,e,o,s),et=et.nextSibling;return;case ATTRIBUTE_NODE:return i.push(" ",a.name,'="',a.value.replace(/[<&"]/g,_xmlEncoder),'"');case TEXT_NODE:return i.push(a.data.replace(/[<&]/g,_xmlEncoder));case CDATA_SECTION_NODE:return i.push("<![CDATA[",a.data,"]]>");case COMMENT_NODE:return i.push("<!--",a.data,"-->");case DOCUMENT_TYPE_NODE:var tt=a.publicId,rt=a.systemId;if(i.push("<!DOCTYPE ",a.name),tt)i.push(' PUBLIC "',tt),rt&&rt!="."&&i.push('" "',rt),i.push('">');else if(rt&&rt!=".")i.push(' SYSTEM "',rt,'">');else{var it=a.internalSubset;it&&i.push(" [",it,"]"),i.push(">")}return;case PROCESSING_INSTRUCTION_NODE:return i.push("<?",a.target," ",a.data,"?>");case ENTITY_REFERENCE_NODE:return i.push("&",a.nodeName,";");default:i.push("??",a.nodeName)}}function importNode(a,i,e){var o;switch(i.nodeType){case ELEMENT_NODE:o=i.cloneNode(!1),o.ownerDocument=a;case DOCUMENT_FRAGMENT_NODE:break;case ATTRIBUTE_NODE:e=!0;break}if(o||(o=i.cloneNode(!1)),o.ownerDocument=a,o.parentNode=null,e)for(var s=i.firstChild;s;)o.appendChild(importNode(a,s,e)),s=s.nextSibling;return o}function cloneNode(a,i,e){var o=new i.constructor;for(var s in i){var c=i[s];typeof c!="object"&&c!=o[s]&&(o[s]=c)}switch(i.childNodes&&(o.childNodes=new NodeList),o.ownerDocument=a,o.nodeType){case ELEMENT_NODE:var d=i.attributes,_=o.attributes=new NamedNodeMap,b=d.length;_._ownerElement=o;for(var k=0;k<b;k++)o.setAttributeNode(cloneNode(a,d.item(k),!0));break;case ATTRIBUTE_NODE:e=!0}if(e)for(var j=i.firstChild;j;)o.appendChild(cloneNode(a,j,e)),j=j.nextSibling;return o}function __set__(a,i,e){a[i]=e}try{if(Object.defineProperty){let a=function(i){switch(i.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:var e=[];for(i=i.firstChild;i;)i.nodeType!==7&&i.nodeType!==8&&e.push(a(i)),i=i.nextSibling;return e.join("");default:return i.nodeValue}};var getTextContent=a;Object.defineProperty(LiveNodeList.prototype,"length",{get:function(){return _updateLiveList(this),this.$$length}}),Object.defineProperty(Node$1.prototype,"textContent",{get:function(){return a(this)},set:function(i){switch(this.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(;this.firstChild;)this.removeChild(this.firstChild);(i||String(i))&&this.appendChild(this.ownerDocument.createTextNode(i));break;default:this.data=i,this.value=i,this.nodeValue=i}}}),__set__=function(i,e,o){i["$$"+e]=o}}}catch(a){}dom.DOMImplementation=DOMImplementation$1;dom.XMLSerializer=XMLSerializer$1;function DOMParser$1(a){this.options=a||{locator:{}}}DOMParser$1.prototype.parseFromString=function(a,i){var e=this.options,o=new XMLReader,s=e.domBuilder||new DOMHandler,c=e.errorHandler,d=e.locator,_=e.xmlns||{},b={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};return d&&s.setDocumentLocator(d),o.errorHandler=buildErrorHandler(c,s,d),o.domBuilder=e.domBuilder||s,/\/x?html?$/.test(i)&&(b.nbsp="\xA0",b.copy="\xA9",_[""]="http://www.w3.org/1999/xhtml"),_.xml=_.xml||"http://www.w3.org/XML/1998/namespace",a?o.parse(a,_,b):o.errorHandler.error("invalid doc source"),s.doc};function buildErrorHandler(a,i,e){if(!a){if(i instanceof DOMHandler)return i;a=i}var o={},s=a instanceof Function;e=e||{};function c(d){var _=a[d];!_&&s&&(_=a.length==2?function(b){a(d,b)}:a),o[d]=_&&function(b){_("[xmldom "+d+"] "+b+_locator(e))}||function(){}}return c("warning"),c("error"),c("fatalError"),o}function DOMHandler(){this.cdata=!1}function position(a,i){i.lineNumber=a.lineNumber,i.columnNumber=a.columnNumber}DOMHandler.prototype={startDocument:function(){this.doc=new DOMImplementation().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(a,i,e,o){var s=this.doc,c=s.createElementNS(a,e||i),d=o.length;appendElement(this,c),this.currentElement=c,this.locator&&position(this.locator,c);for(var _=0;_<d;_++){var a=o.getURI(_),b=o.getValue(_),e=o.getQName(_),k=s.createAttributeNS(a,e);this.locator&&position(o.getLocator(_),k),k.value=k.nodeValue=b,c.setAttributeNode(k)}},endElement:function(a,i,e){var o=this.currentElement;o.tagName,this.currentElement=o.parentNode},startPrefixMapping:function(a,i){},endPrefixMapping:function(a){},processingInstruction:function(a,i){var e=this.doc.createProcessingInstruction(a,i);this.locator&&position(this.locator,e),appendElement(this,e)},ignorableWhitespace:function(a,i,e){},characters:function(a,i,e){if(a=_toString.apply(this,arguments),a){if(this.cdata)var o=this.doc.createCDATASection(a);else var o=this.doc.createTextNode(a);this.currentElement?this.currentElement.appendChild(o):/^\s*$/.test(a)&&this.doc.appendChild(o),this.locator&&position(this.locator,o)}},skippedEntity:function(a){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(a){(this.locator=a)&&(a.lineNumber=0)},comment:function(a,i,e){a=_toString.apply(this,arguments);var o=this.doc.createComment(a);this.locator&&position(this.locator,o),appendElement(this,o)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(a,i,e){var o=this.doc.implementation;if(o&&o.createDocumentType){var s=o.createDocumentType(a,i,e);this.locator&&position(this.locator,s),appendElement(this,s)}},warning:function(a){console.warn("[xmldom warning] "+a,_locator(this.locator))},error:function(a){console.error("[xmldom error] "+a,_locator(this.locator))},fatalError:function(a){throw console.error("[xmldom fatalError] "+a,_locator(this.locator)),a}};function _locator(a){if(a)return`
  12493. @`+(a.systemId||"")+"#[line:"+a.lineNumber+",col:"+a.columnNumber+"]"}function _toString(a,i,e){return typeof a=="string"?a.substr(i,e):a.length>=i+e||i?new java.lang.String(a,i,e)+"":a}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(a){DOMHandler.prototype[a]=function(){return null}});function appendElement(a,i){a.currentElement?a.currentElement.appendChild(i):a.doc.appendChild(i)}var XMLReader=sax.XMLReader,DOMImplementation=domParser.DOMImplementation=dom.DOMImplementation;domParser.XMLSerializer=dom.XMLSerializer;domParser.DOMParser=DOMParser$1;var DOMParser=domParser.DOMParser,xmlToJSON=function(){this.version="1.3.5";var a={mergeCDATA:!0,normalize:!0,stripElemPrefix:!0},i=new RegExp(/(?!xmlns)^.*:/);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?e.toLowerCase()==="true":isFinite(e)?parseFloat(e):e},this.parseString=function(e,o){if(e){var s=this.stringToXML(e);return s.getElementsByTagName("parsererror").length?null:this.parseXML(s,o)}else return null},this.parseXML=function(e,o){for(var s in o)a[s]=o[s];var c={},d=0,_="",b=e.childNodes.length;if(b)for(var k,j,$,_e=0;_e<e.childNodes.length;_e++)k=e.childNodes.item(_e),k.nodeType===4?a.mergeCDATA&&(_+=k.nodeValue):k.nodeType===3?_+=k.nodeValue:k.nodeType===1&&(d===0&&(c={}),a.stripElemPrefix?j=k.nodeName.replace(i,""):j=k.nodeName,$=xmlToJSON.parseXML(k),c.hasOwnProperty(j)?(c[j].constructor!==Array&&(c[j]=[c[j]]),c[j].push($)):(c[j]=$,d++));return Object.keys(c).length||(c=_||""),c},this.xmlToString=function(e){try{var o=e.xml?e.xml:new XMLSerializer().serializeToString(e);return o}catch{return null}},this.stringToXML=function(e){try{var o=null;if(window.DOMParser){var s=new DOMParser;return o=s.parseFromString(e,"text/xml"),o}else return o=new ActiveXObject("Microsoft.XMLDOM"),o.async=!1,o.loadXML(e),o}catch{return null}},this}.call({}),xml2json$1=function(a){return xmlToJSON.parseString(a)},xml2json_1=xml2json$1,element_start_char="a-zA-Z_\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FFF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",element_non_start_char="-.0-9\xB7\u0300-\u036F\u203F\u2040",element_replace=new RegExp("^([^"+element_start_char+"])|^((x|X)(m|M)(l|L))|([^"+element_start_char+element_non_start_char+"])","g"),not_safe_in_xml=/[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm,objKeys=function(a){var i=[];if(a instanceof Object)for(var e in a)a.hasOwnProperty(e)&&i.push(e);return i},process_to_xml=function(a,i){var e=function(o,s,c,d,_){var b=i.indent!==void 0?i.indent:" ",k=i.prettyPrint?`
  12494. `+new Array(d).join(b):"";i.removeIllegalNameCharacters&&(o=o.replace(element_replace,"_"));var j=[k,"<",o,c||""];return s&&s.length>0?(j.push(">"),j.push(s),_&&j.push(k),j.push("</"),j.push(o),j.push(">")):j.push("/>"),j.join("")};return function o(s,c,d){var _=typeof s;switch((Array.isArray?Array.isArray(s):s instanceof Array)?_="array":s instanceof Date&&(_="date"),_){case"array":var b=[];return s.map(function(_e){b.push(o(_e,1,d+1))}),i.prettyPrint&&b.push(`
  12495. `),b.join("");case"date":return s.toJSON?s.toJSON():s+"";case"object":var k=[];for(var j in s)if(s.hasOwnProperty(j))if(s[j]instanceof Array)for(var $=0;$<s[j].length;$++)s[j].hasOwnProperty($)&&k.push(e(j,o(s[j][$],0,d+1),null,d+1,objKeys(s[j][$]).length));else k.push(e(j,o(s[j],0,d+1),null,d+1));return i.prettyPrint&&k.length>0&&k.push(`
  12496. `),k.join("");case"function":return s();default:return i.escape?esc(s):""+s}}(a,0,0)},xml_header=function(a){var i=['<?xml version="1.0" encoding="UTF-8"'];return a&&i.push(' standalone="yes"'),i.push("?>"),i.join("")};function esc(a){return(""+a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/'/g,"&apos;").replace(/"/g,"&quot;").replace(not_safe_in_xml,"")}var json2xml$1=function(a,i){if(i||(i={xmlHeader:{standalone:!0},prettyPrint:!0,indent:" ",escape:!0}),typeof a=="string")try{a=JSON.parse(a.toString())}catch{return!1}var e="",o="";i&&(typeof i=="object"?(i.xmlHeader&&(e=xml_header(!!i.xmlHeader.standalone)),typeof i.docType!="undefined"&&(o="<!DOCTYPE "+i.docType+">")):e=xml_header()),i=i||{};var s=[e,i.prettyPrint&&o?`
  12497. `:"",o,process_to_xml(a,i)];return s.join("").replace(/\n{2,}/g,`
  12498. `).replace(/\s+$/g,"")},md5=md5$1.exports,CryptoJS=crypto.exports,xml2json=xml2json_1,json2xml=json2xml$1;function camSafeUrlEncode(a){return encodeURIComponent(a).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}function getObjectKeys(a,i){var e=[];for(var o in a)a.hasOwnProperty(o)&&e.push(i?camSafeUrlEncode(o).toLowerCase():o);return e.sort(function(s,c){return s=s.toLowerCase(),c=c.toLowerCase(),s===c?0:s>c?1:-1})}var obj2str=function(a,i){var e,o,s,c=[],d=getObjectKeys(a);for(e=0;e<d.length;e++)o=d[e],s=a[o]===void 0||a[o]===null?"":""+a[o],o=i?camSafeUrlEncode(o).toLowerCase():camSafeUrlEncode(o),s=camSafeUrlEncode(s)||"",c.push(o+"="+s);return c.join("&")},signHeaders=["content-disposition","content-encoding","content-length","content-md5","expect","host","if-match","if-modified-since","if-none-match","if-unmodified-since","origin","range","response-cache-control","response-content-disposition","response-content-encoding","response-content-language","response-content-type","response-expires","transfer-encoding","versionid"],getSignHeaderObj=function(a){var i={};for(var e in a){var o=e.toLowerCase();(o.indexOf("x-cos-")>-1||signHeaders.indexOf(o)>-1)&&(i[e]=a[e])}return i},getAuth$1=function(a){a=a||{};var i=a.SecretId,e=a.SecretKey,o=a.KeyTime,s=(a.method||a.Method||"get").toLowerCase(),c=clone(a.Query||a.params||{}),d=getSignHeaderObj(clone(a.Headers||a.headers||{})),_=a.Key||"",b;if(a.UseRawKey?b=a.Pathname||a.pathname||"/"+_:(b=a.Pathname||a.pathname||_,b.indexOf("/")!==0&&(b="/"+b)),!d.Host&&!d.host&&a.Bucket&&a.Region&&(d.Host=a.Bucket+".cos."+a.Region+".myqcloud.com"),!i)throw new Error("missing param SecretId");if(!e)throw new Error("missing param SecretKey");var k=Math.round(getSkewTime(a.SystemClockOffset)/1e3)-1,j=k,$=a.Expires||a.expires;$===void 0?j+=900:j+=$*1||0;var _e="sha1",et=i,tt=o||k+";"+j,rt=o||k+";"+j,it=getObjectKeys(d,!0).join(";").toLowerCase(),nt=getObjectKeys(c,!0).join(";").toLowerCase(),ot=CryptoJS.HmacSHA1(rt,e).toString(),at=[s,b,util$5.obj2str(c,!0),util$5.obj2str(d,!0),""].join(`
  12499. `),st=["sha1",tt,CryptoJS.SHA1(at).toString(),""].join(`
  12500. `),ut=CryptoJS.HmacSHA1(st,ot).toString(),ft=["q-sign-algorithm="+_e,"q-ak="+et,"q-sign-time="+tt,"q-key-time="+rt,"q-header-list="+it,"q-url-param-list="+nt,"q-signature="+ut].join("&");return ft},readIntBE=function(a,i,e){var o=i/8,s=a.slice(e,e+o);return new Uint8Array(s).reverse(),new{8:Uint8Array,16:Uint16Array,32:Uint32Array}[i](s)[0]},buf2str=function(a,i,e,o){var s=a.slice(i,e),c="";return new Uint8Array(s).forEach(function(d){c+=String.fromCharCode(d)}),o&&(c=decodeURIComponent(escape(c))),c},parseSelectPayload=function(a){for(var i={},e=buf2str(a),o={records:[]};a.byteLength;){var s=readIntBE(a,32,0),c=readIntBE(a,32,4),d=s-c-16,_=0,b;for(a=a.slice(12);_<c;){var k=readIntBE(a,8,_),j=buf2str(a,_+1,_+1+k),$=readIntBE(a,16,_+k+2),_e=buf2str(a,_+k+4,_+k+4+$);i[j]=_e,_+=k+4+$}if(i[":event-type"]==="Records")b=buf2str(a,_,_+d,!0),o.records.push(b);else if(i[":event-type"]==="Stats")b=buf2str(a,_,_+d,!0),o.stats=util$5.xml2json(b).Stats;else if(i[":event-type"]==="error"){var et=i[":error-code"],tt=i[":error-message"],rt=new Error(tt);rt.message=tt,rt.name=rt.code=et,o.error=rt}else["Progress","Continuation","End"].includes(i[":event-type"]);a=a.slice(_+d+4)}return{payload:o.records.join(""),body:e}},getSourceParams=function(a){var i=this.options.CopySourceParser;if(i)return i(a);var e=a.match(/^([^.]+-\d+)\.cos(v6|-cdc)?\.([^.]+)\.myqcloud\.com\/(.+)$/);return e?{Bucket:e[1],Region:e[3],Key:e[4]}:null},noop=function(){},clearKey=function(a){var i={};for(var e in a)a.hasOwnProperty(e)&&a[e]!==void 0&&a[e]!==null&&(i[e]=a[e]);return i},readAsBinaryString=function(a,i){var e,o=new FileReader;FileReader.prototype.readAsBinaryString?(e=FileReader.prototype.readAsBinaryString,o.onload=function(){i(this.result)}):FileReader.prototype.readAsArrayBuffer?e=function(s){var c="",d=new FileReader;d.onload=function(_){for(var b=new Uint8Array(d.result),k=b.byteLength,j=0;j<k;j++)c+=String.fromCharCode(b[j]);i(c)},d.readAsArrayBuffer(s)}:console.error("FileReader not support readAsBinaryString"),e.call(o,a)},fileSliceNeedCopy=function(){var a=function(e,o){e=e.split("."),o=o.split(".");for(var s=0;s<o.length;s++)if(e[s]!==o[s])return parseInt(e[s])>parseInt(o[s])?1:-1;return 0},i=function(e){if(!e)return!1;var o=(e.match(/Chrome\/([.\d]+)/)||[])[1],s=(e.match(/QBCore\/([.\d]+)/)||[])[1],c=(e.match(/QQBrowser\/([.\d]+)/)||[])[1],d=o&&a(o,"53.0.2785.116")<0&&s&&a(s,"3.53.991.400")<0&&c&&a(c,"9.0.2524.400")<=0||!1;return d};return i(typeof navigator!="undefined"&&navigator.userAgent)}(),fileSlice=function(a,i,e,o,s){var c;if(a.slice?c=a.slice(i,e):a.mozSlice?c=a.mozSlice(i,e):a.webkitSlice&&(c=a.webkitSlice(i,e)),o&&fileSliceNeedCopy){var d=new FileReader;d.onload=function(_){c=null,s(new Blob([d.result]))},d.readAsArrayBuffer(c)}else s(c)},getBodyMd5=function(a,i,e,o){e=e||noop,a?typeof i=="string"?e(util$5.md5(i,!0)):Blob&&i instanceof Blob?util$5.getFileMd5(i,function(s,c){e(c)},o):e():e()},md5ChunkSize=1024*1024,getFileMd5=function(a,i,e){var o=a.size,s=0,c=md5.getCtx(),d=function(_){if(_>=o){var b=c.digest("hex");i(null,b);return}var k=Math.min(o,_+md5ChunkSize);util$5.fileSlice(a,_,k,!1,function(j){readAsBinaryString(j,function($){j=null,c=c.update($,!0),s+=$.length,$=null,e&&e({loaded:s,total:o,percent:Math.round(s/o*1e4)/1e4}),d(_+md5ChunkSize)})})};d(0)};function clone(a){return map$1(a,function(i){return typeof i=="object"&&i!==null?clone(i):i})}function attr(a,i,e){return a&&i in a?a[i]:e}function extend$1(a,i){return each(i,function(e,o){a[o]=i[o]}),a}function isArray(a){return a instanceof Array}function isInArray(a,i){for(var e=!1,o=0;o<a.length;o++)if(i===a[o]){e=!0;break}return e}function makeArray(a){return isArray(a)?a:[a]}function each(a,i){for(var e in a)a.hasOwnProperty(e)&&i(a[e],e)}function map$1(a,i){var e=isArray(a)?[]:{};for(var o in a)a.hasOwnProperty(o)&&(e[o]=i(a[o],o));return e}function filter(a,i){var e=isArray(a),o=e?[]:{};for(var s in a)a.hasOwnProperty(s)&&i(a[s],s)&&(e?o.push(a[s]):o[s]=a[s]);return o}var binaryBase64=function(a){var i,e,o,s="";for(i=0,e=a.length/2;i<e;i++)o=parseInt(a[i*2]+a[i*2+1],16),s+=String.fromCharCode(o);return btoa(s)},uuid=function(){var a=function(){return((1+Math.random())*65536|0).toString(16).substring(1)};return a()+a()+"-"+a()+"-"+a()+"-"+a()+"-"+a()+a()+a()},hasMissingParams=function(a,i){var e=i.Bucket,o=i.Region,s=i.Key,c=this.options.Domain,d=!c||c.indexOf("{Bucket}")>-1,_=!c||c.indexOf("{Region}")>-1;if(a.indexOf("Bucket")>-1||a==="deleteMultipleObject"||a==="multipartList"||a==="listObjectVersions"){if(d&&!e)return"Bucket";if(_&&!o)return"Region"}else if(a.indexOf("Object")>-1||a.indexOf("multipart")>-1||a==="sliceUploadFile"||a==="abortUploadTask"){if(d&&!e)return"Bucket";if(_&&!o)return"Region";if(!s)return"Key"}return!1},formatParams=function(a,i){if(i=extend$1({},i),a!=="getAuth"&&a!=="getV4Auth"&&a!=="getObjectUrl"){var e=i.Headers||{};if(i&&typeof i=="object"){(function(){for(var s in i)i.hasOwnProperty(s)&&s.indexOf("x-cos-")>-1&&(e[s]=i[s])})();var o={"x-cos-mfa":"MFA","Content-MD5":"ContentMD5","Content-Length":"ContentLength","Content-Type":"ContentType",Expect:"Expect",Expires:"Expires","Cache-Control":"CacheControl","Content-Disposition":"ContentDisposition","Content-Encoding":"ContentEncoding",Range:"Range","If-Modified-Since":"IfModifiedSince","If-Unmodified-Since":"IfUnmodifiedSince","If-Match":"IfMatch","If-None-Match":"IfNoneMatch","x-cos-copy-source":"CopySource","x-cos-copy-source-Range":"CopySourceRange","x-cos-metadata-directive":"MetadataDirective","x-cos-copy-source-If-Modified-Since":"CopySourceIfModifiedSince","x-cos-copy-source-If-Unmodified-Since":"CopySourceIfUnmodifiedSince","x-cos-copy-source-If-Match":"CopySourceIfMatch","x-cos-copy-source-If-None-Match":"CopySourceIfNoneMatch","x-cos-acl":"ACL","x-cos-grant-read":"GrantRead","x-cos-grant-write":"GrantWrite","x-cos-grant-full-control":"GrantFullControl","x-cos-grant-read-acp":"GrantReadAcp","x-cos-grant-write-acp":"GrantWriteAcp","x-cos-storage-class":"StorageClass","x-cos-traffic-limit":"TrafficLimit","x-cos-mime-limit":"MimeLimit","x-cos-server-side-encryption-customer-algorithm":"SSECustomerAlgorithm","x-cos-server-side-encryption-customer-key":"SSECustomerKey","x-cos-server-side-encryption-customer-key-MD5":"SSECustomerKeyMD5","x-cos-server-side-encryption":"ServerSideEncryption","x-cos-server-side-encryption-cos-kms-key-id":"SSEKMSKeyId","x-cos-server-side-encryption-context":"SSEContext"};util$5.each(o,function(s,c){i[s]!==void 0&&(e[c]=i[s])}),i.Headers=clearKey(e)}}return i},apiWrapper=function(a,i){return function(e,o){var s=this;typeof e=="function"&&(o=e,e={}),e=formatParams(a,e);var c=function($){return $&&$.headers&&($.headers["x-cos-request-id"]&&($.RequestId=$.headers["x-cos-request-id"]),$.headers["x-cos-version-id"]&&($.VersionId=$.headers["x-cos-version-id"]),$.headers["x-cos-delete-marker"]&&($.DeleteMarker=$.headers["x-cos-delete-marker"])),$},d=function($,_e){o&&o(c($),c(_e))},_=function(){if(a!=="getService"&&a!=="abortUploadTask"){var $=hasMissingParams.call(s,a,e);if($)return"missing param "+$;if(e.Region){if(s.options.CompatibilityMode){if(!/^([a-z\d-.]+)$/.test(e.Region))return"Region format error."}else{if(e.Region.indexOf("cos.")>-1)return'param Region should not be start with "cos."';if(!/^([a-z\d-]+)$/.test(e.Region))return"Region format error."}!s.options.CompatibilityMode&&e.Region.indexOf("-")===-1&&e.Region!=="yfb"&&e.Region!=="default"&&e.Region!=="accelerate"&&console.warn("warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224")}if(e.Bucket){if(!/^([a-z\d-]+)-(\d+)$/.test(e.Bucket))if(e.AppId)e.Bucket=e.Bucket+"-"+e.AppId;else if(s.options.AppId)e.Bucket=e.Bucket+"-"+s.options.AppId;else return'Bucket should format as "test-1250000000".';e.AppId&&(console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).'),delete e.AppId)}!s.options.UseRawKey&&e.Key&&e.Key.substr(0,1)==="/"&&(e.Key=e.Key.substr(1))}},b=_(),k=a==="getAuth"||a==="getObjectUrl";if(window.Promise&&!k&&!o)return new Promise(function($,_e){if(o=function(et,tt){et?_e(et):$(tt)},b)return d(util$5.error(new Error(b)));i.call(s,e,d)});if(b)return d(util$5.error(new Error(b)));var j=i.call(s,e,d);if(k)return j}},throttleOnProgress=function(a,i){var e=this,o=0,s=0,c=Date.now(),d,_;function b(){if(_=0,i&&typeof i=="function"){d=Date.now();var k=Math.max(0,Math.round((s-o)/((d-c)/1e3)*100)/100)||0,j;s===0&&a===0?j=1:j=Math.floor(s/a*100)/100||0,c=d,o=s;try{i({loaded:s,total:a,speed:k,percent:j})}catch{}}}return function(k,j){if(k&&(s=k.loaded,a=k.total),j)clearTimeout(_),b();else{if(_)return;_=setTimeout(b,e.options.ProgressInterval)}}},getFileSize=function(a,i,e){var o;if(typeof i.Body=="string"?i.Body=new Blob([i.Body],{type:"text/plain"}):i.Body instanceof ArrayBuffer&&(i.Body=new Blob([i.Body])),i.Body&&(i.Body instanceof Blob||i.Body.toString()==="[object File]"||i.Body.toString()==="[object Blob]"))o=i.Body.size;else{e(util$5.error(new Error("params body format error, Only allow File|Blob|String.")));return}i.ContentLength=o,e(null,o)},getSkewTime=function(a){return Date.now()+(a||0)},error=function(a,i){var e=a;return a.message=a.message||null,typeof i=="string"?(a.error=i,a.message=i):typeof i=="object"&&i!==null&&(extend$1(a,i),(i.code||i.name)&&(a.code=i.code||i.name),i.message&&(a.message=i.message),i.stack&&(a.stack=i.stack)),typeof Object.defineProperty=="function"&&(Object.defineProperty(a,"name",{writable:!0,enumerable:!1}),Object.defineProperty(a,"message",{enumerable:!0})),a.name=i&&i.name||a.name||a.code||"Error",a.code||(a.code=a.name),a.error||(a.error=clone(e)),a},isNode=function(){return typeof window!="object"&&typeof process=="object"&&typeof commonjsRequire=="function"},isCIHost=function(a){return/^https?:\/\/([^/]+\.)?ci\.[^/]+/.test(a)},util$5={noop,formatParams,apiWrapper,xml2json,json2xml,md5,clearKey,fileSlice,getBodyMd5,getFileMd5,binaryBase64,extend:extend$1,isArray,isInArray,makeArray,each,map:map$1,filter,clone,attr,uuid,camSafeUrlEncode,throttleOnProgress,getFileSize,getSkewTime,error,obj2str,getAuth:getAuth$1,parseSelectPayload,getSourceParams,isBrowser:!0,isNode,isCIHost},util_1=util$5,event$1={},initEvent=function(a){var i={},e=function(o){return!i[o]&&(i[o]=[]),i[o]};a.on=function(o,s){o==="task-list-update"&&console.warn('warning: Event "'+o+'" has been deprecated. Please use "list-update" instead.'),e(o).push(s)},a.off=function(o,s){for(var c=e(o),d=c.length-1;d>=0;d--)s===c[d]&&c.splice(d,1)},a.emit=function(o,s){for(var c=e(o).map(function(_){return _}),d=0;d<c.length;d++)c[d](s)}},EventProxy$1=function(){initEvent(this)};event$1.init=initEvent;event$1.EventProxy=EventProxy$1;var task$1={},util$4=util_1,cacheKey="cos_sdk_upload_cache",expires=30*24*3600,cache,timer,getCache=function(){try{var a=JSON.parse(localStorage.getItem(cacheKey))}catch{}a||(a=[]),cache=a},setCache=function(){try{localStorage.setItem(cacheKey,JSON.stringify(cache))}catch{}},init=function(){if(!cache){getCache.call(this);for(var a=!1,i=Math.round(Date.now()/1e3),e=cache.length-1;e>=0;e--){var o=cache[e][2];(!o||o+expires<i)&&(cache.splice(e,1),a=!0)}a&&setCache()}},save=function(){timer||(timer=setTimeout(function(){setCache(),timer=null},400))},mod={using:{},setUsing:function(a){mod.using[a]=!0},removeUsing:function(a){delete mod.using[a]},getFileId:function(a,i,e,o){return a.name&&a.size&&a.lastModifiedDate&&i?util$4.md5([a.name,a.size,a.lastModifiedDate,i,e,o].join("::")):null},getUploadIdList:function(a){if(!a)return null;init.call(this);for(var i=[],e=0;e<cache.length;e++)cache[e][0]===a&&i.push(cache[e][1]);return i.length?i:null},saveUploadId:function(a,i,e){if(init.call(this),!!a){for(var o=cache.length-1;o>=0;o--){var s=cache[o];s[0]===a&&s[1]===i&&cache.splice(o,1)}cache.unshift([a,i,Math.round(Date.now()/1e3)]),cache.length>e&&cache.splice(e),save()}},removeUploadId:function(a){init.call(this),delete mod.using[a];for(var i=cache.length-1;i>=0;i--)cache[i][1]===a&&cache.splice(i,1);save()}},session$2=mod,session$1=session$2,util$3=util_1,originApiMap={},transferToTaskMethod=function(a,i){originApiMap[i]=a[i],a[i]=function(e,o){e.SkipTask?originApiMap[i].call(this,e,o):this._addTask(i,e,o)}},initTask=function(a){var i=[],e={},o=0,s=0,c=function($){var _e={id:$.id,Bucket:$.Bucket,Region:$.Region,Key:$.Key,FilePath:$.FilePath,state:$.state,loaded:$.loaded,size:$.size,speed:$.speed,percent:$.percent,hashPercent:$.hashPercent,error:$.error};return $.FilePath&&(_e.FilePath=$.FilePath),$._custom&&(_e._custom=$._custom),_e},d=function(){var $,_e=function(){$=0,a.emit("task-list-update",{list:util$3.map(i,c)}),a.emit("list-update",{list:util$3.map(i,c)})};return function(){$||($=setTimeout(_e))}}(),_=function(){if(!(i.length<=a.options.UploadQueueSize)){for(var $=0;$<s&&$<i.length&&i.length>a.options.UploadQueueSize;){var _e=i[$].state==="waiting"||i[$].state==="checking"||i[$].state==="uploading";!i[$]||!_e?(e[i[$].id]&&delete e[i[$].id],i.splice($,1),s--):$++}d()}},b=function(){if(!(o>=a.options.FileParallelLimit)){for(;i[s]&&i[s].state!=="waiting";)s++;if(!(s>=i.length)){var $=i[s];s++,o++,$.state="checking",$.params.onTaskStart&&$.params.onTaskStart(c($)),!$.params.UploadData&&($.params.UploadData={});var _e=util$3.formatParams($.api,$.params);originApiMap[$.api].call(a,_e,function(et,tt){!a._isRunningTask($.id)||(($.state==="checking"||$.state==="uploading")&&($.state=et?"error":"success",et&&($.error=et),o--,d(),b(),$.callback&&$.callback(et,tt),$.state==="success"&&($.params&&(delete $.params.UploadData,delete $.params.Body,delete $.params),delete $.callback)),_())}),d(),setTimeout(b)}}},k=function($,_e){var et=e[$];if(!!et){var tt=et&&et.state==="waiting",rt=et&&(et.state==="checking"||et.state==="uploading");if(_e==="canceled"&&et.state!=="canceled"||_e==="paused"&&tt||_e==="paused"&&rt){if(_e==="paused"&&et.params.Body&&typeof et.params.Body.pipe=="function"){console.error("stream not support pause");return}et.state=_e,a.emit("inner-kill-task",{TaskId:$,toState:_e});try{var it=et&&et.params&&et.params.UploadData.UploadId}catch{}_e==="canceled"&&it&&session$1.removeUsing(it),d(),rt&&(o--,b()),_e==="canceled"&&(et.params&&(delete et.params.UploadData,delete et.params.Body,delete et.params),delete et.callback)}_()}};a._addTasks=function($){util$3.each($,function(_e){a._addTask(_e.api,_e.params,_e.callback,!0)}),d()};var j=!0;a._addTask=function($,_e,et,tt){_e=util$3.formatParams($,_e);var rt=util$3.uuid();_e.TaskId=rt,_e.onTaskReady&&_e.onTaskReady(rt),_e.TaskReady&&(_e.TaskReady(rt),j&&console.warn('warning: Param "TaskReady" has been deprecated. Please use "onTaskReady" instead.'),j=!1);var it={params:_e,callback:et,api:$,index:i.length,id:rt,Bucket:_e.Bucket,Region:_e.Region,Key:_e.Key,FilePath:_e.FilePath||"",state:"waiting",loaded:0,size:0,speed:0,percent:0,hashPercent:0,error:null,_custom:_e._custom},nt=_e.onHashProgress;_e.onHashProgress=function(at){!a._isRunningTask(it.id)||(it.hashPercent=at.percent,nt&&nt(at),d())};var ot=_e.onProgress;return _e.onProgress=function(at){!a._isRunningTask(it.id)||(it.state==="checking"&&(it.state="uploading"),it.loaded=at.loaded,it.speed=at.speed,it.percent=at.percent,ot&&ot(at),d())},util$3.getFileSize($,_e,function(at,st){if(at)return et(util$3.error(at));e[rt]=it,i.push(it),it.size=st,!tt&&d(),b(),_()}),rt},a._isRunningTask=function($){var _e=e[$];return!!(_e&&(_e.state==="checking"||_e.state==="uploading"))},a.getTaskList=function(){return util$3.map(i,c)},a.cancelTask=function($){k($,"canceled")},a.pauseTask=function($){k($,"paused")},a.restartTask=function($){var _e=e[$];_e&&(_e.state==="paused"||_e.state==="error")&&(_e.state="waiting",d(),s=Math.min(s,_e.index),b())},a.isUploadRunning=function(){return o||s<i.length}};task$1.transferToTaskMethod=transferToTaskMethod;task$1.init=initTask;var base$1={},stringifyPrimitive=function(a){switch(typeof a){case"string":return a;case"boolean":return a?"true":"false";case"number":return isFinite(a)?a:"";default:return""}},queryStringify=function(a,i,e,o){return i=i||"&",e=e||"=",a===null&&(a=void 0),typeof a=="object"?Object.keys(a).map(function(s){var c=encodeURIComponent(stringifyPrimitive(s))+e;return Array.isArray(a[s])?a[s].map(function(d){return c+encodeURIComponent(stringifyPrimitive(d))}).join(i):c+encodeURIComponent(stringifyPrimitive(a[s]))}).filter(Boolean).join(i):o?encodeURIComponent(stringifyPrimitive(o))+e+encodeURIComponent(stringifyPrimitive(a)):""},xhrRes=function(a,i,e){var o={};return i.getAllResponseHeaders().trim().split(`
  12501. `).forEach(function(s){if(s){var c=s.indexOf(":"),d=s.substr(0,c).trim().toLowerCase(),_=s.substr(c+1).trim();o[d]=_}}),{error:a,statusCode:i.status,statusMessage:i.statusText,headers:o,body:e}},xhrBody=function(a,i){return!i&&i==="text"?a.responseText:a.response},request$1=function(a,i){var e=(a.method||"GET").toUpperCase(),o=a.url;if(a.qs){var s=queryStringify(a.qs);s&&(o+=(o.indexOf("?")===-1?"?":"&")+s)}var c=new XMLHttpRequest;if(c.open(e,o,!0),c.responseType=a.dataType||"text",a.xhrFields)for(var d in a.xhrFields)c[d]=a.xhrFields[d];var _=a.headers;if(_)for(var b in _)_.hasOwnProperty(b)&&b.toLowerCase()!=="content-length"&&b.toLowerCase()!=="user-agent"&&b.toLowerCase()!=="origin"&&b.toLowerCase()!=="host"&&c.setRequestHeader(b,_[b]);return a.onProgress&&c.upload&&(c.upload.onprogress=a.onProgress),a.onDownloadProgress&&(c.onprogress=a.onDownloadProgress),a.timeout&&(c.timeout=a.timeout),c.ontimeout=function(k){var j=new Error("timeout");i(xhrRes(j,c))},c.onload=function(){i(xhrRes(null,c,xhrBody(c,a.dataType)))},c.onerror=function(k){var j=xhrBody(c,a.dataType);if(j)i(xhrRes(null,c,j));else{var $=c.statusText;!$&&c.status===0&&($=new Error("CORS blocked or network error")),i(xhrRes($,c,j))}},c.send(a.body||""),c},request_1=request$1,REQUEST=request_1,util$2=util_1;function getService(a,i){typeof a=="function"&&(i=a,a={});var e=this.options.Protocol||(util$2.isBrowser&&location.protocol==="http:"?"http:":"https:"),o=this.options.ServiceDomain,s=a.AppId||this.options.appId,c=a.Region;o?(o=o.replace(/\{\{AppId\}\}/ig,s||"").replace(/\{\{Region\}\}/ig,c||"").replace(/\{\{.*?\}\}/ig,""),/^[a-zA-Z]+:\/\//.test(o)||(o=e+"//"+o),o.slice(-1)==="/"&&(o=o.slice(0,-1))):c?o=e+"//cos."+c+".myqcloud.com":o=e+"//service.cos.myqcloud.com";var d="",_=c?"cos."+c+".myqcloud.com":"service.cos.myqcloud.com",b=o.replace(/^https?:\/\/([^/]+)(\/.*)?$/,"$1");_===b&&(d=_),submitRequest.call(this,{Action:"name/cos:GetService",url:o,method:"GET",headers:a.Headers,SignHost:d},function(k,j){if(k)return i(k);var $=j&&j.ListAllMyBucketsResult&&j.ListAllMyBucketsResult.Buckets&&j.ListAllMyBucketsResult.Buckets.Bucket||[];$=util$2.isArray($)?$:[$];var _e=j&&j.ListAllMyBucketsResult&&j.ListAllMyBucketsResult.Owner||{};i(null,{Buckets:$,Owner:_e,statusCode:j.statusCode,headers:j.headers})})}function putBucket(a,i){var e=this,o="";if(a.BucketAZConfig){var s={BucketAZConfig:a.BucketAZConfig};o=util$2.json2xml({CreateBucketConfiguration:s})}submitRequest.call(this,{Action:"name/cos:PutBucket",method:"PUT",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,body:o},function(c,d){if(c)return i(c);var _=getUrl({protocol:e.options.Protocol,domain:e.options.Domain,bucket:a.Bucket,region:a.Region,isLocation:!0});i(null,{Location:_,statusCode:d.statusCode,headers:d.headers})})}function headBucket(a,i){submitRequest.call(this,{Action:"name/cos:HeadBucket",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,method:"HEAD"},i)}function getBucket(a,i){var e={};e.prefix=a.Prefix||"",e.delimiter=a.Delimiter,e.marker=a.Marker,e["max-keys"]=a.MaxKeys,e["encoding-type"]=a.EncodingType,submitRequest.call(this,{Action:"name/cos:GetBucket",ResourceKey:e.prefix,method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,qs:e},function(o,s){if(o)return i(o);var c=s.ListBucketResult||{},d=c.Contents||[],_=c.CommonPrefixes||[];d=util$2.isArray(d)?d:[d],_=util$2.isArray(_)?_:[_];var b=util$2.clone(c);util$2.extend(b,{Contents:d,CommonPrefixes:_,statusCode:s.statusCode,headers:s.headers}),i(null,b)})}function deleteBucket(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucket",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,method:"DELETE"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketAcl(a,i){var e=a.Headers,o="";if(a.AccessControlPolicy){var s=util$2.clone(a.AccessControlPolicy||{}),c=s.Grants||s.Grant;c=util$2.isArray(c)?c:[c],delete s.Grant,delete s.Grants,s.AccessControlList={Grant:c},o=util$2.json2xml({AccessControlPolicy:s}),e["Content-Type"]="application/xml",e["Content-MD5"]=util$2.binaryBase64(util$2.md5(o))}util$2.each(e,function(d,_){_.indexOf("x-cos-grant-")===0&&(e[_]=uniqGrant(e[_]))}),submitRequest.call(this,{Action:"name/cos:PutBucketACL",method:"PUT",Bucket:a.Bucket,Region:a.Region,headers:e,action:"acl",body:o},function(d,_){if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketAcl(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketACL",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"acl"},function(e,o){if(e)return i(e);var s=o.AccessControlPolicy||{},c=s.Owner||{},d=s.AccessControlList.Grant||[];d=util$2.isArray(d)?d:[d];var _=decodeAcl(s);o.headers&&o.headers["x-cos-acl"]&&(_.ACL=o.headers["x-cos-acl"]),_=util$2.extend(_,{Owner:c,Grants:d,statusCode:o.statusCode,headers:o.headers}),i(null,_)})}function putBucketCors(a,i){var e=a.CORSConfiguration||{},o=e.CORSRules||a.CORSRules||[];o=util$2.clone(util$2.isArray(o)?o:[o]),util$2.each(o,function(d){util$2.each(["AllowedOrigin","AllowedHeader","AllowedMethod","ExposeHeader"],function(_){var b=_+"s",k=d[b]||d[_]||[];delete d[b],d[_]=util$2.isArray(k)?k:[k]})});var s=util$2.json2xml({CORSConfiguration:{CORSRule:o}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutBucketCORS",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:s,action:"cors",headers:c},function(d,_){if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketCors(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketCORS",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"cors"},function(e,o){if(e){if(e.statusCode===404&&e.error&&e.error.Code==="NoSuchCORSConfiguration"){var s={CORSRules:[],statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}var c=o.CORSConfiguration||{},d=c.CORSRules||c.CORSRule||[];d=util$2.clone(util$2.isArray(d)?d:[d]),util$2.each(d,function(_){util$2.each(["AllowedOrigin","AllowedHeader","AllowedMethod","ExposeHeader"],function(b){var k=b+"s",j=_[k]||_[b]||[];delete _[b],_[k]=util$2.isArray(j)?j:[j]})}),i(null,{CORSRules:d,statusCode:o.statusCode,headers:o.headers})})}function deleteBucketCors(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketCORS",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"cors"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode||e.statusCode,headers:o.headers})})}function getBucketLocation(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketLocation",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"location"},i)}function putBucketPolicy(a,i){var e=a.Policy;try{typeof e=="string"&&(e=JSON.parse(e))}catch{}if(!e||typeof e=="string")return i(util$2.error(new Error("Policy format error")));var o=JSON.stringify(e);e.version||(e.version="2.0");var s=a.Headers;s["Content-Type"]="application/json",s["Content-MD5"]=util$2.binaryBase64(util$2.md5(o)),submitRequest.call(this,{Action:"name/cos:PutBucketPolicy",method:"PUT",Bucket:a.Bucket,Region:a.Region,action:"policy",body:o,headers:s},function(c,d){if(c&&c.statusCode===204)return i(null,{statusCode:c.statusCode});if(c)return i(c);i(null,{statusCode:d.statusCode,headers:d.headers})})}function getBucketPolicy(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketPolicy",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"policy",rawBody:!0},function(e,o){if(e)return e.statusCode&&e.statusCode===403?i(util$2.error(e,{ErrorStatus:"Access Denied"})):e.statusCode&&e.statusCode===405?i(util$2.error(e,{ErrorStatus:"Method Not Allowed"})):e.statusCode&&e.statusCode===404?i(util$2.error(e,{ErrorStatus:"Policy Not Found"})):i(e);var s={};try{s=JSON.parse(o.body)}catch{}i(null,{Policy:s,statusCode:o.statusCode,headers:o.headers})})}function deleteBucketPolicy(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketPolicy",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"policy"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode||e.statusCode,headers:o.headers})})}function putBucketTagging(a,i){var e=a.Tagging||{},o=e.TagSet||e.Tags||a.Tags||[];o=util$2.clone(util$2.isArray(o)?o:[o]);var s=util$2.json2xml({Tagging:{TagSet:{Tag:o}}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutBucketTagging",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:s,action:"tagging",headers:c},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketTagging(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketTagging",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"tagging"},function(e,o){if(e){if(e.statusCode===404&&e.error&&(e.error==="Not Found"||e.error.Code==="NoSuchTagSet")){var s={Tags:[],statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}var c=[];try{c=o.Tagging.TagSet.Tag||[]}catch{}c=util$2.clone(util$2.isArray(c)?c:[c]),i(null,{Tags:c,statusCode:o.statusCode,headers:o.headers})})}function deleteBucketTagging(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketTagging",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"tagging"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketLifecycle(a,i){var e=a.LifecycleConfiguration||{},o=e.Rules||a.Rules||[];o=util$2.clone(o);var s=util$2.json2xml({LifecycleConfiguration:{Rule:o}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutBucketLifecycle",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:s,action:"lifecycle",headers:c},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketLifecycle(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketLifecycle",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"lifecycle"},function(e,o){if(e){if(e.statusCode===404&&e.error&&e.error.Code==="NoSuchLifecycleConfiguration"){var s={Rules:[],statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}var c=[];try{c=o.LifecycleConfiguration.Rule||[]}catch{}c=util$2.clone(util$2.isArray(c)?c:[c]),i(null,{Rules:c,statusCode:o.statusCode,headers:o.headers})})}function deleteBucketLifecycle(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketLifecycle",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"lifecycle"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketVersioning(a,i){if(!a.VersioningConfiguration){i(util$2.error(new Error("missing param VersioningConfiguration")));return}var e=a.VersioningConfiguration||{},o=util$2.json2xml({VersioningConfiguration:e}),s=a.Headers;s["Content-Type"]="application/xml",s["Content-MD5"]=util$2.binaryBase64(util$2.md5(o)),submitRequest.call(this,{Action:"name/cos:PutBucketVersioning",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:o,action:"versioning",headers:s},function(c,d){if(c&&c.statusCode===204)return i(null,{statusCode:c.statusCode});if(c)return i(c);i(null,{statusCode:d.statusCode,headers:d.headers})})}function getBucketVersioning(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketVersioning",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"versioning"},function(e,o){e||!o.VersioningConfiguration&&(o.VersioningConfiguration={}),i(e,o)})}function putBucketReplication(a,i){var e=util$2.clone(a.ReplicationConfiguration),o=util$2.json2xml({ReplicationConfiguration:e});o=o.replace(/<(\/?)Rules>/ig,"<$1Rule>"),o=o.replace(/<(\/?)Tags>/ig,"<$1Tag>");var s=a.Headers;s["Content-Type"]="application/xml",s["Content-MD5"]=util$2.binaryBase64(util$2.md5(o)),submitRequest.call(this,{Action:"name/cos:PutBucketReplication",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:o,action:"replication",headers:s},function(c,d){if(c&&c.statusCode===204)return i(null,{statusCode:c.statusCode});if(c)return i(c);i(null,{statusCode:d.statusCode,headers:d.headers})})}function getBucketReplication(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketReplication",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"replication"},function(e,o){if(e){if(e.statusCode===404&&e.error&&(e.error==="Not Found"||e.error.Code==="ReplicationConfigurationnotFoundError")){var s={ReplicationConfiguration:{Rules:[]},statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}!o.ReplicationConfiguration&&(o.ReplicationConfiguration={}),o.ReplicationConfiguration.Rule&&(o.ReplicationConfiguration.Rules=util$2.makeArray(o.ReplicationConfiguration.Rule),delete o.ReplicationConfiguration.Rule),i(e,o)})}function deleteBucketReplication(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketReplication",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"replication"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketWebsite(a,i){if(!a.WebsiteConfiguration){i(util$2.error(new Error("missing param WebsiteConfiguration")));return}var e=util$2.clone(a.WebsiteConfiguration||{}),o=e.RoutingRules||e.RoutingRule||[];o=util$2.isArray(o)?o:[o],delete e.RoutingRule,delete e.RoutingRules,o.length&&(e.RoutingRules={RoutingRule:o});var s=util$2.json2xml({WebsiteConfiguration:e}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutBucketWebsite",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:s,action:"website",headers:c},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketWebsite(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketWebsite",method:"GET",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,action:"website"},function(e,o){if(e){if(e.statusCode===404&&e.error.Code==="NoSuchWebsiteConfiguration"){var s={WebsiteConfiguration:{},statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}var c=o.WebsiteConfiguration||{};if(c.RoutingRules){var d=util$2.clone(c.RoutingRules.RoutingRule||[]);d=util$2.makeArray(d),c.RoutingRules=d}i(null,{WebsiteConfiguration:c,statusCode:o.statusCode,headers:o.headers})})}function deleteBucketWebsite(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketWebsite",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"website"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketReferer(a,i){if(!a.RefererConfiguration){i(util$2.error(new Error("missing param RefererConfiguration")));return}var e=util$2.clone(a.RefererConfiguration||{}),o=e.DomainList||{},s=o.Domains||o.Domain||[];s=util$2.isArray(s)?s:[s],s.length&&(e.DomainList={Domain:s});var c=util$2.json2xml({RefererConfiguration:e}),d=a.Headers;d["Content-Type"]="application/xml",d["Content-MD5"]=util$2.binaryBase64(util$2.md5(c)),submitRequest.call(this,{Action:"name/cos:PutBucketReferer",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:c,action:"referer",headers:d},function(_,b){if(_&&_.statusCode===204)return i(null,{statusCode:_.statusCode});if(_)return i(_);i(null,{statusCode:b.statusCode,headers:b.headers})})}function getBucketReferer(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketReferer",method:"GET",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,action:"referer"},function(e,o){if(e){if(e.statusCode===404&&e.error.Code==="NoSuchRefererConfiguration"){var s={WebsiteConfiguration:{},statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}var c=o.RefererConfiguration||{};if(c.DomainList){var d=util$2.makeArray(c.DomainList.Domain||[]);c.DomainList={Domains:d}}i(null,{RefererConfiguration:c,statusCode:o.statusCode,headers:o.headers})})}function putBucketDomain(a,i){var e=a.DomainConfiguration||{},o=e.DomainRule||a.DomainRule||[];o=util$2.clone(o);var s=util$2.json2xml({DomainConfiguration:{DomainRule:o}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutBucketDomain",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:s,action:"domain",headers:c},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketDomain(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketDomain",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"domain"},function(e,o){if(e)return i(e);var s=[];try{s=o.DomainConfiguration.DomainRule||[]}catch{}s=util$2.clone(util$2.isArray(s)?s:[s]),i(null,{DomainRule:s,statusCode:o.statusCode,headers:o.headers})})}function deleteBucketDomain(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketDomain",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"domain"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketOrigin(a,i){var e=a.OriginConfiguration||{},o=e.OriginRule||a.OriginRule||[];o=util$2.clone(o);var s=util$2.json2xml({OriginConfiguration:{OriginRule:o}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutBucketOrigin",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:s,action:"origin",headers:c},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketOrigin(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketOrigin",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"origin"},function(e,o){if(e)return i(e);var s=[];try{s=o.OriginConfiguration.OriginRule||[]}catch{}s=util$2.clone(util$2.isArray(s)?s:[s]),i(null,{OriginRule:s,statusCode:o.statusCode,headers:o.headers})})}function deleteBucketOrigin(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketOrigin",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"origin"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketLogging(a,i){var e=util$2.json2xml({BucketLoggingStatus:a.BucketLoggingStatus||""}),o=a.Headers;o["Content-Type"]="application/xml",o["Content-MD5"]=util$2.binaryBase64(util$2.md5(e)),submitRequest.call(this,{Action:"name/cos:PutBucketLogging",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:e,action:"logging",headers:o},function(s,c){if(s&&s.statusCode===204)return i(null,{statusCode:s.statusCode});if(s)return i(s);i(null,{statusCode:c.statusCode,headers:c.headers})})}function getBucketLogging(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketLogging",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"logging"},function(e,o){if(e)return i(e);i(null,{BucketLoggingStatus:o.BucketLoggingStatus,statusCode:o.statusCode,headers:o.headers})})}function putBucketInventory(a,i){var e=util$2.clone(a.InventoryConfiguration);if(e.OptionalFields){var o=e.OptionalFields||[];e.OptionalFields={Field:o}}if(e.Destination&&e.Destination.COSBucketDestination&&e.Destination.COSBucketDestination.Encryption){var s=e.Destination.COSBucketDestination.Encryption;Object.keys(s).indexOf("SSECOS")>-1&&(s["SSE-COS"]=s.SSECOS,delete s.SSECOS)}var c=util$2.json2xml({InventoryConfiguration:e}),d=a.Headers;d["Content-Type"]="application/xml",d["Content-MD5"]=util$2.binaryBase64(util$2.md5(c)),submitRequest.call(this,{Action:"name/cos:PutBucketInventory",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:c,action:"inventory",qs:{id:a.Id},headers:d},function(_,b){if(_&&_.statusCode===204)return i(null,{statusCode:_.statusCode});if(_)return i(_);i(null,{statusCode:b.statusCode,headers:b.headers})})}function getBucketInventory(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketInventory",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"inventory",qs:{id:a.Id}},function(e,o){if(e)return i(e);var s=o.InventoryConfiguration;if(s&&s.OptionalFields&&s.OptionalFields.Field){var c=s.OptionalFields.Field;util$2.isArray(c)||(c=[c]),s.OptionalFields=c}if(s.Destination&&s.Destination.COSBucketDestination&&s.Destination.COSBucketDestination.Encryption){var d=s.Destination.COSBucketDestination.Encryption;Object.keys(d).indexOf("SSE-COS")>-1&&(d.SSECOS=d["SSE-COS"],delete d["SSE-COS"])}i(null,{InventoryConfiguration:s,statusCode:o.statusCode,headers:o.headers})})}function listBucketInventory(a,i){submitRequest.call(this,{Action:"name/cos:ListBucketInventory",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"inventory",qs:{"continuation-token":a.ContinuationToken}},function(e,o){if(e)return i(e);var s=o.ListInventoryConfigurationResult,c=s.InventoryConfiguration||[];c=util$2.isArray(c)?c:[c],delete s.InventoryConfiguration,util$2.each(c,function(d){if(d&&d.OptionalFields&&d.OptionalFields.Field){var _=d.OptionalFields.Field;util$2.isArray(_)||(_=[_]),d.OptionalFields=_}if(d.Destination&&d.Destination.COSBucketDestination&&d.Destination.COSBucketDestination.Encryption){var b=d.Destination.COSBucketDestination.Encryption;Object.keys(b).indexOf("SSE-COS")>-1&&(b.SSECOS=b["SSE-COS"],delete b["SSE-COS"])}}),s.InventoryConfigurations=c,util$2.extend(s,{statusCode:o.statusCode,headers:o.headers}),i(null,s)})}function deleteBucketInventory(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketInventory",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"inventory",qs:{id:a.Id}},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function putBucketAccelerate(a,i){if(!a.AccelerateConfiguration){i(util$2.error(new Error("missing param AccelerateConfiguration")));return}var e={AccelerateConfiguration:a.AccelerateConfiguration||{}},o=util$2.json2xml(e),s={};s["Content-Type"]="application/xml",s["Content-MD5"]=util$2.binaryBase64(util$2.md5(o)),submitRequest.call(this,{Action:"name/cos:PutBucketAccelerate",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:o,action:"accelerate",headers:s},function(c,d){if(c)return i(c);i(null,{statusCode:d.statusCode,headers:d.headers})})}function getBucketAccelerate(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketAccelerate",method:"GET",Bucket:a.Bucket,Region:a.Region,action:"accelerate"},function(e,o){e||!o.AccelerateConfiguration&&(o.AccelerateConfiguration={}),i(e,o)})}function putBucketEncryption(a,i){var e=a.ServerSideEncryptionConfiguration||{},o=e.Rule||e.Rules||[],s=util$2.json2xml({ServerSideEncryptionConfiguration:{Rule:o}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutBucketEncryption",method:"PUT",Bucket:a.Bucket,Region:a.Region,body:s,action:"encryption",headers:c},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getBucketEncryption(a,i){submitRequest.call(this,{Action:"name/cos:GetBucketEncryption",method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"encryption"},function(e,o){if(e){if(e.statusCode===404&&e.code==="NoSuchEncryptionConfiguration"){var s={EncryptionConfiguration:{Rules:[]},statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}var c=util$2.makeArray(o.EncryptionConfiguration&&o.EncryptionConfiguration.Rule||[]);o.EncryptionConfiguration={Rules:c},i(e,o)})}function deleteBucketEncryption(a,i){submitRequest.call(this,{Action:"name/cos:DeleteBucketReplication",method:"DELETE",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"encryption"},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function headObject(a,i){submitRequest.call(this,{Action:"name/cos:HeadObject",method:"HEAD",Bucket:a.Bucket,Region:a.Region,Key:a.Key,VersionId:a.VersionId,headers:a.Headers},function(e,o){if(e){var s=e.statusCode;return a.Headers["If-Modified-Since"]&&s&&s===304?i(null,{NotModified:!0,statusCode:s}):i(e)}o.ETag=util$2.attr(o.headers,"etag",""),i(null,o)})}function listObjectVersions(a,i){var e={};e.prefix=a.Prefix||"",e.delimiter=a.Delimiter,e["key-marker"]=a.KeyMarker,e["version-id-marker"]=a.VersionIdMarker,e["max-keys"]=a.MaxKeys,e["encoding-type"]=a.EncodingType,submitRequest.call(this,{Action:"name/cos:GetBucketObjectVersions",ResourceKey:e.prefix,method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,qs:e,action:"versions"},function(o,s){if(o)return i(o);var c=s.ListVersionsResult||{},d=c.DeleteMarker||[];d=util$2.isArray(d)?d:[d];var _=c.Version||[];_=util$2.isArray(_)?_:[_];var b=util$2.clone(c);delete b.DeleteMarker,delete b.Version,util$2.extend(b,{DeleteMarkers:d,Versions:_,statusCode:s.statusCode,headers:s.headers}),i(null,b)})}function getObject(a,i){var e=a.Query||{},o=a.QueryString||"",s=util$2.throttleOnProgress.call(this,0,a.onProgress);e["response-content-type"]=a.ResponseContentType,e["response-content-language"]=a.ResponseContentLanguage,e["response-expires"]=a.ResponseExpires,e["response-cache-control"]=a.ResponseCacheControl,e["response-content-disposition"]=a.ResponseContentDisposition,e["response-content-encoding"]=a.ResponseContentEncoding,submitRequest.call(this,{Action:"name/cos:GetObject",method:"GET",Bucket:a.Bucket,Region:a.Region,Key:a.Key,VersionId:a.VersionId,DataType:a.DataType,headers:a.Headers,qs:e,qsStr:o,rawBody:!0,onDownloadProgress:s},function(c,d){if(s(null,!0),c){var _=c.statusCode;return a.Headers["If-Modified-Since"]&&_&&_===304?i(null,{NotModified:!0}):i(c)}i(null,{Body:d.body,ETag:util$2.attr(d.headers,"etag",""),statusCode:d.statusCode,headers:d.headers})})}function putObject(a,i){var e=this,o=a.ContentLength,s=util$2.throttleOnProgress.call(e,o,a.onProgress),c=a.Headers;!c["Cache-Control"]&&!c["cache-control"]&&(c["Cache-Control"]=""),!c["Content-Type"]&&!c["content-type"]&&(c["Content-Type"]=a.Body&&a.Body.type||"");var d=a.UploadAddMetaMd5||e.options.UploadAddMetaMd5||e.options.UploadCheckContentMd5;util$2.getBodyMd5(d,a.Body,function(_){_&&(e.options.UploadCheckContentMd5&&(c["Content-MD5"]=util$2.binaryBase64(_)),(a.UploadAddMetaMd5||e.options.UploadAddMetaMd5)&&(c["x-cos-meta-md5"]=_)),a.ContentLength!==void 0&&(c["Content-Length"]=a.ContentLength),s(null,!0),submitRequest.call(e,{Action:"name/cos:PutObject",TaskId:a.TaskId,method:"PUT",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,qs:a.Query,body:a.Body,onProgress:s},function(b,k){if(b)return s(null,!0),i(b);s({loaded:o,total:o},!0);var j=getUrl({ForcePathStyle:e.options.ForcePathStyle,protocol:e.options.Protocol,domain:e.options.Domain,bucket:a.Bucket,region:e.options.UseAccelerate?"accelerate":a.Region,object:a.Key});j=j.substr(j.indexOf("://")+3),k.Location=j,k.ETag=util$2.attr(k.headers,"etag",""),i(null,k)})},a.onHashProgress)}function deleteObject(a,i){submitRequest.call(this,{Action:"name/cos:DeleteObject",method:"DELETE",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,VersionId:a.VersionId,action:a.Recursive?"recursive":""},function(e,o){if(e){var s=e.statusCode;return s&&s===404?i(null,{BucketNotFound:!0,statusCode:s}):i(e)}i(null,{statusCode:o.statusCode,headers:o.headers})})}function getObjectAcl(a,i){submitRequest.call(this,{Action:"name/cos:GetObjectACL",method:"GET",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,action:"acl"},function(e,o){if(e)return i(e);var s=o.AccessControlPolicy||{},c=s.Owner||{},d=s.AccessControlList&&s.AccessControlList.Grant||[];d=util$2.isArray(d)?d:[d];var _=decodeAcl(s);delete _.GrantWrite,o.headers&&o.headers["x-cos-acl"]&&(_.ACL=o.headers["x-cos-acl"]),_=util$2.extend(_,{Owner:c,Grants:d,statusCode:o.statusCode,headers:o.headers}),i(null,_)})}function putObjectAcl(a,i){var e=a.Headers,o="";if(a.AccessControlPolicy){var s=util$2.clone(a.AccessControlPolicy||{}),c=s.Grants||s.Grant;c=util$2.isArray(c)?c:[c],delete s.Grant,delete s.Grants,s.AccessControlList={Grant:c},o=util$2.json2xml({AccessControlPolicy:s}),e["Content-Type"]="application/xml",e["Content-MD5"]=util$2.binaryBase64(util$2.md5(o))}util$2.each(e,function(d,_){_.indexOf("x-cos-grant-")===0&&(e[_]=uniqGrant(e[_]))}),submitRequest.call(this,{Action:"name/cos:PutObjectACL",method:"PUT",Bucket:a.Bucket,Region:a.Region,Key:a.Key,action:"acl",headers:e,body:o},function(d,_){if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function optionsObject(a,i){var e=a.Headers;e.Origin=a.Origin,e["Access-Control-Request-Method"]=a.AccessControlRequestMethod,e["Access-Control-Request-Headers"]=a.AccessControlRequestHeaders,submitRequest.call(this,{Action:"name/cos:OptionsObject",method:"OPTIONS",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:e},function(o,s){if(o)return o.statusCode&&o.statusCode===403?i(null,{OptionsForbidden:!0,statusCode:o.statusCode}):i(o);var c=s.headers||{};i(null,{AccessControlAllowOrigin:c["access-control-allow-origin"],AccessControlAllowMethods:c["access-control-allow-methods"],AccessControlAllowHeaders:c["access-control-allow-headers"],AccessControlExposeHeaders:c["access-control-expose-headers"],AccessControlMaxAge:c["access-control-max-age"],statusCode:s.statusCode,headers:s.headers})})}function putObjectCopy(a,i){var e=this,o=a.Headers;!o["Cache-Control"]&&!o["cache-control"]&&(o["Cache-Control"]="");var s=a.CopySource||"",c=util$2.getSourceParams.call(this,s);if(!c){i(util$2.error(new Error("CopySource format error")));return}var d=c[1],_=c[3],b=decodeURIComponent(c[4]);submitRequest.call(this,{Scope:[{action:"name/cos:GetObject",bucket:d,region:_,prefix:b},{action:"name/cos:PutObject",bucket:a.Bucket,region:a.Region,prefix:a.Key}],method:"PUT",Bucket:a.Bucket,Region:a.Region,Key:a.Key,VersionId:a.VersionId,headers:a.Headers},function(k,j){if(k)return i(k);var $=util$2.clone(j.CopyObjectResult||{}),_e=getUrl({ForcePathStyle:e.options.ForcePathStyle,protocol:e.options.Protocol,domain:e.options.Domain,bucket:a.Bucket,region:a.Region,object:a.Key,isLocation:!0});util$2.extend($,{Location:_e,statusCode:j.statusCode,headers:j.headers}),i(null,$)})}function uploadPartCopy(a,i){var e=a.CopySource||"",o=util$2.getSourceParams.call(this,e);if(!o){i(util$2.error(new Error("CopySource format error")));return}var s=o[1],c=o[3],d=decodeURIComponent(o[4]);submitRequest.call(this,{Scope:[{action:"name/cos:GetObject",bucket:s,region:c,prefix:d},{action:"name/cos:PutObject",bucket:a.Bucket,region:a.Region,prefix:a.Key}],method:"PUT",Bucket:a.Bucket,Region:a.Region,Key:a.Key,VersionId:a.VersionId,qs:{partNumber:a.PartNumber,uploadId:a.UploadId},headers:a.Headers},function(_,b){if(_)return i(_);var k=util$2.clone(b.CopyPartResult||{});util$2.extend(k,{statusCode:b.statusCode,headers:b.headers}),i(null,k)})}function deleteMultipleObject(a,i){var e=a.Objects||[],o=a.Quiet;e=util$2.isArray(e)?e:[e];var s=util$2.json2xml({Delete:{Object:e,Quiet:o||!1}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s));var d=util$2.map(e,function(_){return{action:"name/cos:DeleteObject",bucket:a.Bucket,region:a.Region,prefix:_.Key}});submitRequest.call(this,{Scope:d,method:"POST",Bucket:a.Bucket,Region:a.Region,body:s,action:"delete",headers:c},function(_,b){if(_)return i(_);var k=b.DeleteResult||{},j=k.Deleted||[],$=k.Error||[];j=util$2.isArray(j)?j:[j],$=util$2.isArray($)?$:[$];var _e=util$2.clone(k);util$2.extend(_e,{Error:$,Deleted:j,statusCode:b.statusCode,headers:b.headers}),i(null,_e)})}function restoreObject(a,i){var e=a.Headers;if(!a.RestoreRequest){i(util$2.error(new Error("missing param RestoreRequest")));return}var o=a.RestoreRequest||{},s=util$2.json2xml({RestoreRequest:o});e["Content-Type"]="application/xml",e["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:RestoreObject",method:"POST",Bucket:a.Bucket,Region:a.Region,Key:a.Key,VersionId:a.VersionId,body:s,action:"restore",headers:e},i)}function putObjectTagging(a,i){var e=a.Tagging||{},o=e.TagSet||e.Tags||a.Tags||[];o=util$2.clone(util$2.isArray(o)?o:[o]);var s=util$2.json2xml({Tagging:{TagSet:{Tag:o}}}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:PutObjectTagging",method:"PUT",Bucket:a.Bucket,Key:a.Key,Region:a.Region,body:s,action:"tagging",headers:c,VersionId:a.VersionId},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);i(null,{statusCode:_.statusCode,headers:_.headers})})}function getObjectTagging(a,i){submitRequest.call(this,{Action:"name/cos:GetObjectTagging",method:"GET",Key:a.Key,Bucket:a.Bucket,Region:a.Region,headers:a.Headers,action:"tagging",VersionId:a.VersionId},function(e,o){if(e){if(e.statusCode===404&&e.error&&(e.error==="Not Found"||e.error.Code==="NoSuchTagSet")){var s={Tags:[],statusCode:e.statusCode};e.headers&&(s.headers=e.headers),i(null,s)}else i(e);return}var c=[];try{c=o.Tagging.TagSet.Tag||[]}catch{}c=util$2.clone(util$2.isArray(c)?c:[c]),i(null,{Tags:c,statusCode:o.statusCode,headers:o.headers})})}function deleteObjectTagging(a,i){submitRequest.call(this,{Action:"name/cos:DeleteObjectTagging",method:"DELETE",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,action:"tagging",VersionId:a.VersionId},function(e,o){if(e&&e.statusCode===204)return i(null,{statusCode:e.statusCode});if(e)return i(e);i(null,{statusCode:o.statusCode,headers:o.headers})})}function selectObjectContent(a,i){var e=a.SelectType;if(!e)return i(util$2.error(new Error("missing param SelectType")));var o=a.SelectRequest||{},s=util$2.json2xml({SelectRequest:o}),c=a.Headers;c["Content-Type"]="application/xml",c["Content-MD5"]=util$2.binaryBase64(util$2.md5(s)),submitRequest.call(this,{Action:"name/cos:GetObject",method:"POST",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,action:"select",qs:{"select-type":a.SelectType},VersionId:a.VersionId,body:s,DataType:"arraybuffer",rawBody:!0},function(d,_){if(d&&d.statusCode===204)return i(null,{statusCode:d.statusCode});if(d)return i(d);var b=util$2.parseSelectPayload(_.body);i(null,{statusCode:_.statusCode,headers:_.headers,Body:b.body,Payload:b.payload})})}function multipartInit(a,i){var e=this,o=a.Headers;!o["Cache-Control"]&&!o["cache-control"]&&(o["Cache-Control"]=""),!o["Content-Type"]&&!o["content-type"]&&(o["Content-Type"]=a.Body&&a.Body.type||""),util$2.getBodyMd5(a.Body&&(a.UploadAddMetaMd5||e.options.UploadAddMetaMd5),a.Body,function(s){s&&(a.Headers["x-cos-meta-md5"]=s),submitRequest.call(e,{Action:"name/cos:InitiateMultipartUpload",method:"POST",Bucket:a.Bucket,Region:a.Region,Key:a.Key,action:"uploads",headers:a.Headers,qs:a.Query},function(c,d){if(c)return i(c);if(d=util$2.clone(d||{}),d&&d.InitiateMultipartUploadResult)return i(null,util$2.extend(d.InitiateMultipartUploadResult,{statusCode:d.statusCode,headers:d.headers}));i(null,d)})},a.onHashProgress)}function multipartUpload(a,i){var e=this;util$2.getFileSize("multipartUpload",a,function(){util$2.getBodyMd5(e.options.UploadCheckContentMd5,a.Body,function(o){o&&(a.Headers["Content-MD5"]=util$2.binaryBase64(o)),submitRequest.call(e,{Action:"name/cos:UploadPart",TaskId:a.TaskId,method:"PUT",Bucket:a.Bucket,Region:a.Region,Key:a.Key,qs:{partNumber:a.PartNumber,uploadId:a.UploadId},headers:a.Headers,onProgress:a.onProgress,body:a.Body||null},function(s,c){if(s)return i(s);i(null,{ETag:util$2.attr(c.headers,"etag",""),statusCode:c.statusCode,headers:c.headers})})})})}function multipartComplete(a,i){for(var e=this,o=a.UploadId,s=a.Parts,c=0,d=s.length;c<d;c++)s[c].ETag&&s[c].ETag.indexOf('"')===0||(s[c].ETag='"'+s[c].ETag+'"');var _=util$2.json2xml({CompleteMultipartUpload:{Part:s}});_=_.replace(/\n\s*/g,"");var b=a.Headers;b["Content-Type"]="application/xml",b["Content-MD5"]=util$2.binaryBase64(util$2.md5(_)),submitRequest.call(this,{Action:"name/cos:CompleteMultipartUpload",method:"POST",Bucket:a.Bucket,Region:a.Region,Key:a.Key,qs:{uploadId:o},body:_,headers:b},function(k,j){if(k)return i(k);var $=getUrl({ForcePathStyle:e.options.ForcePathStyle,protocol:e.options.Protocol,domain:e.options.Domain,bucket:a.Bucket,region:a.Region,object:a.Key,isLocation:!0}),_e=j.CompleteMultipartUploadResult||{};_e.ProcessResults&&_e&&_e.ProcessResults&&(_e.UploadResult={OriginalInfo:{Key:_e.Key,Location:$,ETag:_e.ETag,ImageInfo:_e.ImageInfo},ProcessResults:_e.ProcessResults},delete _e.ImageInfo,delete _e.ProcessResults);var et=util$2.extend(_e,{Location:$,statusCode:j.statusCode,headers:j.headers});i(null,et)})}function multipartList(a,i){var e={};e.delimiter=a.Delimiter,e["encoding-type"]=a.EncodingType,e.prefix=a.Prefix||"",e["max-uploads"]=a.MaxUploads,e["key-marker"]=a.KeyMarker,e["upload-id-marker"]=a.UploadIdMarker,e=util$2.clearKey(e),submitRequest.call(this,{Action:"name/cos:ListMultipartUploads",ResourceKey:e.prefix,method:"GET",Bucket:a.Bucket,Region:a.Region,headers:a.Headers,qs:e,action:"uploads"},function(o,s){if(o)return i(o);if(s&&s.ListMultipartUploadsResult){var c=s.ListMultipartUploadsResult.Upload||[];c=util$2.isArray(c)?c:[c],s.ListMultipartUploadsResult.Upload=c}var d=util$2.clone(s.ListMultipartUploadsResult||{});util$2.extend(d,{statusCode:s.statusCode,headers:s.headers}),i(null,d)})}function multipartListPart(a,i){var e={};e.uploadId=a.UploadId,e["encoding-type"]=a.EncodingType,e["max-parts"]=a.MaxParts,e["part-number-marker"]=a.PartNumberMarker,submitRequest.call(this,{Action:"name/cos:ListParts",method:"GET",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,qs:e},function(o,s){if(o)return i(o);var c=s.ListPartsResult||{},d=c.Part||[];d=util$2.isArray(d)?d:[d],c.Part=d;var _=util$2.clone(c);util$2.extend(_,{statusCode:s.statusCode,headers:s.headers}),i(null,_)})}function multipartAbort(a,i){var e={};e.uploadId=a.UploadId,submitRequest.call(this,{Action:"name/cos:AbortMultipartUpload",method:"DELETE",Bucket:a.Bucket,Region:a.Region,Key:a.Key,headers:a.Headers,qs:e},function(o,s){if(o)return i(o);i(null,{statusCode:s.statusCode,headers:s.headers})})}function request(a,i){submitRequest.call(this,{method:a.Method,Bucket:a.Bucket,Region:a.Region,Key:a.Key,action:a.Action,headers:a.Headers,qs:a.Query,body:a.Body,Url:a.Url,rawBody:a.RawBody,DataType:a.DataType},function(e,o){if(e)return i(e);o&&o.body&&(o.Body=o.body,delete o.body),i(e,o)})}function appendObject(a,i){var e=a.Headers;!e["Cache-Control"]&&!e["cache-control"]&&(e["Cache-Control"]=""),!e["Content-Type"]&&!e["content-type"]&&(e["Content-Type"]=a.Body&&a.Body.type||""),submitRequest.call(this,{Action:"name/cos:AppendObject",method:"POST",Bucket:a.Bucket,Region:a.Region,action:"append",Key:a.Key,body:a.Body,qs:{position:a.Position},headers:a.Headers},function(o,s){if(o)return i(o);i(null,s)})}function getAuth(a){var i=this;return util$2.getAuth({SecretId:a.SecretId||this.options.SecretId||"",SecretKey:a.SecretKey||this.options.SecretKey||"",Bucket:a.Bucket,Region:a.Region,Method:a.Method,Key:a.Key,Query:a.Query,Headers:a.Headers,Expires:a.Expires,UseRawKey:i.options.UseRawKey,SystemClockOffset:i.options.SystemClockOffset})}function getObjectUrl(a,i){var e=this,o=getUrl({ForcePathStyle:e.options.ForcePathStyle,protocol:a.Protocol||e.options.Protocol,domain:a.Domain||e.options.Domain,bucket:a.Bucket,region:a.Region,object:a.Key}),s="";a.Query&&(s+=util$2.obj2str(a.Query)),a.QueryString&&(s+=(s?"&":"")+a.QueryString);var c=o;if(a.Sign!==void 0&&!a.Sign)return s&&(c+="?"+s),i(null,{Url:c}),c;var d=getSignHost.call(this,{Bucket:a.Bucket,Region:a.Region,Url:o}),_=getAuthorizationAsync.call(this,{Action:(a.Method||"").toUpperCase()==="PUT"?"name/cos:PutObject":"name/cos:GetObject",Bucket:a.Bucket||"",Region:a.Region||"",Method:a.Method||"get",Key:a.Key,Expires:a.Expires,Headers:a.Headers,Query:a.Query,SignHost:d},function(b,k){if(!!i){if(b){i(b);return}var j=function(_e){var et=_e.match(/q-url-param-list.*?(?=&)/g)[0],tt="q-url-param-list="+encodeURIComponent(et.replace(/q-url-param-list=/,"")).toLowerCase(),rt=new RegExp(et,"g"),it=_e.replace(rt,tt);return it},$=o;$+="?"+(k.Authorization.indexOf("q-signature")>-1?j(k.Authorization):"sign="+encodeURIComponent(k.Authorization)),k.SecurityToken&&($+="&x-cos-security-token="+k.SecurityToken),k.ClientIP&&($+="&clientIP="+k.ClientIP),k.ClientUA&&($+="&clientUA="+k.ClientUA),k.Token&&($+="&token="+k.Token),s&&($+="&"+s),setTimeout(function(){i(null,{Url:$})})}});return _?(c+="?"+_.Authorization+(_.SecurityToken?"&x-cos-security-token="+_.SecurityToken:""),s&&(c+="&"+s)):s&&(c+="?"+s),c}function decodeAcl(a){var i={GrantFullControl:[],GrantWrite:[],GrantRead:[],GrantReadAcp:[],GrantWriteAcp:[],ACL:""},e={FULL_CONTROL:"GrantFullControl",WRITE:"GrantWrite",READ:"GrantRead",READ_ACP:"GrantReadAcp",WRITE_ACP:"GrantWriteAcp"},o=a&&a.AccessControlList||{},s=o.Grant;s&&(s=util$2.isArray(s)?s:[s]);var c={READ:0,WRITE:0,FULL_CONTROL:0};return s&&s.length&&util$2.each(s,function(d){d.Grantee.ID==="qcs::cam::anyone:anyone"||d.Grantee.URI==="http://cam.qcloud.com/groups/global/AllUsers"?c[d.Permission]=1:d.Grantee.ID!==a.Owner.ID&&i[e[d.Permission]].push('id="'+d.Grantee.ID+'"')}),c.FULL_CONTROL||c.WRITE&&c.READ?i.ACL="public-read-write":c.READ?i.ACL="public-read":i.ACL="private",util$2.each(e,function(d){i[d]=uniqGrant(i[d].join(","))}),i}function uniqGrant(a){var i=a.split(","),e={},o,s;for(o=0;o<i.length;)s=i[o].trim(),e[s]?i.splice(o,1):(e[s]=!0,i[o]=s,o++);return i.join(",")}function getUrl(a){var i=a.region||"",e=a.bucket||"",o=e.substr(0,e.lastIndexOf("-")),s=e.substr(e.lastIndexOf("-")+1),c=a.domain,d=a.object;typeof c=="function"&&(c=c({Bucket:e,Region:i}));var _=a.protocol||(util$2.isBrowser&&location.protocol==="http:"?"http:":"https:");c||(["cn-south","cn-south-2","cn-north","cn-east","cn-southwest","sg"].indexOf(i)>-1?c="{Region}.myqcloud.com":c="cos.{Region}.myqcloud.com",a.ForcePathStyle||(c="{Bucket}."+c)),c=c.replace(/\{\{AppId\}\}/ig,s).replace(/\{\{Bucket\}\}/ig,o).replace(/\{\{Region\}\}/ig,i).replace(/\{\{.*?\}\}/ig,""),c=c.replace(/\{AppId\}/ig,s).replace(/\{BucketName\}/ig,o).replace(/\{Bucket\}/ig,e).replace(/\{Region\}/ig,i).replace(/\{.*?\}/ig,""),/^[a-zA-Z]+:\/\//.test(c)||(c=_+"//"+c),c.slice(-1)==="/"&&(c=c.slice(0,-1));var b=c;return a.ForcePathStyle&&(b+="/"+e),b+="/",d&&(b+=util$2.camSafeUrlEncode(d).replace(/%2F/g,"/")),a.isLocation&&(b=b.replace(/^https?:\/\//,"")),b}var getSignHost=function(a){if(!a.Bucket||!a.Region)return"";var i=a.Url||getUrl({ForcePathStyle:this.options.ForcePathStyle,protocol:this.options.Protocol,domain:this.options.Domain,bucket:a.Bucket,region:this.options.UseAccelerate?"accelerate":a.Region}),e=i.replace(/^https?:\/\/([^/]+)(\/.*)?$/,"$1"),o=new RegExp("^([a-z\\d-]+-\\d+\\.)?(cos|cosv6|ci|pic)\\.([a-z\\d-]+)\\.myqcloud\\.com$");return o.test(e)?e:""};function getAuthorizationAsync(a,i){var e=util$2.clone(a.Headers),o="";util$2.each(e,function(ot,at){(ot===""||["content-type","cache-control","expires"].indexOf(at.toLowerCase())>-1)&&delete e[at],at.toLowerCase()==="host"&&(o=ot)}),!o&&a.SignHost&&(e.Host=a.SignHost);var s=!1,c=function(ot,at){s||(s=!0,at&&at.XCosSecurityToken&&!at.SecurityToken&&(at=util$2.clone(at),at.SecurityToken=at.XCosSecurityToken,delete at.XCosSecurityToken),i&&i(ot,at))},d=this,_=a.Bucket||"",b=a.Region||"",k=a.Key||"";d.options.ForcePathStyle&&_&&(k=_+"/"+k);var j="/"+k,$={},_e=a.Scope;if(!_e){var et=a.Action||"",tt=a.ResourceKey||a.Key||"";_e=a.Scope||[{action:et,bucket:_,region:b,prefix:tt}]}var rt=util$2.md5(JSON.stringify(_e));d._StsCache=d._StsCache||[],function(){var ot,at;for(ot=d._StsCache.length-1;ot>=0;ot--){at=d._StsCache[ot];var st=Math.round(util$2.getSkewTime(d.options.SystemClockOffset)/1e3)+30;if(at.StartTime&&st<at.StartTime||st>=at.ExpiredTime){d._StsCache.splice(ot,1);continue}if(!at.ScopeLimit||at.ScopeLimit&&at.ScopeKey===rt){$=at;break}}}();var it=function(){var ot=$.StartTime&&$.ExpiredTime?$.StartTime+";"+$.ExpiredTime:"",at=util$2.getAuth({SecretId:$.TmpSecretId,SecretKey:$.TmpSecretKey,Method:a.Method,Pathname:j,Query:a.Query,Headers:e,Expires:a.Expires,UseRawKey:d.options.UseRawKey,SystemClockOffset:d.options.SystemClockOffset,KeyTime:ot}),st={Authorization:at,SecurityToken:$.SecurityToken||$.XCosSecurityToken||"",Token:$.Token||"",ClientIP:$.ClientIP||"",ClientUA:$.ClientUA||""};c(null,st)},nt=function(ot){if(ot.Authorization){var at=!1,st=ot.Authorization;if(st)if(st.indexOf(" ")>-1)at=!1;else if(st.indexOf("q-sign-algorithm=")>-1&&st.indexOf("q-ak=")>-1&&st.indexOf("q-sign-time=")>-1&&st.indexOf("q-key-time=")>-1&&st.indexOf("q-url-param-list=")>-1)at=!0;else try{st=atob(st),st.indexOf("a=")>-1&&st.indexOf("k=")>-1&&st.indexOf("t=")>-1&&st.indexOf("r=")>-1&&st.indexOf("b=")>-1&&(at=!0)}catch{}if(!at)return util$2.error(new Error("getAuthorization callback params format error"))}else{if(!ot.TmpSecretId)return util$2.error(new Error('getAuthorization callback params missing "TmpSecretId"'));if(!ot.TmpSecretKey)return util$2.error(new Error('getAuthorization callback params missing "TmpSecretKey"'));if(!ot.SecurityToken&&!ot.XCosSecurityToken)return util$2.error(new Error('getAuthorization callback params missing "SecurityToken"'));if(!ot.ExpiredTime)return util$2.error(new Error('getAuthorization callback params missing "ExpiredTime"'));if(ot.ExpiredTime&&ot.ExpiredTime.toString().length!==10)return util$2.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits'));if(ot.StartTime&&ot.StartTime.toString().length!==10)return util$2.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime'))}return!1};if($.ExpiredTime&&$.ExpiredTime-util$2.getSkewTime(d.options.SystemClockOffset)/1e3>60)it();else if(d.options.getAuthorization)d.options.getAuthorization.call(d,{Bucket:_,Region:b,Method:a.Method,Key:k,Pathname:j,Query:a.Query,Headers:e,Scope:_e,SystemClockOffset:d.options.SystemClockOffset},function(ot){typeof ot=="string"&&(ot={Authorization:ot});var at=nt(ot);if(at)return c(at);ot.Authorization?c(null,ot):($=ot||{},$.Scope=_e,$.ScopeKey=rt,d._StsCache.push($),it())});else if(d.options.getSTS)d.options.getSTS.call(d,{Bucket:_,Region:b},function(ot){$=ot||{},$.Scope=_e,$.ScopeKey=rt,$.TmpSecretId||($.TmpSecretId=$.SecretId),$.TmpSecretKey||($.TmpSecretKey=$.SecretKey);var at=nt($);if(at)return c(at);d._StsCache.push($),it()});else return function(){var ot=util$2.getAuth({SecretId:a.SecretId||d.options.SecretId,SecretKey:a.SecretKey||d.options.SecretKey,Method:a.Method,Pathname:j,Query:a.Query,Headers:e,Expires:a.Expires,UseRawKey:d.options.UseRawKey,SystemClockOffset:d.options.SystemClockOffset}),at={Authorization:ot,SecurityToken:d.options.SecurityToken||d.options.XCosSecurityToken};return c(null,at),at}();return""}function allowRetry(a){var i=!1,e=!1,o=a.headers&&(a.headers.date||a.headers.Date)||a.error&&a.error.ServerTime;try{var s=a.error.Code,c=a.error.Message;(s==="RequestTimeTooSkewed"||s==="AccessDenied"&&c==="Request has expired")&&(e=!0)}catch{}if(a)if(e&&o){var d=Date.parse(o);this.options.CorrectClockSkew&&Math.abs(util$2.getSkewTime(this.options.SystemClockOffset)-d)>=3e4&&(console.error("error: Local time is too skewed."),this.options.SystemClockOffset=d-Date.now(),i=!0)}else Math.floor(a.statusCode/100)===5&&(i=!0);return i}function submitRequest(a,i){var e=this;!a.headers&&(a.headers={}),!a.qs&&(a.qs={}),a.VersionId&&(a.qs.versionId=a.VersionId),a.qs=util$2.clearKey(a.qs),a.headers&&(a.headers=util$2.clearKey(a.headers)),a.qs&&(a.qs=util$2.clearKey(a.qs));var o=util$2.clone(a.qs);a.action&&(o[a.action]="");var s=a.url||a.Url,c=a.SignHost||getSignHost.call(this,{Bucket:a.Bucket,Region:a.Region,Url:s}),d=function(_){var b=e.options.SystemClockOffset;getAuthorizationAsync.call(e,{Bucket:a.Bucket||"",Region:a.Region||"",Method:a.method,Key:a.Key,Query:o,Headers:a.headers,SignHost:c,Action:a.Action,ResourceKey:a.ResourceKey,Scope:a.Scope},function(k,j){if(k){i(k);return}a.AuthData=j,_submitRequest.call(e,a,function($,_e){$&&_<2&&(b!==e.options.SystemClockOffset||allowRetry.call(e,$))?(a.headers&&(delete a.headers.Authorization,delete a.headers.token,delete a.headers.clientIP,delete a.headers.clientUA,a.headers["x-cos-security-token"]&&delete a.headers["x-cos-security-token"],a.headers["x-ci-security-token"]&&delete a.headers["x-ci-security-token"]),d(_+1)):i($,_e)})})};d(1)}function _submitRequest(a,i){var e=this,o=a.TaskId;if(!(o&&!e._isRunningTask(o))){var s=a.Bucket,c=a.Region,d=a.Key,_=a.method||"GET",b=a.Url||a.url,k=a.body,j=a.rawBody;e.options.UseAccelerate&&(c="accelerate"),b=b||getUrl({ForcePathStyle:e.options.ForcePathStyle,protocol:e.options.Protocol,domain:e.options.Domain,bucket:s,region:c,object:d}),a.action&&(b=b+"?"+a.action),a.qsStr&&(b.indexOf("?")>-1?b=b+"&"+a.qsStr:b=b+"?"+a.qsStr);var $={method:_,url:b,headers:a.headers,qs:a.qs,body:k},_e="x-cos-security-token";if(util$2.isCIHost(b)&&(_e="x-ci-security-token"),$.headers.Authorization=a.AuthData.Authorization,a.AuthData.Token&&($.headers.token=a.AuthData.Token),a.AuthData.ClientIP&&($.headers.clientIP=a.AuthData.ClientIP),a.AuthData.ClientUA&&($.headers.clientUA=a.AuthData.ClientUA),a.AuthData.SecurityToken&&($.headers[_e]=a.AuthData.SecurityToken),$.headers&&($.headers=util$2.clearKey($.headers)),$=util$2.clearKey($),a.onProgress&&typeof a.onProgress=="function"){var et=k&&(k.size||k.length)||0;$.onProgress=function(it){if(!(o&&!e._isRunningTask(o))){var nt=it?it.loaded:0;a.onProgress({loaded:nt,total:et})}}}a.onDownloadProgress&&($.onDownloadProgress=a.onDownloadProgress),a.DataType&&($.dataType=a.DataType),this.options.Timeout&&($.timeout=this.options.Timeout),e.options.ForcePathStyle&&($.pathStyle=e.options.ForcePathStyle),e.emit("before-send",$);var tt=(e.options.Request||REQUEST)($,function(it){if(it.error!=="abort"){var nt={options:$,error:at,statusCode:ot&&ot.statusCode||0,headers:ot&&ot.headers||{},body:st};e.emit("after-receive",nt),at=nt.error,st=nt.body,ot={statusCode:nt.statusCode,headers:nt.headers},e.emit("after-receive",it);var ot={statusCode:it.statusCode,statusMessage:it.statusMessage,headers:it.headers},at=it.error,st=it.body,ut,ft=function(dt,gt){if(o&&e.off("inner-kill-task",rt),!ut){ut=!0;var _t={};ot&&ot.statusCode&&(_t.statusCode=ot.statusCode),ot&&ot.headers&&(_t.headers=ot.headers),dt?(dt=util$2.extend(dt||{},_t),i(dt,null)):(gt=util$2.extend(gt||{},_t),i(null,gt)),tt=null}};if(at)return ft(util$2.error(at));var lt=ot.statusCode,ht=Math.floor(lt/100)===2;if(j&&ht)return ft(null,{body:st});var pt;try{pt=st&&st.indexOf("<")>-1&&st.indexOf(">")>-1&&util$2.xml2json(st)||{}}catch{pt={}}var mt=pt&&pt.Error;ht?ft(null,pt):mt?ft(util$2.error(new Error(mt.Message),{code:mt.Code,error:mt})):lt?ft(util$2.error(new Error(ot.statusMessage),{code:""+lt})):lt&&ft(util$2.error(new Error("statusCode error")))}}),rt=function(it){it.TaskId===o&&(tt&&tt.abort&&tt.abort(),e.off("inner-kill-task",rt))};o&&e.on("inner-kill-task",rt)}}var API_MAP$1={getService,putBucket,headBucket,getBucket,deleteBucket,putBucketAcl,getBucketAcl,putBucketCors,getBucketCors,deleteBucketCors,getBucketLocation,getBucketPolicy,putBucketPolicy,deleteBucketPolicy,putBucketTagging,getBucketTagging,deleteBucketTagging,putBucketLifecycle,getBucketLifecycle,deleteBucketLifecycle,putBucketVersioning,getBucketVersioning,putBucketReplication,getBucketReplication,deleteBucketReplication,putBucketWebsite,getBucketWebsite,deleteBucketWebsite,putBucketReferer,getBucketReferer,putBucketDomain,getBucketDomain,deleteBucketDomain,putBucketOrigin,getBucketOrigin,deleteBucketOrigin,putBucketLogging,getBucketLogging,putBucketInventory,getBucketInventory,listBucketInventory,deleteBucketInventory,putBucketAccelerate,getBucketAccelerate,putBucketEncryption,getBucketEncryption,deleteBucketEncryption,getObject,headObject,listObjectVersions,putObject,deleteObject,getObjectAcl,putObjectAcl,optionsObject,putObjectCopy,deleteMultipleObject,restoreObject,putObjectTagging,getObjectTagging,deleteObjectTagging,selectObjectContent,appendObject,uploadPartCopy,multipartInit,multipartUpload,multipartComplete,multipartList,multipartListPart,multipartAbort,request,getObjectUrl,getAuth};function warnOldApi(a,i,e){util$2.each(["Cors","Acl"],function(o){if(a.slice(-o.length)===o){var s=a.slice(0,-o.length)+o.toUpperCase(),c=util$2.apiWrapper(a,i),d=!1;e[s]=function(){!d&&console.warn("warning: cos."+s+" has been deprecated. Please Use cos."+a+" instead."),d=!0,c.apply(this,arguments)}}})}base$1.init=function(a,i){i.transferToTaskMethod(API_MAP$1,"putObject"),util$2.each(API_MAP$1,function(e,o){a.prototype[o]=util$2.apiWrapper(o,e),warnOldApi(o,e,a.prototype)})};var advance$1={},eachLimit=function(a,i,e,o){if(o=o||function(){},!a.length||i<=0)return o();var s=0,c=0,d=0;(function _(){if(s>=a.length)return o();for(;d<i&&c<a.length;)c+=1,d+=1,e(a[c-1],function(b){b?(o(b),o=function(){}):(s+=1,d-=1,s>=a.length?o():_())})})()},retry=function(a,i,e){var o=function(s){i(function(c,d){c&&s<a?o(s+1):e(c,d)})};a<1?e():o(1)},async={eachLimit,retry},async_1=async,session=session$2,Async=async_1,EventProxy=event$1.EventProxy,util$1=util_1;function sliceUploadFile(a,i){var e=this,o=new EventProxy,s=a.TaskId,c=a.Bucket,d=a.Region,_=a.Key,b=a.Body,k=a.ChunkSize||a.SliceSize||e.options.ChunkSize,j=a.AsyncLimit,$=a.StorageClass,_e=a.ServerSideEncryption,et,tt,rt=a.onHashProgress;o.on("error",function(it){if(!!e._isRunningTask(s))return it.UploadId=a.UploadData.UploadId||"",i(it)}),o.on("upload_complete",function(it){var nt=util$1.extend({UploadId:a.UploadData.UploadId||""},it);i(null,nt)}),o.on("upload_slice_complete",function(it){var nt={};util$1.each(a.Headers,function(ot,at){var st=at.toLowerCase();(st.indexOf("x-cos-meta-")===0||st==="pic-operations")&&(nt[at]=ot)}),uploadSliceComplete.call(e,{Bucket:c,Region:d,Key:_,UploadId:it.UploadId,SliceList:it.SliceList,Headers:nt},function(ot,at){if(!!e._isRunningTask(s)){if(session.removeUsing(it.UploadId),ot)return tt(null,!0),o.emit("error",ot);session.removeUploadId.call(e,it.UploadId),tt({loaded:et,total:et},!0),o.emit("upload_complete",at)}})}),o.on("get_upload_data_finish",function(it){var nt=session.getFileId(b,a.ChunkSize,c,_);nt&&session.saveUploadId.call(e,nt,it.UploadId,e.options.UploadIdCacheLimit),session.setUsing(it.UploadId),tt(null,!0),uploadSliceList.call(e,{TaskId:s,Bucket:c,Region:d,Key:_,Body:b,FileSize:et,SliceSize:k,AsyncLimit:j,ServerSideEncryption:_e,UploadData:it,Headers:a.Headers,onProgress:tt},function(ot,at){if(!!e._isRunningTask(s)){if(ot)return tt(null,!0),o.emit("error",ot);o.emit("upload_slice_complete",at)}})}),o.on("get_file_size_finish",function(){if(tt=util$1.throttleOnProgress.call(e,et,a.onProgress),a.UploadData.UploadId)o.emit("get_upload_data_finish",a.UploadData);else{var it=util$1.extend({TaskId:s,Bucket:c,Region:d,Key:_,Headers:a.Headers,StorageClass:$,Body:b,FileSize:et,SliceSize:k,onHashProgress:rt},a);getUploadIdAndPartList.call(e,it,function(nt,ot){if(!!e._isRunningTask(s)){if(nt)return o.emit("error",nt);a.UploadData.UploadId=ot.UploadId,a.UploadData.PartList=ot.PartList,o.emit("get_upload_data_finish",a.UploadData)}})}}),et=a.ContentLength,delete a.ContentLength,!a.Headers&&(a.Headers={}),util$1.each(a.Headers,function(it,nt){nt.toLowerCase()==="content-length"&&delete a.Headers[nt]}),function(){for(var it=[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,5120],nt=1024*1024,ot=0;ot<it.length&&(nt=it[ot]*1024*1024,!(et/nt<=e.options.MaxPartNumber));ot++);a.ChunkSize=a.SliceSize=k=Math.max(k,nt)}(),et===0?(a.Body="",a.ContentLength=0,a.SkipTask=!0,e.putObject(a,i)):o.emit("get_file_size_finish")}function getUploadIdAndPartList(a,i){var e=a.TaskId,o=a.Bucket,s=a.Region,c=a.Key,d=a.StorageClass,_=this,b={},k=a.FileSize,j=a.SliceSize,$=Math.ceil(k/j),_e=0,et=util$1.throttleOnProgress.call(_,k,a.onHashProgress),tt=function(nt,ot){var at=j*(nt-1),st=Math.min(at+j,k),ut=st-at;b[nt]?ot(null,{PartNumber:nt,ETag:b[nt],Size:ut}):util$1.fileSlice(a.Body,at,st,!1,function(ft){util$1.getFileMd5(ft,function(lt,ht){if(lt)return ot(util$1.error(lt));var pt='"'+ht+'"';b[nt]=pt,_e+=ut,et({loaded:_e,total:k}),ot(null,{PartNumber:nt,ETag:pt,Size:ut})})})},rt=function(nt,ot){var at=nt.length;if(at===0)return ot(null,!0);if(at>$)return ot(null,!1);if(at>1){var st=Math.max(nt[0].Size,nt[1].Size);if(st!==j)return ot(null,!1)}var ut=function(ft){if(ft<at){var lt=nt[ft];tt(lt.PartNumber,function(ht,pt){pt&&pt.ETag===lt.ETag&&pt.Size===lt.Size?ut(ft+1):ot(null,!1)})}else ot(null,!0)};ut(0)},it=new EventProxy;it.on("error",function(nt){if(!!_._isRunningTask(e))return i(nt)}),it.on("upload_id_available",function(nt){var ot={},at=[];util$1.each(nt.PartList,function(ft){ot[ft.PartNumber]=ft});for(var st=1;st<=$;st++){var ut=ot[st];ut?(ut.PartNumber=st,ut.Uploaded=!0):ut={PartNumber:st,ETag:null,Uploaded:!1},at.push(ut)}nt.PartList=at,i(null,nt)}),it.on("no_available_upload_id",function(){if(!!_._isRunningTask(e)){var nt=util$1.extend({Bucket:o,Region:s,Key:c,Query:util$1.clone(a.Query),StorageClass:d,Body:a.Body},a),ot=util$1.clone(a.Headers);delete ot["x-cos-mime-limit"],nt.Headers=ot,_.multipartInit(nt,function(at,st){if(!!_._isRunningTask(e)){if(at)return it.emit("error",at);var ut=st.UploadId;if(!ut)return i(util$1.error(new Error("no such upload id")));it.emit("upload_id_available",{UploadId:ut,PartList:[]})}})}}),it.on("has_and_check_upload_id",function(nt){nt=nt.reverse(),Async.eachLimit(nt,1,function(ot,at){if(!!_._isRunningTask(e)){if(session.using[ot]){at();return}wholeMultipartListPart.call(_,{Bucket:o,Region:s,Key:c,UploadId:ot},function(st,ut){if(!!_._isRunningTask(e)){if(st)return session.removeUsing(ot),it.emit("error",st);var ft=ut.PartList;ft.forEach(function(lt){lt.PartNumber*=1,lt.Size*=1,lt.ETag=lt.ETag||""}),rt(ft,function(lt,ht){if(!!_._isRunningTask(e)){if(lt)return it.emit("error",lt);ht?at({UploadId:ot,PartList:ft}):at()}})}})}},function(ot){!_._isRunningTask(e)||(et(null,!0),ot&&ot.UploadId?it.emit("upload_id_available",ot):it.emit("no_available_upload_id"))})}),it.on("seek_local_avail_upload_id",function(nt){var ot=session.getFileId(a.Body,a.ChunkSize,o,c),at=session.getUploadIdList.call(_,ot);if(!ot||!at){it.emit("has_and_check_upload_id",nt);return}var st=function(ut){if(ut>=at.length){it.emit("has_and_check_upload_id",nt);return}var ft=at[ut];if(!util$1.isInArray(nt,ft)){session.removeUploadId.call(_,ft),st(ut+1);return}if(session.using[ft]){st(ut+1);return}wholeMultipartListPart.call(_,{Bucket:o,Region:s,Key:c,UploadId:ft},function(lt,ht){!_._isRunningTask(e)||(lt?(session.removeUploadId.call(_,ft),st(ut+1)):it.emit("upload_id_available",{UploadId:ft,PartList:ht.PartList}))})};st(0)}),it.on("get_remote_upload_id_list",function(){wholeMultipartList.call(_,{Bucket:o,Region:s,Key:c},function(nt,ot){if(!!_._isRunningTask(e)){if(nt)return it.emit("error",nt);var at=util$1.filter(ot.UploadList,function(ft){return ft.Key===c&&(!d||ft.StorageClass.toUpperCase()===d.toUpperCase())}).reverse().map(function(ft){return ft.UploadId||ft.UploadID});if(at.length)it.emit("seek_local_avail_upload_id",at);else{var st=session.getFileId(a.Body,a.ChunkSize,o,c),ut;st&&(ut=session.getUploadIdList.call(_,st))&&util$1.each(ut,function(ft){session.removeUploadId.call(_,ft)}),it.emit("no_available_upload_id")}}})}),it.emit("get_remote_upload_id_list")}function wholeMultipartList(a,i){var e=this,o=[],s={Bucket:a.Bucket,Region:a.Region,Prefix:a.Key},c=function(){e.multipartList(s,function(d,_){if(d)return i(d);o.push.apply(o,_.Upload||[]),_.IsTruncated==="true"?(s.KeyMarker=_.NextKeyMarker,s.UploadIdMarker=_.NextUploadIdMarker,c()):i(null,{UploadList:o})})};c()}function wholeMultipartListPart(a,i){var e=this,o=[],s={Bucket:a.Bucket,Region:a.Region,Key:a.Key,UploadId:a.UploadId},c=function(){e.multipartListPart(s,function(d,_){if(d)return i(d);o.push.apply(o,_.Part||[]),_.IsTruncated==="true"?(s.PartNumberMarker=_.NextPartNumberMarker,c()):i(null,{PartList:o})})};c()}function uploadSliceList(a,i){var e=this,o=a.TaskId,s=a.Bucket,c=a.Region,d=a.Key,_=a.UploadData,b=a.FileSize,k=a.SliceSize,j=Math.min(a.AsyncLimit||e.options.ChunkParallelLimit||1,256),$=a.Body,_e=Math.ceil(b/k),et=0,tt=a.ServerSideEncryption,rt=a.Headers,it=util$1.filter(_.PartList,function(ot){return ot.Uploaded&&(et+=ot.PartNumber>=_e&&b%k||k),!ot.Uploaded}),nt=a.onProgress;Async.eachLimit(it,j,function(ot,at){if(!!e._isRunningTask(o)){var st=ot.PartNumber,ut=Math.min(b,ot.PartNumber*k)-(ot.PartNumber-1)*k,ft=0;uploadSliceItem.call(e,{TaskId:o,Bucket:s,Region:c,Key:d,SliceSize:k,FileSize:b,PartNumber:st,ServerSideEncryption:tt,Body:$,UploadData:_,Headers:rt,onProgress:function(lt){et+=lt.loaded-ft,ft=lt.loaded,nt({loaded:et,total:b})}},function(lt,ht){!e._isRunningTask(o)||(!lt&&!ht.ETag&&(lt='get ETag error, please add "ETag" to CORS ExposeHeader setting.( \u83B7\u53D6ETag\u5931\u8D25\uFF0C\u8BF7\u5728CORS ExposeHeader\u8BBE\u7F6E\u4E2D\u6DFB\u52A0ETag\uFF0C\u8BF7\u53C2\u8003\u6587\u6863\uFF1Ahttps://cloud.tencent.com/document/product/436/13318 )'),lt?et-=ft:(et+=ut-ft,ot.ETag=ht.ETag),nt({loaded:et,total:b}),at(lt||null,ht))})}},function(ot){if(!!e._isRunningTask(o)){if(ot)return i(ot);i(null,{UploadId:_.UploadId,SliceList:_.PartList})}})}function uploadSliceItem(a,i){var e=this,o=a.TaskId,s=a.Bucket,c=a.Region,d=a.Key,_=a.FileSize,b=a.Body,k=a.PartNumber*1,j=a.SliceSize,$=a.ServerSideEncryption,_e=a.UploadData,et=a.Headers||{},tt=e.options.ChunkRetryTimes+1,rt=j*(k-1),it=j,nt=rt+j;nt>_&&(nt=_,it=nt-rt);var ot=["x-cos-traffic-limit","x-cos-mime-limit"],at={};util$1.each(et,function(ut,ft){ot.indexOf(ft)>-1&&(at[ft]=ut)});var st=_e.PartList[k-1];Async.retry(tt,function(ut){!e._isRunningTask(o)||util$1.fileSlice(b,rt,nt,!0,function(ft){e.multipartUpload({TaskId:o,Bucket:s,Region:c,Key:d,ContentLength:it,PartNumber:k,UploadId:_e.UploadId,ServerSideEncryption:$,Body:ft,Headers:at,onProgress:a.onProgress},function(lt,ht){if(!!e._isRunningTask(o))return lt?ut(lt):(st.Uploaded=!0,ut(null,ht))})})},function(ut,ft){if(!!e._isRunningTask(o))return i(ut,ft)})}function uploadSliceComplete(a,i){var e=a.Bucket,o=a.Region,s=a.Key,c=a.UploadId,d=a.SliceList,_=this,b=this.options.ChunkRetryTimes+1,k=a.Headers,j=d.map(function($){return{PartNumber:$.PartNumber,ETag:$.ETag}});Async.retry(b,function($){_.multipartComplete({Bucket:e,Region:o,Key:s,UploadId:c,Parts:j,Headers:k},$)},function($,_e){i($,_e)})}function abortUploadTask(a,i){var e=a.Bucket,o=a.Region,s=a.Key,c=a.UploadId,d=a.Level||"task",_=a.AsyncLimit,b=this,k=new EventProxy;if(k.on("error",function(j){return i(j)}),k.on("get_abort_array",function(j){abortUploadTaskArray.call(b,{Bucket:e,Region:o,Key:s,Headers:a.Headers,AsyncLimit:_,AbortArray:j},i)}),d==="bucket")wholeMultipartList.call(b,{Bucket:e,Region:o},function(j,$){if(j)return i(j);k.emit("get_abort_array",$.UploadList||[])});else if(d==="file"){if(!s)return i(util$1.error(new Error("abort_upload_task_no_key")));wholeMultipartList.call(b,{Bucket:e,Region:o,Key:s},function(j,$){if(j)return i(j);k.emit("get_abort_array",$.UploadList||[])})}else if(d==="task"){if(!c)return i(util$1.error(new Error("abort_upload_task_no_id")));if(!s)return i(util$1.error(new Error("abort_upload_task_no_key")));k.emit("get_abort_array",[{Key:s,UploadId:c}])}else return i(util$1.error(new Error("abort_unknown_level")))}function abortUploadTaskArray(a,i){var e=a.Bucket,o=a.Region,s=a.Key,c=a.AbortArray,d=a.AsyncLimit||1,_=this,b=0,k=new Array(c.length);Async.eachLimit(c,d,function(j,$){var _e=b;if(s&&s!==j.Key){k[_e]={error:{KeyNotMatch:!0}},$(null);return}var et=j.UploadId||j.UploadID;_.multipartAbort({Bucket:e,Region:o,Key:j.Key,Headers:a.Headers,UploadId:et},function(tt){var rt={Bucket:e,Region:o,Key:j.Key,UploadId:et};k[_e]={error:tt,task:rt},$(null)}),b++},function(j){if(j)return i(j);for(var $=[],_e=[],et=0,tt=k.length;et<tt;et++){var rt=k[et];rt.task&&(rt.error?_e.push(rt.task):$.push(rt.task))}return i(null,{successList:$,errorList:_e})})}function uploadFile(a,i){var e=this,o=a.SliceSize===void 0?e.options.SliceSize:a.SliceSize,s=[],c=a.Body,d=c.size||c.length||0,_={TaskId:""};util$1.each(a,function(et,tt){typeof et!="object"&&typeof et!="function"&&(_[tt]=et)});var b=a.onTaskReady,k=function(et){_.TaskId=et,b&&b(et)};a.onTaskReady=k;var j=a.onFileFinish,$=function(et,tt){j&&j(et,tt,_),i&&i(et,tt)},_e=d>o?"sliceUploadFile":"putObject";s.push({api:_e,params:a,callback:$}),e._addTasks(s)}function uploadFiles(a,i){var e=this,o=a.SliceSize===void 0?e.options.SliceSize:a.SliceSize,s=0,c=0,d=util$1.throttleOnProgress.call(e,c,a.onProgress),_=a.files.length,b=a.onFileFinish,k=Array(_),j=function(_e,et,tt){d(null,!0),b&&b(_e,et,tt),k[tt.Index]={options:tt,error:_e,data:et},--_<=0&&i&&i(null,{files:k})},$=[];util$1.each(a.files,function(_e,et){(function(){var tt=_e.Body,rt=tt.size||tt.length||0,it={Index:et,TaskId:""};s+=rt,util$1.each(_e,function(pt,mt){typeof pt!="object"&&typeof pt!="function"&&(it[mt]=pt)});var nt=_e.onTaskReady,ot=function(pt){it.TaskId=pt,nt&&nt(pt)};_e.onTaskReady=ot;var at=0,st=_e.onProgress,ut=function(pt){c=c-at+pt.loaded,at=pt.loaded,st&&st(pt),d({loaded:c,total:s})};_e.onProgress=ut;var ft=_e.onFileFinish,lt=function(pt,mt){ft&&ft(pt,mt),j&&j(pt,mt,it)},ht=rt>o?"sliceUploadFile":"putObject";$.push({api:ht,params:_e,callback:lt})})()}),e._addTasks($)}function sliceCopyFile(a,i){var e=new EventProxy,o=this,s=a.Bucket,c=a.Region,d=a.Key,_=a.CopySource,b=util$1.getSourceParams.call(this,_);if(!b){i(util$1.error(new Error("CopySource format error")));return}var k=b.Bucket,j=b.Region,$=decodeURIComponent(b.Key),_e=a.CopySliceSize===void 0?o.options.CopySliceSize:a.CopySliceSize;_e=Math.max(0,_e);var et=a.CopyChunkSize||this.options.CopyChunkSize,tt=this.options.CopyChunkParallelLimit,rt=0,it,nt;e.on("copy_slice_complete",function(ot){var at={};util$1.each(a.Headers,function(ut,ft){ft.toLowerCase().indexOf("x-cos-meta-")===0&&(at[ft]=ut)});var st=util$1.map(ot.PartList,function(ut){return{PartNumber:ut.PartNumber,ETag:ut.ETag}});o.multipartComplete({Bucket:s,Region:c,Key:d,UploadId:ot.UploadId,Parts:st},function(ut,ft){if(ut)return nt(null,!0),i(ut);nt({loaded:it,total:it},!0),i(null,ft)})}),e.on("get_copy_data_finish",function(ot){Async.eachLimit(ot.PartList,tt,function(at,st){var ut=at.PartNumber,ft=at.CopySourceRange,lt=at.end-at.start;copySliceItem.call(o,{Bucket:s,Region:c,Key:d,CopySource:_,UploadId:ot.UploadId,PartNumber:ut,CopySourceRange:ft},function(ht,pt){if(ht)return st(ht);rt+=lt,nt({loaded:rt,total:it}),at.ETag=pt.ETag,st(ht||null,pt)})},function(at){if(at)return nt(null,!0),i(at);e.emit("copy_slice_complete",ot)})}),e.on("get_file_size_finish",function(ot){(function(){for(var ut=[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,5120],ft=1024*1024,lt=0;lt<ut.length&&(ft=ut[lt]*1024*1024,!(it/ft<=o.options.MaxPartNumber));lt++);a.ChunkSize=et=Math.max(et,ft);for(var ht=Math.ceil(it/et),pt=[],mt=1;mt<=ht;mt++){var dt=(mt-1)*et,gt=mt*et<it?mt*et-1:it-1,_t={PartNumber:mt,start:dt,end:gt,CopySourceRange:"bytes="+dt+"-"+gt};pt.push(_t)}a.PartList=pt})();var at;if(a.Headers["x-cos-metadata-directive"]==="Replaced"?at=a.Headers:at=ot,at["x-cos-storage-class"]=a.Headers["x-cos-storage-class"]||ot["x-cos-storage-class"],at=util$1.clearKey(at),ot["x-cos-storage-class"]==="ARCHIVE"||ot["x-cos-storage-class"]==="DEEP_ARCHIVE"){var st=ot["x-cos-restore"];if(!st||st==='ongoing-request="true"'){i(util$1.error(new Error("Unrestored archive object is not allowed to be copied")));return}}delete at["x-cos-copy-source"],delete at["x-cos-metadata-directive"],delete at["x-cos-copy-source-If-Modified-Since"],delete at["x-cos-copy-source-If-Unmodified-Since"],delete at["x-cos-copy-source-If-Match"],delete at["x-cos-copy-source-If-None-Match"],o.multipartInit({Bucket:s,Region:c,Key:d,Headers:at},function(ut,ft){if(ut)return i(ut);a.UploadId=ft.UploadId,e.emit("get_copy_data_finish",a)})}),o.headObject({Bucket:k,Region:j,Key:$},function(ot,at){if(ot){ot.statusCode&&ot.statusCode===404?i(util$1.error(ot,{ErrorStatus:$+" Not Exist"})):i(ot);return}if(it=a.FileSize=at.headers["content-length"],it===void 0||!it){i(util$1.error(new Error('get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.\uFF08 \u83B7\u53D6Content-Length\u5931\u8D25\uFF0C\u8BF7\u5728CORS ExposeHeader\u8BBE\u7F6E\u4E2D\u6DFB\u52A0Content-Length\uFF0C\u8BF7\u53C2\u8003\u6587\u6863\uFF1Ahttps://cloud.tencent.com/document/product/436/13318 \uFF09')));return}if(nt=util$1.throttleOnProgress.call(o,it,a.onProgress),it<=_e)a.Headers["x-cos-metadata-directive"]||(a.Headers["x-cos-metadata-directive"]="Copy"),o.putObjectCopy(a,function(ft,lt){if(ft)return nt(null,!0),i(ft);nt({loaded:it,total:it},!0),i(ft,lt)});else{var st=at.headers,ut={"Cache-Control":st["cache-control"],"Content-Disposition":st["content-disposition"],"Content-Encoding":st["content-encoding"],"Content-Type":st["content-type"],Expires:st.expires,"x-cos-storage-class":st["x-cos-storage-class"]};util$1.each(st,function(ft,lt){var ht="x-cos-meta-";lt.indexOf(ht)===0&&lt.length>ht.length&&(ut[lt]=ft)}),e.emit("get_file_size_finish",ut)}})}function copySliceItem(a,i){var e=a.TaskId,o=a.Bucket,s=a.Region,c=a.Key,d=a.CopySource,_=a.UploadId,b=a.PartNumber*1,k=a.CopySourceRange,j=this.options.ChunkRetryTimes+1,$=this;Async.retry(j,function(_e){$.uploadPartCopy({TaskId:e,Bucket:o,Region:s,Key:c,CopySource:d,UploadId:_,PartNumber:b,CopySourceRange:k},function(et,tt){_e(et||null,tt)})},function(_e,et){return i(_e,et)})}var API_MAP={sliceUploadFile,abortUploadTask,uploadFile,uploadFiles,sliceCopyFile};advance$1.init=function(a,i){i.transferToTaskMethod(API_MAP,"sliceUploadFile"),util$1.each(API_MAP,function(e,o){a.prototype[o]=util$1.apiWrapper(o,e)})};var util=util_1,event=event$1,task=task$1,base=base$1,advance=advance$1,defaultOptions={AppId:"",SecretId:"",SecretKey:"",SecurityToken:"",ChunkRetryTimes:2,FileParallelLimit:3,ChunkParallelLimit:3,ChunkSize:1024*1024,SliceSize:1024*1024,CopyChunkParallelLimit:20,CopyChunkSize:1024*1024*10,CopySliceSize:1024*1024*10,MaxPartNumber:1e4,ProgressInterval:1e3,Domain:"",ServiceDomain:"",Protocol:"",CompatibilityMode:!1,ForcePathStyle:!1,UseRawKey:!1,Timeout:0,CorrectClockSkew:!0,SystemClockOffset:0,UploadCheckContentMd5:!1,UploadQueueSize:1e4,UploadAddMetaMd5:!1,UploadIdCacheLimit:50,UseAccelerate:!1},COS$1=function(a){this.options=util.extend(util.clone(defaultOptions),a||{}),this.options.FileParallelLimit=Math.max(1,this.options.FileParallelLimit),this.options.ChunkParallelLimit=Math.max(1,this.options.ChunkParallelLimit),this.options.ChunkRetryTimes=Math.max(0,this.options.ChunkRetryTimes),this.options.ChunkSize=Math.max(1024*1024,this.options.ChunkSize),this.options.CopyChunkParallelLimit=Math.max(1,this.options.CopyChunkParallelLimit),this.options.CopyChunkSize=Math.max(1024*1024,this.options.CopyChunkSize),this.options.CopySliceSize=Math.max(0,this.options.CopySliceSize),this.options.MaxPartNumber=Math.max(1024,Math.min(1e4,this.options.MaxPartNumber)),this.options.Timeout=Math.max(0,this.options.Timeout),this.options.AppId&&console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").'),this.options.SecretId&&this.options.SecretId.indexOf(" ")>-1&&(console.error("error: SecretId\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5"),console.error("error: SecretId format is incorrect. Please check")),this.options.SecretKey&&this.options.SecretKey.indexOf(" ")>-1&&(console.error("error: SecretKey\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5"),console.error("error: SecretKey format is incorrect. Please check")),util.isNode()&&(console.warn("warning: cos-js-sdk-v5 \u4E0D\u652F\u6301 nodejs \u73AF\u5883\u4F7F\u7528\uFF0C\u8BF7\u6539\u7528 cos-nodejs-sdk-v5\uFF0C\u53C2\u8003\u6587\u6863\uFF1A https://cloud.tencent.com/document/product/436/8629"),console.warn("warning: cos-js-sdk-v5 does not support nodejs environment. Please use cos-nodejs-sdk-v5 instead. See: https://cloud.tencent.com/document/product/436/8629")),event.init(this),task.init(this)};base.init(COS$1,task);advance.init(COS$1,task);COS$1.util={md5:util.md5,xml2json:util.xml2json,json2xml:util.json2xml};COS$1.getAuthorization=util.getAuth;COS$1.version="1.3.5";var cos=COS$1,COS=cos,cosJsSdkV5=COS;const SERVER_URL="https://cos-auth.xversepro.com/sts",COS_BUCKET="xvbs-1258211750",COS_REGION="ap-guangzhou";var myCos=new cosJsSdkV5({getAuthorization:function(a,i){var e=SERVER_URL,o=new XMLHttpRequest;o.open("GET",e,!0),o.onload=function(s){try{var c=JSON.parse(s.target.responseText),d=c.credentials}catch(_){console.error(_)}if(!c||!d)return console.error(`credentials invalid:
  12502. `+JSON.stringify(c,null,2));i({TmpSecretId:d.tmpSecretId,TmpSecretKey:d.tmpSecretKey,SecurityToken:d.sessionToken,StartTime:c.startTime,ExpiredTime:c.expiredTime})},o.send()}});function uploadStream(a,i){myCos.putObject({Bucket:COS_BUCKET,Region:COS_REGION,Key:a,StorageClass:"STANDARD",Body:i,onProgress:function(e){console.log(JSON.stringify(e))}},function(e,o){console.log(e||o)})}const defaultLogger={info:console.log,debug:console.log,error:console.error,infoAndReportMeasurement:(...a)=>{}};let log$H=defaultLogger,USER_ID="987412365",PAGE_SESSION="aaabbbccc",SERVER_SESSION="cccbbbaaa";const COS_PREFIX="error-bitstreams-auto-uploaded-from-application/",FRAME_COMPOSE_LENGTH=5;class Workers{constructor(i,e){this.rtcp=i,this.cacheSize=0,this.cacheBuffer=new Uint8Array(262144),this.cacheFrameCnt=0,this.startReceiveTime=0,this.cacheFrameComposes=new Array(0),this.cacheSizes=new Array(5).fill(0),this.cacheFrameCnts=new Array(5).fill(-1),this.cacheStartReceiveTimes=new Array(5).fill(0),this.cacheBuffers=[new Uint8Array(262144),new Uint8Array(262144),new Uint8Array(262144),new Uint8Array(262144),new Uint8Array(262144)],this.panoCacheSize=0,this.panoCacheBuffer=new Uint8Array(2097152),this.cachePanoTileID=0,this.receivedMedia=0,this.receivedMedia_worker=0,this.receivedYUV=0,this.receivedEmit=0,this.returnFrames=0,this.lastReturnFrames=0,this.lastReceivedEmit=0,this.mediaBytesReceived=0,this.metaBytesReceived=0,this.noWasmBytesReceived=0,this.rtcBytesReceived=0,this.rtcMessageReceived=0,this.packetsDrop=0,this.framesAwait=0,this.sendOutBuffer=0,this.decodeTimePerFrame=0,this.decodeTimeMaxFrame=0,this.lastRenderTs=0,this.JankTimes=0,this.bigJankTimes=0,this.DecodeJankTimes=0,this.bigDecodeJankTimes=0,this.saveframe=!1,this.SaveMediaStream=!1,this.packetsLost=0,this.showAllReceivedMetadata=!1,this.firstMediaArraval=0,this.firstMediaReceived=!1,this.firstYUVDecoded=0,this.firstRender=0,this.firstYUVReceived=!1,this.reconnectSignal=!1,this.serverFrameSlow=0,this.serverFrameFast=0,this.clientFrameSlow=0,this.clientFrameFast=0,this.lastServerTS=0,this.lastClientTS=0,this.lastSeq=0,this.lastIsPureMeta=!1,this.lastHBPacketTs=0,this.HBPacketInterval=0,this.lastHBPacketSrvSentTs=0,this.HBPacketIntervalSrvSent=0,this.cachedLength=2,this.cachedStreams=new Array(this.cachedLength),this.cachedMetas=new Array(this.cachedLength),this.cachedPtss=new Array(this.cachedLength),this.cachedRender=Array(this.cachedLength).fill(!1),this.cachedResolution=new Array(this.cachedLength),this.getPtr=0,this.setPtr=0,this.receiveIframes=0,this.decodeIframes=0,this.prevSenderTs=-1,this.serverSendTimeArray=new CircularArray(120,!1,[]),this.inPanoMode=!1,this.PanoStatus={x:0,y:0,z:0,tiles:[]},this.DynamicPanoTest=!1,this.PanoMask=new ArrayBuffer(8),this.PanoView=new DataView(this.PanoMask),this.userId_test="",this.PendingMasks=[],this.traceIdMap=new Map,this.responseTimeArray=[],this.processTimeArray=[],this.displayTimeArray=[],this.overallTimeArray=[],this.responseMiss=0,this.processMiss=0,this.displayMiss=0,this.joyStickTraceIdMap=new Map,this.joyStickResponseTimeArray=[],this.joyStickProcessTimeArray=[],this.joyStickDisplayTimeArray=[],this.joyStickOverallTimeArray=[],this.joyStickResponseMiss=0,this.joyStickProcessMiss=0,this.joyStickDisplayMiss=0,this.updateYUVCircular=new CircularArray(120,!1,[]),this.updateDropFrame=0,this.metaParseAraay=[],this.responseMoveMiss=0,this.processMoveMiss=0,this.displayMoveMiss=0,this.MovingTraceId="",this.PendingMovingTraceId="",this.inMovingMode=!1,this.StartMovingTs=0,this.PendingStartMovingTs=0,this.moveEvent="",this.MoveToFrameCnt=0,this.lastIsMoving=0,this.MoveResponseDelay=0,this.MoveProcessDelay=0,this.MoveDisplayDelay=0,this.lastMoveResponseTime=0,this.lastMoveProcessTime=0,this.lastMoveDisplayTime=0,this.moveResponseCircular=new CircularArray(120,!0,[STUCK_STAGE_GOOD,STUCK_STAGE_WELL,STUCK_STAGE_FAIR,STUCK_STAGE_BAD]),this.moveProcessCircular=new CircularArray(120,!0,[STUCK_STAGE_GOOD,STUCK_STAGE_WELL,STUCK_STAGE_FAIR,STUCK_STAGE_BAD]),this.moveDisplayCircular=new CircularArray(120,!0,[STUCK_STAGE_GOOD,STUCK_STAGE_WELL,STUCK_STAGE_FAIR,STUCK_STAGE_BAD]),this.moveStartPts=-1,this.frameServerCircular=new CircularArray(120,!1,[]),this.srvMetaIntervalCircular=new CircularArray(120,!1,[]),this.srvMediaIntervalCircular=new CircularArray(120,!1,[]),this.srvHBMetaIntervalCircular=new CircularArray(120,!1,[]),this.srvHBMetaIntervalSrvSentCircular=new CircularArray(120,!1,[]),this.frameClientCircular=new CircularArray(120,!1,[]),this.unmarshalStreamExecutionArray=new SecondArray,this.receiveYUVExecutionArray=new SecondArray,this.postMessageWaitArray=new SecondArray,this.firstUpdateYUV=!0,this.functionMap=new Map,this.WASM_VERSION="WASM-1.1",this.frameHistory=[],this.getVersion=function(){return DECODER_VERSION},this.downloadBlob=(o,s,c)=>{const d=new Blob([o],{type:c}),_=window.URL.createObjectURL(d);this.downloadURL(_,s),setTimeout(function(){return window.URL.revokeObjectURL(_)},1e3)},this.downloadURL=function(o,s){const c=document.createElement("a");c.href=o,c.download=s,document.body.appendChild(c),c.style.display="none",c.click(),c.remove()},this.Stringify=function(o){let s="";for(let d=0;d<o.length/8192;d++)s+=String.fromCharCode.apply(null,o.slice(d*8192,(d+1)*8192));return s},this._rtcp=i}registerLogger(i){log$H=i}registerFunction(i,e){this.functionMap.set(i,e)}hasFrmCntInCache(i){let e=-1;for(let o=0;o<this.cacheFrameComposes.length;o++)this.cacheFrameComposes[o].frameCnt==i&&(e=o);return e}requestPanoramaTest(i,e,o,s,c){const d=c,_={action_type:16,change_rotation_render_type_action:{render_type:5,player:{position:{x:0,y:0,z:0},angle:{yaw:0,pitch:0,roll:0}},camera:{position:{x:i,y:e,z:o},angle:{yaw:0,pitch:0,roll:0}},client_pano_titles_bitmap:s},trace_id:d,user_id:this.userId_test,packet_id:d};log$H.debug("send data: ",_),this._rtcp.sendData(_)}onRotateInPanoMode(i){const e=i.traceId,o={};o.width=1280,o.height=720,o.horz_fov=92,o.angle={yaw:100,pitch:30};const s=new ArrayBuffer(8),c=new DataView(s);getTilesInView(o,s);const d=s.slice(0);this.PendingMasks.unshift({buffer:d,angle:o.angle}),MaskSetToOne(18,this.PanoView),operateForDataView(c,this.PanoView,c,(_,b)=>_^_&b),this.requestPanoramaTest(0,0,0,[c.getUint8(0),c.getUint8(1),c.getUint8(2),c.getUint8(3),c.getUint8(4),c.getUint8(5),c.getUint8(6),c.getUint8(7)],e)}processMetaWithTraceId(i){for(const e of i.traceIds){if(this.traceIdMap.has(e)){const o=this.traceIdMap.get(e);o!=null&&(o.receiveTime=Date.now(),o.status=1)}if(this.joyStickTraceIdMap.has(e)){const o=this.joyStickTraceIdMap.get(e);o!=null&&(o.receiveTime=Date.now(),o.status=1)}if(e==this.PendingMovingTraceId){this.inMovingMode=!0,this.MovingTraceId=this.PendingMovingTraceId,this.StartMovingTs=this.PendingStartMovingTs,this.PendingMovingTraceId="",this.PendingStartMovingTs=0,log$H.info("MoveTo TraceId match",this.StartMovingTs,Date.now());const o=Date.now();this.lastMoveResponseTime=o,this.lastMoveProcessTime=o,this.lastMoveDisplayTime=o,this.frameServerCircular.clear(),this.frameClientCircular.clear()}}}onTraceId(i,e=this){const o=i.traceId,s=i.timestamp,c=i.event;if(c==="Rotation"){const d={traceId:o,pts:0,startTime:s,receiveTime:0,readyTime:0,displayTime:0,status:0};this.traceIdMap.set(o,d);const _=setTimeout(()=>{if(_&&clearTimeout(_),this.traceIdMap.has(o)){const b=this.traceIdMap.get(o);switch(b==null?void 0:b.status){case 0:{this.responseMiss+=1;break}case 1:{this.processMiss+=1;const k=b.receiveTime-b.startTime;this.responseTimeArray.push(k);break}case 2:{this.displayMiss+=1;const k=b.receiveTime-b.startTime,j=b.readyTime-b.receiveTime;this.responseTimeArray.push(k),this.processTimeArray.push(j);break}case 3:log$H.debug("status is 3")}}},1e3)}else if(c==="Joystick"){const d={traceId:o,pts:0,startTime:s,receiveTime:0,readyTime:0,displayTime:0,status:0};this.joyStickTraceIdMap.set(o,d);const _=setTimeout(()=>{if(_&&clearTimeout(_),this.joyStickTraceIdMap.has(o)){const b=this.joyStickTraceIdMap.get(o);switch(b==null?void 0:b.status){case 0:{this.joyStickResponseMiss+=1;break}case 1:{this.joyStickProcessMiss+=1;const k=b.receiveTime-b.startTime;this.joyStickResponseTimeArray.push(k);break}case 2:{this.joyStickDisplayMiss+=1;const k=b.receiveTime-b.startTime,j=b.readyTime-b.receiveTime;this.joyStickResponseTimeArray.push(k),this.joyStickProcessTimeArray.push(j);break}case 3:log$H.debug("status is 3")}}},1e3)}else c==="MoveTo"?(log$H.info("receive moveto traceId ",o," at timestamp",s),this.PendingMovingTraceId=o,this.PendingStartMovingTs=s,this.moveEvent=c,this.frameServerCircular.clear()):c==="GetOnAirship"||c==="GetOnVehicle"?(log$H.info("receive airship traceId ",o," at timestamp ",s),this.PendingMovingTraceId=o,this.PendingStartMovingTs=s,this.moveEvent=c,this.frameServerCircular.clear()):(c==="GetOffAirship"||c==="GetOffVehicle")&&this.clearMoveArray()}executeFunction(i,e){if(this.functionMap.has(i)){const o=this.functionMap.get(i);o!=null&&o(e)}}UpdateStats(i){var e;(e=this._rtcp.connection)==null||e.getStats(null).then(o=>{o.forEach(s=>{s.type=="data-channel"&&(this.rtcMessageReceived=s.messagesReceived-s.messagesSent,this.rtcBytesReceived=s.bytesReceived)})}),this.receivedMedia_worker=i.data.framesReceived,this.receivedYUV=i.data.framesDecoded,this.receivedEmit=i.data.framesRendered,this.mediaBytesReceived=i.data.mediaBytesReceived,this.metaBytesReceived=i.data.metaBytesReceived,this.packetsLost=i.data.packetsLost,this.packetsDrop=i.data.packetsDrop,this.framesAwait=i.data.framesAwait,this.decodeTimePerFrame=i.data.decodeTimePerFrame,this.decodeTimeMaxFrame=i.data.decodeTimeMaxFrame,this.returnFrames=i.data.framesReturned,this.sendOutBuffer=i.data.sendOutBuffer,this.DecodeJankTimes=i.data.JankTimes,this.bigDecodeJankTimes=i.data.bigJankTimes,this.receiveIframes=i.data.receivedIframe,this.decodeIframes=i.data.decodedIframe}ReceiveDecodeMessage(i){var b;const e=Date.now(),o=e-i.data.postTs;if(this.postMessageWaitArray.add(o),!this.firstYUVReceived){this.firstYUVDecoded=i.data.yuv_ts;const k=this.firstYUVDecoded-this.rtcp.network.room._startTime;log$H.infoAndReportMeasurement({metric:"firstYUVDecodedAt",value:k,group:"joinRoom"}),this.firstRender=Date.now();const j=this.firstYUVDecoded-this.rtcp.network.room._startTime;log$H.infoAndReportMeasurement({metric:"firstRenderAt",value:j,group:"joinRoom"}),this.firstYUVReceived=!0,this.lastRenderTs=Date.now()}!this.cachedRender[this.setPtr]&&this.cachedMetas[this.setPtr]!=null&&(this.cachedStreams[this.setPtr]!=null&&this.cachedStreams[this.setPtr].byteLength!=0&&(i.data.data==null?(this.executeFunction("stream",{stream:this.cachedStreams[this.setPtr],width:this.cachedResolution[this.setPtr].width,height:this.cachedResolution[this.setPtr].height,pts:this.cachedPtss[this.setPtr]}),this.executeFunction("signal",{signal:this.cachedMetas[this.setPtr],pts:this.cachedPtss[this.setPtr],alreadyUpdateYUV:!0})):this.updateDropFrame+=1,this.decoderWorker.postMessage({t:2,frameCnt:this.cachedPtss[this.setPtr],buffer:this.cachedStreams[this.setPtr]},[this.cachedStreams[this.setPtr].buffer])),this.getPtr=(this.getPtr+1)%this.cachedLength);const s=i.data.metadata;if((b=s==null?void 0:s.traceIds)!=null&&b.length)for(const k of s.traceIds){if(this.traceIdMap.has(k)){const j=this.traceIdMap.get(k);j!=null&&(j.readyTime=Date.now(),j.status=2)}if(this.joyStickTraceIdMap.has(k)){const j=this.joyStickTraceIdMap.get(k);j!=null&&(j.readyTime=Date.now(),j.status=2)}}if(i.data.pts==this.moveStartPts&&(this.MoveProcessDelay=Date.now()-this.StartMovingTs),this.userId_test=this.rtcp.network.room.userId,this.inMovingMode){const k=Date.now(),j=k-this.lastMoveProcessTime;this.moveProcessCircular.add(j),this.lastMoveProcessTime=k}const c=this.setPtr;this.cachedStreams[c]=i.data.data,this.cachedMetas[c]=i.data.metadata,this.cachedPtss[c]=i.data.pts,this.cachedRender[c]=!1,this.cachedResolution[c]={width:i.data.width,height:i.data.height},this.setPtr=(this.setPtr+1)%this.cachedLength;const _=Date.now()-e;this.receiveYUVExecutionArray.add(_)}SendCacheFrameInfo(i){var $,_e,et,tt,rt,it,nt;const e=i.data.cachedKey,o=i.data.metadata,s=e,c=o,d=(et=(_e=($=c.newUserStates)==null?void 0:$.find(ot=>ot.userId===this.rtcp.network.room.userId))==null?void 0:_e.playerState)==null?void 0:et.roomTypeId,_=this.rtcp.network.room.skinId,b=(nt=(it=(rt=(tt=c.newUserStates)==null?void 0:tt.find(ot=>ot.userId===this._rtcp.network.room.userId))==null?void 0:rt.playerState)==null?void 0:it.player)==null?void 0:nt.position,k={MsgType:1,FrameCacheMsg:{FrameIndex:s,RoomTypeId:d,SkinID:_,Position:b}};let j="";try{j=JSON.stringify(k)}catch(ot){log$H.error(ot);return}}ReceivePanoramaDecodeMessage(i){log$H.info("Receive Panorama Image in Workers.ts"),MaskSetToOne(i.data.tileId,this.PanoView);let e=0,o;const s=this.PendingMasks.length;for(e=0;e<s;e++){const c=this.PendingMasks[e].buffer,d=new DataView(c),_=new ArrayBuffer(8),b=new DataView(_);if(operateForDataView(this.PanoView,d,b,(k,j)=>j^k&j),IsAll0(b)){o=this.PendingMasks[e].angle;break}}for(let c=e;c<s;c++)this.PendingMasks.pop();this.executeFunction("panorama",{data:i.data.data,metadata:i.data.metadata,tileId:i.data.tileId,finished:!0,matchAngle:o})}enable_decoder_queue_logging(){this.decoderWorker.postMessage({t:100,status:!0})}disable_decoder_queue_logging(){this.decoderWorker.postMessage({t:100,status:!1})}async init(i={width:1280,height:720,userID:"testUserId",pageSession:"pagesession1",serverSession:"serversession1"}){for(let o=0;o<FRAME_COMPOSE_LENGTH;o++){const s={buffer:new Uint8Array(262144),size:0,startReceiveTime:0,serverTime:0,frameCnt:-1};this.cacheFrameComposes.push(s)}USER_ID=i.userID,PAGE_SESSION=i.pageSession,SERVER_SESSION=i.serverSession;const e=new Blob([decoder],{type:"application/javascript"});return this.decoderWorker=new Worker(URL.createObjectURL(e)),this.decoderWorker.postMessage({t:9,url:WASM_URLS[WASM_Version],jitterLength:DECODER_PASSIVE_JITTER}),this.decoderWorker.postMessage({t:1,config:i}),new Promise(o=>{this.decoderWorker.onmessage=s=>{switch(s.data.t){case 0:this.ReceiveDecodeMessage(s);break;case 1:this.UpdateStats(s);break;case 2:o();break;case 3:this.SendCacheFrameInfo(s);break;case 4:{const c=new Date().toISOString(),d=USER_ID+"-"+PAGE_SESSION+"-"+SERVER_SESSION+"-"+c+".264";uploadStream(COS_PREFIX+d,s.data.fileObj);break}case 5:this.executeFunction("signal",{signal:s.data.metadata,pts:-1,alreadyUpdateYUV:!1});break;case 6:log$H.infoAndReportMeasurement(s.data.data),log$H.debug("WASM Ready Cost");break;case 7:this.ReceivePanoramaDecodeMessage(s);break;case 8:{const c={MstType:0};let d="";try{d=JSON.stringify(c)}catch(b){log$H.error(b);return}const _="wasm:"+d;this._rtcp.sendStringData(_);break}case 9:{log$H.info(s.data.printMsg);break}case 10:{log$H.error(s.data.printMsg),this.executeFunction("error",{code:s.data.code,message:s.data.printMsg});break}default:log$H.error("Receive unknown message event from decoder"),log$H.debug(s.data);break}}})}setPageSession(i){PAGE_SESSION=i}UpdateYUV(){var e,o;const i=this.getPtr;if(this.cachedMetas[i]!=null&&!this.cachedRender[i]){const s=Date.now();if(this.firstUpdateYUV){const $=((e=this.cachedStreams[i])==null?void 0:e.byteLength)||0;log$H.infoAndReportMeasurement({metric:"firstUpdateStreamLength",value:$,group:"joinRoom"}),this.firstUpdateYUV=!1}this.cachedStreams[i]!=null&&this.executeFunction("stream",{stream:this.cachedStreams[i],width:this.cachedResolution[i].width,height:this.cachedResolution[i].height,pts:this.cachedPtss[i]});const c=Date.now();this.cachedStreams[i]!=null&&this.decoderWorker.postMessage({t:2,frameCnt:this.cachedPtss[i],buffer:this.cachedStreams[i]},[this.cachedStreams[i].buffer]);const d=Date.now(),_=c-s,b=d-c;(_>33||b>10)&&log$H.debug("[wwwarning] updateYUV takes ",_," ms, postMessage takes ",b," ms for index ",this.cachedPtss[i]),c-this.lastRenderTs>84&&this.JankTimes++,c-this.lastRenderTs>125&&this.bigJankTimes++,this.lastRenderTs=c;const k=c-s;this.updateYUVCircular.add(k);const j=this.cachedMetas[i];if((o=j==null?void 0:j.traceIds)!=null&&o.length)for(const $ of j.traceIds){if(this.traceIdMap.has($)){const _e=this.traceIdMap.get($);if(_e!=null){_e.displayTime=Date.now(),_e.status=3;const et=_e.receiveTime-_e.startTime,tt=_e.readyTime-_e.receiveTime,rt=_e.displayTime-_e.readyTime,it=_e.displayTime-_e.startTime;this.responseTimeArray.push(et),this.processTimeArray.push(tt),this.displayTimeArray.push(rt),this.overallTimeArray.push(it),this.traceIdMap.delete($)}}if(this.joyStickTraceIdMap.has($)){const _e=this.joyStickTraceIdMap.get($);if(_e!=null){_e.displayTime=Date.now(),_e.status=3;const et=_e.receiveTime-_e.startTime,tt=_e.readyTime-_e.receiveTime,rt=_e.displayTime-_e.readyTime,it=_e.displayTime-_e.startTime;this.joyStickResponseTimeArray.push(et),this.joyStickProcessTimeArray.push(tt),this.joyStickDisplayTimeArray.push(rt),this.joyStickOverallTimeArray.push(it),this.joyStickTraceIdMap.delete($)}}}if(this.cachedPtss[i]==this.moveStartPts&&(this.MoveDisplayDelay=Date.now()-this.StartMovingTs),this.inMovingMode){const $=Date.now(),_e=$-this.lastMoveDisplayTime;this.moveDisplayCircular.add(_e),this.lastMoveDisplayTime=$}this.executeFunction("signal",{signal:this.cachedMetas[i],pts:this.cachedPtss[i],alreadyUpdateYUV:!0}),this.cachedRender[i]=!0,this.getPtr=(this.getPtr+1)%this.cachedLength}}unmarshalPano(i){const e=new DataView(i),o=e.getUint32(0);if(o==1723558763)return!0;if(o!=2296221069)return!1;console.log("Receive Pano Message"),e.getUint16(4);const s=e.getUint16(6),c=e.getUint32(8),d=e.getUint32(12),_=e.getUint32(16),b=e.getUint32(20),k=i.byteLength-s;if(k==d){const j=new Uint8Array(i).subarray(s).slice(0,_),_e={data:new Uint8Array(i).subarray(s).slice(_,d),mediaLen:d-_,metadata:j,metaLen:_,tileId:c};this.decoderWorker.postMessage({t:8,data:_e})}else{const j=new Uint8Array(i,s,k);if(this.cachePanoTileID==c){if(this.panoCacheBuffer.set(j,b),this.panoCacheSize+=k,this.panoCacheSize===d){const $=new Uint8Array(this.panoCacheBuffer).slice(0,_),et={data:new Uint8Array(this.panoCacheBuffer).slice(_,d),mediaLen:d-_,metadata:$,metaLen:_,tileId:c};this.decoderWorker.postMessage({t:8,data:et}),this.panoCacheSize=0}}else this.panoCacheBuffer.set(j,b),this.panoCacheSize=k,this.cachePanoTileID=c}return!0}clearMoveArray(){this.MovingTraceId="",this.inMovingMode=!1,this.StartMovingTs=0,this.MoveToFrameCnt=0,this.MoveResponseDelay=0,this.MoveProcessDelay=0,this.MoveDisplayDelay=0,this.moveStartPts=-1,this.moveResponseCircular.clear(),this.moveProcessCircular.clear(),this.moveDisplayCircular.clear(),this.moveEvent=""}getIsMoving(i){let e;if(typeof i.newUserStates!="undefined")for(let o=0;o<i.newUserStates.length;o++){const s=i.newUserStates[o];if(s.userId==this.rtcp.network.room.userId){e=s.renderInfo.isMoving;break}}return e}isHeartBeatPacket(i,e){return new DataView(i).getUint32(0)==2009889916}resetSendTimeDiff(){this.prevSenderTs=0,this.serverSendTimeArray.clear()}calcSendTimeDiff(i){if(this.prevSenderTs==-1){this.prevSenderTs=i;return}const e=i-this.prevSenderTs;this.serverSendTimeArray.add(e),this.prevSenderTs=i}unmarshalStream(i){var lt,ht,pt,mt,dt,gt,_t,yt,Tt,St;const e=Date.now(),o=new DataView(i);if(o.getUint32(0)!=1437227610)return!1;o.getUint16(4);const c=o.getUint16(6),d=o.getUint16(8),_=d,b=o.getUint16(10);let k=!1;b==1&&(k=!0);const j=o.getUint32(12),$=o.getUint32(16),_e=o.getUint32(20),et=o.getUint16(24),tt=o.getUint16(26),rt=o.getUint32(28),it=o.getUint32(c-4),nt=j+$,ot=i.byteLength-c,at=new Uint8Array(i,c,ot);this.calcSendTimeDiff(_e);let st;if(this.inPanoMode&&($>0||et))return log$H.error("Stream Protocal Violation: receive illegal stream in Pano mode"),!0;if(ot===nt){this.receivedMedia++;const At=new Uint8Array(i).subarray(c);_e-this.lastServerTS>60?this.serverFrameSlow++:_e-this.lastServerTS<16&&this.serverFrameFast++;const vt=Date.now();vt-this.lastClientTS>60?this.clientFrameSlow++:vt-this.lastClientTS<16&&this.clientFrameFast++;const Et=$===0,xt=_e-this.lastServerTS;this.lastServerTS!=0&&((d+65536-this.lastSeq)%65536===1&&this.lastIsPureMeta==Et&&(Et?this.srvMetaIntervalCircular.add(xt):this.srvMediaIntervalCircular.add(xt)),this.frameServerCircular.add(xt),this.frameClientCircular.add(vt-this.lastClientTS)),this.lastSeq=d,this.lastIsPureMeta=Et,this.lastServerTS=_e,this.lastClientTS=vt;const bt=At.subarray(0,j),Mt=Date.now(),Rt=JSON.parse(this.Stringify(bt)),Pt=Date.now();this.showAllReceivedMetadata&&console.log(_e,vt,Rt),this.metaParseAraay.push(Pt-Mt),(lt=Rt.traceIds)!=null&&lt.length&&this.processMetaWithTraceId(Rt),$!=0&&this.moveStartPts==-1&&this.inMovingMode&&(this.moveStartPts=d),this.moveStartPts==d&&(this.MoveResponseDelay=Date.now()-this.StartMovingTs,console.log("move response delay: ",d,this.moveStartPts,this.MoveResponseDelay));const It=this.getIsMoving(Rt);if(this.inMovingMode&&It==0&&this.lastIsMoving==1&&this.clearMoveArray(),typeof It!="undefined"&&(this.lastIsMoving=It),this.inMovingMode){const Ct=Date.now(),Ot=Ct-this.lastMoveResponseTime;this.moveResponseCircular.add(Ot),this.lastMoveResponseTime=Ct}(et||tt)&&(st=(dt=(mt=(pt=(ht=Rt.newUserStates)==null?void 0:ht.find(Ct=>Ct.userId===this._rtcp.network.room.userId))==null?void 0:pt.playerState)==null?void 0:mt.player)==null?void 0:dt.position);const Dt={t:0,data:At,mediaLen:$,metaLen:j,metadata:Rt,frameCnt:_,server_ts:_e,isIDR:k,cacheRequest:tt,cached:et,cachedKey:rt,position:st};if(this.inPanoMode)return this.executeFunction("signal",{signal:Rt,pts:-1,alreadyUpdateYUV:!0}),!0;if(this.decoderWorker.postMessage(Dt,[At.buffer]),!this.firstMediaReceived){this.firstMediaArraval=Date.now();const Ct=this.firstMediaArraval-this.rtcp.network.room._startTime;log$H.infoAndReportMeasurement({metric:"firstMediaArravalAt",value:Ct,group:"joinRoom"}),this.firstMediaReceived=!0}}else{const At=this.hasFrmCntInCache(_);if(At!=-1)if(this.cacheFrameComposes[At].buffer.set(at,it),this.cacheFrameComposes[At].size+=ot,this.cacheFrameComposes[At].size===nt){const vt=new Uint8Array(this.cacheFrameComposes[At].buffer).slice(0,nt);this.cacheFrameComposes[At].frameCnt=-1,this.cacheFrameComposes[At].size=0,this.cacheFrameComposes[At].startReceiveTime=0,this.cacheFrameComposes[At].serverTime=0,this.receivedMedia++,_e-this.lastServerTS>60?this.serverFrameSlow++:_e-this.lastServerTS<16&&this.serverFrameFast++;const Et=Date.now();Et-this.lastClientTS>60?this.clientFrameSlow++:Et-this.lastClientTS<16&&this.clientFrameFast++,this.lastServerTS!=0&&(this.frameServerCircular.add(_e-this.lastServerTS),this.frameClientCircular.add(Et-this.lastClientTS)),this.lastServerTS=_e,this.lastClientTS=Et;const xt=vt.subarray(0,j),bt=Date.now(),Mt=JSON.parse(this.Stringify(xt)),Rt=Date.now();this.showAllReceivedMetadata&&console.log(_e,Et,Mt),this.metaParseAraay.push(Rt-bt),(gt=Mt.traceIds)!=null&&gt.length&&this.processMetaWithTraceId(Mt),$!=0&&this.moveStartPts==-1&&this.inMovingMode&&(this.moveStartPts=d),this.moveStartPts==d&&(this.MoveResponseDelay=Date.now()-this.StartMovingTs);const Pt=this.getIsMoving(Mt);if(this.inMovingMode&&Pt==0&&this.lastIsMoving==1&&this.clearMoveArray(),typeof Pt!="undefined"&&(this.lastIsMoving=Pt),this.inMovingMode){const Dt=Date.now(),Ct=Dt-this.lastMoveResponseTime;this.moveResponseCircular.add(Ct),this.lastMoveResponseTime=Dt}(et||tt)&&(st=(St=(Tt=(yt=(_t=Mt.newUserStates)==null?void 0:_t.find(Dt=>Dt.userId===this._rtcp.network.room.userId))==null?void 0:yt.playerState)==null?void 0:Tt.player)==null?void 0:St.position);const It={t:0,data:vt,mediaLen:$,metaLen:j,metadata:Mt,frameCnt:_,server_ts:_e,isIDR:k,cacheRequest:tt,cached:et,cachedKey:rt,position:st};if(this.inPanoMode)return this.executeFunction("signal",{signal:Mt,pts:-1,alreadyUpdateYUV:!0}),!0;if(this.decoderWorker.postMessage(It,[vt.buffer]),!this.firstMediaReceived){this.firstMediaArraval=Date.now();const Dt=this.firstMediaArraval-this.rtcp.network.room._startTime;log$H.infoAndReportMeasurement({metric:"firstMediaArravalAt",value:Dt,group:"joinRoom"}),this.firstMediaReceived=!0}}else this.cacheFrameComposes[At].size>nt&&log$H.debug("I frame exceed, cache size is ",this.cacheSize,", total size is ",nt);else if(At==-1){let vt=this.hasFrmCntInCache(-1);if(vt==-1){let Et=Date.now()+1e18,xt=-1;for(let bt=0;bt<this.cacheFrameComposes.length;bt++)this.cacheFrameComposes[bt].serverTime<Et&&(Et=this.cacheFrameComposes[bt].serverTime,xt=bt);vt=xt}this.cacheFrameComposes[vt].buffer.set(at,it),this.cacheFrameComposes[vt].size=ot,this.cacheFrameComposes[vt].frameCnt=_,this.cacheFrameComposes[vt].startReceiveTime=Date.now(),this.cacheFrameComposes[vt].serverTime=_e}}const ft=Date.now()-e;return this.unmarshalStreamExecutionArray.add(ft),!0}reset(){log$H.debug("Worker reset is called"),this.cacheFrameCnt=0,this.receivedMedia=0,this.reconnectSignal=!0,this.decoderWorker.postMessage({t:4})}dataHandleOff(i){log$H.debug("hhh")}dataHandle(i){this.saveframe&&(this.decoderWorker.postMessage({t:6}),this.saveframe=!1),this.SaveMediaStream&&(this.decoderWorker.postMessage({t:7}),this.SaveMediaStream=!1);const e=new Uint8Array(i);if(e.length>=4&&this.isHeartBeatPacket(e.buffer,e.length)==!0)return;if(e.length>36&&this.unmarshalStream(e.buffer)==!0){this.reconnectSignal&&(this.executeFunction("reconnectedFrame",{}),this.reconnectSignal=!1);return}if(e.length>20&&this.unmarshalPano(e.buffer)==!0)return;this.noWasmBytesReceived+=i.byteLength;const o=JSON.parse(this.Stringify(e));this.executeFunction("signal",{signal:o,pts:-1,alreadyUpdateYUV:!0})}changePanoMode(i){this.inPanoMode=i}uploadDataToServer(){this.DynamicPanoTest==!0&&(this.onRotateInPanoMode({traceId:"b2e1a296-6438-4371-8a31-687beb724ebe"}),this.DynamicPanoTest=!1);function i(gr,lr){return lr==-1&&(lr=0),gr+lr}function e(gr,lr){return Math.max(gr,lr)}const o=this.responseTimeArray.reduce(i,0)/this.responseTimeArray.length||0,s=this.processTimeArray.reduce(i,0)/this.processTimeArray.length||0,c=this.displayTimeArray.reduce(i,0)/this.displayTimeArray.length||0,d=this.overallTimeArray.reduce(i,0)/this.overallTimeArray.length||0,_=this.overallTimeArray.length;this.responseTimeArray=[],this.processTimeArray=[],this.displayTimeArray=[],this.overallTimeArray=[];const b=this.joyStickResponseTimeArray.reduce(i,0)/this.joyStickResponseTimeArray.length||0,k=this.joyStickProcessTimeArray.reduce(i,0)/this.joyStickProcessTimeArray.length||0,j=this.joyStickDisplayTimeArray.reduce(i,0)/this.joyStickDisplayTimeArray.length||0,$=this.joyStickOverallTimeArray.reduce(i,0)/this.joyStickOverallTimeArray.length||0,_e=this.joyStickResponseTimeArray.reduce(e,0),et=this.joyStickProcessTimeArray.reduce(e,0),tt=this.joyStickDisplayTimeArray.reduce(e,0),rt=this.joyStickOverallTimeArray.reduce(e,0);this.joyStickResponseTimeArray=[],this.joyStickProcessTimeArray=[],this.joyStickDisplayTimeArray=[],this.joyStickOverallTimeArray=[];const it=this.moveResponseCircular.getThreshPercent(),nt=it[0],ot=it[1],at=it[2],st=it[3],ut=it[4],ft=ut-st,lt=1-ot/ut||0,ht=[nt,ot-nt,at-ot,st-at,ft],pt=this.moveProcessCircular.getThreshPercent(),mt=pt[0],dt=pt[1],gt=pt[2],_t=pt[3],yt=pt[4],Tt=yt-_t,St=1-dt/yt||0,At=[mt,dt-mt,gt-dt,_t-gt,Tt],vt=this.moveDisplayCircular.getThreshPercent(),Et=vt[0],xt=vt[1],bt=vt[2],Mt=vt[3],Rt=vt[4],Pt=Rt-Mt,It=1-xt/Rt||0,Dt=[Et,xt-Et,bt-xt,Mt-bt,Pt],Ct=Et,Ot=xt-Et,Ft=bt-xt,wt=Mt-bt,Bt=Pt,Ut=this.moveResponseCircular.getAvg(),Vt=this.moveProcessCircular.getAvg(),Gt=this.moveDisplayCircular.getAvg(),Lt=this.moveResponseCircular.getMax(),Ht=this.moveProcessCircular.getMax(),Wt=this.moveDisplayCircular.getMax(),Yt=this.moveResponseCircular.getStandardDeviation(),jt=this.moveProcessCircular.getStandardDeviation(),$t=this.moveDisplayCircular.getStandardDeviation();this.moveResponseCircular.getIncomingAvg(),this.moveProcessCircular.getIncomingAvg(),this.moveDisplayCircular.getIncomingAvg(),this.moveResponseCircular.getIncomingMax(),this.moveProcessCircular.getIncomingMax(),this.moveDisplayCircular.getIncomingMax(),this.moveResponseCircular.clearIncoming(),this.moveProcessCircular.clearIncoming(),this.moveDisplayCircular.clearIncoming();const Qt=this.frameServerCircular.getAvg(),ir=this.frameServerCircular.getMax();this.frameClientCircular.getAvg(),this.frameClientCircular.getMax();const nr=this.metaParseAraay.reduce(i,0)/this.metaParseAraay.length||0,rr=this.metaParseAraay.reduce(e,0);this.metaParseAraay=[];const or=this.unmarshalStreamExecutionArray.getStat(),tr=this.receiveYUVExecutionArray.getStat(),Jt=this.postMessageWaitArray.getStat().max,hr={mediaBytesReceived:this.mediaBytesReceived,metaBytesReceived:this.metaBytesReceived,packetsLost:this.packetsLost,timestamp:Date.now(),frameHeight:1280,frameWidth:720,framesReceived:this.receivedMedia,framesReceivedWorker:this.receivedMedia_worker,framesDecoded:this.receivedYUV,framesEmited:this.receivedEmit,decodeTimePerFrame:this.decodeTimePerFrame,decodeTimeMaxFrame:this.decodeTimeMaxFrame,packetsDrop:this.packetsDrop,framesAwait:this.framesAwait,firstMediaArraval:this.firstMediaArraval,firstYUVDecoded:this.firstYUVDecoded,firstRender:this.firstRender,returnFrames:this.returnFrames,sendOutBuffer:this.sendOutBuffer,maxGraphicTime:this.updateYUVCircular.getMax(),averageGraphicTime:this.updateYUVCircular.getAvg(),jankTimes:this.JankTimes,bigJankTimes:this.bigJankTimes,decodeJankTimes:this.DecodeJankTimes,bigDecodeJankTimes:this.bigDecodeJankTimes,serverFrameSlow:this.serverFrameSlow,serverFrameFast:this.serverFrameFast,clientFrameSlow:this.clientFrameSlow,clientFrameFast:this.clientFrameFast,rtcMessageReceived:this.rtcMessageReceived,rtcBytesReceived:this.rtcBytesReceived-this.noWasmBytesReceived,noWasmBytesReceived:this.noWasmBytesReceived,receiveIframes:this.receiveIframes,decodeIframes:this.decodeIframes,avgResponseTime:o,avgProcessTime:s,avgDisplayTime:c,avgOverallTime:d,overallTimeCount:_,responseMiss:this.responseMiss,processMiss:this.processMiss,displayMiss:this.displayMiss,updateDropFrame:this.updateDropFrame,moveEvent:this.moveEvent,avgResponseMoveDiff:this.moveEvent=="MoveTo"?Ut:0,avgProcessMoveDiff:this.moveEvent=="MoveTo"?Vt:0,avgDisplayMoveDiff:this.moveEvent=="MoveTo"?Gt:0,maxResponseMoveDiff:this.moveEvent=="MoveTo"?Lt:0,maxProcessMoveDiff:this.moveEvent=="MoveTo"?Ht:0,maxDisplayMoveDiff:this.moveEvent=="MoveTo"?Wt:0,moveResponseJank:this.moveEvent=="MoveTo"?lt:0,moveProcessJank:this.moveEvent=="MoveTo"?St:0,moveDisplayJank:this.moveEvent=="MoveTo"?It:0,moveResponseCounts:this.moveEvent=="MoveTo"?ht.toString():"0,0,0,0,0",moveProcessCounts:this.moveEvent=="MoveTo"?At.toString():"0,0,0,0,0",moveDisplayCounts:this.moveEvent=="MoveTo"?Dt.toString():"0,0,0,0,0",MoveDisplayCountGood:this.moveEvent=="MoveTo"?Ct.toString():"0",MoveDisplayCountWell:this.moveEvent=="MoveTo"?Ot.toString():"0",MoveDisplayCountFair:this.moveEvent=="MoveTo"?Ft.toString():"0",MoveDisplayCountBad:this.moveEvent=="MoveTo"?wt.toString():"0",MoveDisplayCountRest:this.moveEvent=="MoveTo"?Bt.toString():"0",moveResponseDelay:this.moveEvent=="MoveTo"?this.MoveResponseDelay:0,moveProcessDelay:this.moveEvent=="MoveTo"?this.MoveProcessDelay:0,moveDisplayDelay:this.moveEvent=="MoveTo"?this.MoveDisplayDelay:0,sdMoveResponseLongTime:Yt,sdMoveProcessLongTime:jt,sdMoveDisplayLongTime:$t,avgResponseFlyDiff:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?Ut:0,avgProcessFlyDiff:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?Vt:0,avgDisplayFlyDiff:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?Gt:0,maxResponseFlyDiff:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?Lt:0,maxProcessFlyDiff:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?Ht:0,maxDisplayFlyDiff:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?Wt:0,flyResponseJank:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?lt:0,flyProcessJank:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?St:0,flyDisplayJank:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?It:0,flyResponseCounts:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?ht.toString():"0,0,0,0,0",flyProcessCounts:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?At.toString():"0,0,0,0,0",flyDisplayCounts:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?Dt.toString():"0,0,0,0,0",flyResponseDelay:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?this.MoveResponseDelay:0,flyProcessDelay:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?this.MoveProcessDelay:0,flyDisplayDelay:this.moveEvent=="GetOnVehicle"||this.moveEvent=="GetOnAirship"?this.MoveDisplayDelay:0,avgMetaParseTime:nr,maxMetaParseTime:rr,avgServerDiff:Qt,maxServerDiff:ir,unmarshalStreamStat:or,receiveYUVStat:tr,maxPostMsgDiff:Jt,streamType:WASM_Version,avgJoyStickResponseTime:b,avgJoyStickProcessTime:k,avgJoyStickDisplayTime:j,avgJoyStickOverallTime:$,maxJoyStickResponseTime:_e,maxJoyStickProcessTime:et,maxJoyStickDisplayTime:tt,maxJoyStickOverallTime:rt};return this.lastReturnFrames=this.returnFrames,this.lastReceivedEmit=this.receivedEmit,hr}}const log$G=new Logger("rtcp");class Rtcp extends EventEmitter{constructor(e){super();ct(this,"connection",null);ct(this,"inputChannel",null);ct(this,"mediaStream");ct(this,"socket");ct(this,"connected",!1);ct(this,"candidates",[]);ct(this,"isAnswered",!1);ct(this,"isFlushing",!1);ct(this,"inputReady",!1);ct(this,"workers");ct(this,"actived",!0);ct(this,"heartbeat");ct(this,"onIcecandidate",e=>{if(e.candidate!=null){const o=JSON.stringify(e.candidate);log$G.debug(`Got ice candidate: ${o}`),this.network.socket.send({id:"ice_candidate",data:btoa(o)})}});ct(this,"onIcecandidateerror",e=>{log$G.error("onicecandidateerror",e.errorCode,e.errorText,e)});ct(this,"onIceStateChange",e=>{switch(e.target.iceGatheringState){case"gathering":log$G.info("ice gathering");break;case"complete":log$G.info("Ice gathering completed")}});ct(this,"onIceConnectionStateChange",()=>{if(!!this.connection)switch(log$G.info(`iceConnectionState: ${this.connection.iceConnectionState}`),this.connection.iceConnectionState){case"connected":{this.connected=!0;break}case"disconnected":{this.connected=!1,this.emit("rtcDisconnected");break}case"failed":{this.emit("rtcDisconnected"),this.connected=!1;break}}});ct(this,"setRemoteDescription",async(e,o)=>{var _,b,k;if(!this.connection)return;const s=JSON.parse(atob(e)),c=new RTCSessionDescription(s);await this.connection.setRemoteDescription(c);const d=await this.connection.createAnswer();if(d.sdp=(_=d.sdp)==null?void 0:_.replace(/(a=fmtp:111 .*)/g,"$1;stereo=1;sprop-stereo=1"),((k=(b=d.sdp)==null?void 0:b.match(/a=mid:1/g))==null?void 0:k.length)==2){const j=d.sdp.lastIndexOf("a=mid:1");d.sdp=d.sdp.slice(0,j)+"a=mid:2"+d.sdp.slice(j+7)}try{await this.connection.setLocalDescription(d)}catch(j){log$G.error("error",j)}this.isAnswered=!0,this.network.rtcp.flushCandidate(),this.network.socket.send({id:"answer",data:btoa(JSON.stringify(d))}),o.srcObject=this.mediaStream});ct(this,"flushCandidate",()=>{this.isFlushing||!this.isAnswered||(this.isFlushing=!0,this.candidates.forEach(e=>{const o=atob(e),s=JSON.parse(o);if(/172\./.test(s.candidate))return;const c=new RTCIceCandidate(s);this.connection&&this.connection.addIceCandidate(c).then(()=>{},d=>{log$G.info("add candidate failed",d)})}),this.isFlushing=!1)});ct(this,"input",e=>{var o;!this.actived||!this.inputChannel||this.inputChannel.readyState==="open"&&((o=this.inputChannel)==null||o.send(e))});this.network=e,this.workers=new Workers(this,new Logger("decode")),this.workers.registerLogger(new Logger("decode")),this.workers.registerFunction("data",o=>{this.emit("data",o)}),this.heartbeat=new Heartbeat({ping:o=>{e.room.actionsHandler.echo(o)},pong(o,s){var c;s&&o>500&&log$G.warn(`high hb value ${o}, traceId:`+s),(c=e.room.stats)==null||c.assign({hb:o})}})}start(){this.connection=new RTCPeerConnection;const e=Date.now();this.connection.ondatachannel=o=>{log$G.info(`ondatachannel: ${o.channel.label}`),this.inputChannel=o.channel,this.inputChannel.onopen=()=>{var s;log$G.info("The input channel has opened, id:",(s=this.inputChannel)==null?void 0:s.id),this.inputReady=!0,this.emit("rtcConnected"),this.network.room.currentNetworkOptions.reconnect||(log$G.infoAndReportMeasurement({metric:"datachannelOpenedAt",startTime:this.network.room._startTime,group:"joinRoom"}),log$G.infoAndReportMeasurement({metric:"datachannelOpenedCost",startTime:e,group:"joinRoom"}))},this.inputChannel.onclose=()=>{var s;return log$G.info("The input channel has closed, id:",(s=this.inputChannel)==null?void 0:s.id)},this.inputChannel.onmessage=s=>{this.workers.dataHandle(s.data)}},this.connection.oniceconnectionstatechange=this.onIceConnectionStateChange,this.connection.onicegatheringstatechange=this.onIceStateChange,this.connection.onicecandidate=this.onIcecandidate,this.connection.onicecandidateerror=this.onIcecandidateerror,this.network.socket.send({id:"init_webrtc",data:JSON.stringify({is_mobile:!0})})}addCandidate(e){e===""?this.network.rtcp.flushCandidate():this.candidates.push(e)}disconnect(){var e,o,s;this.heartbeat.stop(),log$G.info("ready to close datachannel, id",(e=this.inputChannel)==null?void 0:e.id),(o=this.inputChannel)==null||o.close(),(s=this.connection)==null||s.close(),this.connection=null,this.inputChannel=null}sendStringData(e){this.input(e)}sendData(e){let o="";try{o=JSON.stringify(e)}catch(s){log$G.error(s);return}this.input(o)}}class Timeout{constructor(i,e,o=!0){ct(this,"_fn");ct(this,"_delay");ct(this,"_timeout");this._fn=i,this._delay=e,o&&this.start()}get delay(){return this._delay}get isSet(){return!!this._timeout}setDelay(i){this._delay=i}start(){this.isSet||(this._timeout=window.setTimeout(()=>{const i=this._fn;this.clear(),i()},this._delay))}clear(){window.clearTimeout(this._timeout),this._timeout=void 0}reset(){this.clear(),this.start()}}const log$F=new Logger("ws");class Socket extends EventEmitter{constructor(e){super();ct(this,"_ws");ct(this,"_openTimer");ct(this,"connected",!1);ct(this,"_hasTimeout",!1);ct(this,"heartbeat");ct(this,"latency",(e,o)=>this.send({id:"checkLatency",data:JSON.stringify(e),packet_id:o}));ct(this,"send",e=>{if(this.wsNoReady())return;const o=JSON.stringify(e);e.id!=="heartbeat"&&log$F.info("send ws frame",o),this._ws.send(o)});ct(this,"startGame",()=>{const{roomId:e,userId:o,avatarId:s,skinId:c,role:d,avatarComponents:_,versionId:b,rotationRenderType:k,isAllSync:j,nickname:$,avatarScale:_e,appId:et,camera:tt,player:rt,firends:it,syncByEvent:nt,areaName:ot,attitude:at,pathName:st,person:ut,roomTypeId:ft="",syncToOthers:lt,hasAvatar:ht,prioritySync:pt,extra:mt={},removeWhenDisconnected:dt}=this.network.room.currentNetworkOptions;mt.removeWhenDisconnected=dt;const gt={id:"start",room_id:e,user_id:o,trace_id:uuid$1(),data:JSON.stringify({avatar_components:JSON.stringify(_),avatar_id:s,skin_id:c,is_host:d?d=="host":!0,skin_data_version:c!==void 0&&b!==void 0?c+b:void 0,rotation_render_type:k,is_all_sync:j,nick_name:encodeURIComponent($||""),app_id:et,camera:tt,player:rt,person:ut,firends:JSON.stringify(it),sync_by_event:nt,area_name:ot,path_name:st,attitude:at,room_type_id:ft,syncToOthers:lt,hasAvatar:ht,avatarSize:_e,prioritySync:pt,extra:JSON.stringify(mt)})};this.send(gt);const _t=JSON.parse(gt.data);delete _t.token,log$F.infoAndReportMeasurement({metric:"startGame",extra:_t,startTime:Date.now()})});this.network=e,this.heartbeat=new Heartbeat({ping:o=>{var s;if(!this.connected){this.heartbeat.stop(),(s=e.room.stats)==null||s.assign({rtt:0});return}this.send({id:"heartbeat",data:o})},pong(o){var s;(s=e.room.stats)==null||s.assign({rtt:o})}})}get connection(){return this._ws}start(){this._hasTimeout=!1;const e=this.getAddress();log$F.info(`connecting to ${e}`);const o=Date.now();this._ws=new WebSocket(e),this._openTimer=new Timeout(()=>{const s=`Failed to open websocket in ${DEFAULT_OPEN_TIMEOUT_MS} ms`;this._hasTimeout=!0,this.emit("socketClosed",new InitNetworkTimeoutError(s))},DEFAULT_OPEN_TIMEOUT_MS),this._ws.onopen=()=>{var s;(s=this._openTimer)==null||s.clear(),this.connected=!0,this.heartbeat.start(),this.network.room.currentNetworkOptions.reconnect||(log$F.infoAndReportMeasurement({metric:"wsOpenedAt",group:"joinRoom",startTime:this.network.room._startTime}),log$F.infoAndReportMeasurement({metric:"wsOpenedCost",group:"joinRoom",startTime:o}))},this.handleWSEvent()}getAddress(){const{wsServerUrl:e,reconnect:o,sessionId:s,token:c,roomId:d,userId:_,pageSession:b}=this.network.room.currentNetworkOptions,k=this.network.room.skinId;let j=e;o&&(j=j+`?reconnect=true&lastSessionID=${s}`);const $=`userId=${_}&roomId=${d}&pageSession=${b}`+(this.network.room.isHost?`&skinId=${k}`:"")+(c?`&token=${c}`:"");return j=j.indexOf("?")>-1?j+"&"+$:j+"?"+$,j}handleWSEvent(){const e=this._ws;e.addEventListener("error",o=>{this.connected=!1,log$F.error("webscoket error",o),this.emit("socketClosed",new InternalError("connect to address error: "+this.network.room.currentNetworkOptions.wsServerUrl))}),e.addEventListener("close",o=>{this.connected=!1,this._onClose(o)}),e.addEventListener("message",o=>{var d;if(!o||this._hasTimeout||!this.connected)return;let s=null;try{s=JSON.parse(o.data)}catch(_){log$F.error(_);return}if(!s)return;const c=s.id;if(!!c)switch(c!=="heartbeat"&&log$F.info(`receive ws frame: ${o.data}`),c){case"fail":break;case"init":try{const _=(d=JSON.parse(s.data))==null?void 0:d.session_id;reporter.updateBody({serverSession:_})}catch{const b=s.data.slice(-37,-1);reporter.updateBody({serverSession:b})}this.network.rtcp.start();break;case"heartbeat":this.heartbeat.pong(s.data);break;case"offer":this.network.rtcp.setRemoteDescription(s.data,this.network.stream.el);break;case"ice_candidate":this.network.rtcp.addCandidate(s.data);break;case"start":this.emit("gameRoomAvailable",s);break;case"error":try{const{Code:_,Msg:b}=JSON.parse(s.data);if(_){if(_==3003)return this.emit("socketClosed",new TokenExpiredError);if(authenticationErrorCodes.indexOf(_)>-1)return this.emit("socketClosed",new AuthenticationError("\u9274\u6743\u9519\u8BEF:"+b));{const k=getErrorByCode(_);this.emit("socketClosed",new k(b))}}}catch(_){const b=new InternalError("JSON.parse websocket data error: "+s.data);log$F.error(_,b),this.emit("socketClosed",b)}break;case"checkLatency":{const _=s.packet_id,b=s.data.split(",");this.onLatencyCheck({packetId:_,addresses:b});break}default:log$F.warn("unkown ws message type",c,s)}})}onLatencyCheck(e){const o=[...new Set(e.addresses||[])];Promise.all(o.map(s=>({[s]:9999}))).then(s=>{const c=Object.assign({},...s);this.latency(c,e.packetId)})}wsNoReady(){return this._ws.readyState==WebSocket.CLOSED||this._ws.readyState==WebSocket.CLOSING||this._ws.readyState==WebSocket.CONNECTING}prepareReconnect(){this._close({code:WS_CLOSE_RECONNECT,reason:"reconnect"})}_onClose({code:e,reason:o}){this._openTimer&&this._openTimer.clear(),log$F.warn(`ws closed: ${e} `+o),[WS_CLOSE_RECONNECT,WS_CLOSE_NORMAL].includes(e)||this.emit("socketClosed",new InternalError("Websocket error"))}_close({code:e,reason:o}){var s;(s=this._ws)==null||s.close(e,o)}quit(){this._close({code:WS_CLOSE_NORMAL,reason:"quit"})}}const log$E=new Logger("stream");class Stream{constructor(i){ct(this,"el");ct(this,"_streamPlayTimer",null);ct(this,"play",()=>new Promise((i,e)=>{this._streamPlayTimer=new Timeout(()=>{e(new InternalError("Stream play timeout"))},5e3),this.el&&this.el.play().then(()=>{var o;i(),log$E.info("Media can autoplay"),(o=this._streamPlayTimer)==null||o.clear()}).catch(o=>{var s;log$E.error("Media Failed to autoplay"),log$E.error(o),e(new InternalError("Media Failed to autoplay")),(s=this._streamPlayTimer)==null||s.clear()})}));if(!i){this.el=this.createVideoElement();return}this.el=i}createVideoElement(){const i=document.createElement("video");return i.muted=!0,i.autoplay=!1,i.playsInline=!0,i.setAttribute("autostart","false"),i.setAttribute("controls","controls"),i.setAttribute("muted","true"),i.setAttribute("preload","auto"),i.setAttribute("hidden","hidden"),document.body.appendChild(i),i}}const log$D=new Logger("NetworkController"),xr=class extends EventEmitter{constructor(e){super();ct(this,"socket");ct(this,"rtcp");ct(this,"stream");ct(this,"_state","connecting");ct(this,"_networkMonitor");ct(this,"reconnectCount",0);ct(this,"startGame",()=>new Promise((e,o)=>{if(!this.rtcp.connected)return o(new InternalError("Game cannot load. Please refresh"));if(!this.rtcp.inputReady)return o(new InternalError("Game is not ready yet. Please wait"));this.socket.on("gameRoomAvailable",s=>{this.setState("connected"),e(s),this.rtcp.heartbeat.start()}),this.socket.on("socketClosed",s=>{o(s)}),this.socket.startGame()}));this.room=e,this.socket=new Socket(this),this.rtcp=new Rtcp(this),this.stream=new Stream,this._networkMonitor=new NetworkMonitor(()=>{log$D.info("network changed, online:",this._networkMonitor.isOnline),this._state==="disconnected"&&this._networkMonitor.isOnline&&(log$D.info("network back to online, try to reconnect"),this.reconnect())}),checkNetworkQuality(this.room.currentNetworkOptions.wsServerUrl),this._networkMonitor.start(),new VisibilityChangeHandler().subscribe(s=>{var c,d;s?((d=this.room.stats)==null||d.disable(),this.room.pageHideHandler(),log$D.infoAndReportMeasurement({metric:"pageHide",startTime:Date.now()})):((c=this.room.stats)==null||c.enable(),this.room.pageShowHandler(),log$D.infoAndReportMeasurement({metric:"pageShow",startTime:Date.now(),extra:{state:this._state}}),this._state==="disconnected"&&this.reconnect())})}setState(e){this._state!==e&&(this._state==="closed"&&!xr.ALLOW_RECONNECT_AFTER_QUIT||(log$D.info("Set network state to ",e),this._state=e))}async connectAndStart(e){return this.connect(e).then(this.startGame)}async connect(e=!1){return this.room.updateCurrentNetworkOptions({reconnect:e}),new Promise((o,s)=>{this.rtcp.on("rtcConnected",()=>{this.setState("connected"),o()}),this.rtcp.on("rtcDisconnected",()=>{log$D.info("rtc disconnected"),this._state==="connecting"?(this.setState("disconnected"),s(new InternalError("rtc connect failed"))):(this.setState("disconnected"),log$D.info("rtc disconnected, start to reconnect"),this.reconnect())}),this.socket.on("socketQuit",()=>{log$D.info("socket quit success"),this.setState("closed")}),this.socket.on("socketClosed",c=>{this._state==="connecting"&&(this.setState("disconnected"),s(c)),s(c)}),this.socket.start()})}reconnect(){const e=Date.now();if(this.reconnectCount++,this.reconnectCount>MAX_RECONNECT_COUNT){log$D.error("reconnect failed, reached max reconnect count",MAX_RECONNECT_COUNT),this.reconnectCount=0,this.emit("stateChanged",{state:"disconnected"});return}return log$D.info("start reconnect, count:",this.reconnectCount),this._reconnect().then(()=>{log$D.infoAndReportMeasurement({startTime:e,metric:"reconnect"})}).catch(o=>{if(log$D.infoAndReportMeasurement({startTime:e,metric:"reconnect",error:o}),(o==null?void 0:o.code)===Codes.RepeatLogin){this.room.handleRepetLogin();return}const s=1e3;log$D.info("reconnect failed, wait "+s+" ms for next reconnect"),setTimeout(()=>{this.reconnect()},s)})}_reconnect(){return this._state==="closed"?(log$D.warn("connection closed already"),Promise.reject()):this._state==="connecting"?(log$D.warn("connection is already in connecting state"),Promise.reject()):this._state!=="disconnected"?Promise.reject():(this.prepareReconnect(),this._state="connecting",this.emit("stateChanged",{state:"reconnecting",count:this.reconnectCount}),this.socket.off("gameRoomAvailable"),this.socket.off("socketClosed"),this.rtcp.off("rtcDisconnected"),this.rtcp.off("rtcConnected"),this.connectAndStart(!0).then(({session_id:e})=>{this.room.updateCurrentNetworkOptions({sessionId:e}),reporter.updateBody({serverSession:e}),log$D.info("reconnect success"),this.setState("connected"),this.reconnectCount=0,this.emit("stateChanged",{state:"reconnected"})}))}prepareReconnect(){this.rtcp.disconnect(),this.socket.prepareReconnect(),this.prepareReconnectOptions()}prepareReconnectOptions(){const{camera:e,player:o}=this.room.currentClickingState||{};e&&o&&this.room.updateCurrentNetworkOptions({camera:e,player:o})}sendRtcData(e){this.rtcp.sendData(e)}sendSocketData(e){log$D.debug("ws send ->",e),this.socket.send(e)}quit(){const e=uuid$1(),o={action_type:Actions.Exit,trace_id:e,exit_action:{},user_id:this.room.options.userId,packet_id:e};this.setState("closed"),this.socket.quit(),this.sendRtcData(o)}};let NetworkController=xr;ct(NetworkController,"ALLOW_RECONNECT_AFTER_QUIT",!0);let DecodeFunctionTimeList=[],SDKFunctionTimeList=[],EngineFunctionTimeList=[],OtherFunctionTimeList=[],HeavyFunctionList=[];function getSum(a){let i=0;for(let e=0;e<a.length;e++)i+=a[e];return i||0}function getMax(a){let i=0;for(let e=0;e<a.length;e++)i<a[e]&&(i=a[e]);return i}function getFuncStat(){const a={sum:getSum(DecodeFunctionTimeList),max:getMax(DecodeFunctionTimeList)},i={sum:getSum(SDKFunctionTimeList),max:getMax(SDKFunctionTimeList)},e={sum:getSum(EngineFunctionTimeList),max:getMax(EngineFunctionTimeList)},o={sum:getSum(OtherFunctionTimeList),max:getMax(OtherFunctionTimeList)},s=HeavyFunctionList;return DecodeFunctionTimeList=[],SDKFunctionTimeList=[],EngineFunctionTimeList=[],OtherFunctionTimeList=[],HeavyFunctionList=[],{function:s,decode:a,sdk:i,engine:e,other:o}}const SAMPLES_LENGTH=10,log$C=new Logger("stats"),numberFormat=new Intl.NumberFormat(window.navigator.language,{maximumFractionDigits:0});class Stats extends EventEmitter{constructor(e){super();ct(this,"_netInterval",null);ct(this,"_disabled",!1);ct(this,"_aggregatedStats",{});ct(this,"isNetworkGood",!0);ct(this,"_displayElements",{});ct(this,"showStatus",{default:!1,extra:!1});ct(this,"_extraStats",{});ct(this,"_networkSamples",[]);ct(this,"externalStats");ct(this,"constructedTime");ct(this,"_interval");this.room=e,this.constructedTime=Date.now(),this._interval=window.setInterval(()=>{if(this._disabled||!e.joined)return;this.onStats(e.networkController.rtcp.workers.uploadDataToServer());const o=e.signal.getSignalStat(),s=e.sceneManager.engineRunTimeStats,c=s.timeArray_addAvatarToScene.getStat(),d=s.timeArray_loadStaticMesh.getStat(),_=s.timeArray_updateStaticMesh.getStat();this._aggregatedStats.engineCPUSum=c.sum+d.sum+_.sum,this._aggregatedStats.engineCPUMax=Math.max(c.max,d.max,_.max),this._aggregatedStats.sdkSignalPartial=o.partialMax.toString(),this._aggregatedStats.sdkCPUAvg=o.sdkAvg,this._aggregatedStats.sdkCPUMax=o.sdkMax,this._aggregatedStats.sdkBlobSum=o.blobSum,this._aggregatedStats.sdkBlobMax=o.blobMax;const k=getFuncStat().function;let j="<br />";for(let $=0;$<k.length;$++)j+=k[$].name+": "+k[$].time.toFixed(0)+"<br />";this._aggregatedStats.heavyFunc=j},1e3),this._netInterval=window.setInterval(()=>{this.checkNetworkQuality()},DURATION*1e3)}get isShow(){return this.showStatus.default||this.showStatus.extra}isStatsShow(e="default"){return this.showStatus[e]}assign(e){Object.assign(this._extraStats,e),((e==null?void 0:e.hb)||(e==null?void 0:e.rtt))&&this.startStatsNetSamples()}appendExternalStats(e){const o={};if(!e||typeof e!="object"){console.warn("appendExternalStats should be plain object");return}Object.keys(e).forEach(s=>{Object.prototype.hasOwnProperty.call(this._aggregatedStats,s)?console.warn(`${s} is duplicate with internal stats`):o[s]=e[s]}),!(Object.keys(o).length>10)&&(this.externalStats=o)}getRtt(){const e=this._extraStats.rtt;return typeof e!="number"?0:e>999?999:e}enable(){this._disabled=!1}disable(){this._disabled=!0}disableNet(){this._netInterval&&window.clearInterval(this._netInterval)}show(e="default"){this.showStatus[e]=!0,this._render(e)}hide(e="default"){this.showStatus[e]=!1;const o=this._displayElements[e];o&&document.body.removeChild(o),this._displayElements[e]=null}checkNetworkQuality(){if(this._networkSamples.length<SAMPLES_LENGTH||this.room.networkController._state!=="connected")return;const o=this._networkSamples.map($=>this.isNetDelay($,"rtt")),s=this._networkSamples.map($=>this.isNetDelay($,"hb")),c=o.reduce(($,_e)=>$+_e,0),d=s.reduce(($,_e)=>$+_e,0),_=Math.floor(c/this._networkSamples.length)*100,b=Math.floor(d/this._networkSamples.length)*100,k=70;let j=!0;(_>=k||b>=k)&&(j=!1),this.isNetworkGood=j,this.emit("networkQuality",{good:j}),j||this.emit("weakNetwork"),this.isNetworkGood!==j&&log$C.infoAndReportMeasurement({metric:"networkQualityChange",startTime:Date.now(),extra:{msg:this._networkSamples,netDelayRTTValues:c,netDelayHBValues:d,isNetworkGood:j}})}startStatsNetSamples(){const{rtt:e,hb:o}=this._extraStats;if(e||o){const s={rtt:e,hb:o,time:Date.now()};this._networkSamples.unshift(s),this._networkSamples.splice(SAMPLES_LENGTH)}}isNetDelay(e,o){return o==="rtt"?e.rtt>RTT_MAX_VALUE?1:0:o==="hb"&&e.hb>HB_MAX_VALUE?1:0}_render(e){var $,_e,et,tt,rt,it,nt,ot,at,st,ut,ft,lt,ht,pt,mt,dt,gt,_t,yt,Tt,St,At,vt,Et,xt,bt,Mt,Rt,Pt,It,Dt,Ct;if(!this._aggregatedStats)return;const o=[],s=Date.now()-this.constructedTime,c=Math.floor(s/1e3%60),d=Math.floor(s/(1e3*60)%60),_=Math.floor(s/(1e3*60*60)%24),b=_<10?"0"+_.toString():_.toString(),k=d<10?"0"+d:d,j=c<10?"0"+c:c;if(o.push({key:new Date(Math.floor(this._aggregatedStats.timestamp||0)).toLocaleString("en-GB"),value:b+":"+k+":"+j}),o.push({key:"rtt: "+this._extraStats.rtt+" hb: "+this._extraStats.hb,value:"FPS: "+this._extraStats.fps+" avatar: "+(($=this.room._userAvatar)==null?void 0:$.state)}),o.push({key:"SDK: "+Xverse$1.SUB_PACKAGE_VERSION,value:"ENGINE:"+VERSION$2+" uid:"+this._extraStats.userId}),o.push({key:"\u540C\u6B65/\u6709\u6548/\u663E\u793A\u73A9\u5BB6",value:`${this._extraStats.syncUserNum||0}/${this._extraStats.userNum||0}/${this._extraStats.renderedUserNum||0}`}),o.push({key:"media/meta bitrate(kbps)",value:numberFormat.format(this._aggregatedStats.mediaBitrate||0)+"/"+numberFormat.format(this._aggregatedStats.metaBitrate||0)}),o.push({key:":----------------Decoding---------------",value:""}),o.push({key:"-max/avg decodeTime(ms)",value:numberFormat.format(this._aggregatedStats.decodeTimeMaxFrame||0)+"/"+numberFormat.format(this._aggregatedStats.decodeTimePerFrame||0)}),o.push({key:"-frmAwait/Lost/Drop",value:numberFormat.format(this._aggregatedStats.framesAwait||0)+"/"+numberFormat.format(this._aggregatedStats.packetsLost||0)+"/"+numberFormat.format(this._aggregatedStats.packetsDrop||0)+"/"+numberFormat.format(this._aggregatedStats.updateDropFrame)||0}),o.push({key:":----------------FrameLoop-------------",value:""}),o.push({key:"interval(max/avg/>40)",value:(((_e=this._extraStats.maxFrameTime)==null?void 0:_e.toFixed(1))||0)+"/"+(((et=this._extraStats.avgFrameTime)==null?void 0:et.toFixed(0))||0)+"/"+this._extraStats.engineSloppyCnt}),o.push({key:"systemStuck",value:this._extraStats.systemStuckCnt}),o.push({key:"--update",value:(this._aggregatedStats.maxGraphicTime.toFixed(1)||0)+"/"+(((tt=this._aggregatedStats.averageGraphicTime)==null?void 0:tt.toFixed(0))||0)}),o.push({key:"--timeout",value:(((rt=this._extraStats.maxTimeoutTime)==null?void 0:rt.toFixed(1))||0)+"/"+((it=this._extraStats.avgTimeoutTime)==null?void 0:it.toFixed(0))||0}),o.push({key:"--render",value:(((nt=this._extraStats.maxRenderFrameTime)==null?void 0:nt.toFixed(1))||0)+"/"+(((ot=this._extraStats.renderFrameTime)==null?void 0:ot.toFixed(0))||0)}),o.push({key:"---anim/regBR/clip(avg ms)",value:(this._extraStats.animationTime.toFixed(2)||0)+" / "+(this._extraStats.registerBeforeRenderTime.toFixed(2)||0)+" / "+(this._extraStats.meshSelectTime.toFixed(2)||0)}),o.push({key:"---anim/regBR/clip(max ms)",value:(this._extraStats.maxAnimationTime.toFixed(2)||0)+" / "+(this._extraStats.maxRegisterBeforeRenderTime.toFixed(2)||0)+" / "+(this._extraStats.maxMeshSelectTime.toFixed(2)||0)}),o.push({key:"---rTR/drC/regAF(avg ms)",value:(this._extraStats.renderTargetRenderTime.toFixed(2)||0)+" / "+(this._extraStats.drawcallTime.toFixed(2)||0)+" / "+(this._extraStats.registerAfterRenderTime.toFixed(2)||0)}),o.push({key:"---rTR/drC/regAF(max ms)",value:(this._extraStats.maxRenderTargetRenderTime.toFixed(2)||0)+" / "+(this._extraStats.maxDrawcallTime.toFixed(2)||0)+" / "+(this._extraStats.maxRegisterAfterRenderTime.toFixed(2)||0)}),o.push({key:"--tri/drC/pati/bones/anim(Num)",value:(this._extraStats.triangle||0)+" / "+(this._extraStats.drawcall.toFixed(0)||0)+" / "+(this._extraStats.activeParticles.toFixed(0)||0)+" / "+(this._extraStats.activeBones.toFixed(0)||0)+" / "+(this._extraStats.activeAnimation.toFixed(0)||0)}),o.push({key:"--rootN/mesh/geo/tex/mat(Num)",value:(this._extraStats.totalRootNodes.toFixed(0)||0)+" / "+(this._extraStats.totalMeshes.toFixed(0)||0)+" / "+(this._extraStats.totalGeometries.toFixed(0)||0)+" / "+(this._extraStats.totalTextures.toFixed(0)||0)+" / "+(this._extraStats.totalMaterials.toFixed(0)||0)}),o.push({key:"--registerBF/AF(Num)",value:(this._extraStats.registerBeforeCount.toFixed(0)||0)+" / "+(this._extraStats.registerAfterCount.toFixed(0)||0)}),o.push({key:":----------------JoyStick----------------------",value:""}),o.push({key:"Total(avg/max)",value:(((at=this._aggregatedStats.avgJoyStickOverallTime)==null?void 0:at.toFixed(2))||0)+"/"+(((st=this._aggregatedStats.maxJoyStickOverallTime)==null?void 0:st.toFixed(2))||0)}),o.push({key:"--Rsp(avg/max)",value:(((ut=this._aggregatedStats.avgJoyStickResponseTime)==null?void 0:ut.toFixed(1))||0)+"/"+this._aggregatedStats.maxJoyStickResponseTime}),o.push({key:"--Proc(avg/max)",value:(((ft=this._aggregatedStats.avgJoyStickProcessTime)==null?void 0:ft.toFixed(1))||0)+"/"+this._aggregatedStats.maxJoyStickProcessTime}),o.push({key:"--Show(avg/max)",value:(((lt=this._aggregatedStats.avgJoyStickDisplayTime)==null?void 0:lt.toFixed(1))||0)+"/"+this._aggregatedStats.maxJoyStickDisplayTime}),o.push({key:":----------------Rotation-------------------",value:""}),o.push({key:"Total(ms/miss)",value:(((ht=this._aggregatedStats.avgOverallTime)==null?void 0:ht.toFixed(2))||0)+"/"+(this._aggregatedStats.responseMissPs+this._aggregatedStats.processMissPs+this._aggregatedStats.displayMissPs)}),o.push({key:"--rotateRsp",value:(((pt=this._aggregatedStats.avgResponseTime)==null?void 0:pt.toFixed(1))||0)+"/"+this._aggregatedStats.responseMissPs}),o.push({key:"--rotateProc",value:(((mt=this._aggregatedStats.avgProcessTime)==null?void 0:mt.toFixed(1))||0)+"/"+this._aggregatedStats.processMissPs}),o.push({key:"--rotateShow",value:(((dt=this._aggregatedStats.avgDisplayTime)==null?void 0:dt.toFixed(1))||0)+"/"+this._aggregatedStats.displayMissPs}),((gt=this.room._userAvatar)==null?void 0:gt.state)=="moving",o.push({key:":----------------Move----------------------",value:""}),o.push({key:"-startDelay",value:(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.moveResponseDelay||0:this._aggregatedStats.flyResponseDelay||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.moveProcessDelay||0:this._aggregatedStats.flyProcessDelay||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.moveDisplayDelay||0:this._aggregatedStats.flyDisplayDelay||0)}),(((_t=this.room._userAvatar)==null?void 0:_t.state)=="moving"||this._aggregatedStats.moveEvent=="GetOnAirship"||this._aggregatedStats.moveEvent=="GetOnVehicle")&&o.push({key:"-srvInterFrm(max/avg)",value:(this._aggregatedStats.maxServerDiff||0)+"/"+(this._aggregatedStats.avgServerDiff.toFixed(1)||0)}),o.push({key:"-interFrameDelay",value:"(max/avg/jank)"}),o.push({key:"--toDisplay",value:(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.maxDisplayMoveDiff||0:this._aggregatedStats.maxDisplayFlyDiff||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.avgDisplayMoveDiff.toFixed(1)||0:this._aggregatedStats.avgDisplayFlyDiff.toFixed(1)||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?((yt=this._aggregatedStats.moveDisplayJank)==null?void 0:yt.toFixed(3))||0:((Tt=this._aggregatedStats.flyDisplayJank)==null?void 0:Tt.toFixed(3))||0)}),o.push({key:"--received",value:(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.maxResponseMoveDiff||0:this._aggregatedStats.maxResponseFlyDiff||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.avgResponseMoveDiff.toFixed(1)||0:this._aggregatedStats.avgResponseFlyDiff.toFixed(1)||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?((St=this._aggregatedStats.moveResponseJank)==null?void 0:St.toFixed(3))||0:((At=this._aggregatedStats.flyResponseJank)==null?void 0:At.toFixed(3))||0)}),o.push({key:"--decoded",value:(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.maxProcessMoveDiff||0:this._aggregatedStats.maxProcessFlyDiff||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.avgProcessMoveDiff.toFixed(1)||0:this._aggregatedStats.avgProcessFlyDiff.toFixed(1)||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?((vt=this._aggregatedStats.moveProcessJank)==null?void 0:vt.toFixed(3))||0:((Et=this._aggregatedStats.flyProcessJank)==null?void 0:Et.toFixed(3))||0)}),o.push({key:":----------------DevInfo-----------------",value:""}),o.push({key:"sd",value:(this._aggregatedStats.sdMoveResponseLongTime.toFixed(1)||0)+"/"+(this._aggregatedStats.sdMoveProcessLongTime.toFixed(1)||0)+"/"+(this._aggregatedStats.sdMoveDisplayLongTime.toFixed(1)||0)}),o.push({key:"----hardwareInfo",value:this._extraStats.hardwareInfo}),e==="default")this.createAndRender(o,e);else{const Ot=[];Ot.push({key:"rtt: "+this._extraStats.rtt+" hb: "+this._extraStats.hb,value:""}),Ot.push({key:":----------------PerFrame-------------",value:""}),Ot.push({key:"render(max/avg)",value:(((xt=this._extraStats.maxRenderFrameTime)==null?void 0:xt.toFixed(1))||0)+"/"+(((bt=this._extraStats.renderFrameTime)==null?void 0:bt.toFixed(2))||0)}),Ot.push({key:"update(max/avg)",value:(this._aggregatedStats.maxGraphicTime.toFixed(1)||0)+"/"+(((Mt=this._aggregatedStats.averageGraphicTime)==null?void 0:Mt.toFixed(2))||0)}),Ot.push({key:"receive(max/avg)",value:this._aggregatedStats.decodeCPUMax+"/"+((Rt=this._aggregatedStats.decodeCPUAvg)==null?void 0:Rt.toFixed(2))}),Ot.push({key:"handleSignal(max/avg)",value:this._aggregatedStats.sdkCPUMax+"/"+((Pt=this._aggregatedStats.sdkCPUAvg)==null?void 0:Pt.toFixed(2))}),Ot.push({key:":----------------LowFrequent-------------",value:""}),Ot.push({key:"engine(max/sum)",value:this._aggregatedStats.engineCPUMax+"/"+this._aggregatedStats.engineCPUSum}),Ot.push({key:"blob(max/sum)",value:this._aggregatedStats.sdkBlobMax+"/"+this._aggregatedStats.sdkBlobSum}),((It=this.room._userAvatar)==null?void 0:It.state)=="moving",Ot.push({key:":----------------Move----------------------",value:""}),(((Dt=this.room._userAvatar)==null?void 0:Dt.state)=="moving"||this._aggregatedStats.moveEvent=="GetOnAirship"||this._aggregatedStats.moveEvent=="GetOnVehicle")&&Ot.push({key:"-srvInterFrm(max/avg)",value:(this._aggregatedStats.maxServerDiff||0)+"/"+(this._aggregatedStats.avgServerDiff.toFixed(1)||0)}),Ot.push({key:"-interFrameDelay",value:"(max/avg)"}),Ot.push({key:"--received",value:(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.maxResponseMoveDiff||0:this._aggregatedStats.maxResponseFlyDiff||0)+"/"+(this._aggregatedStats.moveEvent=="MoveTo"?this._aggregatedStats.avgResponseMoveDiff.toFixed(1)||0:this._aggregatedStats.avgResponseFlyDiff.toFixed(1)||0)}),Ot.push({key:"postMsg",value:this._aggregatedStats.postMsgMaxTime||0}),Ot.push({key:"timeoutGap",value:((Ct=this._extraStats.maxTimeoutGap)==null?void 0:Ct.toFixed(1))||0}),Ot.push({key:":----------------DevInfo-------------",value:""}),Ot.push({key:"handleSignalPartial",value:this._aggregatedStats.sdkSignalPartial||""}),Ot.push({key:"heavyFunc",value:this._aggregatedStats.heavyFunc||""}),this.createAndRender(Ot,e)}}createAndRender(e,o="default"){if(!this._displayElements[o]){const c=document.createElement("div");this._displayElements[o]=c,c.style.position="absolute",c.style.top="10px",c.style.left="120px",c.style.width="200px",c.style.backgroundColor="rgba(0,0,0,.5)",c.style.color="white",c.style.textAlign="left",c.style.fontSize="8px",c.style.lineHeight="10px",document.body.appendChild(c)}let s="";for(const c of e)s+=`<div><span>${c.key}</span>: <span>${c.value}</span> </div>`;this._displayElements[o].innerHTML=s}onStats(e){var _;if(!e)return;const o={},s=this;s._aggregatedStats||(s._aggregatedStats={}),o.timestamp=e.timestamp,o.mediaBytesReceived=e.mediaBytesReceived,o.metaBytesReceived=e.metaBytesReceived,o.packetsLost=e.packetsLost,o.frameHeight=e.frameHeight,o.frameWidth=e.frameWidth,o.framesReceivedUI=e.framesReceived,o.framesReceived=e.framesReceivedWorker,o.framesDecoded=e.framesDecoded,o.framesEmited=e.framesEmited,o.decodeTimePerFrame=e.decodeTimePerFrame,o.decodeTimeMaxFrame=e.decodeTimeMaxFrame,o.packetsDrop=e.packetsDrop,o.framesAwait=e.framesAwait,o.updateDropFrame=e.updateDropFrame,o.firstMediaArraval=e.firstMediaArraval,o.firstYUVDecoded=e.firstYUVDecoded,o.firstRender=e.firstRender,o.returnFrames=e.returnFrames,o.sendOutBuffer=e.sendOutBuffer,o.averageGraphicTime=e.averageGraphicTime,o.maxGraphicTime=e.maxGraphicTime,o.jankTimes=e.jankTimes,o.bigJankTimes=e.bigJankTimes,o.decodeJankTimes=e.decodeJankTimes,o.bigDecodeJankTimes=e.bigDecodeJankTimes,o.serverFrameFast=e.serverFrameFast,o.serverFrameSlow=e.serverFrameSlow,o.clientFrameFast=e.clientFrameFast,o.clientFrameSlow=e.clientFrameSlow,o.rtcMessageReceived=e.rtcMessageReceived,o.rtcBytesReceived=e.rtcBytesReceived,o.receiveIframes=e.receiveIframes,o.decodeIframes=e.decodeIframes,o.avgResponseTime=e.avgResponseTime,o.avgProcessTime=e.avgProcessTime,o.avgDisplayTime=e.avgDisplayTime,o.avgOverallTime=e.avgOverallTime,o.overallTimeCount=e.overallTimeCount,o.responseMiss=e.responseMiss,o.processMiss=e.processMiss,o.displayMiss=e.displayMiss,o.avgResponseMoveDiff=e.avgResponseMoveDiff,o.avgProcessMoveDiff=e.avgProcessMoveDiff,o.avgDisplayMoveDiff=e.avgDisplayMoveDiff,o.maxResponseMoveDiff=e.maxResponseMoveDiff,o.maxProcessMoveDiff=e.maxProcessMoveDiff,o.maxDisplayMoveDiff=e.maxDisplayMoveDiff,o.moveResponseDelay=e.moveResponseDelay,o.moveProcessDelay=e.moveProcessDelay,o.moveDisplayDelay=e.moveDisplayDelay,o.moveResponseJank=e.moveResponseJank,o.moveProcessJank=e.moveProcessJank,o.moveDisplayJank=e.moveDisplayJank,o.avgMetaParseTime=e.avgMetaParseTime,o.maxMetaParseTime=e.maxMetaParseTime,o.moveResponseCounts=e.moveResponseCounts,o.moveProcessCounts=e.moveProcessCounts,o.moveDisplayCounts=e.moveDisplayCounts,o.MoveDisplayCountGood=e.MoveDisplayCountGood,o.MoveDisplayCountWell=e.MoveDisplayCountWell,o.MoveDisplayCountFair=e.MoveDisplayCountFair,o.MoveDisplayCountBad=e.MoveDisplayCountBad,o.MoveDisplayCountRest=e.MoveDisplayCountRest,o.avgServerDiff=e.avgServerDiff,o.maxServerDiff=e.maxServerDiff,o.avgResponseFlyDiff=e.avgResponseFlyDiff,o.avgProcessFlyDiff=e.avgProcessFlyDiff,o.avgDisplayFlyDiff=e.avgDisplayFlyDiff,o.maxResponseFlyDiff=e.maxResponseFlyDiff,o.maxProcessFlyDiff=e.maxProcessFlyDiff,o.maxDisplayFlyDiff=e.maxDisplayFlyDiff,o.flyResponseCounts=e.flyResponseCounts,o.flyProcessCounts=e.flyProcessCounts,o.flyDisplayCounts=e.flyDisplayCounts,o.flyResponseJank=e.flyResponseJank,o.flyProcessJank=e.flyProcessJank,o.flyDisplayJank=e.flyDisplayJank,o.flyResponseDelay=e.flyResponseDelay,o.flyProcessDelay=e.flyProcessDelay,o.flyDisplayDelay=e.flyDisplayDelay,o.moveEvent=e.moveEvent,o.sdMoveResponseLongTime=e.sdMoveResponseLongTime,o.sdMoveProcessLongTime=e.sdMoveProcessLongTime,o.sdMoveDisplayLongTime=e.sdMoveDisplayLongTime,o.avgJoyStickResponseTime=e.avgJoyStickResponseTime,o.avgJoyStickProcessTime=e.avgJoyStickProcessTime,o.avgJoyStickDisplayTime=e.avgJoyStickDisplayTime,o.avgJoyStickOverallTime=e.avgJoyStickOverallTime,o.maxJoyStickResponseTime=e.maxJoyStickResponseTime,o.maxJoyStickProcessTime=e.maxJoyStickProcessTime,o.maxJoyStickDisplayTime=e.maxJoyStickDisplayTime,o.maxJoyStickOverallTime=e.maxJoyStickOverallTime;const c=e.unmarshalStreamStat,d=e.receiveYUVStat;o.decodeCPUMax=Math.max(c.max,d.max),o.decodeCPUAvg=c.avg+d.avg,o.postMsgMaxTime=e.maxPostMsgDiff,s._aggregatedStats&&s._aggregatedStats.timestamp&&(o.mediaBitrate=8*(o.mediaBytesReceived-s._aggregatedStats.mediaBytesReceived)/1e3,o.mediaBitrate=Math.round(o.mediaBitrate||0),o.metaBitrate=8*(o.metaBytesReceived-s._aggregatedStats.metaBytesReceived)/1e3,o.metaBitrate=Math.round(o.metaBitrate||0),o.rtcMessagePs=o.rtcMessageReceived-s._aggregatedStats.rtcMessageReceived,o.rtcBitrate=8*(o.rtcBytesReceived-s._aggregatedStats.rtcBytesReceived)/1e3,o.rtcBitrate=Math.round(o.rtcBitrate||0),o.framesEmitedPs=o.framesEmited-s._aggregatedStats.framesEmited,o.framesEmitedPs=Math.round(o.framesEmitedPs||0),o.framesReceivedPs=o.framesReceived-s._aggregatedStats.framesReceived,o.framesReceivedPs=Math.round(o.framesReceivedPs||0),o.framesDecodedPs=o.framesDecoded-s._aggregatedStats.framesDecoded,o.framesDecodedPs=Math.round(o.framesDecodedPs||0),o.returnFramesPs=o.returnFrames-s._aggregatedStats.returnFrames,o.returnFramesPs=Math.round(o.returnFramesPs||0),o.responseMissPs=o.responseMiss-s._aggregatedStats.responseMiss,o.processMissPs=o.processMiss-s._aggregatedStats.processMiss,o.displayMissPs=o.displayMiss-s._aggregatedStats.displayMiss,o.returnFrames=e.returnFrames),this.showStatus.default?this._render("default"):this.showStatus.extra&&this._render("extra"),o.registerBeforeRenderTime=this._extraStats.registerBeforeRenderTime,o.registerAfterRenderTime=this._extraStats.registerAfterRenderTime,o.renderTargetRenderTime=this._extraStats.renderTargetRenderTime,o.renderFrameTime=this._extraStats.renderFrameTime,o.maxRenderFrameTime=this._extraStats.maxRenderFrameTime,o.interFrameTime=this._extraStats.interFrameTime,o.animationTime=this._extraStats.animationTime,o.meshSelectTime=this._extraStats.meshSelectTime,o.drawcall=this._extraStats.drawcall,o.drawcallTime=this._extraStats.drawcallTime,o.triangle=this._extraStats.triangle,o.registerAfterCount=this._extraStats.registerAfterCount,o.registerBeforeCount=this._extraStats.registerBeforeCount,o.fps=this._extraStats.fps,o.rtt=this._extraStats.rtt,o.hb=this._extraStats.hb,o.avgFrameTime=this._extraStats.avgFrameTime,o.avgTimeoutTime=this._extraStats.avgTimeoutTime,o.engineSloppyCnt=this._extraStats.engineSloppyCnt,o.systemStuckCnt=this._extraStats.systemStuckCnt,o.avatarState=(_=this.room._userAvatar)==null?void 0:_.state,o.maxFrameTime=this._extraStats.maxFrameTime,o.maxTimeoutTime=this._extraStats.maxTimeoutTime,o.activeParticles=this._extraStats.activeParticles,o.activeBones=this._extraStats.activeBones,o.activeAnimation=this._extraStats.activeAnimation,o.totalRootNodes=this._extraStats.totalRootNodes,o.totalGeometries=this._extraStats.totalGeometries,o.totalMeshes=this._extraStats.totalMeshes,o.totalTextures=this._extraStats.totalTextures,o.totalMaterials=this._extraStats.totalMaterials,o.hardwareInfo=this._extraStats.hardwareInfo,o.maxInterFrameTime=this._extraStats.maxInterFrameTime,o.maxDrawcallTime=this._extraStats.maxDrawcallTime,o.maxMeshSelectTime=this._extraStats.maxMeshSelectTime,o.maxAnimationTime=this._extraStats.maxAnimationTime,o.maxRegisterBeforeRenderTime=this._extraStats.maxRegisterBeforeRenderTime,o.maxRegisterAfterRenderTime=this._extraStats.maxRegisterAfterRenderTime,o.maxRenderTargetRenderTime=this._extraStats.maxRenderTargetRenderTime,this.externalStats&&Object.keys(this.externalStats||{}).forEach(b=>{o[b]=this.externalStats[b]}),s._aggregatedStats=o,this.emit("stats",{stats:o})}}const blobToDataURI$1=async a=>new Promise((i,e)=>{const o=new FileReader;o.readAsDataURL(a),o.onload=function(s){var c;i((c=s.target)==null?void 0:c.result)},o.onerror=function(s){e(s)}}),objectParseFloat=a=>{const i={};return a&&Object.keys(a).forEach(e=>{i[e]=parseFloat(a[e])}),i},log$B=new Logger("model-manager"),sr=class{constructor(i,e){ct(this,"avatarModelList",[]);ct(this,"skinList",[]);ct(this,"applicationConfig");ct(this,"config");ct(this,"appId");ct(this,"releaseId");this.appId=i,this.releaseId=e}static getInstance(i,e){return sr.instance||(sr.instance=new sr(i,e)),sr.instance}static findModels(i,e,o){return i.filter(c=>c.typeName===e&&c.className===o)}static findModel(i,e,o){const s=i.filter(c=>c.typeName===e&&c.className===o)[0];return s||null}async findSkinConfig(i){let e=null;if(e=(this.skinList=await this.getSkinsList()).find(s=>s.id===i),e)return e;{const s=`skin is invalid: skinId: ${i}`;return Promise.reject(new ParamError(s))}}async findRoute(i,e){const s=(await this.findSkinConfig(i)).routeList.find(c=>c.pathName===e);if(!s){const c=`find path failed: skinId: ${i}, pathName: ${e}`;return Promise.reject(new ParamError(c))}return log$B.debug("find route success",s),s}async findAssetList(i){const o=(await this.findSkinConfig(i)).assetList;if(!o){const s=`find path failed: skinId: ${i}`;return Promise.reject(new ParamError(s))}return log$B.debug("find route success",o),o}async findAsset(i,e,o="id"){const s=await this.findSkinConfig(i);if(Array.isArray(e))return e.map(d=>s.models.find(_=>_[o]===d)).filter(Boolean);const c=s.models.find(d=>d[o]===e);if(!c){const d=`find asset failed: skinId: ${i}, keyValue: ${e}`;return Promise.reject(new ParamError(d))}return log$B.debug("find asset success",c),c}async findPoint(i,e){const s=(await this.findSkinConfig(i)).pointList.find(c=>c.id===e);if(!s){const c=`find point failed: skinId: ${i}, id: ${e}`;return Promise.reject(new ParamError(c))}return log$B.debug("find point success",s),s}async requestConfig(){if(this.config)return this.config;let i=`https://static.xverse.cn/console/config/${this.appId}/config.json`;this.releaseId&&(i=`https://static.xverse.cn/console/config/${this.appId}/${this.releaseId}/config.json`),sr.configCdnHost&&(i=i.replace(/(https?:\/\/)(.*?)(\/.*)/g,"$1"+sr.configCdnHost+"$3"));try{const e=await http$1.get({url:`${i}?t=${Date.now()}`,key:"config",timeout:6e3,retry:2}),{config:o,preload:s}=e.data.data||{};if(!o)throw new Error("config data parse error"+e.data);return this.config={config:o,preload:s},log$B.debug("get config success",this.config),this.config}catch(e){return Promise.reject(e)}}async getApplicationConfig(){if(this.applicationConfig)return this.applicationConfig;try{const i=await this.requestConfig();return this.applicationConfig=i.config,this.applicationConfig}catch(i){return Promise.reject(i)}}async getAvatarModelList(){if(this.avatarModelList.length)return this.avatarModelList;try{const{avatars:i}=await this.getApplicationConfig();return this.avatarModelList=i.map(e=>({name:e.name,id:e.id,modelUrl:e.url,url:e.url,gender:e.gender,animations:e.animations,components:e.components})),this.avatarModelList}catch(i){return log$B.error(i),Promise.reject(new InitConfigTimeoutError(i||"getAvatarModelList error"))}}async getSkinsList(){if(this.skinList.length)return this.skinList;try{const{skins:i}=await this.getApplicationConfig();return this.skinList=i.map(e=>{var o;return{name:e.name,dataVersion:e.id+e.versionId,id:e.id,fov:parseInt(e.fov||90),models:e.assetList.map(s=>{const{assetId:c,url:d,thumbnailUrl:_,typeName:b,className:k}=s;return{id:c,modelUrl:d,name:s.name,thumbnailUrl:_,typeName:b,className:k==="\u4F4E\u6A21"?"\u7C97\u6A21":k}}),routeList:(o=e.routeList)==null?void 0:o.map(s=>{const{areaName:c,attitude:d,id:_,pathName:b,step:k,birthPointList:j}=s;return{areaName:c,attitude:d,id:_,pathName:b,step:k,birthPointList:j.map($=>({camera:$.camera&&{position:objectParseFloat($.camera.position),angle:objectParseFloat($.camera.rotation)},player:$.player&&{position:objectParseFloat($.player.position),angle:objectParseFloat($.player.rotation)}}))}}),pointList:e.pointList.map(s=>qt(Kt({},s),{position:objectParseFloat(s.position),rotation:objectParseFloat(s.rotation)})),versionId:e.versionId,isEnable:e.isEnable,assetList:e.assetList,visibleRules:e.visibleRules,animationList:e.animationList,resolution:e.resolution}}),this.skinList}catch(i){return log$B.error(i),Promise.reject(new InitConfigTimeoutError(i||"getSkinsList error"))}}async getBreathPointTextrueList(){return[{url:TEXTURE_URL}]}async findEffectList(i){const o=(await this.findSkinConfig(i)).assetList.filter(s=>s.typeName==="EFFECTS");if(!o){const s=`find effect failed: skinId: ${i}`;return Promise.reject(new ParamError(s))}return log$B.debug("find asset success",o),o}};let ModelManager=sr;ct(ModelManager,"configCdnHost"),ct(ModelManager,"instance");var AssetTypeName=(a=>(a.Config="CONFIG",a.Model="MODEL",a.Vedio="VEDIO",a.Media="MEDIA",a.Effects="EFFECTS",a.Gift="GIFT",a.Textures="TEXTURES",a))(AssetTypeName||{}),AssetClassName=(a=>(a.Effects="\u7279\u6548",a.Tv="TV",a.Lpm="\u7C97\u6A21",a.Reward="\u571F\u8C6A\u699C",a.Env="\u73AF\u5883\u5149",a.Gbq="\u544A\u767D\u5899",a.BreathPoint="\u547C\u5438\u70B9",a.Gifts="\u9001\u793C",a.Panorama="\u5168\u666F\u56FE",a.GiftBubble="\u9001\u793C\u6C14\u6CE1",a.SayBubble="\u804A\u5929\u6C14\u6CE1",a))(AssetClassName||{});function mapLimit(a,i,e){return new Promise((o,s)=>{const c=a.length;let d=i-1,_=0;const b=k=>{k.forEach(j=>{e(j).then(()=>{if(_++,_===c){o();return}d++;const $=a[d];$&&b([$])},$=>{s($)})})};b(a.slice(0,i))})}const log$A=new Logger("preload");class Preload{constructor(i){ct(this,"config");ct(this,"allKeys",[]);ct(this,"oldResourcesDeleted",!1);ct(this,"requests",{simple:{stopped:!0,requests:{}},observer:{stopped:!0,requests:{}},full:{stopped:!0,requests:{}}});this.modelManager=i,this.init(i.appId)}init(i){reporter.updateBody({appId:i})}static getTimeoutBySize(i){return i?i<500*1e3?30*1e3:i<1e3*1e3?60*1e3:100*1e3:100*1e3}async getConfig(i){if(this.config)return this.config;const{preload:e}=await this.modelManager.requestConfig();return e?(this.config=e,Promise.resolve(e)):Promise.reject("no preload config")}async getAllKeys(){if(this.allKeys.length)return this.allKeys;try{const i=await modelTable.getAllKeys()._timeout(3e3,new TimeoutError("db getAllKeys timeout"));return this.allKeys=i,i}catch{const e="preload getAllKeys error";return log$A.error(e),Promise.reject(e)}}stop(i){i==="serverless"&&(i="observer"),this.requests[i].stopped=!0;const e=this.requests[i].requests;Object.keys(e).forEach(o=>{http$1.canceler.removePending(o),delete e[o]})}clearPreload(i){this.requests[i].stopped=!1,this.allKeys=[]}async start(i,e,o){let s=Date.now(),c=0;try{if(i==="serverless"&&(i="observer"),!this.requests[i])return Promise.reject(new ParamError("invalid stage name: "+i));this.clearPreload(i);const d=await this.getConfig(i);let _=[];const b=d.assetUrls.map(et=>et.url);try{_=await this.getAllKeys(),await this.deleteOldResources(b,_)}catch{log$A.error("getAllKeys error, deleting db"),await modelTable.clearDataBase()}const{baseUrls:k,assetUrls:j}=d;let $;switch(i){case"simple":$=k;break;case"observer":$=j;break;case"full":$=j;break;default:$=j}let _e=$.filter(et=>!_.includes(et.url));o&&isFunction(o)&&(_e=_e.filter(o)),c=_e.length,log$A.debug("keysNeedToPreload",_e),log$A.warn("preloadStart",_e.length),_e.length||e&&e($.length,$.length),s=Date.now(),await this._preload(i,_e,e),log$A.infoAndReportMeasurement({tag:i,startTime:s,metric:"assetsPreload",extra:{total:c}});return}catch(d){let _=d;return(this.requests[i].stopped||axios.isCancel(d))&&(_=new PreloadCanceledError),log$A.infoAndReportMeasurement({tag:i,startTime:s,metric:"assetsPreload",extra:{total:c},error:_,reportOptions:{immediate:!0}}),Promise.reject(_)}}async deleteOldResources(i,e){if(!this.oldResourcesDeleted)this.oldResourcesDeleted=!0;else return Promise.resolve();const o=e.filter(c=>!i.includes(c));log$A.debug("keysNeedToDelete",o),log$A.warn("keysNeedToDelete",o.length);const s=Promise.all(o.map(c=>modelTable.delete(c)));try{await s}catch(c){log$A.error("deleteOldResources error",c)}}async _preload(i,e,o){const s=e.length;if(!s)return Promise.resolve();let c=0;const d=window.setInterval(()=>{o&&o(c,s),c>=s&&window.clearInterval(d)},1e3);return mapLimit(e,10,async _=>{const{size:b,url:k}=_;return this.requests[i].stopped?Promise.reject(new PreloadCanceledError):AssetsStorage.requestAndPut({url:k,timeout:Preload.getTimeoutBySize(b),responseType:"blob",retry:2,beforeRequest:()=>{this.requests[i].requests[k]=!0}}).then(()=>{c++,delete this.requests[i].requests[k]},j=>(delete this.requests[i].requests[k],window.clearInterval(d),Promise.reject(j)))})}}let sceneManager;function getSceneManager(a,i){return sceneManager||(sceneManager=new XSceneManager(a,i)),sceneManager}const log$z=new Logger("tv");class TV extends XTelevision{constructor(e,o,s,c){super(s.scene,o,s.sceneManager,c);ct(this,"decal");ct(this,"id");ct(this,"imageUrl");ct(this,"mode","video");ct(this,"room");ct(this,"_isStoped",!1);ct(this,"setVideo",(e,o=!1,s=!0)=>(log$z.warn("setVideo",{isLive:o,fixElement:s,src:e.src}),super.setVideo(e,o,s).then(()=>(this._isStoped=!1,log$z.warn("setVideo Success",{isLive:o,fixElement:s,src:e.src}),this))));this.id=e,this.room=s,this.decal=new XDecalManager(s.sceneManager)}get isStoped(){return this._isStoped}get objectFit(){return this.tvFitMode}set objectFit(e){this.objectFit!==e&&(this.tvFitMode=e,this.getVideoMat()&&this.changeTvFitMode())}show(){this.mode==="video"?this.toggle(!0):this.mode==="poster"&&this.showPoster()}hide(){this.mode==="video"?this.toggle(!1):this.mode==="poster"&&this.hidePoster()}showVideo(){this.mode="video",this.toggle(!0)}hideVideo(){this.toggle(!1)}showPoster(){const e=this.imageUrl;if(!e)return Promise.reject("set poster url before show it");if(!this.decal)return Promise.reject("decal was not found");const o=this.id;return this.decal.addDecal({id:o,meshPath:this.meshPath}).then(()=>{var s;this.mode="poster",(s=this.decal)==null||s.setDecalTexture({id:o,buffer:e}).then(()=>{var c;(c=this.decal)==null||c.toggle(o,!0)})})}setPoster(e){return this.imageUrl=e,this.showPoster()}hidePoster(){return this.decal?this.decal.toggle(this.id,!1):Promise.reject("decal was not found")}async setUrl(e){const o=Date.now(),{url:s,loop:c=!1,muted:d}=e||{};if(log$z.warn("setUrl",{url:s,loop:c,muted:d}),!s)return log$z.error("tv url is required"),Promise.reject("tv url is required");await super.setUrl({url:s,bLoop:c,bMuted:d});const _=this.videoElement;if(!_)return Promise.reject(new InternalError("video element is not found"));_.crossOrigin="anonymous",_.playsInline=!0,_.load(),this.mode="video",this._isStoped=!1;try{await new Promise(b=>{_.oncanplay=()=>{log$z.warn(`setUrl success, video oncanplay within ${(Date.now()-o)/1e3}s`,{url:s,loop:c,muted:d}),this.room.afterSetUrlHook(),_.play(),b(this)}})._timeout(15e3,new InternalError("video oncanplay timeout in 15s"))}catch(b){return log$z.error(b),Promise.reject(b)}return this}stop(){return log$z.warn("tv stop success"),this._isStoped=!0,this.room.afterTvStopedHook(),super.stop()}play(){return this._isStoped=!1,this.room.afterTvPlayedHook(),super.play().then(()=>{log$z.warn("tv play success"),!this.videoElement&&log$z.error("tv play fake success, videoElement is not found")}).catch(e=>(log$z.error("tv play error",e),Promise.reject(e)))}mirrorFrom(e){const o=e.getVideoMat();return this.setSameVideo(o).then(()=>{this.toggle(!0)})}clean(){var e;this.cleanTv(!1,!0),(e=this.decal)==null||e.deleteDecal(this.id)}}const log$y=new Logger("xverse-bus"),_r=class{constructor(i){ct(this,"_tvs",[]);ct(this,"isRenderFirstFrame",!1);ct(this,"_idleTime",0);ct(this,"renderTimer");ct(this,"lightManager");ct(this,"_checkSceneNotReadyCount",0);ct(this,"_checkSceneDurationFrameNum",0);ct(this,"_checkSceneFrameCount",0);ct(this,"timeoutCircularArray",new CircularArray(120,!1,[]));ct(this,"frameCircularArray",new CircularArray(120,!1,[]));ct(this,"interFrameCircularArray",new CircularArray(120,!1,[]));ct(this,"drawCallCntCircularArray",new CircularArray(120,!1,[]));ct(this,"activeFacesCircularArray",new CircularArray(120,!1,[]));ct(this,"renderTimeCircularArray",new CircularArray(120,!1,[]));ct(this,"drawCallTimeCircularArray",new CircularArray(120,!1,[]));ct(this,"animationCircularArray",new CircularArray(120,!1,[]));ct(this,"meshSelectCircularArray",new CircularArray(120,!1,[]));ct(this,"renderTargetCircularArray",new CircularArray(120,!1,[]));ct(this,"regBeforeRenderCircularArray",new CircularArray(120,!1,[]));ct(this,"regAfterRenderCircularArray",new CircularArray(120,!1,[]));ct(this,"renderCnt",0);ct(this,"renderErrorCount",0);ct(this,"engineSloppyCnt",0);ct(this,"systemStuckCnt",0);ct(this,"timeoutSecondArray",new SecondArray);ct(this,"frameRenderNumber",0);ct(this,"_setFPS",(i,e=25)=>{log$y.info("Set fps to",e);const o=e>60?60:e<24?24:e;i.Engine.stopRenderLoop();const s=1e3/o;let c=Date.now(),d=Date.now(),_=s,b=1;const k=()=>{var st;const j=Date.now(),$=j-c,_e=j-d;d=j,this.frameCircularArray.add(_e),$-_>s&&(this.systemStuckCnt+=1),this.timeoutSecondArray.add($-_);const et=$/_;b=.9*b+.1*et;const tt=Date.now();let rt=0,it=0;if(this.room.isUpdatedRawYUVData||this.room.isPano){if(this.isRenderFirstFrame=!0,this._checkSceneDurationFrameNum>0)this._checkSceneFrameCount++,this.room.sceneManager.isReadyToRender({})&&this._checkSceneDurationFrameNum--,this._checkSceneFrameCount>_r._CHECK_DURATION&&(this._checkSceneDurationFrameNum=_r._CHECK_DURATION,this._checkSceneFrameCount=0,this._checkSceneNotReadyCount++,(this._checkSceneNotReadyCount==1||this._checkSceneNotReadyCount%100==0)&&log$y.error(`[SDK] Scene not ready, skip render. loop: ${this._checkSceneNotReadyCount}`),this._checkSceneNotReadyCount>10&&(log$y.error("[SDK] Scene not ready, reload later"),this.room.proxyEvents("renderError",{error:new Error("[SDK] Scene not ready, skip render and reload.")})),this.room.stats.assign({renderErrorCount:this._checkSceneNotReadyCount}),log$y.infoAndReportMeasurement({value:0,startTime:Date.now(),metric:"renderError",error:new Error("[SDK] Scene not ready, skip render and reload."),reportOptions:{sampleRate:.1}}));else try{this.room.allowRender&&i.render()}catch(ut){this.renderErrorCount++,this.renderErrorCount>10&&this.room.proxyEvents("renderError",{error:ut}),this.room.stats.assign({renderErrorCount:this.renderErrorCount}),log$y.infoAndReportMeasurement({value:0,startTime:Date.now(),metric:"renderError",error:ut,reportOptions:{sampleRate:.1}})}rt=Date.now()-tt,this.frameRenderNumber<1e3&&this.frameRenderNumber++,this.room.networkController.rtcp.workers.UpdateYUV(),it=Date.now()-tt-rt}this.isRenderFirstFrame||this.room.networkController.rtcp.workers.UpdateYUV();const ot=Date.now()-tt;c=j+ot,_=Math.min(Math.max((s-ot)/b,5),200),ot>s&&(_=10,this.engineSloppyCnt+=1),this._idleTime=_;const at=_;if(_>150&&console.log("lastGap is ",_,", ratio is ",b,", usedTimeMs is ",ot,", cpuRenderTime is ",rt,", cpuUpdateYUVTime is ",it),this.timeoutCircularArray.add(at),this.renderCnt%25==0){const ut=this.frameCircularArray.getAvg(),ft=this.timeoutCircularArray.getAvg(),lt=this.frameCircularArray.getMax(),ht=this.timeoutCircularArray.getMax();(st=this.room.stats)==null||st.assign({avgFrameTime:ut,avgTimeoutTime:ft,maxFrameTime:lt,maxTimeoutTime:ht,systemStuckCnt:this.systemStuckCnt})}this.renderTimer=window.setTimeout(k,_)};this.renderTimer=window.setTimeout(k,s/b)});ct(this,"updateStats",()=>{var e;const i=this.timeoutSecondArray.getStat();(e=this.room.stats)==null||e.assign({renderFrameTime:this.renderTimeCircularArray.getAvg(),maxRenderFrameTime:this.renderTimeCircularArray.getMax(),interFrameTime:this.interFrameCircularArray.getAvg(),animationTime:this.animationCircularArray.getAvg(),meshSelectTime:this.meshSelectCircularArray.getAvg(),drawcallTime:this.drawCallTimeCircularArray.getAvg(),idleTime:this._idleTime,registerBeforeRenderTime:this.regBeforeRenderCircularArray.getAvg(),registerAfterRenderTime:this.regAfterRenderCircularArray.getAvg(),renderTargetRenderTime:this.renderTargetCircularArray.getAvg(),fps:(1e3/(this.renderTimeCircularArray.getAvg()+this.interFrameCircularArray.getAvg())).toFixed(2),drawcall:this.drawCallCntCircularArray.getAvg(),engineSloppyCnt:this.engineSloppyCnt,maxInterFrameTime:this.interFrameCircularArray.getMax(),maxDrawcallTime:this.drawCallTimeCircularArray.getMax(),maxMeshSelectTime:this.meshSelectCircularArray.getMax(),maxAnimationTime:this.animationCircularArray.getMax(),maxRegisterBeforeRenderTime:this.regBeforeRenderCircularArray.getMax(),maxRegisterAfterRenderTime:this.regAfterRenderCircularArray.getMax(),maxRenderTargetRenderTime:this.renderTargetCircularArray.getMax(),avgFrameTime:this.frameCircularArray.getAvg(),avgTimeoutTime:this.timeoutCircularArray.getAvg(),maxFrameTime:this.frameCircularArray.getMax(),maxTimeoutTime:this.timeoutCircularArray.getMax(),maxTimeoutGap:i.max})});this.room=i}async initEngine(i){var d,_;await this.updateBillboard(),log$y.info("engine version:",VERSION$2);const e=new Logger("engine");e.setLevel(LoggerLevels.Warn);const o={videoResOriArray:[{width:720,height:1280},{width:1280,height:720},{width:480,height:654},{width:654,height:480},{width:1920,height:1080},{width:1080,height:1920},{width:414,height:896}],forceKeepVertical:this.room.options.objectFit!=="cover",panoInfo:{dynamicRange:1,width:4096,height:2048},shaderMode:EShaderMode.videoAndPano,yuvInfo:{width:1280,height:720,fov:i.fov||DEFAULT_MAIN_CAMERA_FOV},cameraParam:{maxZ:1e4},urlTransformer,logger:e,disableWebGL2:this.room.options.disableWebGL2||!1},s=(_=(d=this.room)==null?void 0:d.skin)==null?void 0:_.resolution;s&&(o.videoResOriArray.some(k=>k.width===s.width&&k.height===s.height)||o.videoResOriArray.push(s));const c=this.room.sceneManager=getSceneManager(this.room.canvas,o);this.room.setPictureQualityLevel(this.room.options.pictureQualityLevel||"high"),this.room.sceneManager.staticmeshComponent.setRegionLodRule([2,2,-1,-1,-1]),this.room.scene=c.Scene,this.room.breathPointManager=c.breathPointComponent,this.lightManager=c.lightComponent,this.registerStats(),await this.setEnv(i),await this.room.avatarManager.init(),await this._updateSkinAssets(i.id),this._setFPS(c)}pause(){clearTimeout(this.renderTimer),log$y.info("Invoke room.pause to pause render");const i={roomId:this.room.id,effects:[],lowPolyModels:[],breathPointsConfig:[],skinId:this.room.skinId};return this.loadAssets(i,this.room.skinId)}async resume(){this._setFPS(this.room.sceneManager),this.room.sceneManager.cameraComponent.cameraFovChange(this.room.sceneManager.yuvInfo),log$y.info("Invoke room.resume to render");const i=this._createAssetList(this.room.skin);await this.loadAssets(i,"")}async setEnv(i){var o;this.lightManager||(this.lightManager=this.room.sceneManager.lightComponent),i=i||this.room.skin;const e=ModelManager.findModel(i.models,AssetTypeName.Config,AssetClassName.Env);return e?(o=this.lightManager)==null?void 0:o.setIBL(e.modelUrl):(log$y.error("env file not found"),Promise.resolve())}async _parseModelsAndLoad(i,e,o){log$y.info("Invoke _parseModelsAndLoad start",e);const s=["airship","balloon","default","ground_feiting","ground_reqiqiu"],c=new Map;o==null&&(o="xxxx");let d=!0;for(let k=0;k<i.length;++k){d=!0;for(let j=0;j<s.length;++j)if(i[k].modelUrl.toLowerCase().indexOf(s[j])>=0){const $=c.get(s[j]);$?($.push(i[k]),c.set(s[j],$)):c.set(s[j],[i[k]]),d=!1;break}if(d){const j=c.get("default");j?(j.push(i[k]),c.set("default",j)):c.set("default",[i[k]])}}let _=c.get(e)||[];if(this.room.viewMode==="simple"&&(_=_.filter(k=>!k.modelUrl.endsWith("zip"))),!_)return Promise.reject(`no invalid scene model with group name: ${e}`);const b=[];for(let k=0;k<_.length;++k){const j=_[k];if(j.modelUrl.toLowerCase().endsWith("zip"))j.modelUrl.toLowerCase().endsWith("zip")&&b.push(this.room.sceneManager.addNewLowPolyMesh({url:j.modelUrl,skinInfo:o}));else{const $=e;b.push(this.room.sceneManager.addNewLowPolyMesh({url:j.modelUrl,group:$,pick:!0,skinInfo:o}))}}return Promise.all(b)}async _deleteAssetsLowpolyModel(i){this.room.sceneManager.staticmeshComponent.deleteMeshesBySkinInfo(i),this.room.sceneManager.breathPointComponent.clearBreathPointsBySkinInfo(i),this.room.sceneManager.decalComponent.deleteDecalBySkinInfo(i);const e=[];this.room.sceneManager.Scene.meshes.forEach(o=>{o.xskinInfo==i&&e.push(o)}),e.forEach(o=>{o.dispose(!1,!1)})}async loadLandAssets(){const i=this._createAssetList(this.room.skin);return this.loadAssets(i,this.room.skinId).catch(()=>this.loadAssets(i,this.room.skinId))}async loadAssets(i,e="",o=8e3){const s=Date.now();return this._loadAssets(i,e)._timeout(o,new InitEngineTimeoutError(`loadAssets timeout(${o}ms)`)).then(c=>(log$y.infoAndReportMeasurement({tag:"loadAssets",startTime:s,metric:"loadAssets"}),c)).catch(c=>(log$y.infoAndReportMeasurement({tag:"loadAssets",startTime:s,metric:"loadAssets",error:c}),Promise.reject(c)))}async _loadAssets(i,e=""){try{const o=[];o.push(this._loadAssetsLowpolyModel(i,e)),await Promise.all(o),this._checkSceneDurationFrameNum=_r._CHECK_DURATION,this._checkSceneNotReadyCount=0,this._checkSceneFrameCount=0,this.updateAnimationList()}catch(o){return Promise.reject(o)}}updateAnimationList(){if(this.room.avatarManager&&this.room.avatarManager.xAvatarManager){const i=this.room.skin.animationList;if(!i)return;i.forEach(e=>{this.room.avatarManager.xAvatarManager.updateAnimationLists(e.animations,e.avatarId)})}}async _loadAssetsLowpolyModel(i,e=""){const o=[],s=[],c=[];i.lowPolyModels.forEach($=>{$.group==="TV"?s.push({id:"",name:"",thumbnailUrl:"",typeName:AssetTypeName.Model,className:AssetClassName.Tv,modelUrl:$.url}):$.group==="\u544A\u767D\u5899"?c.push({id:"",name:"",thumbnailUrl:"",typeName:AssetTypeName.Model,className:AssetClassName.Lpm,modelUrl:$.url}):o.push({id:"",name:"",thumbnailUrl:"",typeName:AssetTypeName.Model,className:AssetClassName.Lpm,modelUrl:$.url})}),e!=""&&e!=null&&this._deleteAssetsLowpolyModel(e);const d=i.skinId;log$y.info("====> from ",e," to ",d),this._tvs.forEach($=>$.clean()),this._tvs=[],Array.isArray(s)&&s.forEach(($,_e)=>{this._tvs.push(new TV("squareTv"+_e,$.modelUrl,this.room,{fitMode:EFitMode.cover}))}),i.breathPointsConfig.forEach(async $=>{let _e;try{_e=await urlTransformer($.imageUrl)}catch(et){_e=$.imageUrl,log$y.error("urlTransformer error",et)}this.room.breathPointManager.addBreathPoint({id:$.id,position:$.position,spriteSheet:_e,rotation:$.rotation||{pitch:0,yaw:270,roll:0},billboardMode:!0,type:$.type||"no_type",spriteWidthNumber:$.spriteWidthNum||1,spriteHeightNumber:$.spriteHeightNum||1,maxVisibleRegion:$.maxVisibleRegion||150,width:$.width,height:$.height,skinInfo:$.skinId})}),c.forEach($=>{this.room.sceneManager.decalComponent.addDecal({id:$.id||"gbq",meshPath:$.modelUrl,skinInfo:d})});const b=this.room.sceneManager.staticmeshComponent.lowModel_group,k=Array.from(b.keys()).filter($=>!$.startsWith("region_")),j=["airship","balloon","ground_feiting","ground_reqiqiu","default"];return new Promise(($,_e)=>{Promise.all(j.map(et=>this._parseModelsAndLoad(o,et,d))).then(()=>{let et=!1;o.forEach(it=>{it.modelUrl.endsWith("zip")&&(et=!0)}),et==!1&&this.room.sceneManager.staticmeshComponent.deleteLastRegionMesh(),this.room.sceneManager.staticmeshComponent.lowModel_group;const tt=Array.from(b.keys()).filter(it=>!it.startsWith("region_")),rt=k.filter(it=>tt.indexOf(it)<0);rt.length>0&&rt.forEach(it=>{this.room.sceneManager.staticmeshComponent.deleteMeshesByGroup(it)}),$(!0)}).catch(et=>{_e(et)})})}async _updateSkinAssets(i){const e=this.room.currentState.skinId,o=await this.room.getSkin(i),s=this._createAssetList(o);try{await this.loadAssets(s,e),this.room.updateCurrentState({versionId:o.versionId,skinId:o.id,skin:o})}catch{await this.loadAssets(s,e),this.room.updateCurrentState({versionId:o.versionId,skinId:o.id,skin:o})}const c=this.room.sceneManager.yuvInfo;this.room.sceneManager.changeCameraFovWithShaderUpdate(qt(Kt({},c),{fov:o.fov})),this.room.afterLoadAssetsHook(),await this.setEnv(o)}_createAssetList(i){const e=[],o=[],s=[];let c=i.models;const d=this.room.modelManager.config.preload;return this.room.viewMode==="simple"?d&&(c=d.baseUrls.map(b=>(b.modelUrl=b.url,b))):this.room.viewMode,ModelManager.findModels(c,AssetTypeName.Effects,AssetClassName.Effects).forEach(b=>{e.push({url:b.modelUrl,group:b.className,name:b.name})}),ModelManager.findModels(c,AssetTypeName.Model,AssetClassName.Lpm).forEach(b=>{o.push({url:b.modelUrl,group:b.className})}),ModelManager.findModels(c,AssetTypeName.Model,AssetClassName.Gbq).forEach(b=>{o.push({url:b.modelUrl,group:b.className})}),ModelManager.findModels(c,AssetTypeName.Model,AssetClassName.Tv).forEach(b=>{o.push({url:b.modelUrl,group:b.className})}),[].forEach(b=>{b.skinId==i.id&&s.push(b)}),{roomId:this.room.id,effects:e,lowPolyModels:o,breathPointsConfig:s,skinId:i.id}}registerStats(){const i=this.room.sceneManager;this.room.scene.registerAfterRender(()=>{var gt;const e=i.statisticComponent.getInterFrameTimeCounter(),o=i.statisticComponent.getDrawCall(),s=i.statisticComponent.getActiveFaces(),c=i.statisticComponent.getFrameTimeCounter(),d=i.statisticComponent.getDrawCallTime(),_=i.statisticComponent.getAnimationTime(),b=i.statisticComponent.getActiveMeshEvaluationTime(),k=i.statisticComponent.getRenderTargetRenderTime(),j=i.statisticComponent.getRegisterBeforeRenderTime(),$=i.statisticComponent.getRegisterAfterRenderTime(),_e=i.statisticComponent.getActiveParticles(),et=i.statisticComponent.getActiveBones(),tt=i.Scene._activeAnimatables.length,rt=i.statisticComponent.getTotalRootNodes(),it=i.Scene.geometries.length,nt=i.Scene.onBeforeRenderObservable.observers.length,ot=i.Scene.onAfterRenderObservable.observers.length,at=i.statisticComponent.getTotalMeshes(),st=i.statisticComponent.getTotalTextures(),ut=i.statisticComponent.getTotalMaterials(),ft=i.statisticComponent.getSystemInfo(),lt=ft.resolution,ht=ft.driver;ft.vender;const pt=ft.version,mt=ft.hardwareScalingLevel,dt=lt+"_"+ht+"_"+pt+"_"+mt;this.interFrameCircularArray.add(e),this.renderTimeCircularArray.add(c),this.animationCircularArray.add(_),this.meshSelectCircularArray.add(b),this.drawCallTimeCircularArray.add(d),this.regAfterRenderCircularArray.add($),this.regBeforeRenderCircularArray.add(j),this.renderTargetCircularArray.add(k),this.drawCallCntCircularArray.add(o),this.renderCnt+=1,this.renderCnt%25==0&&((gt=this.room.stats)==null||gt.assign({renderFrameTime:this.renderTimeCircularArray.getAvg(),maxRenderFrameTime:this.renderTimeCircularArray.getMax(),interFrameTime:this.interFrameCircularArray.getAvg(),animationTime:this.animationCircularArray.getAvg(),meshSelectTime:this.meshSelectCircularArray.getAvg(),drawcallTime:this.drawCallTimeCircularArray.getAvg(),idleTime:this._idleTime,registerBeforeRenderTime:this.regBeforeRenderCircularArray.getAvg(),registerAfterRenderTime:this.regAfterRenderCircularArray.getAvg(),renderTargetRenderTime:this.renderTargetCircularArray.getAvg(),fps:(1e3/(this.renderTimeCircularArray.getAvg()+this.interFrameCircularArray.getAvg())).toFixed(2),drawcall:this.drawCallCntCircularArray.getAvg(),triangle:s.toString(),engineSloppyCnt:this.engineSloppyCnt,maxInterFrameTime:this.interFrameCircularArray.getMax(),maxDrawcallTime:this.drawCallTimeCircularArray.getMax(),maxMeshSelectTime:this.meshSelectCircularArray.getMax(),maxAnimationTime:this.animationCircularArray.getMax(),maxRegisterBeforeRenderTime:this.regBeforeRenderCircularArray.getMax(),maxRegisterAfterRenderTime:this.regAfterRenderCircularArray.getMax(),maxRenderTargetRenderTime:this.renderTargetCircularArray.getMax(),activeParticles:_e,activeBones:et,activeAnimation:tt,totalMeshes:at,totalRootNodes:rt,totalGeometries:it,totalTextures:st,totalMaterials:ut,registerBeforeCount:nt,registerAfterCount:ot,hardwareInfo:dt}))})}async updateBillboard(){const{options:{skinId:i}}=this.room,o=(await this.room.modelManager.findAssetList(i)).filter(d=>d.typeName===AssetTypeName.Textures&&d.className===AssetClassName.SayBubble),s=["bubble01","bubble02","bubble03"],c=["bubble01_npc","bubble02_npc","bubble03_npc"];if(o.length){const d=o.filter(b=>s.includes(b.name)).map(b=>b.url),_=o.filter(b=>c.includes(b.name)).map(b=>b.url);d.length&&(XBillboardManager.userBubbleUrls=d),_.length&&(XBillboardManager.npcBubbleUrls=_)}}};let EngineProxy=_r;ct(EngineProxy,"_CHECK_DURATION",2);var CameraStates=(a=>(a[a.Normal=0]="Normal",a[a.ItemView=1]="ItemView",a[a.CGView=2]="CGView",a[a.PathView=3]="PathView",a))(CameraStates||{}),Direction=(a=>(a.Left="left",a.Right="right",a))(Direction||{});const calNormVector=(a,i)=>{let e=0;for(let s=0;s<3;++s)e=e+(i[s]-a[s])*(i[s]-a[s]);return e=Math.sqrt(e),[(i[0]-a[0])/e,(i[1]-a[1])/e,(i[2]-a[2])/e]},vectorCrossMulti=(a,i)=>{const e=a[0],o=a[2],s=i[0],c=i[2];return e*c-o*s},log$x=new Logger("camera");class Camera extends EventEmitter{constructor(e){super();ct(this,"initialFov",0);ct(this,"_state",CameraStates.Normal);ct(this,"_person",Person.Third);ct(this,"_room");ct(this,"_cameraFollowing",!0);ct(this,"checkPointOnLeftOrRight",e=>{const o=ue4Position2Xverse(e);if(!o||this.checkPointInView(e))return;const d=this._room.scene.activeCamera;if(!d)return;const _=[d.target.x,d.target.y,d.target.z],b=[d.position.x,d.position.y,d.position.z],{x:k,y:j,z:$}=o,_e=calNormVector(b,_),et=calNormVector(b,[k,j,$]);return vectorCrossMulti(_e,et)<0?Direction.Right:Direction.Left});ct(this,"checkPointInView",({x:e,y:o,z:s})=>{const c=ue4Position2Xverse({x:e,y:o,z:s});if(!c)return!1;for(let d=0;d<6;d++)if(this._room.scene.frustumPlanes[d].dotCoordinate(c)<0)return!1;return!0});this._room=e}get person(){return this._person}get state(){return this._state}get pose(){return this._room.currentClickingState.camera}set cameraFollowing(e){log$x.info("cameraFollowing setter",e),this.setCameraFollowing({isFollowHost:e})}get cameraFollowing(){return this._cameraFollowing}setCameraFollowing({isFollowHost:e}){}handleRenderInfo(e){const{cameraStateType:o}=e.renderInfo,s=this._room.sceneManager;if(o!==this._state&&(this._state=o,log$x.debug("camera._state changed to",CameraStates[o]),o===CameraStates.CGView?(s.cameraComponent.switchToCgCamera(),s.staticmeshComponent.getCgMesh().show()):(s.cameraComponent.switchToMainCamera(),s.staticmeshComponent.getCgMesh().hide()),this.emit("stateChanged",{state:o})),this._room.isHost)return;const{isFollowHost:c}=e.playerState;!!c!==this._cameraFollowing&&(this._cameraFollowing=!!c,this.emit("cameraFollowingChanged",{cameraFollowing:!!c}))}setCameraState({state:e}){if(this._state===e){log$x.warn(`You are already in ${CameraStates[e]} camera state`);return}e===CameraStates.Normal||this._state===CameraStates.ItemView&&log$x.warn("CloseUp camera state can only be triggerd by room internally")}turnToFace({extra:e="",offset:o=0}){const s={action_type:Actions.TurnToFace,turn_to_face_action:{offset:o}};return this.emit("viewChanged",{extra:e}),this._room.actionsHandler.sendData({data:s})}isInDefaultView(){if(!this._room.isHost){log$x.warn("It is recommended to call the function on the host side");return}if(!this._room._currentClickingState)return log$x.error("CurrentState should not be empty"),!1;const{camera:e,player:o}=this._room._currentClickingState;return Math.abs(o.angle.yaw-180-e.angle.yaw)%360<=4}async screenShot({name:e,autoSave:o=!1}){const s=this._room.scene.getEngine(),c=this._room.scene.activeCamera;try{this._room.sceneManager.setImageQuality(EImageQuality.high);const d=await CreateScreenshotAsync(s,c,{precision:1});return this._room.sceneManager.setImageQuality(EImageQuality.low),o===!0&&downloadFileByBase64(d,e),Promise.resolve(d)}catch(d){return this._room.sceneManager.setImageQuality(EImageQuality.low),Promise.reject(d)}}changeToFirstPerson(e,o,s){const{camera:c,player:d,attitude:_,areaName:b,pathName:k}=e;return this._room.actionsHandler.requestPanorama({camera:c,player:d,attitude:_,areaName:b,pathName:k},o,s).then(()=>{this._room.networkController.rtcp.workers.changePanoMode(!0);const{position:j,angle:$}=d||{};this._room.sceneManager.cameraComponent.changeToFirstPersonView({position:j,rotation:$})})}setPerson(e,o={camera:this._room._currentClickingState.camera,player:this._room._currentClickingState.player}){const s=Date.now();return this._setPerson(e,o).then(c=>(log$x.infoAndReportMeasurement({tag:Person[e],startTime:s,metric:"setPerson"}),c)).catch(c=>(log$x.infoAndReportMeasurement({tag:Person[e],startTime:s,metric:"setPerson",error:c}),Promise.reject(c)))}_setPerson(e,o={camera:this._room._currentClickingState.camera,player:this._room._currentClickingState.player}){return e!==Person.First&&e!==Person.Third?Promise.reject("invalid person "+e):!o.camera||!o.player?Promise.reject(new ParamError("wrong camera or player")):e===Person.First?this._room.panorama.access({camera:o.camera,player:o.player,tag:"setPerson"}).then(()=>{var d,_;this._person=e,(d=this._room._userAvatar)==null||d.hide();const{position:s,angle:c}=((_=this._room.currentClickingState)==null?void 0:_.camera)||{};!s||!c||this._room.sceneManager.cameraComponent.changeToFirstPersonView({position:s,rotation:c})}):this._room.panorama.exit({camera:o.camera,player:o.player}).then(()=>{var s,c;this._person=e,(s=this._room._userAvatar)!=null&&s.xAvatar&&((c=this._room._userAvatar)==null||c.xAvatar.show())})}setCameraPose(e){this._room.sceneManager.cameraComponent.setCameraPose({position:e.position,rotation:e.angle})}async setMainCameraRotationLimit(e){if(!this._room.panorama.actived)return Promise.reject(new Error("panorama not actived when setMainCameraRotationLimit"));const{limitAxis:o,limitRotation:s}=e;await this._room.sceneManager.cameraComponent.setMainCameraRotationLimit(o,s)}removeMainCameraRotationLimit(){this._room.sceneManager.cameraComponent.removeMainCameraRotationLimit()}}var IEffectType=(a=>(a.Sequence="sequence",a.SubSequence="subSequence",a))(IEffectType||{});const log$w=new Logger("effectManager");class XverseEffect extends EventEmitter{constructor({id:e,jsonPath:o,type:s,room:c,scale:d=1}){super();ct(this,"_id");ct(this,"type");ct(this,"effect");ct(this,"_room");ct(this,"_isLoading",!0);ct(this,"_failed",!1);ct(this,"_scale",1);this._room=c,this._id=e,this.type=s,this._scale=d,this.effect=e==="Rain"||e==="Boom"?new XRain(this._room.scene,o,urlTransformer):s===IEffectType.Sequence?new XSequence(this._room.scene,o,"",urlTransformer):new XSubSequence(this._room.scene,o,urlTransformer)}get failed(){return this._failed}get position(){if(this.type!==IEffectType.Sequence)return this.effect.position}get rotation(){if(this.type!==IEffectType.Sequence)return this.effect.rotation}get isLoading(){return this._isLoading}get id(){return this._id}get name(){return this.effect.name}get isPlaying(){var e;return!!((e=this.effect)!=null&&e.isPlaying)}async init(){try{await this.effect.init()._timeout(1e4,new TimeoutError("effect init timeout(10s)")),this._isLoading=!1,this._failed=!1}catch(e){throw this._isLoading=!1,this._failed=!0,log$w.error(`effect: ${this.id} init error`,e),e}}play(e=!1){return new Promise((o,s)=>{this.effect.play(e),o()})}hide(){return this.effect.hide()}show(){return this.effect.show()}setRotation(e){var o;return this.type===IEffectType.Sequence?Promise.reject("setRotation failed, sequence unSuported"):(o=this.effect)==null?void 0:o.setRotation(e)}setPosition(e){var o;return this.type===IEffectType.Sequence?Promise.reject("setPosition failed, sequence unSuported"):(o=this.effect)==null?void 0:o.setPosition(e)}setScaling(e){var o;return this.type===IEffectType.Sequence?Promise.reject("setScaling failed, sequence unSuported"):(this._scale=e,(o=this.effect)==null?void 0:o.setScaling({x:e,y:-e,z:e}))}dispose(){this.effect.dispose()}}const log$v=new Logger("xverse-effect-manager"),Pr=class extends EventEmitter{constructor(e){super();ct(this,"effects",new Map);ct(this,"room");this.room=e}async addEffect(e){var d;const{jsonPath:o,id:s,type:c=IEffectType.SubSequence}=e;try{this.effects.get(s)&&((d=this.effects.get(s))==null||d.dispose());const _=new Pr.subEffect({id:s,jsonPath:o,type:c,room:this.room});return this.effects.set(s,_),await _.init(),_}catch(_){return this.effects.delete(s),log$v.error(_),Promise.reject(_)}}clearEffects(){this.effects.forEach(e=>{e.dispose(),this.effects.delete(e.id)})}removeEffect(e){const o=this.effects.get(e);o==null||o.dispose(),o&&this.effects.delete(o.id)}};let XverseEffectManager=Pr;ct(XverseEffectManager,"subEffect",XverseEffect);Scene.DoubleClickDelay=500;class StaticMeshEvent extends EventEmitter{constructor(e){super();ct(this,"scene");ct(this,"_staringPointerTime",-1);ct(this,"_pickedMeshID","0");ct(this,"_pointerDownTime",-1);ct(this,"_currentPickPoint");ct(this,"_longPressDelay",500);ct(this,"_pointerTapDelay",200);ct(this,"_pickedMeshType");ct(this,"registerEvent",()=>{this.scene.onPrePointerObservable.add(this.onDown,PointerEventTypes.POINTERDOWN),this.scene.onPrePointerObservable.add(this.onUp,PointerEventTypes.POINTERUP),this.scene.onPrePointerObservable.add(this.onDoubleTap,PointerEventTypes.POINTERDOUBLETAP),this.scene.onDispose=()=>{this.scene.onPrePointerObservable.removeCallback(this.onUp),this.scene.onPrePointerObservable.removeCallback(this.onDown),this.scene.onPrePointerObservable.removeCallback(this.onDoubleTap)}});ct(this,"onUp",()=>{if(Date.now()-this._pointerDownTime<this._pointerTapDelay&&!this.scene._inputManager._isPointerSwiping()){this.scene._inputManager._totalPointersPressed=0;const e=this._currentPickPoint;e!=null&&this.emit("pointTap",e)}});ct(this,"onDown",()=>{const e=this.onPointerTap(o=>o.isPickable);this._currentPickPoint=e,this._pointerDownTime=Date.now()});ct(this,"onDoubleTap",()=>{const e=this.onPointerTap(void 0);e!=null&&this.emit("pointDoubleTap",e)});this.manager=e,this.scene=e.Scene,this.registerEvent(),this._currentPickPoint=null,this._pickedMeshType=null}onPointerTap(e,o=!1){var c,d;let s=new PickingInfo;if(o){const _=this.scene.multiPick(this.scene.pointerX,this.scene.pointerY,e,void 0,void 0);_&&_.length>1?s=_[1]:_&&(s=_[0])}else s=this.scene.pick(this.scene.pointerX,this.scene.pointerY,e,!1,null);if(s.hit){const _=(c=s==null?void 0:s.pickedPoint)==null?void 0:c.asArray();if(_){const[b,k,j]=_,$=xversePosition2Ue4({x:b,y:k,z:j});return{name:(d=s.pickedMesh)==null?void 0:d.name,type:s.pickedMesh.xtype,id:s.pickedMesh.xid,point:$}}}return null}}class RotationEvent{constructor(i){ct(this,"touchStartX");ct(this,"touchStartY");ct(this,"handelResize");ct(this,"_room");ct(this,"_canvas");ct(this,"handleTouchStart",i=>{const e=i.touches[0];this.touchStartX=e.pageX,this.touchStartY=e.pageY,this._room.emit("touchStart",{event:i})});ct(this,"handleMouseDown",i=>{this.touchStartX=i.pageX,this.touchStartY=i.pageY});ct(this,"handleMouseMove",i=>{if(!this.touchStartX||!this.touchStartY)return;const e=i.pageX,o=i.pageY,s=e-this.touchStartX,c=o-this.touchStartY,d=this._room.options.canvas.offsetHeight,_=this._room.options.canvas.offsetWidth;let b=2*c/d,k=2*s/_;b>1&&(b=1),k>1&&(k=1),this._room.actionsHandler.rotate({pitch:b,yaw:k}),this.touchStartX=e,this.touchStartY=o});ct(this,"handleMouseUp",i=>{this.touchStartX=void 0,this.touchStartY=void 0,this._room.emit("mouseUp",{event:i})});ct(this,"handleTouchMove",i=>{if(!this.touchStartX||!this.touchStartY)return;const e=i.touches[0],o=e.pageX,s=e.pageY,c=o-this.touchStartX,d=s-this.touchStartY,_=this._room.options.canvas.offsetHeight,b=this._room.options.canvas.offsetWidth;let k=2*d/_,j=2*c/b;k>1&&(k=1),j>1&&(j=1),this._room.actionsHandler.rotate({pitch:k,yaw:j}),this.touchStartX=o,this.touchStartY=s,this._room.emit("touchMove",{pitch:k,yaw:j,event:i})});ct(this,"handleTouchEnd",i=>{this._room.emit("touchEnd",{event:i})});this._room=i,this._canvas=i.canvas,this.handelResize=this.reiszeChange()}init(){this._canvas.addEventListener("touchstart",this.handleTouchStart),this._canvas.addEventListener("touchmove",this.handleTouchMove),this._canvas.addEventListener("touchend",this.handleTouchEnd),this._room.scene.preventDefaultOnPointerDown=!1,this._room.scene.preventDefaultOnPointerUp=!1,this._canvas.addEventListener("mousedown",this.handleMouseDown),this._canvas.addEventListener("mousemove",this.handleMouseMove),this._canvas.addEventListener("mouseup",this.handleMouseUp)}clear(){this._canvas.removeEventListener("touchstart",this.handleTouchStart),this._canvas.removeEventListener("touchmove",this.handleTouchMove),this._canvas.removeEventListener("touchend",this.handleTouchEnd),this._canvas.removeEventListener("mousedown",this.handleMouseDown),this._canvas.removeEventListener("mousemove",this.handleMouseMove),this._canvas.removeEventListener("mouseup",this.handleMouseUp)}reiszeChange(){window.addEventListener("resize",()=>{})}}const log$u=new Logger("eventsController");class EventsController{constructor(i){ct(this,"staticmeshEvent");ct(this,"rotationEvent");ct(this,"resize",()=>{this.room.panorama.actived||this.room.sceneManager.cameraComponent.cameraFovChange(this.room.sceneManager.yuvInfo)});ct(this,"clickEvent",i=>{const{point:e,name:o,type:s,id:c}=i;log$u.debug("pointEvent",i),this.room.proxyEvents("pointTap",{point:e,meshName:o,type:s,id:c}),this.room.proxyEvents("_coreClick",i)});ct(this,"longPressEvent",i=>{this.room.proxyEvents("_corePress",i)});ct(this,"handleActionResponseTimeout",({error:i,event:e})=>{this.room.proxyEvents("actionResponseTimeout",{error:i,event:e})});ct(this,"handleNetworkStateChange",i=>{const{state:e,count:o}=i;e=="reconnecting"?this.room.proxyEvents("reconnecting",{count:o||1}):e==="reconnected"?(this.room.networkController.rtcp.workers.reset(),this.room.proxyEvents("reconnected"),this.room.afterReconnected()):e==="disconnected"&&this.room.proxyEvents("disconnected")});this.room=i,this.staticmeshEvent=new StaticMeshEvent(this.room.sceneManager),this.rotationEvent=new RotationEvent(i)}bindEvents(){window.addEventListener("orientationchange"in window?"orientationchange":"resize",this.resize),this.staticmeshEvent.on("pointTap",this.clickEvent),this.staticmeshEvent.on("longPress",this.longPressEvent),this.rotationEvent.init(),eventsManager.on("actionResponseTimeout",this.handleActionResponseTimeout),this.room.networkController.on("stateChanged",this.handleNetworkStateChange)}clearEvents(){window.removeEventListener("orientationchange"in window?"orientationchange":"resize",this.resize),this.staticmeshEvent.off("pointTap",this.clickEvent),this.staticmeshEvent.off("longPress",this.longPressEvent),eventsManager.off("actionResponseTimeout",this.handleActionResponseTimeout),this.room.networkController.off("stateChanged",this.handleNetworkStateChange),this.rotationEvent.clear()}}const isWebAssemblySupported=()=>{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){const a=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(a instanceof WebAssembly.Module)return new WebAssembly.Instance(a)instanceof WebAssembly.Instance}}catch{}return console.log("wasm is not supported"),!1};function isSupported(){return typeof RTCPeerConnection=="function"&&isWebAssemblySupported()}const log$t=new Logger("panorama");class Panorama{constructor(i){ct(this,"_actived",!1);ct(this,"isLoading",!1);ct(this,"handleReceivePanorama",async i=>{const e=i.camera;log$t.warn("handle panorama",e);const o={data:i.data,pose:{position:e.position,rotation:e==null?void 0:e.angle}},s=this.room.sceneManager;if(this.room.networkController.rtcp.workers.changePanoMode(!0),await s.materialComponent.changePanoImg(0,o),!!i.finished)if(await s.changePanoShaderForLowModel(0),this.room.isPano=!0,this._actived=!0,e)this.room.sceneManager.cameraComponent.changeToFirstPersonView({position:e.position,rotation:e.angle});else{const{skinId:c,pathName:d}=this.room.currentState;if(!c||!d)return;const _=await this.room.modelManager.findRoute(c,d),{camera:b}=getRandomItem(_.birthPointList)||{};b&&this.room.sceneManager.cameraComponent.changeToFirstPersonView(qt(Kt({},b),{rotation:b.angle}))}});this.room=i}get actived(){return this._actived}bindListener(i){this.room.networkController.rtcp.workers.registerFunction("panorama",o=>{var b;log$t.warn("receive panorama");const{metadata:s}=o,c=JSON.parse(String.fromCharCode.apply(null,s));o.parsedMetaData=c;const d=(b=o.parsedMetaData.newUserStates)==null?void 0:b.find(k=>k.userId===this.room.userId),_=d==null?void 0:d.playerState.camera;o.camera=_,eventsManager.remove(o.parsedMetaData.traceIds[0],Codes.Success,o,!0),this.room.isFirstDataUsed||(this.room.isFirstDataUsed=!0,this.handleReceivePanorama(o).then(i))})}access(i,e,o){this.isLoading=!0;const{camera:s,player:c,attitude:d,areaName:_,pathName:b,tag:k}=i;return this.room.actionsHandler.requestPanorama({camera:s,player:c,attitude:d,areaName:_,pathName:b,tag:k},e,o).then(j=>(this.isLoading=!1,this.handleReceivePanorama(j))).catch(j=>(this.isLoading=!1,Promise.reject(j)))}exit(i){const{camera:e,player:o,attitude:s,areaName:c,pathName:d}=i;return this.room.networkController.rtcp.workers.changePanoMode(!1),this.room.actionsHandler.changeRotationRenderType({renderType:RenderType.RotationVideo,player:o,camera:e,attitude:s,areaName:c,pathName:d}).then(()=>this.handleExitPanorama()).catch(_=>(this.room.networkController.rtcp.workers.changePanoMode(!0),Promise.reject(_)))}handleExitPanorama(){var i,e,o,s,c,d;this.room.isPano=!1,this._actived=!1,(s=(i=this.room.sceneManager)==null?void 0:i.cameraComponent)==null||s.forceChangeSavedCameraPose({position:(e=this.room._currentClickingState)==null?void 0:e.camera.position,rotation:(o=this.room._currentClickingState)==null?void 0:o.camera.angle}),this.room.sceneManager.changeVideoShaderForLowModel(),(d=(c=this.room.sceneManager)==null?void 0:c.cameraComponent)==null||d.changeToThirdPersonView()}}class PathManager{constructor(){ct(this,"currentArea","");ct(this,"currentPathName","");ct(this,"currentAttitude","");ct(this,"speed",0)}getSpeed(i){const e={guangchang:{[MotionType.Walk]:17,[MotionType.Run]:51},tower:{[MotionType.Walk]:12.5,[MotionType.Run]:25},zhiboting:{[MotionType.Walk]:12.5,[MotionType.Run]:25},youxiting:{[MotionType.Walk]:12.5,[MotionType.Run]:25},diqing:{[MotionType.Walk]:12.5,[MotionType.Run]:25}},o=e[this.currentArea]||e.guangchang;return this.speed=o[i]*30,this.speed}}const log$s=new Logger("xverse"),mr=class{constructor(i){ct(this,"debug",!1);ct(this,"pageSession");ct(this,"preload");ct(this,"appId");ct(this,"releaseId");i||(i={});const{onLog:e,env:o,appId:s,releaseId:c,subPackageVersion:d}=i;mr.NO_CACHE=!1,mr.env=o||"PROD",mr.SUB_PACKAGE_VERSION=d,this.debug&&Logger.setLevel(LoggerLevels.Debug);const _=this.pageSession=uuid$1();if(reporter.updateHeader({pageSession:_}),reporter.updateReportUrl(REPORT_URL[mr.env]),d&&reporter.updateBody({sdkVersion:d,appId:s}),log$s.infoAndReportMeasurement({metric:"sdkInit",startTime:Date.now(),extra:{version:d,enviroment:o,pageSession:_,engineVersion:VERSION$2}}),log$s.debug("debug mode:",this.debug),reporter.on("report",b=>{e&&e(b)}),s){this.appId=s,this.releaseId=c;const b=ModelManager.getInstance(s,c);this.preload=new Preload(b)}}get isSupported(){return isSupported()}disableLogUpload(){reporter.disable(),log$s.debug("log upload has been disabled")}async getSkinList(){return[]}async getAvatarList(){return[]}async getGiftList(){return[{id:"hack "}]}};let Xverse$1=mr;ct(Xverse$1,"NO_CACHE"),ct(Xverse$1,"env"),ct(Xverse$1,"SUB_PACKAGE_VERSION");const log$r=new Logger("http");class Http extends EventEmitter{constructor(){super(...arguments);ct(this,"secondArray",new SecondArray)}async get({url:e,useIndexedDb:o=!1,timeout:s=15e3,key:c,isOutPutObjectURL:d=!0}){if(Xverse$1.NO_CACHE!==void 0&&(o=!Xverse$1.NO_CACHE),o)if(isIndexedDbSupported()){window.performance.now();let _=null;try{_=await modelTable.query("url",e)}catch(b){return log$r.debug(b),log$r.warn("cache query error",e),Promise.resolve(e)}if(_&&_.model){let b=null;const k=Date.now();if(_.model instanceof Blob?b=_.model:b=dataURItoBlob(_.model),!b)return Promise.reject("blob is null");const j=Date.now();this.secondArray.add(j-k);const $=Promise.resolve(d?URL.createObjectURL(b):b);return window.performance.now(),$}else return this.request({url:e,timeout:s,contentType:"blob",key:c}).then(async b=>{const k=await blobToDataURI(b.response);try{await modelTable.put({url:e,model:k})}catch(j){log$r.warn("unable to add data to indexedDB",j)}return Promise.resolve(d?URL.createObjectURL(b.response):b.response)})}else return this.request({url:e,timeout:s,contentType:"blob",key:c}).then(_=>{const b=_.response;return Promise.resolve(d?URL.createObjectURL(b):b)}).catch(_=>Promise.reject(_));else return this.request({url:e,timeout:s,key:c}).then(_=>_.getResponseHeader("content-type")==="application/json"?Promise.resolve(JSON.parse(_.responseText)):Promise.resolve(_.responseText))}request(e){const{timeout:o=3e4,contentType:s,key:c,onRequestStart:d}=e,{url:_}=e;return new Promise((b,k)=>{window.performance.now();const j=new XMLHttpRequest;s&&(j.responseType=s),j.timeout=o,j.addEventListener("readystatechange",()=>{if(j.readyState==4){if(j.status==200)return window.performance.now(),this.emit("loadend",{message:`request ${_} load success`}),b(j);{const $=`Unable to load the request ${_}`;return this.emit("error",{message:$}),log$r.error($),k($)}}}),d&&d(j),j.open("GET",_),j.send()})}}const http=new Http,isIndexedDbSupported=()=>(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB)!==void 0,blobToDataURI=async a=>new Promise((i,e)=>{const o=new FileReader;o.readAsDataURL(a),o.onload=function(s){var c;i((c=s.target)==null?void 0:c.result)},o.onerror=function(s){e(s)}}),dataURItoBlob=a=>{let i;a.split(",")[0].indexOf("base64")>=0?i=atob(a.split(",")[1]):i=unescape(a.split(",")[1]);const e=a.split(",")[0].split(":")[1].split(";")[0],o=new Uint8Array(i.length);for(let c=0;c<i.length;c++)o[c]=i.charCodeAt(c);return new Blob([o],{type:e})},log$q=new Logger("xverse-signal");class Signal{constructor(i){ct(this,"_room");ct(this,"signalHandleActived",!0);ct(this,"isUpdatedYUV",!0);ct(this,"handleSignalSecondArray",new SecondArray);ct(this,"handleSignalPartialArray2",new SecondArray);ct(this,"handleSignalPartialArray3",new SecondArray);ct(this,"handleSignalPartialArray4",new SecondArray);ct(this,"handleSignalPartialArray5",new SecondArray);ct(this,"handleSignalPartialArray6",new SecondArray);ct(this,"handleSignalPartialArray7",new SecondArray);this._room=i}getSignalStat(){const i=this.handleSignalSecondArray.getStat(),e=this.handleSignalPartialArray2.getStat().max,o=this.handleSignalPartialArray3.getStat().max,s=this.handleSignalPartialArray4.getStat().max,c=this.handleSignalPartialArray5.getStat().max,d=this.handleSignalPartialArray6.getStat().max,_=this.handleSignalPartialArray7.getStat().max,b=http.secondArray.getStat();return{sdkAvg:i.avg,sdkMax:i.max,blobSum:b.sum,blobMax:b.max,partialMax:[e,o,s,c,d,_]}}handleSignal(i,e){var tt,rt,it;if(!this.signalHandleActived)return;const o=Date.now(),{signal:s,alreadyUpdateYUV:c}=i;this.handleActionResponses(s),this._room.handleSignalHook(s);const d=Date.now();if(this.handleSignalPartialArray2.add(d-o),!c){const nt=(tt=s.newUserStates)==null?void 0:tt.find(ot=>ot.userId===this._room.userId);if((nt==null?void 0:nt.renderInfo)&&((rt=this._room._userAvatar)==null?void 0:rt.isMoving)){log$q.debug("stream stoped, make avatar to stop");const{isMoving:ot,isRotating:at}=nt.renderInfo;this._room.avatarManager._updateAvatarMovingStatus({id:nt.userId,isMoving:!!ot,isRotating:!!at})}return}this.isUpdatedYUV=c;const _=s;if(!s){log$q.warn("metadata signal is empty");return}if(_.actionType===Actions.GetNewUserState){eventsManager.remove(_.traceId,_.code,_);return}if(_.code===Codes.RepeatLogin){this._room.handleRepetLogin();return}if(_.code!==void 0&&_.code!==Codes.Success&&_.code!==Codes.ActionMaybeDelay&&_.code!==Codes.DoActionBlocked&&_.code!==Codes.GetOnVehicle)if(_.code===Codes.UnReachable)log$q.debug("signal errcode: ",_.code),this._room.proxyEvents("unreachable");else{if(!this._room.joined){const nt=getErrorByCode(_.code),ot=new nt(_.msg);e(ot)}log$q.error("signal errcode: ",_),this._room.emit("error",_)}const b=Date.now();this.handleSignalPartialArray3.add(b-d);const k=(it=_.newUserStates)==null?void 0:it.find(nt=>nt.userId===this._room.userId);if(_.broadcastAction)try{const nt=JSON.parse(_.broadcastAction.data);Broadcast.handlers.forEach(ot=>ot(nt))}catch(nt){log$q.error(nt)}const j=Date.now();this.handleSignalPartialArray4.add(j-b),_.newUserStates&&_.newUserStates.length>0&&this._room.avatarManager.handleAvatar(_);const $=Date.now();if(this.handleSignalPartialArray5.add($-j),k!=null&&k.playerState){this._room._currentClickingState=k.playerState;const{pathName:nt,attitude:ot,areaName:at,skinId:st}=k.playerState;if(nt&&(this._room.pathManager.currentPathName=nt,this._room.updateCurrentState({pathName:nt})),at&&this._room.updateCurrentState({areaName:at}),ot){const ut=this._room.skin.routeList.find(lt=>lt.areaName===this._room.currentState.areaName),ft=((ut==null?void 0:ut.step)||7.5)*30;this._room.updateCurrentState({speed:ft,attitude:ot}),this._room.pathManager.currentAttitude=ot,this._room._userAvatar&&(this._room._userAvatar.motionType=ot)}this._room.sceneManager.getCurrentShaderMode()!==ECurrentShaderMode.pano&&!this._room.isPano&&k.playerState.camera&&!this._room.panorama.isLoading&&this._room.camera.setCameraPose(k.playerState.camera)}k!=null&&k.renderInfo&&this._room.camera.handleRenderInfo(k);const _e=Date.now();if(this.handleSignalPartialArray6.add(_e-$),_.actionType!==void 0){const{actionType:nt,code:ot,echoMsg:at,traceId:st}=_;nt===Actions.Echo&&ot===Codes.Success&&this._room.networkController.rtcp.heartbeat.pong(at,st),ot!==Codes.Success?eventsManager.remove(st,ot):[Actions.GetReserveStatus,Actions.Broadcast,Actions.ChangeNickname,Actions.ConfirmEvent,Actions.ReserveSeat,Actions.Rotation,Actions.TurnTo,Actions.RotateTo,Actions.SetPlayerState,Actions.GetNeighborPoints,Actions.TurnToFace,Actions.AudienceChangeToVisitor,Actions.RemoveVisitor,Actions.GetUserWithAvatar,Actions.GetNewUserState,Actions.SetSyncPolicy,Actions.StartLive].includes(nt)&&eventsManager.remove(st,ot,_)}const et=Date.now();this.handleSignalSecondArray.add(et-o),this.handleSignalPartialArray7.add(et-_e)}handleActionResponses(i){!(i!=null&&i.actionResponses)||i.actionResponses.length===0||i.actionResponses.forEach(e=>{if(e.actionType==null)return;const{pointType:o,extra:s,actionType:c,traceId:d,code:_,msg:b}=e;c===Actions.GetNeighborPoints?eventsManager.remove(d,_,e.nps):c===Actions.GetUserWithAvatar?eventsManager.remove(d,_,e.userWithAvatarList):eventsManager.remove(d,_,b),o===PointType.Path&&c===Actions.Clicking&&(this._room.moveToExtra=decodeURIComponent(s))})}}const BREATH_POINT_TYPE="debugBreathPoint",TAP_BREATH_POINT_TYPE="debugTapBreathPoint",DEFAULT_SEARCH_RANGE=1e3;class Debug{constructor(i){ct(this,"isShowNearbyBreathPoints",!1);ct(this,"isShowTapBreathPoints",!1);ct(this,"isSceneShading",!0);ct(this,"searchRange",DEFAULT_SEARCH_RANGE);ct(this,"nearbyBreathPointListening",!1);ct(this,"tapBreathPointListening",!1);ct(this,"dumpStreamTimer",0);this.room=i}toggleStats(){return this.room.stats.isShow?this.room.stats.hide():this.room.stats.show()}toggleNearbyBreathPoint(i=DEFAULT_SEARCH_RANGE){this.searchRange=i,this.isShowNearbyBreathPoints=!this.isShowNearbyBreathPoints,this.isShowNearbyBreathPoints?(this.getPointsAndRender(),this.setupNearbyBreathPointListener()):this.room.breathPointManager.clearBreathPoints(BREATH_POINT_TYPE)}toggleTapBreathPoint(){this.isShowTapBreathPoints=!this.isShowTapBreathPoints,this.isShowTapBreathPoints?this.setupTapPointListener():this.room.breathPointManager.clearBreathPoints(TAP_BREATH_POINT_TYPE)}dumpStream(i,e=10*1e3){if(this.dumpStreamTimer)throw new Error("dumpStream running");this.room.networkController.rtcp.workers.saveframe=!0,this.dumpStreamTimer=window.setTimeout(()=>{this.room.networkController.rtcp.workers.SaveMediaStream=!0,this.dumpStreamTimer=0,i&&i()},e)}toggleSceneshading(){this.isSceneShading=!this.isSceneShading,this.isSceneShading?this.room.sceneManager.changeVideoShaderForLowModel():this.room.sceneManager.changeDefaultShaderForLowModel()}setupTapPointListener(){this.tapBreathPointListening||(this.tapBreathPointListening=!0,this.room.on("_coreClick",({point:i})=>{this.isShowTapBreathPoints&&this.renderTapBreathPoint({id:"tapToint",position:i})}))}renderTapBreathPoint({position:i,id:e}){let o;if(o=this.room.breathPointManager.breathPoints.get(e)){o.position=i;return}this.room.breathPointManager.addBreathPoint({id:e,position:i,type:TAP_BREATH_POINT_TYPE,size:.8,forceLeaveGround:!0,billboardMode:!0,rotation:Math.abs(i.z)<20?{pitch:90,yaw:0,roll:0}:{pitch:0,yaw:270,roll:0}})}setupNearbyBreathPointListener(){var i;this.nearbyBreathPointListening||(this.nearbyBreathPointListening=!0,(i=this.room._userAvatar)==null||i.on("stopMoving",()=>{this.isShowNearbyBreathPoints&&this.getPointsAndRender()}))}async getPointsAndRender(){var o,s;const i=this.searchRange,e=((o=this.room._userAvatar)==null?void 0:o.position)&&await this.getNeighborPoints({point:(s=this.room._userAvatar)==null?void 0:s.position,containSelf:!0,searchRange:i})||[];this.room.breathPointManager.breathPoints.forEach(c=>{!!e.find(_=>JSON.stringify(_)===c._id)||this.room.breathPointManager.clearBreathPoints(c._id)}),e.forEach(c=>{const d=JSON.stringify(c);this.room.breathPointManager.breathPoints.get(d)||this.room.breathPointManager.addBreathPoint({id:d,position:c,type:BREATH_POINT_TYPE,rotation:{pitch:90,yaw:0,roll:0},forceLeaveGround:!0})})}getNeighborPoints(i){const{point:e,containSelf:o=!1,searchRange:s=500}=i;return this.room.actionsHandler.getNeighborPoints({point:e,containSelf:o,searchRange:s})}}const log$p=new Logger("xverse-room");class XverseRoom$1 extends EventEmitter{constructor(e){super();ct(this,"disableAutoTurn",!1);ct(this,"options");ct(this,"_currentNetworkOptions");ct(this,"lastSkinId");ct(this,"debug");ct(this,"isFirstDataUsed",!1);ct(this,"userId",null);ct(this,"pathManager",new PathManager);ct(this,"networkController");ct(this,"_startTime",Date.now());ct(this,"canvas");ct(this,"modelManager");ct(this,"eventsController");ct(this,"panorama");ct(this,"engineProxy");ct(this,"_id");ct(this,"skinList",[]);ct(this,"isHost",!1);ct(this,"avatarManager",new XverseAvatarManager(this));ct(this,"effectManager",new XverseEffectManager(this));ct(this,"sceneManager");ct(this,"scene");ct(this,"breathPointManager");ct(this,"_currentState");ct(this,"joined",!1);ct(this,"disableRotate",!1);ct(this,"isPano",!1);ct(this,"movingByClick",!1);ct(this,"camera",new Camera(this));ct(this,"stats",new Stats(this));ct(this,"isUpdatedRawYUVData",!1);ct(this,"actionsHandler",new ActionsHandler(this));ct(this,"_currentClickingState",null);ct(this,"signal",new Signal(this));ct(this,"allowRender",!0);ct(this,"firstFrameTimestamp");ct(this,"receiveRtcData",async()=>{log$p.info("Invoke receiveRtcData");let e=!1,o=!1,s=!1,c=!1;return this.viewMode==="serverless"?(log$p.warn("set view mode to serverless"),this.setViewMode("observer").then(()=>this,()=>this)):new Promise((d,_)=>{const b=this.networkController.rtcp.workers;b.registerFunction("signal",k=>{this.signal.handleSignal(k,_)}),b.registerFunction("stream",k=>{var j;if(this.emit("streamTimestamp",{timestamp:Date.now()}),o||(o=!0,log$p.info("Invoke stream event")),k.stream){s||(s=!0,log$p.info("Invoke updateRawYUVData")),this.isUpdatedRawYUVData=!1;const $=(j=this._currentState.skin)==null?void 0:j.fov;this.sceneManager.materialComponent.updateRawYUVData(k.stream,k.width,k.height,$),this.isUpdatedRawYUVData=!0}e||(log$p.info("Invoke isAfterRenderRegistered"),e=!0,this.scene.registerAfterRender(()=>{this.engineProxy.frameRenderNumber>=2&&(c||(c=!0,log$p.info("Invoke registerAfterRender")),this.isFirstDataUsed||(log$p.info("Invoke isStreamAvailable"),this.isFirstDataUsed=!0,this.firstFrameTimestamp=Date.now(),d(this),this.afterJoinRoom()))}))}),this.panorama.bindListener(()=>{d(this),this.afterJoinRoom()}),b.registerFunction("reconnectedFrame",()=>{}),log$p.info("Invoke decoderWorker.postMessage"),b.decoderWorker.postMessage({t:5})})});ct(this,"moveToExtra","");this.options=e,this.options.wsServerUrl||(this.options.wsServerUrl=SERVER_URLS.DEV),this.modelManager=ModelManager.getInstance(e.appId,e.releaseId),this.updateReporter();const c=e,{canvas:o}=c,s=wr(c,["canvas"]);log$p.infoAndReportMeasurement({metric:"startJoinRoomAt",startTime:Date.now(),group:"joinRoom",extra:s,value:0})}get currentNetworkOptions(){return this._currentNetworkOptions}get viewMode(){var e;return((e=this._currentState)==null?void 0:e.viewMode)||"full"}get id(){return this._id}get skinId(){return this._currentState.skinId}get skin(){return this._currentState.skin}get sessionId(){return this.currentNetworkOptions.sessionId}get pictureQualityLevel(){return this.currentState.pictureQualityLevel}get avatars(){return Array.from(this.avatarManager.avatars.values())}get currentState(){var e;return qt(Kt({},this._currentState),{state:(e=this.networkController)==null?void 0:e._state})}get _userAvatar(){return this.avatars.find(e=>e.userId===this.userId)}get tvs(){return this.engineProxy._tvs}get tv(){return this.tvs[0]}get currentClickingState(){return this._currentClickingState}afterJoinRoomHook(){}beforeJoinRoomResolveHook(){}afterReconnectedHook(){}handleSignalHook(e){}skinChangedHook(){}async beforeStartGameHook(e){}afterLoadAssetsHook(){}afterUserAvatarLoadedHook(){}audienceViewModeHook(e){}setViewModeToObserver(){}handleVehicleHook(e){}updateReporter(){const{avatarId:e,skinId:o,userId:s,roomId:c,role:d,appId:_,wsServerUrl:b}=this.options;reporter.updateHeader({userId:s}),reporter.updateBody({roomId:c,role:d,skinId:o,avatarId:e,appId:_,wsServerUrl:b})}async initRoom(){const{timeout:e=DEFAULT_JOINROOM_TIMEOUT}=this.options;return isSupported()?this._initRoom()._timeout(e,new TimeoutError("initRoom timeout")):Promise.reject(new UnsupportedError)}async _initRoom(){const e=this.validateOptions(this.options);if(e)return log$p.error("initRoom param error",e),Promise.reject(e);const{canvas:o,avatarId:s,skinId:c,userId:d,wsServerUrl:_,role:b,token:k,pageSession:j,rotationRenderType:$,isAllSync:_e=!1,appId:et,camera:tt,player:rt,avatarComponents:it,nickname:nt,avatarScale:ot,firends:at=[],syncByEvent:st=!1,areaName:ut,attitude:ft=MotionType.Walk,pathName:lt,viewMode:ht="full",person:pt,roomId:mt,roomTypeId:dt,hasAvatar:gt=!1,syncToOthers:_t=!1,prioritySync:yt=!1,removeWhenDisconnected:Tt=!0,extra:St}=this.options;this.setCurrentNetworkOptions({avatarId:s,skinId:c,roomId:mt,userId:d,wsServerUrl:_,role:b,token:k,pageSession:j,rotationRenderType:$,isAllSync:_e,appId:et,camera:tt,player:rt,avatarComponents:it,nickname:nt,avatarScale:ot,firends:at,syncByEvent:st,areaName:ut,attitude:ft,pathName:lt,person:pt,roomTypeId:dt,hasAvatar:gt,syncToOthers:_t,prioritySync:yt,extra:St,removeWhenDisconnected:Tt}),this.userId=d,this.canvas=o,ut&&(this.pathManager.currentArea=ut),this.networkController=new NetworkController(this),this.setCurrentState({areaName:ut,pathName:lt,attitude:ft,speed:0,viewMode:ht,state:this.networkController._state,skinId:c});try{await Promise.all([this.initNetwork(),this.initConfig(),this.initWasm()]),log$p.info("network config wasm all ready, start to create game");const At=await this.requestCreateRoom({skinId:c}),vt=At.routeList.find(xt=>xt.areaName===ut),Et=((vt==null?void 0:vt.step)||7.5)*30;this.updateCurrentState({skin:At,skinId:At.id,versionId:At.versionId,speed:Et}),await this.initEngine(At)}catch(At){return Promise.reject(At)}return this.beforeJoinRoomResolve(),this.receiveRtcData()}beforeJoinRoomResolve(){this.setupStats(),this.eventsController=new EventsController(this),this.eventsController.bindEvents(),this.panorama=new Panorama(this),this.beforeJoinRoomResolveHook()}afterJoinRoom(){this.joined=!0,this.viewMode==="observer"&&this.setViewModeToObserver(),log$p.infoAndReportMeasurement({tag:this.viewMode,value:(this.firstFrameTimestamp||Date.now())-this._startTime,startTime:Date.now(),metric:"joinRoom",reportOptions:{immediate:!0}}),this.camera.initialFov=this.sceneManager.cameraComponent.getCameraFov(),this.stats.on("stats",({stats:e})=>{reporter.report("stats",Kt({},e))}),this.debug=new Debug(this),this.afterJoinRoomHook(),setInterval(()=>{this.actionsHandler.getNewUserState(NewUserStateType.NUST_Undefined).then(e=>{this.avatarManager.handleAvatar(e)}).catch(()=>{})},2e3)}afterReconnected(){this.avatarManager.clearOtherUsers(),this.afterReconnectedHook()}leave(){var e,o;return log$p.info("Invoke room.leave"),(e=this.eventsController)==null||e.clearEvents(),(o=this.networkController)==null||o.quit(),this}validateOptions(e){const{canvas:o,avatarId:s,skinId:c,userId:d,role:_,roomId:b,token:k,appId:j,avatarComponents:$}=e||{},_e=[];return o instanceof HTMLCanvasElement||_e.push(new ParamError("`canvas` must be instanceof of HTMLCanvasElement")),(!d||typeof d!="string")&&_e.push(new ParamError("`userId` must be string")),(!k||typeof k!="string")&&_e.push(new ParamError("`token` must be string")),(!j||typeof j!="string")&&_e.push(new ParamError("`appId` must be string")),_=="audience"||(!s||!c)&&_e.push(new ParamError("`avatarId` and `skinId` is required when create room")),_e[0]}async initNetwork(){if(this.viewMode==="serverless")return Promise.resolve();const e=Date.now();try{await this.networkController.connect()._timeout(8e3,new InitNetworkTimeoutError),log$p.infoAndReportMeasurement({metric:"networkInitAt",startTime:this._startTime,group:"joinRoom"}),log$p.infoAndReportMeasurement({metric:"networkInitCost",startTime:e,group:"joinRoom"})}catch(o){throw log$p.infoAndReportMeasurement({metric:"networkInitAt",startTime:e,group:"joinRoom",error:o}),o}}async initConfig(){const e=Date.now();try{await this.modelManager.getApplicationConfig()._timeout(8e3,new InitConfigTimeoutError),log$p.infoAndReportMeasurement({metric:"configInitAt",startTime:this._startTime,group:"joinRoom"}),log$p.infoAndReportMeasurement({metric:"configInitCost",startTime:e,group:"joinRoom"})}catch(o){throw log$p.infoAndReportMeasurement({metric:"configInitAt",startTime:e,group:"joinRoom",error:o}),o}}async initEngine(e){const o=Date.now();try{this.engineProxy=new EngineProxy(this),await this.engineProxy.initEngine(e)._timeout(8e3,new InitEngineError("init engine timeout in 8s")),log$p.infoAndReportMeasurement({metric:"webglInitAt",startTime:this._startTime,group:"joinRoom"}),log$p.infoAndReportMeasurement({metric:"webglInitCost",startTime:o,group:"joinRoom"});return}catch(s){let c=s;return s.code!==Codes.InitEngineTimeout&&(c=new InitEngineError(s)),log$p.error(s),log$p.infoAndReportMeasurement({metric:"webglInitAt",startTime:o,group:"joinRoom",error:c}),Promise.reject(c)}}async initWasm(){if(this.viewMode==="serverless")return Promise.resolve();const e=Date.now();try{await this.networkController.rtcp.workers.init({width:1920,height:1080,userID:this.userId,pageSession:this.options.pageSession,serverSession:""})._timeout(8e3,new InitDecoderTimeoutError),this.networkController.rtcp.workers.registerFunction("error",o=>{log$p.error("decode error",o);const{code:s,message:c}=o;this.emit("error",{code:s,msg:c})}),log$p.infoAndReportMeasurement({metric:"wasmInitAt",group:"joinRoom",startTime:this._startTime}),log$p.infoAndReportMeasurement({metric:"wasmInitCost",group:"joinRoom",startTime:e}),eventsManager.on("traceId",o=>{this.networkController.rtcp.workers.onTraceId(o)})}catch(o){throw log$p.infoAndReportMeasurement({metric:"wasmInitAt",group:"joinRoom",startTime:e,error:o}),o}}async requestCreateRoom({skinId:e}){let o;if(e){o=await this.getSkin(e),this.updateCurrentState({skin:o});const s=await this.modelManager.findRoute(e,this.options.pathName);this.updateCurrentNetworkOptions({areaName:s.areaName,attitude:s.attitude,versionId:o.versionId});const{camera:c,player:d}=getRandomItem(s.birthPointList)||this.options;this.options.camera||this.updateCurrentNetworkOptions({camera:c}),this.options.player||this.updateCurrentNetworkOptions({player:d})}if(this.viewMode==="serverless")return o;try{await this.beforeStartGameHook(this.options);const{room_id:s,data:c,session_id:d}=await this.networkController.startGame();this._id=s;const _=JSON.parse(c);this.isHost=_.IsHost,e=_.SkinID||e;const b=await this.getSkin(e);return this.updateCurrentNetworkOptions({roomId:s,sessionId:d}),reporter.updateBody({roomId:s,skinId:e,serverSession:d}),b}catch(s){return log$p.error("requestCreateRoom error:",s),Promise.reject(s)}}pause(){return this.engineProxy.pause()}resume(){return this.engineProxy.resume()}reconnect(){this.networkController.reconnect()}async setViewMode(e){}handleRepetLogin(){log$p.warn("receive "+Codes.RepeatLogin+" for repeat login"),this.emit("repeatLogin"),reporter.disable(),this.networkController.quit()}setPictureQualityLevel(e){const o={high:EImageQuality.high,low:EImageQuality.low,average:EImageQuality.mid};return this.updateCurrentState({pictureQualityLevel:e}),this.sceneManager.setImageQuality(o[e])}async getSkin(e){let o=null;if(o=(this.skinList=await this.modelManager.getSkinsList()).find(c=>c.id===e||c.id===e),o)return o;{const c=`skin is invalid: skinId: ${e}`;return Promise.reject(new ParamError(c))}}setupStats(){this.stats.assign({roomId:this.id,userId:this.userId}),setInterval(this.engineProxy.updateStats,1e3)}proxyEvents(e,o){this.emit(e,o)}setCurrentNetworkOptions(e){this._currentNetworkOptions=e}updateCurrentNetworkOptions(e){Object.assign(this._currentNetworkOptions,e),Object.assign(this.options,e)}setCurrentState(e){this._currentState=e}updateCurrentState(e){e.skinId&&(this.lastSkinId=this.currentState.skinId,this.updateCurrentNetworkOptions({skinId:e.skinId})),e.versionId&&this.updateCurrentNetworkOptions({versionId:e.versionId}),Object.assign(this._currentState,e)}afterSetUrlHook(){}afterTvStopedHook(){}afterTvPlayedHook(){}pageShowHandler(){this.engineProxy.setEnv(this.skin),this.allowRender=!0}pageHideHandler(){this.allowRender=!1}}var RenderType=(a=>(a[a.PathVideo=0]="PathVideo",a[a.RotationVideo=1]="RotationVideo",a[a.RotationImage=2]="RotationImage",a[a.PanoramaImage=3]="PanoramaImage",a[a.CGVideo=4]="CGVideo",a[a.ClientRotationPano=5]="ClientRotationPano",a[a.CloudRotationPano=6]="CloudRotationPano",a))(RenderType||{}),Person=(a=>(a[a.Third=0]="Third",a[a.First=1]="First",a))(Person||{}),LandingType=(a=>(a[a.Stay=0]="Stay",a[a.InitPoint=1]="InitPoint",a[a.NewPoint=2]="NewPoint",a))(LandingType||{}),ClickType=(a=>(a[a.Screen=0]="Screen",a[a.ThreeDimension=1]="ThreeDimension",a[a.ThreeDimensionQuick=2]="ThreeDimensionQuick",a[a.IgnoreView=3]="IgnoreView",a))(ClickType||{}),ChangeMode=(a=>(a[a.Preview=0]="Preview",a[a.Confirm=1]="Confirm",a[a.Cancel=2]="Cancel",a))(ChangeMode||{}),PointType=(a=>(a[a.Path=0]="Path",a[a.Item=1]="Item",a[a.Closeup=2]="Closeup",a[a.NoValidMatched=3]="NoValidMatched",a))(PointType||{});const log$o=new Logger("xverse-avatar-tools"),isSuit=a=>a==="suit",isPendant=a=>a===EDressType.PENDANT,avatarComponentsParser=async(a=null,i,e=[])=>new Promise(async(o,s)=>{var k,j;if(i.find($=>isSuit($.type))){const $=(j=(k=a==null?void 0:a.components)==null?void 0:k.find(_e=>isSuit(_e.type)))==null?void 0:j.suitComb;i=i.filter(_e=>($==null?void 0:$.indexOf(_e.type))===-1)}const d=i.filter($=>!e.some(_e=>_e.id===$.id));d.length===0&&o([]);const _=[];d.forEach(async $=>{var tt;let _e=(tt=a==null?void 0:a.components)==null?void 0:tt.find(rt=>rt.type===$.type);if(!_e){const rt=`changeComponents, no such component with type: ${$.type}`;log$o.error(rt),s(rt)}_e=JSON.parse(JSON.stringify(_e));let et=_e==null?void 0:_e.units.find(rt=>rt.id===$.id);et||(log$o.warn(`changeComponents, no unit with type: ${$.type}, id: ${$.id}`),et=_e==null?void 0:_e.units.find(rt=>rt.isDefault),!et&&log$o.warn(`changeComponents, no default unit with type: ${$.type}`)),et&&_.push({id:et.id,url:et.url,suitComb:(_e==null?void 0:_e.suitComb)||[],type:$.type})});const b=[];Promise.all(b).then($=>{_.forEach((_e,et)=>{var tt,rt;if(!isSuit(_e.type)){const it=((rt=(tt=a==null?void 0:a.components)==null?void 0:tt.find(nt=>isSuit(nt.type)))==null?void 0:rt.suitComb)||[];it.length>0&&(it==null?void 0:it.indexOf(_e.type))!==-1&&(_e.suitComb=["suit"])}_e.url=$[et]}),o(_)}).catch($=>{s($)})}),avatarComponentsModify=(a,i)=>new Promise((e,o)=>{var b;let s=[];const c=[],d=[];let _=i.some(k=>isSuit(k.type));if((b=a==null?void 0:a.components)==null||b.forEach(k=>{var _e;const j=i.find(et=>et.type===k.type),$=j&&((_e=a==null?void 0:a.components)==null?void 0:_e.find(et=>et.type===j.type&&et.units.some(tt=>tt.id===j.id)))!==void 0;if(j)if($)s.push(j);else{if(isPendant(k.type))return;const et=k.units.find(tt=>tt.isDefault)||k.units[0];et?s.push({type:k.type,id:et.id}):c.push(`component with type: ${k.type} without default and available unit`)}else if(isSuit(k.type)||isPendant(k.type)){const et=k.units.find(tt=>tt.isDefault);et&&s.push({type:k.type,id:et.id})}else{const et=k.units.find(tt=>tt.isDefault)||k.units[0];et?s.push({type:k.type,id:et.id}):c.push(`component with type: ${k.type} without default and available unit`)}}),_=s.some(k=>isSuit(k.type)),_){const k=a==null?void 0:a.components.find(j=>isSuit(j.type));s=s.filter(j=>(k==null?void 0:k.suitComb.indexOf(j.type))===-1)}c.length>0&&(log$o.error(c.join(", ")),o(c.join(", "))),d.length>0&&log$o.warn(d.join(", ")),e(s)}),positionPrecisionProtect=a=>{const{x:i,y:e,z:o}=a;return{x:+i.toFixed(2),y:+e.toFixed(2),z:+o.toFixed(2)}},rotationPrecisionProtect=a=>{const{pitch:i,yaw:e,roll:o}=a;return{pitch:+i.toFixed(2),yaw:+e.toFixed(2),roll:+o.toFixed(2)}},avatarComponentsValidate=(a,i)=>{a=a.filter(s=>s.type!=="effect");const e=[],o={};return Array.isArray(a)?(a.forEach(s=>{o[s.type]?o[s.type].num++:o[s.type]={num:1,isSuit:isSuit(s.type)}}),Object.keys(o).forEach(s=>{if(o[s].num>1&&!isPendant(s)&&e.push(new ParamError(`avatarComponent with type: ${s} repeated`)),o[s].isSuit){const c=i.components.find(d=>isSuit(d.type));c==null||c.suitComb.forEach(d=>{Object.keys(o).indexOf(d)>-1&&e.push(new ParamError(`suit already contains: ${d}, ${d} repeated`))})}}),e[0]):(e.push(new ParamError("avatarComponents must be array")),e[0])},safeParseComponents=a=>{let i=[];try{i=JSON.parse(a||"[]")}catch{i=[],log$o.error(`avatarComponents parse error: ${a}`)}return i};var QueueType=(a=>(a.Move="Move",a.Rotate="Rotate",a))(QueueType||{});class Queue{constructor(){ct(this,"queue",[]);ct(this,"currentAction")}async append(i){var e,o;this.queue.length===0||((e=this.currentAction)==null?void 0:e.type)===i.type&&this.queue.length===1?(this.queue=[],this.queue.push(i),await this.go()):(((o=this.queue[this.queue.length-1])==null?void 0:o.type)===i.type&&this.queue.pop(),this.queue.push(i))}async go(){if(this.queue.length!==0){const i=this.queue[0];this.currentAction=i,await i.action(),this.currentAction=void 0,this.queue.splice(0,1),await this.go()}}async reject(){this.queue=[]}}const log$n=new Logger("xverse-avatar");class XverseAvatar extends EventEmitter{constructor({userId:e,isHost:o,room:s,avatarId:c,isSelf:d,group:_=AvatarGroup.Npc}){super();ct(this,"xAvatar");ct(this,"_isHost",!1);ct(this,"_room");ct(this,"_withModel",!1);ct(this,"_userId");ct(this,"group",AvatarGroup.User);ct(this,"state","idle");ct(this,"isLoading",!0);ct(this,"_isMoving",!1);ct(this,"_isRotating",!1);ct(this,"_failed",!1);ct(this,"disconnected",!1);ct(this,"_avatarId");ct(this,"prioritySync",!1);ct(this,"priority",EAvatarRelationRank.Stranger);ct(this,"_avatarModel");ct(this,"_motionType",MotionType.Walk);ct(this,"isSelf",!1);ct(this,"_lastAnimTraceId","");ct(this,"statusSyncQueue",new Queue);ct(this,"extraInfo",{});ct(this,"attachedEffects",new Set);ct(this,"currentPathName","");ct(this,"setPosition",e=>{var o;!this._room.signal.isUpdatedYUV||(o=this.xAvatar)==null||o.setPosition(positionPrecisionProtect(e))});ct(this,"setRotation",e=>{var o;!this._room.signal.isUpdatedYUV||(o=this.xAvatar)==null||o.setRotation(rotationPrecisionProtect(e))});ct(this,"stopAnimation",()=>{var e,o;(o=(e=this.xAvatar)==null?void 0:e.controller)==null||o.stopAnimation()});ct(this,"_playAnimation",async(e,o=!0,s=!1)=>{var d;if(!this._room.signal.isUpdatedYUV)return;if(this.state!=="idle"&&!s)return log$n.warn("_playAnimation",e,"state is not idle, play animation failed"),Promise.resolve("_playAnimation, state is not idle");const c=Date.now();try{if(!((d=this.xAvatar)!=null&&d.controller))return Promise.reject(new InternalError(`[avatar: ${this.userId}] Play animation failed: ${e}, no controller`));this.isSelf&&setTimeout(()=>{log$n.infoAndReportMeasurement({tag:e,startTime:c,value:0,metric:"playAnimationStart"})});const _=uuid$1();this._lastAnimTraceId=_,await this.xAvatar.controller.playAnimation(e,o),_===this._lastAnimTraceId&&!this.isMoving&&!o&&e!=="Idle"&&this.xAvatar.controller.playAnimation("Idle",o).catch(b=>{log$n.error(`[avatar: ${this.userId}] Play animation failed [force idle]`,b)}),this.isSelf&&log$n.infoAndReportMeasurement({tag:e,startTime:c,extra:{loop:o},metric:"playAnimationEnd"})}catch(_){return log$n.error(`[avatar: ${this.userId}] Play animation failed: ${e}`,_),this.isSelf&&log$n.infoAndReportMeasurement({tag:e,startTime:c,metric:"playAnimationEnd",error:_,extra:{loop:o}}),Promise.reject(_)}});ct(this,"avatarComponentsSync",e=>{e=e.map(o=>({type:o.type,id:o.id})),this._room.actionsHandler.avatarComponentsSync(e)});ct(this,"hide",()=>{var e;if((e=this.xAvatar)!=null&&e.hide())return Promise.resolve(`avatar: ${this.userId} hide success`);{const o=`avatar: ${this.userId} hide failed ${!this.xAvatar&&"without instance: xAvatar"}`;return log$n.warn(o),Promise.reject(o)}});ct(this,"show",()=>{var e;if((e=this.xAvatar)!=null&&e.show())return Promise.resolve(`avatar: ${this.userId} show success`);{const o=`avatar: ${this.userId} show failed ${!this.xAvatar&&"without instance: xAvatar"}`;return log$n.warn(o),Promise.reject(o)}});ct(this,"sayTimer");this._userId=e,this._room=s,this.isSelf=d||!1,this._withModel=!!c,this._isHost=o||!1,this._avatarId=c,this.group=_,this._room.modelManager.getAvatarModelList().then(b=>{const k=b.find(j=>j.id===c);k&&(this._avatarModel=k)})}get avatarId(){return this._avatarId}get isRender(){var e;return!!((e=this.xAvatar)!=null&&e.isRender)}get isHidden(){var e;return!!((e=this.xAvatar)!=null&&e.isHide)}get motionType(){return this._motionType}set motionType(e){this._motionType=e}get nickname(){var e;return(e=this.xAvatar)==null?void 0:e.nickName}get words(){var e;return(e=this.xAvatar)==null?void 0:e.words}get isHost(){return this._isHost}get failed(){return this._failed}get scale(){var e;return(e=this.xAvatar)==null?void 0:e.scale}get animations(){var e;return!this.xAvatar||!this.xAvatar.controller?[]:((e=this.xAvatar)==null?void 0:e.getAvaliableAnimations())||[]}get position(){var e;return(e=this.xAvatar)==null?void 0:e.position}get rotation(){var e;return(e=this.xAvatar)==null?void 0:e.rotation}get pose(){return{position:this.position,angle:this.rotation}}get id(){return this.userId}get isMoving(){return this._isMoving}set isMoving(e){this._isMoving=e,this.state=e?"moving":"idle"}get isRotating(){return this._isRotating}set isRotating(e){this._isRotating=e,this.state=e?"rotating":"idle"}get withModel(){return this._withModel}get avatarComponents(){var e;return JSON.parse(JSON.stringify(((e=this.xAvatar)==null?void 0:e.clothesList)||[]))}get userId(){return this._userId}get removeWhenDisconnected(){return this.extraInfo&&this.extraInfo.removeWhenDisconnected!==void 0?this.extraInfo.removeWhenDisconnected:!0}setConnectionStatus(e){this.disconnected!==e&&(this.disconnected=e,e?this.emit("disconnected"):this.emit("reconnected"),log$n.warn(`avatar ${this.userId} status changed, disconnected:`,e))}setScale(e){var o;this.scale!==e&&((o=this.xAvatar)==null||o.setScale(e>0?e:1))}async playAnimation(e){const{animationName:o,loop:s,extra:c}=e||{};if(this.isSelf){if(this.isMoving)try{await this.stopMoving()}catch(_){return log$n.error(`stopMoving error before playAnimation ${o}`,_),Promise.reject(`stopMoving error before playAnimation ${o}`)}const d={info:{userId:this.userId,animation:o,loop:s,extra:encodeURIComponent(c||"")},broadcastType:CoreBroadcastType.PlayAnimation};this._room.avatarManager.broadcast.broadcast({data:d})}return this.isSelf&&(log$n.warn("animationStart emit",o),this.emit("animationStart",{animationName:o,extra:safeDecodeURIComponent(c||"")})),this._playAnimation(o,s).then(()=>{this.isSelf&&(log$n.warn("animationEnd emit",o),this.emit("animationEnd",{animationName:o,extra:safeDecodeURIComponent(c||"")}))})}async changeComponents(e){const{mode:o,endAnimation:s=""}=e||{},c=JSON.parse(JSON.stringify(e.avatarComponents));let d=avatarComponentsValidate(c,this._avatarModel);return!ChangeComponentsMode[o]&&!d&&(d=new ParamError(`changeComponents failed, mode: ${o} is invalid`)),d?(log$n.error(d),Promise.reject(d)):this._changeComponents({avatarComponents:c,mode:o,endAnimation:s}).then(()=>{this.isSelf&&o!==ChangeComponentsMode.Preview&&this.avatarComponentsSync(this.avatarComponents)})}async _changeComponents(e){var d,_,b,k;const{avatarComponents:o=[],mode:s}=e||{},c=Date.now();try{if(!this.xAvatar)return Promise.reject(new InternalError("changeComponents failed, without instance: xAvatar"));const j=await avatarComponentsModify(this._avatarModel,o),$=[];let _e=await avatarComponentsParser(this._avatarModel,j,this.avatarComponents);if((b=(_=(d=this.xAvatar)==null?void 0:d.component)==null?void 0:_.accessories)==null||b.forEach(et=>{j.find(tt=>tt.type===EDressType.PENDANT&&tt.id===et.name)?_e=_e.filter(tt=>!(tt.type===EDressType.PENDANT&&tt.id===et.name)):this.xAvatar.removeComponent(EDressType.PENDANT,et.pointId)}),_e.length===0)return this.avatarComponents;await this.beforeChangeComponentsHook(e);for(const et of _e){const{id:tt,type:rt,url:it,suitComb:nt}=et;$.push((k=this.xAvatar)==null?void 0:k.addComponent(tt,rt,it,nt))}return await Promise.all($),this.emit("componentsChanged",{components:this.avatarComponents,mode:s}),this.isSelf&&log$n.infoAndReportMeasurement({tag:"changeComponents",startTime:c,metric:"changeComponents",extra:{inputComponents:o,finalComponents:this.avatarComponents,mode:ChangeComponentsMode[s]}}),this.avatarComponents}catch(j){return this.isSelf&&log$n.infoAndReportMeasurement({tag:"changeComponents",startTime:c,metric:"changeComponents",error:j,extra:{inputComponents:o,finalComponents:this.avatarComponents,mode:ChangeComponentsMode[s]}}),Promise.reject(j)}}async beforeChangeComponentsHook(e){}turnTo(e){if(this._room.viewMode==="observer"){this._room.sceneManager.cameraComponent.MainCamera.setTarget(ue4Position2Xverse(e.point));return}return this._room.actionsHandler.turnTo(e).then(()=>{this.emit("viewChanged",{extra:(e==null?void 0:e.extra)||""})})}async moveTo(e){const{point:o,extra:s=""}=e||{};if(!this.position)return Promise.reject(new ParamError("avatar position is empty"));if(typeof s!="string"||typeof s=="string"&&s.length>64){const _="extra shoud be string which length less than 64";return log$n.warn(_),Promise.reject(new ParamError(_))}const d=getDistance(this.position,o)/100>100?MotionType.Run:MotionType.Walk;return this._room.actionsHandler.moveTo({point:o,motionType:d,extra:s})}async stopMoving(){if(!!this.isMoving)return this._room.actionsHandler.stopMoving()}rotateTo(e){return this._room.actionsHandler.rotateTo(e)}setRayCast(e){this.xAvatar&&(this.xAvatar.isRayCastEnable=e)}say(e,o){let s,c,d,_;if(typeof o=="object"?(s=o.duration,c=o.background,d=o.fontSize,_=o.fontColor):typeof o=="number"&&(s=o),this.sayTimer&&window.clearTimeout(this.sayTimer),!this.xAvatar){log$n.error("say failed, without instance: xAvatar");return}this.xAvatar.say(e,{scale:this.xAvatar.scale,isUser:this.group===AvatarGroup.User,background:c,fontsize:d,fontcolor:_}),!(s===void 0||s<=0)&&(this.sayTimer=window.setTimeout(()=>{this.silent()},s))}silent(){var e;if(!this.xAvatar){log$n.error("silent failed, without instance: xAvatar");return}(e=this.xAvatar)==null||e.silent()}setMotionType({type:e=MotionType.Walk}){return this.motionType===e?Promise.resolve():this._room.actionsHandler.setMotionType(e).then(()=>{this._motionType=e})}setNickname(e){return this._room.actionsHandler.setNickName(encodeURIComponent(e))}_setNickname(e){var s,c;if(!e)return;const o=safeDecodeURIComponent(e);((s=this.xAvatar)==null?void 0:s.nickName)!==o&&(this.isSelf&&(this._room.updateCurrentNetworkOptions({nickname:o}),this._room.options.nickname=o),(c=this.xAvatar)==null||c.setNickName(o,{scale:this.xAvatar.scale}))}_move(e){var k;const{start:o,end:s,walkSpeed:c,moveAnimation:d="Walking",inter:_=[],enforceRaycast:b=!1}=e||{};return(k=this.xAvatar)==null?void 0:k.move(o,s,c,d,_,b)}moveHermite(e){var k;const{start:o,end:s,moveAnimation:c="Walking",duration:d,tension:_,enforceRaycast:b=!1}=e||{};return(k=this.xAvatar)==null?void 0:k.moveHermite(o,s,d,_,c,b)}move(e){return this._move(e)}setPickBoxScale(e=1){return this.xAvatar?(this.xAvatar.setPickBoxScale(e),!0):(log$n.error("setPickBoxScale failed, without instance: xAvatar"),!1)}transfer(e){const{player:o,camera:s,areaName:c,attitude:d,pathName:_}=e;return this._room.actionsHandler.transfer({renderType:RenderType.RotationVideo,player:o,camera:s,areaName:c,attitude:d,pathName:_,tag:"transfer"})}avatarLoadedHook(){}avatarStartMovingHook(){}avatarStopMovingHook(){}async statusSync(e){var o,s,c;try{if((o=e.event)!=null&&o.rotateEvent){const{angle:d,speed:_}=e.event.rotateEvent,b=this.motionType===MotionType.Run?"Running":"Walking";this.rotation&&(this.rotation.yaw=this.rotation.yaw%360,d.yaw-this.rotation.yaw>180&&(d.yaw=180-d.yaw),this.isRotating=!0,await this.xAvatar.rotateTo(d,this.rotation,b).then(()=>{this._playAnimation("Idle",!0),this.isRotating=!1}))}if(e.event&&(((s=e.event)==null?void 0:s.points.length)||0)>1&&!this.isSelf){this.isMoving=!0,e.playerState.attitude&&(this._motionType=e.playerState.attitude);const d=this.getMotionAnimtion(this.motionType===MotionType.Run?"run":"walk"),_=this._room.skin.routeList.find(k=>k.areaName===this.currentPathName),b=((_==null?void 0:_.step)||7.5)*30*(25/30);this.position&&await this._move({start:this.position,end:e.event.points[e.event.points.length-1],walkSpeed:b,moveAnimation:d,inter:(c=e.event)==null?void 0:c.points.slice(0,-1)}).then(()=>{this.isMoving=!1})}}catch{return}}removeAttachedEffects(){this.attachedEffects.forEach((e,o)=>{this._room.effectManager.removeEffect(o)}),this.attachedEffects.clear()}removeAttachedEffect(e){this.attachedEffects.delete(e),this._room.effectManager.removeEffect(e)}getMotionAnimtion(e){return MotionAnimtion[e]||MotionAnimtion.idle}faceTo({point:e,rotateSpeed:o=.1}){return this.xAvatar.faceTo(e,o)}}var SyncEventType=(a=>(a[a.Reset=0]="Reset",a[a.Appear=1]="Appear",a[a.Disappear=2]="Disappear",a[a.Move=3]="Move",a[a.ChangeRenderInfo=4]="ChangeRenderInfo",a[a.KeepAlive=5]="KeepAlive",a[a.Rotate=6]="Rotate",a[a.ET_RemoveVisitor=7]="ET_RemoveVisitor",a))(SyncEventType||{}),MoveType=(a=>(a[a.Stop=0]="Stop",a[a.Moving=1]="Moving",a))(MoveType||{});const log$m=new Logger("xverse-avatar-manager"),Mr=class{constructor(i){ct(this,"xAvatarManager");ct(this,"_room");ct(this,"avatars",new Map);ct(this,"syncAvatarsLength",0);ct(this,"broadcast");this._room=i,this._usersStatistics(),this.broadcast=this.setupBroadcast(),i.on("skinChanged",()=>{this.avatars.forEach(e=>{e.disconnected&&this.removeAvatar(e.userId,!0)})})}setupBroadcast(){return new Broadcast(this._room,async i=>{const{broadcastType:e,info:o}=i;if(e!==CoreBroadcastType.PlayAnimation)return;const{userId:s,animation:c,extra:d,loop:_=!1}=o,b=this.avatars.get(s);b&&!b.isSelf&&(b.emit("animationStart",{animationName:c,extra:decodeURIComponent(d)}),await(b==null?void 0:b._playAnimation(c,_)),b.emit("animationEnd",{animationName:c,extra:decodeURIComponent(d)}))})}hideAll(i=!0){this.xAvatarManager.hideAll(i)}showAll(i=!0){this.xAvatarManager.showAll(i)}async init(){this.xAvatarManager=this._room.sceneManager.avatarComponent;try{const i=await this._room.modelManager.getAvatarModelList();if(i){await avatarLoader.parse(this._room.sceneManager,i);return}return Promise.reject("cannot find avatar config list")}catch(i){return log$m.error(i),Promise.reject("avatar mananger init error!"+i)}}async handleAvatar(i){if(this._room.viewMode==="simple"||!this._room.joined||!i.newUserStates)return;const e=i.newUserStates;if(i.actionType===Actions.GetNewUserState){this.syncAvatarsLength=(e||[]).length;const o=this._room.avatars.filter(d=>d.group==AvatarGroup.User);o.filter(d=>!(e!=null&&e.find(_=>_.userId==d.userId))).forEach(d=>{this.removeAvatar(d.userId)});const c=e.filter(d=>!o.find(_=>_.userId==d.userId));this._handleAvatar(c)}else this._handleAvatar(e)}async _handleAvatar(i){i==null||i.forEach(e=>{var s,c,d,_,b,k,j,$,_e;const o=this._room.userId===e.userId;if(((s=e.event)==null?void 0:s.type)===SyncEventType.ET_RemoveVisitor){const et=(d=(c=e.event)==null?void 0:c.removeVisitorEvent)==null?void 0:d.removeVisitorEvent,tt=JSON.parse(safeDecodeURIComponent(((b=(_=e.event)==null?void 0:_.removeVisitorEvent)==null?void 0:b.extraInfo)||"")),{code:rt,msg:it}=tt;et===RemoveVisitorType.RVT_ChangeToObserver?this._room.audienceViewModeHook(tt):et===RemoveVisitorType.RVT_MoveOutOfTheRoom&&this._room.leave(),this._room.proxyEvents("kicked",{code:rt,msg:it}),log$m.warn("kicked emit: ",{code:rt,msg:it})}if(e.event&&[SyncEventType.Appear,SyncEventType.Reset].includes(e.event.type)){let et=this.avatars.get(e.userId);if(et&&e.playerState.avatarId&&(et==null?void 0:et.avatarId)!==e.playerState.avatarId&&(et=void 0,this.removeAvatar(e.userId,!0)),et){if(e.playerState.pathName&&(et.currentPathName=e.playerState.pathName),et.disconnected&&et.setConnectionStatus(!1),(k=e.event)!=null&&k.id&&this._room.actionsHandler.confirmEvent(e.event.id),e.playerState.nickName&&(et==null||et._setNickname(e.playerState.nickName)),e.playerState.avatarComponents&&!et.isSelf&&et.xAvatar){const tt=safeParseComponents(e.playerState.avatarComponents);et._changeComponents({avatarComponents:tt,mode:ChangeComponentsMode.Preview})}if(!et.isSelf&&et.position&&(et.statusSyncQueue.queue.length===0||!et.statusSyncQueue.currentAction)){const{x:tt,y:rt}=et.position,{x:it,y:nt}=e.playerState.player.position;(Math.abs(tt-it)>50||Math.abs(rt-nt)>50)&&(et.setPosition(e.playerState.player.position),et.setRotation(e.playerState.player.angle))}}else{if(!e.playerState.player)return;const{position:tt,angle:rt}=e.playerState.player,it=e.playerState.avatarId,nt=e.playerState.prioritySync,ot=safelyJsonParse(e.playerState.extra),at=safeParseComponents(e.playerState.avatarComponents),st=safeDecodeURIComponent(e.playerState.nickName),ut=this.calculatePriority(e.userId,ot);this.addAvatar({userId:e.userId,isHost:e.playerState.isHost,nickname:st,avatarPosition:tt,avatarRotation:rt,avatarScale:e.playerState.avatarSize,avatarId:it,avatarComponents:e.playerState.person===Person.First?[]:at,priority:ut,group:AvatarGroup.User,prioritySync:nt,extraInfo:ot}).then(ft=>{var lt;e.playerState.pathName&&(ft.currentPathName=e.playerState.pathName),(lt=e.event)!=null&&lt.id&&this._room.actionsHandler.confirmEvent(e.event.id),this.updateAvatarPositionAndRotation(e),o&&(this.xAvatarManager.setMainAvatar(e.userId),this._room.emit("userAvatarLoaded"),log$m.info("userAvatarLoaded"))}).catch(ft=>{o&&(this.xAvatarManager.setMainAvatar(e.userId),this._room.emit("userAvatarFailed",{error:ft}),log$m.error("userAvatarFailed",ft))})}}if(e.event&&SyncEventType.Disappear===e.event.type&&((j=e==null?void 0:e.event)!=null&&j.id&&this._room.actionsHandler.confirmEvent(e.event.id),this.removeAvatar(e.userId)),e.event&&[SyncEventType.Move,SyncEventType.ChangeRenderInfo].includes(e.event.type)||!e.event){($=e==null?void 0:e.event)!=null&&$.id&&this._room.actionsHandler.confirmEvent(e.event.id);const et=this.avatars.get(e.userId);et&&et.withModel&&!et.isLoading&&this.updateAvatarPositionAndRotation(e)}if(!o&&((_e=e.event)==null?void 0:_e.type)===SyncEventType.Rotate){const et=this.avatars.get(e.userId);et.statusSyncQueue.append({type:QueueType.Rotate,action:()=>et.statusSync(e)})}})}calculatePriority(i,e){var s;return i===this._room.userId?EAvatarRelationRank.Self:(s=this._room.options.firends)!=null&&s.includes(i)?EAvatarRelationRank.Friend:EAvatarRelationRank.Stranger}updateAvatarPositionAndRotation(i){var e,o;if((e=i==null?void 0:i.playerState)!=null&&e.player){let{position:s,angle:c}=i.playerState.player;const d=this.avatars.get(i.userId);if(!d)return;if(s=positionPrecisionProtect(s),c=rotationPrecisionProtect(c),d.isSelf&&!this._room.networkController.rtcp.workers.inPanoMode&&(d.setPosition(s),d.setRotation(c)),i.event&&(((o=i.event)==null?void 0:o.points.length)||0)>1&&!d.isSelf&&d.statusSyncQueue.append({type:QueueType.Move,action:()=>d.statusSync(i)}),i.renderInfo&&d.isSelf){const{isMoving:_,isRotating:b}=i.renderInfo;this._updateAvatarMovingStatus({id:i.userId,isMoving:!!_,isRotating:!!b})}}}async addAvatar(i){const{userId:e,isHost:o,avatarPosition:s,avatarId:c,avatarRotation:d,nickname:_,avatarComponents:b=[],priority:k,group:j=AvatarGroup.Npc,avatarScale:$=DEFAULT_AVATAR_SCALE$1,extraInfo:_e,prioritySync:et}=i,tt=e===this._room.userId;let rt=this.avatars.get(e);if(rt)return Promise.resolve(rt);if(rt=new Mr.subAvatar({userId:e,isHost:o,isSelf:tt,room:this._room,avatarComponents:b,avatarId:c,nickname:_,group:j}),this.avatars.set(e,rt),!rt.withModel)return rt.isLoading=!1,rt.avatarLoadedHook(),this._room.emit("avatarChanged",{avatars:this._room.avatars}),rt;const nt=(await this._room.modelManager.getAvatarModelList()).find(at=>at.id===c),ot=Date.now();if(!nt)return this._room.emit("avatarChanged",{avatars:this._room.avatars}),this.avatars.delete(e),Promise.reject(`no such avatar model with id: ${c}`);try{let at=await avatarComponentsModify(nt,b);at=at.filter(ft=>ft.type!="pendant");const st=await avatarComponentsParser(nt,at),ut=await this.xAvatarManager.loadAvatar({id:e,avatarType:c,priority:k,avatarManager:this.xAvatarManager,assets:st,status:{avatarPosition:s,avatarRotation:d,avatarScale:$}})._timeout(8e3,new TimeoutError$1("loadAvatar timeout(8s)"));return ut.setPickBoxScale(e===this._room.userId?0:1),rt.xAvatar=ut,rt.setScale($),s&&rt.setPosition(s),rt.extraInfo=_e,rt.priority=k,rt.isLoading=!1,rt.prioritySync=!!et,rt._playAnimation("Idle",!0,!0),rt.avatarLoadedHook(),this._room.emit("avatarChanged",{avatars:this._room.avatars}),_&&rt._setNickname(_),e===this._room.userId&&(log$m.infoAndReportMeasurement({metric:"avatarLoadDuration",startTime:ot,group:"costs"}),log$m.infoAndReportMeasurement({metric:"avatarLoadAt",startTime:this._room._startTime,group:"costs"})),rt}catch(at){return rt.isLoading=!1,this._room.emit("avatarChanged",{avatars:this._room.avatars}),log$m.error(at),Promise.reject(at)}}removeAvatar(i,e=!1){const o=this.avatars.get(i);if(!!o){if(o.removeWhenDisconnected||e){o.removeAttachedEffects(),o.xAvatar&&this.xAvatarManager.deleteAvatar(o.xAvatar),this.avatars.delete(i),this._room.emit("avatarChanged",{avatars:this._room.avatars});return}o.setConnectionStatus(!0)}}clearOtherUsers(){this.avatars.forEach(i=>{!i.isSelf&&i.group===AvatarGroup.User&&this.removeAvatar(i.userId)})}async _updateAvatarMovingStatus(i){var d,_;const{id:e,isMoving:o,isRotating:s}=i,c=this.avatars.get(e);if(!!c){if(c.isRotating!==s){c.isRotating=s;let b=c.getMotionAnimtion("idle");s&&(b=c.getMotionAnimtion("walk"),c.motionType===MotionType.Run&&(b=c.getMotionAnimtion("run"))),c._playAnimation(b,!0,!0),log$m.infoAndReportMeasurement({startTime:Date.now(),value:0,metric:s?"userAvatarStartRotating":"userAvatarStopRotating",extra:{motionType:c.motionType,moveToExtra:this._room.moveToExtra}})}if(c.isMoving!==o){c.isMoving=o;let b=c.getMotionAnimtion("idle");o&&(b=c.getMotionAnimtion("walk"),c.motionType===MotionType.Run&&(b=c.getMotionAnimtion("run"))),o?(c.avatarStartMovingHook(),c.isSelf&&(log$m.warn("startMoving emit",this._room.moveToExtra),c.emit("startMoving",{target:c,extra:this._room.moveToExtra}))):(c.avatarStopMovingHook(),c.isSelf&&(log$m.warn("stopMoving emit",this._room.moveToExtra),c.emit("stopMoving",{target:c,extra:this._room.moveToExtra}))),c._playAnimation(b,!0,!0),log$m.infoAndReportMeasurement({startTime:Date.now(),value:0,metric:o?"userAvatarStartMoving":"userAvatarStopMoving",extra:{motionType:c.motionType,moveToExtra:this._room.moveToExtra}})}if(o&&((_=(d=c.xAvatar)==null?void 0:d.controller)==null?void 0:_.onPlay)==="Idle"){let b="Walking";c.motionType===MotionType.Run&&(b="Running"),log$m.error("force avoiding slide step"),c._playAnimation(b,!0,!0)}}}_usersStatistics(){this._room.on("userAvatarLoaded",()=>{window.setInterval(()=>{const i=this._room.avatars.filter(o=>o.group===AvatarGroup.User).length||0,e=this._room.avatars.filter(o=>o.group===AvatarGroup.User&&o.isRender).length||0;this._room.stats.assign({userNum:i,syncUserNum:this.syncAvatarsLength,renderedUserNum:e})},3e3)})}};let XverseAvatarManager=Mr;ct(XverseAvatarManager,"subAvatar",XverseAvatar);const log$l=new Logger("Wsutils"),isPositionCorrect=a=>!isObject(a)||isObject(a)&&(!isNumber(a.x)||!isNumber(a.y)||!isNumber(a.z))?(log$l.error("position is required and must be an object with x y and z property",a),!1):!0,isRotationCorrect=a=>!isObject(a)||isObject(a)&&(!isNumber(a.pitch)||!isNumber(a.yaw)||!isNumber(a.roll))?(log$l.error("rotation is required and must be an object with pitch yaw and roll property",a),!1):!0,isNumber=a=>getDataType(a)==="Number",isObject=a=>getDataType(a)==="Object",getDataType=a=>Object.prototype.toString.call(a).slice(8,-1);function downloadFileByBase64(a,i){const e=dataURLtoBlob(a),o=URL.createObjectURL(e);downloadFile(o,i)}function dataURLtoBlob(a){var d;const i=a.split(","),e=(d=i[0].match(/:(.*?);/))==null?void 0:d[1],o=atob(i[1]);let s=o.length;const c=new Uint8Array(s);for(;s--;)c[s]=o.charCodeAt(s);return new Blob([c],{type:e})}function downloadFile(a,i="screenShot.png"){const e=document.createElement("a");e.setAttribute("href",a),e.setAttribute("download",i),e.setAttribute("target","_blank");const o=document.createEvent("MouseEvents");o.initEvent("click",!0,!0),e.dispatchEvent(o)}const distance=(a,i)=>{const e=i.x-a.x,o=i.y-a.y;return Math.sqrt(e*e+o*o)},angle=(a,i)=>{const e=i.x-a.x,o=i.y-a.y;return degrees(Math.atan2(o,e))},findCoord=(a,i,e)=>{const o={x:0,y:0};return e=radians(e),o.x=a.x-i*Math.cos(e),o.y=a.y-i*Math.sin(e),o},radians=a=>a*(Math.PI/180),degrees=a=>a*(180/Math.PI),isPressed=a=>isNaN(a.buttons)?a.pressure!==0:a.buttons!==0,timers=new Map,throttle=a=>{timers.has(a)&&clearTimeout(timers.get(a)),timers.set(a,setTimeout(a,100))},bindEvt=(a,i,e)=>{const o=i.split(/[ ,]+/g);let s;for(let c=0;c<o.length;c+=1)s=o[c],a.addEventListener?a.addEventListener(s,e,!1):a.attachEvent&&a.attachEvent(s,e)},unbindEvt=(a,i,e)=>{const o=i.split(/[ ,]+/g);let s;for(let c=0;c<o.length;c+=1)s=o[c],a.removeEventListener?a.removeEventListener(s,e):a.detachEvent&&a.detachEvent(s,e)},prepareEvent=a=>(a.preventDefault(),a.type.match(/^touch/)?a.changedTouches:a),getScroll=()=>{const a=window.pageXOffset!==void 0?window.pageXOffset:(document.documentElement||document.body.parentNode||document.body).scrollLeft,i=window.pageYOffset!==void 0?window.pageYOffset:(document.documentElement||document.body.parentNode||document.body).scrollTop;return{x:a,y:i}},applyPosition=(a,i)=>{i.top||i.right||i.bottom||i.left?(a.style.top=i.top,a.style.right=i.right,a.style.bottom=i.bottom,a.style.left=i.left):(a.style.left=i.x+"px",a.style.top=i.y+"px")},getTransitionStyle=(a,i,e)=>{const o=configStylePropertyObject(a);for(let s in o)if(o.hasOwnProperty(s))if(typeof i=="string")o[s]=i+" "+e;else{let c="";for(let d=0,_=i.length;d<_;d+=1)c+=i[d]+" "+e+", ";o[s]=c.slice(0,-2)}return o},getVendorStyle=(a,i)=>{const e=configStylePropertyObject(a);for(let o in e)e.hasOwnProperty(o)&&(e[o]=i);return e},configStylePropertyObject=a=>{const i={};return i[a]="",["webkit","Moz","o"].forEach(function(o){i[o+a.charAt(0).toUpperCase()+a.slice(1)]=""}),i},extend=(a,i)=>{for(let e in i)i.hasOwnProperty(e)&&(a[e]=i[e]);return a},safeExtend=(a,i)=>{const e={};for(let o in a)a.hasOwnProperty(o)&&i.hasOwnProperty(o)?e[o]=i[o]:a.hasOwnProperty(o)&&(e[o]=a[o]);return e},map=(a,i)=>{if(a.length)for(let e=0,o=a.length;e<o;e+=1)i(a[e]);else i(a)},clamp=(a,i,e)=>({x:Math.min(Math.max(a.x,i.x-e),i.x+e),y:Math.min(Math.max(a.y,i.y-e),i.y+e)});var isTouch="ontouchstart"in window,isPointer=!!window.PointerEvent,isMSPointer=!!window.MSPointerEvent,events={touch:{start:"touchstart",move:"touchmove",end:"touchend, touchcancel"},mouse:{start:"mousedown",move:"mousemove",end:"mouseup"},pointer:{start:"pointerdown",move:"pointermove",end:"pointerup, pointercancel"},MSPointer:{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}},toBind,secondBind={};isPointer?toBind=events.pointer:isMSPointer?toBind=events.MSPointer:isTouch?(toBind=events.touch,secondBind=events.mouse):toBind=events.mouse;function Super(){}Super.prototype.on=function(a,i){var e=this,o=a.split(/[ ,]+/g),s;e._handlers_=e._handlers_||{};for(var c=0;c<o.length;c+=1)s=o[c],e._handlers_[s]=e._handlers_[s]||[],e._handlers_[s].push(i);return e};Super.prototype.off=function(a,i){var e=this;return e._handlers_=e._handlers_||{},a===void 0?e._handlers_={}:i===void 0?e._handlers_[a]=null:e._handlers_[a]&&e._handlers_[a].indexOf(i)>=0&&e._handlers_[a].splice(e._handlers_[a].indexOf(i),1),e};Super.prototype.trigger=function(a,i){var e=this,o=a.split(/[ ,]+/g),s;e._handlers_=e._handlers_||{};for(var c=0;c<o.length;c+=1)s=o[c],e._handlers_[s]&&e._handlers_[s].length&&e._handlers_[s].forEach(function(d){d.call(e,{type:s,target:e},i)})};Super.prototype.config=function(a){var i=this;i.options=i.defaults||{},a&&(i.options=safeExtend(i.options,a))};Super.prototype.bindEvt=function(a,i){var e=this;return e._domHandlers_=e._domHandlers_||{},e._domHandlers_[i]=function(){typeof e["on"+i]=="function"?e["on"+i].apply(e,arguments):console.warn('[WARNING] : Missing "on'+i+'" handler.')},bindEvt(a,toBind[i],e._domHandlers_[i]),secondBind[i]&&bindEvt(a,secondBind[i],e._domHandlers_[i]),e};Super.prototype.unbindEvt=function(a,i){var e=this;return e._domHandlers_=e._domHandlers_||{},unbindEvt(a,toBind[i],e._domHandlers_[i]),secondBind[i]&&unbindEvt(a,secondBind[i],e._domHandlers_[i]),delete e._domHandlers_[i],this};function Nipple(a,i){return this.identifier=i.identifier,this.position=i.position,this.frontPosition=i.frontPosition,this.collection=a,this.defaults={size:100,threshold:.1,color:"white",fadeTime:250,dataOnly:!1,restJoystick:!0,restOpacity:.5,mode:"dynamic",zone:document.body,lockX:!1,lockY:!1,shape:"circle"},this.config(i),this.options.mode==="dynamic"&&(this.options.restOpacity=0),this.id=Nipple.id,Nipple.id+=1,this.buildEl().stylize(),this.instance={el:this.ui.el,on:this.on.bind(this),off:this.off.bind(this),show:this.show.bind(this),hide:this.hide.bind(this),add:this.addToDom.bind(this),remove:this.removeFromDom.bind(this),destroy:this.destroy.bind(this),setPosition:this.setPosition.bind(this),resetDirection:this.resetDirection.bind(this),computeDirection:this.computeDirection.bind(this),trigger:this.trigger.bind(this),position:this.position,frontPosition:this.frontPosition,ui:this.ui,identifier:this.identifier,id:this.id,options:this.options},this.instance}Nipple.prototype=new Super;Nipple.constructor=Nipple;Nipple.id=0;Nipple.prototype.buildEl=function(a){return this.ui={},this.options.dataOnly?this:(this.ui.el=document.createElement("div"),this.ui.back=document.createElement("div"),this.ui.front=document.createElement("div"),this.ui.el.className="nipple collection_"+this.collection.id,this.ui.back.className="back",this.ui.front.className="front",this.ui.el.setAttribute("id","nipple_"+this.collection.id+"_"+this.id),this.ui.el.appendChild(this.ui.back),this.ui.el.appendChild(this.ui.front),this)};Nipple.prototype.stylize=function(){if(this.options.dataOnly)return this;var a=this.options.fadeTime+"ms",i=getVendorStyle("borderRadius","50%"),e=getTransitionStyle("transition","opacity",a),o={};return o.el={position:"absolute",opacity:this.options.restOpacity,display:"block",zIndex:999},o.back={position:"absolute",display:"block",width:this.options.size+"px",height:this.options.size+"px",marginLeft:-this.options.size/2+"px",marginTop:-this.options.size/2+"px",background:this.options.color,opacity:".5"},o.front={width:this.options.size/2+"px",height:this.options.size/2+"px",position:"absolute",display:"block",marginLeft:-this.options.size/4+"px",marginTop:-this.options.size/4+"px",background:this.options.color,opacity:".5"},extend(o.el,e),this.options.shape==="circle"&&extend(o.back,i),extend(o.front,i),this.applyStyles(o),this};Nipple.prototype.applyStyles=function(a){for(var i in this.ui)if(this.ui.hasOwnProperty(i))for(var e in a[i])this.ui[i].style[e]=a[i][e];return this};Nipple.prototype.addToDom=function(){return this.options.dataOnly||document.body.contains(this.ui.el)?this:(this.options.zone.appendChild(this.ui.el),this)};Nipple.prototype.removeFromDom=function(){return this.options.dataOnly||!document.body.contains(this.ui.el)?this:(this.options.zone.removeChild(this.ui.el),this)};Nipple.prototype.destroy=function(){clearTimeout(this.removeTimeout),clearTimeout(this.showTimeout),clearTimeout(this.restTimeout),this.trigger("destroyed",this.instance),this.removeFromDom(),this.off()};Nipple.prototype.show=function(a){var i=this;return i.options.dataOnly||(clearTimeout(i.removeTimeout),clearTimeout(i.showTimeout),clearTimeout(i.restTimeout),i.addToDom(),i.restCallback(),setTimeout(function(){i.ui.el.style.opacity=1},0),i.showTimeout=setTimeout(function(){i.trigger("shown",i.instance),typeof a=="function"&&a.call(this)},i.options.fadeTime)),i};Nipple.prototype.hide=function(a){var i=this;return i.options.dataOnly||(i.ui.el.style.opacity=i.options.restOpacity,clearTimeout(i.removeTimeout),clearTimeout(i.showTimeout),clearTimeout(i.restTimeout),i.removeTimeout=setTimeout(function(){var e=i.options.mode==="dynamic"?"none":"block";i.ui.el.style.display=e,typeof a=="function"&&a.call(i),i.trigger("hidden",i.instance)},i.options.fadeTime),i.options.restJoystick&&i.setPosition(a,{x:0,y:0})),i};Nipple.prototype.setPosition=function(a,i){var e=this;e.frontPosition={x:i.x,y:i.y};var o=e.options.fadeTime+"ms",s={};s.front=getTransitionStyle("transition",["top","left"],o);var c={front:{}};c.front={left:e.frontPosition.x+"px",top:e.frontPosition.y+"px"},e.applyStyles(s),e.applyStyles(c),e.restTimeout=setTimeout(function(){typeof a=="function"&&a.call(e),e.restCallback()},e.options.fadeTime)};Nipple.prototype.restCallback=function(){var a=this,i={};i.front=getTransitionStyle("transition","none",""),a.applyStyles(i),a.trigger("rested",a.instance)};Nipple.prototype.resetDirection=function(){this.direction={x:!1,y:!1,angle:!1}};Nipple.prototype.computeDirection=function(a){var i=a.angle.radian,e=Math.PI/4,o=Math.PI/2,s,c,d;if(i>e&&i<e*3&&!a.lockX?s="up":i>-e&&i<=e&&!a.lockY?s="left":i>-e*3&&i<=-e&&!a.lockX?s="down":a.lockY||(s="right"),a.lockY||(i>-o&&i<o?c="left":c="right"),a.lockX||(i>0?d="up":d="down"),a.force>this.options.threshold){var _={},b;for(b in this.direction)this.direction.hasOwnProperty(b)&&(_[b]=this.direction[b]);var k={};this.direction={x:c,y:d,angle:s},a.direction=this.direction;for(b in _)_[b]===this.direction[b]&&(k[b]=!0);if(k.x&&k.y&&k.angle)return a;(!k.x||!k.y)&&this.trigger("plain",a),k.x||this.trigger("plain:"+c,a),k.y||this.trigger("plain:"+d,a),k.angle||this.trigger("dir dir:"+s,a)}else this.resetDirection();return a};function Collection(a,i){var e=this;return e.nipples=[],e.idles=[],e.actives=[],e.ids=[],e.pressureIntervals={},e.manager=a,e.id=Collection.id,Collection.id+=1,e.defaults={zone:document.body,multitouch:!1,maxNumberOfNipples:10,mode:"dynamic",position:{top:0,left:0},catchDistance:200,size:100,threshold:.1,color:"white",fadeTime:250,dataOnly:!1,restJoystick:!0,restOpacity:.5,lockX:!1,lockY:!1,shape:"circle",dynamicPage:!1,follow:!1},e.config(i),(e.options.mode==="static"||e.options.mode==="semi")&&(e.options.multitouch=!1),e.options.multitouch||(e.options.maxNumberOfNipples=1),e.updateBox(),e.prepareNipples(),e.bindings(),e.begin(),e.nipples}Collection.prototype=new Super;Collection.constructor=Collection;Collection.id=0;Collection.prototype.prepareNipples=function(){var a=this,i=a.nipples;i.on=a.on.bind(a),i.off=a.off.bind(a),i.options=a.options,i.destroy=a.destroy.bind(a),i.ids=a.ids,i.id=a.id,i.processOnMove=a.processOnMove.bind(a),i.processOnEnd=a.processOnEnd.bind(a),i.get=function(e){if(e===void 0)return i[0];for(var o=0,s=i.length;o<s;o+=1)if(i[o].identifier===e)return i[o];return!1}};Collection.prototype.bindings=function(){var a=this;a.bindEvt(a.options.zone,"start"),a.options.zone.style.touchAction="none",a.options.zone.style.msTouchAction="none"};Collection.prototype.begin=function(){var a=this,i=a.options;if(i.mode==="static"){var e=a.createNipple(i.position,a.manager.getIdentifier());e.add(),a.idles.push(e)}};Collection.prototype.createNipple=function(a,i){var e=this,o=e.manager.scroll,s={},c=e.options;if(a.x&&a.y)s={x:a.x-(o.x+e.box.left),y:a.y-(o.y+e.box.top)};else if(a.top||a.right||a.bottom||a.left){var d=document.createElement("DIV");d.style.display="hidden",d.style.top=a.top,d.style.right=a.right,d.style.bottom=a.bottom,d.style.left=a.left,d.style.position="absolute",c.zone.appendChild(d);var _=d.getBoundingClientRect();c.zone.removeChild(d),s=a,a={x:_.left+o.x,y:_.top+o.y}}var b=new Nipple(e,{color:c.color,size:c.size,threshold:c.threshold,fadeTime:c.fadeTime,dataOnly:c.dataOnly,restJoystick:c.restJoystick,restOpacity:c.restOpacity,mode:c.mode,identifier:i,position:a,zone:c.zone,frontPosition:{x:0,y:0},shape:c.shape});return c.dataOnly||(applyPosition(b.ui.el,s),applyPosition(b.ui.front,b.frontPosition)),e.nipples.push(b),e.trigger("added "+b.identifier+":added",b),e.manager.trigger("added "+b.identifier+":added",b),e.bindNipple(b),b};Collection.prototype.updateBox=function(){var a=this;a.box=a.options.zone.getBoundingClientRect()};Collection.prototype.bindNipple=function(a){var i=this,e,o=function(s,c){e=s.type+" "+c.id+":"+s.type,i.trigger(e,c)};a.on("destroyed",i.onDestroyed.bind(i)),a.on("shown hidden rested dir plain",o),a.on("dir:up dir:right dir:down dir:left",o),a.on("plain:up plain:right plain:down plain:left",o)};Collection.prototype.pressureFn=function(a,i,e){var o=this,s=0;clearInterval(o.pressureIntervals[e]),o.pressureIntervals[e]=setInterval(function(){var c=a.force||a.pressure||a.webkitForce||0;c!==s&&(i.trigger("pressure",c),o.trigger("pressure "+i.identifier+":pressure",c),s=c)}.bind(o),100)};Collection.prototype.onstart=function(a){var i=this,e=i.options,o=a;a=prepareEvent(a),i.updateBox();var s=function(c){i.actives.length<e.maxNumberOfNipples?i.processOnStart(c):o.type.match(/^touch/)&&(Object.keys(i.manager.ids).forEach(function(d){if(Object.values(o.touches).findIndex(function(b){return b.identifier===d})<0){var _=[a[0]];_.identifier=d,i.processOnEnd(_)}}),i.actives.length<e.maxNumberOfNipples&&i.processOnStart(c))};return map(a,s),i.manager.bindDocument(),!1};Collection.prototype.processOnStart=function(a){var i=this,e=i.options,o,s=i.manager.getIdentifier(a),c=a.force||a.pressure||a.webkitForce||0,d={x:a.pageX,y:a.pageY},_=i.getOrCreate(s,d);_.identifier!==s&&i.manager.removeIdentifier(_.identifier),_.identifier=s;var b=function(j){j.trigger("start",j),i.trigger("start "+j.id+":start",j),j.show(),c>0&&i.pressureFn(a,j,j.identifier),i.processOnMove(a)};if((o=i.idles.indexOf(_))>=0&&i.idles.splice(o,1),i.actives.push(_),i.ids.push(_.identifier),e.mode!=="semi")b(_);else{var k=distance(d,_.position);if(k<=e.catchDistance)b(_);else{_.destroy(),i.processOnStart(a);return}}return _};Collection.prototype.getOrCreate=function(a,i){var e=this,o=e.options,s;return/(semi|static)/.test(o.mode)?(s=e.idles[0],s?(e.idles.splice(0,1),s):o.mode==="semi"?e.createNipple(i,a):(console.warn("Coudln't find the needed nipple."),!1)):(s=e.createNipple(i,a),s)};Collection.prototype.processOnMove=function(a){var i=this,e=i.options,o=i.manager.getIdentifier(a),s=i.nipples.get(o),c=i.manager.scroll;if(!isPressed(a)){this.processOnEnd(a);return}if(!s){console.error("Found zombie joystick with ID "+o),i.manager.removeIdentifier(o);return}if(e.dynamicPage){var d=s.el.getBoundingClientRect();s.position={x:c.x+d.left,y:c.y+d.top}}s.identifier=o;var _=s.options.size/2,b={x:a.pageX,y:a.pageY};e.lockX&&(b.y=s.position.y),e.lockY&&(b.x=s.position.x);var k=distance(b,s.position),j=angle(b,s.position),$=radians(j),_e=k/_,et={distance:k,position:b},tt,rt;if(s.options.shape==="circle"?(tt=Math.min(k,_),rt=findCoord(s.position,tt,j)):(rt=clamp(b,s.position,_),tt=distance(rt,s.position)),e.follow){if(k>_){let at=b.x-rt.x,st=b.y-rt.y;s.position.x+=at,s.position.y+=st,s.el.style.top=s.position.y-(i.box.top+c.y)+"px",s.el.style.left=s.position.x-(i.box.left+c.x)+"px",k=distance(b,s.position)}}else b=rt,k=tt;var it=b.x-s.position.x,nt=b.y-s.position.y;s.frontPosition={x:it,y:nt},e.dataOnly||applyPosition(s.ui.front,s.frontPosition);var ot={identifier:s.identifier,position:b,force:_e,pressure:a.force||a.pressure||a.webkitForce||0,distance:k,angle:{radian:$,degree:j},vector:{x:it/_,y:-nt/_},raw:et,instance:s,lockX:e.lockX,lockY:e.lockY};ot=s.computeDirection(ot),ot.angle={radian:radians(180-j),degree:180-j},s.trigger("move",ot),i.trigger("move "+s.id+":move",ot)};Collection.prototype.processOnEnd=function(a){var i=this,e=i.options,o=i.manager.getIdentifier(a),s=i.nipples.get(o),c=i.manager.removeIdentifier(s.identifier);!s||(e.dataOnly||s.hide(function(){e.mode==="dynamic"&&(s.trigger("removed",s),i.trigger("removed "+s.id+":removed",s),i.manager.trigger("removed "+s.id+":removed",s),s.destroy())}),clearInterval(i.pressureIntervals[s.identifier]),s.resetDirection(),s.trigger("end",s),i.trigger("end "+s.id+":end",s),i.ids.indexOf(s.identifier)>=0&&i.ids.splice(i.ids.indexOf(s.identifier),1),i.actives.indexOf(s)>=0&&i.actives.splice(i.actives.indexOf(s),1),/(semi|static)/.test(e.mode)?i.idles.push(s):i.nipples.indexOf(s)>=0&&i.nipples.splice(i.nipples.indexOf(s),1),i.manager.unbindDocument(),/(semi|static)/.test(e.mode)&&(i.manager.ids[c.id]=c.identifier))};Collection.prototype.onDestroyed=function(a,i){var e=this;e.nipples.indexOf(i)>=0&&e.nipples.splice(e.nipples.indexOf(i),1),e.actives.indexOf(i)>=0&&e.actives.splice(e.actives.indexOf(i),1),e.idles.indexOf(i)>=0&&e.idles.splice(e.idles.indexOf(i),1),e.ids.indexOf(i.identifier)>=0&&e.ids.splice(e.ids.indexOf(i.identifier),1),e.manager.removeIdentifier(i.identifier),e.manager.unbindDocument()};Collection.prototype.destroy=function(){var a=this;a.unbindEvt(a.options.zone,"start"),a.nipples.forEach(function(e){e.destroy()});for(var i in a.pressureIntervals)a.pressureIntervals.hasOwnProperty(i)&&clearInterval(a.pressureIntervals[i]);a.trigger("destroyed",a.nipples),a.manager.unbindDocument(),a.off()};function Manager(a){var i=this;i.ids={},i.index=0,i.collections=[],i.scroll=getScroll(),i.config(a),i.prepareCollections();var e=function(){var s;i.collections.forEach(function(c){c.forEach(function(d){s=d.el.getBoundingClientRect(),d.position={x:i.scroll.x+s.left,y:i.scroll.y+s.top}})})};bindEvt(window,"resize",function(){throttle(e)});var o=function(){i.scroll=getScroll()};return bindEvt(window,"scroll",function(){throttle(o)}),i.collections}Manager.prototype=new Super;Manager.constructor=Manager;Manager.prototype.prepareCollections=function(){var a=this;a.collections.create=a.create.bind(a),a.collections.on=a.on.bind(a),a.collections.off=a.off.bind(a),a.collections.destroy=a.destroy.bind(a),a.collections.get=function(i){var e;return a.collections.every(function(o){return e=o.get(i),!e}),e}};Manager.prototype.create=function(a){return this.createCollection(a)};Manager.prototype.createCollection=function(a){var i=this,e=new Collection(i,a);return i.bindCollection(e),i.collections.push(e),e};Manager.prototype.bindCollection=function(a){var i=this,e,o=function(s,c){e=s.type+" "+c.id+":"+s.type,i.trigger(e,c)};a.on("destroyed",i.onDestroyed.bind(i)),a.on("shown hidden rested dir plain",o),a.on("dir:up dir:right dir:down dir:left",o),a.on("plain:up plain:right plain:down plain:left",o)};Manager.prototype.bindDocument=function(){var a=this;a.binded||(a.bindEvt(document,"move").bindEvt(document,"end"),a.binded=!0)};Manager.prototype.unbindDocument=function(a){var i=this;(!Object.keys(i.ids).length||a===!0)&&(i.unbindEvt(document,"move").unbindEvt(document,"end"),i.binded=!1)};Manager.prototype.getIdentifier=function(a){var i;return a?(i=a.identifier===void 0?a.pointerId:a.identifier,i===void 0&&(i=this.latest||0)):i=this.index,this.ids[i]===void 0&&(this.ids[i]=this.index,this.index+=1),this.latest=i,this.ids[i]};Manager.prototype.removeIdentifier=function(a){var i={};for(var e in this.ids)if(this.ids[e]===a){i.id=e,i.identifier=this.ids[e],delete this.ids[e];break}return i};Manager.prototype.onmove=function(a){var i=this;return i.onAny("move",a),!1};Manager.prototype.onend=function(a){var i=this;return i.onAny("end",a),!1};Manager.prototype.oncancel=function(a){var i=this;return i.onAny("end",a),!1};Manager.prototype.onAny=function(a,i){var e=this,o,s="processOn"+a.charAt(0).toUpperCase()+a.slice(1);i=prepareEvent(i);var c=function(_,b,k){k.ids.indexOf(b)>=0&&(k[s](_),_._found_=!0)},d=function(_){o=e.getIdentifier(_),map(e.collections,c.bind(null,_,o)),_._found_||e.removeIdentifier(o)};return map(i,d),!1};Manager.prototype.destroy=function(){var a=this;a.unbindDocument(!0),a.ids={},a.index=0,a.collections.forEach(function(i){i.destroy()}),a.off()};Manager.prototype.onDestroyed=function(a,i){var e=this;if(e.collections.indexOf(i)<0)return!1;e.collections.splice(e.collections.indexOf(i),1)};const factory=new Manager;var nipplejs={create:function(a){return factory.create(a)},factory};class JoyStick{constructor(i){ct(this,"_zone");ct(this,"_joystick",null);ct(this,"_room");this._room=i}get zone(){return this._zone}init(i){var _e,et;this.destroy();const e={position:"absolute",width:"200px",height:"200px",left:"0px",bottom:"0px",zIndex:"999",userSelect:"none",webkitUserSelect:"none"},{interval:o=33,triggerDistance:s=25,size:c=110,zoneClassName:d="xverse-joystick-zone"}=i||{};typeof((_e=i==null?void 0:i.style)==null?void 0:_e.left)=="number"&&(i.style.left=i.style.left+"px"),typeof((et=i==null?void 0:i.style)==null?void 0:et.bottom)=="number"&&(i.style.bottom=i.style.bottom+"px");const _=Object.assign(e,i==null?void 0:i.style),b=(tt,rt)=>{this._room.actionsHandler.joystick({degree:Math.floor(tt),level:Math.floor(rt/5)})},k=this._zone=document.createElement("div");document.body.appendChild(k),k.className=d,Object.keys(_).forEach(tt=>{const rt=_[tt];rt!==void 0&&(k.style[tt]=rt)}),this._joystick=nipplejs.create({zone:k,mode:"static",position:{left:"50%",top:"50%"},color:"white",restOpacity:.3,size:c}),this.customizeStyle();let j,$;return this._joystick.on("move",(tt,rt)=>{j=rt}),this._joystick.on("start",()=>{$=window.setInterval(()=>{j&&j.distance>s&&b&&b(j.angle.degree,j.distance)},o)}),this._joystick.on("end",()=>{$&&window.clearInterval($),$=void 0}),this._joystick}destroy(){if(!!this._joystick){this._joystick.destroy();try{this._zone&&document.body.removeChild(this._zone)}catch{}}}customizeStyle(){var c,d;const i=this._zone;if(!i)return;const e=i.querySelector(".front"),o=i.querySelector(".back"),s=30;e.style.width=s+"px",e.style.height=s+"px",e.style.marginLeft=s/-2+"px",e.style.marginTop=s/-2+"px",o.style.boxSizing="border-box",o.style.backgroundColor="black",o.style.backgroundClip="padding-box",o.style.border="2px solid white",(c=this._joystick)==null||c.on("start",()=>{o.style.border="2px solid #FFEA95",o.style.boxShadow="inset 0px 0px 8px rgba(255, 255, 255, 0.25)",e.style.opacity="1"}),(d=this._joystick)==null||d.on("end",()=>{o.style.border="2px solid white",o.style.boxShadow="none"})}show(){if(!this._joystick||!this._zone)throw new Error("joystick is not created");this._zone.style.display="block"}hide(){this._zone&&(this._zone.style.display="none")}}const AREA_INFO={airshipBase:{breathPointId:"AirshipEntrance",points:[{position:{x:-836,y:-31655,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:-2e3,y:-32e3,z:0},rotation:{pitch:0,yaw:15,roll:0}},{position:{x:-2e3,y:-31e3,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:0,y:-32500,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:0,y:-31e3,z:0},rotation:{pitch:0,yaw:0,roll:0}}]},birthSquare:{breathPointId:"DiscoEntranceA",points:[{position:{x:-540,y:61450,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:-1500,y:61e3,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:-1500,y:62e3,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:500,y:61e3,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:500,y:62e3,z:0},rotation:{pitch:0,yaw:0,roll:0}}]},disco:{breathPointId:"DiscoEntranceA",points:[{position:{x:729,y:7729,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:0,y:7e3,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:-1999,y:8e3,z:0},rotation:{pitch:0,yaw:15,roll:0}},{position:{x:0,y:8500,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:3500,y:8e3,z:0},rotation:{pitch:0,yaw:-25,roll:0}}]},hotAirBalloonBase:{breathPointId:"HotAirBalloonEntrance",points:[{position:{x:-28e3,y:-32e3,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:-28380,y:-32820,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:-27e3,y:-32500,z:0},rotation:{pitch:0,yaw:-60,roll:0}},{position:{x:-27e3,y:-31500,z:0},rotation:{pitch:0,yaw:-50,roll:0}},{position:{x:-29e3,y:-32010,z:0},rotation:{pitch:0,yaw:0,roll:0}}]},reportHall:{breathPointId:"ReportHallEntrance1",points:[{position:{x:15e3,y:31e3,z:0},rotation:{pitch:0,yaw:-100,roll:0}},{position:{x:15500,y:32e3,z:0},rotation:{pitch:0,yaw:115,roll:0}},{position:{x:16e3,y:30500,z:0},rotation:{pitch:0,yaw:125,roll:0}},{position:{x:15e3,y:3e4,z:0},rotation:{pitch:0,yaw:125,roll:0}},{position:{x:14e3,y:30500,z:0},rotation:{pitch:0,yaw:125,roll:0}}]},sculptureGallery:{breathPointId:"photoboothB",points:[{position:{x:-19916,y:34044,z:0},rotation:{pitch:0,yaw:50,roll:0}},{position:{x:-21e3,y:34e3,z:0},rotation:{pitch:0,yaw:-150,roll:0}},{position:{x:-19e3,y:34500,z:0},rotation:{pitch:0,yaw:-135,roll:0}},{position:{x:-2e4,y:33e3,z:0},rotation:{pitch:0,yaw:-150,roll:0}},{position:{x:-20603,y:34962,z:0},rotation:{pitch:0,yaw:-150,roll:0}}]},watchTower:{breathPointId:"WatchTowerEntrance",points:[{position:{x:37e3,y:-29e3,z:0},rotation:{pitch:0,yaw:50,roll:0}},{position:{x:36e3,y:-3e4,z:0},rotation:{pitch:0,yaw:115,roll:0}},{position:{x:36e3,y:-29500,z:0},rotation:{pitch:0,yaw:50,roll:0}},{position:{x:38e3,y:-28500,z:0},rotation:{pitch:0,yaw:0,roll:0}},{position:{x:38e3,y:-29500,z:0},rotation:{pitch:0,yaw:75,roll:0}}]},gameCenter:{breathPointId:"GameCenterEntrance",points:[{position:{x:41500,y:1e4,z:0},rotation:{pitch:0,yaw:150,roll:0}},{position:{x:40500,y:9450,z:0},rotation:{pitch:0,yaw:75,roll:0}},{position:{x:40500,y:10450,z:0},rotation:{pitch:0,yaw:60,roll:0}},{position:{x:41500,y:9e3,z:0},rotation:{pitch:0,yaw:180,roll:0}},{position:{x:42450,y:9450,z:0},rotation:{pitch:0,yaw:70,roll:0}}]},manmadeGarden:{breathPointId:"photoboothC",points:[{position:{x:-37e3,y:-9500,z:0},rotation:{pitch:0,yaw:-135,roll:0}},{position:{x:-36300,y:-1e4,z:0},rotation:{pitch:0,yaw:-40,roll:0}},{position:{x:-37e3,y:-8500,z:0},rotation:{pitch:0,yaw:-80,roll:0}},{position:{x:-37940,y:-8540,z:0},rotation:{pitch:0,yaw:95,roll:0}},{position:{x:-38530,y:-6540,z:0},rotation:{pitch:0,yaw:-15,roll:0}}]},musicMuseum:{points:[{position:{x:-32989,y:474.69,z:0},rotation:{pitch:0,yaw:120,roll:0}},{position:{x:-34500,y:1110,z:0},rotation:{pitch:0,yaw:-110,roll:0}},{position:{x:-34e3,y:460,z:0},rotation:{pitch:0,yaw:-110,roll:0}},{position:{x:-32e3,y:120,z:0},rotation:{pitch:0,yaw:-120,roll:0}},{position:{x:-32e3,y:760,z:0},rotation:{pitch:0,yaw:-105,roll:0}}]}};var Skins=(a=>(a.Island="10050",a.Disco="10048",a.GameCenter="10055",a.LiveHall="10056",a.ReportHall="10078",a.MusicianHall="10105",a.MusicianHallDusk="10103",a.MusicianHallNight="10084",a.MusicianHallLuHan="10107",a))(Skins||{});const DEFAULT_SKINS={ISLAND:{skinId:"10050",defaultStreamPath:"thirdwalk",defaultPanoramaPath:"firstwalk"},DISCO:{skinId:"10048",defaultStreamPath:"thirdwalk",defaultPanoramaPath:"toushidian"},GAME_CENTER:{skinId:"10055",defaultStreamPath:"thirdwalk",defaultPanoramaPath:"firstwalk"},LIVE_HALL:{skinId:"10056",defaultStreamPath:"thirdwalk",defaultPanoramaPath:"firstwalk"},REPORT_HALL:{skinId:"10078",defaultStreamPath:"thirdwalk",defaultPanoramaPath:"firstwalk"},MUSICIAN_HALL:{skinId:"10105",defaultStreamPath:"thirdwalk",defaultPanoramaPath:"firstwalk"}},DEFAULT_AVATAR_SCALE=.8,DEfAULT_ANIMATIONS=["Dance01","Dance05","RumbaDancing","LockingHipHopDance","Jump_all","Qiangtui","Hallo","Yaotou","BlowAKiss","Cheering","HappyIdle","Singing","Talking","Thankful","Waving","StartWalking","Running","Walking","StopWalking","TurnBack","RightTurn","LeftTurn","Idle","GiftClap","PHOTO_1","PHOTO_2","PHOTO_3","PHOTO_4","PHOTO_5","PHOTO_6","PHOTO_7","PHOTO_8","PHOTO_9","PHOTO_10","PHOTO_11","PHOTO_12"],DISCO_EXTRA_ANIMATIONS=["Dance01b","Dance01c","Dance02","Dance03","Dance04","WaveHipHopDance"],BOSS_ANIMATIONS=["Idle","Talking","Clap","Hallo","Hand01","Hand02","Clap02"];DEFAULT_SKINS.REPORT_HALL.skinId,DEFAULT_SKINS.GAME_CENTER.skinId,DEFAULT_SKINS.ISLAND.skinId,DEFAULT_SKINS.LIVE_HALL.skinId,DEFAULT_SKINS.DISCO.skinId,[...DEfAULT_ANIMATIONS,...DISCO_EXTRA_ANIMATIONS],[...DEfAULT_ANIMATIONS,...DISCO_EXTRA_ANIMATIONS];const SKY_TV_ID="skyTV",LOCATION_STORAGE_KEY="xverse_last_location",log$k=new Logger("avatar"),GIFT_CONFIGS={flower:{button:"flower2",effect:"Rose"},heart:{button:"heart2",effect:"Heart"},beer:{button:"beers2",effect:"Glass"}},effectNameMap={happy:"Sun",sad:"Cloud",drunk:"Heart02",angry:"Angry",heartbreak:"HeartBreak01",listening:"Star01"};class Avatar extends XverseAvatar{constructor({userId:e,isHost:o,room:s,avatarId:c,nickname:d,isSelf:_,group:b=AvatarGroup.Npc,avatarComponents:k=[]}){super({userId:e,isHost:o,room:s,avatarId:c,nickname:d,isSelf:_,group:b,avatarComponents:k});ct(this,"_isChangingComponentsMode",!1);ct(this,"_room");ct(this,"mood");ct(this,"moodId","");ct(this,"moodList",[]);this._room=s,_&&this._faceToBuilding(),this.init()}get isBoss(){return!!this.bossName}get bossName(){var e;return(e=this.extraInfo)==null?void 0:e.bossName}get currentArea(){return this.comparedDistance()}async init(){const o=(await this._room.modelManager.findEffectList(this._room.skinId)).filter(s=>s.className==="\u5FC3\u60C5\u6302\u4EF6");this.moodList=o}transferTo(e){if(this.isBoss)return Promise.resolve();const o={position:e,angle:{pitch:0,roll:0,yaw:0}},s=o;return this.transfer({camera:s,player:o,areaName:"guangchang",attitude:MotionType.Walk,pathName:"thirdwalk"})}async moveToArea(e,o=!1){var d;let s;const c={inDisco:"disco",inGameCenter:"gameCenter",inReportHall:"reportHall"};try{const _=c[e]||e,b=AREA_INFO[_].points;if(s=(d=b[Math.floor(b.length*Math.random())])==null?void 0:d.position,!s)throw new ParamError("no correct position for running to "+e)}catch(_){return log$k.error(_),Promise.reject(_)}return o?this.transferTo(s):this.moveTo({point:s,extra:JSON.stringify({position:s,moveToArea:!0})})}async moveTo(e){return this.isBoss?Promise.resolve():super.moveTo(e)}showButtons(){var s;if(this.group===AvatarGroup.Npc)return;if(!this.xAvatar)return Promise.reject("showButtons failed, without instance: xAvatar");const e=new Map,o=[];return Object.keys(GIFT_CONFIGS).forEach(c=>{var _,b;const d=(b=(_=this._room.skinList.find(k=>k.id===Skins.Island))==null?void 0:_.models.find(k=>k.typeName===AssetTypeName.Textures&&k.className===AssetClassName.GiftBubble&&k.name===GIFT_CONFIGS[c].button))==null?void 0:b.modelUrl;if(!d){o.push(`bubble texture ${c} is undefined`);return}e.set(c,d)}),o.length>0?Promise.reject(o[0]):(s=this.xAvatar)==null?void 0:s.generateButtons(e,this.xAvatar.scale)}hideButtons(){var e;return this.xAvatar?(e=this.xAvatar)==null?void 0:e.setGiftButtonsVisible(!1):(log$k.warn("hideButtons failed, without instance: xAvatar"),Promise.reject())}startChangeComponentsMode(e={r:.7,g:.7,b:.7,a:1},o={x:.5,y:.8,z:3}){if(!this.xAvatar.isRender)return log$k.error("Avatar not rendered yet"),!1;if(this._room.camera.person===Person.First)return log$k.error("`changeComponentsMode` is not allowed in third person"),!1;log$k.info("startChangeComponentsMode",e,o),this._room.sceneManager.setBackgroundColor(e);const s=this._room.avatarManager.dressUpToggle(!0,o);return s&&(this._isChangingComponentsMode=!0),s}exitChangeComponentsMode(){const e=this._room.avatarManager.dressUpToggle(!1);return this._isChangingComponentsMode=!1,e}comparedDistance(e){if(this._room.reportHall.actived)return"inReportHall";if(this._room.gameCenter.actived)return"inGameCenter";if(this._room.disco.actived)return"inDisco";const o=this.position;if(!o)return"birthSquare";const{x:s,y:c,z:d}=o;let _=e||Number.MAX_VALUE,b="";return Object.entries(AREA_INFO).forEach(([k,j])=>{const $=j.points[0].position;if(!$)return;const _e=Math.sqrt(Math.abs($.x-s)**2+Math.abs($.y-c)**2+Math.abs($.z-d)**2);_e<_&&(_=_e,b=k)}),b||"tmeLand"}_faceToBuilding(){this.on("stopMoving",async({extra:e})=>{if(!e)return;let o;try{o=JSON.parse(e).moveToArea}catch(c){log$k.error(c);return}if(!o)return;const s=await this._room.breathPoint.getBreathPointsConfig();Object.entries(AREA_INFO).find(c=>{var d,_,b;if(c[0]===this.currentArea&&((d=c[1])==null?void 0:d.breathPointId)){const k=(_=s.find(nt=>nt.id===c[1].breathPointId))==null?void 0:_.position;if(!(k&&this.position)){log$k.error(`no turnTo target point with id: ${(b=c[1])==null?void 0:b.breathPointId}`);return}const{x:j,y:$,z:_e}=this.position,{x:et,y:tt,z:rt}=k;Math.sqrt((j-et)**2+($-tt)**2+(_e-rt)**2)<15e3&&this.turnTo({point:k})}})})}async sendGift(e,o){const s=Date.now(),c=e.userId,d=this.userId;try{const _={info:{userId:this.userId,giftReceiver:e.userId,giftId:o,num:1,messageFromHost:this.isHost,extra:encodeURIComponent("")},broadcastType:"SendGift"};return this._room.avatarManager.giftBroadCast.broadcast({data:_}),log$k.infoAndReportMeasurement({tag:o,startTime:s,metric:"sendGift",extra:{giftGiver:d,giftReceiver:c}}),this._room.avatarManager.playGiftAnimation(d,c,o)}catch(_){return log$k.infoAndReportMeasurement({tag:o,startTime:s,metric:"sendGift",error:_,extra:{giftGiver:d,giftReceiver:c}}),Promise.reject(_)}}async setMood(e){await this._setMood(e),this.broadCastMood(e);const o={metric:"setMood",tag:e,startTime:Date.now()};log$k.infoAndReportMeasurement(o)}broadCastMood(e){const o={info:{userId:this.userId,mood:e},broadcastType:"SetMood"};this._room.avatarManager.moodBroadCast.broadcast({data:o})}async _setMood(e){if(this.mood===e)return Promise.reject("already in this mood");if(!e){this._removeMood();return}const c=this.moodList.map(k=>k.name).includes(e)?e:effectNameMap[e];if(!c)return Promise.reject("invalid mood,"+e);if(!this.xAvatar)return Promise.reject("avatar incomplete");this._removeMood();const d=uuid$1(),_=await this._room.effectManager.loadMoodEffect(c,d),b=_.effect.root;this.xAvatar.attachToAvatar(b,!1,{x:0,y:0,z:30},!1,"",!0),_.play(!0),this.attachedEffects.add(d),this.mood=e,this.moodId=d}removeMood(){this._removeMood(),this.broadCastMood(void 0)}_removeMood(){this.moodId&&(this.removeAttachedEffect(this.moodId),this.mood=void 0,this.moodId="")}}class DressUpPanel{constructor(i){ct(this,"_room");ct(this,"_tempCameraPose");ct(this,"_tempAvatarPose");ct(this,"active",!1);ct(this,"_offset",1e4);ct(this,"events",{});this._room=i}bindUserRotate(){let i=0,e=0,o=0;const s=this._room.canvas;this.events.touchStart=c=>{const{pageX:d,pageY:_}=c.touches[0];i=d,e=_,o=Date.now(),this._room._userAvatar.xAvatar.rotate(!0,1,1)},this.events.touchMove=c=>{var et;const{pageX:d,pageY:_}=c.touches[0],b=Math.sqrt(Math.pow(d-i,2)+Math.pow(_-e,2)),k=Date.now(),j=o-k,$=i-d;if(i=d,e=_,o=k,j==0)return;const _e=b/j*3;this._room._userAvatar.xAvatar.rotate(!0,Math.abs(_e),$),(c.changedTouches[0].pageY>document.documentElement.clientHeight||c.changedTouches[0].pageY<0)&&((et=this.events)==null||et.touchEnd())},this.events.touchEnd=()=>this._room._userAvatar.xAvatar.rotate(!1),s.addEventListener("touchstart",this.events.touchStart),s.addEventListener("touchmove",this.events.touchMove),s.addEventListener("touchend",this.events.touchEnd),s.addEventListener("touchcancel",this.events.touchEnd)}removeUserRotateBind(){const i=this._room.canvas;i.removeEventListener("touchstart",this.events.touchStart),i.removeEventListener("touchmove",this.events.touchMove),i.removeEventListener("touchend",this.events.touchEnd),i.removeEventListener("touchcancel",this.events.touchEnd)}dressUpToggle(i,e){var o,s;return this.active=i,(s=(o=this._room.userAvatar)==null?void 0:o.xAvatar)!=null&&s.isRender?i?(this._room.networkController.rtcp.actived=!1,this._room.signal.signalHandleActived=!1,this._room.userAvatar.setRayCast(!1),this._room.userAvatar._playAnimation("Idle",!0),this._room.sceneManager.staticmeshComponent.stopMeshUpdate(),this._room.actionsHandler.addBlockedActions([Actions.GetNewUserState]),this.bindUserRotate(),this.focusCameraOnUser(i,e)):(this._room.networkController.rtcp.actived=!0,this._room.signal.signalHandleActived=!0,this._room.userAvatar.setRayCast(!0),this._room.actionsHandler.removeBlockedActions(Actions.GetNewUserState),this._room.sceneManager.staticmeshComponent.startMeshUpdate(),this.removeUserRotateBind(),this.focusCameraOnUser(i,e)):!1}focusCameraOnUser(i,e){var s;const o=this._room.userAvatar;if(o&&o.isRender)if(i){const c=this._room.sceneManager.cameraComponent.MainCamera;this._tempCameraPose=this._room.sceneManager.cameraComponent.getCameraPose(),this._tempAvatarPose=o.pose,c.rotation.x=0,c.rotation.y=0,c.rotation.z=0,c.position.x=this._offset,c.position.y=this._offset,c.position.z=this._offset;let d=0,_=0;d=this._room.sceneManager.canvas.offsetWidth,_=this._room.sceneManager.canvas.offsetHeight;let b=0,k=0,j=0;e=e||{x:.5,y:.5,z:5};const $=(s=this._room.avatarManager)==null?void 0:s.xAvatarManager.scene.createPickingRay(e.x*d,e.y*_,null,c);$!=null&&(b=$.origin.x+$.direction.x*e.z,k=$.origin.y+$.direction.y*e.z,j=$.origin.z+$.direction.z*e.z);const _e=xversePosition2Ue4({x:b,y:k,z:j});o.setPosition(_e),o.setRotation({yaw:90,pitch:0,roll:0})}else this._tempCameraPose&&this._room.sceneManager.cameraComponent.setCameraPose(this._tempCameraPose),this._tempAvatarPose&&(o.setPosition(this._tempAvatarPose.position),o.setRotation(this._tempAvatarPose.angle));else return!1;return!0}}const log$j=new Logger("avatar-manager");class AvatarManager extends XverseAvatarManager{constructor(e){var o;super(e);ct(this,"isInChangeComponentsMode",!1);ct(this,"giftBroadCast");ct(this,"dressUpPanel");ct(this,"moodBroadCast");this.dressUpPanel=new DressUpPanel(e),(o=this._room.avatarManager)!=null&&o.xAvatarManager&&(this._room.avatarManager.xAvatarManager.enableAllNickname(!0),this._room.avatarManager.xAvatarManager.maxBillBoardDist=3e3),this.giftBroadCast=this.setupGiftBroadCast(),this.moodBroadCast=this.setupMoodBroadCast()}setupGiftBroadCast(){return new Broadcast(this._room,async e=>{const{broadcastType:o,info:s}=e;if(o!=="SendGift")return;const{userId:c,giftReceiver:d,giftId:_}=s;this.playGiftAnimation(c,d,_)})}setupMoodBroadCast(){return new Broadcast(this._room,async e=>{const{broadcastType:o,info:s}=e;if(o!=="SetMood")return;const{userId:c,mood:d}=s,_=this.avatars.get(c);!_||_._setMood(d)})}dressUpToggle(e,o){return this.dressUpPanel.dressUpToggle(e,o)}playGiftAnimation(e,o,s){if(![o,e].includes(this._room.userId)||this.dressUpPanel.active)return Promise.reject();const c=GIFT_CONFIGS[s];return!c||!c.effect?(log$j.error("invalid giftId "+s),Promise.reject()):this._room.effectManager.loadEffect(c.effect).then(d=>{d.setScaling(.8);const _=this._room.avatars.find(k=>k.userId===e),b=this._room.avatars.find(k=>k.userId===o);_&&b&&(d.effect.goToFrame(0),_._playAnimation("BlowAKiss",!1).then(()=>{_.xAvatar.shootTo(b.xAvatar,d.effect,1,20).then(()=>{b._playAnimation("GiftClap",!1),d.hide(),setTimeout(()=>{d.play(!1)},500)})})),o===this._room.userId&&this._room._userAvatar.emit("giftReceived",{giftGiver:e,giftId:s})})}calculatePriority(e,o){const s=e===this._room.userId;return o.bossName&&!s?EAvatarRelationRank.Npc:super.calculatePriority(e,o)}addNpc(e){const{userId:o,avatarPosition:s,avatarId:c,avatarRotation:d,nickname:_,avatarComponents:b=[],avatarScale:k=DEFAULT_AVATAR_SCALE}=e,j=this.avatars.get(o);return j?(log$j.warn(`npc: ${o} already exists`),Promise.resolve(j)):super.addAvatar({userId:o,isHost:!1,avatarPosition:s,avatarId:c,avatarRotation:d,nickname:_,avatarComponents:b,priority:EAvatarRelationRank.Npc,group:AvatarGroup.Npc,avatarScale:k})}removeNpc(e){return super.removeAvatar(e,!0)}}XverseAvatarManager.subAvatar=Avatar;var ClickTargetName=(a=>(a.PhotoBooth="PhotoBooth",a.Avatar="Avatar",a.ConfessionsWall="ConfessionsWall",a.GiftPanel="GiftPanel",a.LiveEntrance="LiveEntrance",a.AirshipEntrance="AirshipEntrance",a.HotAirBalloonEntrance="HotAirBalloonEntrance",a.WatchTowerEntrance="WatchTowerEntrance",a.DiscoEntrance="DiscoEntrance",a.ReportHallEntrance="ReportHallEntrance",a.ReportHallExit="ReportHallExit",a.DiscoExit="DiscoExit",a.LiveInfoRefresh="LiveInfoRefresh",a.WatchTowerExit="WatchTowerExit",a.LeftBoxEntrance="LeftBoxEntrance",a.RightBoxEntrance="RightBoxEntrance",a.TelescopeEntrace="TelescopeEntrace",a.GameCenterEntrance="GameCenterEntrance",a.PlayGame="PlayGame",a.GameCenterExit="GameCenterExit",a.PlayAlbum="PlayAlbum",a.AlbumPlaying="AlbumPlaying",a.AddLeftComments="AddLeftComments",a.AddRightComments="AddRightComments",a.NextAlbum="NextAlbum",a.LastAlbum="LastAlbum",a.LitPixel="LitPixel",a.CheckPixelStatus="CheckPixelStatus",a.NoticePixelPanel="NoticePixelPanel",a.ClosePixelPanel="ClosePixelPanel",a))(ClickTargetName||{});const log$i=new Logger("breathPoint");class BreathPoint{constructor(i){ct(this,"visibilities",{});ct(this,"idVisibilities",{});ct(this,"batchUpdate",debounceDelay(()=>this.showBreathPointInSkin(),33));this.room=i,this.updateVisibilities(),this.room.on("userAvatarLoaded",()=>{this.showBreathPointInSkin()}),this.room.on("skinChanged",({skin:e})=>{setTimeout(()=>{const o=e.id;this.showBreathPointInSkin(o)},0)})}async getBreathPointsConfig(){return[{position:{x:-38726,y:-12614,z:980},id:"photoboothC",name:ClickTargetName.PhotoBooth,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:60,width:11.2,height:8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/PhotoBooth.png",textureName:"PhotoBooth"},{position:{x:-23974,y:36203,z:730},id:"photoboothB",name:ClickTargetName.PhotoBooth,skinId:DEFAULT_SKINS.ISLAND.skinId,width:11.2,height:8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/PhotoBooth.png",textureName:"PhotoBooth"},{position:{x:3008,y:-308,z:285},id:"photoboothDisco",name:ClickTargetName.PhotoBooth,skinId:DEFAULT_SKINS.DISCO.skinId,maxVisibleRegion:21,width:5.6,height:4,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/PhotoBooth.png",textureName:"PhotoBooth"},{position:{x:-2788,y:-773,z:135},id:"ConfessionsWall1",name:ClickTargetName.ConfessionsWall,skinId:DEFAULT_SKINS.DISCO.skinId,maxVisibleRegion:100,width:2.8,height:2,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/ConfessionsWall.png",textureName:"ConfessionsWall"},{position:{x:-360,y:-35225,z:480},id:"AirshipEntrance",name:ClickTargetName.AirshipEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:80,width:11.2,height:8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/AirshipEntrance.png",textureName:"AirshipEntrance"},{position:{x:-27966,y:-33960,z:400},id:"HotAirBalloonEntrance",name:ClickTargetName.HotAirBalloonEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:110,height:6,width:8.4,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/HotAirBalloonEntrance.png",textureName:"HotAirBalloonEntrance"},{position:{x:38727,y:-29688,z:242},id:"WatchTowerEntrance",name:ClickTargetName.WatchTowerEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,height:6,width:8.4,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/WatchTowerEntrance.png",textureName:"WatchTowerEntrance"},{position:{x:39588,y:-30480,z:10730},id:"WatchTowerExit",name:ClickTargetName.WatchTowerExit,skinId:DEFAULT_SKINS.ISLAND.skinId,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/Exit.png",height:3,width:4.2,textureName:"Exit"},{position:{x:478,y:2005,z:1263},id:"DiscoEntranceA",name:ClickTargetName.DiscoEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:450,height:12,width:16.8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/DiscoEntrance.png",textureName:"DiscoEntrance"},{position:{x:5390,y:-2978,z:1088},id:"DiscoEntranceB",name:ClickTargetName.DiscoEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:250,height:7,width:9.8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/DiscoEntrance.png",textureName:"DiscoEntrance"},{position:{x:-5110,y:-1710,z:1263},id:"DiscoEntranceC",name:ClickTargetName.DiscoEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:250,height:10,width:14,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/DiscoEntrance.png",textureName:"DiscoEntrance"},{position:{x:-20,y:-4694,z:282},id:"DiscoExit",name:ClickTargetName.DiscoExit,skinId:DEFAULT_SKINS.DISCO.skinId,maxVisibleRegion:40,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/Exit.png",width:5.6,height:4,textureName:"Exit"},{position:{x:16303,y:32996,z:450},id:"ReportHallEntrance1",name:ClickTargetName.ReportHallEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:60,width:11.2,height:8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/LiveHallEntrance.png",textureName:"FinaicalHallEntrance"},{position:{x:960,y:580,z:150},id:"ReportHallExit1",name:ClickTargetName.ReportHallExit,skinId:DEFAULT_SKINS.REPORT_HALL.skinId,height:3,width:4.2,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/Exit.png",textureName:"Exit"},{position:{x:-940,y:555,z:150},id:"ReportHallExit2",name:ClickTargetName.ReportHallExit,skinId:DEFAULT_SKINS.REPORT_HALL.skinId,height:3,width:4.2,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/Exit.png",textureName:"Exit"},{position:{x:63,y:-513,z:183},id:"LiveInfoRefresh",name:ClickTargetName.LiveInfoRefresh,skinId:DEFAULT_SKINS.LIVE_HALL.skinId,width:2.8,height:2,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/LiveInfoRefresh.png",textureName:"LiveInfoRefresh"},{position:{x:38628,y:-29795,z:10730},id:"TelescopeA",name:ClickTargetName.TelescopeEntrace,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/View.png",height:1,width:1.4,textureName:"View"},{position:{x:39318,y:-29339,z:10730},id:"TelescopeB",name:ClickTargetName.TelescopeEntrace,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/View.png",height:1,width:1.4,textureName:"View"},{position:{x:38443,y:-30640,z:10730},id:"TelescopeC",name:ClickTargetName.TelescopeEntrace,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:8,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/View.png",height:1,width:1.4,textureName:"View"},{position:{x:43179,y:9938,z:300},id:"GameCenterEntrance",name:ClickTargetName.GameCenterEntrance,skinId:DEFAULT_SKINS.ISLAND.skinId,maxVisibleRegion:150,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/GameHall.png",width:4.2,height:3,textureName:"GameHall"},{position:{x:48,y:-1160,z:150},id:"PlayGame",name:ClickTargetName.PlayGame,skinId:DEFAULT_SKINS.GAME_CENTER.skinId,maxVisibleRegion:150,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/Play.png",width:2.8,height:2,textureName:"PlayGame"},{position:{x:-142,y:1609,z:200},id:"GameCenterExit",name:ClickTargetName.GameCenterExit,skinId:DEFAULT_SKINS.GAME_CENTER.skinId,maxVisibleRegion:150,imageUrl:"https://static.xverse.cn/tmeland/images/breathpoint-static/Exit.png",width:2.8,height:2,textureName:"Exit"}]}async updateVisibilities(){(await this.getBreathPointsConfig()).forEach(e=>{this.visibilities[e.name]=!0}),this.visibilities[ClickTargetName.LiveEntrance]=!0}setVisibility(i,e=!1){Array.isArray(i)||(i=[i]),i.forEach(o=>this.visibilities[o]=e),this.batchUpdate()}setVisibilityById(i,e=!1){Array.isArray(i)||(i=[i]),i.forEach(o=>this.idVisibilities[o]=e),this.batchUpdate()}async showBreathPointInSkin(i){if(this.room.disco.actived&&this.room.isPano||this.room.watchTower.telescope.actived)return;i||(i=this.room.skin.id);const e=await this.getBreathPointsConfig(),o=[],s=[];e.forEach(c=>{const d=String(c.skinId)===i,_=this.visibilities[c.name]!==!1&&this.idVisibilities[c.id]!==!1;d&&_?o.push(c):s.push(c)}),o.forEach(c=>{const d=this.room.breathPointManager.breathPoints.get(c.id);if(d){d.toggleVisibility(!0);return}this.renderBreathPoint(c)}),this.deleteBreathPoints(s.map(c=>c.id))}async renderBreathPoint(i){if(this.room.breathPointManager.breathPoints.get(i.id))return;const o=this.room.skin.models.find(c=>c.typeName===AssetTypeName.Textures&&i.textureName&&i.textureName===c.name);if(i.textureName&&!o){log$i.error(`no such texture with name: ${i.name}`);return}if(i.imageUrl=i.imageUrl||(o==null?void 0:o.modelUrl),!i.imageUrl)return;let s;try{s=await urlTransformer(i.imageUrl)}catch(c){s=i.imageUrl,log$i.error("urlTransformer error",c)}return this.room.breathPointManager.addBreathPoint({id:i.id,position:i.position,spriteSheet:s,rotation:i.rotation||{pitch:0,yaw:270,roll:0},billboardMode:i.billboardMode!==void 0?i.billboardMode:!0,type:i.name,spriteWidthNumber:i.spriteWidthNum||1,spriteHeightNumber:i.spriteHeightNum||1,maxVisibleRegion:i.maxVisibleRegion||80,width:i.width||2.8*4,height:i.height||2*4}).then(()=>{var c;i.defaultVisibility===!1&&((c=this.room.breathPointManager.breathPoints.get(i.id))==null||c.toggleVisibility(!1))})}async hideAll(){(await this.getBreathPointsConfig()).forEach(e=>{this.room.breathPointManager.clearBreathPoints(e.name)})}deleteBreathPoints(i){i.map(e=>this.room.breathPointManager.clearBreathPoints(e))}async isMatched(i){const e=await this.getBreathPointsConfig(),o=await this.room.musicianHall.getBreathPoints();e.push(...o,...this.room.musicianHall.beAddedBreathPoint);let s;if(this.room.liveHall.liveIds.includes(i.id))return this.room.emit("click",{target:{name:ClickTargetName.LiveEntrance,id:i.id}}),log$i.infoAndReportMeasurement({startTime:Date.now(),value:0,metric:"liveEntranceClick",extra:{id:i.id}}),!0;if(i.name.startsWith(ALBUM_ID_PREFIX)){let c=i.id.split(ALBUM_ID_PREFIX)[1];const d=i.name.endsWith(PLAYING_ALBUM_ID_SUFFIX);d&&(c=c.split(PLAYING_ALBUM_ID_SUFFIX)[0]);const _=this.room.musicianHall.currentAlbums[Number(c)];return this.room.emit("click",{target:{name:d?ClickTargetName.AlbumPlaying:ClickTargetName.PlayAlbum,id:String(_.id)}}),!0}else if(s=e.find(c=>c.id===i.id))return(s.name===ClickTargetName.LastAlbum||s.name===ClickTargetName.NextAlbum)&&this.room.musicianHall.handleClickPagination(s.name),this.room.emit("click",{target:{name:s.name,id:s.id}}),!0;return!1}}const log$h=new Logger("Rain");class Rain{constructor(i){ct(this,"spriteRain");ct(this,"actived",!1);this.room=i}play(i){if(!this.room._userAvatar||!this.room._userAvatar.position)return Promise.reject("user avatar is not inited yet");const e=this.room.skinList.find(b=>b.id===DEFAULT_SKINS.DISCO.skinId),o=e==null?void 0:e.models.find(b=>b.typeName===AssetTypeName.Effects&&b.name==="MoneyRain");if(!o)return log$h.error("MoneyRain effect not found"),Promise.reject("MoneyRain effect not found");const{url:s,type:c}=this.room.effectManager.effectJsonUrlParse(o)||{};if(!s||!c)return Promise.reject(`effect\uFF1A${o.name} parse url error`);const{duration:d=5e3,onEnd:_=()=>{}}=i||{};return this.spriteRain=new SpriteRain(this.room.scene,s,{x:this.room._userAvatar.position.x,y:this.room._userAvatar.position.y,z:1e3},{x:this.room._userAvatar.position.x,y:this.room._userAvatar.position.y,z:150},40,1,100,15,urlTransformer),this.spriteRain.init().then(()=>{this.actived=!0,this.spriteRain.play(!0).catch(b=>{throw b}),setTimeout(()=>{_(this.spriteRain.pickNumber),this.stop()},d)}).catch(()=>{this.actived=!1})}stop(){this.actived=!1,this.spriteRain.stop()}}class Effect extends XverseEffect{constructor({id:i,jsonPath:e,type:o,room:s}){super({id:i,jsonPath:e,type:o,room:s})}}const log$g=new Logger("effect-manager");class EffectManager extends XverseEffectManager{constructor(e){super(e);ct(this,"rain");this.rain=new Rain(e)}async loadEffect(e){const o=this.effects.get(e);if(o)return o;try{const s=this.room.skin.models.find(_=>_.typeName===AssetTypeName.Effects&&_.name===e);if(!s)throw`effect\uFF1A${e} was not found`;const{url:c,type:d}=this.effectJsonUrlParse(s)||{};if(!c||!d)throw`effect\uFF1A${e} parse url error`;return await this.room.effectManager.addEffect({jsonPath:c,id:s.name,type:d})}catch(s){return log$g.error("loadEffect failed,",s),Promise.reject(s)}}async loadMoodEffect(e,o,s="EFFECTS"){try{const c=this.room.skin.models.find(k=>k.typeName===s&&k.name===e);if(!c)throw`effect\uFF1A${e} was not found`;const{url:d,type:_}=this.effectJsonUrlParse(c)||{};if(!d||!_)throw`effect\uFF1A${e} parse url error`;return await this.room.effectManager.addEffect({jsonPath:d,id:o,type:_})}catch(c){return log$g.error("loadEffect failed,",c),Promise.reject(c)}}effectJsonUrlParse(e){var c;const o=(c=e.modelUrl.split("/")[e.modelUrl.split("/").length-1])==null?void 0:c.slice(0,-4);if(!o)return;const s=e.name.indexOf("Group_")>-1;return{url:`${e.modelUrl.slice(0,-4)}/${s?"Sequence":"SubSequence"}_${o}.json`,type:s?IEffectType.Sequence:IEffectType.SubSequence}}}XverseEffectManager.subEffect=Effect;const VERSION="1.2.12",log$f=new Logger("data-report"),TMELAND_ONLY_METRICS=["addComments","playAlbum","setMood","albumPaging"];Reporter.appendExtraMetrics(TMELAND_ONLY_METRICS);class DataReport{constructor(i){this.room=i,this.init()}init(){this.room.on("click",i=>{var o,s,c;let e;switch((o=i.target)==null?void 0:o.name){case ClickTargetName.AddLeftComments:case ClickTargetName.AddRightComments:e={metric:"addComments",startTime:Date.now(),tag:(s=i.target)==null?void 0:s.name};break;case ClickTargetName.LastAlbum:case ClickTargetName.NextAlbum:e={metric:"albumPaging",startTime:Date.now(),tag:(c=i.target)==null?void 0:c.name};break;case ClickTargetName.PlayAlbum:e={metric:"playAlbum",tag:i.target.id,startTime:Date.now()};break}e&&log$f.infoAndReportMeasurement(e)})}}class Switch{constructor(i){ct(this,"_othersVisible",!1);this.room=i}get nicknameVisible(){return!!this.room.avatarManager.xAvatarManager.enableNickname}set nicknameVisible(i){this.room.avatarManager.xAvatarManager.enableAllNickname(i)}get bubbleVisible(){return this.room.avatarManager.xAvatarManager.enableBubble}set bubbleVisible(i){this.room.avatarManager.xAvatarManager.enableAllBubbles(i)}get othersVisible(){return this._othersVisible}set othersVisible(i){i?(this.room.avatarManager.xAvatarManager.launchProcessLoadingLoop(),this.room.avatars.forEach(e=>{e.show()})):(this.room.avatarManager.xAvatarManager.stopProcessLoadingLoop(),this.room.avatars.forEach(e=>{e.isBoss||e.isSelf||e.hide()})),this._othersVisible=i}}const ASSISTANT_URL="v1/dialogue/utter",NPC_URL="v1/dialogue/npcs",PoiMap={tmeLand:"tmeland",disco:"hailuoditing_outside",inDisco:"hailuoditing",gameCenter:"youxikongjian",inGameCenter:"youxikongjian",watchTower:"haibinguanguangta",hotAirBalloonBase:"reqiqiuguangchang",airshipBase:"huanyoufeiting",musicMuseum:"yinyuebowuguan",sculptureGallery:"diaoxiangguangchang",birthSquare:"yinyueguangchang",manmadeGarden:"jingguangongyuan",reportHall:"tmeland",inReportHall:"tmeland"};class Assistant{constructor(i){ct(this,"assistantUrl",ENV_URL[Xverse.env].concat(ASSISTANT_URL));ct(this,"inited",!1);ct(this,"seqId",0);this.room=i}get currentArea(){return this.room.userAvatar.comparedDistance(12e3)}init(){return this.request("",this.seqId++,"self_intro")}request(i,e,o){const s=this.assistantUrl,c={header:{app:"tmeland",userId:this.room.userId,npcId:0,seqId:e,timestamp:Math.round(new Date().getTime())},aux_info:{poi:PoiMap[this.currentArea],intent:o},sentence:i};return o?delete c.sentence:(c.sentence=i,delete c.aux_info.intent),axios({method:"POST",url:s,data:c}).then(d=>{this.inited=!0;const{data:_}=d;if(_&&_.retCode===0)return{sentence:_.sentence,nextQuestions:_.nextQuestions};throw new Error("assistant input failed")})}input(i){return this.inited?i?this.request(i,this.seqId++):Promise.reject("sentence is required"):Promise.reject("Invoke init() before invoke input")}getGuideSentence({npcId:i,scenicName:e}){return axios({method:"POST",url:this.assistantUrl,data:{header:{app:"tmeland",user_id:this.room.userId,npcId:i,timestamp:Math.round(new Date().getTime())},aux_info:{poi:e,intent:"scene_intro"}}}).then(o=>{const{data:s}=o;if(s&&s.retCode===0)return{sentence:s.sentence,header:s.header};throw new Error("getGuideSentence failed")})}getGuideList(){return axios({method:"get",url:ENV_URL[Xverse.env].concat(NPC_URL)}).then(i=>{const{data:e}=i;if(e&&e.retCode===0)return{npcProfiles:e.npcProfiles};throw new Error("getGuideList failed")})}}class Zone{constructor(i){ct(this,"lastUserAvatarPose");ct(this,"lastCameraPose");ct(this,"actived",!1);this.room=i}saveLastPoses(){this.lastUserAvatarPose=this.room.currentClickingState.player,this.lastCameraPose=this.room.currentClickingState.camera}}const log$e=new Logger("box");class Box extends Zone{constructor(e){super(e);ct(this,"lastLocation");this.room=e}async access(e){if(!["left","right"].includes(e))return log$e.error(`direction: ${e} is invalid`),Promise.reject(`direction: ${e} is invalid`);this.lastLocation={player:this.room.currentClickingState.player,camera:this.room.currentClickingState.camera};const o=DEFAULT_SKINS.ISLAND.skinId,s=await this.room.modelManager.findRoute(o,e==="left"?"zuobaoxiang":"youbaoxiang"),c=getRandomItem(s.birthPointList),{areaName:d,pathName:_,attitude:b}=s;return c?(this.room.breathPoint.hideAll(),this.handleChangePerson(qt(Kt({},c),{areaName:d,pathName:_,attitude:b}))):(log$e.error("targetLocation is undefined"),Promise.reject("targetLocation is undefined"))}async exit(){const{player:e,camera:o}=this.lastLocation;if(!e||!o)return log$e.error("params error, camera or player is undefined"),Promise.reject("params error, camera or player is undefined");const s=DEFAULT_SKINS.ISLAND.skinId,c=await this.room.modelManager.findRoute(s,DEFAULT_SKINS.ISLAND.defaultStreamPath),{pathName:d,areaName:_,attitude:b}=c;return!_||!d||!b?(log$e.error("params error, areaName, pathName or attitude is undefined"),Promise.reject("params error, areaName, pathName or attitude is undefined")):(this.room.breathPoint.showBreathPointInSkin(),this.room.panorama.exit({player:e,camera:o,attitude:b,areaName:_,pathName:d}).then(()=>{this.actived=!1,this.room.fireworkEffectsManager.unRegisterFireworkEvents(),this.room.fireworkEffectsManager.disposeEffects()}))}handleChangePerson(e){return this.room.panorama.access(e).then(()=>{this.actived=!0,this.room.fireworkEffectsManager.registerFireworkEvents(["NewYear"],["Sphere"])})}}const log$d=new Logger("watchTower");let lastUserAvatarPose$2=null,lastCameraPose$2;const WATCHTOWER_PATHNAME="thirdwalktower",TELESCOPE_PATHNAME="wangyuanjing";class Telescope{constructor(i){ct(this,"actived",!1);this.room=i}access(){const i=Date.now();return this._access().then(e=>(log$d.infoAndReportMeasurement({startTime:i,metric:"telescope"}),e)).catch(e=>(log$d.infoAndReportMeasurement({startTime:i,metric:"telescope",error:e}),Promise.reject(e)))}async _access(){const i=DEFAULT_SKINS.ISLAND.skinId,e=await this.room.modelManager.findRoute(i,TELESCOPE_PATHNAME),{pathName:o,areaName:s,attitude:c}=e,{camera:d,player:_}=getRandomItem(e.birthPointList)||{};return!d||!_?Promise.reject("params error, camera or player is undefined"):this.room.panorama.access({camera:d,player:_,areaName:s,pathName:o,attitude:c}).then(()=>{var b;this.actived=!0,(b=this.room._userAvatar)==null||b.hide(),this.room.breathPoint.hideAll()})}exit(){const i=Date.now();return this._exit().then(e=>(log$d.infoAndReportMeasurement({startTime:i,metric:"telescopeExit"}),e)).catch(e=>(log$d.infoAndReportMeasurement({startTime:i,metric:"telescopeExit",error:e}),Promise.reject(e)))}async _exit(){const i=DEFAULT_SKINS.ISLAND.skinId,e=await this.room.modelManager.findRoute(i,WATCHTOWER_PATHNAME),{pathName:o,areaName:s,attitude:c}=e,{camera:d,player:_}=getRandomItem(e.birthPointList)||{};return!d||!_||!o||!s||!c?(log$d.error("params error,attitude\u3001pathName\u3001areaName\u3001camera or player is undefined"),Promise.reject("params error,attitude\u3001pathName\u3001areaName\u3001camera or player is undefined")):this.room.panorama.exit({camera:d,player:_,areaName:s,attitude:c,pathName:o}).then(()=>{var b;this.actived=!1,this.room.sceneManager.cameraComponent.detachMainCameraController(),this.room.sceneManager.cameraComponent.changeCameraFov(this.room.camera.initialFov),(b=this.room._userAvatar)==null||b.show(),this.room.breathPoint.showBreathPointInSkin()})}setLensTimes(i){if(!this.actived){log$d.error("telescope is not actived");return}const e=c=>c*Math.PI/180,s={1:e(90),2:e(50),4:e(30)}[i];if(!s){log$d.warn("invalid lens times",i);return}this.room.sceneManager.cameraComponent.changeCameraFov(s)}accessDiscoView(){const i=this.room.isPano;if(!this.actived&&i){const e="telescope is not actived";return log$d.error(e),Promise.reject(e)}return this.room.disco.access()}async exitDiscoView(){const i=this.room.isPano;if(!this.actived&&i){const o="telescope is not actived";return log$d.error(o),Promise.reject(o)}if(!this.room.watchTower.actived&&i)try{await this.room.camera.setPerson(Person.Third),this.room.isPano=!1}catch(o){return log$d.error(`change to third person failed, msg: ${o}`),Promise.reject(`change to third person failed, msg: ${o}`)}return this.room.disco.exit()}}class WatchTower extends EventEmitter{constructor(e){super();ct(this,"actived",!1);ct(this,"telescope");this.room=e,this.telescope=new Telescope(e)}access(){const e=Date.now();return this._access().then(o=>(log$d.infoAndReportMeasurement({startTime:e,metric:"getOnWatchTower"}),this.emit("getOnWatchTower"),o)).catch(o=>(log$d.infoAndReportMeasurement({startTime:e,metric:"getOnWatchTower",error:o}),Promise.reject(o)))}async _access(){if(this.actived)return Promise.reject(new ParamError("watchtower is not actived"));lastUserAvatarPose$2=this.room.currentClickingState.player,lastCameraPose$2=this.room.currentClickingState.camera;const e=DEFAULT_SKINS.ISLAND.skinId,o=await this.room.modelManager.findRoute(e,WATCHTOWER_PATHNAME),{pathName:s,areaName:c,attitude:d}=o,{camera:_,player:b}=getRandomItem(o.birthPointList)||{};return!_||!b||!s||!c||!d?(log$d.error("params error,attitude\u3001pathName\u3001areaName\u3001camera or player is undefined"),Promise.reject("params error,attitude\u3001pathName\u3001areaName\u3001camera or player is undefined")):this.room.transfer({renderType:RenderType.RotationVideo,camera:_,player:b,areaName:c,attitude:d,pathName:s,tag:"watchTower.access"}).then(()=>{this.actived=!0})}exit(){const e=Date.now();return this._exit().then(o=>(log$d.infoAndReportMeasurement({startTime:e,metric:"getOffWatchTower"}),this.emit("getOffWatchTower"),o)).catch(o=>(log$d.infoAndReportMeasurement({startTime:e,metric:"getOffWatchTower",error:o}),Promise.reject(o)))}async _exit(){if(!this.actived)return Promise.reject("watchtower is not actived");if(this.telescope.actived)return Promise.reject("exit telescope before exit watchtower");if(!lastUserAvatarPose$2||!lastCameraPose$2)return log$d.error("params error, camera or player is undefined"),Promise.reject("params error, camera or player is undefined");const{attitude:e,areaName:o,pathName:s}=await this.room.modelManager.findRoute(DEFAULT_SKINS.ISLAND.skinId,DEFAULT_SKINS.ISLAND.defaultStreamPath);return!e||!o||!s?(log$d.error("params error, attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, attitude\u3001areaName or pathName is undefined")):this.room.transfer({renderType:RenderType.RotationVideo,player:lastUserAvatarPose$2,camera:lastCameraPose$2,pathName:s,areaName:o,attitude:e,tag:"watchTower.exit"}).then(()=>{this.actived=!1})}}let lastUserAvatarPose$1,lastCameraPose$1;const log$c=new Logger("disco");class Disco extends EventEmitter{constructor(e){super();ct(this,"actived",!1);ct(this,"decalManager");ct(this,"confessionsWallDecalId","gbq");this.room=e,this.decalManager=e.sceneManager.decalComponent}get effects(){const e=[];return this.room.skin.models.forEach(o=>{o.typeName===AssetTypeName.Effects&&o.className===AssetClassName.Effects&&e.push(o.name)}),e}access(){const e=Date.now(),o=this.room.isPano;return this._access().then(s=>(log$c.infoAndReportMeasurement({tag:DEFAULT_SKINS.DISCO.skinId,startTime:e,metric:"changeSkin",extra:{isPano:o}}),s)).catch(s=>(log$c.infoAndReportMeasurement({tag:DEFAULT_SKINS.DISCO.skinId,startTime:e,metric:"changeSkin",extra:{isPano:o},error:s}),Promise.reject(s)))}async _access(e){const o=this.room.isPano;o||(lastUserAvatarPose$1=this.room.currentClickingState.player,lastCameraPose$1=this.room.currentClickingState.camera);const s=DEFAULT_SKINS.DISCO.skinId,c=await this.room.modelManager.findRoute(s,o?DEFAULT_SKINS.DISCO.defaultPanoramaPath:DEFAULT_SKINS.DISCO.defaultStreamPath),{pathName:d,areaName:_,attitude:b}=c,{camera:k,player:j}=getRandomItem(c.birthPointList)||{};if(!j||!k||!b||!_||!d)return log$c.error("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, camera or player is undefined");const $={skinId:s,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:j,landingCamera:k,renderType:o?RenderType.ClientRotationPano:RenderType.RotationVideo,attitude:b,areaName:_,pathName:d,person:o?Person.First:Person.Third};return e&&(e=Object.assign($,e)),this.room.actionsHandler.changeSkin($).then(_e=>(this.afterAccess(),_e))}afterAccess(){this.actived=!0,this.room.effectManager.clearEffects()}exit(){const e=Date.now();return this._exit().then(o=>(log$c.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin"}),o)).catch(o=>(log$c.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin",error:o}),Promise.reject(o)))}async _exit(e){const o=this.room.isPano,s=DEFAULT_SKINS.ISLAND.skinId,c=await this.room.modelManager.findRoute(s,o?TELESCOPE_PATHNAME:DEFAULT_SKINS.ISLAND.defaultStreamPath),{areaName:d,pathName:_,attitude:b}=c||{},{camera:k,player:j}=getRandomItem(c.birthPointList)||{};if(!j||!k||!b||!d||!_)return log$c.error("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined");if(!o&&(!lastCameraPose$1||!lastUserAvatarPose$1))return log$c.error("params error, camera\u3001playeris undefined"),Promise.reject("params error, camera or player is undefined");let $={skinId:s,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:o?j:lastUserAvatarPose$1,landingCamera:o?k:lastCameraPose$1,renderType:o?RenderType.ClientRotationPano:RenderType.RotationVideo,attitude:b,areaName:d,pathName:_,person:o?Person.First:Person.Third};return e&&($=Object.assign($,e)),this.room.actionsHandler.changeSkin($).then(_e=>(this.afterLeave(),_e))}async setConfessionsWallTexts(e){var _e;if(!Array.isArray(e))return Promise.reject("texts must be array");if(!this.actived)return Promise.reject("disco is not actived");const o=this.confessionsWallDecalId,s=1.47,c=10,d=4,_=1114,b=25,k=_/d,j=90/4,$=17;try{await this.decalManager.setDecalTexture({id:o,buffer:null,isDynamic:!0,width:k*c*s,height:b*s,slots:c,visibleSlots:d});const et=(_e=this.room.skin.models.find(rt=>rt.typeName===AssetTypeName.Textures&&rt.className===AssetClassName.Gbq&&rt.name==="highlight2"))==null?void 0:_e.modelUrl;if(!et)return log$c.error("decal img highlight2 not found"),Promise.reject("decal img highlight2 not found");let tt=k;for(const rt of e){const it=(computeWordLength(typeof rt=="object"?rt.text:rt)+2)*$/2;await this.decalManager.updateTexAsImg(o,et,{clearArea:!0,x:(tt+k/2)*s,y:b/2*s,w:it*s,h:j*s,clearW:k*s}),this.decalManager.updateTexAsWords(o,typeof rt=="object"?rt.text:rt,{clearArea:typeof rt=="object"?!rt.isHighlight:!0,x:(tt+k/2)*s,y:b/2*s,w:k*s,h:j*s,fontsize:$*s,slots:c,visibleSlots:d,font:"foundertype16",color:"#e6e6e6",fontweight:300}),tt+=k,tt>=k*c&&(tt=0)}return this.decalManager.startAnime(o,{callback:()=>{this.emit("confessionsWallEnter")}}),Promise.resolve()}catch(et){return Promise.reject(et)}}afterLeave(){this.actived=!1,this.room.effectManager.clearEffects()}async showEffect(e){let o,s,c,d;if(typeof e=="string")o=e;else if(typeof e=="object")o=e.name,s=e.scale,c=e.userId,d=e.position;else return Promise.reject("the param must be string or object");this.room.effectManager.clearEffects();const _=Date.now(),b=this.room.skin.models.find(k=>k.typeName===AssetTypeName.Effects&&k.name===o);return b?this.room.effectManager.loadEffect(b.name).then(k=>{var j;if(!k)return Promise.reject(`no such effect with name: ${o}`);if(s&&k.setScaling(s),c){const $=d||((j=this.room.avatars.find(_e=>_e.userId===c))==null?void 0:j.position);$&&k.setPosition($)}return k.play(!0).then($=>(log$c.infoAndReportMeasurement({tag:o,startTime:_,metric:"playEffect"}),$))}).catch(k=>(log$c.infoAndReportMeasurement({tag:o,startTime:_,metric:"playEffect",error:k}),Promise.reject(k))):Promise.reject(`no such effect with name: ${o}`)}hideEffect(e){const o=this.room.effectManager.effects.get(e);return o?o.hide():Promise.reject(`no such effect with name :${e}`)}hideAllEffect(){this.room.effectManager.effects.forEach(e=>{e.hide()})}clearEffects(){this.room.effectManager.clearEffects()}removeEffect(e){this.room.effectManager.removeEffect(e)}}const log$b=new Logger("effects-manager");class EffectsManager{constructor(i){ct(this,"_active",!1);ct(this,"_pickableMeshs",[]);ct(this,"_effects",[]);this.room=i,i.on("pointTap",debounce(async e=>{var c;if(!this._active||this._effects.length===0||!((c=this._pickableMeshs)!=null&&c.includes(e.meshName)))return;e=getPointerWorldPos(this.room.scene,150);const o=this._effects[Math.floor(Math.random()*this._effects.length)],s=Date.now();try{let d=this.room.effectManager.effects.get(o);d||(d=await this.loadEffect(o)),d.setPosition(e.position),await d.play(),log$b.infoAndReportMeasurement({tag:o,startTime:s,metric:"playEffect"})}catch(d){const _={code:"3xxx",msg:d};this.room.emit("error",_),log$b.infoAndReportMeasurement({tag:o,startTime:s,metric:"playEffect",error:d})}},500))}registerFireworkEvents(i,e){this._active=!0,this._effects=i,this._pickableMeshs=e,this.room.skin.models.filter(o=>o.typeName===AssetTypeName.Effects&&i.includes(o.name)).forEach(o=>this.loadEffect(o.name))}unRegisterFireworkEvents(){this._active=!1,this._effects=[]}loadEffect(i){return this.room.effectManager.loadEffect(i)}disposeEffects(){this.room.effectManager.clearEffects()}}const log$a=new Logger("game-center");class GameCenter extends Zone{constructor(e){super(e);ct(this,"actived",!1);this.room=e}access(){const e=Date.now();return this._access().then(o=>(log$a.infoAndReportMeasurement({tag:DEFAULT_SKINS.GAME_CENTER.skinId,startTime:e,metric:"changeSkin"}),o)).catch(o=>(log$a.infoAndReportMeasurement({tag:DEFAULT_SKINS.GAME_CENTER.skinId,startTime:e,metric:"changeSkin",error:o}),Promise.reject(o)))}async _access(){this.saveLastPoses();const e=DEFAULT_SKINS.GAME_CENTER.skinId,o=await this.room.modelManager.findRoute(e,DEFAULT_SKINS.GAME_CENTER.defaultStreamPath),{pathName:s,areaName:c,attitude:d}=o,{camera:_,player:b}=getRandomItem(o.birthPointList)||{};if(!b||!_||!d||!c||!s)return log$a.error("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined");const k={skinId:e,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:b,landingCamera:_,renderType:RenderType.RotationVideo,attitude:d,areaName:c,pathName:s,person:Person.Third};return this.room.actionsHandler.changeSkin(k).then(j=>(this.actived=!0,j))}exit(){const e=Date.now();return this._exit().then(o=>(log$a.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin"}),o)).catch(o=>(log$a.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin",error:o}),Promise.reject(o)))}async _exit(e){if(!this.lastUserAvatarPose||!this.lastCameraPose)return log$a.error("params error, camera or player is undefined"),Promise.reject("params error, camera or player is undefined");const o=DEFAULT_SKINS.ISLAND.skinId,s=await this.room.modelManager.findRoute(o,DEFAULT_SKINS.ISLAND.defaultStreamPath),{attitude:c,areaName:d,pathName:_}=s||{};if(!c||!d||!_)return log$a.error("params error, attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, attitude\u3001areaName or pathName is undefined");let b={skinId:o,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:this.lastUserAvatarPose,landingCamera:this.lastCameraPose,renderType:RenderType.RotationVideo,attitude:c,areaName:d,pathName:_,person:Person.Third};return e&&(b=Object.assign(b,e)),this.room.actionsHandler.changeSkin(b).then(k=>(this.actived=!1,k))}}const log$9=new Logger("livehall"),LIVE_BOARD_CONFIGS=[{modelName:"TV1_xverse.glb",animation:"Hallo",index:0,avatarPose:{position:{x:-1147,y:-346,z:0},rotation:{pitch:0,yaw:385,roll:0}},breathPointPose:{position:{x:-1695,y:-545,z:216}},words:"\u4E3B\u64AD\u53EF\u4EE5\u9009\u62E9\u81EA\u5DF1\u7684\u865A\u62DF\u5F62\u8C61"},{modelName:"TV2_xverse.glb",animation:"Singing",index:1,avatarPose:{position:{x:-496,y:-1144,z:0},rotation:{pitch:0,yaw:414,roll:0}},breathPointPose:{position:{x:-636,y:-1662,z:243}},words:"\u4E3B\u64AD\u53EF\u4EE5\u4F7F\u7528\u89C2\u4F17\u9001\u51FA\u7684\u623F\u95F4\u76AE\u80A4"},{modelName:"TV3_xverse.glb",animation:"Yaotou",index:2,avatarPose:{position:{x:534,y:-1223,z:0},rotation:{pitch:0,yaw:473,roll:0}},breathPointPose:{position:{x:760,y:-1747,z:186}},words:"\u89C2\u4F17\u53EF\u4EE5\u9001\u7ED9\u4E3B\u64AD\u670D\u88C5\uFF0C\u4E3B\u64AD\u53EF\u4EE5\u6362\u88C5"},{modelName:"TV4_xverse.glb",animation:"Dance05",index:3,avatarPose:{position:{x:1183,y:-571,z:0},rotation:{pitch:0,yaw:505,roll:0}},breathPointPose:{position:{x:1957,y:-831,z:194}},words:"\u89C2\u4F17\u8D2D\u4E70\u9001\u51FA\u7684\u793C\u7269\u53EF\u4EE5\u5728\u623F\u95F4\u5185\u6446\u653E"},{modelName:"TV4_xverse.glb",animation:"GiftClap",index:4,avatarPose:{position:{x:193,y:426,z:0},rotation:{pitch:0,yaw:65,roll:0}},breathPointPose:{position:{x:1957,y:-831,z:194}},words:"\u865A\u62DF\u76F4\u64AD\u95F4\u5373\u5C06\u5F00\u653E\uFF0C\u656C\u8BF7\u671F\u5F85"}];class LiveHall extends Zone{constructor(e){super(e);ct(this,"liveIds",[]);ct(this,"actived",!1);ct(this,"billboardManager");ct(this,"decalManager");ct(this,"decalTextureMap",new Map);this.room=e,this.billboardManager=this.room.sceneManager.billboardComponent,this.decalManager=new XDecalManager(this.room.sceneManager)}access(){const e=Date.now();return this._access().then(o=>(log$9.infoAndReportMeasurement({tag:DEFAULT_SKINS.LIVE_HALL.skinId,startTime:e,metric:"changeSkin"}),o)).catch(o=>(log$9.infoAndReportMeasurement({tag:DEFAULT_SKINS.LIVE_HALL.skinId,startTime:e,metric:"changeSkin",error:o}),Promise.reject(o)))}async _access(){this.saveLastPoses();const e=DEFAULT_SKINS.LIVE_HALL.skinId,o=await this.room.modelManager.findRoute(e,DEFAULT_SKINS.LIVE_HALL.defaultStreamPath),{pathName:s,areaName:c,attitude:d}=o,{camera:_,player:b}=getRandomItem(o.birthPointList)||{};if(!b||!_||!d||!c||!s)return log$9.error("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined");const k={skinId:e,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:b,landingCamera:_,renderType:RenderType.RotationVideo,attitude:d,areaName:c,pathName:s,person:Person.Third};return this.room.actionsHandler.changeSkin(k).then(j=>(this.actived=!0,j))}exit(){const e=Date.now();return this._exit().then(o=>(log$9.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin"}),o)).catch(o=>(log$9.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin",error:o}),Promise.reject(o)))}async _exit(e){if(!this.lastUserAvatarPose||!this.lastCameraPose)return log$9.error("params error, camera or player is undefined"),Promise.reject("params error, camera or player is undefined");const o=DEFAULT_SKINS.ISLAND.skinId,s=await this.room.modelManager.findRoute(o,DEFAULT_SKINS.ISLAND.defaultStreamPath),{attitude:c,areaName:d,pathName:_}=s||{};if(!c||!d||!_)return log$9.error("params error, attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, attitude\u3001areaName or pathName is undefined");let b={skinId:o,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:this.lastUserAvatarPose,landingCamera:this.lastCameraPose,renderType:RenderType.RotationVideo,attitude:c,areaName:d,pathName:_,person:Person.Third};return e&&(b=Object.assign(b,e)),this.room.actionsHandler.changeSkin(b).then(k=>(this.actived=!1,this.clearLiveInfos(),k))}setLiveInfos(e){this.clearLiveInfos(),log$9.info("livehall setLiveInfos",e),this.liveIds=e.map(c=>c.id);const o=[];LIVE_BOARD_CONFIGS.length===0&&log$9.warn("LIVE_BOARD_CONFIGS is empty");const s=[{x:-1757,y:-546,z:501},{x:-661,y:-1739,z:491},{x:630,y:-1723,z:427},{x:1960,y:-832,z:373}];return LIVE_BOARD_CONFIGS.forEach(async(c,d)=>{const _=e[d];if(!!_){try{this.updateBillboard(_,s[d]),this.updateDecal(_,c),this.updateBreathPoint(_,c)}catch(b){return log$9.error(b),Promise.reject(b)}this.room.avatarManager.addAvatar({userId:"hostAvatar"+uuid$1(),avatarPosition:c.avatarPose.position,avatarRotation:c.avatarPose.rotation,avatarId:_.avatarId,avatarComponents:_.avatarComponents||[],nickname:_.avatarNickname||_.hostName,priority:1}).then(b=>{b==null||b._playAnimation("GiftClap",!0),setTimeout(()=>{b==null||b._playAnimation(_.animation||c.animation,!0)},3e3),_.words&&(b==null||b.say(_.words))}).catch(b=>{log$9.error(`livehallGuider: ${"hostAvatar"+uuid$1()} load error`,b)})}}),Promise.all(o)}showLiveGuiders(){LIVE_BOARD_CONFIGS.forEach(async e=>{this.room.avatarManager.addAvatar({userId:"hostAvatar"+uuid$1(),avatarPosition:e.avatarPose.position,avatarRotation:e.avatarPose.rotation,avatarId:Math.random()>.5?"KGe_Girl":"KGe_Boy",avatarComponents:[],priority:1}).then(o=>{o==null||o._playAnimation(e.animation,!0),o==null||o.say(e.words)}).catch(o=>{log$9.error(`livehallGuider: ${"hostAvatar"+uuid$1()} load error`,o)})})}toggleChangeComponents(e){!this.actived||(this.liveIds.forEach(o=>{this.billboardManager.toggle(o,e),this.decalManager.toggle(o,e)}),this.liveIds.map(o=>{var s;return(s=this.room.breathPointManager.breathPoints.get(o))==null?void 0:s.toggleVisibility(e)}))}clearLiveInfos(){this.room.avatars.filter(o=>o.userId.startsWith("hostAvatar")).map(o=>o.id).forEach(o=>this.room.avatarManager.removeAvatar(o)),this.room.breathPoint.deleteBreathPoints(this.liveIds),this.liveIds.forEach(o=>{this.billboardManager.removeBillboard(o),this.decalManager.deleteDecal(o),this.decalTextureMap.delete(o)})}async updateDecal(e,o){var _;const{id:s,thumbnailUrl:c}=e,d=(_=this.room.skin.models.find(b=>b.typeName===AssetTypeName.Model&&b.className===AssetClassName.Reward&&b.name===o.modelName))==null?void 0:_.modelUrl;if(!d)return log$9.error(new ParamError(`model with name: ${o.modelName} is undefined`)),Promise.reject(new ParamError(`model with name: ${o.modelName} is undefined`));this.decalManager.decals.find(b=>b.id===s)||await this.decalManager.addDecal({id:s,meshPath:d}),!(this.decalTextureMap.get(s)===c&&c)&&(await this.decalManager.setDecalTexture({id:s,buffer:c}),this.decalTextureMap.set(s,c))}async updateBillboard(e,o){const{id:s}=e;this.billboardManager.billboardMap.has(s)||this.billboardManager.generateStaticBillboard(e.hostName,{id:s,isUser:!1,font:"Arial",fontsize:40,fontcolor:"#ffffff",fontstyle:"600",linesize:16,scale:1.5,width:.01,height:.01,position:o})}async updateBreathPoint(e,o){var d;if(this.room.breathPointManager.breathPoints.get(e.id))return;const s=(d=this.room.skin.models.find(_=>_.typeName===AssetTypeName.Textures&&_.name==="LiveEntrance"))==null?void 0:d.modelUrl;if(!s)return log$9.error("no such textrue with name : LiveEntrance"),Promise.reject("no such textrue with name : LiveEntrance");let c;try{c=await urlTransformer(s)}catch(_){return c=s,log$9.error("urlTransformer error",_),Promise.reject(_)}return this.room.breathPointManager.addBreathPoint({id:e.id,position:o.breathPointPose.position,spriteSheet:c,spriteWidthNumber:1,spriteHeightNumber:1,width:2.8,height:2,rotation:o.breathPointPose.rotation||{pitch:0,yaw:270,roll:0},billboardMode:!0,type:ClickTargetName.LiveEntrance})}}const httpUrl="https://sit-eks.xverse.cn/pixelPoster",getLatestLit=a=>{const{userId:i}=a;return http$1.post({url:httpUrl+"/GetLatestLit",timeout:6e3,data:{userId:i}})},getAllLit=a=>{const{userId:i,isNeedUserComments:e=!0}=a;return http$1.post({url:httpUrl+"/GetAllLit",timeout:6e3,data:{condition:{userId:i,isNeedUserComments:e}}})},getLuckyChoose=a=>{const{userId:i}=a;return http$1.post({url:httpUrl+"/LuckyChoose",timeout:6e3,withCredentials:!0,data:{userId:i}})},postLitPixel=a=>{const{userId:i,comment:e,nickname:o,avatarUrl:s}=a;return http$1.post({url:httpUrl+"/LitPixel",timeout:6e3,data:{userId:i,comment:e,nickname:o,avatarUrl:s}})},getLitByCoor=a=>{const{coordinate:i}=a;return http$1.post({url:httpUrl+"/GetLitByCoor",timeout:6e3,data:{coordinate:i}})},getAllLitBlock=()=>http$1.post({url:httpUrl+"/GetAllLitBlock",timeout:6e3,data:{}}),log$8=new Logger("musicianHall");var CommentWallBlock=(a=>(a[a.Left=0]="Left",a[a.Right=1]="Right",a))(CommentWallBlock||{});const ALBUM_ID_PREFIX="bofang_",PLAYING_ALBUM_ID_SUFFIX="_playing",getDecalId=a=>"Bofang_"+a+"_xverse.glb",getPlayBreathPointId=a=>ALBUM_ID_PREFIX+a,getPlayingBreathPointId=a=>ALBUM_ID_PREFIX+a+PLAYING_ALBUM_ID_SUFFIX,Rr=class extends Zone{constructor(e){super(e);ct(this,"decal");ct(this,"canvas",null);ct(this,"canvas2",null);ct(this,"currentAlbums",[]);ct(this,"totalAlbums");ct(this,"currentPage",0);ct(this,"albumsPerPage",6);ct(this,"_playingAlbumdId");ct(this,"defaultImageUrl");ct(this,"isPixelLuckyChoose",!1);ct(this,"isPixelLit",!1);ct(this,"pixelPreTime",6);ct(this,"pixelStartTime",10);ct(this,"pixelEndTime",23);ct(this,"beAddedBreathPoint",[]);ct(this,"maxHeight",1e3);ct(this,"scaleUnit",e=>e*1);ct(this,"drawRoundedRect",(e,o,s,c,d,_,b,k)=>{const j=e;if(typeof k=="undefined"&&(k=!0),typeof _=="undefined"&&(_=5),typeof _=="number")_={tl:_,tr:_,br:_,bl:_};else{const $={tl:0,tr:0,br:0,bl:0};for(const _e in $)_[_e]=_[_e]||$[_e]}j.beginPath(),j.moveTo(o+_.tl,s),j.lineTo(o+c-_.tr,s),j.quadraticCurveTo(o+c,s,o+c,s+_.tr),j.lineTo(o+c,s+d-_.br),j.quadraticCurveTo(o+c,s+d,o+c-_.br,s+d),j.lineTo(o+_.bl,s+d),j.quadraticCurveTo(o,s+d,o,s+d-_.bl),j.lineTo(o,s+_.tl),j.quadraticCurveTo(o,s,o+_.tl,s),j.closePath(),b&&(j.fillStyle=b,j.fill()),k&&j.stroke()});ct(this,"drawRect",(e,o,s,c,d,_)=>{e.fillStyle=_,e.fillRect(this.scaleUnit(o),this.scaleUnit(s),this.scaleUnit(c),this.scaleUnit(d))});ct(this,"drawFont",e=>{const o=e.canvas,s=o.getContext("2d");if(!s)return;const c=e.size||10,d=this.scaleUnit(c)+"px",_=e.color||"black",b=e.family||'-apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif',k=e.textBaseline||"top";s.beginPath(),s.fillStyle=_,s.font=`${d} ${b}`,s.textBaseline=k,this.wrapText({canvas:o,text:e.value,x:this.scaleUnit(e.x),y:this.scaleUnit(e.y),maxWidth:e.maxWidth&&this.scaleUnit(e.maxWidth),maxHeight:e.maxHeight&&this.scaleUnit(e.maxHeight),lineHeight:e.lineHeight&&this.scaleUnit(e.lineHeight),noWrap:e.noWrap}),s.closePath()});ct(this,"wrapText",function(e){const{text:o,x:s,maxWidth:c=e.canvas&&e.canvas.width||300,maxHeight:d=e.maxHeight,lineHeight:_=e.canvas&&parseInt(window.getComputedStyle(e.canvas).lineHeight)||parseInt(window.getComputedStyle(document.body).lineHeight),noWrap:b=!1}=e;let{y:k}=e;if(typeof o!="string"||typeof s!="number"||typeof k!="number")return;const j=e.canvas.getContext("2d");if(!j||typeof o!="string"||typeof s!="number"||typeof k!="number")return;const $=o.split(""),_e=j.measureText(o).width;let et="",tt=1;if(_e<=c){j.fillText(o,s,k);return}for(let rt=0;rt<$.length;rt++){const it=j.measureText(et).width,nt=j.measureText($[rt]).width;if(it+nt>c){if(b||d&&tt*_>d){const ot=et.split("");ot.pop(),ot.pop(),j.fillText(ot.join("")+"...",s,k);break}j.fillText(et,s,k),tt+=1,k+=_,et=$[rt]}else j.measureText($.slice(rt,$.length-1).join("")).width<=c&&rt===$.length-1?j.fillText(et,s,k):et+=$[rt]}j.fillText(et,s,k)});ct(this,"getTextsHeight",(e,o,s,c,d)=>{const _=o.split("");let b="",k=d;e.beginPath();const j='-apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif',$=this.scaleUnit(s)+"px";e.font=`${$} ${j}`,e.fillText("",0,0);for(let _e=0;_e<_.length;_e++){const et=b+_[_e];e.measureText(et).width>c&&_e>0?(k+=d,b=_[_e]):b=et}return e.closePath(),k});ct(this,"genereateCanvasImageSource",async e=>new Promise((o,s)=>{const c=new Image;c.src=e,c.crossOrigin="anonymous",c.onload=()=>{o(c)},c.onerror=d=>{s(d)}}));ct(this,"pagingInterval",0);this.room=e,this.decal=e.sceneManager.decalComponent,this.totalAlbums=[],this.init()}set playingAlbumdId(e){const o=this._playingAlbumdId;this._playingAlbumdId=e,this.refreshBreathPoint(o)}get playingAlbumdId(){return this._playingAlbumdId}async init(){var o,s,c;const e=this.room.userId;if(!![Skins.MusicianHall,Skins.MusicianHallDusk,Skins.MusicianHallNight].some(d=>d===this.room.skinId))try{const d=await getLuckyChoose({userId:e});if(d.status!==200)return;((o=d.data)==null?void 0:o.isLucky)===100?(this.isPixelLuckyChoose=!0,this.isPixelLit=!0):((s=d.data)==null?void 0:s.isLucky)===99?(this.isPixelLuckyChoose=!1,this.isPixelLit=!1):((c=d.data)==null?void 0:c.isLucky)===98&&(this.isPixelLuckyChoose=!0,this.isPixelLit=!1)}catch(d){console.error("error",d)}}setPixelPreTime(e){this.pixelPreTime=e}setPixelStartTime(e){this.pixelStartTime=e}setPixelEndTime(e){this.pixelEndTime=e}async postLitPixel(e){var _;const o=e.userId||this.room.userId,s=e.comment,c=e.nickname||"\u672A\u77E5\u7528\u6237",d=e.avatarUrl||"https://thirdwx.qlogo.cn/mmopen/vi_32/O85oHWfSZEeB6jR0Hn3MUM8hwZ2aEvI8YKcH52tMgHxViaoiaIiagDENvB2R1eQ0O36B9ic3GL6oFH1vmJoMNNpqZA/132";try{if((await postLitPixel({userId:o,comment:s,nickname:c,avatarUrl:d})).data.isLitSuccese===100){this.room.effectManager.loadEffect("HeartDz").then(rt=>{rt.setScaling(2);const it=this.room.userAvatar,nt={x:-1408.121338,y:-292.262695,z:258.713547};rt.effect.goToFrame(0),it.xAvatar.shootTo(nt,rt.effect,5,258.713547).then(()=>{this.showEffect({name:"ClickDz",scale:1.5,position:nt})})}).catch(rt=>Promise.reject("\u52A0\u8F7D\u7279\u6548\u5931\u8D25")),this.room.breathPoint.deleteBreathPoints(["dianlianganniu"]),this.room.breathPoint.deleteBreathPoints(["tishimaopao"]),this.room.breathPoint.deleteBreathPoints(["tishimaopaoguanbi"]);const $=((_=(await this.room.modelManager.findSkinConfig(this.room.skinId)).pointList.find(rt=>rt.id==="chakananniu"))==null?void 0:_.position)||{x:-1421.51,y:-441.13,z:170},_e=ClickTargetName.CheckPixelStatus,et=1,tt=1;return this.room.breathPoint.renderBreathPoint({id:"chakananniu",position:$,name:_e,skinId:this.room.skinId,maxVisibleRegion:20,width:tt,height:et,textureName:"pingtuqiangguangkan"}),this.addBreathPoints({id:"chakananniu",position:$,name:_e,skinId:this.room.skinId,maxVisibleRegion:20,width:tt,height:et,textureName:"pingtuqiangguangkan"}),this.room.userAvatar.removeMood(),Promise.resolve(!0)}return Promise.reject("\u53D1\u5E03\u50AC\u66F4\u4FE1\u606F")}catch{return Promise.reject("\u53D1\u5E03\u50AC\u66F4\u4FE1\u606F")}}async getLatestLitPoster(e){const o=e||this.room.userId;try{const s=await getLatestLit({userId:o});return s.status===200&&s.data.posterInfo?Promise.resolve(s.data.posterInfo):Promise.reject("\u83B7\u53D6\u6700\u65B0\u70B9\u4EAE\u7684\u56FE\u7247\u5931\u8D25")}catch{return Promise.reject("\u83B7\u53D6\u6700\u65B0\u70B9\u4EAE\u7684\u56FE\u7247\u5931\u8D25")}}async getAllLit(){const e=this.room.userId;try{const o=await getAllLit({userId:e});return o.status===200&&o.data.userComment&&o.data.userComment.length>0?Promise.resolve(o.data.userComment):Promise.reject("\u83B7\u53D6\u6240\u6709\u70B9\u4EAE\u7684\u56FE\u7247\u4FE1\u606F\u5931\u8D25")}catch{return Promise.reject("\u83B7\u53D6\u6240\u6709\u70B9\u4EAE\u7684\u56FE\u7247\u4FE1\u606F\u5931\u8D25")}}async getLitByCoor(e){try{const o=await getLitByCoor({coordinate:e});return o.status===200&&o.data?Promise.resolve(o.data):Promise.reject("\u83B7\u53D6\u5750\u6807\u83B7\u53D6 url\u5931\u8D25")}catch{return Promise.reject("\u83B7\u53D6\u5750\u6807\u83B7\u53D6 url\u5931\u8D25")}}async getAllLitBlock(){try{const e=await getAllLitBlock();return e.status===200&&e.data.blockInfo&&e.data.blockInfo.length>0?Promise.resolve(e.data.blockInfo):Promise.reject("\u83B7\u53D6\u6240\u6709\u70B9\u4EAE\u7684block\u7684url\u5931\u8D25")}catch{return Promise.reject("\u83B7\u53D6\u6240\u6709\u70B9\u4EAE\u7684block\u7684url\u5931\u8D25")}}addBreathPoints(e){this.beAddedBreathPoint.push(e)}async access(){}async exit(){}refreshBreathPoint(e){var c,d,_,b;if(this.currentAlbums.find(k=>k.id===this._playingAlbumdId)){const k=this.currentAlbums.findIndex(_e=>_e.id===this._playingAlbumdId),j=getPlayBreathPointId(k),$=getPlayingBreathPointId(k);(c=this.room.breathPointManager.getBreathPoint(j))==null||c.toggleVisibility(!1),(d=this.room.breathPointManager.getBreathPoint($))==null||d.toggleVisibility(!0)}if(this.currentAlbums.find(k=>k.id===e)){const k=this.currentAlbums.findIndex(_e=>_e.id===e),j=getPlayBreathPointId(k),$=getPlayingBreathPointId(k);(_=this.room.breathPointManager.getBreathPoint(j))==null||_.toggleVisibility(!0),(b=this.room.breathPointManager.getBreathPoint($))==null||b.toggleVisibility(!1)}}async setAlbumsWallData(e,o){this.totalAlbums=e,this.defaultImageUrl=o,await this.showBreathPoints(),await this.albumPaging()}async showBreathPoints(){const o=(await this.getBreathPoints()).map(s=>this.room.breathPoint.renderBreathPoint(s));return Promise.all(o)}async afterAccess(){this.actived=!0}async setComments(e,o){let s="";this.room.skinId===Skins.MusicianHallLuHan?s="L_TV3_xverse.glb":[Skins.MusicianHall,Skins.MusicianHallDusk,Skins.MusicianHallNight].some(k=>k===this.room.skinId)?s=e===0?"L_TV1_xverse.glb":"L_TV3_xverse.glb":s="L_TV3_xverse.glb",this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.style.width="750px",this.canvas.style.height=this.maxHeight+"px",this.canvas.style.position="absolute",this.canvas.style.top="-99999px",this.canvas.style.left="-99999px",this.canvas.id="commentWallRenderCanvas",document.body.appendChild(this.canvas));let c="",d=0;if(Array.isArray(o)?(o.some(k=>!k.content)&&log$8.error("\u5B58\u5728\u8BC4\u8BBA\u5185\u5BB9\u4E3A\u7A7A",o),d=await this.renderComments(this.canvas,o),c=await this.getImageUrlFromCanvas(this.canvas)):c=o,!c)return 0;const _="commentWall"+e;if(!this.decal.decals.find(k=>k.id===_)){const k=await this.room.modelManager.findAsset(this.room.skinId,s,"name");await this.decal.addDecal({id:_,meshPath:k.modelUrl})}return this.decal.setDecalTexture({id:_,buffer:c}).then(()=>{this.decal.toggle(_,!0)}),d}async setNews(e,o){const s="TV11_xverse.glb";this.canvas2||(this.canvas2=document.createElement("canvas"),this.canvas2.style.width="1080px",this.canvas2.style.height=270+"px",this.canvas2.style.position="absolute",this.canvas2.style.top="-99999px",this.canvas2.style.left="-99999px",this.canvas2.id="newsWallRenderCanvas",document.body.appendChild(this.canvas2));let c="",d=0;if(Array.isArray(o)?(o.some(k=>!k.title)&&log$8.error("\u5B58\u5728\u8BC4\u8BBA\u5185\u5BB9\u4E3A\u7A7A",o),d=await this.renderNews(this.canvas2,o),c=await this.getImageUrlFromCanvas(this.canvas2)):c=o,!c)return 0;const _="newsWall"+e;if(!this.decal.decals.find(k=>k.id===_)){const k=await this.room.modelManager.findAsset(this.room.skinId,s,"name");await this.decal.addDecal({id:_,meshPath:k.modelUrl})}return this.decal.setDecalTexture({id:_,buffer:c}).then(()=>{this.decal.toggle(_,!0)}),d}async setPixelWll(e){if(!e)return;const o="TV12_xverse.glb",s="pixelWall";if(!this.decal.decals.find(d=>d.id===s)){const d=await this.room.modelManager.findAsset(Skins.MusicianHall,o,"name");await this.decal.addDecal({id:s,meshPath:d.modelUrl})}this.decal.setDecalTexture({id:s,buffer:e}).then(()=>{this.decal.toggle(s,!0)})}async renderAlbums(e){this.removeLastAlbums(),this.currentAlbums=e,new Array(this.albumsPerPage).fill(null).map((s,c)=>{const d=e[c];return d?qt(Kt({},d),{isEmpty:!1}):{id:"",cover:"",isEmpty:!0}}).forEach((s,c)=>{this.renderAlbum(s,c,s.isEmpty)})}removeLastAlbums(){this.room.breathPointManager.breathPoints.forEach(e=>{e._id.startsWith(ALBUM_ID_PREFIX)&&e.toggleVisibility(!1)})}async renderAlbum(e,o,s){const c=getDecalId(o);if(!this.decal.decals.find(k=>k.id===c)){const k=await this.room.modelManager.findAsset(this.room.skinId,c,"name");await this.decal.addDecal({id:c,meshPath:k.modelUrl})}this.decal.setDecalTexture({id:c,buffer:e.cover||this.defaultImageUrl}).then(()=>{this.decal.toggle(c,!0)});const _=getPlayBreathPointId(o),b=this.room.breathPointManager.getBreathPoint(_);b==null||b.toggleVisibility(!s),o===this.currentAlbums.length-1&&this.refreshBreathPoint()}async getImageUrlFromCanvas(e){return new Promise(function(o,s){e.toBlob(function(c){if(!c)return s("canvas to blob failed");const d=URL.createObjectURL(c);o(d)})})}drawImage(e,o,s,c,d,_){e.drawImage(o,this.scaleUnit(s),this.scaleUnit(c),this.scaleUnit(d),this.scaleUnit(_))}async renderComments(e,o){const s=e.getContext("2d");if(!s)return 0;s.clearRect(0,0,e.width,e.height);const c="#A8A8A8";let d=30;const _=37,b=32,k=44,j=572,$=k*1.2,_e=e.offsetWidth,et=e.offsetHeight;e.width=this.scaleUnit(_e),e.height=this.scaleUnit(et);const tt=async(nt,ot=_,at=d)=>{const ft=this.getTextsHeight(s,nt.content,k,j,$),lt=18,ht=18;this.drawRoundedRect(s,ot,at,677,ft+18+76,20,"#555555",!1);try{const gt=await this.genereateCanvasImageSource(nt.authorAvatarUrl);this.drawImage(s,gt,ot+lt,at+ht,48,48)}catch{log$8.error("render image error "+nt.authorAvatarUrl)}this.drawFont({canvas:e,value:nt.authorName,size:32,color:c,x:ot+48+lt+21,y:at+ht});const pt=String(nt.likeCount),dt=s.measureText(pt).width;this.drawFont({canvas:e,value:pt,size:32,color:c,x:this.canvas.width-dt-_-67,y:at+ht});try{const gt=await this.genereateCanvasImageSource("https://app-asset-1258211750.file.myqcloud.com/2/textures/like-count.png"),_t=44;this.drawImage(s,gt,ot+615,at+ht/2,_t,_t)}catch{log$8.error("render likeImage error")}return this.drawFont({canvas:e,value:nt.content,size:44,color:"#F2F2F2",lineHeight:$,maxWidth:j,x:ot+48+16+12,y:at+58+12}),at+58+ft+12*2};try{const nt=await this.genereateCanvasImageSource("https://app-asset-1258211750.file.myqcloud.com/2/textures/comment-background.png");this.drawImage(s,nt,0,0,_e,et)}catch{log$8.error("render bgImage error"),this.drawRect(s,0,0,_e,et,"#000000")}let rt=0;const it=this.maxHeight-d;for(const[nt,ot]of o.entries()){const at=await tt(ot,_,d),st=it-at,ut=o[nt+1];if(rt=nt,ut){if(58+this.getTextsHeight(s,ut.content,k,j,$)+b>st)return rt}else return rt;d=at+b}return rt}async renderNews(e,o){const s=e.getContext("2d");if(!s)return 0;s.clearRect(0,0,e.width,e.height);const c="#A8A8A8",d=14;let _=14;const b=14,j=20*1.2,$=135,_e=174,et=e.offsetWidth,tt=e.offsetHeight;e.width=this.scaleUnit(et),e.height=this.scaleUnit(tt);const rt=async(ot,at=_,st=d)=>{const lt=$,ht=18,pt=18,mt=18,dt=30,gt=20;this.drawRoundedRect(s,at,st,340,160+12*2+pt*2,20,"#555555",!1);try{const _t=await this.genereateCanvasImageSource(ot.thumbnail[0]||"https://beta-h5.xverse.cn/music-room-h5/news_default.png");this.drawImage(s,_t,at+ht,st+pt,$,$*4/3)}catch{log$8.error("render image error "+ot.thumbnail[0])}return this.drawFont({canvas:e,value:ot.title,size:dt,color:"#fff",x:at+$+ht+12,y:st+pt,maxWidth:_e,maxHeight:dt*3,lineHeight:dt*1.2}),this.drawFont({canvas:e,value:ot.datetime,size:mt,color:c,x:at+$+ht+12,y:st+pt+dt*3+12*2,maxWidth:_e,noWrap:!0}),this.drawFont({canvas:e,value:ot.summary,size:gt,color:c,lineHeight:j,maxWidth:_e,maxHeight:lt-dt*3-mt*1.2,x:at+$+ht+12,y:st+pt+dt*3+mt+12*3}),at+$+_e+12};try{const ot=await this.genereateCanvasImageSource("https://app-asset-1258211750.file.myqcloud.com/2/textures/comment-background.png");this.drawImage(s,ot,0,0,et,tt)}catch{log$8.error("render bgImage error"),this.drawRect(s,0,0,et,tt,"#000000")}let it=0;const nt=1080-_*2;for(const[ot,at]of o.entries()){const st=await rt(at,_,d),ut=nt-st,ft=o[ot+1];if(it=ot,ft){if($+b>ut)return it}else return it;_=st+b*2}return it}handleChangeAlbum(e){const o=Math.ceil(this.totalAlbums.length/this.albumsPerPage);e===ClickTargetName.NextAlbum?(this.currentPage++,this.currentPage>=o&&(this.currentPage=0),this.albumPaging()):e===ClickTargetName.LastAlbum&&(this.currentPage--,this.currentPage<0&&(this.currentPage=o-1),this.albumPaging())}handleClickPagination(e){this.handleChangeAlbum(e)}albumPaging(){return this.currentAlbums=this.totalAlbums.slice(this.currentPage*this.albumsPerPage,(this.currentPage+1)*this.albumsPerPage),this.renderAlbums(this.currentAlbums)}makeAutoPaging(){const e=Rr.PAGING_INTERVAL;this.pagingInterval=window.setInterval(()=>{this.handleChangeAlbum(ClickTargetName.NextAlbum)},e)}clearAutoPaging(){window.clearInterval(this.pagingInterval)}async getBreathPoints(){const e=new Date().getHours(),o=e>=this.pixelPreTime&&e<this.pixelStartTime,s=e>=this.pixelStartTime&&e<=this.pixelEndTime,c=e>this.pixelEndTime||e<this.pixelPreTime,d=this.room.skin.id;let _=[];o||c||s&&this.isPixelLuckyChoose&&this.isPixelLuckyChoose&&this.isPixelLit;try{_=(await this.room.modelManager.findSkinConfig(this.room.skinId)).pointList}catch{}const b=[];return _.forEach(k=>{if(k.id.startsWith(ALBUM_ID_PREFIX)){const j={id:k.id,position:k.position,name:ClickTargetName.PlayAlbum,skinId:d,maxVisibleRegion:100,width:1,height:1,textureName:"Play2",defaultVisibility:!1};b.push(j);const $={id:k.id+PLAYING_ALBUM_ID_SUFFIX,position:k.position,name:ClickTargetName.AlbumPlaying,skinId:d,maxVisibleRegion:100,width:1,height:1,textureName:"pasue-1",defaultVisibility:!1};b.push($)}else if(k.id.startsWith("fangye_")){const j=k.id==="fangye_left"?"Last-1":"Next-1",$=k.id==="fangye_left"?ClickTargetName.LastAlbum:ClickTargetName.NextAlbum,_e={id:k.id,position:k.position,name:$,skinId:d,maxVisibleRegion:100,width:.5,height:.5,textureName:j,billboardMode:this.room.skinId===Skins.MusicianHallLuHan,rotation:{pitch:0,yaw:-270,roll:0}};b.push(_e)}else if(k.id.startsWith("pinglunqiang_")){const j=k.id==="pinglunqiang_01"?ClickTargetName.AddLeftComments:ClickTargetName.AddRightComments,$={id:k.id,position:k.position,name:j,skinId:d,maxVisibleRegion:20,width:1,height:1,textureName:"Edit2"};b.push($)}if(k.id==="chakananniu"){const j=ClickTargetName.CheckPixelStatus,$=1,_e=1,et={id:k.id,position:k.position,name:j,skinId:d,maxVisibleRegion:20,width:_e,height:$,textureName:"pingtuqiangguangkan"};s&&this.isPixelLuckyChoose&&!this.isPixelLit||b.push(et)}if(k.id==="dianlianganniu"){const j=ClickTargetName.LitPixel,$=1,_e=1,et={id:k.id,position:k.position,name:j,skinId:d,maxVisibleRegion:20,width:_e,height:$,spriteHeightNum:6,spriteWidthNum:6,textureName:"pingtuqiandianliang"};s&&this.isPixelLuckyChoose&&!this.isPixelLit&&b.push(et)}if(k.id==="tishimaopao"){const j=ClickTargetName.NoticePixelPanel,$=3,_e=2,et={id:k.id,position:k.position,name:j,skinId:d,maxVisibleRegion:20,width:$,height:_e,textureName:"pingtuqiangmaopao",billboardMode:!1,rotation:{pitch:0,yaw:180,roll:0}};s&&this.isPixelLuckyChoose&&this.isPixelLit||b.push(et)}if(k.id==="tishimaopaoguanbi"){const j=ClickTargetName.ClosePixelPanel,$=.3,_e=.3,et={id:k.id,position:k.position,name:j,skinId:d,maxVisibleRegion:20,width:$,height:_e,textureName:"pingtuqiangguangbi",billboardMode:!1,rotation:{pitch:0,yaw:180,roll:0}};s&&this.isPixelLuckyChoose&&this.isPixelLit||b.push(et)}}),b}async showEffect(e){let o,s,c,d;if(typeof e=="string")o=e;else if(typeof e=="object")o=e.name,s=e.scale,c=e.userId,d=e.position;else return Promise.reject("the param must be string or object");this.room.effectManager.clearEffects();const _=Date.now(),b=this.room.skin.models.find(k=>k.typeName===AssetTypeName.Effects&&k.name===o);return b?this.room.effectManager.loadEffect(b.name).then(k=>{var $,_e;if(!k)return Promise.reject(`no such effect with name: ${o}`);s&&k.setScaling(s);let j;return c?j=d||(($=this.room.avatars.find(et=>et.userId===c))==null?void 0:$.position):j=d||((_e=this.room.userAvatar)==null?void 0:_e.position),console.log("effectPosition",j),j&&k.setPosition(j),k.play(!0).then(et=>(log$8.infoAndReportMeasurement({tag:o,startTime:_,metric:"playEffect"}),et))}).catch(k=>(log$8.infoAndReportMeasurement({tag:o,startTime:_,metric:"playEffect",error:k}),Promise.reject(k))):Promise.reject(`no such effect with name: ${o}`)}hideEffect(e){const o=this.room.effectManager.effects.get(e);return o?o.hide():Promise.reject(`no such effect with name :${e}`)}hideAllEffect(){this.room.effectManager.effects.forEach(e=>{e.hide()})}clearEffects(){this.room.effectManager.clearEffects()}removeEffect(e){this.room.effectManager.removeEffect(e)}};let MusicianHall=Rr;ct(MusicianHall,"PAGING_INTERVAL",5*1e3);const log$7=new Logger("index");function getRandomPointsByCenterPoint({range:a=2e3,centerPoint:i,num:e=10}){if(!i||!isPositionCorrect(i))return log$7.error(`param ${i} is invalid`),null;const{x:o,y:s,z:c}=i,d=[];for(let _=0;_<e;_++){const b={x:o+(Math.random()>.5?1:-1)*Math.random()*a,y:s+(Math.random()>.5?1:-1)*Math.random()*a,z:c};d.push(b)}return d}function setPlayerRandomPoints({range:a=2e3,centerPoint:i}){const{x:e,y:o,z:s}=i;return{x:e+(Math.random()>.5?1:-1)*Math.random()*a,y:o+(Math.random()>.5?1:-1)*Math.random()*a,z:s}}const log$6=new Logger("npc"),randomNickname=["\u738B\u7684\u6E29\u67D4","\u5982\u4ECA\u65E7\u57CE\u5F52\u5979\u4EBA","\u63D0\u5200\u5C11\u5E74","\u5C11\u5E74\u5C11\u5E74","\u7EC5\u58EB\u98CE\u5EA6","\u6DF1\u60C5\u4E13\u4E00\u7537\u4EBA","Ming","\u795E\u4E00\u822C\u7684\u5BB6\u4F19","\u59CB\u7EC8\u4E00\u4E2A\u4EBA","\u8BF4\u8C0E","\u6240\u8C13\u7684\u5B66\u9738\u5C31\u662F\u4E0D\u5B66\u4E5F\u7F62","\u4E00\u8DEF\u5411\u5317\u8F89","\u5929\u7136\u5446\u3001\u81EA\u7136\u50BB","\u5982\u679C\u53EF\u4EE5","\u5FAE\u5FAE\u7B11\u7684\u8BF4","\u4F2A\u9762\u541B\u5B50","\u6E29\u67D4\u7684\u610F\u4E49","\u6E29\u67D4\u4F3C\u7709\u773C","\u7A33\u573A\u786C\u6D3E\u3002","\u6211\u4E0D\u662F\u4F20\u8BF4","\u5F80\u4E8B\u5982\u98CE","\u9CB8\u9C7C\u5C9B","\u4F1A\u98DE\u7684\u732A","\u6D63\u718A\u8C46\u8C46","\u6D6E\u4E91","\u82E5\u4E00\u4E09","cello","\u5C0F\u67DA\u5B50","\u8DF3\u8DF3\u8DF3","\u592A\u9633\u56F4\u7740\u6708\u4EAE\u8F6C","Miss complicated"],avatarComponentslist=[{id:"KGe_Girl",avatarComponents:[{type:"head",id:"head"},{type:"clothes",id:"test01_clothes_woman"},{type:"hair",id:"test01_hair_woman"},{type:"pants",id:"test01_pants_woman"},{type:"shoes",id:"test01_shoes_woman"}]},{id:"KGe_Girl",avatarComponents:[{type:"head",id:"head"},{type:"clothes",id:"rock01_clothes_woman"},{type:"hair",id:"rock01_hair_woman"},{type:"pants",id:"rock01_pants_woman"},{type:"shoes",id:"rock01_shoes_woman"}]},{id:"KGe_Girl",avatarComponents:[{type:"head",id:"head"},{type:"clothes",id:"campus01_clothes_woman"},{type:"hair",id:"campus01_hair_woman"},{type:"pants",id:"campus01_pants_woman"},{type:"shoes",id:"campus01_shoes_woman"}]},{id:"KGe_Boy",avatarComponents:[{type:"head",id:"head"},{type:"clothes",id:"test02_clothes_man"},{type:"hair",id:"test02_hair_man"},{type:"pants",id:"test02_pants_man"},{type:"shoes",id:"test02_shoes_man"}]},{id:"KGe_Boy",avatarComponents:[{type:"head",id:"head"},{type:"hair",id:"cityPop02_hair_man"},{type:"shoes",id:"cityPop02_shoes_man"},{type:"suit",id:"cityPop02_suit_man"}]}],randomAnimInObserverMode={viewpoint2:["Yaotou","Hallo","Dance03","Jump_all","LockingHipHopDance"],viewpoint1:["LockingHipHopDance","Hallo","Waving","BlowAKiss","Singing"]};let scenics=[],xiaoNiPointList=[];class NpcManager{constructor(i){ct(this,"actived",!0);ct(this,"xiaoNiActived",!0);ct(this,"XIAONI_RANGE_CONFIG",{EVENT_RANGE:500,IN_RANGE:1e3,OUT_RANGE:2e3});ct(this,"xiaoniIdVerification",/^xiaoni-*/);ct(this,"distance",(i,e)=>{const o=i.x-e.x,s=i.y-e.y,c=i.z-e.z;return Math.sqrt(o*o+s*s+c*c)});this.room=i,this.room.on("userAvatarLoaded",async()=>{setTimeout(()=>{this.addGuideNpc("tmeland","\u6B22\u8FCE\u6765\u5230TMELand\uFF01\uFF01\uFF01")},2e3),this.xiaoNiActived&&this.initXiaoNiNpc();try{const{npcProfiles:e}=await this.room.assistant.getGuideList();scenics=e}catch(e){log$6.error(`getGuideList failed, msg: ${e}`)}this.room._userAvatar.on("stopMoving",()=>{this.setNpc()}),this.room.on("skinChanged",({skin:e})=>{this.clearGuideNpcs()})})}setXiaoNiActived(i){this.xiaoNiActived=i,this.updateXiaoNiNPCs()}initXiaoNiNpc(){const{EVENT_RANGE:i,IN_RANGE:e}=this.XIAONI_RANGE_CONFIG;setTimeout(()=>{this.addXiaoNiNPCs(e,i)},2e3),this.room._userAvatar.on("stopMoving",()=>{this.updateXiaoNiNPCs()}),this.room.watchTower.on("getOnWatchTower",()=>{setTimeout(()=>{this.updateXiaoNiNPCs()},1e3)}),this.room.watchTower.on("getOffWatchTower",()=>{setTimeout(()=>{this.updateXiaoNiNPCs()},1e3)}),this.room.on("skinChanged",()=>{setTimeout(()=>{this.updateXiaoNiNPCs()},1e3)}),this.room.on("touchEnd",()=>{this.setXiaoNiFaceToCamera(i)}),this.room.on("mouseUp",()=>{this.setXiaoNiFaceToCamera(i)})}setNpc(){const i=this.findAvailableGuider();if(!i)this.clearGuideNpcs();else{if(this.room.observerBox.actived||this.room.avatars.find(o=>o.userId===i.npcId))return;this.room.assistant.getGuideSentence({npcId:+i.npcId,scenicName:i.bindPoi}).then(({sentence:o})=>{this.addGuideNpc(i.bindPoi,o)})}}clearGuideNpcs(){scenics.forEach(i=>{!this.room.avatarManager.avatars.get(i.npcId)||this.room.avatarManager.removeAvatar(i.npcId)})}addGuideNpc(i,e){if(!this.actived)return Promise.resolve();const o=scenics.find(s=>s.bindPoi===i);if(!o)return Promise.reject(`no such scenic: ${i}`);if(!(!o.position||!o.rotation))try{const s=JSON.parse(o.position),c=JSON.parse(o.rotation);if(!isPositionCorrect(s)||!isRotationCorrect(c))return Promise.reject(`scenic: ${o} guider's position or rotation is invalid`);const d={id:o.npcId,avatarId:"KGe_Boy"},{id:_,avatarId:b}=d,k=this.room.avatars.find(j=>j.userId===o.bindPoi);return k?(k.say(e),Promise.resolve(k)):this.room.avatarManager.addAvatar({userId:_,avatarId:b,avatarPosition:s,avatarRotation:c,isHost:!1,avatarComponents:[],priority:EAvatarRelationRank.Npc}).then(j=>(j==null||j.say(e),j)).catch(()=>{this.room.emit("error",{code:"3xxx",msg:`add scenic: ${o.bindPoi} guider avatar failed`})})}catch(s){return Promise.reject(s)}}findAvailableGuider(i=5e3){const e=this.room._userAvatar.position;return e?scenics.find(s=>{if(!s.rotation||!s.position)return!1;const{x:c,y:d,z:_}=e;let b=null;try{b=JSON.parse(s.position)}catch{return!1}const{x:k,y:j,z:$}=b;return Math.sqrt((c-k)**2+(d-j)**2+(_-$)**2)<i}):null}addRandomNpcs({range:i=2e3,centerPoint:e,avatarId:o,avatarGroup:s,num:c=10,randomPoints:d}){d||(d=getRandomPointsByCenterPoint({range:i,centerPoint:e,num:c})),d&&d.forEach((_,b)=>{if(this.room.avatars.find(et=>et.userId===s+b))return;const k=Math.random()>.5?"KGe_Girl":"KGe_Boy",j=avatarComponentslist.filter(et=>et.id===k),$=j[Math.floor(Math.random()*j.length)].avatarComponents||[],_e=randomNickname[b]||uuid$1().slice(0,13);this.room.avatarManager.addAvatar({userId:s+b,avatarId:k,avatarPosition:_,isHost:!1,avatarComponents:$,priority:EAvatarRelationRank.Npc,group:AvatarGroup.Npc,nickname:_e}).then(et=>{if(!et)return;let tt=[];s==="birthSquare"?(tt=randomAnimInObserverMode.viewpoint1,et.setRotation({pitch:0,roll:0,yaw:90}),et.setScale(1)):(tt=randomAnimInObserverMode.viewpoint2,et.setScale(1.5));const rt=tt[Math.floor(Math.random()*tt.length)];return setTimeout(()=>{et==null||et._playAnimation(rt,!0).catch(it=>{log$6.error(it)})},1e3*Math.random()),et}).catch(()=>{this.room.emit("error",{code:"3xxx",msg:"add npc avatar failed"})})})}clearNpcsByGroup(i){this.room.avatars.forEach(e=>{e.userId.startsWith(i)&&this.room.avatarManager.removeAvatar(e.userId)})}async handleNpcs(i){var o,s;if(!this.actived)return;const e=i.id;if(e===DEFAULT_SKINS.DISCO.skinId)this.addRandomNpcs({avatarId:"KGe_Boy",avatarGroup:"discoNpc",centerPoint:{x:-250,y:-750,z:0}});else if(e===DEFAULT_SKINS.ISLAND.skinId)this.addRandomNpcs({avatarId:"KGe_Boy",avatarGroup:"\u5E7F\u573ANPC\u{1F604}",centerPoint:{x:1500,y:59500,z:-1},num:20,range:3e3}),this.addRandomNpcs({avatarId:"KGe_Boy",avatarGroup:"airshipBaseNpc",centerPoint:AREA_INFO.airshipBase.points[0].position}),this.addRandomNpcs({avatarId:"KGe_Boy",avatarGroup:"hotAirBalloonBaseNpc",centerPoint:AREA_INFO.hotAirBalloonBase.points[0].position});else if(e===DEFAULT_SKINS.GAME_CENTER.skinId){const d=(s=(o=(await this.room.modelManager.findRoute(e,DEFAULT_SKINS.GAME_CENTER.defaultStreamPath)).birthPointList[0])==null?void 0:o.player)==null?void 0:s.position;this.addRandomNpcs({avatarId:"KGe_Boy",avatarGroup:"gameCenterNpc",centerPoint:d})}}addDancerNpcs(){const i=[{id:"dancer-npc-1",avatarId:"KGe_Boy",position:{x:3725,y:52924,z:2071},rotation:{pitch:0,yaw:30,roll:0}},{id:"dancer-npc-2",avatarId:"KGe_Boy",position:{x:-3574,y:52924,z:2071},rotation:{pitch:0,yaw:-30,roll:0}},{id:"dancer-npc-3",avatarId:"KGe_Boy",position:{x:6313,y:54917,z:1246},rotation:{pitch:0,yaw:50,roll:0}},{id:"dancer-npc-4",avatarId:"KGe_Boy",position:{x:-6386,y:55145,z:1160},rotation:{pitch:0,yaw:-50,roll:0}}];this.room.avatarManager.xAvatarManager.setLodDist(0,5e6),this.room.avatarManager.xAvatarManager.setLodDist(1,5e6),this.room.avatarManager.xAvatarManager.setMaxDistRange(5e5),i.forEach(e=>{if(!this.room.avatars.find(s=>s.userId===e.id)){const{avatarId:s,position:c,id:d}=e;this.room.avatarManager.addAvatar({avatarId:s,avatarPosition:c,isHost:!1,userId:d,avatarComponents:this.room._userAvatar.xAvatar.clothesList,nickname:d,priority:EAvatarRelationRank.Npc}).then(_=>{if(!_)return;_.setScale(5);const b=["Song01_1"],k=b[Math.floor(Math.random()*b.length)];e.rotation&&_.setRotation(e.rotation),_._playAnimation(k,!0).catch(j=>{log$6.error(j)})})}})}addXiaoNiNPCs(i,e){xiaoNiPointList=this.findCanViewXiaoNiPoint(i);const o="cussion_12";xiaoNiPointList==null||xiaoNiPointList.forEach(s=>{if(this.room.avatars.find(d=>d.userId===s.id))this.setXiaoNiFaceToCamera(e);else{const{position:d,id:_}=s;this.room.avatarManager.addAvatar({avatarId:o,avatarPosition:d,isHost:!1,userId:_,group:AvatarGroup.Npc,avatarComponents:this.room._userAvatar.xAvatar.clothesList,nickname:"",priority:EAvatarRelationRank.Npc}).then(b=>{!b||this.setXiaoNiFaceToCamera(e)})}})}findCanViewXiaoNiPoint(i){const e=this.room._userAvatar.position;if(!e)return[];let o=[];return this.room.skinId==="10050"?o=[{id:"xiaoni-npc-1",name:"xiaoni-npc-1",position:{x:3545,y:61856,z:0},rotation:{pitch:0,yaw:0,roll:0}},{id:"xiaoni-npc-2",name:"xiaoni-npc-2",position:{x:38965,y:-29502,z:10513},rotation:{pitch:0,yaw:0,roll:0}}]:o=[{id:"xiaoni-npc-3",name:"xiaoni-npc-3",position:{x:1872,y:-312,z:0},rotation:{pitch:0,yaw:0,roll:0}}],o.filter(c=>c.position?this.distance(c.position,e)<i&&this.xiaoniIdVerification.test(c.id):!1)}getXiaoNiAavatar(i,e){let o=null;return xiaoNiPointList==null||xiaoNiPointList.forEach(s=>{const c=this.room.avatars.find(d=>d.userId===s.id);(c==null?void 0:c.position)&&i&&this.distance(c.position,i)<e&&(o=c)}),o}updateXiaoNiNPCs(){const{EVENT_RANGE:i,IN_RANGE:e,OUT_RANGE:o}=this.XIAONI_RANGE_CONFIG;this.clearXiaoNiNpcs(o),this.xiaoNiActived&&this.addXiaoNiNPCs(e,i)}clearXiaoNiNpcs(i){xiaoNiPointList.forEach(e=>{var o;this.room._userAvatar&&this.room._userAvatar.position&&this.distance(e.position,(o=this.room._userAvatar)==null?void 0:o.position)>i&&this.room.avatarManager.removeAvatar(e.id),this.xiaoNiActived||(this.room.avatarManager.removeAvatar(e.id),xiaoNiPointList=[])})}setXiaoNiFaceToCamera(i){const e=this.room.sceneManager.cameraComponent.getCameraPose().position,o=this.room._userAvatar;if(e&&(o==null?void 0:o.position)){const s=this.getXiaoNiAavatar(o==null?void 0:o.position,i);s&&e&&s.xAvatar.faceTo(e,.1)}}}const log$5=new Logger("box"),observersRandomPoints={viewpoint1:[{x:360,y:61685,z:0},{x:-410,y:61250,z:0},{x:-410,y:61677,z:0},{x:-316,y:61833,z:0},{x:-163,y:61143,z:0},{x:-66,y:61503,z:0},{x:-31,y:61931,z:0},{x:-17,y:60684,z:0},{x:-290,y:61958,z:0},{x:59,y:60614,z:0},{x:78,y:61681,z:0},{x:102,y:61056,z:0},{x:134,y:61905,z:0},{x:-148,y:61979,z:0},{x:306,y:61555,z:0},{x:327,y:61188,z:0},{x:329,y:60598,z:0},{x:538,y:60991,z:0},{x:-141,y:61668,z:0},{x:-234,y:61666,z:0}],viewpoint2:[{x:-16,y:-325,z:0},{x:-536,y:459,z:0},{x:-530,y:-200,z:0},{x:-367,y:9,z:0},{x:-324,y:-500,z:0},{x:-265,y:-345,z:0},{x:-204,y:356,z:0},{x:-203,y:-156,z:0},{x:-159,y:-79,z:0},{x:-59,y:424,z:0},{x:19,y:409,z:0},{x:167,y:14,z:0},{x:388,y:-461,z:0},{x:308,y:-355,z:0},{x:412,y:-64,z:0},{x:200,y:-353,z:0},{x:661,y:-67,z:0},{x:515,y:-383,z:0},{x:0,y:-503,z:0},{x:694,y:410,z:0}]},routeList=[{birthPointList:[{player:{position:{x:-58,y:62348,z:180},angle:{pitch:-6,yaw:270,roll:0}},camera:{position:{x:-58,y:62348,z:180},angle:{pitch:-6,yaw:270,roll:0}}}],attitude:"walk",areaName:"guangchang",pathName:"youbaoxiang"},{birthPointList:[{camera:{angle:{pitch:0,yaw:90,roll:0},position:{x:54,y:-1278,z:450}},player:{angle:{pitch:0,yaw:90,roll:0},position:{x:54,y:-1278,z:450}}}],attitude:"walk",areaName:"diting",pathName:"toushidian"}];class ObserverBox extends Zone{constructor(e){super(e);ct(this,"boxUrl");ct(this,"area");ct(this,"currentLocation",{});this.room=e,this.boxUrl=null}get timeout(){let e=100;return this.room.viewMode==="observer"&&(e=4e3),e}async switch(e){const o=Date.now();return this._switch(e).then(s=>(log$5.infoAndReportMeasurement({tag:e,startTime:o,metric:"observer"}),s)).catch(s=>(log$5.infoAndReportMeasurement({tag:e,startTime:o,metric:"observer",error:s}),Promise.reject(s)))}async _switch(e){if(log$5.warn("switch observer to "+e),this.area===e){log$5.warn("switch observer: you already in "+e);return}const{location:o,observeUrl:s}=await this.getConfig(e);if(e==="inDisco")return this.room.disco._access(qt(Kt({noMedia:!0,special:!1},o),{landingCamera:o.camera,landingPoint:o.player,timeout:this.timeout})).finally(()=>{var c;this.area=e,this._addObserveNpcs(),this.handeObserveBoxChangeSkin(s,o),(c=this.room._userAvatar)==null||c.setPosition(qt(Kt({},o.player.position),{z:0}))});if(e==="inReportHall")return this.room.reportHall._access(qt(Kt({noMedia:!0,special:!1},o),{landingCamera:o.camera,landingPoint:o.player,timeout:this.timeout})).finally(()=>{var c;this.area=e,this._addObserveNpcs(),this.handeObserveBoxChangeSkin(s,o),(c=this.room._userAvatar)==null||c.setPosition(qt(Kt({},o.player.position),{z:0}))});if(e==="birthSquare"){if(this.area==="inReportHall")return this.room.reportHall._exit(qt(Kt({noMedia:!0,special:!1},o),{landingCamera:o.camera,landingPoint:o.player,timeout:this.timeout})).finally(()=>{var c;this.area=e,this._addObserveNpcs(),this.handeObserveBoxChangeSkin(s,o),(c=this.room._userAvatar)==null||c.setPosition(qt(Kt({},o.player.position),{z:0}))});if(this.area==="inDisco")return this.room.disco._exit(qt(Kt({noMedia:!0,special:!1},o),{landingCamera:o.camera,landingPoint:o.player,timeout:this.timeout})).finally(()=>{var c;this.area=e,this._addObserveNpcs(),this.handeObserveBoxChangeSkin(s,o),(c=this.room._userAvatar)==null||c.setPosition(qt(Kt({},o.player.position),{z:0}))})}}async getConfig(e){var c,d;let o;if(e==="inReportHall")o=(await this.room.modelManager.findAsset(Skins.ReportHall,"meetingview2","name")).modelUrl;else if(e==="inMusicianHall"){const _=this.room.skin.id;let b="";_===Skins.MusicianHallDusk?b="VRZJ-duskview":_===Skins.MusicianHallNight?b="VRZJ-nightview":_===Skins.MusicianHallLuHan?b="VRZJ-luhanview":b="VRZJ-daytimeview",o=(await this.room.modelManager.findAsset(_,b,"name")).modelUrl}else{const _=Skins.Island,b=await this.room.modelManager.findSkinConfig(_),k="square_X-58.0_Y62348.0_Z180.0",j="disco_X54.0_Y-1278.0_Z450.0",$=ModelManager.findModels((b==null?void 0:b.models)||[],AssetTypeName.Textures,AssetClassName.Panorama),_e=(c=$.find(tt=>tt.name==k))==null?void 0:c.modelUrl,et=(d=$.find(tt=>tt.name==j))==null?void 0:d.modelUrl;o=e==="inDisco"?et:_e}if(!o)return Promise.reject("no invalid url for observer");const s=await this.getObserverConfigs(e);return s?(this.currentLocation=s,Promise.resolve({location:s,observeUrl:o})):(log$5.error("targetLocation is undefined"),Promise.reject("targetLocation is undefined"))}async getObserverConfigs(e){const s={birthSquare:"youbaoxiang",inDisco:"toushidian",inReportHall:"view",inMusicianHall:"view1"}[e];let c=Skins.Island,d;if(e==="inReportHall"?(c=Skins.ReportHall,d=await this.room.modelManager.findRoute(c,s)):e==="inMusicianHall"?(c=this.room.skin.id,d=await this.room.modelManager.findRoute(c,s)):d=routeList.find(j=>j.pathName===s),!d)return Promise.reject("find observer path failed");const{attitude:_,areaName:b,birthPointList:k}=d;return{attitude:_,areaName:b,pathName:s,camera:k[0].camera,player:k[0].player,renderType:RenderType.ClientRotationPano,person:Person.First}}async access(){const e=Date.now();return this._accessLocal().then(o=>(log$5.infoAndReportMeasurement({tag:this.area,startTime:e,metric:"observer"}),o)).catch(o=>{log$5.infoAndReportMeasurement({tag:this.area,startTime:e,metric:"observer",error:o})}).finally(()=>{this.area!=="inMusicianHall"&&this.room.breathPoint.hideAll(),this._addObserveNpcs()})}async exit(){this.room.npcManager.clearGuideNpcs(),this.room.npcManager.clearNpcsByGroup(this.area==="birthSquare"?"birthSquare":"inDisco");const o={birthSquare:DEFAULT_SKINS.ISLAND,inDisco:DEFAULT_SKINS.DISCO,inReportHall:DEFAULT_SKINS.REPORT_HALL,inMusicianHall:DEFAULT_SKINS.MUSICIAN_HALL}[this.area],s=await this.room.modelManager.findRoute(o.skinId,o.defaultStreamPath);return this.room.panorama.exit({camera:s.birthPointList[0].camera,player:s.birthPointList[0].camera}).then(()=>{var c;(c=this.room._userAvatar)==null||c.show()})}async _accessLocal(){let e="birthSquare";this.room.disco.actived||this.room.skin.id===Skins.Disco?e="inDisco":this.room.reportHall.actived||this.room.skin.id===Skins.ReportHall?e="inReportHall":(this.room.musicianHall.actived||[Skins.MusicianHall,Skins.MusicianHallNight,Skins.MusicianHallDusk,Skins.MusicianHallLuHan].some(c=>c===this.room.skin.id))&&(e="inMusicianHall");const{location:o,observeUrl:s}=await this.getConfig(e);return this.area=e,this.room.gameCenter.actived?this.room.gameCenter._exit(qt(Kt({noMedia:!0,special:!1},o),{landingCamera:o.camera,landingPoint:o.player,timeout:this.timeout})).finally(()=>this.handeObserveBoxChangeSkin(s,o)):this.room.liveHall.actived?this.room.liveHall._exit(qt(Kt({noMedia:!0,special:!1},o),{landingCamera:o.camera,landingPoint:o.player,timeout:this.timeout})).finally(()=>this.handeObserveBoxChangeSkin(s,o)):this.room.vehicle.actived?(this.room.actionsHandler.removeBlockedActions(Actions.Transfer),this.handeObserveBoxImg(s,o)):this.handeObserveBoxImg(s,o)}async handeObserveBoxImg(e,o){let s=null;try{s=await modelTable.query("url",e)}catch(c){log$5.debug("query cache table err",c),log$5.warn("query url error",e),Promise.reject(c)}if(s&&s.model){const c=s.model;return this.boxUrl=c,this.handleChangePerson(o,!0)}else return Promise.reject("no local box img")}async handeObserveBoxChangeSkin(e,o){let s=null;try{s=await modelTable.query("url",e)}catch(c){return log$5.debug("query cache table err",c),log$5.warn("query url error",e),Promise.reject(c)}if(s&&s.model){const c=s.model;return this.boxUrl=c,this.handlePanoData(o)}else return Promise.reject("no cached url")}handleChangePerson(e,o){return this.room.actionsHandler.requestPanorama(e,o,this.timeout).finally(()=>(this.actived=!0,this.handlePanoData(e)))}async handlePanoData(e){let o=this.room.observerBox.boxUrl;o instanceof Blob&&(o=await blobToDataURI$1(o));const s={data:o,finished:!0,camera:e.camera};return this.room.panorama.handleReceivePanorama(s)}_addObserveNpcs(){var e,o,s,c,d;this.room.npcManager.clearGuideNpcs(),(e=this.room._userAvatar)==null||e.hide(),this.room.npcManager.clearNpcsByGroup(this.area==="birthSquare"?"birthSquare":"inDisco"),!(this.area==="inReportHall"||this.area==="inMusicianHall")&&(this.addUserAvatarInServerlessViewMode(),(s=(o=this.room)==null?void 0:o._userAvatar)!=null&&s.xAvatar&&((d=(c=this.room.sceneManager)==null?void 0:c.lightComponent)==null||d.removeShadow(this.room._userAvatar.xAvatar)),this.room.avatarManager.xAvatarManager.setLodUserLimits(0,20),this.room.avatarManager.xAvatarManager.setMaxDistRange(6e4),this.room.avatarManager.xAvatarManager.setLodDist(0,4e4),this.room.avatarManager.xAvatarManager.setLodDist(1,5e4),this.room.avatarManager.xAvatarManager.setLodDist(2,6e4),this.room.npcManager.addRandomNpcs({range:700,centerPoint:this.area==="birthSquare"?{x:6,y:61289,z:0}:{x:0,y:-100,z:0},avatarGroup:this.area,num:20,randomPoints:this.area==="birthSquare"?observersRandomPoints.viewpoint1:observersRandomPoints.viewpoint2}))}addUserAvatarInServerlessViewMode(){if(this.room._userAvatar||this.room.viewMode!=="serverless")return;this.room.engineProxy.setEnv();const{userId:e,nickname:o,player:s,avatarId:c}=this.room.options;this.room.avatarManager.addAvatar({userId:e,isHost:this.room.options.role==="host",nickname:o,avatarPosition:s==null?void 0:s.position,avatarRotation:s==null?void 0:s.angle,avatarId:c,avatarComponents:this.room.options.avatarComponents||[],priority:0,group:AvatarGroup.User}).then(d=>{var _,b;d&&(d==null||d.hide()),this.room.avatarManager.xAvatarManager.setMainAvatar(e),this.room.emit("userAvatarLoaded"),log$5.warn("userAvatarLoaded in observer mode"),(b=(_=this.room.sceneManager)==null?void 0:_.lightComponent)==null||b.removeShadow(this.room._userAvatar.xAvatar)}).catch(d=>{log$5.error(`avatar: ${e} load to scene error,`,d),this.room.avatarManager.xAvatarManager.setMainAvatar(e),this.room.emit("userAvatarFailed",{error:d}),log$5.error("userAvatarFailed in observer mode",d)})}}const log$4=new Logger("photobooth"),configs={photoboothC:{avatarPosition:"zipaidianc",skinId:Skins.Island,cameraPoses:{close:"hailuojinjing",medium:"hailuozhongjing",long:"hailuoquanjing"}},photoboothB:{avatarPosition:"zipaidianbren",skinId:Skins.Island,cameraPoses:{close:"guangchangzipaijinjing",medium:"guangchangzipaizhongjing",long:"guangchangzipaiyuanjing"}},photoboothDisco:{avatarPosition:"zipaiavatar",skinId:Skins.Disco,cameraPoses:{close:"jinjing",medium:"zhongjing",long:"quanjing"}}};class PhotoBooth extends EventEmitter{constructor(e){super();ct(this,"_shots","long");ct(this,"lastUserAvatarPose");ct(this,"lastCameraPose");ct(this,"id");this.room=e}get shots(){return this._shots}start(e,o){var c,d;return this.id=e,configs[this.id]?(this.room._userAvatar&&(this.lastUserAvatarPose=(c=this.room.currentClickingState)==null?void 0:c.player,this.lastCameraPose=(d=this.room.currentClickingState)==null?void 0:d.camera),this.setShots(o===void 0?this.shots:o)):Promise.reject("invalid shot, "+e)}setShots(e){const o=Date.now();return this._setShots(e).then(s=>(log$4.infoAndReportMeasurement({tag:this.id+"_"+e,startTime:o,metric:"photobooth"}),s)).catch(s=>(log$4.infoAndReportMeasurement({tag:this.id+"_"+e,startTime:o,metric:"photobooth",error:s}),Promise.reject(s)))}async _setShots(e){if(!this.id)return Promise.reject("Invoke `start()` before `setShots`");const o=configs[this.id],{cameraPoses:s,avatarPosition:c,skinId:d}=o,_=s[e];if(log$4.debug("setShots cameraPose",_),!_){const it="set shots failed, invalid shots value "+e;return log$4.warn(it),Promise.reject(it)}const k=(await this.room.modelManager.findSkinConfig(d)).pointList.find(it=>it.id===c),j=await this.room.modelManager.findRoute(d,_);let{pathName:$}=j;const{areaName:_e,attitude:et}=j,{camera:tt,player:rt}=getRandomItem(j.birthPointList)||{};if($==="hailuoquanjing"?$="hailuoyuanjing":$==="hailuojinjing"&&($="XViewingPointPath_C_2146978511"),!k||!tt||!rt){const it="set shots failed, param error"+e;return log$4.warn(it),Promise.reject(it)}return this.room.panorama.access({camera:tt,player:rt,pathName:$,areaName:_e,attitude:et}).then(()=>{var it,nt;return this.room.switch.othersVisible=!1,this.room.breathPoint.hideAll(),this._shots=e,(it=this.room._userAvatar)==null||it.setPosition(k.position),(nt=this.room._userAvatar)==null||nt.setRotation(k.rotation),e})}stop(){const e=Date.now(),o=this.id+"_"+this._shots;return this._stop().then(s=>(log$4.infoAndReportMeasurement({tag:o,startTime:e,metric:"photoboothExit"}),s)).catch(s=>(log$4.infoAndReportMeasurement({tag:o,startTime:e,metric:"photoboothExit",error:s}),Promise.reject(s)))}async _stop(){if(!this.id)return Promise.reject("Invoke `stop()` before `setShots`");const e=configs[this.id].skinId,o=Object.values(DEFAULT_SKINS).find(b=>b.skinId===e);if(!o)return Promise.reject(new ParamError("photoBooth stop failed"));const s=await this.room.modelManager.findRoute(e,o.defaultStreamPath),{attitude:c,areaName:d,pathName:_}=s;if(!c||!d||!_){const b="stop shots failed, invalid shots value ";return log$4.warn(b),Promise.reject(b)}return this.room.panorama.exit({camera:this.lastCameraPose,player:this.lastUserAvatarPose,attitude:c,areaName:d,pathName:_}).then(()=>{var b,k,j;this.room.switch.othersVisible=!0,this.room.breathPoint.showBreathPointInSkin(),(b=this.room._userAvatar)==null||b.show(),this.lastUserAvatarPose&&((k=this.room._userAvatar)==null||k.setPosition(this.lastUserAvatarPose.position)),this.lastUserAvatarPose&&((j=this.room._userAvatar)==null||j.setRotation(this.lastUserAvatarPose.angle))})}takePhoto(){return this.room.camera.screenShot({name:"screenShot.png"})}}const log$3=new Logger("vehicle");let lastUserAvatarPose=null,lastCameraPose;const VEHICLE_CONFIGS={airship:{routeId:"1",effects:["firework01_1","firework03_2","firework04_2","firework05_2"],camera:{angle:{pitch:-20,yaw:-179,roll:0}}},hotAirBalloon:{routeId:"1",effects:["Xverse","SpriteGun","Hello"]}};class Vehicle extends EventEmitter{constructor(e){super();ct(this,"audio");ct(this,"activedType",null);ct(this,"actived",!1);ct(this,"isBooking",!1);this.room=e}getRouteId(e){return VEHICLE_CONFIGS[e].routeId}getReserveSeat(e){let o=0;if(this.isBooking)throw"\u5DF2\u5728\u9884\u7EA6\u961F\u5217\u4E2D";return this.room.actionsHandler.getReserveSeat({routeId:this.getRouteId(e),name:e}).then(()=>{this.isBooking=!0;const s=setInterval(()=>{this.getReserveState(e).then(c=>{o++,o>=240&&(this.isBooking=!1,clearInterval(s),log$3.debug("\u6392\u961F\u8D85\u65F6")),c!=null&&c.ready&&(this.isBooking=!1,clearInterval(s),this.emit("goOnVehicleReady"))})},5e3)})}getReserveState(e,o){return this.room.actionsHandler.getReserveStatus({routeId:this.getRouteId(e),name:e,need_detail:o||!1})}access(e){const o=Date.now();return this._access(e).then(s=>(log$3.infoAndReportMeasurement({tag:e,startTime:o,metric:"getOnVehicle"}),s)).catch(s=>(log$3.infoAndReportMeasurement({tag:e,startTime:o,metric:"getOnVehicle",error:s}),Promise.reject(s)))}_access(e){if(![VehicleType.Airship,VehicleType.HotAirBalloon].includes(e))return log$3.error(`vehicle: ${e} is invalid`),Promise.reject(`vehicle: ${e} is invalid`);const o=this.getRouteId(e);if(!o)return log$3.error("routeId is undefined"),Promise.reject("routeId is undefined");lastCameraPose=this.room.currentClickingState.camera,lastUserAvatarPose=this.room.currentClickingState.player;let s={routeId:o,name:e};if(e===VehicleType.Airship){const c=VEHICLE_CONFIGS.airship.camera;if(!c)return log$3.error("camera is undefined"),Promise.reject("camera is undefined");s={routeId:o,name:e,camera:c}}return this.getOnVehicle(s).then(c=>{var _,b;log$3.info("this.room.getOnVehicle",c),this.room.actionsHandler.addBlockedActions([Actions.Clicking,Actions.Transfer]);const d=((_=VEHICLE_CONFIGS[e])==null?void 0:_.effects)||[];d.length===0&&log$3.warn("effectsCanPlay is empty"),this.setGroundVehicleVisibility(!1),this.room.fireworkEffectsManager.registerFireworkEvents(d,["Sphere"]),(b=this.room._userAvatar)==null||b.hide(),this.room.breathPoint.hideAll(),this.activedType=e,this.isBooking=!1,this.actived=!0,e===VehicleType.Airship&&this.toggleAudio(!0)})}exit(){const e=Date.now(),o=this.activedType;return this._exit().then(s=>(log$3.infoAndReportMeasurement({tag:o,startTime:e,metric:"getOffVehicle"}),s)).catch(s=>(log$3.infoAndReportMeasurement({tag:o,startTime:e,metric:"getOffVehicle",error:s}),Promise.reject(s)))}_exit(){return!lastUserAvatarPose||!lastCameraPose?(log$3.error("params error, camera or player is undefined"),Promise.reject("params error, camera or player is undefined")):this.getOffVehicle({renderType:RenderType.RotationVideo,player:lastUserAvatarPose,camera:lastCameraPose}).then(()=>{var e;(e=this.room._userAvatar)==null||e.show(),this.activedType===VehicleType.Airship&&this.toggleAudio(!1),this.setGroundVehicleVisibility(!0),this.room.breathPoint.showBreathPointInSkin(),this.clearBlockedActions(),this.activedType=null,this.actived=!1,this.room.sceneManager.cameraComponent.detachMainCameraController(),this.room.fireworkEffectsManager.unRegisterFireworkEvents(),this.room.fireworkEffectsManager.disposeEffects(),this.room.sceneManager.cameraComponent.setCameraPose({position:lastCameraPose.position,rotation:lastCameraPose.angle})})}getOnVehicle({routeId:e,name:o,camera:s}){return this.room.actionsHandler.getOnVehicle({routeId:e,name:o,camera:s}).then(c=>{var d,_;log$3.debug("\u8FDB\u5165\u8F7D\u5177",c),this.room.isOnVehicle=!0,this.room.sceneManager.changeVideoShaderForLowModel(),o===VehicleType.Airship?(d=this.room.airship)==null||d.show():o===VehicleType.HotAirBalloon?(_=this.room.hotAirBalloon)==null||_.show():log$3.warn(`no such type Vehicle with name: ${o}`)})}getOffVehicle({renderType:e,player:o,camera:s}){return this.room.actionsHandler.getOffVehicle({renderType:e,player:o,camera:s}).then(()=>{var c,d;this.activedType===VehicleType.Airship?(c=this.room.airship)==null||c.hide():this.activedType===VehicleType.HotAirBalloon?(d=this.room.hotAirBalloon)==null||d.hide():log$3.warn(`no such type Vehicle with name: ${this.activedType}`),this.room.isOnVehicle=!1})}setGroundVehicleVisibility(e){const o=[];o.push(this.room.sceneManager.staticmeshComponent.getMeshesByGroup("ground_feiting")),o.push(this.room.sceneManager.staticmeshComponent.getMeshesByGroup("ground_reqiqiu")),o.forEach(s=>{s!=null&&(e==!0?s[0].show():s[0].hide())})}clearBlockedActions(){this.room.actionsHandler.removeBlockedActions()}afterReconnect(){this.clearBlockedActions(),setTimeout(()=>{this.activedType&&this.access(this.activedType)},500)}toggleAudio(e){}destroyModel(){["airship","balloon","ground_feiting","ground_reqiqiu"].map(o=>this.room.sceneManager.staticmeshComponent.deleteMeshesByGroup(o))}}const log$2=new Logger("room");class XverseRoom extends XverseRoom$1{constructor(e){super(e);ct(this,"avatarManager",new AvatarManager(this));ct(this,"effectManager",new EffectManager(this));ct(this,"photoBooth");ct(this,"watchTower");ct(this,"vehicle");ct(this,"breathPoint");ct(this,"disco");ct(this,"liveHall");ct(this,"npcManager");ct(this,"box");ct(this,"observerBox");ct(this,"assistant");ct(this,"gameCenter");ct(this,"reportHall");ct(this,"musicianHall");ct(this,"fireworkEffectsManager");ct(this,"airship");ct(this,"hotAirBalloon");ct(this,"isOnVehicle",!1);ct(this,"switch",new Switch(this));ct(this,"joyStick",new JoyStick(this));ct(this,"dataReport",new DataReport(this));ct(this,"_skinStatus","confirm");ct(this,"lastLocationBeforePreviewSkin");ct(this,"handlePress",e=>{log$2.debug("longPress",e)});ct(this,"handleClick",async e=>{var b,k;const{id:o,type:s,point:c}=e;if(await this.breathPoint.isMatched(e))return;if((b=this.userAvatar)!=null&&b._isChangingComponentsMode)return;if(o===SKY_TV_ID)return;if(this.effectManager.rain.actived)return;if(s===EMeshType.XAvatar){this.emit("click",{target:{name:ClickTargetName.Avatar,id:o}});return}else if(s===EMeshType.XBillboard)if(Object.keys(GIFT_CONFIGS).includes(o)){this.emit("click",{target:{name:ClickTargetName.GiftPanel,id:o}});return}else this.emit("click",{target:null});else if(s===EMeshType.Decal)if(this.liveHall.liveIds.includes(o)){this.emit("click",{target:{name:ClickTargetName.LiveEntrance,id:o}}),log$2.infoAndReportMeasurement({value:0,metric:"liveEntranceClick",extra:{id:e.id},startTime:Date.now()});return}else this.emit("click",{target:null});else this.emit("click",{target:null});if(!this.movingByClick||this.isPano||((k=this.vehicle)==null?void 0:k.actived))return;debounce(({point:j,extra:$})=>{var _e;(_e=this.userAvatar)==null||_e.moveTo({point:j,extra:$})},300)({point:c,extra:""})})}get userAvatar(){return this.avatars.find(e=>e.userId===this.userId)}get avatars(){return Array.from(this.avatarManager.avatars.values())}get state(){return this.networkController._state}get skinStatus(){return this._skinStatus}beforeJoinRoomResolveHook(){this.bindEvents(),this.applyPlugin()}afterJoinRoomHook(){this.skinId===Skins.ReportHall?this.reportHall.afterAccess():this.skinId===Skins.GameCenter?this.gameCenter.actived=!0:this.skinId===Skins.LiveHall?this.liveHall.actived=!0:this.skinId===Skins.Disco?this.disco.afterAccess():[Skins.MusicianHall,Skins.MusicianHallNight,Skins.MusicianHallDusk,Skins.MusicianHallLuHan].some(e=>e===this.skinId)&&this.musicianHall.afterAccess(),setInterval(()=>{var e,o;DataStorage.WriteString(LOCATION_STORAGE_KEY,JSON.stringify({skinId:this.skinId,camera:(e=this.currentClickingState)==null?void 0:e.camera,player:(o=this.currentClickingState)==null?void 0:o.player}))},4*1e3)}afterLoadAssetsHook(){let e=EFitMode.cover;[Skins.Disco,Skins.MusicianHall,Skins.MusicianHallNight,Skins.MusicianHallDusk,Skins.MusicianHallLuHan].some(o=>o===this.skinId)&&(e=EFitMode.contain),this.tvs.forEach(o=>{o.objectFit=e})}afterReconnectedHook(){this.vehicle.afterReconnect()}async setViewMode(e){return log$2.warn("invoke setViewMode",e),e==="full"?this.setViewModeToFull():e==="observer"?this.viewMode==="observer"?void 0:this.setViewModeToObserver():(log$2.error("view mode not supported: "+e),Promise.reject("view mode not supported: "+e))}async setViewModeToObserver(){return this.observerBox.access().then(()=>{this.updateCurrentState({viewMode:"observer"})})}async setViewModeToFull(){return this.viewMode==="observer"?(this.networkController._state==="disconnected"&&await this.networkController.reconnect(),this.observerBox.exit().then(()=>{this.updateCurrentState({viewMode:"full"})})):Promise.resolve()}bindEvents(){this.on("_coreClick",this.handleClick)}resume(){return super.resume()}pause(){return super.pause()}applyPlugin(){this.photoBooth=new PhotoBooth(this),this.watchTower=new WatchTower(this),this.vehicle=new Vehicle(this),this.disco=new Disco(this),this.liveHall=new LiveHall(this),this.npcManager=new NpcManager(this),this.box=new Box(this),this.assistant=new Assistant(this),this.gameCenter=new GameCenter(this),this.reportHall=new ReportHall(this),this.fireworkEffectsManager=new EffectsManager(this),this.observerBox=new ObserverBox(this),this.musicianHall=new MusicianHall(this),this.breathPoint=new BreathPoint(this)}switchObserver(e){return this.viewMode!=="observer"?Promise.reject(new ParamError("\u53EA\u80FD\u5728\u89C2\u5BDF\u8005\u6A21\u5F0F\u4E0B\u8C03\u7528\u8BE5\u65B9\u6CD5")):(log$2.info("Invoke switchObserver",e),this.observerBox.switch(e))}transfer(e){const{renderType:o,player:s,camera:c,areaName:d,attitude:_,person:b,pathName:k,tag:j}=e;return this.actionsHandler.transfer({renderType:o,player:s,camera:c,areaName:d,attitude:_,person:b,pathName:k,tag:j}).then(()=>{d&&(this.pathManager.currentArea=d)})}handleSignalHook(e){this.handleVehicle(e)}async beforeStartGameHook(){var s;const o=!!this.options.bossName;if(this.options.skinId===DEFAULT_SKINS.REPORT_HALL.skinId){const{camera:c,player:d}=this.options,_=o?90:250;if(!c||!d)return;let b=d;const{position:k,angle:j}=d;[Skins.Disco,Skins.GameCenter,Skins.Island,Skins.LiveHall,Skins.MusicianHall,Skins.MusicianHallNight,Skins.MusicianHallDusk].includes((s=this.skinId)==null?void 0:s.toString())&&(b={position:setPlayerRandomPoints({centerPoint:k}),angle:j}),c.angle.yaw=_,b.angle.yaw=_,this.updateCurrentNetworkOptions({player:b,camera:c})}}handleVehicle(e){var o,s,c,d,_,b;if(!!e.vehicle)if(e.vehicle.isMoving===MoveType.Stop&&this.vehicle.emit("end",{vehicle:e.vehicle.name}),this.vehicle.activedType===VehicleType.Airship){const k=(c=(s=(o=this.sceneManager.staticmeshComponent)==null?void 0:o.getMeshesByGroup)==null?void 0:s.call(o,"airship"))==null?void 0:c[0];k==null||k.setPosition(e.vehicle.body.position),k==null||k.setRotation(e.vehicle.body.angle)}else if(this.vehicle.activedType===VehicleType.HotAirBalloon){const k=(b=(_=(d=this.sceneManager.staticmeshComponent)==null?void 0:d.getMeshesByGroup)==null?void 0:_.call(d,"balloon"))==null?void 0:b[0];k==null||k.setPosition(e.vehicle.body.position),k==null||k.setRotation(e.vehicle.body.angle)}else log$2.debug(`handleVehicleHook no such type Vehicle with name ${this.vehicle.activedType}`)}setXiaoNiActived(e){this.npcManager.setXiaoNiActived(e)}async changeSkin({skinId:e,mode:o}){if(await this.getSkin(e),this._skinStatus==="confirm"){const{camera:s,player:c}=this._currentClickingState||{};this.lastLocationBeforePreviewSkin=s&&c?{camera:s,player:c}:void 0}return this._changeSkin({skinId:e,mode:o})}async _changeSkin({skinId:e,mode:o}){var et,tt;const s=this.viewMode==="full"?"thirdwalk":"observe2",c=await this.modelManager.findRoute(e,s),d=this.tv.videoElement,_=!!(d!=null&&d.paused),b=!!(d!=null&&d.muted),k=this.tv.isStoped;let j,$,_e=LandingType.Stay;return o===ChangeMode.Cancel?($=(et=this.lastLocationBeforePreviewSkin)==null?void 0:et.player,j=(tt=this.lastLocationBeforePreviewSkin)==null?void 0:tt.camera,$&&j&&(_e=LandingType.NewPoint)):o===ChangeMode.Preview&&await this.actionsHandler.setSyncPolicy({syncPolicy:SyncPolicy.SP_PauseUpdateStatus}),this.actionsHandler.changeSkin({skinId:e,mode:o,areaName:c.areaName,pathName:c.pathName,attitude:c.attitude,renderType:this.viewMode==="full"?RenderType.RotationVideo:RenderType.ClientRotationPano,person:this.viewMode==="full"?Person.Third:Person.First,landingType:_e,landingCamera:j,landingPoint:$,timeout:3e3}).then(()=>{if(this.viewMode==="full")this.camera.removeMainCameraRotationLimit();else{const{camera:rt}=getRandomItem(c.birthPointList)||{};rt&&this.camera.setMainCameraRotationLimit({limitAxis:rt.angle,limitRotation:{yaw:90,pitch:180,roll:180}})}o===ChangeMode.Preview?this.avatarManager.hideAll(!1):(this.avatarManager.showAll(!0),this.actionsHandler.setSyncPolicy({syncPolicy:SyncPolicy.SP_Default})),this._skinStatus=o===ChangeMode.Preview?"preview":"confirm",d&&this.tv.setVideo(d).then(()=>{this.tvs.forEach((rt,it)=>{k&&rt.stop(),it!==0&&rt.mirrorFrom(this.tv).then(()=>{k&&rt.stop()})}),d.muted=b,_&&d.pause()})})}}function injectHttpHook(a,i,e){if(!a||!i)return;let o;Http$1.prototype.transformUrlHook=s=>{var c;if(s.startsWith("https://")){const d=(c=ModelManager.getInstance(a,i).config)==null?void 0:c.preload;if(d){const _=d.assetUrls;o||(o={},_.forEach(k=>{o[k.url]=k.packName}));const b=o[s];b&&(s+=(s.indexOf("?")>0?"&":"?")+`tbundle=${b}`),e&&(s=s.replace(/(https?:\/\/)(.*?)(\/.*)/g,"$1"+e+"$3"))}}return s}}const log$1=new Logger("xverse"),BOSS_AVATAR_SCALE=1.5;class Xverse extends Xverse$1{constructor(e){e&&(e.subPackageVersion=VERSION);super(e);ct(this,"useTmeCdn",!1);ct(this,"subPackageVersion",VERSION);e||(e={});const{useTbundle:o}=e;this.useTmeCdn=o||!1,Xverse.NO_CACHE=!1,this.checkCdnChange(e)}checkCdnChange(e){this.useTmeCdn&&injectHttpHook(e.appId,e.releaseId,e.cdnHost),ModelManager.configCdnHost=e.configCdnHost}async joinRoom(e){let o="thirdwalk",s=RenderType.RotationVideo,c=Person.Third,d=DEFAULT_AVATAR_SCALE;const _={};let b=!1,k=!0;e.bossName&&(o=e.bossName,d=BOSS_AVATAR_SCALE,b=!0,_.bossName=e.bossName,k=!1);const j=!0,$=!0;if(e.rememberLastLocation){const et=safelyJsonParse(DataStorage.ReadString(LOCATION_STORAGE_KEY,"{}"));if(et.skinId){const{camera:tt,player:rt,skinId:it}=et;e.camera=tt,e.player=rt,e.skinId=it}}(e.viewMode==="simple"||e.viewMode==="observer")&&(o="firstwalk",c=Person.First,s=RenderType.ClientRotationPano);const _e=new XverseRoom(qt(Kt({},e),{avatarScale:d,appId:e.appId||this.appId,releaseId:e.releaseId||this.releaseId,pageSession:this.pageSession,isAllSync:!0,rotationRenderType:s,syncByEvent:!0,pathName:o,person:c,role:e.role||"audience",hasAvatar:j,syncToOthers:$,extra:_,prioritySync:b,removeWhenDisconnected:k}));return _e.initRoom().then(()=>_e).catch(et=>{throw log$1.infoAndReportMeasurement({tag:e.viewMode,startTime:_e._startTime,metric:"joinRoom",error:et,reportOptions:{immediate:!0}}),_e.leave(),et})}}const log=new Logger("report-hall"),SKIN_ID=DEFAULT_SKINS.REPORT_HALL.skinId,bossNames=["cussion","ross","shirley","tony"];class ReportHall extends Zone{constructor(e){super(e);ct(this,"actived",!1);this.room=e}access(){const e=Date.now();return this._access().then(o=>(log.infoAndReportMeasurement({tag:SKIN_ID,startTime:e,metric:"changeSkin"}),o)).catch(o=>(log.infoAndReportMeasurement({tag:SKIN_ID,startTime:e,metric:"changeSkin",error:o}),Promise.reject(o)))}async _access(e){this.saveLastPoses();const o=SKIN_ID,s=await this.room.modelManager.findRoute(SKIN_ID,DEFAULT_SKINS.REPORT_HALL.defaultStreamPath),{pathName:c,areaName:d,attitude:_}=s,{camera:b,player:k}=s.birthPointList[0]||{};if(!k||!b||!_||!d||!c)return log.error("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, camera\u3001player\u3001attitude\u3001areaName or pathName is undefined");const j={skinId:o,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:k,landingCamera:b,renderType:RenderType.RotationVideo,attitude:_,areaName:d,pathName:c,person:Person.Third};return e&&(e=Object.assign(j,e)),this.room.actionsHandler.changeSkin(j).then($=>(this.afterAccess(),$))}afterAccess(){this.actived=!0}async addDecal(){const e=await this.room.modelManager.findAsset(SKIN_ID,["paizi1_xverse.glb","paizi2_xverse.glb","paizi3_xverse.glb","paizi4_xverse.glb"],"name"),o=this.room.sceneManager.decalComponent;e.forEach(s=>{o.addDecal({id:s.name,meshPath:s.modelUrl,skinInfo:DEFAULT_SKINS.REPORT_HALL.skinId}).then(()=>{o.setDecalTexture({id:s.name,buffer:"https://app-asset-1258211750.file.myqcloud.com/1/textures/T_Cussion.png"})})})}async tempGenNpc(){bossNames.forEach(async e=>{const o=await this.room.modelManager.findPoint(SKIN_ID,e);o.rotation.yaw=90,o.position.z=30,this.room.avatarManager.addAvatar({userId:"bossAvatar"+e,avatarPosition:o.position,avatarRotation:o.rotation,avatarId:"ross_test",nickname:e,priority:1,group:AvatarGroup.Npc})})}exit(){const e=Date.now();return this._exit().then(o=>(log.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin"}),o)).catch(o=>(log.infoAndReportMeasurement({tag:DEFAULT_SKINS.ISLAND.skinId,startTime:e,metric:"changeSkin",error:o}),Promise.reject(o)))}async _exit(e){var _e;if((_e=this.room.userAvatar)!=null&&_e.isBoss)return Promise.reject("boss can not leave");const o=DEFAULT_SKINS.ISLAND.skinId,s=await this.room.modelManager.findRoute(o,DEFAULT_SKINS.ISLAND.defaultStreamPath),{attitude:c,areaName:d,pathName:_,birthPointList:b}=s||{},{camera:k,player:j}=getRandomItem(b)||{};if(!c||!d||!_)return log.error("params error, attitude\u3001areaName or pathName is undefined"),Promise.reject("params error, attitude\u3001areaName or pathName is undefined");let $={skinId:o,mode:ChangeMode.Preview,landingType:LandingType.NewPoint,landingPoint:this.lastUserAvatarPose||j,landingCamera:this.lastCameraPose||k,renderType:RenderType.RotationVideo,attitude:c,areaName:d,pathName:_,person:Person.Third};return e&&($=Object.assign($,e)),this.room.actionsHandler.changeSkin($).then(et=>(this.afterLeave(),et))}afterLeave(){this.actived=!1}}var app="";function toast(a,i){const{onClick:e,duration:o}=i||{};return window.Toastify({text:a,duration:o||3e3,position:"center",backgroundColor:"#000",opacity:.8,borderRadius:"40px",onClick:function(){e&&e()}}).showToast()}var playerNextIcon="./assets/player-next.d19788fd.svg",playerListIcon="./assets/player-list.6d787580.svg",playerPauseIcon="./assets/player-pause.8f41c056.svg",playerPlayIcon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAADNSURBVHgB7dfhCcIwEAXgFyfQDbqJbuIIdgO7gSN0BEfoCm4QnKAjPFNKoSDaeKW5Q+6D+xfI4/0IF8A555wIyf0wsCgFq9P0HDWwZhZuEtNUsIKf1bCA33XqbXJZTHOGFuZrVdrkb2LxNinTstS7SbmY5oStcb0m964AgeEGrFeFEJ5Lh3bQc8g5pBWwSe09sBXKxTRHbI0yNxp9ZvoirQkD3qmx1GYEG1q7QMtCuI5G1y3d1ub4vvLrtzbH8dM0tXaFRbT87XTOuT/yAkqiIWU/MVlmAAAAAElFTkSuQmCC",personToggleIcon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACcAAAAlCAYAAADBa/A+AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJjSURBVHgBzZiLkdowEIbXqYBUEKWCOBXEJaQEdxA6gFQAHZgOkg48qQA6EKkAOvhPe14PurVkWwJ8980ID3gfv1dPTHQnANauta5d0MHXxrWK3guX3Lh2wjgsckVLI9WaQ0tL4hLWSKOipUioWs9fyqCgDFyyi7ukjKVrURSfKZFPlIgTVlKaMGbl/AwlkiyO0oVl++WIy2URcTXlUVEiOeK+UR4/KJEccf8ojzM9G3TblkUaNme25gpM3SFqegYuMK9Raz+B/GZnCrOhWHdVEl33HXA7CjE7dd9OCfNFSDyfJkmkPN0ulkzZTnVvrexjNJMinUGJ8Wo0yr7COJWyb0dsbVSgCLuMOG6hDo6Yrtyahr1SI14Azl9qYQZhYRykyqxy728i/jGRbwVGjPYIHLHRdeUeaTSIP+Q2YH/0n0CzDVR2g3i3z8UiMPgjAuvQIG1mdvk9DMYWhstMSxgm1k4tnkNLwzHscyn40zdyx+lCOfHaZujxnF2qryrXGy18Krkqg1IFMfQcDI3nvbK4k/rxF70Pa/X9FJutm94C6cejuRy9HJvA/bq/eUREILpTxKOxEje2j7/u4YUI4P7m2aMX3bNrv93APYiNcY2vX+g2Zoz4+b5Xr3GM/3LldnLxzugW5YaGY5p9vrMNeaWd2lv5SXWgIBh5eYOuC20kz3Bv9RznnNF4CDQitpKHWqkY/QNV6t5uJK6NClPBD3gcFlJxhMc2E9zHlxK5lZj+5OpfMhrKRUTyctMin9qL91PiTVYq6S2TBCyl8Z9k/m5oOFt7eObxbN/TRwC3f2Z/cOcr1xf1p6YtGKmk0gAAAABJRU5ErkJggg==",testUserIcon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAlLSURBVHgBlVdbbBzlFf7msjN73/Xaa3t3Y3vthFhxgMQNRSUIBUhFgQIyolWLWonw1D41biv6mvJU9amJqqqlLS1UQlARVC4BQZJSLk0AKxA75ILtONmYOPZ67d3Z3dmd2Z2ZnX5jhyiJUgirnJl45v//7//P+c53zgi4jp/runHeNtNGaNtoWVr84muNNk6boL0jCMLL17OmcB2AO2mjLXcubjqTqJkzqBt52K0KAiEZihJBSF4PSUhDQi/vmRzHP0N7lpvIfW1ggnqAvzaax+KuwMMITTQaFo58XMDh989iuVCH02picKgDD4xsQqIjANcxOKYOBbcjEd2a4/wnCf7MdQMT9HdNa2l0du4vCAeAULQTLzz/Kd48MA27GUCxrKNaLUNbynMBF+1tAYz+8n7c88B61GuLKFeWYRgqhjc8AVVp303wn38lMEH/vlT+YMfiwl4oooyOaA9efHUGf336MPKLBWT6+lHRdVSKS7CtJlotC7ygLRbFE796CA//YAtqxjxq+jIivggS8YehBjc8Q/DHL8cRrz6p2Ti1o1rbh2AohFgsg4WlFl59fRKyLCMea4NW1qATuGEaPH2D7nUhiiIMhuGpPx3E4nkLiVg/OpMZ+JQmSkv/gGlM7PDWviYwX/ClPuq0/otkvAdtiSzUcCf2v30GjuV6I+A4JoxKCSbdvOIqgVdB5D8ZjutiaamMvz21n4sGofpiaIkKKkYdpfwrcFvlUWKMXgHMB1nedjWbh/iHyhOE4ZPbUSzZmP1cJ0iLbm3AJ4krJostxk4io2Uu4J2YIxybcTUw9tFnmDmVo/cVNJsuOA22rqGp7fWgdl3MlEsnfsyxF7KO44MghyHKIchSEJpmYWY6j0KhsLJwi7FMtkeR7kwilYhycyIkGl/CMhv0iEOmuzi47yPYDRGWI8KW/DyYArs6D9uc8EBHLwfeUTenoNs1VJo1lOsVnDuXx9jhSUx+NkkXFlHUKmjy+V03D2CwpwupsIo0bagrzPSxmMOrsS6Wy5g4cpI8aMCyAgyBiDpkLJID+dLbHtZO79QSLyOWvfjTYu0kFquLsFwdraaDsfem8Yff70NhuQTbtuBaJm5Z14X77r6DICJZWyLrgce/fx8yMR+qdQNVLi4y3iFFwQ2DaYTaYvRGAyHVD8kLi+ogoPb4JTH+lswd3Fmu5ThJZ3gd+FUfxt48gwOvf4w6F/Pia5omYgEZW4c3IJlKYfzTE+hM9+L+3jYMbtyESFBBXpeQ6ljAR5PnIZEH0ydn0Tu4BpLIkPjJDZ8DUeJa9mmGqG/EA94kuMto90vQGzL2vzCGA/tOYebsBciqiN6+OE6fuoAAdzww0EvALH746I/hNAwo/hCZH6N0xvDElrvgCg727n0JH0+dwMTxcWx/ZCsC/ghkXwuQakyCFnlw1nP3Ng94c2HxNPRyHYcOnMJrrx0mk4uokyT3PDiMg29MgIdFOrSqN8FQFEoiuUKiRlUneJiZwAXNGjcRpMf8/L/N+Jpo2Q5CFBaVMbHJBMcuk4eGt1DWA44n0gIWzizilRcPohXw8wQqBIdxFSxCNVFlWjiCBIeDGwbTi2plUbXMag1NpooguNCrS2heqGDs6AToHLrfhsqwCWSExHwWOcZm3ltCxQOOe8A49v4n+PNv/oM7Rm7GBW7guGHh1q39uHE4ieX5FI58eB4fzixhJK9hyKgSrMhxZ1kY0mjpVYg+H3X7Aor6Iubml5HpVHHbt74BJaBysw3YZLYkRZlWvkt55N20qeMavvuL25guZWTWJRENuhjoD6O7O4RUKogNG9qhShLe+PchyqQB1zaQTPcjFkwiuWYQyY4+tHV2Yz8PEKRbW5TSWEcbBEmAbpVQbuZRN4toUPkEMebhah5w7qZvD+H8iQI0Tlh7U4IiQVcxpqEwXSXUcPd9a9CTUbGslaBrc7BsG5H2GKS4n0JB3bar+PTMaUzOLjN9WDj4fnmhSPdS8WBAr3+OgnYGBnUATtQDHvdc/a5d7N1c0N7Ftu9tRthpsqJQNjlFDgaQ7kvT5QOUBwEzYzXIgg27ztJnGUik10JNhlBZXsDTz/2LKiajXDMpGj7MnV2C5FagijZTrQKrpkOKxhBREx7whAf8cv+623ZuvOcT5tqqFm/Zvglu3YZgSrjl9mFMHp3BvQ+y47m1DyGSBVS4+kIOU2c+wHzuHD48xjJYI1t9KqIUjQYFZ3a6DL1E1kcj1HBurixT41NId2c94Hc84PFs301aRlsXd1GASibffGcaR946jsqMRgIlMTS4FT5tEAFfY6UgqCyZAl0KkdpsWWg/V2I1smByUxZPG4pGKUgKzk8ZWLvlRp66GxYVzFUHEVRjOa8vk3nRKJt7NvZs33XywkssBC4Munv97YOQG93o6/4O/IEuNBZOQGgwdSSZYxxESTx/LI1goh9r8yamlqYwV/eR4cpKqaxYIqaOLiK1Pgq/FEE4VEFfV8Y77bOXF4ndfYlhrTOxjnH102UiIoEBZCLb6L1OSp0PkZ7NkOMZ5iRTg/nYEhS+izBlYvjm3fdi+9bN6KKbRVGiUvlJKAMnTs4hd+w0qx2FJOKiMxLPYbURXAX2Ts3bkzd2PoJItAPdyjC6a33A8jSa+RNkJ6jXDQSSgyQTCRVOwE8FE9QQaiKLfiLFlFvPGuSiZdaZlnWYBM6XKvjk0PvcpI7hgTs8qCe/6DwvdSB8sFuVI3tuiDwE9XwIbqO6qq2VOdRL8ywVbOtYj8VQN2OVoObaJKOE7o52hD22tndhqCeGbMiBoZdXavfsfAGT07NIKtysHNpzecd5Rc/FF6PhQPbZxMCmlfRhQkKgDpdz4ys6XWMbY1k2XAqH1LZ2hVj0LUTFDzkQwYOPjOBHjz+GNanOFf0W6KpHf/IzdGdu8Hrs0SuwcI0fybabwrBz4dhBOPUS2xe6eeMDXDxGNjtseXyrk13mdPksWgZrdp2pE26DkhzCe28fxD+ffw6/3fNHpNLpPVeD/l/gi+A7eNtVnTuVLeeOohVbC196A2spM5CNlNf+eSdSmLueQrUoKLIS5jOSz3uu+LSLMd19rfW/6hMmy9sO2mOWqWcbbOBczvDc3WR761cVqpXPG8cNyCsxJ+s9wD203RdJi68NfNUmvA+2O2mbsPoBd/lHW472Ls37YBv/MsAvfv8D3d4+ov4lckgAAAAASUVORK5CYII=";const OPEN_API_URL="https://y.qq.com/m/unionlogin/dist/index.html?loginType=weixin",CALL_BACK_URL="https://music-api.xverse.cn/qqmusic_proxy/auth?redirect_uri=https://beta-h5.xverse.cn/music-room-h5/index.html",ENCRYPT_STRING={response_type:"code",callbackUrl:CALL_BACK_URL},oauthUrl=`${OPEN_API_URL}&appId=2000000303&encryptString=${encodeURIComponent(JSON.stringify(ENCRYPT_STRING))}&packageName=com.xverser.package&callbackUrl=${encodeURIComponent(CALL_BACK_URL)}&changeLogin=0&needNotifyErr=0`,hashUserId=a=>{let i=0,e,o;for(e=0;e<a.length;e++)o=a.charCodeAt(e),i=(i<<5)-i+o,i|=0;return Math.abs(i).toString().padEnd(12,"0")},getSingerAlbum=a=>axios.get(`https://music-api.xverse.cn/qqmusic_proxy/music_api?opi_cmd=fcg_music_custom_get_singer_album.fcg&singer_id=${a}&num_per_page=50`,{headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"},withCredentials:!0}).then(i=>(console.log("getSingerAlbum",i),i.data.ret===0?i.data:window.location.href=oauthUrl)),getAlbumDetail=a=>axios.get(`https://music-api.xverse.cn/qqmusic_proxy/music_api?opi_cmd=fcg_music_custom_get_album_detail.fcg&album_id=${a}&page=0&size=50`,{headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"},withCredentials:!0}).then(i=>i.data.ret===0?i.data:{album_desc:`\u5E74\u5EA6\u7279\u5927\u53F7\u671F\u5F85\uFF01
  12503. \u5F88Jay\u7684\u4E00\u5F20\u4E13\u8F91
  12504. \u5468\u6770\u4F26 Jay Chou \u54CE\u5466\uFF0C\u4E0D\u9519\u54E6
  12505. JAY\u8BED\u5F55\u91CC\u6700\u88AB\u6D41\u4F20\u6A21\u4EFF\u7684\u4E00\u53E5 \u6700\u5468\u6770\u4F26\u7684\u4E00\u5F20\u521B\u4F5C
  12506. \u4EE5\u5E7D\u9ED8\u62C9\u5F00\u5E8F\u5E55\uFF0C\u7ED9\u4F60\u300C\u978B\u5B50\u7279\u5927\u53F7\u300D\uFF01
  12507. \u5E7D\u9ED8\u662F\u632B\u6298\u4E2D\u4F18\u96C5\u7684\u793C\u8C8C \u7ED9\u4F60Jay\u7279\u5927\u53F7\u7684\u5E7D\u9ED8\uFF01
  12508. \u4ECA\u5E74\u5EA6\u6700\u7279\u5927\u53F7\u3001\u6700\u9AD8\u5EA6\u671F\u5F85\u7684\u4E13\u8F91--\u5468\u6770\u4F26\u300C\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6\u300D\uFF0C\u9996\u6CE2\u9686\u91CD\u767B\u573A\u7684\u300C\u978B\u5B50\u7279\u5927\u53F7\u300D\uFF0C\u4E3B\u89D2\u5C31\u662F\u9ED8\u7247\u559C\u5267\u5927\u5E08\u5353\u522B\u6797\uFF01\u7559\u7740\u4E00\u6487\u5C0F\u80E1\u5B50\uFF0C\u7A7F\u7740\u4E00\u4EF6\u7A84\u5C0F\u7684\u793C\u670D\u3001\u7279\u5927\u7684\u88E4\u5B50\u548C\u7279\u5927\u7684\u9ED1\u978B\u3001\u6234\u7740\u4E00\u9876\u5706\u9876\u786C\u793C\u5E3D\u3001\u624B\u6301\u4E00\u6839\u68D2\u68D2\u7CD6\u62D0\u6756\uFF0C\u51ED\u80A2\u4F53\u8BED\u8A00\u5C31\u80FD\u9017\u7B11\u89C2\u4F17\u7684\u5353\u522B\u6797\uFF0C\u582A\u79F0\u662F\u795E\u7EA7\u5E7D\u9ED8\uFF0C\u81F3\u4ECA\u65E0\u4EBA\u80FD\u8D85\u8D8A\uFF0C\u4E0D\u4EC5\u662F\u978B\u5B50\u7279\u5927\u53F7\uFF0C\u8FDE\u5E7D\u9ED8\u4E5F\u8981\u7279\u5927\u53F7\uFF01
  12509. \u5C01\u9762\u6982\u5FF5\u6765\u81EA\u4E8E\u7B2C1\u5F20\u4E13\u8F91\uFF0C\u5927\u73A9\u9519\u4F4D\u827A\u672F\u7684\u5E7D\u9ED8\u5353\u522B\u6797
  12510. \u65B0\u4E13\u8F91\u7684\u5C01\u9762\u6982\u5FF5\u6765\u81EA\u4E8E\u5468\u6770\u4F26\u81EA\u5DF1\u7684\u7B2C\u4E00\u5F20\u4E13\u8F91\u5C01\u9762\uFF0C\u6234\u7740\u8033\u673A\u7684\u5468\u6770\u4F26\u6574\u4E2A\u4EBA\u6F02\u6D6E\u5728\u8EBA\u6905\u4E0A\uFF0C\u8FD9\u5F20\u4E13\u8F91\u5468\u6770\u4F26\u5219\u5316\u8EAB\u4E3A\u65F6\u5C1A\u5353\u522B\u6797\uFF0C\u8EAB\u7A7F\u6761\u6587\u7A84\u7248\u897F\u88C5\u3001\u6F02\u6D6E\u5728\u6C99\u53D1\u4E0A\uFF0C\u800C\u5F53\u5E74\u5C4B\u5B50\u91CC\u53EA\u6709\u4E00\u53EA\u8033\u673A\u548C\u7B14\u7535\uFF0C\u73B0\u5728\u5DF2\u7ECF\u53D8\u6210\u4E86\u6EE1\u5C4B\u5B50\u7684\u4E50\u5668\uFF01
  12511. \u66F4\u7279\u522B\u7684\u662F\uFF0C\u5C01\u9762\u4E0A\u9664\u4E86\u6F02\u6D6E\u5728\u6905\u5B50\u4E0A\u7684\u5468\u6770\u4F26\u4EE5\u5916\uFF0C\u7ADF\u7136\u5728\u753B\u9762\u6B63\u4E2D\u95F4\u51FA\u73B0\u4E86\u5468\u6770\u4F26\u7684\u5927\u8138\uFF01\u8FD9\u4E2A\u8138\u5E76\u4E0D\u662F\u7528\u8BA1\u7B97\u673A\u8F6F\u4EF6\u8FED\u4E0A\u53BB\u7684\u6548\u679C\uFF0C\u800C\u662F\u8FD0\u7528\u3010\u9519\u4F4D\u827A\u672F\u3011\uFF0C\u5C06\u573A\u666F\u6446\u8BBE\u4EE5\u9519\u4F4D\u827A\u672F\u7684\u65B9\u6CD5\uFF0C\u4EE52D\u753B\u9762\u521B\u9020\u51FA3D\u5E7D\u9ED8\u611F\uFF0C\u5728\u540C\u4E00\u4E2A\u753B\u9762\u540C\u65F6\u62CD\u51FA\u53E6\u5916\u4E00\u4E2A\u5468\u6770\u4F26\u7684\u7ACB\u4F53\u5927\u8138!!
  12512. \u4E0D\u65AD\u8FDB\u5316\u7684\u5468\u6770\u4F26\uFF0C\u4E0D\u65AD\u5730\u7ED9\u5927\u5BB6\u8D85\u4E4E\u60F3\u8C61\u7684\u97F3\u4E50\uFF01
  12513. \u5468\u6770\u4F26\u7684\u97F3\u4E50\u603B\u662F\u5E26\u7ED9\u4EBA\u5404\u79CD\u60CA\u5947\u3001\u4F53\u4F1A\u4E0E\u611F\u53D7\uFF0C\u5F71\u54CD\u65E0\u8FDC\u5F17\u5C4A\uFF1B\u8FD9\u6B21\u4ECE\u4E13\u8F91\u540D\u53D6\u81EA\u4E8E\u5468\u6770\u4F26\u7684\u53E3\u5934\u7985\u300C\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6\u300D\uFF0C\u5C31\u80FD\u9886\u7565\u5230\u5E7D\u9ED8\u521B\u610F\u662F\u6B64\u6B21\u7684\u4E3B\u8F74\uFF1B\u6B63\u5982\u540C\u300C\u978B\u5B50\u7279\u5927\u53F7\u300D\u7684\u6B4C\u8BCD\u6240\u5199\uFF1A
  12514. \u522B\u4EC0\u4E48\u4F60\u90FD\u60F3\u8981\uFF0C\u5FEB\u4E50\u5374\u627E\u4E0D\u5230\uFF0C\u5E7D\u9ED8\u632B\u6298\u4E2D\u4F18\u96C5\u7684\u793C\u8C8C
  12515. \u559C\u5267\u8981\u767E\u5206\u4E4B\u767E\u7684\u6295\u5165\uFF0C\u4E0D\u7BA1\u6F14\u52A8\u7269\u6216\u690D\u7269\uFF0C\u4F60\u4E00\u5B9A\u90FD\u8981\u6F14\u7684\u8BA9\u4EBA\u5BB6\u7FA1\u6155
  12516. \u8BA9\u4F60\u5F00\u5FC3\u5176\u5B9E\u8981\u4E00\u70B9\u5934\u8111
  12517. \u82E5\u751F\u6D3B\u9700\u8981\u5FAE\u7B11\u8BF7\u770B\u7740\u6211\u5C31\u597D\uFF0C\u5C06\u538B\u529B\u4E00\u80A1\u8111\u5168\u90E8\u91CA\u653E\u6389
  12518. \u5353\u522B\u6797\u7528\u559C\u5267\u7535\u5F71\u5E7D\u9ED8\u751F\u547D\u7684\u60B2\u6B22\uFF1B\u5468\u6770\u4F26\u7528\u4ED6\u7684\u97F3\u4E50\u5C06\u4E16\u754C\u8BD9\u8C10\u6210\u559C\u5267\uFF01
  12519. \u4E16\u754C\u518D\u95F7\uFF0C\u751F\u6D3B\u518D\u65E0\u804A\uFF0C\u5E78\u597D\u6211\u4EEC\u8FD8\u6709\u5468\u6770\u4F26\uFF01
  12520. \u9996\u6CE2\u5E7D\u9ED8\u4E3B\u6253
  12521. \u978B\u5B50\u7279\u5927\u53F7
  12522. \u590D\u53E4\u66F2\u98CE+\u563B\u54C8\u9976\u820C\u5143\u7D20+\u5353\u522B\u6797\u5F0F\u5E7D\u9ED8
  12523. \u8BCD\uFF1A\u65B9\u6587\u5C71 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC OS\uFF1A\u5DE8\u70AE\u3001\u5468\u6770\u4F26
  12524. \u300C\u978B\u5B50\u7279\u5927\u53F7\u300D\u662F\u7531\u5468\u6770\u4F26\u4F5C\u66F2\u3001\u65B9\u6587\u5C71\u4F5C\u8BCD\uFF0C\u4E24\u4EBA\u5728\u8BA8\u8BBA\u8FD9\u5F20\u65B0\u4E13\u8F91\u6B4C\u66F2\u65F6\uFF0C\u60F3\u8981\u5199\u4E00\u9996\u5E7D\u9ED8\u7684\u6B4C\u66F2\uFF0C\u8BA9\u5927\u5BB6\u53EF\u4EE5\u5728\u751F\u6D3B\u4E2D\u591A\u70B9\u5F00\u5FC3\u7684\u5143\u7D20\uFF1B\u800C\u5353\u522B\u6797\u662F\u559C\u5267\u754C\u7684\u5B97\u5E08\uFF0C\u4ED6\u7684\u5F88\u591A\u7279\u8272\u90FD\u5177\u6709\u300E\u7B26\u53F7\u6027\u300F\uFF0C\u50CF\u662F\u5BBD\u5927\u7684\u978B\u5B50\u3001\u5F88\u7A84\u7684\u897F\u88C5\u3001\u624B\u6756\u3001\u5E3D\u5B50\u2026\uFF0C\u8FD9\u4E9B\u90FD\u53D8\u6210\u4E86\u4ED6\u5E7D\u9ED8\u7684\u6807\u5FD7\uFF1B\u5C31\u50CF\u300E\u53CC\u622A\u68CD\u300F\u4E4B\u4E8E\u674E\u5C0F\u9F99\uFF0C\u300C\u7279\u5927\u53F7\u7684\u978B\u5B50\u300D\u5C31\u662F\u5353\u522B\u6797\u7684\u4E2A\u4EBA\u98CE\u683C\u4E4B\u4E00\uFF0C\u5353\u522B\u6797\u672C\u8EAB\u7684\u89C6\u89C9\u5143\u7D20\u5F88\u4E30\u5BCC\uFF0C\u65B9\u6587\u5C71\u5199\u8FD9\u9996\u6B4C\u65F6\u628A\u8FD9\u4E9B\u89C6\u89C9\u5143\u7D20\u653E\u8FDB\u6B4C\u8BCD\u91CC\uFF0C\u975E\u5E38\u4E30\u5BCC\u5E7D\u9ED8\uFF0C\u5E0C\u671B\u8FD9\u9996\u6B4C\u5353\u522B\u6797\u5F0F\u5E7D\u9ED8\u7684\u6B4C\u66F2\uFF0C\u53EF\u4EE5\u8BA9\u5927\u5BB6\u751F\u6D3B\u4E0D\u90A3\u4E48\u7D27\u5F20\uFF0C\u5F00\u5FC3\u4E00\u70B9\u3002
  12525. \u5728\u8FD9\u5F20\u65B0\u4E13\u8F91\u91CC\uFF0C\u5468\u6770\u4F26\u591A\u7528\u4F4E\u6C89\u55D3\u97F3\u8868\u73B0\uFF0C\u524D\u6240\u672A\u6709\u5448\u73B0\u65B0\u7684\u5531\u8154\uFF0C\u800C\u8FD9\u9996\u590D\u53E4\u66F2\u98CE\u52A0\u563B\u54C8\u9976\u820C\u5143\u7D20\u7684\u300C\u978B\u5B50\u7279\u5927\u53F7\u300D\uFF0C\u66F4\u662F\u4E00\u9996\u5E7D\u9ED8\u8BD9\u8C10\u7684\u563B\u54C8\u9976\u820C\u6B4C\u66F2\uFF0C\u6B4C\u8BCD\u6709\u5353\u522B\u6797\u5F0F\u7684\u5E7D\u9ED8\uFF0C\u800C\u5468\u6770\u4F26\u66F4\u4EE5\u4E00\u79CD\u8BD9\u8C10\u3001\u987D\u7AE5\u7684\u53E3\u543B\u6F14\u5531\uFF0C\u58F0\u97F3\u8868\u60C5\u5343\u53D8\u4E07\u5316\uFF0C\u548C\u58F0\u7684\u5B89\u6392\u7EC6\u8282\u4E4B\u5904\u66F4\u4EE4\u4EBA\u60CA\u8273\u839E\u5C14\u4E00\u7B11\uFF1B\u5468\u6770\u4F26\u7684\u597D\u53CB\u3001\u540C\u65F6\u4E5F\u662F\u6770\u4F26\u6F14\u5531\u4F1A\u603B\u76D1--\u5DE8\u70AE\uFF0C\u5728\u5468\u6770\u4F26\u7684\u6BCF\u5F20\u4E13\u8F91\u4E2D\u90FD\u4F1A\u6709\u4E00\u9996\u6B4C\u52A0\u5165O.S.\uFF0C\u8FD9\u5DF2\u7ECF\u53D8\u6210\u4E86\u4E00\u4E2A\u60EF\u4F8B\uFF0C\u8FD9\u9996\u300C\u978B\u5B50\u7279\u5927\u53F7\u300D\uFF0C\u5C31\u6709\u5DE8\u70AE\u7684O.S.\u4F5C\u4E3A\u5F00\u573A\uFF0C\u5468\u6770\u4F26\u8BA4\u4E3A\u5DE8\u70AE\u5F88\u6709\u7279\u8272\u7684\u58F0\u97F3\u52A0\u5165\u6B4C\u66F2O.S.\u4E2D\uFF0C\u53EF\u4EE5\u8BA9\u8FD9\u9996\u5E7D\u9ED8\u7684\u6B4C\u66F2\u66F4\u6709\u8DA3\u3002\u7279\u522B\u7684\u662F\uFF0C\u5DE8\u70AE\u7684O.S.\u5C31\u5982\u540C\u6B4C\u66F2\u4E2D\u4E0E\u5468\u8463\u7684\u7535\u8BDD\u5BF9\u8BDD\u4E00\u6837\uFF0C\u5DE8\u70AE\u5C31\u662F\u6253\u7535\u8BDD\u8FDB\u5F55\u97F3\u5BA4\u5F55\u7684\uFF0C\u975E\u5E38\u5177\u6709\u4E34\u573A\u611F\u4E0E\u72EC\u7279\u7684\u8DA3\u5473\u3002\u800C\u8FD9\u9996\u6B4C\u7684MV\u66F4\u7528\u4E86\u8BB8\u591A\u9519\u4F4D\u7684\u6897\uFF0C\u91CD\u65B0\u8BE0\u91CA\uFF0C\u9ED1\u767D\u5230\u5F69\u8272\u5F62\u6210\u5E7D\u9ED8\u7684\u5BF9\u6BD4\uFF1B\u4ECE\u97F3\u4E50\u51FA\u53D1\uFF0C\u5C06\u89C6\u89C9\u7B26\u53F7\u8F6C\u5316\u6210\u6B4C\u8BCD(\u6587\u5B57)\u3001\u518D\u5C06\u6B4C\u66F2\u8F6C\u5316\u6210\u89C6\u89C9\uFF0C\u4E0D\u65AD\u5730\u6269\u5927\u60F3\u8C61\uFF0C\u8FD9\u5C31\u662F\u5468\u6770\u4F26\u7684\u7279\u5927\u53F7\u9B45\u529B\uFF01
  12526. \u7B97\u4EC0\u4E48\u7537\u4EBA
  12527. \u4E00\u79CD\u53EA\u6709\u81EA\u5DF1\u4E0E\u81EA\u5DF1\u624D\u61C2\u7684\u544A\u89E3
  12528. \u5468\u6770\u4F26\u643A\u624B\u6797\u4F9D\u6668MV\u800D\u6D6A\u6F2B \u300C\u7B97\u4EC0\u4E48\u7537\u4EBA\u300D\u8981\u7537\u751F\u52C7\u6562\u8FFD\u7231
  12529. \u5230\u7F57\u5BC6\u6B27\u4E0E\u6731\u4E3D\u53F6\u7684\u6545\u4E61\u53D6\u666F MV\u4E32\u8054\u610F\u5927\u5229Verona\u4E0E\u53F0\u5317\u7684\u6D6A\u6F2B
  12530. \u8BCD\uFF1A\u5468\u6770\u4F26 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC \u5409\u4ED6\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC
  12531. \u8FD9\u9996\u8D85\u6162\u677F\u6292\u60C5\u6B4C\uFF0C\u662FJay\u5F0F\u60C5\u6B4C\u91CC\u96BE\u5F97\u5448\u73B0\u51FA\u6DF1\u6C89\u7684\u60B2\u6005\uFF0C\u66F4\u662F\u5468\u6770\u4F26\u9996\u6B21\u4EE5\u4F4E\u6C89\u5531\u8154\uFF0C\u6F14\u5531\u7537\u4EBA\u5185\u5FC3\u7684\u6781\u5EA6\u75BC\u75DB\uFF0C\u81EA\u5DF1\u9A82\u81EA\u5DF1\u5BF9\u4E8E\u7231\u60C5\u4E0D\u80FD\u597D\u597D\u628A\u63E1\u3001\u5C06\u5FC3\u7231\u7684\u4EBA\u62F1\u624B\u8BA9\u4EBA\u7684\u5FC3\u60C5\uFF1B\u524D\u594F\u4EE5\u94A2\u7434\u7F13\u6B65\u6C89\u91CD\u5F00\u573A\uFF0C\u63A5\u7740\u5F26\u4E50\u3001\u9F13\u63A5\u7EED\u52A0\u5165\uFF0C\u50CF\u955C\u5934\u4E00\u6B65\u4E00\u6B65\u63A8\u8FDB\uFF0C\u5E26\u9886\u7740\u89C2\u8005\uFF0C\u770B\u89C1\u4E00\u4E2A\u7537\u4EBA\u9893\u5750\u5728\u660F\u6697\u7684\u7A7A\u95F4\u91CC\uFF0C\u72EC\u81EA\u5FCD\u53D7\u7740\u5931\u53BB\u7231\u60C5\u7684\u75BC\u75DB\uFF1B\u800C\u5468\u6770\u4F26\u81EA\u5DF1\u5199\u7684\u6B4C\u8BCD\uFF0C\u662F\u4EE5\u81EA\u5DF1\u4E0E\u81EA\u5DF1\u7684\u5185\u5FC3\u5BF9\u8BDD\u65B9\u5F0F\uFF0C\u81EA\u5DF1\u9A82\u81EA\u5DF1\u5BF9\u4E8E\u7231\u60C5\u4E0D\u80FD\u597D\u597D\u628A\u63E1\uFF0C\u62F1\u624B\u8BA9\u4EBA\uFF1B
  12532. \u4F60\u7B97\u4EC0\u4E48\u7537\u4EBA/\u7B97\u4EC0\u4E48\u7537\u4EBA/\u773C\u7741\u7741\u770B\u5979\u8D70\u5374\u4E0D\u95FB\u4E0D\u95EE/
  12533. \u662F\u6709\u591A\u5929\u771F/\u5C31\u522B\u518D\u786C\u6491/\u671F\u5F85\u4F60\u633D\u56DE\u4F60\u5374\u62F1\u624B\u8BA9\u4EBA
  12534. \u8BB8\u591A\u8BDD\u5728\u7231\u60C5\u9762\u524D\u8BF4\u4E0D\u51FA\u53E3\uFF0C\u633D\u7559\u7684\u8BDD\u66F4\u662F\u6897\u5728\u5589\u5934\uFF0C\u5C24\u5176\u662F\u7537\u4EBA\u7684\u310D\u3127\u3125\uFF0C\u60F3\u8981\u5BF9\u65B9\u5E78\u798F\u800C\u653E\u624B\uFF0C\u4EE5\u4E3A\u8FD9\u5C31\u662F\u6210\u5168\uFF1B\u5374\u53C8\u5728\u5185\u5FC3\u5492\u9A82\u81EA\u5DF1\u7B97\u4EC0\u4E48\u7537\u4EBA\uFF0C\u8FD9\u4E48\u8F7B\u6613\u7684\u5C31\u5C06\u81EA\u5DF1\u7684\u5E78\u798F\u62F1\u624B\u8BA9\u4EBA\uFF1B\u77DB\u76FE\u3001\u7EA0\u7ED3\u3001\u61CA\u6094\u3001\u53CD\u590D\u649E\u51FB\u5185\u5FC3\u8106\u5F31\uFF1B\u5468\u6770\u4F26\u4EE5\u51E0\u53E5\u7B80\u5355\u7684\u573A\u666F\u63CF\u8FF0\u7A7F\u63D2\u5185\u5FC3\u72EC\u767D\uFF0C\u5C31\u5C06\u8FD9\u590D\u6742\u7684\u7537\u4EBA\u60C5\u7EEA\u72EC\u5E55\u620F\u8868\u73B0\u5F97\u6DCB\u6F13\u5C3D\u81F4\uFF0C\u8FD9\u662F\u4E00\u79CD\u53EA\u6709\u81EA\u5DF1\u4E0E\u81EA\u5DF1\u624D\u61C2\u7684\u544A\u89E3\u3002
  12535. \u4E13\u8F91\u5C01\u9762\u4EE5\u300C\u98D8\u6D6E\u300D\u6982\u5FF5\u547C\u5E94\u9996\u5F20\u4E13\u8F91\uFF0C\u610F\u5473\u5468\u6770\u4F26\u97F3\u4E50\u5386\u7A0B\u7684\u300C\u8FDB\u5316\u300D\u9636\u6BB5\u5373\u5C06\u5C55\u5F00\uFF0C\u300C\u7B97\u4EC0\u4E48\u7537\u4EBA\u300DMV\u66F4\u9080\u8BF7\u4E86\u62CD\u8FC7\u300C\u53CC\u622A\u68CD\u300DMV\u7684\u5973\u4E3B\u89D2\u6797\u4F9D\u6668\u518D\u5EA6\u5408\u4F5C\u6F14\u51FA\uFF01\u4E24\u4EBA\u4E0D\u4EC5\u5728MV\u4E2D\u6709\u7CBE\u5F69\u7684\u5BF9\u624B\u620F\uFF0C\u7A7A\u6863\u65F6\u66F4\u5F00\u5FC3\u8BDD\u5F53\u5E74\u3002\u800C\u5408\u4F5C\u62CD\u6444\u300C\u7B97\u4EC0\u4E48\u7537\u4EBA\u300DMV\uFF0C\u5728\u6797\u4F9D\u6668\u773C\u4E2D\uFF0C\u6770\u4F26\u7B97\u662F\u4EC0\u4E48\u6837\u7684\u7537\u4EBA\u5462\uFF1F\u5979\u8BF4\uFF1A\u300C\u5468\u6770\u4F26\u662F\u4F01\u56FE\u5FC3\u5F88\u5F3A\u3001\u5F88\u6709\u80FD\u529B\u7684\u4EBA\u3002\u300D\u4E3A\u4E86\u6B4C\u66F2\u7684\u610F\u5883\uFF0C\u5468\u6770\u4F26\u65E9\u5728\u4ECA\u5E742\u6708\u5C31\u8FDC\u8D74\u610F\u5927\u5229\u62CD\u6444\u5BF9\u5634\u753B\u9762\uFF0C\u8BA9\u8FD9\u652F\u300C\u7B97\u4EC0\u4E48\u7537\u4EBA\u300DMV\u66F4\u52A0\u7CBE\u5F69\u53EF\u671F\uFF01
  12536. \u5468\u6770\u4F26\u4E0E\u6797\u4F9D\u6668\u5728MV\u91CC\u9970\u6F14\u4E00\u5BF9\u4E00\u8D77\u5728\u5496\u5561\u5385\u5DE5\u4F5C\u7684\u60C5\u4FA3\uFF0C\u4E24\u4EBA\u751C\u871C\u6F14\u51FA\u8BB8\u591A\u751C\u871C\u7CBE\u5F69\u7684\u5BF9\u624B\u620F\uFF0C\u4F8B\u5982\u5468\u6770\u4F26\u9694\u7740\u73BB\u7483\u7A97\u5BF9\u7740\u6797\u4F9D\u6668\u753B\u7231\u5FC3\uFF0C\u5C31\u662F\u6B4C\u8BCD\u7684\u5199\u7167\uFF0C\u300C\u6211\u7684\u6E29\u6696\u3001\u4F60\u7684\u51B7\u6F20\uFF0C\u8BA9\u7231\u8D77\u96FE\u4E86\u3002\u5982\u679C\u7231\u5FC3\u753B\u5728\u8D77\u96FE\u7684\u7A97\uFF0C\u662F\u6A21\u7CCA\uFF1F\u8FD8\u662F\u66F4\u6E05\u695A\uFF1F\u300D\u6770\u4F26\u7684\u6D6A\u6F2B\u900F\u8FC7\u6587\u5B57\u3001\u5F71\u50CF\u4E0E\u97F3\u4E50\uFF0C\u5F7B\u5E95\u878D\u5316\u6B4C\u8FF7\u7684\u5FC3\u3002MV\u4E2D\u5C0F\u4E24\u53E3\u5F88\u751C\u871C\uFF0C\u4E0D\u7BA1\u662F\u4E00\u8D77\u6175\u61D2\u5730\u5728\u6C99\u53D1\u770B\u7535\u89C6\uFF0C\u8FD8\u662F\u5728\u53A8\u623F\u6253\u60C5\u9A82\u4FCF\uFF0C\u4E00\u8D77\u73A9\u684C\u5F0F\u8DB3\u7403\uFF0C\u90FD\u653E\u95EA\u5230\u4EE4\u4EBA\u7741\u4E0D\u5F00\u773C\uFF01\u7136\u800C\u7537\u4E3B\u89D2\u5468\u6770\u4F26\u5374\u5E38\u5FFD\u7565\u6797\u4F9D\u6668\u7684\u7528\u5FC3\uFF0C\u6797\u4F9D\u6668\u8D39\u5FC3\u5728\u5496\u5561\u62C9\u82B1\u4E0A\u753B\u4E00\u4E2A\u6770\u4F26\u7684\u8138\u60F3\u7ED9\u4ED6\u60CA\u559C\uFF0C\u5374\u88AB\u4ED6\u4E00\u53E3\u559D\u6389\u2026\uFF0C\u5F53\u5973\u4E3B\u89D2\u5DF2\u7ECF\u6E10\u6E10\u5FC3\u7070\u610F\u51B7\uFF0C\u4ED6\u8FD8\u6C89\u6D78\u5728\u97F3\u4E50\u521B\u4F5C\u4E16\u754C\u91CC\u800C\u4E0D\u81EA\u77E5\u3002\u540E\u6765\u6797\u4F9D\u6668\u751F\u6D3B\u4E2D\u51FA\u73B0\u4E86\u4E00\u4E2A\u8D34\u5FC3\u7684Darren\u90B1\u51EF\u4F1F\uFF0C\u5728\u5973\u4E3B\u89D2\u88ABDarren\u8FFD\u8D70\u4E86\u4E4B\u540E\uFF0C\u7537\u4E3B\u89D2\u53EA\u80FD\u5F92\u7559\u61CA\u6094\uFF0C\u800C\u5F53\u521D\u4E24\u4EBA\u5728\u610F\u5927\u5229Verona\uFF08\u7EF4\u6D1B\u90A3\uFF09\u7684\u300C\u7231\u60C5\u9501\u5899\u300D\u4E0A\u7684\u9501\uFF0C\u5728\u604B\u60C5\u7ED3\u675F\u540E\uFF0C\u6770\u4F26\u4E5F\u53EA\u80FD\u9EEF\u7136\u72EC\u81EA\u62C6\u4E0B\u3002
  12537. \u4E3A\u4E86\u8868\u73B0\u6B4C\u66F2\u7684\u610F\u5883\uFF0C\u5468\u6770\u4F26\u65E9\u5728\u4ECA\u5E742\u6708\u5C31\u8FDC\u8D74\u610F\u5927\u5229\u7684Verona\uFF08\u7EF4\u6D1B\u90A3\uFF09\u4EE5\u53CA\u4F5B\u7F57\u4F26\u8428\u62CD\u6444MV\u5BF9\u5634\uFF0CVerona\u662F\u838E\u58EB\u6BD4\u4E9A\u540D\u4F5C\u300C\u7F57\u5BC6\u6B27\u4E0E\u6731\u4E3D\u53F6\u300D\u7684\u6545\u4E61\uFF0C\u7F57\u5BC6\u6B27\u4E0D\u987E\u4E00\u5207\u963B\u788D\u8FFD\u6C42\u7231\u60C5\uFF0C\u6B63\u662F\u6B4C\u66F2\u91CC\u7537\u4EBA\u7F3A\u4E4F\u7684\u52C7\u6C14\uFF0C\u6770\u4F26\u9009\u62E9\u6B64\u5730\u62CD\u6444\u66F4\u663E\u5F97\u72EC\u5177\u610F\u4E49\uFF1B\u800C\u5F53\u5730\u89C2\u5149\u666F\u70B9\u4E4B\u4E00\u7684\u300C\u7231\u60C5\u9501\u5899\u300D\u4E5F\u5165\u955C\u5176\u4E2D\uFF0C\u56E0\u5E94MV\u5267\u60C5\uFF0C\u6770\u4F26\u62CD\u4E86\u5728\u5899\u4E0A\u89E3\u5F00\u9501\u7684\u753B\u9762\uFF0C\u65E5\u524D\u5728\u53F0\u5317\u62CD\u6444MV\u65F6\uFF0C\u4E0D\u5FD8\u628A\u5F53\u65F6\u7684\u9501\u5E26\u5165\u5267\u60C5\u4E2D\u3002\u6B64\u5916\u6770\u4F26\u4E5F\u628A\u610F\u5927\u5229Verona\u7684\u6D6A\u6F2B\u5E26\u56DE\u53F0\u5317\uFF0C\u6797\u4F9D\u6668\u5728\u53F0\u5317\u62CD\u6444MV\u65F6\uFF0C\u7AD9\u5728\u9633\u53F0\u4E0A\u7684\u4E00\u5E55\u5C31\u5F77\u4F5B\u662F\u7B49\u5F85\u7F57\u5BC6\u6B27\u7684\u6731\u4E3D\u53F6\u3002\u867D\u7136\u65F6\u96949\u4E2A\u6708\uFF0C\u6770\u4F26\u4F9D\u7136\u6CA1\u5FD8\u8BB0\u8981\u8BA9\u4E24\u5730\u62CD\u6444\u7684MV\u5408\u7406\u4E32\u8FDE\u5267\u60C5\uFF0C\u5468\u5BFC\u7528\u5FC3\u5904\u5904\u53EF\u89C1\uFF01
  12538. \u6770\u4F26\u8BF4\uFF1A\u300C\u5F88\u591A\u7537\u4EBA\u90FD\u662F\u4E0D\u6562\u53BB\u8FFD\u6C42\u81EA\u5DF1\u7684\u5E78\u798F\uFF0C\u6216\u662F\u5185\u5FC3\u592A\u51B7\u9759\u4E86\u3002\u5F88\u591A\u7537\u4EBA\u5176\u5B9E\u5185\u5FC3\u4E16\u754C\u662F\u590D\u6742\u7684\uFF0C\u8FD9\u9996\u6B4C\u5C31\u662F\u544A\u8BC9\u5927\u5BB6\u8981\u52C7\u6562\u8FFD\u7231\uFF01\u6BCF\u4E2A\u4EBA\u90FD\u6709\u4E00\u6BB5\u5F88\u68D2\u7684\u521D\u604B\u56DE\u5FC6\u6216\u8FC7\u53BB\uFF0C\u6211\u89C9\u5F97\u5C31\u8981\u597D\u597D\u73CD\u60DC\uFF01\u300D
  12539. 1. \u9633\u660E\u5C71
  12540. \u8BCD\uFF1A\u65B9\u6587\u5C71 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u6797\u8FC8\u53EF
  12541. \u8FD9\u9996\u563B\u54C8\u52A0\u590D\u53E4\u98CE\u7684\u821E\u66F2\uFF0C\u7075\u611F\u6765\u81EA\u4EE5\u524D80\u5E74\u4EE3\u7684\u6821\u56ED\u65F6\u4EE3\uFF0C\u7537\u5973\u8054\u8C0A\u6700\u6D41\u884C\u7684\u300C\u62BD\u94A5\u5319\u6D3B\u52A8\u300D\uFF0C\u5373\u7537\u751F\u4EEC\u62FF\u51FA\u81EA\u5DF1\u7684\u6469\u6258\u8F66\u94A5\u5319\uFF0C\u6DF7\u5728\u4E00\u8D77\u8BA9\u5973\u751F\u62BD\uFF0C\u62BD\u5230\u8C01\u7684\u94A5\u5319\u5C31\u5750\u8C01\u7684\u8F66\uFF0C\u501F\u7740\u9A91\u8F66\u515C\u98CE\u57F9\u517B\u611F\u60C5\uFF0C\u800C\u9633\u660E\u5C71\u7EDD\u5BF9\u662F\u5F53\u5E74\u515C\u98CE\u7684\u6700\u4F73\u5723\u5730\uFF1B\u4EE5\u6770\u4F26\u5F0F\u7684\u5E7D\u9ED8\u563B\u54C8\u66F2\u98CE\u542C\u5230\u65CB\u5F8B\u5C31\u4EE4\u4EBA\u5FCD\u4FCA\u4E0D\u4F4F\u4E86\uFF0C\u518D\u52A0\u4E0A\u65B9\u6587\u5C71\u6D3B\u7075\u6D3B\u73B0\u7684\u6B4C\u8BCD\uFF0C\u8868\u73B0\u51FA\u7537\u751F\u660E\u660E\u60F3\u628A\u59B9\u5374\u5047\u9B3C\u5047\u602A\u88C5\u6B63\u7ECF\uFF1B\u8FDE\u8BF4\u8BDD\u90FD\u8981\u6587\u9752\u9020\u53E5\uFF0C\u539F\u6765\u6587\u9752\u4E0D\u53EA\u73B0\u5728\u6D41\u884C\uFF0C\u5728\u5F53\u65F6\u7684\u5927\u5B66\u751F\u90FD\u7231\u6765\u8FD9\u5957\u88C5\u66A7\u6627\uFF1A
  12542. Everybody\u8DDF\u7740\u6211 \u8C01\u8BF4\u591C\u5E97\u624D\u6709Party Hey Hey
  12543. \u628A\u4F60\u7684\u624B\u653E\u80F8\u53E3 \u6211\u662F\u8BF4\u653E\u6211\u7684\u80F8\u53E3 Hey Hey
  12544. \u6211\u559C\u6B22\u7231\u7B11\u7684\u4F60 \u4F46\u662F\u8FD9\u4E00\u53E5\u592A\u4FD7\u6C14 Hey Hey
  12545. \u6539\u6362\u6587\u9752\u7684\u9020\u53E5 \u4F60\u4E00\u62B9\u5FAE\u7B11\u5982\u8309\u8389
  12546. \u5468\u6770\u4F26\u4EE5\u591A\u53D8\u3001\u5145\u6EE1\u6F14\u6280\u7684\u5531\u8154\uFF0C\u8868\u73B0\u51FA\u6B4C\u8BCD\u91CC\u7684\u5C0F\u5FC3\u673A\uFF0C\u4EE5\u53CA\u7537\u5973\u751F\u7684\u5FAE\u5999\u4E92\u52A8\uFF0C\u4E0D\u4EC5\u5145\u6EE1\u4E86\u5355\u5143\u683C\u6F2B\u753B\u7684\u8DA3\u5473\u611F\u66F4\u4EE4\u4EBA\u4F1A\u5FC3\u4E00\u7B11\uFF0C\u662F\u6240\u6709\u7537\u751F\u5973\u751F\u7EDD\u5BF9\u8981\u542C\u7684\u628A\u59B9\u6B4C\uFF01\u5F55\u97F3\u65F6\uFF0C\u5468\u6770\u4F26\u66F4\u5316\u8EAB\u4E3ADJ\u81EA\u5DF1\u5237\u789F\uFF1B\u800CMV\u573A\u666F\u662F80\u5E74\u4EE3\u590D\u53E4Disco\u821E\u5385\uFF0C\u5468\u6770\u4F26\u9996\u6B21\u5C1D\u8BD5Waacking\u7ED3\u5408Locking\uFF0C\u96BE\u5F97\u4E00\u89C1\u7684\u753B\u9762\u7CBE\u5F69\u53EF\u671F\uFF01
  12547. 2. \u7A83\u7231
  12548. \u8BCD\uFF1A\u9EC4\u4FCA\u90CE \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC
  12549. \u5145\u6EE1\u4E86\u5F02\u56FD\u60C5\u8C03\u7684\u63A2\u6208\u66F2\u98CE\uFF0C\u5728\u563B\u54C8\u91CC\u52A0\u5165\u4F5B\u6717\u660E\u54E5\u8C03\u9999\u7684\u300C\u7A83\u7231\u300D\uFF0C\u662F\u5468\u6770\u4F26\u591A\u53D8\u66F2\u98CE\u91CC\u603B\u662F\u4EE4\u4EBA\u671F\u5F85\u7684\u4E00\u79CD\uFF1B\u795E\u79D8\u7684\u524D\u594F\u6697\u793A\u7740\u7A83\u7231\u602A\u76D7\u7684\u811A\u6B65\u58F0\u3001\u53C8\u6216\u8005\u50CF\u662F\u7231\u60C5\u7684\u5FC3\u8DF3\u58F0\uFF1B\u8282\u594F\u6E10\u6E10\u903C\u8FD1\uFF0C\u5F77\u4F5B\u7231\u60C5\u6162\u6162\u9760\u8FD1\uFF0C\u9B3C\u624D\u9EC4\u4FCA\u90CE\u64C5\u957F\u7528\u534E\u4E3D\u72EC\u7279\u7684\u6587\u5B57\u63CF\u8FF0\u8BE1\u8C32\u3001\u795E\u79D8\u7684\u60C5\u612B\u3001\u6C14\u5473\uFF1B
  12550. \u6211\u7A83\u6765\u4E86\u6DF1\u591C \u4F7F\u4F60\u80FD\u597D\u7761 \u76D7\u8D70\u4E86\u5C81\u6708 \u8BA9\u4F60\u6C38\u4E0D\u67AF\u840E
  12551. \u5173\u4E8E\u7231\u4F60\u7684\u4E00\u5207 \u6211\u505A\u4EC0\u4E48\u90FD\u5BF9
  12552. \u6211\u7A83\u6765\u4E86\u5B89\u6170 \u4F7F\u4F60\u5FD8\u4E86\u6D41\u6CEA \u76D7\u8D70\u4E86\u61CA\u6094 \u8BA9\u4F60\u6C38\u8FDC\u65E0\u90AA
  12553. \u5173\u4E8E\u7231\u4E0A\u7684\u4E00\u5207 \u6211\u5F00\u59CB\u65E0\u8DEF\u53EF\u9000
  12554. \u5468\u6770\u4F26\u4EE5\u4F4E\u6C89\u7684\u55D3\u97F3\u6F14\u5531\uFF0C\u8425\u9020\u51FA\u4E00\u79CD\u795E\u79D8\u3001\u9634\u90C1\u611F\uFF0C\u9AD8\u97F3\u65F6\u53C8\u4EE5\u7565\u5E26\u6175\u61D2\u7684\u8154\u8C03\u54FC\u5531\uFF0C\u5230\u4E86\u526F\u6B4C\u53C8\u6C89\u7A33\u8FF7\u4EBA\u7684\u4F4E\u55D3\u5531\u7740\uFF0C\u4EE5\u58F0\u97F3\u8868\u60C5\u6F14\u51FA\u795E\u79D8\u53C8\u5E05\u6C14\u5341\u8DB3\u7684\u7A83\u7231\u602A\u76D7\uFF1B\u800C\u9EC4\u96E8\u52CB\u7684\u7F16\u66F2\u66F4\u662F\u5145\u6EE1\u60C5\u8282\u8F6C\u6298\uFF0C\u5F00\u573A\u7684\u795E\u79D8\u8DDF\u8E2A\uFF0C\u4E2D\u95F4\u7684\u76F8\u9047\u5171\u821E\uFF0C\u7136\u540E\u53C8\u5206\u5F00\uFF0C\u4E0D\u65AD\u7684\u56DE\u65CB\u3001\u7EA0\u7F20\u3001\u56DE\u8361\u2026\uFF0C\u8BA9\u542C\u8005\u5F77\u4F5B\u5FC3\u4E5F\u88AB\u7A83\u8D70\u4E86\uFF0C\u968F\u7740\u602A\u76D7\u6D88\u5931\u5728\u5F02\u56FD\u9ED1\u591C\u4E4B\u4E2D\u3002
  12555. 4. \u5929\u6DAF\u8FC7\u5BA2
  12556. \u8BCD\uFF1A\u65B9\u6587\u5C71 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC\u2215\u68A6\u60F3\u4E4B\u7FFC
  12557. \u7ECF\u5178\u5468\u6770\u4F26\u5F0F\u7684\u4E2D\u56FD\u98CE\uFF0C\u642D\u4E0A\u65B9\u6587\u5C71\u7EDD\u7F8E\u5982\u8BD7\u7684\u6B4C\u8BCD\uFF0C\u4EE5\u5404\u79CD\u666F\u5199\u60C5\uFF0C\u5C06\u601D\u5FF5\u4E4B\u60C5\u3001\u7231\u60C5\u7684\u9057\u61BE\u3001\u7B49\u5F85\u3001\u5404\u79CD\u7EC6\u817B\u7684\u60C5\u7EEA\u5199\u5F97\u542B\u84C4\u5374\u53C8\u4E1D\u4E1D\u5165\u6263\uFF1B
  12558. \u6668\u971C\u6500\u9EDB\u74E6 \u6296\u843D\u971C \u51B7\u4E86\u8336 / \u629A\u7434\u6B32\u5BF9\u8BDD \u6B32\u95EE\u7434\u58F0 \u521D\u843D\u4E0B
  12559. \u5F26\u5916 \u601D\u5FF5\u900F\u7A97\u82B1 \u800C\u59B3\u5374\u4EC0\u4E48\u4E5F\u4E0D\u56DE\u7B54
  12560. \u800C\u8FD9\u9996\u6B4C\u66F4\u9996\u6B21\u6765\u5230\u5343\u5E74\u53E4\u9547--\u897F\u5858\u53D6\u666F\uFF0C\u91CD\u73B0\u8BCD\u4E2D\u7684\u573A\u666F\uFF0C\u8FD9\u4E5F\u662F\u65B9\u6587\u5C71\u7EE7\u6267\u5BFC\u300C\u5170\u4EAD\u5E8F\u300DMV\u4E4B\u540E\uFF0C\u518D\u5EA6\u62CD\u6444\u4E2D\u56FD\u98CE\u7684MV\uFF0C\u4E0D\u77E5\u53C8\u4F1A\u62CD\u51FA\u4EC0\u4E48\u4EE4\u4EBA\u60CA\u8273\u7684\u53E4\u88C5\u5927\u7247\uFF1F\u4EE4\u4EBA\u671F\u5F85\uFF1B\u8FD9\u652FMV\u4E5F\u662F\u5468\u6770\u4F26\u3001\u65B9\u6587\u5C71\u4E0EDarren\u7B2C\u4E09\u5EA6\u5408\u4F5C\uFF0C\u52BF\u5FC5\u518D\u5EA6\u6380\u8D77\u8BDD\u9898\uFF01
  12561. 5. \u600E\u4E48\u4E86
  12562. \u8BCD\uFF1A\u65B9\u6587\u5C71 \u66F2\uFF1A\u5468\u6770\u4F26 \u5973\u58F0\uFF1A\u8881\u548F\u7433 Cindy Yen \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u6797\u8FC8\u53EF
  12563. \u563B\u54C8\u66F2\u98CE\u7684\u6292\u60C5\u98CE\u683C\uFF0C\u662F\u5468\u6770\u4F26\u6700\u72EC\u7279\u65E0\u6CD5\u53D6\u4EE3\u7684\u66F2\u98CE\uFF0C\u800C\u8FD9\u9996\u6B4C\u6700\u7279\u522B\u7684\u662F\u7537\u5973\u5BF9\u5531\u7684\u5206\u624B\u6B4C (or\u51B7\u6218\u6B4C)\uFF0C\u7537\u5973\u90FD\u4E92\u76F8\u8D4C\u6C14\u51B7\u6218\uFF0C\u5435\u5230\u8981\u5206\u624B\uFF0C\u4F46\u662F\u5728\u72EC\u81EA\u4E00\u4EBA\u65F6\u5374\u53C8\u4E0D\u65AD\u5730\u95EE\u81EA\u5DF1\u600E\u4E48\u4E86\uFF1F
  12564. \u600E\u4E48\u4E86\uFF08\u4F60\u8BF4\u5462\uFF09 \u4E3A\u4F55\u6C9F\u901A\u6700\u540E\u603B\u662F \u6211\u54ED\u4E86\uFF08\u4E0D\u8BF4\u4E86\uFF09
  12565. \u627F\u8BA4\u72AF\u9519\u53C8\u80FD\u5982\u4F55 \u4F60\u9009\u62E9\uFF08\u6211\u8BA4\u4E86\uFF09
  12566. \u662F\u4E0D\u662F\u6211\u4EEC\u90FD\u592A\u81EA\u6211 \uFF08\u81EA\u6211\uFF09 \u501F\u53E3 \u8981\u81EA\u7531
  12567. \u8FD9\u6BB5\u7231\u5230\u5E95\u600E\u4E48\u4E86\uFF1F\u5F80\u5F80\u662F\u5F53\u4E8B\u4EBA\u6700\u641E\u4E0D\u61C2\u5230\u5E95\u600E\u4E48\u4E86\uFF0C\u800C\u8FD9\u79CD\u5FC3\u60C5\u4EE5\u7537\u5973\u5BF9\u5531\u5904\u7406\uFF0C\u66F4\u6709\u51FA\u73B0\u4E86\u5FAE\u5999\u7684\u5BF9\u7167\uFF0C\u4EE4\u4EBA\u5FC3\u6709\u621A\u621A\u7109\uFF0C\u4E5F\u8BB8\u7231\u60C5\u53D1\u751F\u95EE\u9898\u65F6\uFF0C\u4E0D\u8981\u53EA\u95EE\u5BF9\u65B9\u600E\u4E48\u4E86\uFF1F\u800C\u662F\u95EE\u81EA\u5DF1\u600E\u4E48\u4E86\uFF0C\u4E5F\u8BB8\u624D\u80FD\u771F\u7684\u627E\u5230\u7B54\u6848\uFF1B\u53C8\u6216\u8005\uFF0C\u7231\u60C5\u901D\u53BB\u65F6\uFF0C\u6839\u672C\u4E0D\u9700\u8981\u7B54\u6848\u3002
  12568. 6. \u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9
  12569. \u8BCD\uFF1A\u65B9\u6587\u5C71 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u5468\u6770\u4F26
  12570. \u5728\u300C\u54CE\u5466 \u4E0D\u9519\u54E6\u300D\u8FD9\u573A\u6D3E\u5BF9\u4E2D\uFF0C\u5468\u6770\u4F26\u8981\u5927\u5BB6\u4E0D\u4EC5\u52A8\u52A8\u8EAB\u4F53\u3001\u52A8\u52A8\u8033\u6735\u3001\u66F4\u8981\u52A8\u52A8\u5634\uFF01\u4E00\u8D77\u6765\u6311\u6218\u526F\u6B4C\u8FDE\u73E0\u70AE\u5F0F\u7684\u6B4C\u8BCD\uFF0C\u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9\uFF01
  12571. \u8FD9\u9996\u975E\u5E38\u6770\u4F26\u5F0F\u7684\u563B\u54C8\u821E\u66F2\uFF0C\u5982\u4E00\u5F00\u573A\u7684OS\uFF0C\u5C31\u662F\u8981\u5927\u5BB6\u9AD8\u4E3E\u624B\uFF0C\u4E00\u8D77\u52A8\u8D77\u6765\u5F00\u8DB4\uFF01\u800C\u8FD9\u9996\u6B4C\u6700\u72EC\u7279\u7684\u5C31\u662F\u5982\u540C\u6B4C\u540D\u300C\u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9\u300D\uFF0C\u65B9\u6587\u5C71\u5728\u526F\u6B4C\u8BBE\u4E86\u4E00\u6BB5\u6587\u5B57\u8C1C\uFF0C\u770B\u4F3C\u6BEB\u65E0\u610F\u4E49\u7684\u4E00\u4E32\u6587\u5B57\uFF0C\u4E2D\u95F4\u6BCF\u4E2A\u5B57\u90FD\u7A7F\u63D2\u4E86\u300C\u54AA\u300D\uFF0C\u4E00\u517161\u4E2A\u5B57\uFF0C\u8981\u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9\uFF1B
  12572. \u8FD9\u8FD9\u8C01 \u6B22\u8FCE\u4F60\u6765\u6D3E\u5BF9 \u6211\u7684\u4E16\u754C /\u5728\u5BBD\u655E\u7684\u5927\u8857 \u98D9\u97F3\u4E50
  12573. \u518D\u5FF5\u4E00\u6BB5\u788E\u5634 \u8FC7\u6765\u6311\u6218\u5C31\u5BF9 /\u9E23\u67AA\u8D77\u8DD1\u9884\u5907
  12574. \u5C31\u54AA\u8BA9\u54AA\u538B\u54AA\u529B\u54AA \u5598\u54AA\u4E00\u54AA\u53E3\u54AA\u6C14\u54AA \u7ED9\u54AA\u5B83\u54AA\u673A\u54AA\u4F1A\u54AA \u8DDF\u54AA\u7740\u54AA\u97F3\u54AA\u4E50\u54AA
  12575. \u5C06\u54AA\u7231\u54AA\u5199\u54AA\u6210\u54AA \u4E00\u54AA\u6BB5\u54AA\u8FC7\u54AA\u53BB\u54AA \u53EA\u54AA\u7559\u54AA\u4E0B\u54AA\u5BF9\u54AA\u7684\u54AA\u8BB0\u54AA\u5FC6 \u563F
  12576. \u5BF9\u5BF9\u5BF9\u5BF9\u4E86 \u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9 \u5BF9\u5BF9\u5BF9\u5BF9\u4E86 \u6CA1\u4E8B\u5C31\u52A8\u52A8\u5634 \u52A8\u52A8\u52A8\u52A8\u5634
  12577. \u52A8\u52A8\u5634 \u52A8\u52A8\u5634 \u62CD\u5B50\u8981\u5FF5\u51C6\u786E \u624D\u4F1A\u6293\u5230\u611F\u89C9
  12578. \u4F60\uFF0C\u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9\u4E86\u5417\uFF1F
  12579. 7. \u6211\u8981\u590F\u5929
  12580. \u8BCD\uFF1A\u5468\u6770\u4F26 \u66F2\uFF1A\u5468\u6770\u4F26 \u7537\u58F0\uFF1A\u6768\u745E\u4EE3 Gary Yang \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC
  12581. \u9633\u5149\u6447\u6EDA\u563B\u54C8\uFF0C\u4E5F\u662F\u5468\u6770\u4F26\u6700\u72EC\u95E8\u7684\u4E00\u79CD\u66F2\u98CE\uFF0C\u4E00\u5F00\u573A\u5C31\u4EE4\u4EBA\u8840\u8109\u8D32\u5F20\uFF0C\u7099\u70ED\u7684\u9633\u5149\u3001\u70EB\u811A\u7684\u6C99\u6EE9\u3001\u6EE1\u6C60\u7684\u6CF3\u88C5\u6B63\u59B9\u2026\uFF1B\u5468\u6770\u4F26\u548C\u597D\u54E5\u513F\u4EEC\u6768\u745E\u4EE3\u5408\u5531\uFF0C\u5C06\u70ED\u8840\u4E0E\u9752\u6625\u8868\u73B0\u5F97\u6DCB\u6F13\u5C3D\u81F4\uFF0C\u8FD9\u9996\u6B4C\u6770\u4F26\u4E5F\u73A9\u4E86\u4E00\u4E0B\u58F0\u97F3\u8868\u60C5\uFF0C\u975E\u5E38\u8C03\u76AE\u751F\u52A8\uFF1B\u5728\u7F16\u66F2\u7684\u90E8\u5206\u540E\u6BB5\u52A0\u5165\u4E86\u4E61\u6751\u98CE\u683C\u7684\u7F16\u66F2\uFF0C\u4EE4\u4EBA\u60CA\u8273\uFF1B
  12582. \u51B2\u51B2\u51B2\u51B2\u51B2 \u51B2\u5411\u6D77\u8FB9 GoGoGoGoGo \u51C6\u5907\u75AF\u766B
  12583. \u6211\u8981\u590F\u5929 \u5728\u6211\u8033\u8FB9\u788E\u788E\u5FF5
  12584. \u51B2\u51B2\u51B2\u51B2\u51B2 \u51B2\u5411\u6D77\u8FB9 GoGoGoGoGo \u5230\u4F60\u8EAB\u8FB9
  12585. \u522B\u8BF4\u518D\u89C1 \u6211\u5DF2\u7ECF\u5F00\u59CB\u60F3\u5FF5
  12586. \u5728\u5BD2\u51B7\u7684\u5C81\u672B\u542C\u89C1\u8FD9\u9996\u5145\u6EE1\u590F\u5929\u6C14\u606F\u7684\u6B4C\u66F2\uFF0C\u6574\u4E2A\u5FC3\u90FD\u6696\u4E86\u8D77\u6765\uFF0C\u5FEB\u548C\u6770\u4F26\u4E00\u8D77\u5927\u558A\uFF1A\u6211\u8981\u590F\u5929\uFF01
  12587. 8. \u624B\u5199\u7684\u4ECE\u524D
  12588. \u8BCD\uFF1A\u65B9\u6587\u5C71 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC
  12589. \u8FD9\u79CD\u6292\u60C5\u6B4C\u5145\u6EE1\u4E86\u6D53\u6D53\u7684\u7EAF\u7231\u98CE\uFF0C\u4EE5\u300C\u624B\u5199\u300D\u6765\u8868\u8FBE\u6821\u56ED\u7684\u521D\u604B\uFF0C\u624B\u5199\u7684\u60C5\u4E66\uFF0C\u4F20\u9012\u7684\u9752\u6625\u7684\u6E29\u5EA6\u4E0E\u7EAF\u7CB9\uFF1B\u4EE4\u4EBA\u5411\u5F80\uFF1B\u800C\u8FD9\u9996\u6B4C\u6700\u7279\u522B\u7684\u5C31\u662F\u7B2C\u4E00\u904D\u4EE5\u7B80\u5355\u7684\u94A2\u7434\u4F34\u594F\uFF0C\u886C\u7740\u5468\u6770\u4F26\u8F7B\u8F7B\u541F\u5531\uFF0C\u5F77\u4F5B\u5728\u7A7A\u8361\u7684\u6821\u56ED\u6559\u5BA4\u91CC\uFF0C\u5B89\u9759\u56DE\u5FC6\u7740\u5F53\u65F6\u7684\u521D\u604B\u60C5\u666F\uFF1B\u95F4\u594F\u4E4B\u540E\u4E8C\u6BB5\u4E3B\u6B4C\u622A\u7136\u4E0D\u540C\uFF0C\u8BA9\u4EBA\u610F\u60F3\u4E0D\u5230\uFF0C\u9F13\u58F0\u4E00\u8FDB\u4E4B\u540E\u66F2\u98CE\u53D8\u9976\u820C\uFF0C\u5F77\u4F5B\u5C06\u65F6\u7A7A\u62C9\u56DE\u5230\u521D\u604B\u73B0\u573A\uFF0C\u90A3\u4E2A\u66FE\u7ECF\u4E00\u8D77\u5F39\u7434\u7684\u516C\u56ED\u3001\u7CD6\u679C\u5E97\u7684\u9752\u6DA9\u5FAE\u751C\uFF1B
  12590. \u6211\u770B\u7740 \u59B3\u7684\u8138 \u8F7B\u5237\u7740\u548C\u5F26 /\u60C5\u4EBA\u8282\u5361\u7247 \u624B\u5199\u7684\u6C38\u8FDC
  12591. \u8FD8\u8BB0\u5F97 \u5E7F\u573A\u516C\u56ED \u4E00\u8D77\u8868\u6F14 /\u6821\u56ED\u65C1 \u7CD6\u679C\u5E97 \u8BB0\u5FC6\u91CC \u5728\u5FAE\u751C
  12592. \u5728\u73B0\u5728\u624B\u673A\u7B80\u8BAF\u4F20\u60C5\u7684\u7535\u5B50\u65F6\u4EE3\uFF0C\u6709\u591A\u4E45\u6CA1\u6709\u6536\u5230\u624B\u5199\u7684\u5361\u7247\uFF1F\u5982\u679C\u624B\u5199\u672A\u6765\uFF0C
  12593. \u60C5\u53EF\u4EE5\u56DE\u5230\u5F53\u521D\u7684\u7F8E\u597D\u5417\uFF1F
  12594. 10. \u542C\u7238\u7238\u7684\u8BDD
  12595. \u8BCD\uFF1A\u5468\u6770\u4F26 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC
  12596. \u5468\u6770\u4F26\u518D\u5EA6\u4EE4\u4EBA\u60CA\u8273\u4E4B\u4F5C\uFF0C\u547C\u5E94\u81EA\u5DF1\u7684\u6B4C\uFF0C\u7537\u751F\u5C0F\u65F6\u5019\u8981\u542C\u5988\u5988\u7684\u8BDD\uFF0C\u5973\u751F\u957F\u5927\u4E86\u8981\u300C\u542C\u7238\u7238\u7684\u8BDD\u300D\uFF0C\u5728\u8C08\u604B\u7231\u65F6\uFF0C\u660E\u660E\u662F\u4E24\u4E2A\u4EBA\u5BF9\u4E8E\u7231\u60C5\u7684\u4E0D\u5BF9\u7B49\u800C\u57CB\u6028\uFF0C\u5973\u751F\u6709\u65F6\u5019\u5374\u642C\u51FA\u7238\u7238\u6765\u5F53\u5206\u624B\u7684\u501F\u53E3\uFF0C\u53EF\u662F\u7537\u751F\u5374\u4E5F\u4EE5\u5B5D\u987A\u4E3A\u7406\u7531\uFF0C\u542C\u5988\u5988\u7684\u8BDD\uFF0C\u4E0D\u80FD\u8F7B\u8A00\u653E\u5F03\uFF0C\u8A93\u8A00\u8FFD\u56DE\u5973\u751F\uFF01
  12597. \u4F60\u542C\u7238\u7238\u7684\u8BDD \u8BF4\u6211\u4E0D\u662F\u4E2A\u597D\u4E1C\u897F /\u9001\u7ED9\u4F60\u7684\u82B1 \u4E0D\u914D\u653E\u5728\u4F60\u5BB6\u82B1\u74F6\u91CC
  12598. \u4ED6\u8981\u6211\u8D8A\u8D70\u8D8A\u8FDC\u8D8A\u597D /\u4E0D\u8981\u5728\u4E00\u8D77\u90A3\u6700\u597D
  12599. \u4F46\u6211\u542C\u5988\u5988\u7684\u8BDD /\u8981\u6211\u4E0D\u80FD\u8F7B\u6613\u653E\u5F03/\u8FD8\u559C\u6B22\u7684\u8BDD\u8BA9\u6211\u518D\u8FFD\u56DE\u4F60\u6C42\u6C42\u4F60
  12600. \u96BE\u9053\u4F60\u8981\u6211\u4E0D\u5B5D\u987A\u5417 /\u8FD9\u662F\u501F\u53E3\u4F60\u5E94\u8BE5\u61C2\u5427
  12601. \u7537\u751F\u4EEC\uFF0C\u61C2\u4E86\u5417\uFF1F
  12602. 11. \u7F8E\u4EBA\u9C7C
  12603. \u8BCD\uFF1A\u7F57\u5B87\u8F69 Josh Lo\u3001\u9EC4\u5A55\u7199 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u6797\u8FC8\u53EF
  12604. \u8FD9\u9996\u5145\u6EE1\u6D6A\u6F2B\u7AE5\u8BDD\u98CE\u683C\u7684\u300C\u7F8E\u4EBA\u9C7C\u300D\uFF0C\u4E2D\u7248\u8F7B\u5FEB\u563B\u54C8\u66F2\u98CE\u5374\u6697\u85CF\u7740\u7F8E\u4EBA\u9C7C\u7684\u773C\u6CEA\uFF0C\u9690\u55BB\u7231\u60C5\u7684\u6267\u7740\u4E0E\u54C0\u6101\uFF1B\u524D\u594F\u4EE5\u865A\u5E7B\u98D8\u6E3A\u7684\u6548\u679C\u97F3\u8868\u73B0\u51FA\u6DF1\u6D77\u91CC\u7684\u60C5\u5883\uFF0C\u4EE4\u4EBA\u6DF1\u6DF1\u6389\u5165\u7231\u60C5\u7684\u6DF1\u6D77\uFF0C\u503E\u542C\u7740\u7F8E\u4EBA\u7684\u6B4C\u58F0\uFF1B\u60A0\u6E38\u5728\u65CB\u5F8B\u4E2D\uFF0C\u6F02\u6D6E\u5728\u7231\u60C5\u91CC\uFF0C\u60B2\u4F24\u5728\u773C\u6CEA\u91CC\uFF1B\u56DA\u7981\u5728\u6C34\u91CC\u843D\u6CEA\u7684\u7F8E\u4EBA\u9C7C\uFF0C\u4EBA\u7C7B\u4F1A\u61C2\u5F97\u8FD9\u6837\u7684\u54C0\u6101\u5417\uFF1F
  12605. \u7F8E\u4EBA\u9C7C\u7684\u773C\u6CEA/\u662F\u4E00\u4E2A\u8FDE\u4F24\u5FC3\u90FD\u900F\u660E\u7684\u4E16\u754C
  12606. \u5730\u5E73\u7EBF\u7684\u8FDC\u65B9\u4E00\u8F6E\u6EE1\u6708/\u7AE5\u8BDD\u822C\u611F\u89C9/\u8BA9\u6211\u7231\u4E0A\u6709\u59B3\u7684\u9ED1\u591C
  12607. \u65E0\u58F0\u7684\u773C\u6CEA/\u6C34\u65CF\u73BB\u7483\u91CC\u59B3\u4E00\u6B21\u6B21\u7684\u6765\u56DE/\u601D\u5FF5\u6210\u4E86\u4EC5\u5B58\u7684\u90A3\u4E00\u5207
  12608. \u7F3A\u6C27\u7684\u611F\u89C9
  12609. \u5468\u6770\u4F26\u4EE5\u4E00\u79CD\u7565\u5E26\u6F47\u6D12\u800C\u968F\u6027\u7684\u53E3\u6C14\u6F14\u5531\u7740\uFF0C\u50CF\u662F\u4E2A\u53D9\u4E8B\u8005\u4E00\u822C\uFF0C\u7F13\u7F13\u8BF4\u7740\u5173\u4E8E\u7231\uFF0C\u5173\u4E8E\u773C\u6CEA\u7684\u79CD\u79CD\uFF1B\u4E5F\u8BB8\u7231\u60C5\uFF0C\u5F88\u591A\u65F6\u5019\u5C31\u50CF\u7F8E\u4EBA\u9C7C\u7684\u773C\u6CEA\uFF0C\u65E0\u58F0\u7684\u773C\u6CEA\uFF0C\u8BF4\u4E0D\u51FA\u53E3\u7684\u5374\u662F\u6700\u6DF1\u523B\u7684\u3002
  12610. 12. \u542C\u89C1\u4E0B\u96E8\u7684\u58F0\u97F3
  12611. \u8BCD\uFF1A\u65B9\u6587\u5C71 \u66F2\uFF1A\u5468\u6770\u4F26 \u5236\u4F5C\u4EBA\uFF1A\u5468\u6770\u4F26 \u7F16\u66F2\uFF1A\u9EC4\u96E8\u52CB\u2215\u68A6\u60F3\u4E4B\u7FFC
  12612. \u8FD9\u9996\u6B4C\u662F\u65B9\u6587\u5C71\u6267\u5BFC\u7684\u7535\u5F71\u300C\u542C\u89C1\u4E0B\u96E8\u7684\u58F0\u97F3\u300D\u4E3B\u9898\u66F2\uFF0C\u4E4B\u524D\u662F\u7531\u9B4F\u5982\u6600\u6F14\u5531\u7684\u5973\u751F\u7248\u672C\uFF0C\u8FD9\u5F20\u4E13\u8F91\u7ADF\u7136\u91CD\u65B0\u6536\u5F55\u6770\u4F26\u81EA\u5DF1\u6F14\u5531\u7684\u7248\u672C\uFF0C\u771F\u662F\u7ED9\u6B4C\u8FF7\u4E00\u4E2A\u975E\u5E38\u5927\u7684\u60CA\u559C\uFF01\u975E\u5E38\u503C\u5F97\u73CD\u85CF\u3002\u548C\u5973\u751F\u7248\u6D41\u9732\u51FA\u51C4\u7F8E\u6D6A\u6F2B\u6C1B\u56F4\u7684\u4E0D\u540C\uFF0C\u6770\u4F26\u7248\u7684\u300C\u542C\u89C1\u4E0B\u96E8\u7684\u58F0\u97F3\u300D\uFF0C\u4E3B\u6B4C\u4EE5\u4F4E\u6C89\u800C\u5BC2\u5BDE\u7684\u5B64\u5BC2\u611F\u541F\u5531\u7740\uFF0C\u5E26\u7740\u542C\u8005\u56DE\u5230\u7231\u60C5\u7684\u56DE\u5FC6\u73B0\u573A\uFF1B\u5230\u4E86\u526F\u6B4C\uFF0C\u5374\u5F77\u4F5B\u5728\u5185\u5FC3\u5436\u558A\u7740\u5BF9\u7231\u60C5\u7684\u8FFD\u5FC6\u4E0E\u4E0D\u820D\uFF1B\u5531\u8154\u5145\u6EE1\u620F\u5267\u5F20\u529B\uFF0C\u4EE4\u4EBA\u52A8\u5BB9\uFF01`,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID.jpg",album_trans_name:"",company_id:2317,company_name:"\u6770\u5A01\u5C14\u97F3\u4E50\u6709\u9650\u516C\u53F8",listen_num:0,long_audio_tag:"",msg:"success",public_time:"2014-12-26",ret:0,singers:[{singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26"}],songlist:[{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Rap/Hip Hop \u563B\u54C8\u8BF4\u5531",hot:0,isdigital_album:1,isonly:0,k_song_id:87824,k_song_mid:"003zLs4x0ihkvF",language:"\u56FD\u8BED",mv_id:304437,mv_vid:"w0015wi6oey",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=003b6hhl3jOPyV",song_id:101787864,song_mid:"003b6hhl3jOPyV",song_name:"\u9633\u660E\u5C71",song_play_time:152,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u9633\u660E\u5C71",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02060Zpq8J40vCyv.mp3?guid=2000000303&vkey=BD3B785318999324C852F17061533478E45047E4AFBC9574D77126BD2DCEEDB573FB1ED5CAE120B2ADC8495AEAD7801750E100BD9EC68A57&uin=&fromtag=20303",try_begin:34646,try_end:94646,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Rap/Hip Hop \u563B\u54C8\u8BF4\u5531",hot:0,isdigital_album:1,isonly:0,k_song_id:89107,k_song_mid:"001eg4fD47XIQE",language:"\u56FD\u8BED",mv_id:702098,mv_vid:"b0020b91gbc",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=003zL01l3vYMKT",song_id:101787865,song_mid:"003zL01l3vYMKT",song_name:"\u7A83\u7231",song_play_time:204,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u7A83\u7231",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02064Ka8Lw2rsEEu.mp3?guid=2000000303&vkey=269D57998A9A2CC46D779DAB471CB8268DD6054AE74870AEFEC9148B747429EDA1974049EC61CCC40EE020080480ADA05EC87DEA60B970D7&uin=&fromtag=20303",try_begin:0,try_end:6e4,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Pop \u6D41\u884C",hot:0,isdigital_album:1,isonly:0,k_song_id:87825,k_song_mid:"000bkVDn2cW5wU",language:"\u56FD\u8BED",mv_id:303718,mv_vid:"c0015vx9gdg",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=001Js78a40BZU6",song_id:101369814,song_mid:"001Js78a40BZU6",song_name:"\u7B97\u4EC0\u4E48\u7537\u4EBA",song_play_time:289,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u7B97\u4EC0\u4E48\u7537\u4EBA",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02062akW8V1iGkR1.mp3?guid=2000000303&vkey=76C1FF1C125E083397EC9CCB3E6758379C7CC0644C314AF70E3EBB89524FC843A833C195EF7911B825B3EB737733C1930B113BC6DCD51FBD&uin=&fromtag=20303",try_begin:89469,try_end:149469,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Pop \u6D41\u884C",hot:0,isdigital_album:1,isonly:0,k_song_id:89109,k_song_mid:"000YEH7z2dhwzW",language:"\u56FD\u8BED",mv_id:306253,mv_vid:"q00157ht6pm",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=00162TQ12285h4",song_id:101787866,song_mid:"00162TQ12285h4",song_name:"\u5929\u6DAF\u8FC7\u5BA2",song_play_time:253,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u5929\u6DAF\u8FC7\u5BA2",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02061d1ELm0emD1l.mp3?guid=2000000303&vkey=D12DD1A5BFBB09955829005B7D684FEEF25C4E9D62C4C506A4F51F007543E488672C53087790BF3120F9128537309257621E6D7E70E26105&uin=&fromtag=20303",try_begin:65301,try_end:125301,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Pop \u6D41\u884C",hot:0,isdigital_album:1,isonly:0,k_song_id:89113,k_song_mid:"004JOyLr0eS1Sx",language:"\u56FD\u8BED",mv_id:308837,mv_vid:"f0016x7gfl1",other_singer_list:[{singer_id:20424,singer_mid:"001lH4Rz0rnWGE",singer_name:"\u8881\u548F\u7433",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R500x500M000001lH4Rz0rnWGE_8.jpg",singer_title:"\u8881\u548F\u7433"}],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=001zqHER0WFQvO",song_id:101787867,song_mid:"001zqHER0WFQvO",song_name:"\u600E\u4E48\u4E86",song_play_time:232,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u600E\u4E48\u4E86",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02064cZXw20zgJke.mp3?guid=2000000303&vkey=76A11EB5A78BCD16008A3574113F464C3E2CA65E0AC3C35D5883B297D23728EB7822CBF8684142010977302F56EBD571FD68281213716F05&uin=&fromtag=20303",try_begin:26784,try_end:86784,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Rap/Hip Hop \u563B\u54C8\u8BF4\u5531",hot:0,isdigital_album:1,isonly:0,k_song_id:89111,k_song_mid:"001ILEo5414pQi",language:"\u56FD\u8BED",mv_id:653353,mv_vid:"k0018hq6zsq",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=003md41m1MBhMc",song_id:101787868,song_mid:"003md41m1MBhMc",song_name:"\u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9",song_play_time:158,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u4E00\u53E3\u6C14\u5168\u5FF5\u5BF9",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02060JNPkU4YVrz6.mp3?guid=2000000303&vkey=06A750EC1EA8283D3BB1240C7994909A8833CE266D24C17F86A1B2B3D937B11BF0FD048F76C98C29865212F3DA8CEAD63D021544F1DE59F9&uin=&fromtag=20303",try_begin:52238,try_end:112238,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Pop \u6D41\u884C",hot:0,isdigital_album:1,isonly:0,k_song_id:89112,k_song_mid:"002Xldvu0eVXnJ",language:"\u56FD\u8BED",mv_id:370550,mv_vid:"u00169aw33r",other_singer_list:[{singer_id:13886,singer_mid:"002Z462D2amcz9",singer_name:"\u6768\u745E\u4EE3",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R500x500M000002Z462D2amcz9_1.jpg",singer_title:"\u6768\u745E\u4EE3"}],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=0007w9Eb0lilhZ",song_id:101787869,song_mid:"0007w9Eb0lilhZ",song_name:"\u6211\u8981\u590F\u5929",song_play_time:219,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u6211\u8981\u590F\u5929",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02063xUMkB0ASilt.mp3?guid=2000000303&vkey=E351C1693CA00182D0064D420FEA36B3D219699B1F73D2045DCCDE97E7783A91C468B9BB7138C6EB5F4CD39A5501E41ED103B58F2693E791&uin=&fromtag=20303",try_begin:13888,try_end:73888,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Pop \u6D41\u884C",hot:0,isdigital_album:1,isonly:0,k_song_id:89108,k_song_mid:"001F73Ty1gFviH",language:"\u56FD\u8BED",mv_id:304855,mv_vid:"k0015ms0ov0",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=002u8ZOM4C7QF4",song_id:101787870,song_mid:"002u8ZOM4C7QF4",song_name:"\u624B\u5199\u7684\u4ECE\u524D",song_play_time:297,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u624B\u5199\u7684\u4ECE\u524D",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02061YA6OT4P6U8a.mp3?guid=2000000303&vkey=04E830D7104A5DB1096FFD890B857A8C5259B03BAA6FA3406EA338A7DD4E30FC89D9CD914C8363532B9A0AE071FBA3F383747E41A23BEAFD&uin=&fromtag=20303",try_begin:8928,try_end:68928,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Rap/Hip Hop \u563B\u54C8\u8BF4\u5531",hot:0,isdigital_album:1,isonly:0,k_song_id:86308,k_song_mid:"000KFMiU18009e",language:"\u56FD\u8BED",mv_id:302873,mv_vid:"o0015n27kp4",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=004KpNVr0EdY0v",song_id:101133228,song_mid:"004KpNVr0EdY0v",song_name:"\u978B\u5B50\u7279\u5927\u53F7",song_play_time:221,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u978B\u5B50\u7279\u5927\u53F7",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02063Pc2853RgjXI.mp3?guid=2000000303&vkey=575974A851CC61B64C76F9B311D8182F14769C567743E3AE5D5BEAF8D5BC55D0868B706193D96955C511C9BA4FE96E38E543B58FAA85AE52&uin=&fromtag=20303",try_begin:72394,try_end:132394,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1},{WeightPlayCnt:0,album_id:852856,album_mid:"001uqejs3d6EID",album_name:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",album_pic:"http://y.gtimg.cn/music/photo_new/T002R120x120M000001uqejs3d6EID_1.jpg",album_pic_150x150:"http://y.gtimg.cn/music/photo_new/T002R150x150M000001uqejs3d6EID_1.jpg",album_pic_300x300:"http://y.gtimg.cn/music/photo_new/T002R300x300M000001uqejs3d6EID_1.jpg",album_pic_500x500:"http://y.gtimg.cn/music/photo_new/T002R500x500M000001uqejs3d6EID_1.jpg",album_title:"\u54CE\u5466\uFF0C\u4E0D\u9519\u54E6",copyright:1,genre:"Pop \u6D41\u884C",hot:0,isdigital_album:1,isonly:0,k_song_id:98462,k_song_mid:"002NEPvs1MJihR",language:"\u56FD\u8BED",mv_id:307243,mv_vid:"y0015upwxtm",other_singer_list:[],playable:0,public_time:"2014-12-26",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singer_pic:"http://y.gtimg.cn/music/photo_new/T001R120x120M0000025NhlN2yWrP4_1.jpg",singer_pic_150x150:"http://y.gtimg.cn/music/photo_new/T001R150x150M0000025NhlN2yWrP4_1.jpg",singer_pic_300x300:"http://y.gtimg.cn/music/photo_new/T001R300x300M0000025NhlN2yWrP4_1.jpg",singer_pic_500x500:"http://y.gtimg.cn/music/photo_new/T001R500x500M0000025NhlN2yWrP4_1.jpg",singer_title:"\u5468\u6770\u4F26",song_h5_url:"http://c.y.qq.com/v8/playsong.html?songmid=003BiKB44LknC0",song_id:101787871,song_mid:"003BiKB44LknC0",song_name:"\u542C\u7238\u7238\u7684\u8BDD",song_play_time:263,song_play_url:"",song_play_url_hq:"",song_play_url_sq:"",song_play_url_standard:"",song_size:0,song_size_hq:0,song_size_sq:0,song_size_standard:0,song_title:"\u542C\u7238\u7238\u7684\u8BDD",song_version:0,try_30s_url:"http://isure6.stream.qqmusic.qq.com/RS02062jsrEg44GuFq.mp3?guid=2000000303&vkey=73FF6641C72664768E26E0982E4D510E2E2F2B4F4A4FAC24459966A769112C2A387113370E864B2D3636A17058E26EE4EB43441F34171FA6&uin=&fromtag=20303",try_begin:95167,try_end:155167,try_file_size:960887,try_playable:1,unplayable_code:2,unplayable_msg:"\u5E94\u7248\u6743\u65B9\u8981\u6C42\u4E0D\u80FD\u514D\u8D39\u64AD\u653E\uFF0C\u53EF\u4ED8\u8D39\u540E\u7545\u4EAB",user_own_rule:1,vip:1}],sub_ret:0,total_num:12,update_time:"2014-12-23 13:37:19"}),getMvDetail=a=>axios.get(`https://music-api.xverse.cn/qqmusic_proxy/music_api?opi_cmd=fcg_music_custom_get_mv_info.fcg&mv_id=${a}`,{headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"},withCredentials:!0}).then(i=>i.data.ret===0?i.data:{msg:"success",mv_list:[{mv_BlueRay_size:146732618,mv_BlueRay_url:"http://opimv.music.tc.qq.com/342CCBEE8F6893DBFFC95909241772B546F4355E943244D42580F4AD7743DE3C7826C5F5955A1910BEC3BF55D2D5A3E7ZZ1152921504878547564/1049_M0143700004FSwAW2Mxtku1001735049.f9844.mp4?fname=1049_M0143700004FSwAW2Mxtku1001735049.f9844.mp4&stdfrom=1&fromtag=50303",mv_HQ_size:26750769,mv_HQ_url:"http://opimv.music.tc.qq.com/44516749EA14F1B72CC22E13CF2B93F50945DEFA64C61F3AF205E7848606B0BB2644DEA455CC4E8FA6C4D85E05B159EDZZ1152921504878547564/1049_M0143700004FSwAW2Mxtku1001735049.f9824.mp4?fname=1049_M0143700004FSwAW2Mxtku1001735049.f9824.mp4&stdfrom=1&fromtag=30303",mv_LQ_size:9493503,mv_LQ_url:"http://opimv.music.tc.qq.com/2DE34560B7DDE72DF7579A89F31EE3D9FB2EAD5EBB3F8ED7E5D1D91952D3EF1A60E7DAF0B32EDC22F681F8F19F3AFD81ZZ1152921504878547564/1049_M0143700004FSwAW2Mxtku1001735049.f9814.mp4?fname=1049_M0143700004FSwAW2Mxtku1001735049.f9814.mp4&stdfrom=1&fromtag=20303",mv_SQ_size:40078045,mv_SQ_url:"http://opimv.music.tc.qq.com/9036ED33469EDA0270625FC7F4D911A7DBF3268FF3E96CEFC23685A4AD0E73EBA2C7E3A8763AB0BACDA20B597BA59DAAZZ1152921504878547564/1049_M0143700004FSwAW2Mxtku1001735049.f9834.mp4?fname=1049_M0143700004FSwAW2Mxtku1001735049.f9834.mp4&stdfrom=1&fromtag=40303",mv_fileid:"1049_M0143700004FSwAW2Mxtku1001735049",mv_id:1625184,mv_play_time:188,mv_title:"Mojito",mv_vid:"q0034sb9eru",pic_url:"http://y.gtimg.cn/music/photo_new/T015R640x360M101003N420L1V0qwU.jpg",playable:1,public_time:"2020-06-12",singer_id:4558,singer_mid:"0025NhlN2yWrP4",singer_name:"\u5468\u6770\u4F26",singers:[{id:4558,mid:"0025NhlN2yWrP4",name:"\u5468\u6770\u4F26"}],unplayable_code:0}],ret:0,sub_ret:0}),getComments=a=>axios.post("https://beta-lang-api.xverse.cn/v1/dialogue/recommend",{header:{app:"applet",userId:a.userId,npc_id:0,seq_id:0,timestamp:Date.now()},aux_info:{musician:a.musician,intent:"comments",number:a.number,song:a.song,album:a.album}});var style$3="",jsxRuntime={exports:{}},reactJsxRuntime_production_min={};/** @license React v17.0.2
  12613. * react-jsx-runtime.production.min.js
  12614. *
  12615. * Copyright (c) Facebook, Inc. and its affiliates.
  12616. *
  12617. * This source code is licensed under the MIT license found in the
  12618. * LICENSE file in the root directory of this source tree.
  12619. */var f=react.exports,g=60103;reactJsxRuntime_production_min.Fragment=60107;if(typeof Symbol=="function"&&Symbol.for){var h=Symbol.for;g=h("react.element"),reactJsxRuntime_production_min.Fragment=h("react.fragment")}var m=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n=Object.prototype.hasOwnProperty,p={key:!0,ref:!0,__self:!0,__source:!0};function q(a,i,e){var o,s={},c=null,d=null;e!==void 0&&(c=""+e),i.key!==void 0&&(c=""+i.key),i.ref!==void 0&&(d=i.ref);for(o in i)n.call(i,o)&&!p.hasOwnProperty(o)&&(s[o]=i[o]);if(a&&a.defaultProps)for(o in i=a.defaultProps,i)s[o]===void 0&&(s[o]=i[o]);return{$$typeof:g,type:a,key:c,ref:d,props:s,_owner:m.current}}reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;jsxRuntime.exports=reactJsxRuntime_production_min;const jsx=jsxRuntime.exports.jsx,jsxs=jsxRuntime.exports.jsxs,Fragment=jsxRuntime.exports.Fragment;function drawer(a){var c,d;const{songList:i,songIndex:e,coloseDrawer:o,clickCurrentSong:s}=a;return jsx("div",{className:"x-song-list",children:jsxs("div",{className:"detail",children:[jsxs("div",{className:"header",children:[jsx("div",{className:"close-button",onClick:o,children:"x \u5173\u95ED"}),jsxs("div",{className:"album-abstract",children:[jsx("img",{className:"singer-img",src:(c=i[0])==null?void 0:c.singer_pic}),jsxs("span",{className:"album-name",children:[jsx("span",{children:(d=i[0])==null?void 0:d.album_name}),jsx("span",{className:"change-album",children:"\u6362\u4E13\u8F91"})]})]})]}),jsx("div",{className:"content",children:i.map((_,b)=>jsx("div",{className:`item ${_.song_id===e?"active":" "}`,onClick:()=>s(_.song_id),children:jsxs("div",{className:"song-info",children:[jsx("span",{className:"album-name",children:_.song_name}),jsx("span",{className:"hyphen",children:"\u2014"}),jsx("span",{className:"singer-name",children:_.singer_name})]})},b))})]})})}var style$2="",arrowLeft="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFQAAABUCAYAAAAcaxDBAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAUJSURBVHgB7Z2Lcds4EIZXrsBXwbGDpAR1cO7ATAXRVRBdBclVEHUQpwKmAykVUKnA6uDPwoQiCVzwIeLJ4TeDkTW2ieWvXSxAgiuihYWFhYWFRFhRIgB4zy/n9je3gtvjVVOcdDvq9z/1z4fVavWDEiCaoCxgwS9P3P6hRsRHms4Pbt+5vbDAR5o7LOIjtw23Cv7Zcyv1BzcvtJCfuL0iPKrPr6GE9RrySkh++chtQ/0hfdDtz7jI7cShexKOWejjncfcd/q1jx23/7IcDvjEP6LbI9XvKjRhOXn8VB6oj/Wt22FRq7+jXNAnVnWckBrbNi5E7LGh1OLZqJD6+MoGPsPuleoE1hSYHmFfk/VWNEknWaN7hP1EKYEmi0p8gcfQHguaoWBnsfUrxQbNdOiQqlfa0N4qDU37qA5gEbNGBpNp7a21JCrFAHKYH5BQiPehRd0jdvhDTkBZiXkGzbAliRomUaEZf2Yh5pkOUZ/JJzpEzMG8xgwuQGhRa+PcXr2eG9orIL8dBsbiMBX5wBLqJc0My3luyCWQpxjxJ8KeQLMgMSPRXY5Ae3VRzynUTdCMp2bob8kF2jtnH+omQui78VLJOykguFzBqrk9UUDQTsJbmgLkrFdSILSYN15CAeH+1k69VHD7YN4piBm0/ys7zAn//RlfOFhJAbCIqQga8tqWjWHDffNSyMmoIM90iFlSBCBn/ILGInwyL+SZ1MS8sqsy7Bkf9sJBSvJIqmJq28xcMj7shRMryBMpi6lAE/bXjJttoD1d8HYVO3Uxz6CdoMWNFQ+W/zf/+EAeQHO9cSf86sNqtdpRWvw03o8StOg52GQyE1NhOtWQrT8NaCekNTkklzC/hm17MmwdPusRBB3+afQf+zk3MRVoz8uH5xW0r306uRaYq5gKtDP98GUwjJUBOQDtkAlFDUdLVuO44tRpZfvHmz9iaLox6hMtKA5qn+lfNJEhujxQOGLeZj5RIB4CGvAvxeHkqe/hGsFfUiot45zfDQUOwMSkZC6zCnJErqKyfe8Ne8ULJLaQ/2W8dzYP1augD8KvdomLOihKbYIejfcFOSRTUU2nEpfjNkHNdes7ckyGopqCHmkownjh8/JdFmOqkFfWY/6/tVqC38dgkhYVwv01GgvC3wJJVlQ4ugXi5vbpuD6TFJX7fzHsuesmnenmbneg2ftNSlS4vJ0OF7dP7+s3GVEFW+5P0GiHfbBHTiyiBt3bpO2oDRtKuhfIuybWFAhE3Ftl6X/6Fng+wNY4qPfkZPT/pL1EnUzo7Yy1ce7Td21bvLSkmWMZcgpygeClQTJ+LOD7mQKLl36mmYIQzxSgnfEVyV8YHgtCPj6E5cGvIB3WmMF4Cnnc9O8wlpCI++D+RGAvpFBSCNDO+tmK2iHmlkICuXbHHhmNqR1i7igGkJ8xr3MQFfYSGV72wg41yvbgfupFXJ4hF3FJo5ACOkr3pOSt2gE+W2zdUUpATlRAIrXmYC8tpNhSivQYXccQFs0DGJXFpqSHpjfQX0ywhudCqbgUft132FEhp1Ue+qsjKr65EleLWGqh+spseruV47sga8EvW25DLqJcF2R9K8bK7WgpyHouxlrQpRhr3/4rdZz/uX0xj5kduBTxi1UyeIs5Xr/FpVDqHv6p4Lnwq0QqZdfXNB0VxmqoiFp2PaUvBljT7bhIdPvlAIoT3X45gNrH+jb2soDxlowLCwsLCwsp8hs+a+PKsgY0IQAAAABJRU5ErkJggg==",arrowTop="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAP0SURBVHgB7ZuLcaMwEIbXN1eAOzg6SDoIV8G5g7iDuIO4BHdgXwVJKiAdxFeBSQWkg/+kQcwtYuXwWAG++JvZMQYktL8eCD2Irlz50ixoAgAszc/SO/2xWCw+aGSiC2CcTczPytiNsVtj9v8ycLsVIHf2YuxoRDnSpWGcvjX2aOyE4ZyM7ZyQ88YkMjWWtXCqcI5xa0Nmn0FzA2WOZ2ecfTK2cQItz8SzdPdsXJgiEKe9ltAcQFnUg7l1zuGW8a+cwxKPNBU2B4wdhUTtY+SOe95BeN4JY5cGl7OFkOO3FBknRCaIEP3ZVQLuvYdbITY0MijbCZ97iong/Gk05eX0JGi+QeKIgLKln7buyemSREhJE+Ehs3C+QkhfoZq+OTtfIYjwRhqg+Z5PaKa4asrfTlsaglOVM3pr3xU03w79G2nUe2AZXQio9xP6pRtlZydq0UfZ9x/UVQ7E67+xUuqKp+KelEHZp6jqq/q7G/Vuc7dSINT9hBRBs0OlLoLgQ/u2AOUARJTcDzgfS4SMxb3tEvDEAq5IiU+cVxcB9Xbs1DYQb0AKUqKl86oioGxkeb8gaRNozQI8kwKQP6L27P8BkT5qrA8szkY/5psQhhf5VxqeAOvIgZ3Kjf009i6cy9m5g5IIr+z4xr8oCfCDHQ8akg45b4a6c/9edy6GCNyHz98EXp3p3UkJFPuEXd+ya1t2XvUbH2U7UFHo3Xw+nvtzzrt7RAHcNW0RgpnqVwF+sdc0FToU+xARqgP35awAg3DqHtipnDo6XxEQYQflbwdVARyV2jn1dL5CEEH9w+k7KWJnd00O2QSnxg4as71WBBfn2tir9gyyL0CwrrTFzeaqzui6krCl/iTsuCbgN+9BH+yGKN/qY+P50FiDILUBOTuebMxfEe5D7l+UBPgTCHypcB/e/YuSALz+pnT5pOy48XEnCcBvuvsP2oE7dtxonBsCuBY3d3+t8xdbDVAO5lQZmEvrjUIdod/seLpFCMNZs+MX6YaQALwapLiEBUoeLs2/2KkddQHxh8Wr8Tr7paZezTBkWNxLYEVCyiDexIg/JJ5SH6AxxTQBXrqfqC9oTjFtaOaYND6ollzUR26i1FcthKK/JQ1MRG8s0hMuY4FEu4mQDpEXcxUBYyzhQfOtMAsRIA+gxqmmqM8aTS4Cykbad35NMRFEsEyxUPIBzdWqaxqDgPLZGKUB8lJZK0RKYxKoe5Y9MOpi6SOmbItQ7yf4QqxoAPi3fyALPGNLc8DlznMgkTE2TGSYY4cMw7bMFC3CZZjjlhkflCViB71NU7aaRcnxMbbN2YRbs4MTCbXbNmeHruzo9POQqbU2fPmNk1eufHH+An3VVD4OQ3jbAAAAAElFTkSuQmCC",arrowRight="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFQAAABUCAYAAAAcaxDBAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAT4SURBVHgB7Z2BddowEIaPTJBOUG/QjsAGzQY4EySdIHSCpBOEDZJO4GwAmcB0grDBXykWBeQTtrGkk/38vafn8AKS/HOnk2z5IJqYmJiYmEiEGSUCgO/qsC9fVclUuT4qmp0pW/P63fy9mc1mb5QAYoIqATN1uFHlB1UiXlN/3lT5o8qrEnhLY0eJeK3KvSoFwrNWJTdf3LgwQj6o8oH46DafYwkb1OW1kOpwp8o9Nbv0xpT/46IqO+W6O6bOzNS3H3O/mWMTK1V+DXI4UCd+h/MWqf9XoHLL3uOntkBT18t5g0Wp30dDwZxYceaE9Nh270PEhj7kRjwXBVIfX1UHF3BbpT6BOUWmQdiPZK0VVdBJttMNwj5QSqCKohxPCOjaXUE1FKwcfX0maVBNhzapWqULY63c0LQWNQCHmCUGMJk21lpyopIE4N18g4RcvAkj6hrS7g8+AA1KzD2ohi1O1DiBCtX4Mwox95wRdUEhMS5iD+YlRnABwohaWuf2EfTcUF8BhW0wMg6DKSgEDlfPaWQ4zvOefAJ+iiE/EQ4EqgWJ7Yn+YgTqq4tyTK5ug2o8tV1/ST4w1jl6V7dhXN+PlXLWSRFR7d2Ykyn13xQR1IPwkvoAPurlFBHUx+6wc8PTtuderZQx+6jWafrAXcSIKao94b884jOV5RQZ8NOYaKKiurtwzGXzUvDBKCMBJEUFH/Ez6grzzbySIMKiFlab3d2eqSQnYaREZdrt7vZMpzNKAAlRUbn9MR9dK7CnCzJXsR0IiWoHaHZjxZXj8/abN5QQs9lspQ63zL9WAUV9t153EjRrqEwcAVFto2qz9acC9YA0p0SJ5f6olsDHtJ/1MIK2/zYEiCEq6vPy9nEF9fVz8veLQouKeqRvvwyHtTIgD+Bw1UgCX6Iew06dZq4PnrxJQf07o7/RjGTQ+0y/UE/a6HJF8ZAcNnYUiauIHdBTnC3J8JP8014jDDMoLRzjZ04eQM+gZC+zMkqY0GKaNr5bdbMXSFwu/9d6new81ETwFfOvW7Oa8kUrL3UJurVeZ5QgEcXU2EbFLsddgtrr1m+UGJHF1NiCbqktzHiR2uW7Regxk2nTjivzLp+vrZaQSKQXEtNex3dfPSLNWyCL2GKadr3cAvFz+9QTUmKatl+tNi+6SWebud8daN36shAUM2PazegS4OP2aU9Qv7AbTUzTvu3ulwdo1N0+erQH/+hLTpFg2s/pUsDvmphTRCC4WQ38lsaM+qAqWFqVRg1OqFy+hMDTeQixa9thpTmNHPC3VDLyAWOlYhE/Bgj9TIHDSh9ppCDGMwWoR3xNtI2vsUDMx4cwPfgVpcESIxhPwY+b4Q3G4RKyD+73BO5ECjnFAPWoP1hRz4i5pJiAz92xxoDG1DNirkgC8M+Yl0MQFe4UGXJ7YeF+cD/1JC4L8Pus0kikgDOpe1KyVmMAj46+riglwAcqIJFcc3CnFtIsKUUaOl1KCIvqAYzC0aekh6ZP0JxMsETgRKk4JH5dn+lHgSGt8tCcHVHz4ktcI2JuhGpKsxnsVk7ohKyZOixVaXMR5Tgh62cyVlW2joSs+2SsGR2SsTbtv9L1/Fblya5zcOCQxE8qZfASY7x+i0Oi1DXCUyBw4leOVNKuz6k/2o31UCGadj2lHwaY0+m4SHT64wCaHZ3+OIDex/o59ioBk3p8cmJiYmJiQpx/9LjjywzO+koAAAAASUVORK5CYII=",arrowDown="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAPwSURBVHgB7ZuLcdswDIbhXAfwBlUnSEZQJ6g3iDJB3AnibpAN7A3iTKB0grgTyJ1A3gAlT1ALUaCtB6hH4++OpzdJ/HwKogCuXPnQLGAEEHFpNkvn9GmxWJxgYIILYIyNzGZlwq0JdybY46XndivAkcKrCQcjygHmhjH6zoQnEzLsT2bCMwk5bUwmYxPSBkblZBgPeYPnUpsGTA0sSjw9Y+yLCWsSaHkmniXds6ZnfKLYaxFMASyqure0zhncMP6VCTtPGk8wFrYETDgImdqGKB1KTxIiw6FrA5VsLpR4BIEhIVJBhDsYApPQvZO4FWINA4NFP+FyDyERjM8GU17OT4T1oTaMCFj09OO2PTlfkggxaCIkMgnjS4T85ar5m7LxJYII76AB1sf5CCYKNVM+Om2gD6QqZ/Devi1YHx26d9JYTDlLUpgJWJ0ndMs3FpOdoFUfi7l/r6myJ1635sbQFkfFLSjjtNcYlMHqtLldLRAUjEAZ20Gx+DegjGCD2BfceJ7nnd2r8cocYWZQnt/YqZV0n0+Ab2x/B/PlB9sXp8g1AaiqRHRoHZV7mC/Wn1g6WiOpKUs1gLeVnzBjyMvMbag1A0kAftMbzJ83tn/rXpQE+Mz25+eSrsNtqI0EkgCR5+G5wm2I3IsVAdD5YjPGlxptyIbSjtrM060B/OIROkBT6I3m5ImmzGvs/mLDC7IiwCdQhNQtp5335vhr30kUCWnjtNuTOf6iWTNvQJ+/464JaZ+a4BhvUX9xUhWASuY7OxVBRxEE4y0P2v2SK4C3rTTFZHBnNg/sVAQtRThj/A66wW05XUqcu5Q6VznzbOK8jWVcBN/bIMpe3gQ6Qh1oSe5el5rAke13did1qQkBSt7CbTi6FyUBfnkebk0bEQIZb+E2/L54N1adiipvgp7msGXHO81q76S9bxUnVj0ptj9QGXoEEc6RgBJY7dOa1WinNGJQoqEICSiBxdqCkqzNg7yHVnWHXxAhAUWw6hh9bvOg+yE0AkU8IiSgCPZ17GJ4t3gpQq5tPMXf3S1OEcSOgurrAHDKH0YoorSXiiPh5PsFuiL0BWuYOCaPj9in7QsR8hEhxxGXxFxCqPob0MBE9M4izVB5VNAAhVUsoAVFnk9VBBxiCQ/WR4VJiIDy63OYZooX3vGHBotO2jU+gZCgPIsbY6HkI9ZXqyYwBB7l0yFqA8or060QMQyJp+1ZtiGEQP9i6QOO2RdhdZ7AsQusVtAD/Pf/QOpJYwNTgEpn78lkiB8mUpzihAyb/zJjyfB/+WXGBYsa8Yx6P03ZZhakxIf4bc5m3Aa77iiCZr/NHaDwTu9DL9D68D9OXrnywfkDAyQ8UFd8YlAAAAAASUVORK5CYII=",shareJayImg="./assets/share_jay.c5e10303.png",closeIcon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAbCAYAAACN1PRVAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAADkSURBVHgBzdXRDQIhDABQ4gSOwAiO4iiOwAbeBt4GugEjOAIjGCeo5QKRIHeWthiblB+4vpQAZ0wKALhg3jEPRiGwjsX0qaY1FZTjIQUTFIqaYQFxOMNnsMEGlMPvcP7Z+GaP6XvBtF0e067UXBbN0A5yhxsdvbexWMwGuyAJyII4oAgigE4V2gDdEKgBuqFQUfz4E6hC/wKCsvvRUAzx402F5GAnxAeBcBhA4fHuOnUiEBjHmwWC4B51gaBwYUmgBkQGcbhpQAQwxMmTFvQFnPKk04JWwLmejB1eNaCi5gTFv/AF0GNAe2kSmeQAAAAASUVORK5CYII=",pointerIcon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACIAAAAqCAYAAADWFImvAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAHzSURBVHgB7Zj/dYIwEMe/8XUAR6AT6AbiBNYJSiewG5QNqhP0dQJ1grKBOgFsYDdI70rwRzgkIsF//Lx3KkmAby7H5RBwRGs9I0vJNmQvuAd8Y10mQIv0HMeFjm2NcRXSF9oCtIirkAyecRXinYcQm4cQm4cQm5uFUKr/NCl/T/aBhrThkWID5Owbk5h3NKANIZl1POEP3hTJfozN6i7yhPYJzHeI48YYkpihUuqt6qQeDejz2ppa44uP4YeoKB1MbTM/LSV4aeZkMfKZRGRL+CM03xxHvFxcZIWFkIE9uOisYWRmFFjtHBtDuNUr7P0lrwLHyK8wgJ+EpOYiIVla0bepaA8E8SwmYo8shBNePcUK5xlJ5ICFJCh7hUU0ygcOSBMc9uiRYhHfQufsxCvS8rVJv0hoK6kT+VPUhZA8s5JXEsjBOUFHnKb4tdBfPMq+ktwBVfww8ZAKN81Mm08x2cEjF4I2QAcesXffFe5DdibEBO0Wd0CqR9bonp2yWy4ErU+mJY+YoF2gW7ZKau3YKwlNfizWrB175T9lqKpe4xXesgP4I6NJP/OPyireeGUKvxve2HkkeSbSfohxLTr/M2+v2yNGU3T+wpTq20i1W2HuJCjS1wtib/LraGU6UGiIPr4yjFDeoTnAM7Id8jyR1F3vD3lV/a6kMxACAAAAAElFTkSuQmCC";function piexlPanel(a){const{onClose:i,pixelWallUrl:e,pixeUserUrl:o,pixeUserCoordinate:s,allLitBlock:c}=a,[d,_]=react.exports.useState("preview");react.exports.useState(!1);const[b,k]=react.exports.useState(0),[j,$]=react.exports.useState(0),[_e,et]=react.exports.useState(0),[tt,rt]=react.exports.useState([0,0]),[it,nt]=react.exports.useState(o);react.exports.useEffect(()=>{try{if(!s)return;const dt=JSON.parse(s);rt(dt);const gt=dt[1]*8,_t=dt[0]*8,yt=dt[0]*32+(dt[1]+1);et(yt),k(gt),$(_t);const Tt=document.getElementById("active-avatar");if(!Tt)return;Tt.style.left=gt+"px",Tt.style.top=_t+"px"}catch(dt){console.log("error:",dt)}},[s,d]),react.exports.useEffect(()=>{ut(JSON.stringify(tt))},[tt]);const ot=()=>{_("detail")},at=()=>{_("preview")},st=()=>{_("share")},ut=dt=>{const gt=c.find(_t=>_t.coordinate===dt);return nt(gt?window.atob(gt.litUrl):null)},ft=()=>{const dt=document.getElementById("active-avatar");if(!dt)return;const gt=parseInt(getComputedStyle(dt).left.replace("px","")),_t=parseInt(getComputedStyle(dt).top.replace("px",""));if(dt.style.left=gt-8+"px",et(_e<=0?_e+1024-1:_e-1===0?1024:_e-1),gt===0){if(dt.style.left="248px",_t===0){dt.style.top="248px",rt([31,31]);return}dt.style.top=_t-8+"px",rt([tt[0]-1,31]);return}rt([tt[0],tt[1]-1]),dt.style.left=gt-8+"px"},lt=()=>{const dt=document.getElementById("active-avatar");if(!dt)return;const gt=parseInt(getComputedStyle(dt).left.replace("px","")),_t=parseInt(getComputedStyle(dt).top.replace("px",""));if(et(_e>=1024?_e-1024+1:_e+1),gt===248){if(dt.style.left="0px",_t===248){dt.style.top="0px",rt([0,0]);return}rt([tt[0]+1,0]),dt.style.top=8+_t+"px";return}rt([tt[0],tt[1]+1]),dt.style.left=8+gt+"px"},ht=()=>{const dt=document.getElementById("active-avatar");if(!dt)return;const gt=parseInt(getComputedStyle(dt).top.replace("px",""));if(et(_e>=992?_e-1024+32:_e+32),gt===248){dt.style.top="0px",rt([0,tt[1]]);return}rt([tt[0]+1,tt[1]]),dt.style.top=gt+8+"px"},pt=()=>{const dt=document.getElementById("active-avatar");if(!dt)return;const gt=parseInt(getComputedStyle(dt).top.replace("px",""));if(et(_e<=32?_e+1024-32:_e-32),gt===0){dt.style.top="248px",rt([31,tt[1]]);return}rt([tt[0]-1,tt[1]]),dt.style.top=gt-8+"px"},mt=()=>{const dt=document.getElementById("active-avatar");if(!dt||(dt.style.left=b+"px",dt.style.top=j+"px",!s))return;const gt=JSON.parse(s),_t=gt[0]*32+(gt[1]+1);rt(gt),et(_t)};return jsxs("div",{className:"x-piexl-panel",children:[d==="preview"&&jsxs(Fragment,{children:[jsxs("div",{className:"previw",children:[jsx("div",{className:"left",children:jsxs("div",{className:"left-item",children:[jsx("img",{src:e}),s&&jsx("span",{id:"active-avatar"}),jsxs("div",{className:"point-info",children:[jsxs("span",{children:["\u5F53\u524D\u7F16\u53F7 NO.",String(_e).padStart(4,"0")]}),jsx("span",{className:"click-to-my-button",onClick:mt,children:"\u8DF3\u81F3\u6211\u7684\u683C\u5B50"})]})]})}),jsxs("div",{className:"middle",children:[jsx("div",{className:"title",children:"\u660E\u661F\u5E94\u63F4\u6D77\u62A5"}),jsxs("div",{className:"control-panel",children:[jsx("span",{className:"top-arrow",onClick:pt,children:jsx("img",{src:arrowTop,alt:""})}),jsxs("span",{className:"control-middle",children:[jsx("span",{className:"left-arrow",onClick:ft,children:jsx("img",{src:arrowLeft,alt:""})}),jsx("span",{className:"avatar",children:it&&jsx("img",{className:"avatar-img",src:it})}),jsx("span",{className:"right-arrow",onClick:lt,children:jsx("img",{src:arrowRight,alt:""})})]}),jsx("span",{className:"down-arrow",onClick:ht,children:jsx("img",{src:arrowDown,alt:""})})]}),jsxs("div",{className:"button-panel",children:[jsx("span",{className:"download",onClick:ot,children:"\u4E0B\u8F7D\u6D77\u62A5"}),jsx("span",{className:"share",onClick:st,children:"\u5206\u4EAB\u6D77\u62A5"})]})]})]}),jsx("div",{className:"close-preview-button",onClick:i,children:jsx("img",{src:closeIcon})})]}),d==="detail"&&jsxs("div",{className:"detail",children:[jsx("div",{className:"close-detail-button",onClick:at,children:"\u8FD4\u56DE"}),jsxs("div",{className:"avatar",children:[jsx("img",{className:"avatar-img",src:e}),jsxs("div",{className:"img-save-area",children:[jsx("img",{className:"pointer",src:pointerIcon}),jsx("span",{children:"\u957F\u6309\u56FE\u7247\u4FDD\u5B58"})]})]})]}),d==="share"&&jsxs("div",{className:"share",children:[jsx("div",{className:"close-share-button",onClick:at,children:"\u8FD4\u56DE"}),jsx("div",{className:"content",children:jsx("img",{className:"share-img",src:shareJayImg})})]})]})}var style$1="";const tabList=[{areaList:[{}],isBoss:"0",tabName:"\u821E\u8E48",tabSort:"2",motionType:"male",tabEffect:"1",motionList:[{id:"Dance01"},{id:"Dance05"},{id:"LockingHipHopDance"},{id:"WaveHipHopDance"},{id:"Dance01b"},{id:"Dance01c"},{id:"Dance02"},{id:"Dance03"},{id:"Dance04"}]},{areaList:[{}],isBoss:"0",tabName:"\u4E92\u52A8",tabSort:"1",motionType:"male",tabEffect:"1",motionList:[{id:"Jump_all"},{id:"Qiangtui"},{id:"Hallo"},{id:"Yaotou"},{id:"BlowAKiss"},{id:"Cheering"},{id:"HappyIdle"},{id:"Singing"},{id:"Talking"},{id:"Thankful"},{id:"Waving"}]},{areaList:[{}],isBoss:"0",tabName:"\u821E\u8E48",tabSort:"2",motionType:"female",tabEffect:"1",motionList:[{id:"Dance01"},{id:"Dance05"},{id:"RumbaDancing"},{id:"Dance01b"},{id:"Dance01c"},{id:"Dance02"},{id:"Dance03"},{id:"Dance04"},{id:"WaveHipHopDance"}]},{areaList:[{}],isBoss:"0",tabName:"\u4E92\u52A8",tabSort:"1",motionType:"female",tabEffect:"1",motionList:[{id:"Jump_all"},{id:"Qiangtui"},{id:"Hallo"},{id:"Yaotou"},{id:"BlowAKiss"},{id:"Cheering"},{id:"HappyIdle"},{id:"Singing"},{id:"Talking"},{id:"Thankful"},{id:"Waving"}]},{areaList:[{}],isBoss:"1",tabName:"\u8001\u677F",tabSort:"1",motionType:"male",tabEffect:"1",motionList:[{id:"Idle"},{id:"Talking"},{id:"Clap"},{id:"Hallo"},{id:"Hand01"},{id:"Hand02"},{id:"Clap02"}]}],motionList=[{id:"Jump_all",title:"\u8DF3\u8DC3",panelIcon:["//y.qq.com/music/photo_new/T011M0000000Rm1I2eLpHG.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003knom51PT1pG.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000000rPiE21hxTtK.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000000dookV11zgZL.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Qiangtui",title:"\u70B9\u5934",panelIcon:["//y.qq.com/music/photo_new/T011M0000015NdLH382Zme.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000002ydwXy2XtFZG.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000003jGCaB0bpCMP.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000001vYT430xeTHC.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Hallo",title:"\u6447\u6446",panelIcon:["//y.qq.com/music/photo_new/T011M0000034yEoX1zpe42.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000004IiLNN49mpjT.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000000Jdyst2xoKSo.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000002ArA3c0Ah6xQ.png?max_age=2592000"],area:[{}],loop:"0",bossPanelIcon:["//y.qq.com/music/photo_new/T011M000001Oj5XB2Mi67N.gif?max_age=2592000"],bossControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000001lmNbm1AA45i.png?max_age=2592000"]},{id:"Yaotou",title:"\u6643\u5934",panelIcon:["//y.qq.com/music/photo_new/T011M000000xPvGG32myOw.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003ttHhJ2BpySj.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000000dadqi3lJbEB.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M0000013ELvo44L6Ys.png?max_age=2592000"],area:[{}],loop:"0"},{id:"BlowAKiss",title:"\u98DE\u543B",panelIcon:["//y.qq.com/music/photo_new/T011M0000026bRmh0R7sBx.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000002niT9H0HbRiy.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000001m2H7D483Wbm.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000001SgVFG1UZ3mi.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Cheering",title:"\u6253CALL",panelIcon:["//y.qq.com/music/photo_new/T011M000002wKHKj2E4Vr4.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M0000034rEZy1s3XMl.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000002NVfiW2K6ZI6.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000000D5oPP4GpV7T.png?max_age=2592000"],area:[{}],loop:"0"},{id:"HappyIdle",title:"\u5F00\u5FC3",panelIcon:["//y.qq.com/music/photo_new/T011M000003xrjUo2hAK7o.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000002rGuNB0BlH5B.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000001S4isY274w5U.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003V2VRd3sD1op.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Singing",title:"\u5531\u6B4C",panelIcon:["//y.qq.com/music/photo_new/T011M000001E59Jz1T3HZK.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000001NzCuo1S2I9r.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000003N9bjD4JTbuk.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000000QMSeB3wTafg.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Talking",title:"\u804A\u5929",panelIcon:["//y.qq.com/music/photo_new/T011M000003cr0lx25hA1R.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000002MnSY54BdVWH.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000003VyL532LvniX.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003coQNh2fvXCQ.png?max_age=2592000"],area:[{}],loop:"0",bossPanelIcon:["//y.qq.com/music/photo_new/T011M000003DrVhP2I7jB7.gif?max_age=2592000"],bossControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000001hL8Jc3gjtEw.png?max_age=2592000"]},{id:"Thankful",title:"\u611F\u8C22",panelIcon:["//y.qq.com/music/photo_new/T011M0000025u2iK2qUnwx.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003kuh0F3GmEMU.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M0000012sqCT0bnMB3.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000004fqhum0OiGmz.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Waving",title:"\u6253\u62DB\u547C",panelIcon:["//y.qq.com/music/photo_new/T011M0000002QpXi3PuEmA.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000000paZaL1htHD6.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000004Baxqv0KaPg1.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000004Li2z03AJld6.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Dance01",title:"\u7535\u6446\u821E",panelIcon:["//y.qq.com/music/photo_new/T011M000000br1Vx1fH04k.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003nV5QL0wKAaw.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000002RvjFI3tZxwl.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003YGzVL262OEY.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Dance05",title:"\u54C8\u6797\u6447",panelIcon:["//y.qq.com/music/photo_new/T011M000003yHZlb2cV2lb.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M0000033SSbM0xfwVy.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011M000001gEadb32PfAR.gif?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000003JosTC0FPP56.png?max_age=2592000"],area:[{id:""}],loop:"0"},{id:"RumbaDancing",title:"\u4F26\u5DF4\u821E",panelIcon:["//y.qq.com/music/photo_new/T011M000000ZwtoG0eFfdH.gif?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000002K4qEc0Ggwl0.png?max_age=2592000"],area:[{}],loop:"0"},{id:"Idle",title:"\u9ED8\u8BA4\u52A8\u4F5C",panelIcon:["//y.qq.com/music/photo_new/T011R148x180M000001MH4pp1DhfLR.png?max_age=2592000"],controlIcon:["//y.qq.com/music/photo_new/T011R148x180M000000WNYiL1AQWjs.png?max_age=2592000"],malePanelIcon:["//y.qq.com/music/photo_new/T011R148x180M000004I8HDL2goA3Q.png?max_age=2592000"],maleControlIcon:["//y.qq.com/music/photo_new/T011R148x180M000002mrBCw26eg1c.png?max_age=2592000"],area:[{}],loop:"0"}],mainMotion=[{config:[{id:"Cheering",areaList:"inReportHall",startTime:"2022-03-11 14:43:24",endTime:"2022-03-31 14:43:27",icon:["//y.qq.com/music/photo_new/T011R184x184M00000020P584Kcz58.png?max_age=2592000"]}],defaultMotion:[{id:"Jump_all",icon:["//y.qq.com/music/photo_new/T011R184x184M000002JEeJf40yp6v.png?max_age=2592000"]}],bossMotion:[{id:"Clap",icon:["//y.qq.com/music/photo_new/T011R184x184M000000gkFl53OIRTo.png?max_age=2592000"]}]}];var config={tabList,motionList,mainMotion};function AnimationList(a){const{onPlay:i,coloseDrawer:e}=a,o=config.motionList.map(s=>({name:s.title,id:s.id,url:(s.panelIcon||[])[0]}));return jsxs("div",{className:"x-animation",children:[jsx("div",{className:"close-button",onClick:e,children:"x \u5173\u95ED"}),jsx("div",{className:"x-animation-list",children:o.map(s=>jsxs("div",{className:"animation-item",onClick:()=>i(s.id),children:[jsx("img",{className:"animation-item__img",src:s.url,alt:""}),jsx("span",{className:"animation-item__name",children:s.name})]},s.id))})]})}var style="",luhanPng="./assets/luhan.bc35471c.png",zhoujielun="./assets/zhoujielun.d9d243b4.png";function SingerRoomList(a){const{singer:i,gotoOtherSinger:e,closeSingerRoom:o}=a,s=c=>{e(c)};return jsxs("div",{className:"x-singer-room",children:[jsx("div",{className:"close_button",onClick:o,children:"x \u5173\u95ED"}),jsx("div",{className:"content",children:i.map((c,d)=>jsxs("div",{children:[jsx("div",{className:"title",children:"VR \u4E13\u8F91"}),jsx("div",{className:"dec",children:"\u8FD9\u4E9B\u660E\u661F\u4E5F\u5F00\u901A\u4E86VR\u4E13\u8F91\u623F,\u5FEB\u770B\u770B\uFF01"}),jsxs("div",{className:"singer-area",children:[jsx("div",{className:"singer-img",children:jsx("img",{src:c.singer_id===204664?luhanPng:zhoujielun})}),jsxs("div",{children:[jsx("div",{className:"singer-name",children:c.name}),jsx("div",{className:"intro",children:"VR \u4E13\u8F91\u623F"})]}),jsx("div",{className:"link-to__button",onClick:()=>s(c.skinId),children:"\u524D\u5F80"})]})]},d))})]})}const TOTAL_ALBUMS=[{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/1458791.png",id:"1458791"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/8217.png",id:"8217"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/8220.png",id:"8220"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/8218.png",id:"8218"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/60671.png",id:"60671"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/20612.png",id:"20612"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/8219.png",id:"8219"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/13004.png",id:"13004"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/7876962.png",id:"7876962"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/33021.png",id:"33021"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/36062.png",id:"36062"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/852856.png",id:"852856"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/194021.png",id:"194021"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/56705.png",id:"56705"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/9040723.png",id:"9040723"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/85650.png",id:"85650"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/14323.png",id:"14323"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/12924001.png",id:"12924001"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/32611.png",id:"32611"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/1366240.png",id:"1366240"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/4044657.png",id:"4044657"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/3883404.png",id:"3883404"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/8221.png",id:"8221"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/33802.png",id:"33802"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/60736.png",id:"60736"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/14536.png",id:"14536"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/67340.png",id:"67340"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/14320.png",id:"14320"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/9612009.png",id:"9612009"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/453899.png",id:"453899"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/1306793.png",id:"1306793"},{cover:"https://app-asset-1258211750.file.myqcloud.com/1/textures/60745.png",id:"60745"}];let room;const urlParam=new window.URLSearchParams(location.search),appId=urlParam.get("appId")||"10005",releaseId="2204222041_4dfac7",xverse=new Xverse({appId,releaseId,env:"DEV"}),albums=[];let commentWallInterval,nicknameHash="";urlParam.get("nickname")&&urlParam.get("avatarUrl")&&(nicknameHash=hashUserId(urlParam.get("nickname")+urlParam.get("avatarUrl")));function App(){const[a,i]=react.exports.useState(nicknameHash||urlParam.get("userId")||Math.random().toString().slice(6)),[e,o]=react.exports.useState(0),[s,c]=react.exports.useState("init"),[d,_]=react.exports.useState(!1),[b,k]=react.exports.useState(!1),[j,$]=react.exports.useState(!1),[_e,et]=react.exports.useState([]),[tt,rt]=react.exports.useState(void 0),[it,nt]=react.exports.useState([]),[ot,at]=react.exports.useState(void 0),[st,ut]=react.exports.useState(!1),[ft,lt]=react.exports.useState(0),[ht,pt]=react.exports.useState("third"),[mt,dt]=react.exports.useState([]),[gt,_t]=react.exports.useState(!1),[yt,Tt]=react.exports.useState(""),[St,At]=react.exports.useState(""),[vt,Et]=react.exports.useState(""),[xt,bt]=react.exports.useState("\u5468\u6770\u4F26"),[Mt,Rt]=react.exports.useState(!1),[Pt,It]=react.exports.useState([]),[Dt,Ct]=react.exports.useState([]);react.exports.useRef(mt),react.exports.useEffect(()=>{Ht()},[]),react.exports.useEffect(()=>{tt&&Bt(tt),console.log("currentAlbumdId",tt)},[tt]),react.exports.useEffect(()=>{ot&&Ut(ot),console.log("currentSongId",ot)},[ot]);const Ot=async()=>{var Or;const Nt=document.getElementById("canvas"),kt=parseInt(Math.random().toString().slice(6,7),10)>5?"KGe_Girl":"KGe_Boy",zt=urlParam.get("roomId")||"22fe9ab47b244e7ba8a8e5a57d130183",Xt=urlParam.get("nickname")||a,Zt=urlParam.get("avatarId")||kt,er=urlParam.get("ws")?decodeURIComponent(urlParam.get("ws")):"wss://uat-eks.xverse.cn/ws",ur=urlParam.get("role")||(zt?"audience":"host"),cr=urlParam.get("skinId")||Ft();let Tr=[];try{Tr=JSON.parse(localStorage.getItem(Zt)||"[]")}catch{Tr=[]}if(urlParam.get("preload")==null?!0:!!urlParam.get("preload"))try{await((Or=xverse.preload)==null?void 0:Or.start("full",(dr,Vr)=>{o(dr/Vr)}))}catch(dr){return dr.code===Codes.PreloadCanceled,void 0}try{room=await xverse.joinRoom({canvas:Nt,skinId:cr,avatarId:Zt,avatarComponents:Tr,roomId:zt,userId:a,wsServerUrl:er,role:ur,appId,token:" ",nickname:Xt,objectFit:"cover",viewMode:"full"}),window.room=room,wt()}catch(dr){console.error(dr),toast("\u52A0\u5165\u623F\u95F4\u5931\u8D25")}},Ft=()=>{let Nt="10084";const kt=new Date().getMinutes();return kt%3===0?Nt="10103":kt%3===1?Nt="10105":Nt="10084",Nt},wt=()=>{console.log("join room success"),c("loaded"),Wt(),rt(albums[10].id),room.joyStick.init(),setInterval(()=>{lt(room.avatars.length)},3*1e3)},Bt=async Nt=>{if(!Nt)return;const kt=await getAlbumDetail(Nt);console.log("get album detail",Nt,kt);const zt=kt.songlist;nt(zt);const Xt=zt[0].song_id;at(Xt)},Ut=async Nt=>{Vt(Nt),Yt(Nt)},Vt=async Nt=>{const kt=it.find(ur=>ur.song_id===Nt);if(!kt)return;const zt=kt.album_name,Xt=kt.song_name;if(room.musicianHall.totalAlbums=albums,!tt)return;const er=await getComments({userId:a,musician:"zhoujielun",song:Xt,album:zt,number:10});console.log("get comments",er),er.data.retCode==0&&Gt(er.data.comments),room.musicianHall.setAlbumsWallData(albums||TOTAL_ALBUMS)},Gt=async Nt=>{window.clearInterval(commentWallInterval);let kt=0;const zt=async()=>{const Xt=Nt.slice(kt),Zt=await room.musicianHall.setComments(CommentWallBlock.Left,Xt);[Skins.MusicianHall,Skins.MusicianHallDusk,Skins.MusicianHallNight].some(er=>er===room.skinId)&&room.musicianHall.setComments(CommentWallBlock.Right,Xt),kt=Zt,kt>=Nt.length-1&&(kt=0)};commentWallInterval=window.setInterval(()=>{zt()},5e3)},Lt=async Nt=>{await room.musicianHall.setPixelWll(Nt)},Ht=async()=>{const Nt=urlParam.get("skinId");let kt=4558,zt=204664,Xt="10107",Zt="\u9E7F\u6657";Nt&&Nt==="10107"&&(bt("\u9E7F\u6657"),kt=204664,zt=4558,Xt=Ft(),Zt="\u5468\u6770\u4F26");const er=await getSingerAlbum(kt);It([{singer_id:zt,name:Zt,skinId:Xt}]);const ur=er.album_list.map(cr=>qt(Kt({},cr),{cover:cr.album_big_url,id:cr.album_id.toString()}));albums.push(...ur),console.log("singerId",kt,"skinId",Nt,"albums",albums),Ot()},Wt=()=>{room.on("click",async Nt=>{if(Nt.target&&Nt.target.name===ClickTargetName.PlayAlbum){const kt=Nt.target.id;room.musicianHall.playingAlbumdId=kt,rt(kt)}else if(Nt.target&&Nt.target.name===ClickTargetName.AlbumPlaying)room.musicianHall.playingAlbumdId=void 0;else if(Nt.target&&Nt.target.name===ClickTargetName.AddRightComments){let kt="";Nt.target.id==="pinglunqiang_test1"?kt="https://cognitive-img-1258211750.file.myqcloud.com/pic/1.png":Nt.target.id==="pinglunqiang_test2"?kt="https://cognitive-img-1258211750.file.myqcloud.com/pic/2.png":kt="https://cognitive-img-1258211750.file.myqcloud.com/pic/3.png";const zt=document.createElement("iframe"),Xt=document.createElement("button");zt.src=kt,zt.style.width="50%",zt.style.height="100%",zt.style.zIndex="999",zt.style.position="absolute",zt.style.right="0",zt.style.top="0",Xt.innerText="\u5173\u95ED",Xt.style.position="absolute",Xt.style.right="50%",Xt.style.top="10px",Xt.style.background="red",Xt.style.color="white",document.body.appendChild(zt),document.body.appendChild(Xt),Xt.addEventListener("click",function Zt(){document.body.removeChild(zt),Xt.removeEventListener("click",Zt),document.body.removeChild(Xt)})}else if(Nt.target&&Nt.target.name===ClickTargetName.ClosePixelPanel)room.breathPoint.deleteBreathPoints(["pixelqiang_test4"]),room.breathPoint.deleteBreathPoints(["pixelqiang_test3"]);else if(Nt.target&&Nt.target.name===ClickTargetName.CheckPixelStatus){_t(!gt);const kt=await room.musicianHall.getLatestLitPoster(),zt=await room.musicianHall.getAllLit(),Xt=await room.musicianHall.getAllLitBlock();if(kt){const Zt=kt[kt.length-1].latestLitUrl;Tt(window.atob(Zt)),Lt(window.atob(Zt))}zt&&(At(window.atob(zt[0].litUrl)),Et(zt[0].coordinate)),Xt&&Ct(Xt)}else if(Nt.target&&Nt.target.name===ClickTargetName.LitPixel){const kt=await room.musicianHall.postLitPixel({comment:"\u50AC\u66F4\u6D4B\u8BD5",nickname:urlParam.get("nickname"),avatarUrl:urlParam.get("avatarUrl")});console.log("zzzzz",kt),kt?(window.setTimeout(()=>{room.musicianHall.clearEffects(),_t(!gt)},3500),toast("\u70B9\u4EAE\u50CF\u7D20\u5899\u6210\u529F")):toast("\u70B9\u4EAE\u50CF\u7D20\u5899\u5931\u8D25")}}),room.on("userAvatarLoaded",()=>{if(et(room.userAvatar.animations),![Skins.MusicianHall,Skins.MusicianHallDusk,Skins.MusicianHallNight].some(zt=>zt===room.skinId))return;Ir(),Lr();const{isPixelLit:Nt,isPixelLuckyChoose:kt}=room.musicianHall;kt?Nt?toast("\u606D\u559C\u4F60\u5DF2\u7ECF\u70B9\u4EAE\u8FC7\u50CF\u7D20\u5899\uFF01"):(toast("\u606D\u559C\u4F60\u88AB\u62BD\u4E2D\u53EF\u524D\u5F80\u70B9\u4EAE\u50CF\u7D20\u5899\uFF01\u5FEB\u524D\u5F80\u53BB\u70B9\u4EAE\uFF01"),room.userAvatar.setMood("cylinder")):toast("\u5F88\u9057\u61BE\u4F60\u4ECA\u5929\u6CA1\u88AB\u5E78\u8FD0\u5973\u795E\u7737\u987E\uFF0C\u8BF7\u660E\u592920:00-23:00\u518D\u6765\u8BD5\u8BD5\u5427")})},Yt=async Nt=>{const kt=it.find(Zt=>Zt.song_id===Nt);if(!kt||!kt.mv_id)return;const zt=await getMvDetail(kt.mv_id);console.log("get mvDetail",zt);const Xt=zt.mv_list[0];!Xt||jt(Xt.mv_LQ_url)},jt=async Nt=>{var zt;console.log("setTv",Nt);const kt=document.getElementById("tv");kt.src=Nt,kt.load(),(zt=room.tvs[0])==null||zt.setVideo(kt),window.ontouchstart=function(){var Xt,Zt;console.log("touchstart"),!!((Xt=room.tvs[0])!=null&&Xt.videoElement)&&!st&&((Zt=room.tvs[0].videoElement)==null?void 0:Zt.paused)&&(room.tvs[0].videoElement.muted=!1,room.tvs[0].play())}},$t=()=>{_(!d)},Qt=async Nt=>{Nt==="none"&&await room.userAvatar.removeMood(),await room.userAvatar.setMood(Nt)},ir=()=>{const Nt=()=>{let er=it.findIndex(cr=>cr.song_id===ot);if(er<0)return;er++,er>=it.length&&(er=0);const ur=it[er];at(ur.song_id)},kt=()=>{ut(!st),st?room.tvs[0].play():room.tvs[0].pause()};if(!ot)return;const zt=it.find(er=>er.song_id===ot);if(!zt)return;const Xt=zt.album_pic,Zt=zt.song_name;return jsxs("div",{className:"player-bar",children:[jsx("div",{className:"player-bar-album-pic",onClick:or,children:jsx("img",{src:Xt,alt:""})}),jsxs("div",{className:"player-bar-content",children:[jsxs("span",{className:"player-bar-song-name",children:[Zt," - ",xt]}),jsxs("div",{className:"player-icons",children:[jsx("img",{src:st?playerPlayIcon:playerPauseIcon,alt:"",onClick:kt}),jsx("img",{src:playerNextIcon,alt:"",onClick:Nt}),jsx("img",{src:playerListIcon,alt:"",onClick:or})]})]})]})},nr=()=>{k(!1)},rr=()=>{$(!1)},or=()=>{k(!b)},tr=Nt=>{at(Nt)},Jt=Nt=>{room.userAvatar.playAnimation({animationName:Nt,loop:!0})},hr=()=>{ht==="third"?room.setViewMode("observer").then(()=>{pt("first")}):ht==="first"&&room.setViewMode("full").then(()=>{pt("third")})},gr=()=>{_t(!1)},lr=()=>{Rt(!Mt)},Br=Nt=>{const kt=urlParam.get("skinId");let zt;kt?zt=window.location.href.replace(kt,Nt):zt=window.location.href+`&skinId=${Nt}`,window.location.href=zt},Ir=async()=>{const Nt=await room.musicianHall.getLatestLitPoster(),kt=await room.musicianHall.getAllLitBlock();if(Nt){const zt=Nt[Nt.length-1].latestLitUrl;Tt(window.atob(zt)),Lt(window.atob(zt))}kt&&Ct(kt)},Nr=urlParam.get("skinId")?[Skins.MusicianHall,Skins.MusicianHallDusk,Skins.MusicianHallNight].some(Nt=>Nt===urlParam.get("skinId")):!0,Lr=()=>{window.setInterval(()=>{console.log("get lates lit url"),Ir()},1e3*10)};return jsxs("div",{className:"App",children:[s==="init"&&jsxs("div",{className:"loading",children:[jsxs("div",{className:"loading__img-content",children:[jsx("span",{className:"loading__img"}),jsx("div",{children:"VR \u4E13\u8F91\u6B22\u8FCE\u60A8\uFF01"})]}),jsx("div",{className:"loading__progress-content",children:jsxs("div",{children:[jsx("progress",{className:"loading__progress-bar",value:e}),jsxs("span",{className:"loading__progress-precent",children:[(e*100).toFixed(0)," % "]}),jsx("div",{className:"loading__progress-text",children:"\u6B63\u5728\u52A0\u8F7D\u8D44\u6E90\u5305..."})]})})]}),jsx("video",{id:"tv",autoPlay:!0,muted:!0,hidden:!0,crossOrigin:"anonymous",style:{display:"none"}}),jsx("canvas",{id:"canvas",className:"stream unselect"}),s==="loaded"&&jsxs(Fragment,{children:[jsxs("div",{className:"room__info",children:[jsxs("div",{className:"album",children:[jsx("span",{className:"title",children:"VR \u4E13\u8F91"}),jsx("span",{className:"delimiter"}),jsx("span",{className:"singer",children:xt})]}),jsxs("div",{className:"person-count",children:[jsx("img",{className:"user-img",src:testUserIcon})," ",ft,"\u4EBA\u5728\u7EBF"]})]}),Nr&&jsx("div",{className:"room__barrage",children:jsx("div",{className:"item",children:"\u50AC\u66F4\u50CF\u7D20\u5899\u4E0A\u7EBF\u5566\uFF1A\u6BCF\u5929 20:00-23:00 \u9650\u65F6\u62BD\u53D6\u5E78\u8FD0\u5C0F\u4F19\u4F34\u6765\u70B9\u4EAE\u50AC\u66F4\u50CF\u7D20\u5899\uFF01 \u5FEB\u547C\u670B\u5524\u53CB\u6765\u4E00\u8D77\u7559\u4E0B\u4F60\u4EEC\u7684\u5370\u8BB0\uFF01"})}),jsxs("div",{className:"person_toggle",onClick:hr,children:[jsx("img",{src:personToggleIcon}),jsx("span",{children:ht==="third"?"\u7B2C\u4E09\u4EBA\u79F0":"\u7B2C\u4E00\u4EBA\u79F0"})]}),jsxs("div",{className:"control__panel",children:[jsx("div",{children:ir()}),jsxs("div",{className:"control__panel--mood-content",children:[d&&jsxs("div",{className:"control__panel--mood-list",children:[jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("none"),children:[jsx("div",{className:"control__panel--mood-none"}),jsx("div",{children:"\u65E0"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("happy"),children:[jsx("div",{className:"control__panel--mood-sun"}),jsx("div",{children:"\u5F00\u5FC3"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("sad"),children:[jsx("div",{className:"control__panel--mood-cloud"}),jsx("div",{children:"\u96BE\u8FC7"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("drunk"),children:[jsx("div",{className:"control__panel--mood-love"}),jsx("div",{children:"\u7231\u5FC3"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("Star01"),children:[jsx("div",{className:"control__panel--mood-listening"}),jsx("div",{children:"\u6109\u5FEB"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("heartbreak"),children:[jsx("div",{className:"control__panel--mood-heartbreak"}),jsx("div",{children:"\u5FC3\u788E"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("angry"),children:[jsx("div",{className:"control__panel--mood-angry"}),jsx("div",{children:"\u751F\u6C14"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("Nice"),children:[jsx("div",{className:"control__panel--mood-nice"}),jsx("div",{children:"\u8D5E\u540C"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Qt("Speechless"),children:[jsx("div",{className:"control__panel--mood-speechless"}),jsx("div",{children:"\u65E0\u8BED"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Jt("Sitting"),children:[jsx("div",{className:"control__panel--animation_sit"}),jsx("div",{children:"\u5750\u4E0B"})]}),jsxs("div",{className:"control__panel--mood-item",onClick:()=>Jt("Sleepping"),children:[jsx("div",{className:"control__panel--animation_sleep "}),jsx("div",{children:"\u8EBA\u5E73"})]})]}),jsx("span",{className:"control__panel--mood-button",onClick:$t})]})]}),jsx("div",{className:"animation-jump",onClick:()=>$(!0)}),b&&jsx(drawer,{coloseDrawer:nr,clickCurrentSong:tr,songList:it,songIndex:ot}),j&&jsx(AnimationList,{animationList:_e,onPlay:Jt,coloseDrawer:rr}),gt&&jsx(piexlPanel,{pixelWallUrl:yt,pixeUserUrl:St,pixeUserCoordinate:vt,allLitBlock:Dt,onClose:gr}),Mt&&jsx(SingerRoomList,{singer:Pt,closeSingerRoom:lr,gotoOtherSinger:Br})]})]})}ReactDOM.render(jsx(React.StrictMode,{children:jsx(App,{})}),document.getElementById("root"));